From 23b1bfd422aac901c709d5f3d545a2a0cdabb70e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 16:26:50 +0000 Subject: [PATCH 1/5] fix(inbox): archive every inbox kind without telling the agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Raphaël (2026-11-17), extending the silent archive of questions and reviews to every kind: "Make all of them silent". - Tasks: archive closes the task with notified_at set in the closing write and admits no sam.inbox event, so no watching chat is woken. Done and reopen still wake. - Secret requests: archiveRuntimeSecretRequest closes the request as declined with notified_at set, no notice; the expiry path no longer applies. - Operations approvals: decideOperationsAction takes a required `delivery: 'notify_agent' | 'silent'`; inbox archive denies silently, the admin decision route and inbox answers still notify. - Permissions (ACP interactions): archive resolves the inbox marker with reason `archived` and answers nothing; the interaction stays pending and answerable in its chat. The marker is projected once per interaction, so it does not return. New archiveInteractionAttention checks task:write, chat writer, and that the marker is this chat's pending interaction. - Ports: explicit archiveInteraction / archiveSecret / archiveApproval. - Copy and docs: inbox guide, API reference, Connector tool text, MCP assign/attach descriptions, noticeRetryMinutes, secret card. Co-Authored-By: Claude Opus 5.5 --- .../src/routes/admin-operations-approvals.ts | 1 + apps/api/src/routes/chat-attention.ts | 37 +++++++++- apps/api/src/routes/mcp/inbox-tools.ts | 2 +- .../mcp/tool-definitions-inbox-tools.ts | 4 +- apps/api/src/services/inbox/port.ts | 64 +++++++++++++----- .../services/operations-actions/service.ts | 10 ++- .../src/services/runtime-secret-requests.ts | 29 ++++++++ .../integration/ops-action-approvals.test.ts | 16 +++++ .../unit/operations/inbox-operations.test.ts | 31 ++++----- .../tests/workers/inbox-capability.test.ts | 11 ++- .../inbox-interaction-notifications.test.ts | 67 +++++++++++++++++++ .../workers/inbox-tasks-capability.test.ts | 16 +++-- apps/web/src/components/inbox/useInbox.ts | 6 +- .../tool-cards/SecretRequestCard.tsx | 2 +- .../docs/docs/guides/admin-settings.md | 2 +- .../www/src/content/docs/docs/guides/inbox.md | 29 +++++--- .../src/content/docs/docs/reference/api.md | 29 ++++---- packages/operations/src/inbox-operations.ts | 2 +- .../src/inbox-settings-definition.ts | 2 +- packages/operations/src/inbox-task-core.ts | 13 ++-- packages/operations/src/inbox-write-core.ts | 19 +++--- packages/operations/src/ports.ts | 14 ++++ .../project-data/src/client/project-data.ts | 19 ++++++ 23 files changed, 330 insertions(+), 95 deletions(-) diff --git a/apps/api/src/routes/admin-operations-approvals.ts b/apps/api/src/routes/admin-operations-approvals.ts index 06a67b4da4..f941daa2c7 100644 --- a/apps/api/src/routes/admin-operations-approvals.ts +++ b/apps/api/src/routes/admin-operations-approvals.ts @@ -84,6 +84,7 @@ adminOperationsApprovalRoutes.post( decision: body.decision, deciderUserId: getUserId(c), note: body.note?.trim() || null, + delivery: 'notify_agent', }); if (outcome.outcome === 'not_found') throw errors.notFound('Approval'); if (outcome.outcome !== 'decided') { diff --git a/apps/api/src/routes/chat-attention.ts b/apps/api/src/routes/chat-attention.ts index 0424483460..f413609d19 100644 --- a/apps/api/src/routes/chat-attention.ts +++ b/apps/api/src/routes/chat-attention.ts @@ -4,7 +4,11 @@ * (`.claude/rules/18-file-size-limits.md`). */ import type { ArchiveCheckinHold } from '@simple-agent-manager/operations'; -import { HUMAN_INPUT_CATEGORIES, type HumanInputCategory } from '@simple-agent-manager/shared'; +import { + ACP_INTERACTION_ATTENTION_SOURCE, + HUMAN_INPUT_CATEGORIES, + type HumanInputCategory, +} from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; import type { Context, Hono } from 'hono'; @@ -401,3 +405,34 @@ export async function archiveAttention( await recordSharedSessionAnswer(env, writer, { markerId, archived: true }); return { agentNotified: false }; } + +/** + * Archive a pending ACP interaction (a permission, form or link request) from the inbox: its + * inbox marker resolves with reason `archived` and nothing is answered, so the agent is told + * nothing and stays where it is (Raphaël, 2026-11-17: every inbox kind archives silently). The + * interaction stays pending in its chat, where the person can still answer it, until the runtime + * gives up on it. The marker is projected once per interaction + * (`projectInteractionAttention`), so it does not come back. + */ +export async function archiveInteractionAttention( + env: Env, + userId: string, + projectId: string, + sessionId: string, + markerId: string +): Promise { + const db = drizzle(env.DATABASE, { schema }); + await requireProjectCapability(db, projectId, userId, 'task:write'); + await requireSessionWriter(env, projectId, sessionId, userId, { + db, + action: 'archive the agent request in this session', + }); + // Bound to this chat and to a pending interaction marker before anything is written. + const { marker } = await loadAttentionForViewer(env, projectId, sessionId, markerId, userId); + if (!marker || marker.source !== ACP_INTERACTION_ATTENTION_SOURCE) + throw markRejectedBeforeEffects(errors.notFound('Attention request')); + if (marker.resolvedAt !== null) + throw markRejectedBeforeEffects(errors.conflict('Attention request is already resolved')); + const resolved = await projectDataService.archiveInteractionMarker(env, projectId, markerId); + if (resolved === 0) throw errors.conflict('Attention request is already resolved'); +} diff --git a/apps/api/src/routes/mcp/inbox-tools.ts b/apps/api/src/routes/mcp/inbox-tools.ts index a169eb47a4..30eb082bfa 100644 --- a/apps/api/src/routes/mcp/inbox-tools.ts +++ b/apps/api/src/routes/mcp/inbox-tools.ts @@ -230,7 +230,7 @@ export const handleInboxGetItem: Handler = (requestId, params, tokenData, env) = function assigned(result: AgentAssignResult) { const next = !result.created ? `This task was already assigned as ${result.ref}; nothing new was filed.` - : 'Assigned. It does not block you: keep working. You will be woken in this chat when the person comments, takes it, hands it on, finishes, reopens or archives it.'; + : 'Assigned. It does not block you: keep working. You will be woken in this chat when the person comments, takes it, hands it on, finishes or reopens it (archiving it wakes no one).'; const watch = result.watching ? '' : ' This chat could not be subscribed to the task yet; repeat this assign call with the same idempotencyKey (or title) to subscribe it.'; diff --git a/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts b/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts index d29687deda..e28647d8b4 100644 --- a/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts +++ b/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts @@ -112,7 +112,7 @@ export const INBOX_TOOLS = [ { name: 'inbox_assign', description: - 'Hand a person non-blocking work only a person can do (add a production secret, decide a price, record a demo). It goes to their inbox under Tasks; you keep working. You are woken in this chat when they comment, take it, hand it on, finish, reopen or archive it. It never expires.', + 'Hand a person non-blocking work only a person can do (add a production secret, decide a price, record a demo). It goes to their inbox under Tasks; you keep working. You are woken in this chat when they comment, take it, hand it on, finish or reopen it; archiving it wakes no one. It never expires.', inputSchema: { type: 'object' as const, properties: { @@ -168,7 +168,7 @@ export const INBOX_TOOLS = [ { name: 'inbox_attach', description: - 'Watch an open task another of your chats assigned instead of assigning a duplicate: this chat is woken when it is taken, handed on, finished, reopened or archived (comments wake the assigning chat; read them with inbox_read get).', + 'Watch an open task another of your chats assigned instead of assigning a duplicate: this chat is woken when it is taken, handed on, finished or reopened (archiving it wakes no one; comments wake the assigning chat; read them with inbox_read get).', inputSchema: { type: 'object' as const, properties: { ref, wakeOnSteps }, diff --git a/apps/api/src/services/inbox/port.ts b/apps/api/src/services/inbox/port.ts index f3c719c547..db97079232 100644 --- a/apps/api/src/services/inbox/port.ts +++ b/apps/api/src/services/inbox/port.ts @@ -15,12 +15,17 @@ import { hasProjectCapability, projectMemberRolesWithCapability, } from '../../middleware/project-auth'; -import { archiveAttention, loadAttentionForViewer } from '../../routes/chat-attention'; +import { + archiveAttention, + archiveInteractionAttention, + loadAttentionForViewer, +} from '../../routes/chat-attention'; import { authorizeAgentWake } from '../agent-wake-authorization'; import { decideOperationsAction } from '../operations-actions/service'; import * as projectDataService from '../project-data'; import { resolverDisplayName } from '../runtime-secret-request-records'; import { + archiveRuntimeSecretRequest, declineRuntimeSecretRequest, fulfillRuntimeSecretRequest, } from '../runtime-secret-requests'; @@ -106,6 +111,9 @@ export function createInboxPort(env: Env): OperationInboxPort { archiveAttention: (userId, projectId, sessionId, markerId, hold) => archiveAttention(env, userId, projectId, sessionId, markerId, hold), + archiveInteraction: (userId, projectId, sessionId, markerId) => + archiveInteractionAttention(env, userId, projectId, sessionId, markerId), + async fulfilSecret(userId, projectId, requestId, secret) { const database = db(); const result = await fulfillRuntimeSecretRequest(env, database, { @@ -129,23 +137,15 @@ export function createInboxPort(env: Env): OperationInboxPort { return { agentNotified: result.agentNotified }; }, - async decideApproval(userId, approvalId, decision, note) { - await requireActiveSuperadmin(env, userId); - const outcome = await decideOperationsAction(env, { - approvalId, - decision, - deciderUserId: userId, - note: note?.trim() || null, - }); - if (outcome.outcome === 'not_found') throw errors.notFound('Inbox item'); - if (outcome.outcome !== 'decided') { - throw errors.conflict( - outcome.outcome === 'expired' - ? 'This request expired before it was decided' - : `This request was already ${outcome.approval.status}` - ); - } - return { outcome: outcome.approval.status, agentNotified: outcome.delivered }; + archiveSecret: (userId, projectId, requestId) => + archiveRuntimeSecretRequest(db(), { projectId, requestId, actorUserId: userId }), + + decideApproval: (userId, approvalId, decision, note) => + decideInboxApproval(env, userId, approvalId, decision, note, 'notify_agent'), + + async archiveApproval(userId, approvalId) { + const result = await decideInboxApproval(env, userId, approvalId, 'deny', null, 'silent'); + return { outcome: result.outcome }; }, async authorizeAnswerWake(projectId, sessionId, userId) { @@ -262,3 +262,31 @@ async function loadSessionReadAccess( ); return Boolean(session) && access.found; } + +/** An Operations approval decided from the inbox, by an active superadmin. */ +async function decideInboxApproval( + env: Env, + userId: string, + approvalId: string, + decision: 'approve' | 'deny', + note: string | null, + delivery: 'notify_agent' | 'silent' +): Promise<{ outcome: string; agentNotified: boolean }> { + await requireActiveSuperadmin(env, userId); + const outcome = await decideOperationsAction(env, { + approvalId, + decision, + deciderUserId: userId, + note: note?.trim() || null, + delivery, + }); + if (outcome.outcome === 'not_found') throw errors.notFound('Inbox item'); + if (outcome.outcome !== 'decided') { + throw errors.conflict( + outcome.outcome === 'expired' + ? 'This request expired before it was decided' + : `This request was already ${outcome.approval.status}` + ); + } + return { outcome: outcome.approval.status, agentNotified: outcome.delivered }; +} diff --git a/apps/api/src/services/operations-actions/service.ts b/apps/api/src/services/operations-actions/service.ts index 6ff0a59f73..5fd3406f3a 100644 --- a/apps/api/src/services/operations-actions/service.ts +++ b/apps/api/src/services/operations-actions/service.ts @@ -176,6 +176,11 @@ export async function decideOperationsAction( decision: OperationsApprovalDecision; deciderUserId: string; note: string | null; + /** + * `notify_agent` sends the decision to the requesting agent; `silent` records it and tells + * no one (an inbox archive, which denies without telling the agent; Raphaël, 2026-11-17). + */ + delivery: 'notify_agent' | 'silent'; } ): Promise { const result = await decideApproval(env.DATABASE, { @@ -196,7 +201,10 @@ export async function decideOperationsAction( approvalId: result.approval.id, detail: { action: result.approval.action }, }); - const delivered = await deliverOperationsDecision(env, result.approval); + const delivered = + input.delivery === 'notify_agent' + ? await deliverOperationsDecision(env, result.approval) + : false; return { ...result, delivered }; } diff --git a/apps/api/src/services/runtime-secret-requests.ts b/apps/api/src/services/runtime-secret-requests.ts index f2e6de84bb..81371a198b 100644 --- a/apps/api/src/services/runtime-secret-requests.ts +++ b/apps/api/src/services/runtime-secret-requests.ts @@ -470,6 +470,35 @@ export async function fulfillRuntimeSecretRequest( } /** Caller has verified `secret:write` on the project. */ +/** + * Archive a pending secret request from the inbox: it closes as declined and the agent is told + * nothing (Raphaël, 2026-11-17: every inbox kind archives silently). `notified_at` is set in the + * closing write, so the notice sweep (`retryRuntimeSecretRequestNotices`) never sends one, and the + * request is no longer pending, so its expiry does not tell the agent either. + */ +export async function archiveRuntimeSecretRequest( + db: Db, + input: { projectId: string; requestId: string; actorUserId: string } +): Promise { + const { row } = await getRuntimeSecretRequest(db, input.projectId, input.requestId); + const now = Date.now(); + assertStillPending(row, now); + const resolution = { + status: 'declined', + resolvedBy: input.actorUserId, + resolvedAt: now, + notifiedAt: now, + } as const; + if (!(await claimPendingRequest(db, row, resolution, now))) { + throw errors.conflict('This secret request was already answered or has expired'); + } + log.info('runtime_secret_request.archived', { + requestId: row.id, + projectId: row.projectId, + actorUserId: input.actorUserId, + }); +} + export async function declineRuntimeSecretRequest( env: Env, db: Db, diff --git a/apps/api/tests/integration/ops-action-approvals.test.ts b/apps/api/tests/integration/ops-action-approvals.test.ts index 139d8ce38c..843546b180 100644 --- a/apps/api/tests/integration/ops-action-approvals.test.ts +++ b/apps/api/tests/integration/ops-action-approvals.test.ts @@ -44,6 +44,7 @@ import * as schema from '../../src/db/schema'; import type { Env } from '../../src/env'; import { handleAppError } from '../../src/middleware/app-error-handler'; import { adminOperationsApprovalRoutes } from '../../src/routes/admin-operations-approvals'; +import { createInboxPort } from '../../src/services/inbox/port'; import { callMcpTool, createJsonKv, @@ -372,6 +373,21 @@ describe('execute refusals (each is a guard in the claim CAS)', () => { expect(row(approval.id).status).toBe('denied'); }); + it('archiving from the inbox denies the ticket and tells the agent nothing', async () => { + const approval = await request('delete_node', NODE_A); + edges.acceptPromptDelivery.mockClear(); + await expect(createInboxPort(env).archiveApproval('admin', approval.id)).resolves.toEqual({ + outcome: 'denied', + }); + expect(row(approval.id)).toMatchObject({ status: 'denied', decided_by: 'admin' }); + // No decision prompt; the admin route's deny above ("refuses a denied ticket") is the control + // that a deny is otherwise delivered. + expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); + const outcome = await execute(approval.id, 'delete_node', NODE_A); + expect(outcome.error?.message).toContain('denied'); + expect(edges.executeAction).not.toHaveBeenCalled(); + }); + it('refuses an expired approval, and runs an unexpired control', async () => { const stale = await approved('delete_node', NODE_A); main diff --git a/apps/api/tests/unit/operations/inbox-operations.test.ts b/apps/api/tests/unit/operations/inbox-operations.test.ts index b61953200e..1dc4659349 100644 --- a/apps/api/tests/unit/operations/inbox-operations.test.ts +++ b/apps/api/tests/unit/operations/inbox-operations.test.ts @@ -709,7 +709,7 @@ describe('inbox answers and archives for every store', () => { ).toEqual({ status: 'denied', decided_by: 'admin' }); }); - it('archiving a permission declines it through the interaction answer path', async () => { + it('archiving a permission answers nothing: the item leaves the inbox and the agent is not told', async () => { const c = ctx('owner'); c.ports.inbox.attentionMarker = vi.fn().mockResolvedValue({ id: 'm-perm', @@ -728,26 +728,19 @@ describe('inbox answers and archives for every store', () => { canRead: true, canWrite: true, }); - c.ports.access.requireSessionWriter = vi.fn().mockResolvedValue({}); - const prepared = { decision: { kind: 'declined' } }; - c.ports.connector.prepareAgentAnswer = vi.fn().mockResolvedValue(prepared); - c.ports.chat.answerAgentInteraction = vi.fn().mockResolvedValue({ accepted: true }); + c.ports.inbox.archiveInteraction = vi.fn().mockResolvedValue(undefined); + c.ports.connector.prepareAgentAnswer = vi.fn(); + c.ports.chat.answerAgentInteraction = vi.fn(); await expect( archiveInboxItem(c, { projectId: P1, ref: 'attention:chat-1:m-perm' }) - ).resolves.toMatchObject({ outcome: 'declined' }); - expect(c.ports.connector.prepareAgentAnswer).toHaveBeenCalledWith( - P1, - 'chat-1', - 'interaction-1', - expect.objectContaining({ decline: true }) - ); - expect(c.ports.chat.answerAgentInteraction).toHaveBeenCalledWith( - 'owner', - P1, - 'chat-1', - 'interaction-1', - prepared - ); + ).resolves.toEqual({ + ref: 'attention:chat-1:m-perm', + outcome: 'archived', + agentNotified: false, + }); + expect(c.ports.inbox.archiveInteraction).toHaveBeenCalledWith('owner', P1, 'chat-1', 'm-perm'); + expect(c.ports.connector.prepareAgentAnswer).not.toHaveBeenCalled(); + expect(c.ports.chat.answerAgentInteraction).not.toHaveBeenCalled(); }); it('a question a member can only read is not theirs to see or answer', async () => { diff --git a/apps/api/tests/workers/inbox-capability.test.ts b/apps/api/tests/workers/inbox-capability.test.ts index 96417fb805..ba69ee662a 100644 --- a/apps/api/tests/workers/inbox-capability.test.ts +++ b/apps/api/tests/workers/inbox-capability.test.ts @@ -452,7 +452,7 @@ describe('inbox capability through the real entry points', () => { expect(await checkinGate(s.project, s.chatSessionId)).toMatchObject({ questionHold: true }); }); - it('a secret request archived through the inbox is declined and the agent notified', async () => { + it('a secret request archived through the inbox is declined and the agent is not told', async () => { const s = await seed(); const created = await callTool(s.token, 'request_secret', { name: 'STRIPE_API_KEY', @@ -471,14 +471,21 @@ describe('inbox capability through the real entry points', () => { s.ownerCookie ); expect(archived.status).toBe(200); - expect(archived.body).toMatchObject({ outcome: 'declined', agentNotified: true }); + expect(archived.body).toMatchObject({ outcome: 'declined', agentNotified: false }); const row = await testEnv.DATABASE.prepare( 'SELECT status, notified_at FROM runtime_secret_requests WHERE id = ?' ) .bind(requestId) .first<{ status: string; notified_at: number | null }>(); expect(row?.status).toBe('declined'); + // Settled in the closing write, so the notice sweep never sends one. expect(row?.notified_at).not.toBeNull(); + const snapshot = await s.project.getDurableExecutionSnapshot(s.chatSessionId); + expect( + snapshot.deliveries.filter( + (delivery: { sourceKind?: string }) => delivery.sourceKind === 'secret_request' + ) + ).toEqual([]); const after = await get(`/api/projects/${s.projectId}/inbox`, s.ownerCookie); expect(after.body.items.map((item) => item.ref)).not.toContain(ref); }); diff --git a/apps/api/tests/workers/inbox-interaction-notifications.test.ts b/apps/api/tests/workers/inbox-interaction-notifications.test.ts index b43ab7b6c5..325a55cf0b 100644 --- a/apps/api/tests/workers/inbox-interaction-notifications.test.ts +++ b/apps/api/tests/workers/inbox-interaction-notifications.test.ts @@ -16,11 +16,13 @@ import { handleAppError } from '../../src/middleware/app-error-handler'; import { acpInteractionCallbackRoute } from '../../src/routes/projects/acp-interaction-callback'; import { signCallbackToken } from '../../src/services/jwt'; import * as projectDataService from '../../src/services/project-data'; +import { get, post } from './helpers/inbox-harness'; import { seedAgentSession, seedInstallation, seedNode, seedProject, + seedSignedInUser, seedUser, seedWorkspace, } from './helpers/seed-d1'; @@ -158,6 +160,71 @@ describe('ACP interaction notifications and undelivered answers (slice E)', () = }); }); + it('archiving a permission from the inbox answers nothing: it leaves the inbox and stays pending in the chat', async () => { + const { userId, projectId, chatSessionId, interactionId, store } = await setup(); + await drain(store); + const readInteraction = () => + runInDurableObject(store, async (_instance, state) => { + return state.storage.sql + .exec( + 'SELECT state, attention_marker_id FROM interactions WHERE interaction_id = ?', + interactionId + ) + .one() as { state: string; attention_marker_id: string | null }; + }); + const before = await readInteraction(); + const markerId = before.attention_marker_id!; + expect(markerId).toBeTruthy(); + const ref = `attention:${chatSessionId}:${markerId}`; + const project = testEnv.PROJECT_DATA.get(testEnv.PROJECT_DATA.idFromName(projectId)); + const syncSummaries = () => + runInDurableObject(project, async (instance) => { + await ( + instance as unknown as { runSummarySyncLocked(): Promise } + ).runSummarySyncLocked(); + }); + await syncSummaries(); + const cookie = await seedSignedInUser(userId); + type List = { items: { ref: string }[] }; + // Liveness: the permission is in the person's inbox before the archive. + expect((await get('/api/inbox', cookie)).body.items.map((i) => i.ref)).toContain(ref); + + const fetchMock = vi.mocked(globalThis.fetch); + fetchMock.mockClear(); + const archived = await post( + `/api/projects/${projectId}/inbox/items/${encodeURIComponent(ref)}/archive`, + cookie + ); + expect(archived.status).toBe(200); + expect(archived.body).toEqual({ ref, outcome: 'archived', agentNotified: false }); + // Nothing went to the runtime, and the interaction is exactly as pending as it was. + expect(fetchMock).not.toHaveBeenCalled(); + expect(await readInteraction()).toEqual(before); + const { marker } = await projectDataService.getAttentionRequest( + testEnv, + projectId, + chatSessionId, + markerId, + userId + ); + expect(marker).toMatchObject({ resolvedReason: 'archived' }); + // It leaves the inbox and a re-run of the projection job does not bring it back. + await drain(store); + await syncSummaries(); + expect((await get('/api/inbox', cookie)).body.items.map((i) => i.ref)).not.toContain(ref); + // A second archive is a conflict, not a second write. + const again = await post( + `/api/projects/${projectId}/inbox/items/${encodeURIComponent(ref)}/archive`, + cookie + ); + expect([404, 409]).toContain(again.status); + + await runInDurableObject(store, async (_instance, state) => { + state.storage.sql.exec(`DELETE FROM outbox`); + await state.storage.deleteAlarm(); + }); + }); + it('does not notify a chat creator who is no longer a project member', async () => { // The creator was removed after starting the chat, before the request arrived. const removed = await setup(); diff --git a/apps/api/tests/workers/inbox-tasks-capability.test.ts b/apps/api/tests/workers/inbox-tasks-capability.test.ts index e43871a089..170422612a 100644 --- a/apps/api/tests/workers/inbox-tasks-capability.test.ts +++ b/apps/api/tests/workers/inbox-tasks-capability.test.ts @@ -575,7 +575,7 @@ describe('human tasks through the real entry points', () => { expect(await wakesFor(s, s.chatSessionId)).toHaveLength(1); }); - it('archive through the inbox route closes a task and wakes; untick is recorded; wakeOnSteps makes ticks wake', async () => { + it('archive through the inbox route closes a task and wakes no one; untick is recorded; wakeOnSteps makes ticks wake', async () => { const s = await seed(); const filed = await assign(s, { title: 'Check the invoice totals', @@ -605,10 +605,14 @@ describe('human tasks through the real entry points', () => { await deliverWakes(s, s.chatSessionId); const archived = await post(itemPath(s, ref, '/archive'), s.colleagueCookie, {}); expect(archived.status).toBe(200); - expect(archived.body).toMatchObject({ outcome: 'archived', agentNotified: true }); - const wakes = await wakesFor(s, s.chatSessionId); - expect(wakes).toHaveLength(1); - expect(wakes[0]!.content).toContain('archived'); + // Archive tells no watcher (every inbox archive is silent; Raphaël, 2026-11-17). The step + // ticks above prove this chat does get woken by a task event when one is sent. + expect(archived.body).toMatchObject({ outcome: 'archived', agentNotified: false }); + expect(await wakesFor(s, s.chatSessionId)).toHaveLength(0); + const settled = await testEnv.DATABASE.prepare('SELECT notified_at FROM asks WHERE id = ?') + .bind(filed.inboxItem.id) + .first<{ notified_at: number | null }>(); + expect(settled?.notified_at).not.toBeNull(); const view = await get(itemPath(s, ref), s.colleagueCookie); expect(view.body.task?.activity.map((entry) => entry.kind)).toEqual([ 'created', @@ -616,7 +620,7 @@ describe('human tasks through the real entry points', () => { 'step_unchecked', 'archived', ]); - // Reopen from archived wakes again. + // Reopening is engaging with it again, so it does wake the chat. await deliverWakes(s, s.chatSessionId); expect((await post(itemPath(s, ref, '/reopen'), s.colleagueCookie, {})).body).toMatchObject({ status: 'open', diff --git a/apps/web/src/components/inbox/useInbox.ts b/apps/web/src/components/inbox/useInbox.ts index 110cd71382..6f94d53218 100644 --- a/apps/web/src/components/inbox/useInbox.ts +++ b/apps/web/src/components/inbox/useInbox.ts @@ -80,9 +80,9 @@ export function useInvalidateInbox() { } /** - * How long an archive can be undone before it is sent. Archive closes the item (and denies a - * permission, approval or secret request), so a slip of the thumb must be recoverable. Override - * with VITE_INBOX_ARCHIVE_UNDO_MS. + * How long an archive can be undone before it is sent. Archive closes the item (a secret request + * as declined, an approval as denied), so a slip of the thumb must be recoverable. Override with + * VITE_INBOX_ARCHIVE_UNDO_MS. */ const DEFAULT_INBOX_ARCHIVE_UNDO_MS = 5_000; const configuredUndoMs = Number.parseInt(import.meta.env.VITE_INBOX_ARCHIVE_UNDO_MS ?? '', 10); diff --git a/apps/web/src/components/project-message-view/tool-cards/SecretRequestCard.tsx b/apps/web/src/components/project-message-view/tool-cards/SecretRequestCard.tsx index 056395d483..15579c6c9d 100644 --- a/apps/web/src/components/project-message-view/tool-cards/SecretRequestCard.tsx +++ b/apps/web/src/components/project-message-view/tool-cards/SecretRequestCard.tsx @@ -77,7 +77,7 @@ function outcomeText(request: RuntimeSecretRequest, valueExpired: boolean): stri } return `Supplied${by}${when}. The agent sees the name, never the value, and can use it until it expires or is deleted.`; case 'declined': - return `Declined${by}${when}. SAM tells the agent not to wait for it.`; + return `Declined${by}${when}.`; case 'expired': return 'Nobody supplied a value in time. SAM tells the agent not to wait for it.'; case 'pending': diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index c13e190d9a..486ba77cf2 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -287,7 +287,7 @@ items agents file (`packages/operations/src/inbox-settings-definition.ts`). | `inbox.answerMaxChars` | 4,000 | 100–20,000 | Characters of a typed answer or comment | | `inbox.similarMatchesMax` | 3 | 0–20 | Similar open items an agent is shown when it files an ask, review or result; 0 turns it off | | `inbox.similarScanMax` | 50 | 1–500 | Newest open items of the project compared when an agent files (rows read per filing) | -| `inbox.noticeRetryMinutes` | 60 | 5–1,440 | Minutes the sweep retries telling an agent its item was answered or expired, or a task archived | +| `inbox.noticeRetryMinutes` | 60 | 5–1,440 | Minutes the sweep retries telling an agent its item was answered, done or expired | | `inbox.automationFailureThreshold` | 2 | 1–20 | Failed runs in a row that file an inbox error item for an automation's owner | | `inbox.errorSweepBatchSize` | 10 | 1–50 | Error items one five-minute sweep files at most (failed tasks, automations, lost answers) | | `inbox.errorLookbackMinutes` | 30 | 5–1,440 | How far back that sweep looks for failures with no error item yet | diff --git a/apps/www/src/content/docs/docs/guides/inbox.md b/apps/www/src/content/docs/docs/guides/inbox.md index 8b607b683a..233114183f 100644 --- a/apps/www/src/content/docs/docs/guides/inbox.md +++ b/apps/www/src/content/docs/docs/guides/inbox.md @@ -141,8 +141,9 @@ and the chat it came from. In the app today a task is read-only, so finishing it speech bubble at the top) and say so, for example _"done, the key is in the production environment"_. Otherwise tell the person who started that chat, or comment on the task through the [API](/docs/reference/api/#inbox): a comment from the assignee wakes the agent. -3. Leave the task open until the agent has picked it up. **Archive** it only once the agent knows, - or if you won't do it: archiving tells the agent you will not act on it. +3. Leave the task open until the agent has picked it up. **Archive** it once the agent knows, or + if you won't do it. Archiving tells the agent nothing, so if it should stop waiting, say so in + the chat or comment on the task first. Controls for ticking steps, commenting, marking it **done**, handing it on and **I'll take it** come with the task view in the next release; until then they are available through the @@ -158,14 +159,14 @@ from then on it is theirs, and it no longer counts as waiting on the others. Mem cannot write tasks (viewers) can read a task and comment on it, nothing more. The agent that assigned the task is woken in its chat when you comment, take it, hand it on, mark it -done, reopen it or archive it. Ticking steps is recorded and does not wake it unless it asked for +done or reopen it. Archiving it wakes no one. Ticking steps is recorded and does not wake it unless it asked for that. A comment wakes it only when it comes from the assignee, the member who took the task, or someone who can write in the agent's chat; anyone else's comment is kept, and the agent reads it the next time it wakes. A comment from someone other than the chat's owner reaches the agent as a teammate's input, not as an instruction from the owner. Another chat of the same person can watch the task instead of -assigning a duplicate (`attach`); it is woken when the task is taken, handed on, finished, reopened -or archived, and reads the comments at those wakes. +assigning a duplicate (`attach`); it is woken when the task is taken, handed on, finished or +reopened, and reads the comments at those wakes. A teammate who cannot read the agent's chat still sees the task, its steps, links and discussion, never the chat transcript. Task discussion also appears on the project's Comments page for the @@ -211,12 +212,18 @@ item closes by itself. An item you archived stays archived while the thing keeps ## Archive -**Archive** (the box at the top) means you will not act on the item: it closes. Archiving a -question, review or result does not tell the agent; it stays where it is until you answer something or -write in its chat. SAM's automatic check-ins also stay off that chat until you write in it (for up -to `inbox.archiveCheckinHoldHours`, a week by default), so nothing nudges the agent. A permission is denied, a secret declined and an approval denied, and the agent -hears that. Archiving a task tells the chats watching it. A Problem has no agent, so archiving it -tells no one. For a few seconds the +**Archive** (the box at the top) means you will not act on the item: it leaves your inbox, and no +agent is told. The agent stays where it is until you answer something or write in its chat. +Archiving a question also keeps SAM's automatic check-ins off that chat until you write in it (for +up to `inbox.archiveCheckinHoldHours`, a week by default), so nothing nudges the agent. + +- A question, review, result or task closes. +- A secret request closes as declined and an approval as denied, without telling the agent. +- A permission request leaves your inbox but is not answered: it stays pending in its chat, where + you can still answer it, and the agent keeps waiting until it gives up on it. +- A Problem has no agent to tell. + +For a few seconds the receipt offers **Undo**; nothing is sent until that time is up. If you leave the page or close the tab first, the archive is sent then. diff --git a/apps/www/src/content/docs/docs/reference/api.md b/apps/www/src/content/docs/docs/reference/api.md index 97b5ec0057..60db7d550c 100644 --- a/apps/www/src/content/docs/docs/reference/api.md +++ b/apps/www/src/content/docs/docs/reference/api.md @@ -606,21 +606,20 @@ approval decision. Secret values and Operations approval decisions are accepted only from the SAM app, never through an app connected to the Connector (`403`). Answering an item filed from a chat needs the same right to wake that chat's agent as answering in the chat. Archiving wakes nothing: an inbox ask -needs only that it is yours to act on, and a question asked before questions moved to inbox asks -needs the right to write in its chat. - -Archive closes an item for every kind. A question, review or result becomes `archived` (a -question asked before questions moved to inbox asks is resolved with reason `archived`) and the -agent is not told: it stays where it is until you answer something or write in its chat. Archiving -a question also holds SAM's automatic check-ins off that chat until someone writes in it, for at -most `inbox.archiveCheckinHoldHours`. A permission or approval is denied and a secret request is -declined, which the agent does hear. Archiving a task tells the chats watching it. Both writes -return `{ ref, outcome, agentNotified }`; for an answer or an archived task, `agentNotified: false` -means the notice was not queued yet, and SAM retries it for `inbox.noticeRetryMinutes`. The -exception is **Got it** on a result (an empty `acknowledge` answer): it closes the item without -telling the agent, by design, so nothing is retried. A non-empty reply to a review or result whose -agent has finished returns `400`, because it could not be delivered. Writes must come from the -app's own origin with +needs only that it is yours to act on, and a question asked before questions moved to inbox asks or +a pending permission needs the right to write in its chat. + +Archive closes an item for every kind and tells no agent (`agentNotified` is always `false`). A +question, review, result or task becomes `archived` (a question asked before questions moved to +inbox asks is resolved with reason `archived`); a secret request becomes `declined` and an approval +`denied`; a pending permission, form or link request leaves the inbox without an answer and stays +answerable in its chat. Archiving a question also holds SAM's automatic check-ins off that chat +until someone writes in it, for at most `inbox.archiveCheckinHoldHours`. Both writes return +`{ ref, outcome, agentNotified }`; for an answer, `agentNotified: false` means the notice was not +queued yet, and SAM retries it for `inbox.noticeRetryMinutes`. The exception is **Got it** on a +result (an empty `acknowledge` answer): it closes the item without telling the agent, by design, +so nothing is retried. A non-empty reply to a review or result whose agent has finished returns +`400`, because it could not be delivered. Writes must come from the app's own origin with `Content-Type: application/json`, like the other answer routes. A missing item and one in another project both return `404`; an item that is already closed returns `409`, and one you cannot act on returns `403`. The transcript context is returned only to a member who can read the source chat. diff --git a/packages/operations/src/inbox-operations.ts b/packages/operations/src/inbox-operations.ts index e46e800bef..abfac8bd35 100644 --- a/packages/operations/src/inbox-operations.ts +++ b/packages/operations/src/inbox-operations.ts @@ -106,7 +106,7 @@ export const samInboxArchive = defineOperation({ name: 'sam_inbox_archive', title: 'Archive an inbox item (confirm every time)', description: - 'Use this when the user chooses not to act on an inbox item. Archive closes it: a question or review is closed without telling the agent, a permission or approval is denied, a secret request is declined. Confirm with the user first. Reuse requestKey on retries.', + 'Use this when the user chooses not to act on an inbox item. Archive closes it and tells no agent: a question, review or task closes, a secret request closes as declined and an approval as denied, and a pending permission leaves the inbox unanswered (still answerable in its chat). Confirm with the user first. Reuse requestKey on retries.', kind: 'destructive', input: v.object({ projectId: id, ref, requestKey }), run(ctx, input) { diff --git a/packages/operations/src/inbox-settings-definition.ts b/packages/operations/src/inbox-settings-definition.ts index 6d0bbd5a83..044ac7ad08 100644 --- a/packages/operations/src/inbox-settings-definition.ts +++ b/packages/operations/src/inbox-settings-definition.ts @@ -89,7 +89,7 @@ export const INBOX_SETTINGS = [ name: 'inbox.noticeRetryMinutes', defaultValue: 60, description: - 'Minutes the sweep keeps retrying an agent’s notice that an inbox item was answered, a task archived, or an item expired.', + 'Minutes the sweep keeps retrying an agent’s notice that an inbox item was answered, done or expired.', range: { min: 5, max: 1_440 }, }, // Questions (`request_human_input`). Defaults are the old HUMAN_INPUT_* Worker defaults diff --git a/packages/operations/src/inbox-task-core.ts b/packages/operations/src/inbox-task-core.ts index 0f44b8caa5..2dae047510 100644 --- a/packages/operations/src/inbox-task-core.ts +++ b/packages/operations/src/inbox-task-core.ts @@ -407,9 +407,10 @@ export async function reassignTask( } /** - * Close an open task as done or archived. The `sam.inbox` event is the agent's notice; + * Close an open task as done or archived. Done: the `sam.inbox` event is the agent's notice, and * `notified_at` is stamped after it is committed so the ask-notice sweep sends one only when the - * event could not be. + * event could not be. Archived: no event, and `notified_at` is set in the closing write, so no + * watcher is told (every inbox archive is silent; Raphaël, 2026-11-17). */ async function closeTask( ctx: OperationContext, @@ -421,9 +422,10 @@ async function closeTask( requireOpen(row); const me = ctx.actor.userId; const now = Date.now(); + const silent = status === 'archived'; const result = await ctx.env.DATABASE.prepare( `UPDATE asks AS a SET status = ?, answer_json = ?, resolved_by_user_id = ?, resolved_at = ?, - updated_at = ? + updated_at = ?, notified_at = CASE WHEN ? THEN ? ELSE a.notified_at END WHERE a.id = ? AND a.project_id = ? AND a.kind = 'task' AND a.status = 'open' AND ${TASK_WRITABLE_SQL}` ) @@ -433,6 +435,8 @@ async function closeTask( me, now, now, + silent ? 1 : 0, + now, row.id, row.projectId, me, @@ -449,6 +453,7 @@ async function closeTask( actorId: me, at: now, }); + if (silent) return { ref: `ask:${row.id}`, status, agentNotified: false }; const agentNotified = await admit(ctx, row, `inbox.task.${status}`); if (agentNotified) { // The event is the agent's notice. Marked only once it is committed to the outbox: if that @@ -474,7 +479,7 @@ export async function completeTask( return closeTask(ctx, target, 'done', note); } -/** Archive means closed: the watching agents are told the person will not act. */ +/** Archive means closed: the task leaves the inbox and no watching agent is told. */ export async function archiveTask( ctx: OperationContext, target: TaskTarget diff --git a/packages/operations/src/inbox-write-core.ts b/packages/operations/src/inbox-write-core.ts index 3bb208fade..833717f776 100644 --- a/packages/operations/src/inbox-write-core.ts +++ b/packages/operations/src/inbox-write-core.ts @@ -412,8 +412,11 @@ async function archiveCheckinHold(ctx: OperationContext): Promise; + /** + * Remove a pending ACP interaction (permission, form, link) from the inbox. Nothing is + * answered: the agent is not told, and the interaction stays answerable in its chat. + */ + archiveInteraction( + userId: string, + projectId: string, + sessionId: string, + markerId: string + ): Promise; fulfilSecret( userId: string, projectId: string, @@ -503,12 +513,16 @@ export interface OperationInboxPort { projectId: string, requestId: string ): Promise<{ agentNotified: boolean }>; + /** Close a pending secret request as declined without telling the agent. */ + archiveSecret(userId: string, projectId: string, requestId: string): Promise; decideApproval( userId: string, approvalId: string, decision: 'approve' | 'deny', note: string | null ): Promise<{ outcome: string; agentNotified: boolean }>; + /** Deny an Operations approval without telling the agent. */ + archiveApproval(userId: string, approvalId: string): Promise<{ outcome: string }>; /** Authorizes waking the agent in a chat for this actor (`authorizeAgentWake`); throws when refused. */ authorizeAnswerWake(projectId: string, sessionId: string, userId: string): Promise; /** diff --git a/packages/project-data/src/client/project-data.ts b/packages/project-data/src/client/project-data.ts index f90a67d89c..3819320e20 100644 --- a/packages/project-data/src/client/project-data.ts +++ b/packages/project-data/src/client/project-data.ts @@ -3560,6 +3560,25 @@ export async function recordQuestionAsked( ); } +/** + * The person archived a pending ACP interaction (a permission, form or link request) from their + * inbox: its inbox marker resolves with reason `archived`; the interaction itself stays pending + * and answerable in the chat. Returns how many markers resolved (0 when already resolved). + */ +export async function archiveInteractionMarker( + env: Env, + projectId: string, + markerId: string +): Promise { + return callProjectDataWithRetry( + env, + projectId, + 'resolveAttentionMarkerById', + (stub) => stub.resolveAttentionMarkerById(markerId, 'human', 'archived'), + 'mutation' + ); +} + /** The person archived a question held in D1 `asks`: a live update only, nothing reaches the agent. */ export async function recordQuestionArchived( env: Env, From 5fecbd9759975e18000dbc7ed95ee0b0952c9aee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 16:32:45 +0000 Subject: [PATCH 2/5] fix(inbox): audit a teammate's permission archive; skip every archived item in sweeps From security review of #2873: archiving a permission now records the session.shared_answer event for a grantee, as question archives do, and the notice and undelivered-answer sweeps skip every archived item (an earlier build's archived tasks included). Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/chat-attention.ts | 4 +- apps/api/src/services/inbox/sweep.ts | 6 +- apps/api/src/services/inbox/system-errors.ts | 4 +- .../src/services/runtime-secret-requests.ts | 5 +- .../unit/operations/inbox-operations.test.ts | 4 +- .../inbox-interaction-notifications.test.ts | 65 +++++++++++++++++++ 6 files changed, 79 insertions(+), 9 deletions(-) diff --git a/apps/api/src/routes/chat-attention.ts b/apps/api/src/routes/chat-attention.ts index f413609d19..d52d8c93ca 100644 --- a/apps/api/src/routes/chat-attention.ts +++ b/apps/api/src/routes/chat-attention.ts @@ -423,7 +423,7 @@ export async function archiveInteractionAttention( ): Promise { const db = drizzle(env.DATABASE, { schema }); await requireProjectCapability(db, projectId, userId, 'task:write'); - await requireSessionWriter(env, projectId, sessionId, userId, { + const writer = await requireSessionWriter(env, projectId, sessionId, userId, { db, action: 'archive the agent request in this session', }); @@ -435,4 +435,6 @@ export async function archiveInteractionAttention( throw markRejectedBeforeEffects(errors.conflict('Attention request is already resolved')); const resolved = await projectDataService.archiveInteractionMarker(env, projectId, markerId); if (resolved === 0) throw errors.conflict('Attention request is already resolved'); + // A grantee's archive is recorded like their answers and question archives. + await recordSharedSessionAnswer(env, writer, { markerId, archived: true }); } diff --git a/apps/api/src/services/inbox/sweep.ts b/apps/api/src/services/inbox/sweep.ts index c005d4d299..3f00c465ca 100644 --- a/apps/api/src/services/inbox/sweep.ts +++ b/apps/api/src/services/inbox/sweep.ts @@ -252,9 +252,9 @@ export async function runInboxAskSweep(env: Env, now = Date.now()): Promise ? AND resolved_at <= ? ORDER BY resolved_at LIMIT ?` ) diff --git a/apps/api/src/services/inbox/system-errors.ts b/apps/api/src/services/inbox/system-errors.ts index 75a3cf8e3c..f2ff83d778 100644 --- a/apps/api/src/services/inbox/system-errors.ts +++ b/apps/api/src/services/inbox/system-errors.ts @@ -335,8 +335,8 @@ async function fileUndeliveredAskAnswers( -- The status list is \`idx_asks_unnotified\`'s, term for term, so the index applies. WHERE a.notified_at IS NULL AND a.status IN ('answered', 'done', 'archived', 'expired') AND a.status != 'expired' - -- An archived question, review or result owes the agent no notice (2026-11-17), so none is lost. - AND NOT (a.status = 'archived' AND a.kind IN ('question', 'review', 'result')) + -- An archived item owes the agent no notice (2026-11-17), so none is lost. + AND a.status != 'archived' AND a.kind != 'error' AND a.source_session_id IS NOT NULL AND a.resolved_by_user_id IS NOT NULL AND a.resolved_at > ? AND a.resolved_at <= ? diff --git a/apps/api/src/services/runtime-secret-requests.ts b/apps/api/src/services/runtime-secret-requests.ts index 81371a198b..34e92a062e 100644 --- a/apps/api/src/services/runtime-secret-requests.ts +++ b/apps/api/src/services/runtime-secret-requests.ts @@ -469,12 +469,12 @@ export async function fulfillRuntimeSecretRequest( return { request: toRuntimeSecretRequest(resolved, input.actorName, claimedAt), agentNotified }; } -/** Caller has verified `secret:write` on the project. */ /** * Archive a pending secret request from the inbox: it closes as declined and the agent is told * nothing (Raphaël, 2026-11-17: every inbox kind archives silently). `notified_at` is set in the * closing write, so the notice sweep (`retryRuntimeSecretRequestNotices`) never sends one, and the - * request is no longer pending, so its expiry does not tell the agent either. + * request is no longer pending, so its expiry does not tell the agent either. The caller has + * authorized the actor (`requireActable`: task:write and the item's `canAct`). */ export async function archiveRuntimeSecretRequest( db: Db, @@ -499,6 +499,7 @@ export async function archiveRuntimeSecretRequest( }); } +/** Caller has verified `secret:write` on the project. */ export async function declineRuntimeSecretRequest( env: Env, db: Db, diff --git a/apps/api/tests/unit/operations/inbox-operations.test.ts b/apps/api/tests/unit/operations/inbox-operations.test.ts index 1dc4659349..2708adea4d 100644 --- a/apps/api/tests/unit/operations/inbox-operations.test.ts +++ b/apps/api/tests/unit/operations/inbox-operations.test.ts @@ -514,7 +514,7 @@ describe('inbox asks writes', () => { expect(edges.acceptPromptDelivery).not.toHaveBeenCalled(); }); - it('the sweep sends nothing for questions, reviews and results an earlier build archived without a notice', async () => { + it('the sweep sends nothing for items an earlier build archived without a notice', async () => { const resolvedAt = Date.now() - 10 * 60_000; const closed = { source_session_id: 'chat-1', @@ -524,6 +524,7 @@ describe('inbox asks writes', () => { ask('old-question', { ...closed, kind: 'question', status: 'archived' }); ask('old-review', { ...closed, kind: 'review', status: 'archived' }); ask('old-result', { ...closed, kind: 'result', status: 'archived' }); + ask('old-task', { ...closed, kind: 'task', status: 'archived' }); // Control: an answer whose notice was not queued is still retried in the same run. ask('old-answer', { ...closed, kind: 'review', status: 'answered' }); await expect(runInboxAskSweep(env, Date.now())).resolves.toMatchObject({ noticesRetried: 1 }); @@ -536,6 +537,7 @@ describe('inbox asks writes', () => { expect(askRow('old-question').notified_at).toBeNull(); expect(askRow('old-review').notified_at).toBeNull(); expect(askRow('old-result').notified_at).toBeNull(); + expect(askRow('old-task').notified_at).toBeNull(); }); it('the sweep expires an open ask past its deadline and leaves an unexpired one', async () => { diff --git a/apps/api/tests/workers/inbox-interaction-notifications.test.ts b/apps/api/tests/workers/inbox-interaction-notifications.test.ts index 325a55cf0b..3c64240e56 100644 --- a/apps/api/tests/workers/inbox-interaction-notifications.test.ts +++ b/apps/api/tests/workers/inbox-interaction-notifications.test.ts @@ -13,6 +13,8 @@ import { projectInteractionAttention } from '../../src/durable-objects/interacti import type { NotificationService } from '../../src/durable-objects/notification'; import type { Env } from '../../src/env'; import { handleAppError } from '../../src/middleware/app-error-handler'; +import { requireApproved, requireAuth } from '../../src/middleware/auth'; +import { chatRoutes } from '../../src/routes/chat'; import { acpInteractionCallbackRoute } from '../../src/routes/projects/acp-interaction-callback'; import { signCallbackToken } from '../../src/services/jwt'; import * as projectDataService from '../../src/services/project-data'; @@ -225,6 +227,69 @@ describe('ACP interaction notifications and undelivered answers (slice E)', () = }); }); + it('a teammate the chat is shared with can archive a permission, and the archive is audited', async () => { + const { userId, projectId, chatSessionId, interactionId, store } = await setup(); + await drain(store); + const markerId = await runInDurableObject(store, async (_instance, state) => { + const row = state.storage.sql + .exec( + 'SELECT attention_marker_id FROM interactions WHERE interaction_id = ?', + interactionId + ) + .one() as { attention_marker_id: string }; + return row.attention_marker_id; + }); + const granteeId = `inbox-e-grantee-${crypto.randomUUID()}`; + await seedUser(granteeId); + await testEnv.DATABASE.prepare( + `INSERT INTO project_members (project_id, user_id, role, status) VALUES (?, ?, 'maintainer', 'active')` + ) + .bind(projectId, granteeId) + .run(); + const ownerCookie = await seedSignedInUser(userId); + const granteeCookie = await seedSignedInUser(granteeId); + const shareApp = new Hono<{ Bindings: Env }>(); + shareApp.onError(handleAppError); + shareApp.use('/api/projects/*', requireAuth(), requireApproved()); + shareApp.route('/api/projects/:projectId/sessions', chatRoutes); + const shared = await shareApp.request( + `/api/projects/${projectId}/sessions/${chatSessionId}/access/grants`, + { + method: 'POST', + headers: { Cookie: ownerCookie, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + userId: granteeId, + durationMinutes: 30, + acknowledgeSharedCredentials: true, + }), + }, + testEnv + ); + expect(shared.status).toBeLessThan(300); + + const ref = `attention:${chatSessionId}:${markerId}`; + const archived = await post( + `/api/projects/${projectId}/inbox/items/${encodeURIComponent(ref)}/archive`, + granteeCookie + ); + expect(archived.status).toBe(200); + const { events } = await projectDataService.listActivityEvents( + testEnv, + projectId, + 'session.shared_answer', + 10, + null, + chatSessionId + ); + expect(JSON.stringify(events)).toContain(markerId); + expect(JSON.stringify(events)).toContain('"archived":true'); + + await runInDurableObject(store, async (_instance, state) => { + state.storage.sql.exec(`DELETE FROM outbox`); + await state.storage.deleteAlarm(); + }); + }); + it('does not notify a chat creator who is no longer a project member', async () => { // The creator was removed after starting the chat, before the request arrived. const removed = await setup(); From be89038be89c857aa6944fcbfedee08d1b9bf206 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 16:46:48 +0000 Subject: [PATCH 3/5] fix(inbox): archived permissions keep SAM's check-in hold; task watches wind down From correctness review of #2873. - HIGH: archiving a permission resolved its attention marker, and that marker is what keeps the silent-agent reconciliation off a chat whose agent waits on a person; after the hard stall SAM would cancel the prompt and check in. Archive now sets a new `inbox_archived_at` (DO migration 082-attention-marker-inbox-archived, additive column + index) instead of resolving: the summary (inbox list, chat list) skips the marker, the summary delta re-reads chats with newly archived markers, and the item read reports it archived, while reconciliation still sees it unresolved. - MEDIUM: an archived task's watches now wind down (closedTaskWatchHours), as a moot task's do, since no event does it. - MEDIUM: request_secret and ops_request_action text says an inbox archive sends no notice; task watcher comments no longer list archive. - The no-longer-emitted inbox.task.archived event type is kept, commented. Tests: reconciliation candidates exclude a chat with an inbox-archived permission and include it once the marker resolves (fails if archive resolves the marker); the permission worker test asserts the marker stays unresolved and the item leaves the inbox (failed before the delta change); the summary delta plan uses the new index; the task test asserts its watch expires. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/routes/chat-attention.ts | 22 +++++---- apps/api/src/routes/mcp/ops-action-tools.ts | 2 +- .../src/routes/mcp/secret-request-tools.ts | 2 +- .../mcp/tool-definitions-ops-action-tools.ts | 2 +- .../mcp/tool-definitions-secret-exec.ts | 2 +- apps/api/src/services/inbox/port.ts | 1 + .../reconciliation-loop.test.ts | 48 +++++++++++++++++++ .../session-summary-sync.test.ts | 3 +- .../unit/operations/inbox-operations.test.ts | 2 + .../inbox-interaction-notifications.test.ts | 5 +- .../workers/inbox-tasks-capability.test.ts | 8 ++++ .../src/content/docs/docs/reference/api.md | 17 +++---- packages/operations/src/inbox-agent-tasks.ts | 5 +- packages/operations/src/inbox-item-core.ts | 3 +- packages/operations/src/inbox-task-core.ts | 10 +++- packages/operations/src/ports.ts | 2 + .../project-data/src/client/project-data.ts | 9 ++-- packages/project-data/src/do/attention.ts | 28 ++++++++++- packages/project-data/src/do/index.ts | 17 +++++++ packages/project-data/src/do/migrations.ts | 23 +++++++++ .../src/do/row-schemas/attention.ts | 4 ++ .../src/do/session-summary-sync.ts | 10 ++-- packages/shared/src/types/inbox-tasks.ts | 2 + 23 files changed, 191 insertions(+), 36 deletions(-) diff --git a/apps/api/src/routes/chat-attention.ts b/apps/api/src/routes/chat-attention.ts index d52d8c93ca..ab62087fb6 100644 --- a/apps/api/src/routes/chat-attention.ts +++ b/apps/api/src/routes/chat-attention.ts @@ -407,11 +407,12 @@ export async function archiveAttention( } /** - * Archive a pending ACP interaction (a permission, form or link request) from the inbox: its - * inbox marker resolves with reason `archived` and nothing is answered, so the agent is told - * nothing and stays where it is (Raphaël, 2026-11-17: every inbox kind archives silently). The - * interaction stays pending in its chat, where the person can still answer it, until the runtime - * gives up on it. The marker is projected once per interaction + * Archive a pending ACP interaction (a permission, form or link request) from the inbox: nothing + * is answered, so the agent is told nothing and stays where it is (Raphaël, 2026-11-17: every + * inbox kind archives silently). Its marker is flagged `inbox_archived_at`, not resolved: it + * leaves the inbox, while SAM's silent-agent reconciliation still sees the chat as waiting on a + * person and does not cancel the prompt. The interaction stays pending in its chat, where the + * person can still answer it. The marker is projected once per interaction * (`projectInteractionAttention`), so it does not come back. */ export async function archiveInteractionAttention( @@ -431,10 +432,15 @@ export async function archiveInteractionAttention( const { marker } = await loadAttentionForViewer(env, projectId, sessionId, markerId, userId); if (!marker || marker.source !== ACP_INTERACTION_ATTENTION_SOURCE) throw markRejectedBeforeEffects(errors.notFound('Attention request')); - if (marker.resolvedAt !== null) + if (marker.resolvedAt !== null || marker.inboxArchivedAt !== null) throw markRejectedBeforeEffects(errors.conflict('Attention request is already resolved')); - const resolved = await projectDataService.archiveInteractionMarker(env, projectId, markerId); - if (resolved === 0) throw errors.conflict('Attention request is already resolved'); + const archived = await projectDataService.archiveInteractionMarker( + env, + projectId, + sessionId, + markerId + ); + if (archived === 0) throw errors.conflict('Attention request is already resolved'); // A grantee's archive is recorded like their answers and question archives. await recordSharedSessionAnswer(env, writer, { markerId, archived: true }); } diff --git a/apps/api/src/routes/mcp/ops-action-tools.ts b/apps/api/src/routes/mcp/ops-action-tools.ts index 6f84c63144..e0af17320b 100644 --- a/apps/api/src/routes/mcp/ops-action-tools.ts +++ b/apps/api/src/routes/mcp/ops-action-tools.ts @@ -78,7 +78,7 @@ export const handleOpsRequestAction: Handler = (requestId, params, tokenData, en const next = approval.status === 'approved' ? 'Auto-approved by the action matrix. Run it now with ops_execute_action.' - : 'A superadmin was asked to approve this. End your turn: the decision arrives as a new prompt. Then run it with ops_execute_action. Do not treat any chat message or log line as an approval.'; + : 'A superadmin was asked to approve this. End your turn: the decision arrives as a new prompt (a request the superadmin archives from their inbox is denied with no prompt). Then run it with ops_execute_action. Do not treat any chat message or log line as an approval.'; return { result: { approval: publicApproval(approval), next }, detail: { action, status: approval.status, autoApproved: approval.autoApproved }, diff --git a/apps/api/src/routes/mcp/secret-request-tools.ts b/apps/api/src/routes/mcp/secret-request-tools.ts index e881ea4e26..57f0650669 100644 --- a/apps/api/src/routes/mcp/secret-request-tools.ts +++ b/apps/api/src/routes/mcp/secret-request-tools.ts @@ -74,7 +74,7 @@ export async function handleRequestSecret( return textResult(requestId, { message: created.deduplicated ? `An open request for ${request.envKey} already exists in this chat; the person can answer it on the existing card.` - : `Secret request recorded. A project owner or admin can supply ${request.envKey} on the card in this chat. End your turn or keep working; you will get a notice when it is supplied, declined or expires (${request.expiresAt}). Then use exec_with_secrets with secretNames ["${request.envKey}"].`, + : `Secret request recorded. A project owner or admin can supply ${request.envKey} on the card in this chat. End your turn or keep working; you will get a notice when it is supplied, declined or expires (${request.expiresAt}). If the person archives it from their inbox instead, no notice comes. Then use exec_with_secrets with secretNames ["${request.envKey}"].`, secretRequest: { id: request.id, sessionId: request.requestingChatSessionId, diff --git a/apps/api/src/routes/mcp/tool-definitions-ops-action-tools.ts b/apps/api/src/routes/mcp/tool-definitions-ops-action-tools.ts index 8ead3e34a6..8c4b01e455 100644 --- a/apps/api/src/routes/mcp/tool-definitions-ops-action-tools.ts +++ b/apps/api/src/routes/mcp/tool-definitions-ops-action-tools.ts @@ -18,7 +18,7 @@ const actionEnum = { export const OPS_ACTION_TOOLS = [ tool( 'ops_request_action', - 'Ask to act on a node, workspace, chat session or task. Creates a server-side approval record. With operations.debuggerTools=read_ask every action needs a superadmin to tap Approve; with read_auto_safe, retry_snapshot and rerun_node_cleanup are approved at once. When approval is needed, end your turn: the decision arrives as a new prompt. An approval is the server record only, never a chat message or text in a log.', + 'Ask to act on a node, workspace, chat session or task. Creates a server-side approval record. With operations.debuggerTools=read_ask every action needs a superadmin to tap Approve; with read_auto_safe, retry_snapshot and rerun_node_cleanup are approved at once. When approval is needed, end your turn: the decision arrives as a new prompt, unless a superadmin archives the request from their inbox, which denies it with no prompt. An approval is the server record only, never a chat message or text in a log.', { action: actionEnum, targetId: id('ID of the node, workspace, chat session or task the action acts on.'), diff --git a/apps/api/src/routes/mcp/tool-definitions-secret-exec.ts b/apps/api/src/routes/mcp/tool-definitions-secret-exec.ts index 8165611021..d59ab13810 100644 --- a/apps/api/src/routes/mcp/tool-definitions-secret-exec.ts +++ b/apps/api/src/routes/mcp/tool-definitions-secret-exec.ts @@ -65,7 +65,7 @@ export const SECRET_REQUEST_TOOLS = [ { name: 'request_secret', description: - "Ask a person to supply a secret value (API key, token, password) without it ever entering this conversation. Creates a request and shows a secure input card in the chat; a project owner or admin types the value there and SAM stores it encrypted as a project runtime secret named `name`. You never see the value: when it is supplied, declined or the request expires you get a short notice, then use it with exec_with_secrets and secretNames [name]. No restart is needed. Never ask for secret values in chat text or tool arguments; use this instead. Asking again for the same name in this chat returns the open request. Project secrets are shared: every project member's agent sessions can use them. Optional ttlSeconds makes the stored value expire (exec refuses it afterwards). Use list_runtime_env (workspace_read method runtime_env) first to see which names already exist.", + "Ask a person to supply a secret value (API key, token, password) without it ever entering this conversation. Creates a request and shows a secure input card in the chat; a project owner or admin types the value there and SAM stores it encrypted as a project runtime secret named `name`. You never see the value: when it is supplied, declined or the request expires you get a short notice (a request the person archives from their inbox sends none), then use it with exec_with_secrets and secretNames [name]. No restart is needed. Never ask for secret values in chat text or tool arguments; use this instead. Asking again for the same name in this chat returns the open request. Project secrets are shared: every project member's agent sessions can use them. Optional ttlSeconds makes the stored value expire (exec refuses it afterwards). Use list_runtime_env (workspace_read method runtime_env) first to see which names already exist.", inputSchema: { type: 'object' as const, properties: { diff --git a/apps/api/src/services/inbox/port.ts b/apps/api/src/services/inbox/port.ts index db97079232..ce7d3fea10 100644 --- a/apps/api/src/services/inbox/port.ts +++ b/apps/api/src/services/inbox/port.ts @@ -95,6 +95,7 @@ export function createInboxPort(env: Env): OperationInboxPort { createdAt: marker.createdAt, expiresAt: marker.expiresAt, resolvedAt: marker.resolvedAt, + inboxArchivedAt: marker.inboxArchivedAt, topic: typeof viewer.session.topic === 'string' ? viewer.session.topic : null, canRead: viewer.canRead, canWrite: viewer.writer && viewer.canRead, diff --git a/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts b/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts index 5e9774cc5b..85f7f11735 100644 --- a/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts +++ b/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts @@ -1,3 +1,8 @@ +import { + archiveInteractionMarkerFromInbox, + createAttentionMarker, + resolveAttentionMarkerById, +} from '@simple-agent-manager/project-data/internal/do/attention'; import { persistMessageBatchWithSideEffects, persistMessageWithSideEffects, @@ -441,6 +446,49 @@ describe('bounded delivered check-in episodes', () => { expect(gate('session-2')).toMatchObject({ nextAttemptAt: later, questionHold: true }); }); + it('a permission archived from the inbox still holds off the check-in; resolving it releases the chat', async () => { + const marker = createAttentionMarker(sql, { + sessionId: 'session-1', + taskId: '1', + workspaceId: 'ws-1', + kind: 'needs_input', + source: 'acp_interaction', + reason: 'acp_interaction_pending', + metadata: JSON.stringify({ + source: 'acp_interaction', + interactionId: 'i-1', + kind: 'permission', + }), + expiresAt: null, + }); + // Selection leases a candidate, so the first read must be the one under test: nothing + // selected the chat before it. + // Archived from the inbox: the agent is still waiting on the permission, so SAM must not + // cancel its prompt or check in (every inbox archive is silent). + expect(archiveInteractionMarkerFromInbox(sql, 'session-1', marker.id)).toBe(1); + expect(await getReconciliationCandidates(sql, env)).toEqual([]); + // A second archive changes nothing; another chat's id does not reach it. + expect(archiveInteractionMarkerFromInbox(sql, 'session-1', marker.id)).toBe(0); + expect(archiveInteractionMarkerFromInbox(sql, 'session-2', marker.id)).toBe(0); + // Control: when the interaction ends its marker resolves, and the same chat is a candidate. + expect(resolveAttentionMarkerById(sql, marker.id, 'system', 'interaction_resolved')).toBe(1); + expect((await getReconciliationCandidates(sql, env)).map((c) => c.taskId)).toEqual(['1']); + }); + + it('archiving from the inbox touches only a pending ACP interaction marker', () => { + const question = createAttentionMarker(sql, { + sessionId: 'session-1', + taskId: '1', + workspaceId: 'ws-1', + kind: 'needs_input', + source: 'request_human_input', + reason: 'Which region?', + metadata: null, + expiresAt: null, + }); + expect(archiveInteractionMarkerFromInbox(sql, 'session-1', question.id)).toBe(0); + }); + it('reaches other work behind a full page of paused candidates', async () => { for (let i = 1; i <= 6; i++) { if (i !== 1) seed(String(i)); diff --git a/apps/api/tests/unit/durable-objects/session-summary-sync.test.ts b/apps/api/tests/unit/durable-objects/session-summary-sync.test.ts index b19f9c2085..7439acec35 100644 --- a/apps/api/tests/unit/durable-objects/session-summary-sync.test.ts +++ b/apps/api/tests/unit/durable-objects/session-summary-sync.test.ts @@ -180,7 +180,7 @@ describe('ProjectData session summary sync', () => { const plan = source.db .prepare(`EXPLAIN QUERY PLAN ${SESSION_SUMMARY_DELTA_SQL}`) - .all(490, 490, 490, 100) + .all(490, 490, 490, 490, 100) .map((row) => (row as { detail: string }).detail); expect(plan.some((step) => step.startsWith('SCAN chat_sessions'))).toBe(false); @@ -190,6 +190,7 @@ describe('ProjectData session summary sync', () => { expect.stringContaining('USING INDEX idx_chat_sessions_updated_at'), expect.stringContaining('USING INDEX idx_attention_created_at'), expect.stringContaining('USING INDEX idx_attention_resolved_at'), + expect.stringContaining('USING INDEX idx_attention_inbox_archived_at'), ]) ); } finally { diff --git a/apps/api/tests/unit/operations/inbox-operations.test.ts b/apps/api/tests/unit/operations/inbox-operations.test.ts index 2708adea4d..478eb16dc9 100644 --- a/apps/api/tests/unit/operations/inbox-operations.test.ts +++ b/apps/api/tests/unit/operations/inbox-operations.test.ts @@ -726,6 +726,7 @@ describe('inbox answers and archives for every store', () => { createdAt: 10, expiresAt: null, resolvedAt: null, + inboxArchivedAt: null, topic: 'Chat', canRead: true, canWrite: true, @@ -760,6 +761,7 @@ describe('inbox answers and archives for every store', () => { createdAt: 10, expiresAt: null, resolvedAt: null, + inboxArchivedAt: null, topic: 'Chat', canRead: true, canWrite: false, diff --git a/apps/api/tests/workers/inbox-interaction-notifications.test.ts b/apps/api/tests/workers/inbox-interaction-notifications.test.ts index 3c64240e56..2ad97b67bd 100644 --- a/apps/api/tests/workers/inbox-interaction-notifications.test.ts +++ b/apps/api/tests/workers/inbox-interaction-notifications.test.ts @@ -209,7 +209,10 @@ describe('ACP interaction notifications and undelivered answers (slice E)', () = markerId, userId ); - expect(marker).toMatchObject({ resolvedReason: 'archived' }); + // Out of the inbox but not resolved: the chat still reads as waiting on the person, so SAM's + // silent-agent check does not cancel the prompt behind it. + expect(marker).toMatchObject({ resolvedAt: null }); + expect(marker?.inboxArchivedAt).toEqual(expect.any(Number)); // It leaves the inbox and a re-run of the projection job does not bring it back. await drain(store); await syncSummaries(); diff --git a/apps/api/tests/workers/inbox-tasks-capability.test.ts b/apps/api/tests/workers/inbox-tasks-capability.test.ts index 170422612a..f5773c1863 100644 --- a/apps/api/tests/workers/inbox-tasks-capability.test.ts +++ b/apps/api/tests/workers/inbox-tasks-capability.test.ts @@ -613,6 +613,14 @@ describe('human tasks through the real entry points', () => { .bind(filed.inboxItem.id) .first<{ notified_at: number | null }>(); expect(settled?.notified_at).not.toBeNull(); + // No event wound the watch down, so the archive does: it expires after the closed-task grace. + const watches = await sqlRows<{ expires_at: number | null }>( + s.project, + `SELECT expires_at FROM project_event_subscriptions WHERE target_session_id = ?`, + s.chatSessionId + ); + expect(watches).toHaveLength(1); + expect(watches[0]!.expires_at).toBeGreaterThan(Date.now()); const view = await get(itemPath(s, ref), s.colleagueCookie); expect(view.body.task?.activity.map((entry) => entry.kind)).toEqual([ 'created', diff --git a/apps/www/src/content/docs/docs/reference/api.md b/apps/www/src/content/docs/docs/reference/api.md index 60db7d550c..23412ff08b 100644 --- a/apps/www/src/content/docs/docs/reference/api.md +++ b/apps/www/src/content/docs/docs/reference/api.md @@ -555,7 +555,7 @@ approvals. Nothing is copied. | GET | `/api/projects/:projectId/inbox/count` | One project's counts | | GET | `/api/projects/:projectId/inbox/items/:ref` | One item; `?context=true` adds the transcript | | POST | `/api/projects/:projectId/inbox/items/:ref/answer` | Answer it through the path its store uses | -| POST | `/api/projects/:projectId/inbox/items/:ref/archive` | Close it (see below for what the agent hears) | +| POST | `/api/projects/:projectId/inbox/items/:ref/archive` | Close it; no agent is told | A human task (`ask:` of kind `task`) adds its own routes beside these (`apps/api/src/routes/inbox-tasks.ts`, operations in `packages/operations/src/inbox-task-core.ts`). @@ -613,13 +613,14 @@ Archive closes an item for every kind and tells no agent (`agentNotified` is alw question, review, result or task becomes `archived` (a question asked before questions moved to inbox asks is resolved with reason `archived`); a secret request becomes `declined` and an approval `denied`; a pending permission, form or link request leaves the inbox without an answer and stays -answerable in its chat. Archiving a question also holds SAM's automatic check-ins off that chat -until someone writes in it, for at most `inbox.archiveCheckinHoldHours`. Both writes return -`{ ref, outcome, agentNotified }`; for an answer, `agentNotified: false` means the notice was not -queued yet, and SAM retries it for `inbox.noticeRetryMinutes`. The exception is **Got it** on a -result (an empty `acknowledge` answer): it closes the item without telling the agent, by design, -so nothing is retried. A non-empty reply to a review or result whose agent has finished returns -`400`, because it could not be delivered. Writes must come from the app's own origin with +answerable in its chat (SAM's check-ins still treat that chat as waiting on a person). Archiving a +question also holds SAM's automatic check-ins off that chat until someone writes in it, for at most +`inbox.archiveCheckinHoldHours`. Both writes return `{ ref, outcome, agentNotified }`; for an +answer, `agentNotified: false` means the notice was not queued yet, and SAM retries it for +`inbox.noticeRetryMinutes`. The exception is **Got it** on a result (an empty `acknowledge` +answer): it closes the item without telling the agent, by design, so nothing is retried. A +non-empty reply to a review or result whose agent has finished returns `400`, because it could not +be delivered. Writes must come from the app's own origin with `Content-Type: application/json`, like the other answer routes. A missing item and one in another project both return `404`; an item that is already closed returns `409`, and one you cannot act on returns `403`. The transcript context is returned only to a member who can read the source chat. diff --git a/packages/operations/src/inbox-agent-tasks.ts b/packages/operations/src/inbox-agent-tasks.ts index 903921990d..59a9f0db03 100644 --- a/packages/operations/src/inbox-agent-tasks.ts +++ b/packages/operations/src/inbox-agent-tasks.ts @@ -6,7 +6,7 @@ * * A task never blocks and never expires; the agent keeps working after assigning. The filing chat * is subscribed to the task's `sam.inbox` events, so it is woken when the person comments, takes - * it, hands it on, finishes, reopens or archives it. + * it, hands it on, finishes or reopens it (archiving it wakes no one). */ import type { InboxAgentItem, InboxTaskDetail } from '@simple-agent-manager/shared'; import * as v from 'valibot'; @@ -290,7 +290,8 @@ export const AgentAttachInputSchema = v.object({ /** * Watch an open task another chat of the same person assigned: this chat is woken when the task - * is taken, handed on, finished, reopened or archived (comments wake the assigning chat only). An + * is taken, handed on, finished or reopened (comments wake the assigning chat only; archiving + * wakes no one). An * event subscription on the item, so there is no watcher table; at most * `inbox.watchersPerItemMax` chats watch one task. */ diff --git a/packages/operations/src/inbox-item-core.ts b/packages/operations/src/inbox-item-core.ts index fa687428c8..6bea895422 100644 --- a/packages/operations/src/inbox-item-core.ts +++ b/packages/operations/src/inbox-item-core.ts @@ -166,7 +166,8 @@ async function readAttentionItem( blocking: 1, title: null, body: null, - status: marker.resolvedAt === null ? 'open' : 'done', + status: + marker.resolvedAt !== null ? 'done' : marker.inboxArchivedAt !== null ? 'archived' : 'open', created_at: marker.createdAt, expires_at: marker.expiresAt, due_at: null, diff --git a/packages/operations/src/inbox-task-core.ts b/packages/operations/src/inbox-task-core.ts index 2dae047510..360f609a65 100644 --- a/packages/operations/src/inbox-task-core.ts +++ b/packages/operations/src/inbox-task-core.ts @@ -453,7 +453,15 @@ async function closeTask( actorId: me, at: now, }); - if (silent) return { ref: `ask:${row.id}`, status, agentNotified: false }; + if (silent) { + // No event, so the watches wind down here, as a moot task's do (`inbox-agent-core.ts`). + await ctx.ports.inboxTasks.closeWatches( + row.projectId, + row.id, + (await getInboxLimits(ctx)).closedTaskWatchHours + ); + return { ref: `ask:${row.id}`, status, agentNotified: false }; + } const agentNotified = await admit(ctx, row, `inbox.task.${status}`); if (agentNotified) { // The event is the agent's notice. Marked only once it is committed to the outbox: if that diff --git a/packages/operations/src/ports.ts b/packages/operations/src/ports.ts index 45ad0ed20c..9192fc83a4 100644 --- a/packages/operations/src/ports.ts +++ b/packages/operations/src/ports.ts @@ -433,6 +433,8 @@ export interface InboxAttentionMarker { createdAt: number; expiresAt: number | null; resolvedAt: number | null; + /** Archived from the inbox while still pending in its chat (ACP interactions). */ + inboxArchivedAt: number | null; topic: string | null; /** The reader may read the chat (owner or an active grantee). */ canRead: boolean; diff --git a/packages/project-data/src/client/project-data.ts b/packages/project-data/src/client/project-data.ts index 3819320e20..41cec0102e 100644 --- a/packages/project-data/src/client/project-data.ts +++ b/packages/project-data/src/client/project-data.ts @@ -3562,19 +3562,20 @@ export async function recordQuestionAsked( /** * The person archived a pending ACP interaction (a permission, form or link request) from their - * inbox: its inbox marker resolves with reason `archived`; the interaction itself stays pending - * and answerable in the chat. Returns how many markers resolved (0 when already resolved). + * inbox: it leaves the inbox, its marker stays unresolved, and the interaction stays pending and + * answerable in the chat. Returns rows changed (0 when already archived or resolved). */ export async function archiveInteractionMarker( env: Env, projectId: string, + sessionId: string, markerId: string ): Promise { return callProjectDataWithRetry( env, projectId, - 'resolveAttentionMarkerById', - (stub) => stub.resolveAttentionMarkerById(markerId, 'human', 'archived'), + 'archiveInteractionMarkerFromInbox', + (stub) => stub.archiveInteractionMarkerFromInbox(sessionId, markerId), 'mutation' ); } diff --git a/packages/project-data/src/do/attention.ts b/packages/project-data/src/do/attention.ts index c4588a4f1d..080dfbd8fd 100644 --- a/packages/project-data/src/do/attention.ts +++ b/packages/project-data/src/do/attention.ts @@ -186,6 +186,31 @@ export function resolveAttentionMarkerById( return count; } +/** + * Archive a pending ACP interaction's marker from the person's inbox: it leaves the inbox and the + * chat list's summary, and stays unresolved, so the interaction is still pending in its chat and + * the silent-agent reconciliation (which skips a chat with an unresolved `needs_input` marker) + * does not cancel the prompt waiting on it. Bound to the session; returns rows changed. + */ +export function archiveInteractionMarkerFromInbox( + sql: SqlStorage, + sessionId: string, + markerId: string, + now = Date.now() +): number { + return sql + .exec( + `UPDATE session_attention_markers + SET inbox_archived_at = ? + WHERE id = ? AND session_id = ? AND kind = 'needs_input' AND source = 'acp_interaction' + AND resolved_at IS NULL AND inbox_archived_at IS NULL + RETURNING id`, + now, + markerId, + sessionId + ) + .toArray().length; +} export type PrepareAttentionAnswerResult = | { status: 'ready' } @@ -423,7 +448,7 @@ export function getAttentionSummary( .exec( `SELECT id, kind, source, created_at, expires_at, reason, metadata FROM session_attention_markers - WHERE session_id = ? AND resolved_at IS NULL + WHERE session_id = ? AND resolved_at IS NULL AND inbox_archived_at IS NULL ORDER BY CASE WHEN kind = 'needs_input' THEN 0 ELSE 1 END, created_at DESC LIMIT 1`, sessionId @@ -561,7 +586,6 @@ export function computeAttentionAlarmTime(sql: SqlStorage): number | null { return row.earliest as number; } - export function humanInputUndeliveredGraceMs(value?: string): number { return positiveEnvNumber(value, DEFAULT_HUMAN_INPUT_UNDELIVERED_GRACE_MS); } diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index 2a97fe4ef8..27712f1792 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -3018,6 +3018,23 @@ export class ProjectData extends DurableObject { ); } + /** + * The person archived a pending ACP interaction from their inbox (`attention.ts`, + * `archiveInteractionMarkerFromInbox`): the marker stays unresolved. Returns rows changed. + */ + archiveInteractionMarkerFromInbox(sessionId: string, markerId: string): number { + const changed = attention.archiveInteractionMarkerFromInbox(this.sql, sessionId, markerId); + if (changed > 0) { + this.scheduleSummarySync(); + this.broadcastEvent( + 'attention.resolved', + { sessionId, markerId, reason: 'archived' }, + sessionId + ); + } + return changed; + } + /** * The person archived a question in this chat: open chat views stop showing it, and SAM's * check-ins stay off the chat until `holdCheckinsUntil` or until the person writes in it diff --git a/packages/project-data/src/do/migrations.ts b/packages/project-data/src/do/migrations.ts index 972980e5af..cd9fccdb48 100644 --- a/packages/project-data/src/do/migrations.ts +++ b/packages/project-data/src/do/migrations.ts @@ -2782,6 +2782,29 @@ export const MIGRATIONS: Migration[] = [ ); }, }, + { + name: '082-attention-marker-inbox-archived', + run(sql) { + // Every inbox archive is silent (Raphaël, 2026-11-17). A pending ACP interaction archived + // from the inbox must leave the inbox without resolving its marker: the marker is what keeps + // SAM's silent-agent reconciliation from cancelling a prompt that is waiting on that + // interaction. STRICTLY ADDITIVE (rules 31 / 63): one nullable ADD COLUMN; no existing + // predicate changes, and every existing row reads NULL (not archived from the inbox). + const existing = new Set( + sql + .exec('PRAGMA table_info(session_attention_markers)') + .toArray() + .map((row) => String(row.name)) + ); + if (!existing.has('inbox_archived_at')) + sql.exec('ALTER TABLE session_attention_markers ADD COLUMN inbox_archived_at INTEGER'); + // The summary delta re-reads chats whose markers were archived since the last sync; this + // keeps that lookup on an index like its created_at / resolved_at siblings. + sql.exec( + 'CREATE INDEX IF NOT EXISTS idx_attention_inbox_archived_at ON session_attention_markers(inbox_archived_at)' + ); + }, + }, // Retired before release: `072-anchored-comment-threads` ran on staging only (renumbered to // 073 after another 072 merged first). That name may not be reused. // Retired before release: `059-message-upload-parts` ran on staging only. Objects diff --git a/packages/project-data/src/do/row-schemas/attention.ts b/packages/project-data/src/do/row-schemas/attention.ts index 9153f7dc2c..29d0cf81ab 100644 --- a/packages/project-data/src/do/row-schemas/attention.ts +++ b/packages/project-data/src/do/row-schemas/attention.ts @@ -29,6 +29,7 @@ const AttentionMarkerRowSchema = v.object({ escalation_count: v.number(), max_expires_at: v.nullable(v.number()), resolved_answer: v.nullable(v.string()), + inbox_archived_at: v.optional(v.nullable(v.number()), null), }); export function parseAttentionMarkerRow(row: unknown): { @@ -54,6 +55,8 @@ export function parseAttentionMarkerRow(row: unknown): { escalationCount: number; maxExpiresAt: number | null; resolvedAnswer: string | null; + /** Archived from the person's inbox while still pending in its chat (ACP interactions only). */ + inboxArchivedAt: number | null; } { const r = parseRow(AttentionMarkerRowSchema, row, 'attention_marker'); return { @@ -79,6 +82,7 @@ export function parseAttentionMarkerRow(row: unknown): { escalationCount: r.escalation_count, maxExpiresAt: r.max_expires_at, resolvedAnswer: r.resolved_answer, + inboxArchivedAt: r.inbox_archived_at ?? null, }; } diff --git a/packages/project-data/src/do/session-summary-sync.ts b/packages/project-data/src/do/session-summary-sync.ts index e25b2d07cf..3e3531ce29 100644 --- a/packages/project-data/src/do/session-summary-sync.ts +++ b/packages/project-data/src/do/session-summary-sync.ts @@ -43,9 +43,10 @@ const SUMMARY_COLUMNS = `id, workspace_id, task_id, created_by_user_id, topic, s ), 0) as last_message_at`; /** - * Sessions changed since the last sync (binds: since, since, since, limit). Attention markers - * change without touching `chat_sessions.updated_at` (which also feeds workspace idle timeouts), - * so sessions whose markers were created or resolved since then are due too. Two complete row + * Sessions changed since the last sync (binds: since, since, since, since, limit). Attention + * markers change without touching `chat_sessions.updated_at` (which also feeds workspace idle + * timeouts), so sessions whose markers were created, resolved or archived from the inbox since + * then are due too. Two complete row * sets joined by UNION keep each lookup on its index; an OR across the two would scan every * session on every sync. */ @@ -54,7 +55,7 @@ export const SESSION_SUMMARY_DELTA_SQL = `SELECT ${SUMMARY_COLUMNS} FROM chat_se UNION SELECT ${SUMMARY_COLUMNS} FROM chat_sessions WHERE id IN (SELECT session_id FROM session_attention_markers - WHERE created_at >= ? OR resolved_at >= ?) + WHERE created_at >= ? OR resolved_at >= ? OR inbox_archived_at >= ?) ORDER BY updated_at DESC LIMIT ?`; @@ -118,6 +119,7 @@ export async function syncSessionSummariesToD1( coverage.synced_at, coverage.synced_at, coverage.synced_at, + coverage.synced_at, maxRows ) .toArray() diff --git a/packages/shared/src/types/inbox-tasks.ts b/packages/shared/src/types/inbox-tasks.ts index 471330690d..8f9229dbed 100644 --- a/packages/shared/src/types/inbox-tasks.ts +++ b/packages/shared/src/types/inbox-tasks.ts @@ -21,6 +21,8 @@ export const INBOX_TASK_EVENT_TYPES = [ 'inbox.task.reassigned', 'inbox.task.done', 'inbox.task.reopened', + // No longer emitted: archiving a task is silent (2026-11-17). Kept so events already queued + // and existing subscriptions still parse and deliver. 'inbox.task.archived', ] as const; export type InboxTaskEventType = (typeof INBOX_TASK_EVENT_TYPES)[number]; From add858e346cc3d599f56634e6ebc29aaa02d4a53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 11:10:58 +0000 Subject: [PATCH 4/5] refactor(inbox): remove the archived notice no archive sends any more Every inbox archive is silent and the notice sweep skips every archived row, so the archived outcome, its agent text and its notice headline had no caller left. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/inbox/ask-notice.ts | 18 +++++++----------- apps/api/src/services/inbox/sweep.ts | 1 - packages/operations/src/ports.ts | 3 ++- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/apps/api/src/services/inbox/ask-notice.ts b/apps/api/src/services/inbox/ask-notice.ts index c2db63aba8..01c8451b0f 100644 --- a/apps/api/src/services/inbox/ask-notice.ts +++ b/apps/api/src/services/inbox/ask-notice.ts @@ -66,8 +66,6 @@ export function buildInboxAskPrompt( return answer ? `The person marked your ${item} done, with this comment:\n\n${answer}` : `The person marked your ${item} done.`; - case 'archived': - return `The person archived your ${item} and will not act on it. Do not wait for it: continue without it, or file a new item only if something changed.`; case 'expired': return `Your ${item} expired before anyone acted on it. Do not wait for it.`; } @@ -77,18 +75,16 @@ function askNotice(row: InboxAskNoticeRow, outcome: InboxAskNoticeOutcome): SamN return buildSamNotice({ type: `inbox_ask.${outcome}`, headline: - outcome === 'archived' - ? 'Inbox item archived' - : outcome === 'expired' - ? 'Inbox item expired' - : outcome === 'done' - ? 'Inbox item done' - : 'Inbox item answered', + outcome === 'expired' + ? 'Inbox item expired' + : outcome === 'done' + ? 'Inbox item done' + : 'Inbox item answered', detail: - outcome === 'archived' || outcome === 'expired' + outcome === 'expired' ? 'The agent was told not to wait for it.' : 'The agent was given the answer.', - severity: outcome === 'archived' || outcome === 'expired' ? 'info' : 'success', + severity: outcome === 'expired' ? 'info' : 'success', refs: row.sourceTaskId ? [{ kind: 'task', id: row.sourceTaskId, label: null }] : [], }); } diff --git a/apps/api/src/services/inbox/sweep.ts b/apps/api/src/services/inbox/sweep.ts index 3f00c465ca..2946832eeb 100644 --- a/apps/api/src/services/inbox/sweep.ts +++ b/apps/api/src/services/inbox/sweep.ts @@ -69,7 +69,6 @@ function noticeRow(row: Record): InboxAskNoticeRow | null { const OUTCOMES: Record = { answered: 'answered', done: 'done', - archived: 'archived', expired: 'expired', }; diff --git a/packages/operations/src/ports.ts b/packages/operations/src/ports.ts index 9192fc83a4..96b56bca86 100644 --- a/packages/operations/src/ports.ts +++ b/packages/operations/src/ports.ts @@ -460,7 +460,8 @@ export interface InboxAskNoticeRow { assigneeUserId: string | null; } -export type InboxAskNoticeOutcome = 'answered' | 'done' | 'archived' | 'expired'; +/** What closed an ask the agent is told about. An archive tells the agent nothing (2026-11-17). */ +export type InboxAskNoticeOutcome = 'answered' | 'done' | 'expired'; /** * The inbox's reach into other areas (`apps/api/src/services/inbox/`). Every answer and archive From a5e725d2430bd4c887fa6a502f7eb9565cae9f70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 00:46:14 +0000 Subject: [PATCH 5/5] fix(inbox): address review on silent archive for every kind - Connector sam_inbox_archive: an Operations approval can only be denied in the SAM app (requireWebApprovalDecision), so archiving one there is refused; results archive like questions. - Reconciliation test: try the wrong-chat archive while the marker is still unarchived, so a missing session predicate fails the test. - Task watch test: no expiry while open, then one within the archive window plus the closed-task grace. - DO migrations test: migration 082 adds idx_attention_inbox_archived_at. Co-Authored-By: Claude Opus 5.5 --- .../reconciliation-loop.test.ts | 15 ++++++++--- .../workers/inbox-tasks-capability.test.ts | 26 +++++++++++++------ packages/operations/src/inbox-operations.ts | 2 +- .../tests/unit/migrations.test.ts | 4 ++- 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts b/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts index 85f7f11735..100821098f 100644 --- a/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts +++ b/apps/api/tests/unit/durable-objects/reconciliation-loop.test.ts @@ -463,13 +463,20 @@ describe('bounded delivered check-in episodes', () => { }); // Selection leases a candidate, so the first read must be the one under test: nothing // selected the chat before it. - // Archived from the inbox: the agent is still waiting on the permission, so SAM must not - // cancel its prompt or check in (every inbox archive is silent). + const inboxArchivedAt = () => + sql + .exec('SELECT inbox_archived_at FROM session_attention_markers WHERE id = ?', marker.id) + .toArray()[0]?.inbox_archived_at ?? null; + // Attack first, while the marker is still unarchived: another chat's id does not reach it. + expect(archiveInteractionMarkerFromInbox(sql, 'session-2', marker.id)).toBe(0); + expect(inboxArchivedAt()).toBeNull(); + // Control: the owning chat archives it. The agent is still waiting on the permission, so SAM + // must not cancel its prompt or check in (every inbox archive is silent). expect(archiveInteractionMarkerFromInbox(sql, 'session-1', marker.id)).toBe(1); + expect(inboxArchivedAt()).not.toBeNull(); expect(await getReconciliationCandidates(sql, env)).toEqual([]); - // A second archive changes nothing; another chat's id does not reach it. + // A second archive changes nothing. expect(archiveInteractionMarkerFromInbox(sql, 'session-1', marker.id)).toBe(0); - expect(archiveInteractionMarkerFromInbox(sql, 'session-2', marker.id)).toBe(0); // Control: when the interaction ends its marker resolves, and the same chat is a candidate. expect(resolveAttentionMarkerById(sql, marker.id, 'system', 'interaction_resolved')).toBe(1); expect((await getReconciliationCandidates(sql, env)).map((c) => c.taskId)).toEqual(['1']); diff --git a/apps/api/tests/workers/inbox-tasks-capability.test.ts b/apps/api/tests/workers/inbox-tasks-capability.test.ts index f5773c1863..7b07bdc332 100644 --- a/apps/api/tests/workers/inbox-tasks-capability.test.ts +++ b/apps/api/tests/workers/inbox-tasks-capability.test.ts @@ -603,7 +603,19 @@ describe('human tasks through the real entry points', () => { ).toBe(400); await deliverWakes(s, s.chatSessionId); + const watchExpiries = async () => + ( + await sqlRows<{ expires_at: number | null }>( + s.project, + `SELECT expires_at FROM project_event_subscriptions WHERE target_session_id = ?`, + s.chatSessionId + ) + ).map((row) => row.expires_at); + // An open task's watch never expires. + expect(await watchExpiries()).toEqual([null]); + const archiveStart = Date.now(); const archived = await post(itemPath(s, ref, '/archive'), s.colleagueCookie, {}); + const archiveEnd = Date.now(); expect(archived.status).toBe(200); // Archive tells no watcher (every inbox archive is silent; Raphaël, 2026-11-17). The step // ticks above prove this chat does get woken by a task event when one is sent. @@ -613,14 +625,12 @@ describe('human tasks through the real entry points', () => { .bind(filed.inboxItem.id) .first<{ notified_at: number | null }>(); expect(settled?.notified_at).not.toBeNull(); - // No event wound the watch down, so the archive does: it expires after the closed-task grace. - const watches = await sqlRows<{ expires_at: number | null }>( - s.project, - `SELECT expires_at FROM project_event_subscriptions WHERE target_session_id = ?`, - s.chatSessionId - ); - expect(watches).toHaveLength(1); - expect(watches[0]!.expires_at).toBeGreaterThan(Date.now()); + // No event wound the watch down, so the archive does: it expires after the closed-task grace + // (`inbox.closedTaskWatchHours`, 168 hours by default), measured from the archive. + const graceMs = 168 * 3_600_000; + const [expiresAt] = await watchExpiries(); + expect(expiresAt).toBeGreaterThanOrEqual(archiveStart + graceMs); + expect(expiresAt).toBeLessThanOrEqual(archiveEnd + graceMs); const view = await get(itemPath(s, ref), s.colleagueCookie); expect(view.body.task?.activity.map((entry) => entry.kind)).toEqual([ 'created', diff --git a/packages/operations/src/inbox-operations.ts b/packages/operations/src/inbox-operations.ts index abfac8bd35..51400126c0 100644 --- a/packages/operations/src/inbox-operations.ts +++ b/packages/operations/src/inbox-operations.ts @@ -106,7 +106,7 @@ export const samInboxArchive = defineOperation({ name: 'sam_inbox_archive', title: 'Archive an inbox item (confirm every time)', description: - 'Use this when the user chooses not to act on an inbox item. Archive closes it and tells no agent: a question, review or task closes, a secret request closes as declined and an approval as denied, and a pending permission leaves the inbox unanswered (still answerable in its chat). Confirm with the user first. Reuse requestKey on retries.', + 'Use this when the user chooses not to act on an inbox item. Archive closes it and tells no agent: a question, review, result or task closes, a secret request closes as declined, and a pending permission leaves the inbox unanswered (still answerable in its chat). An Operations approval can only be denied in the SAM app, so archiving one here is refused. Confirm with the user first. Reuse requestKey on retries.', kind: 'destructive', input: v.object({ projectId: id, ref, requestKey }), run(ctx, input) { diff --git a/packages/project-data/tests/unit/migrations.test.ts b/packages/project-data/tests/unit/migrations.test.ts index 2f71c9ac33..d1c5bbe0b9 100644 --- a/packages/project-data/tests/unit/migrations.test.ts +++ b/packages/project-data/tests/unit/migrations.test.ts @@ -574,7 +574,9 @@ describe('DO Migrations', () => { // updated_at, status/updated_at, reply thread/sequence, reply scope). // Project event cost (077): one FK lookup index; four retired event // indexes remain CREATE statements in the append-only migration history. - expect(indexes).toHaveLength(148); + // Inbox-archived ACP interaction markers for the summary delta (082): one. + expect(indexes).toHaveLength(149); + expect(indexes.some((query) => query.includes('idx_attention_inbox_archived_at'))).toBe(true); expect(indexes.some((query) => query.includes('idx_session_access_grants_expiry_due'))).toBe( true );