Files
PaperClipAI/server/src/__tests__/issues-creation-visibility.test.ts
T
DottaandPaperclip 66a8aa7f7e feat(issues): add issues.scope surface visibility foundation (#23329)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Issues currently store human board tasks, agent-created operational
tasks, and persistent 1:1 Agent Chats in the same `issues` table.
> - Default board lists, counts, and Mine views previously relied on
ad-hoc creator and origin predicates to hide chats and separate agent
tasks.
> - Upcoming headless channels also need a clean way to isolate channel
issues from default board lists without inventing a separate task
entity.
> - This pull request adds an explicit `issues.scope` column (`board`,
`channel`, `agent`, `chat`) across the schema, shared types, service
filters, client filters, and issue routes.
> - The benefit is unified surface visibility filtering and explicit
scope derivation while keeping rolling deploys safe and preserving
existing Agent Chat and board behavior.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/` REST API &
orchestration services, `ui/` client filters, and `docs/api/issues.md`).

**Problem or motivation**

Paperclip uses the `issues` table for human board work, automated or
agent-created operational work, and persistent 1:1 Agent Chats. Without
a dedicated surface-scope column, list, count, and Mine queries depend
on `conversationAgentId`, `createdByAgentId`, and `originKind` checks,
and there is no first-class way to isolate channel streams from default
board views.

**Proposed solution**

Add an `issues.scope` column (`board` | `channel` | `agent` | `chat`)
with `issues_scope_check` and composite indexes, expose `scope` in
shared types and Zod validators, derive default scope on issue creation
and batch imports, protect `chat` scope on 1:1 conversations and block
unauthorized agent `scope: "board"` writes across routes and
`issueService`, update server visibility queries and `applyIssueFilters`
on the client to honor `scope`, add `scope` filtering on `GET
/api/companies/:companyId/issues` and `/count`, and document the new
parameter in `docs/api/issues.md`.

**Alternatives considered**

1. Create separate tables for chats and channels. We ruled this out
because Paperclip builds assignment, comments, approvals, and execution
around a single `issues` model.
2. Add a DB `CHECK ((conversation_agent_id IS NULL) OR (scope =
'chat'))` constraint in this expand migration. We ruled this out for the
initial rollout because `ADD CONSTRAINT ... NOT VALID` still enforces
checks on new writes from older server instances that omit `scope`
during a rolling deploy.
3. Continue filtering only by `originKind` and `conversationAgentId` at
query time. We ruled this out because it cannot distinguish an explicit
chat-to-board handoff from a background agent task.

**Roadmap alignment**

Supports the **Agent Chat (including CEO Chat)** and **Work Queues** /
channel-intake directions in `ROADMAP.md` by separating surface
visibility on the shared `issues` table.

**Additional context**

This PR introduces the expand-phase schema, shared contract,
service-layer derivation, client filter handling, API filter foundation,
and API documentation. Follow-up work will build channel UI surfaces on
`issues.scope` and add the contract-phase DB check constraint after
older writers drain and re-backfill any rolling-deploy conversation
rows.

## What Changed

- Added `scope` (`board` | `channel` | `agent` | `chat`, default
`board`) to `packages/db/src/schema/issues.ts` with
`issues_scope_check`, `issues_company_scope_status_idx`, and
`issues_company_scope_updated_idx`.
- Added online-compatible migration
`packages/db/src/migrations/0511_simple_the_hunter.sql` (plus updated
Drizzle snapshot/journal and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
entry in `packages/db/src/client.ts`) to backfill existing `chat` and
`agent` rows in bounded 1,000-row primary-key cursor batches matching
`isAgentCreatedIssue`, validate `issues_scope_check` with `NOT VALID` +
`VALIDATE CONSTRAINT`, and build indexes `CONCURRENTLY`.
- Exported `ISSUE_SCOPES`, `IssueScope`, and `deriveDefaultIssueScope`
in `packages/shared`, added `scope?: IssueScope` to `Issue` and
`CompactIssue`, and added optional `scope` validation to
`createIssueSchema` and `updateIssueSchema`.
- Extracted `parseScopeFilter` and `surfaceScopeCondition` in
`server/src/services/issue-visibility.ts`, and updated `issueService`
(`create`, `importIssues`, `update`, `list`, `count`, blocked inbox
counts, and Mine views) to derive default scope (including `scope:
"agent"` for creatorless imports), enforce `chat` scope on 1:1
conversations, reject `scope: "chat"` on non-conversation issues, reject
unauthorized agent `scope: "board"` creation without handoff provenance,
default chat-to-board handoffs to `board`, preserve
`nonIdleSlackIssueCondition` on non-chat/channel scope filters, let
explicit `scope` filters override `includeAgentCreatedTasks=false`, and
exclude `chat` and `channel` rows from default board queries unless
filtered by `scope`, `q`, or `issueIds`.
- Updated `applyIssueFilters` (`isBoardVisibleByDefault`) in
`ui/src/lib/issue-filters.ts` so agent-created tasks with `scope:
"board"` (such as chat-to-board handoffs) stay visible by default.
- Added `scope` query parsing (`parseIssueListScopeQueryParam`
delegating to `parseScopeFilter`) and `assertActorMayWriteIssueScope`
across `POST /companies/:companyId/issues`, `POST /issues/:id/children`,
`POST /issues/:id/accepted-plan-decompositions`, and `PATCH /issues/:id`
in `server/src/routes/issues.ts`, included `scope` in `toCompactIssue`,
and documented `scope` in `docs/api/issues.md`.
- Added tests in `server/src/__tests__/issue-scope-visibility.test.ts`
and `ui/src/lib/issue-filters.test.ts`, updated
`server/src/__tests__/fixtures/issue-detail-response.json` and
`server/src/__tests__/issues-creation-visibility.test.ts`, and refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/db typecheck` (`check:migrations` + `tsc
--noEmit`), `pnpm --filter @paperclipai/shared typecheck`, and `pnpm
--filter @paperclipai/server typecheck` — passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35`.
- `npx vitest run packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/issue-scope-visibility.test.ts
server/src/__tests__/issues-creation-visibility.test.ts
server/src/__tests__/company-portability-import-batching.test.ts
ui/src/lib/issue-filters.test.ts` — 5 files, 51 tests passed (1
pre-existing skip in `company-portability-import-batching.test.ts`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
3db819854f --check` — exited 0
(`"changed":false`).
- Full CI + security/review checks passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35` (88/88 check runs completed
with 0 failures; `mergeable: MERGEABLE`, `mergeStateStatus: CLEAN`;
Greptile `5/5` with 0 unresolved threads).

## Risks

- Migration `0511_simple_the_hunter.sql` runs outside a transaction
(`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`) because it commits bounded
1,000-row primary-key cursor backfill batches and builds indexes with
`CREATE INDEX CONCURRENTLY`. All statements are idempotent, and
`issues_scope_check` uses `NOT VALID` followed by `VALIDATE CONSTRAINT`.
- The DB-level `conversation_agent_id -> scope = 'chat'` check
constraint is deferred to a follow-up contract migration (which must
re-run the bounded `scope = 'chat'` backfill before adding/validating
the constraint) so rolling deploys with previous writers do not fail 1:1
chat inserts; `issueService.create` and `issueService.update` enforce
this invariant in application code, and
`nonChatAndChannelIssueCondition()` continues checking
`isNull(issues.conversationAgentId)`.
- Behavioral shift: `GET /api/companies/:companyId/issues` and
blocked/Mine aggregations now isolate `scope = 'channel'` and `scope =
'chat'` from default board views unless `scope`, `q`, or `issueIds` is
explicitly passed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Google DeepMind Antigravity (Gemini coding agent) with tool use and
code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 19:57:23 -06:00

318 lines
24 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import request from "supertest";
import { expect, it } from "vitest";
import { activityLog, agents, authUsers, chatConversations, chatEndpoints, chatMessageLinks, issueComments, issueReadStates, issues, issueThreadInteractions, toolApplications, toolConnections } from "@paperclipai/db";
import { deriveDefaultIssueScope, isAgentCreatedIssue } from "@paperclipai/shared";
import { issueRoutes } from "../routes/issues.js";
import { issueService } from "../services/issues.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { describeEmbeddedPostgres, resetCompanyIssueFixtures, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("issue creation visibility", () => {
const ctx = useEmbeddedPostgres("paperclip-creation-visibility-", {
resetEach: async (db) => {
await db.delete(activityLog);
await db.delete(chatMessageLinks);
await db.delete(chatConversations);
await db.delete(chatEndpoints);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(issues);
await db.delete(agents);
await resetCompanyIssueFixtures(db);
await db.delete(authUsers);
},
});
it("filters ordinary and compact searches before pagination without changing API defaults", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Creation visibility");
const other = await seedCompanyWithBoardAccess(ctx.db, "Other company");
const rows = [
{ id: randomUUID(), companyId, title: "Visibility human", createdByUserId: userId, originKind: "manual" },
{ id: randomUUID(), companyId, title: "Visibility second human", createdByUserId: userId, originKind: "manual" },
{ id: randomUUID(), companyId, title: "Visibility channel", createdByUserId: userId, originKind: "chat_channel" },
{ id: randomUUID(), companyId, title: "Visibility onboarding", createdByUserId: userId, originKind: "onboarding_first_task" },
{ id: randomUUID(), companyId, title: "Visibility inbound email", originKind: "chat_channel", originId: "email:endpoint:thread" },
{ id: randomUUID(), companyId, title: "Visibility outbound email", originKind: "chat_channel", originId: "email-send:tool-call" },
...["routine_execution", "task_watchdog", "stranded_issue_recovery", "plugin:workflow:task", "harness_liveness_escalation", "manual"].map((originKind) => ({ id: randomUUID(), companyId, title: `Visibility ${originKind}`, originKind, responsibleUserId: userId })),
{ id: randomUUID(), companyId, title: "Visibility manually run routine", createdByUserId: userId, originKind: "routine_execution" },
];
await ctx.db.insert(issues).values([
...rows.map((row, index) => ({ ...row, scope: deriveDefaultIssueScope(row), status: "todo", updatedAt: new Date(2026, 9, 13, 0, index) })),
{ companyId: other.companyId, title: "Visibility other company", createdByUserId: other.userId },
{ companyId, title: "Visibility private task", createdByUserId: other.userId, visibility: "private" },
]);
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
const defaults = await request(app).get(`${path}?includeRoutineExecutions=true`).expect(200);
expect(defaults.body).toHaveLength(rows.length);
for (const view of ["", "&view=compact"]) {
const first = await request(app).get(`${path}?includeAgentCreatedTasks=false&q=Visibility&sortField=updated&limit=2${view}`).expect(200);
const second = await request(app).get(`${path}?includeAgentCreatedTasks=false&q=Visibility&sortField=updated&limit=2&offset=2${view}`).expect(200);
expect(first.body).toHaveLength(2);
expect(second.body).toHaveLength(1);
expect([...first.body, ...second.body].every((issue: Parameters<typeof isAgentCreatedIssue>[0]) => !isAgentCreatedIssue(issue))).toBe(true);
}
await request(app).get(`${path}?includeAgentCreatedTasks=invalid`).expect(400);
await request(app).get(`${path}?includeParticipatedTasks=invalid`).expect(400);
await request(app).get(`/api/companies/${other.companyId}/issues?includeAgentCreatedTasks=false`).expect(403);
});
it.each(["slack", "speko"] as const)("includes waiting %s descendants while preserving task read permissions", async (provider) => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Waiting descendants");
const other = await seedCompanyWithBoardAccess(ctx.db, "Other descendants");
const [agent] = await ctx.db.insert(agents).values({ companyId, name: "Worker", role: "engineer", adapterType: "process" }).returning();
const [application] = await ctx.db.insert(toolApplications).values({ companyId, name: provider, type: "chat" }).returning();
const [connection] = await ctx.db.insert(toolConnections).values({ companyId, applicationId: application!.id, name: provider, uid: randomUUID(), transport: "chat_sdk", connectionPurpose: "channel" }).returning();
const endpointId = randomUUID();
await ctx.db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId: connection!.id, provider, publicId: endpointId, assignedAgentId: agent!.id, status: "active" });
const rootId = randomUUID();
const childId = randomUUID();
const nestedId = randomUUID();
const privateId = randomUUID();
await ctx.db.insert(issues).values({ id: rootId, companyId, title: "Parent task", status: "todo", createdByUserId: userId });
await ctx.db.insert(issues).values([childId, nestedId, privateId].map(id => ({
id, companyId, title: `Waiting ${provider} subtask`, status: "in_review",
parentId: id === nestedId ? childId : rootId,
assigneeAgentId: agent!.id, originKind: "chat_channel", originId: endpointId,
visibility: id === privateId ? "private" : "open",
createdByUserId: id === privateId ? other.userId : userId,
responsibleUserId: id === privateId ? other.userId : userId,
})));
await ctx.db.insert(chatConversations).values([childId, nestedId, privateId].map(issueId => ({
companyId, endpointId, issueId, externalConversationId: randomUUID(), externalThreadId: randomUUID(), externalLabel: "Waiting subtask", state: "waiting",
})));
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
const ambient = await request(app).get(path).expect(200);
expect(ambient.body.map((task: { id: string }) => task.id)).toEqual([rootId]);
for (const view of ["", "&view=compact"]) {
const response = await request(app).get(`${path}?descendantOf=${rootId}${view}`).expect(200);
expect(response.body.map((task: { id: string }) => task.id).sort()).toEqual([childId, nestedId].sort());
expect(response.body.every((task: { externalConversationState: string }) => task.externalConversationState === "waiting")).toBe(true);
}
const restricted = await issueService(ctx.db).list(companyId, { descendantOf: rootId, readCondition: sql<boolean>`${issues.id} = ${childId}` });
expect(restricted.map(task => task.id)).toEqual([childId]);
await request(app).get(`/api/companies/${other.companyId}/issues?descendantOf=${rootId}`).expect(403);
});
it("preserves participation but excludes routine ownership and read-only activity", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Inbox participation");
const ids = Object.fromEntries(["scheduled", "commented", "assigned", "manual", "read", "touched", "channelScheduled", "channelCommented", "channelManual"].map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(Object.entries(ids).map(([name, id]) => ({
id, companyId, title: `Participation ${name}`, status: "todo", scope: "agent" as const, originKind: name.startsWith("channel") ? "chat_channel" : "routine_execution",
responsibleUserId: userId,
assigneeUserId: name === "assigned" ? userId : null,
createdByUserId: name === "manual" || name === "channelManual" ? userId : null,
})));
await ctx.db.insert(issueComments).values([ids.commented!, ids.channelCommented!].map((issueId) => ({ companyId, issueId, authorUserId: userId, body: "I joined this task" })));
await ctx.db.insert(issueReadStates).values({ companyId, issueId: ids.read!, userId, lastReadAt: new Date() });
await ctx.db.insert(activityLog).values([
{ companyId, entityType: "issue", entityId: ids.read!, actorType: "user", actorId: userId, action: "issue.read_marked" },
{ companyId, entityType: "issue", entityId: ids.touched!, actorType: "user", actorId: userId, action: "issue.inbox_touched" },
]);
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
const mine = await request(app).get(`${path}?touchedByUserId=me&inboxArchivedByUserId=me&includeRoutineExecutions=true`).expect(200);
const expected = [ids.commented, ids.assigned, ids.touched, ids.channelCommented].sort();
expect(mine.body.map((issue: { id: string }) => issue.id).sort()).toEqual(expected);
const discovery = await request(app).get(`${path}?q=Participation&includeAgentCreatedTasks=false&includeParticipatedTasks=true`).expect(200);
expect(discovery.body.map((issue: { id: string }) => issue.id).sort()).toEqual(expected);
const strict = await issueService(ctx.db).list(companyId, { includeAgentCreatedTasks: false });
expect(strict).toEqual([]);
});
it("uses source evidence for existing imports and keeps direct board/API participation", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Personal inbox sources");
const svc = issueService(ctx.db);
const names = ["github", "slack", "legacySender", "legacyLink", "direct", "outbound", "manualRun", "human", "agent", "private"];
const ids = Object.fromEntries(names.map((name) => [name, randomUUID()]));
const old = new Date("2026-01-01T00:00:00Z");
const newer = new Date("2026-01-02T00:00:00Z");
const [agent] = await ctx.db.insert(agents).values({ companyId, name: "Worker", role: "engineer", adapterType: "process" }).returning();
await ctx.db.insert(issues).values(names.map((name) => ({
id: ids[name]!, companyId, title: `Source ${name}`, status: "todo",
originKind: name === "human" || name === "agent" ? "manual" : name === "manualRun" ? "routine_execution" : "chat_channel",
createdByUserId: name === "private" ? "other-user" : userId, createdByAgentId: name === "agent" ? agent!.id : null,
responsibleUserId: name === "private" ? "other-user" : userId, visibility: name === "private" ? "private" : "open",
createdAt: old, updatedAt: old,
})));
const comments = await ctx.db.insert(issueComments).values(
["github", "slack", "legacySender", "legacyLink", "direct", "outbound", "private"].map((name) => ({
companyId, issueId: ids[name]!, authorUserId: userId, authorType: "user" as const,
body: "User identity is attribution", createdAt: old,
metadata: name === "github" || name === "slack"
? { version: 1 as const, sourceChannel: name as "github" | "slack", sections: [] }
: name === "legacySender" ? { version: 1 as const, sections: [{ title: "GitHub sender", rows: [{ type: "key_value" as const, label: "Provider ID", value: "external-user" }] }] } : null,
})),
).returning();
const [appRow] = await ctx.db.insert(toolApplications).values({ companyId, name: "Chat", type: "mcp_http" }).returning();
const [connection] = await ctx.db.insert(toolConnections).values({ companyId, applicationId: appRow!.id, name: "GitHub", uid: randomUUID(), transport: "mcp_remote", authKind: "api_key" }).returning();
const [endpoint] = await ctx.db.insert(chatEndpoints).values({ companyId, connectionId: connection!.id, assignedAgentId: agent!.id, provider: "github", publicId: randomUUID(), sponsorUserId: userId }).returning();
const conversations = await ctx.db.insert(chatConversations).values(["legacyLink", "outbound"].map((name) => ({
companyId, endpointId: endpoint!.id, issueId: ids[name]!, externalConversationId: name, externalLabel: "Review",
}))).returning();
await ctx.db.insert(chatMessageLinks).values(["legacyLink", "outbound"].map((name) => ({
companyId, endpointId: endpoint!.id, conversationId: conversations.find((conversation) => conversation.issueId === ids[name])!.id,
commentId: comments.find((comment) => comment.issueId === ids[name])!.id,
providerMessageId: name, direction: name === "legacyLink" ? "inbound" : "outbound",
})));
await ctx.db.insert(activityLog).values({ companyId, entityType: "issue", entityId: ids.manualRun!, actorType: "user", actorId: userId, action: "issue.inbox_touched", details: { source: "manual_routine_run" } });
await ctx.db.insert(issueComments).values(names.map((name) => ({ companyId, issueId: ids[name]!, body: "New agent result", createdAt: newer })));
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
const expected = [ids.direct, ids.outbound, ids.human].sort();
for (const view of ["", "&view=compact"]) {
const mine = await request(app).get(`${path}?touchedByUserId=me&includeRoutineExecutions=true${view}`).expect(200);
expect(mine.body.map((issue: { id: string }) => issue.id).sort()).toEqual(expected);
const unread = await request(app).get(`${path}?unreadForUserId=me&includeRoutineExecutions=true${view}`).expect(200);
expect(unread.body.map((issue: { id: string }) => issue.id).sort()).toEqual(expected);
}
await ctx.db.delete(issues).where(eq(issues.id, ids.private!));
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(3);
expect((await svc.unreadInboxIssueIds(companyId, userId, sql<boolean>`true`)).sort()).toEqual(expected);
await ctx.db.insert(issueComments).values({ companyId, issueId: ids.github!, authorUserId: userId, body: "Direct API reply" });
const beforeReply = await request(app).get(`${path}?includeRoutineExecutions=true&inboxArchivedByUserId=me`).expect(200);
const imported = beforeReply.body.find((issue: { id: string }) => issue.id === ids.slack);
expect(imported.myLastTouchAt).toBeNull();
expect(imported.isUnreadForMe).toBe(false);
const joined = await request(app).get(`${path}?touchedByUserId=me`).expect(200);
expect(joined.body.map((issue: { id: string }) => issue.id)).toContain(ids.github);
});
it("admits open addressed requests and removes that reason when they resolve", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Human requests");
const ids = Object.fromEntries(["question", "confirmation", "otherUser", "creatorExcluded", "private"].map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(Object.entries(ids).map(([name, id]) => ({ id, companyId, title: name, status: "todo", scope: "agent" as const, originKind: "chat_channel", visibility: name === "private" ? "private" : "open", createdAt: new Date("2026-01-01") })));
const requests = await ctx.db.insert(issueThreadInteractions).values(Object.entries(ids).map(([name, issueId]) => ({
companyId, issueId, kind: name === "confirmation" ? "request_confirmation" : "ask_user_questions",
addresseeUserId: name === "otherUser" ? "someone-else" : userId,
createdByUserId: name === "creatorExcluded" ? userId : null,
effectiveResolverPolicy: name === "creatorExcluded" ? "not_creator" as const : "human_only" as const,
payload: name === "confirmation" ? { version: 1 as const, prompt: "Accept this result?" } : { version: 1 as const, questions: [{ id: "answer", prompt: "Choose a result.", selectionMode: "single" as const, options: [{ id: "yes", label: "Accept" }, { id: "no", label: "Reject" }] }] },
}))).returning();
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
for (const filter of ["touchedByUserId=me", "unreadForUserId=me", "includeAgentCreatedTasks=false&includeParticipatedTasks=true"]) {
const result = await request(app).get(`${path}?${filter}`).expect(200);
expect(result.body.map((issue: { id: string }) => issue.id).sort()).toEqual([ids.question, ids.confirmation].sort());
if (!filter.includes("includeParticipatedTasks")) {
expect(result.body.every((issue: { isUnreadForMe: boolean }) => issue.isUnreadForMe)).toBe(true);
}
}
const svc = issueService(ctx.db);
await svc.markRead(companyId, ids.question!, userId);
const unread = await request(app).get(`${path}?unreadForUserId=me`).expect(200);
expect(unread.body.map((issue: { id: string }) => issue.id)).toEqual([ids.confirmation]);
for (const interaction of requests) await ctx.db.update(issueThreadInteractions).set({ status: "accepted" }).where(eq(issueThreadInteractions.id, interaction.id));
const resolved = await request(app).get(`${path}?touchedByUserId=me`).expect(200);
expect(resolved.body).toEqual([]);
});
it("keeps a service-created request unread for the human assignee until they read it", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Assigned request");
await ctx.db.insert(authUsers).values({ id: userId, name: "Recipient", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
const [agent] = await ctx.db.insert(agents).values({ companyId, name: "Requester", role: "engineer", adapterType: "process" }).returning();
const [issue] = await ctx.db.insert(issues).values({
companyId, title: "Assigned channel task", originKind: "chat_channel", status: "todo", assigneeUserId: userId,
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
}).returning();
const svc = issueService(ctx.db);
await svc.markRead(companyId, issue!.id, userId, new Date("2026-01-02"));
const interaction = await issueThreadInteractionService(ctx.db).create(issue!, {
kind: "ask_user_questions", addresseeUserId: userId, resolverPolicy: "human_only",
payload: { version: 1, questionSet: { schema: "paperclip.question_set.v1", questions: [{ id: "answer", prompt: "What result do you need?", answerMode: "text", required: true }] } },
}, { agentId: agent!.id });
const [updated] = await ctx.db.select().from(issues).where(eq(issues.id, issue!.id));
expect(updated!.updatedAt.getTime()).toBeGreaterThanOrEqual(new Date(interaction.createdAt).getTime());
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
for (const view of ["", "&view=compact"]) {
const unread = await request(app).get(`${path}?unreadForUserId=me${view}`).expect(200);
expect(unread.body.map((row: { id: string }) => row.id)).toEqual([issue!.id]);
expect(unread.body[0].isUnreadForMe).toBe(true);
}
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(1);
await svc.markRead(companyId, issue!.id, userId);
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(0);
const read = await request(app).get(`${path}?touchedByUserId=me`).expect(200);
expect(read.body[0].isUnreadForMe).toBe(false);
});
it.each(["request_checkbox_confirmation", "request_item_verdicts"] as const)("resurfaces archived automatic work for an addressed %s", async (kind) => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Archived requests");
await ctx.db.insert(authUsers).values({ id: userId, name: "Recipient", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
const [agent] = await ctx.db.insert(agents).values({ companyId, name: "Requester", role: "engineer", adapterType: "process" }).returning();
const tasks = await ctx.db.insert(issues).values(["addressed", "otherRecipient"].map((title) => ({
companyId, title, originKind: "chat_channel", status: "todo",
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
}))).returning();
const svc = issueService(ctx.db);
for (const task of tasks) {
await svc.archiveInbox(companyId, task.id, userId, new Date("2026-01-02"));
await svc.markRead(companyId, task.id, userId, new Date("2026-01-02"));
}
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
const mineQuery = "touchedByUserId=me&inboxArchivedByUserId=me";
const unreadQuery = "unreadForUserId=me&inboxArchivedByUserId=me";
await request(app).get(`${path}?${mineQuery}`).expect(200).expect([]);
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(0);
const input = kind === "request_checkbox_confirmation"
? { kind, payload: { version: 1 as const, prompt: "Select the result.", options: [{ id: "result", label: "Result" }] } }
: { kind, payload: { version: 1 as const, prompt: "Review the result.", items: [{ id: "result", label: "Result" }] } };
await issueThreadInteractionService(ctx.db).create(tasks[0]!, {
...input, addresseeUserId: userId, resolverPolicy: "human_only",
}, { agentId: agent!.id });
await ctx.db.insert(issueThreadInteractions).values({
companyId, issueId: tasks[1]!.id, kind, addresseeUserId: "someone-else",
effectiveResolverPolicy: "human_only", payload: input.payload,
});
for (const view of ["", "&view=compact"]) {
for (const query of [mineQuery, unreadQuery]) {
const result = await request(app).get(`${path}?${query}${view}`).expect(200);
expect(result.body.map((row: { id: string }) => row.id)).toEqual([tasks[0]!.id]);
expect(result.body[0].isUnreadForMe).toBe(true);
}
}
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(1);
await svc.markRead(companyId, tasks[0]!.id, userId);
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(0);
const read = await request(app).get(`${path}?${mineQuery}`).expect(200);
expect(read.body.map((row: { id: string }) => row.id)).toEqual([tasks[0]!.id]);
expect(read.body[0].isUnreadForMe).toBe(false);
await svc.archiveInbox(companyId, tasks[0]!.id, userId);
await request(app).get(`${path}?${mineQuery}`).expect(200).expect([]);
expect(await svc.countUnreadTouchedByUser(companyId, userId)).toBe(0);
});
it("excludes historical and closed requests while preserving current questions and authorization requests", async () => {
const { companyId, userId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Current requests");
const names = ["historical", "done", "cancelled", "current", "authorization"];
const ids = Object.fromEntries(names.map((name) => [name, randomUUID()]));
await ctx.db.insert(issues).values(names.map((name) => ({
id: ids[name]!, companyId, title: name, scope: "agent" as const, originKind: "chat_channel",
status: name === "done" || name === "cancelled" ? name : "todo",
createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"),
})));
await ctx.db.insert(issueThreadInteractions).values(names.map((name) => ({
companyId, issueId: ids[name]!, kind: "ask_user_questions", addresseeUserId: userId,
effectiveResolverPolicy: "human_only" as const, createdAt: new Date("2026-01-02"),
payload: { version: 1 as const, questions: [], ...(name === "authorization" ? { connectionAuthorization: {} } : {}),
questionSet: { schema: "paperclip.question_set.v1" as const, questions: [{ id: "answer", prompt: "What result do you need?", answerMode: "text" as const, required: true }] } },
})));
await ctx.db.insert(issueComments).values(["historical", "authorization"].map((name) => ({
companyId, issueId: ids[name]!, authorUserId: "another-human", body: "The request has changed.", createdAt: new Date("2026-01-03"),
})));
const app = routeApp(ctx.db, actor, issueRoutes);
const path = `/api/companies/${companyId}/issues`;
for (const filter of ["touchedByUserId=me", "unreadForUserId=me", "includeAgentCreatedTasks=false&includeParticipatedTasks=true"]) {
const result = await request(app).get(`${path}?${filter}`).expect(200);
expect(result.body.map((row: { id: string }) => row.id).sort()).toEqual([ids.current, ids.authorization].sort());
}
expect(await issueService(ctx.db).countUnreadTouchedByUser(companyId, userId)).toBe(2);
});
});