From 5347c01de5bc00f4933a975b28d280ea9001339b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:50:44 -0600 Subject: [PATCH] fix(antigravity): give the follow-up after a swarm its result, and say each thing once in the thread (#22893) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A task thread shows an agent's runs, and each new run starts from the task's saved context > - A second hands-on check of Google Antigravity `/swarm` runs (after #22886) still found gaps > - The first ordinary follow-up after a swarm was slow: it spent minutes searching the instance's run logs to learn what the swarm did > - The thread also showed each file twice, lost the "Swarm" note after a reload, and read "Swarm Swarm started…" > - This pull request gives the next run the swarm's result in its opening context and removes the prompt's pointer to run records, and it fixes the four thread problems > - The benefit is a faster follow-up after a swarm and a thread that says each thing once ## Linked Issues or Issue Description Refs #22886 **What happened?** 1. After a finished `/swarm`, the ordinary follow-up "append three to v1.txt" took 4 min 6 s (an earlier one took 5.5 min). The agent read the server's raw run log of the swarm run with about 20 shell commands, searched the instance folder, and listed processes. Other follow-ups took 41 s and 105 s. 2. Each file showed twice: the run's file card, and a second card under the final reply (from the reply's "Download: v1.txt" link). This also happened on the ordinary follow-up. 3. The "Swarm" note on the user's message showed while live, but not after a page reload. 4. Swarm activity rows read "Swarm Swarm started in the task folder…", with the word twice. **Expected behavior** 1. The follow-up starts with what the swarm did, so it has no reason to search for it. 2. Each file shows once per run, as the run's file card. 3. The "Swarm" note shows after a reload. 4. A swarm row reads its sentence once. **Steps to reproduce** 1. Send `/swarm Create v1.txt containing "one" and v2.txt containing "two", one helper per file, then verify both.` to a Google Antigravity agent. 2. When it finishes, look at the files and the activity rows, then reload the page. 3. Send the ordinary follow-up `append three to v1.txt` and time it. 4. Put another task in Plan mode and send `/swarm do something`. ## What Changed - Follow-up context (cause of item 1). A swarm runs in the Antigravity CLI, and an ordinary turn runs on the registry route. The ordinary route cannot reopen the swarm's conversation, so the Runner refuses the saved session and the server starts a fresh one. That fresh session gets the same wake prompt as any other turn. Before this change, its only record of the swarm was the task continuation summary, and that summary listed no files ("No file or route paths were detected"; the path detector only knows repository folders such as `server/`). It also gave three run ids and said "Detailed shell/tool commands remain in the run log and transcript." The agent followed that line: its first searches matched the swarm's run id, and an earlier follow-up searched for `transcript*.jsonl` files. An ordinary follow-up after an ordinary turn gets the same prompt, but it resumes its own conversation, so it already knows what it did. - `issue-continuation-summary.ts` (shared by every harness): a new "Files Delivered" section lists, by name, the files the run handed in as deliverables (applied or duplicate receipts), newest first, and keeps earlier runs' names. These names are kept apart from "Files / Routes Touched", because a deliverable's name is not always its path. The run's own checks are listed, read through the shared accepted-result reader. The summary contains no run ids, adapter names or log locations. The "Commands Run" section is removed: it held only the run id and the log pointer. The summary reaches the next turn through the existing mechanism (the wake prompt's "Issue continuation summary" and the continuation evidence). - Server: `GET /issues/:id/recent-comments` and both chat bootstrap routes now add the swarm marker with the same shared rule (`withAntigravitySwarmMarkers`) as the comment list, the single comment and the POST response. A cold task page reads this recent window, so the marker was missing after a reload. - UI: a reply does not show a second card for a file that its own run already shows as a file card. The reply text and its links do not change. A later run's reply that links the same file still shows the file. - UI: a swarm progress row shows its sentence without the "Swarm" label. A failed or stopped row keeps its label and marker. Live and settled rows use the same rule. Not changed, by investigation: - "Check passed cat v1.txt one\nthree" and "verifier check on swarm board #6": the model wrote both strings in its `paperclip_finish` call. The Runner's first record of the result already holds the literal backslash and the board number, so this is model text, not Paperclip's presentation. - The inline "Download: v1.txt" links in the reply are the model's own words, so they stay. - No read-confinement policy is added. The agent finds the instance folder from its working directory, not from the prompt. - A refused send still shows its reason twice (inline under the composer and as a toast). Each attempt to remove the toast missed a send path, which could leave a refusal with no visible reason. A repeated reason is better than a missing one, so this PR does not change the toast. ## Verification - Red/green `server/src/__tests__/issue-continuation-summary.test.ts`: a swarm's accepted result (from a live run, with ids replaced) is built into the summary and rendered into the follow-up's wake prompt. The prompt contains the hand-in summary, `v1.txt` and `v2.txt` under "Files Delivered" (one with a different content reference and a duplicate receipt), and the verifier check. A later run lists its own delivered file first. A full path list still takes the latest run's path first. It contains no run id, "run log", "transcript", attachment path, digest or adapter name. A later run keeps the files listed. This failed before the change. - Red/green `server/src/__tests__/issue-chat-bootstrap-routes.test.ts` (embedded Postgres): for an ordinary task and a conversation, a recorded `/swarm` request carries `nativeCommand: "swarm"` on `GET /comments`, `GET /comments/:id`, `GET /recent-comments`, `GET /issues/:ref/chat-bootstrap` and the batch chat bootstrap. It failed on `recent-comments` before the change. - Red/green `ui/src/components/TaskChatThread.test.tsx`: a reply that links its run's file shows no second card; a later run's reply still shows it. It failed before the change. - Red/green `ui/src/components/task-chat/antigravity-thread.test.tsx`: the live swarm fixture's rows read "Swarm started in the task folder…" (no doubled word), and live rows equal settled rows. - Focused suites: UI `TaskChatThread.test.tsx` and `src/components/task-chat` (925 tests), server bootstrap routes (19 tests) and continuation summary (7 tests) pass. UI and server typechecks pass. - Not proved without a live run: that the next follow-up after a swarm is faster. The tests prove the opening input; the agent's behavior with that input needs a live Antigravity run. ## Risks - The continuation summary wording changes for every harness that runs on a task (every adapter whose finished run refreshes the summary, not only Antigravity): no run ids, no adapter name, no "Commands Run" section, and a new "Files Delivered" section when the run registered deliverables. Nothing in the code parses those lines. Older saved summaries keep their text until the next run refreshes them. - One extra indexed activity-log query for each recent-comments or chat-bootstrap read (the same query the comment list already runs). The bootstrap budget test still passes. - The second-card rule matches only a file whose card belongs to the same run as the reply. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../issue-chat-bootstrap-routes.test.ts | 24 +++++++ .../issue-continuation-summary.test.ts | 65 ++++++++++++++++++- server/src/routes/issues.ts | 5 +- server/src/services/heartbeat-run-summary.ts | 9 ++- .../services/issue-continuation-summary.ts | 54 +++++++++++---- .../native-deliverable-feedback.ts | 5 +- ui/src/components/TaskChatThread.test.tsx | 29 +++++++++ ui/src/components/TaskChatThread.tsx | 6 +- .../task-chat/RunFileCardsContext.ts | 3 + .../components/task-chat/TaskChatBubble.tsx | 11 +++- .../task-chat/TaskChatRunnerActivityGroup.tsx | 10 +-- .../task-chat/antigravity-thread.test.tsx | 24 +++---- .../components/task-chat/image-resources.ts | 9 +++ .../task-chat-activity-presentation.ts | 11 ++++ .../task-chat/task-chat-attachments.ts | 2 +- ui/src/components/task-chat/tool-taxonomy.ts | 11 +++- 16 files changed, 234 insertions(+), 44 deletions(-) create mode 100644 ui/src/components/task-chat/RunFileCardsContext.ts diff --git a/server/src/__tests__/issue-chat-bootstrap-routes.test.ts b/server/src/__tests__/issue-chat-bootstrap-routes.test.ts index 2efe1a2302f..1f0d00a0706 100644 --- a/server/src/__tests__/issue-chat-bootstrap-routes.test.ts +++ b/server/src/__tests__/issue-chat-bootstrap-routes.test.ts @@ -10,6 +10,7 @@ import { issueRoutes } from "../routes/issues.js"; import { activityRoutes } from "../routes/activity.js"; import { agentRoutes } from "../routes/agents.js"; import { errorHandler } from "../middleware/index.js"; +import { recordAntigravitySwarmRequest } from "../services/antigravity-swarm.js"; import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres, type BoardActor } from "./helpers/route-test-harness.js"; describeEmbeddedPostgres("task chat bootstrap", () => { @@ -140,6 +141,29 @@ describeEmbeddedPostgres("task chat bootstrap", () => { expect(res.body.items[0].recentComments).not.toHaveProperty("oldestCommentId"); }); + it("marks a recorded /swarm request on every path that returns comments to the thread", async () => { + const f = await seedCompanyWithBoardAccess(ctx.db, "Swarm marker"); + const server = app(f.actor); + for (const conversation of [false, true]) { + const task = await seedTask(f.companyId, { userId: f.userId, conversation }); + const requested = task.commentIds[6]!; + await recordAntigravitySwarmRequest(ctx.db, { companyId: f.companyId, issueId: task.issueId, commentId: requested, userId: f.userId }); + const marks = (comments: Array<{ id: string; nativeCommand?: string }>) => + comments.filter((comment) => comment.nativeCommand === "swarm").map((comment) => comment.id); + + const list = await request(server).get(`/api/issues/${task.issueId}/comments`).expect(200); + expect(marks(list.body), "comments").toEqual([requested]); + const one = await request(server).get(`/api/issues/${task.issueId}/comments/${requested}`).expect(200); + expect(one.body.nativeCommand, "comment").toBe("swarm"); + const recent = await request(server).get(`/api/issues/${task.issueId}/recent-comments`).expect(200); + expect(marks(recent.body.comments), "recent-comments").toEqual([requested]); + const single = await request(server).get(`/api/issues/${task.issueId}/chat-bootstrap`).expect(200); + expect(marks(single.body.recentComments.comments), "chat-bootstrap").toEqual([requested]); + const batch = await request(server).get(url(f.companyId)).query({ ids: task.issueId }).expect(200); + expect(marks(batch.body.items[0].recentComments.comments), "batch chat-bootstrap").toEqual([requested]); + } + }); + it("follows request order with mixed UUIDs and identifiers, and reads a task named twice once per ref", async () => { const f = await seedCompanyWithBoardAccess(ctx.db, "Order"); const a = await seedTask(f.companyId, { userId: f.userId }); diff --git a/server/src/__tests__/issue-continuation-summary.test.ts b/server/src/__tests__/issue-continuation-summary.test.ts index 5e4815c8c43..0ec94518df7 100644 --- a/server/src/__tests__/issue-continuation-summary.test.ts +++ b/server/src/__tests__/issue-continuation-summary.test.ts @@ -5,6 +5,7 @@ import { continuationSummaryParksExecutor, extractContinuationSummaryNextAction, } from "../services/issue-continuation-summary.js"; +import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils"; describe("issue continuation summaries", () => { it("builds bounded issue-local handoff context with required sections", () => { @@ -50,14 +51,74 @@ describe("issue continuation summaries", () => { expect(body).toContain("## Acceptance Criteria"); expect(body).toContain("- Summary is issue-local"); expect(body).toContain("## Recent Concrete Actions"); - expect(body).toContain("Run `run-1` finished with status `succeeded`"); + expect(body).toContain("The latest run finished with status `succeeded`"); expect(body).toContain("`server/src/services/heartbeat.ts`"); - expect(body).toContain("## Commands Run"); expect(body).toContain("## Blockers / Decisions"); expect(body).toContain("## Next Action"); expect(body.length).toBeLessThanOrEqual(ISSUE_CONTINUATION_SUMMARY_MAX_BODY_CHARS); }); + it("opens the next session after a swarm with what the swarm did, never with where Paperclip keeps its records", () => { + const swarmRunId = "6a1f0c2e-0000-4000-8000-00000000a001"; + const deliverable = (filename: string, attachmentId: string, contentRef = filename, disposition = "applied") => ({ + operationId: "register_deliverable", + input: { title: `${filename} deliverable`, filename, contentRef, contentType: "text/plain", byteSize: 3, sha256: "0".repeat(64) }, + result: { disposition, attachmentId, contentPath: `/api/attachments/${attachmentId}/content` }, + }); + const body = buildContinuationSummaryMarkdown({ + issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", description: "Please wait for the request in a comment.", + status: "done", priority: "medium" }, + run: { + id: swarmRunId, status: "succeeded", error: null, finishedAt: new Date("2026-11-25T07:49:36.000Z"), + resultJson: { + summary: "Successfully created v1.txt containing \"one\" and v2.txt containing \"two\" using dedicated swarm helpers per file, and verified both files.", + acceptedResult: { verification: [{ status: "passed", commandOrCheck: "verifier check", + detail: "Both files verified successfully: v1.txt exists and contains \"one\", and v2.txt exists and contains \"two\"." }] }, + semanticToolReceipts: { + "register-v1-txt": deliverable("v1.txt", "6a1f0c2e-0000-4000-8000-00000000b001"), + "register-v2-txt": deliverable("v2.txt", "6a1f0c2e-0000-4000-8000-00000000b002", "out/v2.txt", "duplicate"), + }, + }, + }, + agent: { id: "agent-1", name: "Swarm Agent", adapterType: "paperclip_runner" }, + }); + + const prompt = renderPaperclipWakePrompt({ + reason: "issue_reopened_via_comment", + issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", status: "in_progress" }, + comments: [{ id: "comment-1", body: "append three to v1.txt" }], + fallbackFetchNeeded: false, + continuationSummary: { key: "continuation-summary", body }, + }); + expect(prompt).toContain("Successfully created v1.txt containing \"one\" and v2.txt containing \"two\""); + expect(prompt).toContain("## Files Delivered\n\n- `v1.txt`\n- `v2.txt`"); + expect(prompt).toContain("## Files / Routes Touched\n\n- No file or route paths were detected"); + expect(prompt).toContain("Check verifier check: passed (Both files verified successfully"); + expect(prompt).not.toContain(swarmRunId); + expect(prompt).not.toMatch(/run log|transcript|\/api\/attachments|[0-9a-f]{64}|paperclip_runner/); + + const next = buildContinuationSummaryMarkdown({ + issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", description: null, status: "done", priority: "medium" }, + run: { id: "run-next", status: "succeeded", error: null, resultJson: { summary: "Appended three.", + semanticToolReceipts: { "register-v3-txt": deliverable("v3.txt", "6a1f0c2e-0000-4000-8000-00000000b003") } } }, + agent: { id: "agent-1", name: "Swarm Agent", adapterType: "paperclip_runner" }, + previousSummaryBody: body, + }); + expect(next).toContain("## Files Delivered\n\n- `v3.txt`\n- `v1.txt`\n- `v2.txt`"); + }); + + it("lists the latest run's paths before older ones once the list is full", () => { + const older = Array.from({ length: 12 }, (_, index) => `- \`server/src/old-${index}.ts\``).join("\n"); + const body = buildContinuationSummaryMarkdown({ + issue: { id: "issue-1", identifier: "PAP-1", title: "Paths", description: null, status: "in_progress", priority: "medium" }, + run: { id: "run-1", status: "succeeded", error: null, resultJson: { summary: "Updated server/src/new.ts." } }, + agent: { id: "agent-1", name: "Agent", adapterType: "codex_local" }, + previousSummaryBody: `# Continuation Summary\n\n## Files / Routes Touched\n\n${older}\n`, + }); + expect(body).toContain("## Files / Routes Touched\n\n- `server/src/new.ts`\n- `server/src/old-0.ts`"); + expect(body).not.toContain("old-11.ts"); + }); + it("uses failure state to point the next run at the error", () => { const body = buildContinuationSummaryMarkdown({ issue: { diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 686d6f6d714..d60f1a329b1 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -17385,7 +17385,7 @@ export function issueRoutes( }) { if (issue.conversationAgentId) { const recent = await svc.listComments(issue.id, { companyId: issue.companyId, order: "desc", limit: 21 }); - const comments = recent.slice(0, 20); + const comments = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, recent.slice(0, 20)); return runRedactions.redactForIssue(issue.companyId, issue.id, { comments, latestCommentId: comments[0]?.id ?? null, @@ -17400,7 +17400,8 @@ export function issueRoutes( ? Promise.resolve([]) : svc.listComments(issue.id, { companyId: issue.companyId, order: "asc", limit: 1, humanOnly: true }), ]); - const comments = [...new Map([...firstInstruction, ...human, ...recent.slice(0, 4)].map((comment) => [comment.id, comment])).values()]; + const comments = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, + [...new Map([...firstInstruction, ...human, ...recent.slice(0, 4)].map((comment) => [comment.id, comment])).values()]); const included = new Set(comments.map((comment) => comment.id)); return runRedactions.redactForIssue(issue.companyId, issue.id, { comments, diff --git a/server/src/services/heartbeat-run-summary.ts b/server/src/services/heartbeat-run-summary.ts index 3c9d73ff629..cea1c78e53c 100644 --- a/server/src/services/heartbeat-run-summary.ts +++ b/server/src/services/heartbeat-run-summary.ts @@ -353,7 +353,12 @@ function readAcceptedSemanticSummary(resultJson: Record) { return null; } -function semanticResultCandidates(resultJson: Record) { +export function isCommittedToolReceiptResult(result: unknown): boolean { + const disposition = record(result).disposition; + return disposition === "applied" || disposition === "duplicate"; +} + +export function semanticResultCandidates(resultJson: Record) { return [ record(resultJson.nativeResult), record(resultJson.acceptedResult), @@ -782,7 +787,7 @@ export function findHeartbeatRunCompletionComment | null | undefine ); } +function asRecord(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; +} + +function readDeliveredFiles(resultJson: Record | null | undefined): string[] { + const receipts = asRecord(resultJson?.semanticToolReceipts); + if (!receipts) return []; + const files = new Set(); + for (const value of Object.values(receipts)) { + const receipt = asRecord(value); + if (receipt?.operationId !== "register_deliverable" || !isCommittedToolReceiptResult(receipt.result)) continue; + const filename = asNonEmptyString(asRecord(receipt.input)?.filename); + if (filename && filename.length <= 200 && !/[`\u0000-\u001f]/.test(filename)) files.add(filename); + if (files.size >= 12) break; + } + return [...files]; +} + +function readVerification(resultJson: Record | null | undefined): string[] { + const checks = semanticResultCandidates(resultJson ?? {}).map((candidate) => candidate.verification).find(Array.isArray); + if (!checks) return []; + return checks.slice(0, 6).flatMap((value) => { + const check = asRecord(value); + const name = asNonEmptyString(check?.commandOrCheck); + const status = asNonEmptyString(check?.status); + if (!name || !status) return []; + const detail = asNonEmptyString(check?.detail); + const oneLine = (text: string, max: number) => truncateText(text.replace(/\s+/g, " "), max).replace(/\n/g, " "); + return [`Check ${oneLine(name, 160)}: ${status}${detail ? ` (${oneLine(detail, 240)})` : ""}.`]; + }); +} + function extractMarkdownSection(markdown: string | null | undefined, heading: string) { if (!markdown) return null; const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -150,13 +182,17 @@ export function buildContinuationSummaryMarkdown(input: { const modelError = summarizeRunErrorForModel( run.error ? withoutSqlStatementText(run.error, readRunFailureCause(run.resultJson)) : run.error, terminalFailureCategory); const recentActions = [ - `Run \`${run.id}\` finished with status \`${run.status}\`${run.finishedAt ? ` at ${run.finishedAt.toISOString()}` : ""}.`, + `The latest run finished with status \`${run.status}\`${run.finishedAt ? ` at ${run.finishedAt.toISOString()}` : ""}.`, resultSummary ? truncateText(resultSummary, SUMMARY_SECTION_MAX_CHARS) : "No adapter-provided result summary was captured for this run.", + ...readVerification(run.resultJson), ]; if (modelError) { recentActions.push(`Latest run error${run.errorCode ? ` (${run.errorCode})` : ""}: ${truncateText(modelError, 500)}`); } + const previousDelivered = [...(extractMarkdownSection(input.previousSummaryBody, "Files Delivered") ?? "") + .matchAll(/^[-*]\s+`([^`\n]+)`\s*$/gm)].map((match) => match[1]!); + const delivered = [...new Set([...readDeliveredFiles(run.resultJson), ...previousDelivered])].slice(0, 12); const paths = extractPathCandidates(resultSummary, run.stdoutExcerpt, run.stderrExcerpt, input.previousSummaryBody); const objective = extractMarkdownSection(issue.description, "Objective") ?? issue.description?.trim() ?? "No objective captured."; const acceptanceCriteria = extractMarkdownSection(issue.description, "Acceptance Criteria") ?? "No explicit acceptance criteria captured."; @@ -170,8 +206,7 @@ export function buildContinuationSummaryMarkdown(input: { `- Status: ${issue.status}`, `- Priority: ${issue.priority}`, `- Current mode: ${mode}`, - `- Last updated by run: ${run.id}`, - `- Agent: ${agent.name} (${agent.adapterType ?? "unknown"})`, + `- Agent: ${agent.name}`, "", "## Objective", "", @@ -189,16 +224,7 @@ export function buildContinuationSummaryMarkdown(input: { "", bulletList(paths.map((path) => `\`${path}\``), "No file or route paths were detected in the captured run summary."), "", - "## Commands Run", - "", - bulletList( - [ - `Heartbeat run \`${run.id}\` invoked adapter \`${agent.adapterType ?? "unknown"}\`.`, - "Detailed shell/tool commands remain in the run log and transcript.", - ], - "No command metadata captured.", - ), - "", + ...(delivered.length > 0 ? ["## Files Delivered", "", bulletList(delivered.map((name) => `\`${name}\``), ""), ""] : []), "## Blockers / Decisions", "", bulletList( diff --git a/server/src/services/native-runtime/native-deliverable-feedback.ts b/server/src/services/native-runtime/native-deliverable-feedback.ts index 9ca7d377772..024ba1c9793 100644 --- a/server/src/services/native-runtime/native-deliverable-feedback.ts +++ b/server/src/services/native-runtime/native-deliverable-feedback.ts @@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm"; import { createHash } from "node:crypto"; import { assets, companies, completionContracts, documents, documentRevisions, heartbeatRuns, issueDocuments, issueAttachments, issues, issueThreadInteractions, issueWorkProducts, mcpAttachmentUploads, dotRunnerAssignments, type Db } from "@paperclipai/db"; import { projectHumanInteractionResponse } from "../execution-continuation.js"; +import { isCommittedToolReceiptResult } from "../heartbeat-run-summary.js"; export class NativeDeliverableEvidenceError extends Error {} @@ -42,7 +43,7 @@ async function hasCurrentPublicationReceipt(db: Db, companyId: string, receipts: const receipt = record(value); const input = record(receipt.input); const result = record(receipt.result); - if ((result.disposition !== "applied" && result.disposition !== "duplicate") || + if (!isCommittedToolReceiptResult(result) || !Array.isArray(result.entityRefs) || result.entityRefs[0] !== attachment.id) continue; if (receipt.operationId === "publish_external_deliverable" && result.source === "authenticated_upload" && result.commandId === `deliverable-uploaded:${attachment.id}` && typeof input.uploadId === "string" @@ -324,7 +325,7 @@ export async function publishedTaskDocuments(db: Db, binding: { companyId: strin const saved = await (binding.lockSources ? query.for("share", { of: [issueDocuments, documents, documentRevisions, heartbeatRuns], noWait: true }) : query); return saved.filter(document => Object.values(record(document.resultJson?.semanticToolReceipts)).some(value => { const receipt = record(value), result = record(receipt.result), published = record(result.document); - return receipt.operationId === "write_document" && ["applied", "duplicate"].includes(String(result.disposition)) + return receipt.operationId === "write_document" && isCommittedToolReceiptResult(result) && published.id === document.id && published.latestRevisionId === document.revisionId; })).map(({ id, revisionId, key, issuePrefix, issueIdentifier }) => ({ id, revisionId, key, href: `/${encodeURIComponent(issuePrefix)}/issues/${encodeURIComponent(issueIdentifier ?? binding.issueId)}#document-${encodeURIComponent(key)}` })); diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index e48d3ee3f6d..c08e0a41417 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -1533,6 +1533,35 @@ describe("TaskChatThread draft pass-through", () => { expect(container.textContent).toContain("u1.txt"); }); + it("does not repeat a run's file card under that run's reply when the reply links the file", async () => { + type Props = ComponentProps; + const fileId = "00000000-0000-4000-8000-000000000021"; + const at = new Date("2026-11-25T07:49:27Z"); + const workProducts = [{ + id: "file-v1", type: "artifact", provider: "paperclip", title: "v1.txt deliverable", status: "active", reviewState: "none", healthStatus: "unknown", + createdByRunId: "swarm-run", createdAt: at, updatedAt: at, + metadata: { attachmentId: fileId, originalFilename: "v1.txt", contentType: "text/plain", byteSize: 3, contentPath: `/api/attachments/${fileId}/content`, openPath: `/api/attachments/${fileId}/content`, downloadPath: `/api/attachments/${fileId}/content?download=1` }, + }] as unknown as NonNullable; + const attachments = [{ id: fileId, issueCommentId: null, originatingRunId: "swarm-run", createdByAgentId: "agent", + originalFilename: "v1.txt", contentType: "text/plain", contentPath: `/api/attachments/${fileId}/content`, createdAt: at, updatedAt: at, byteSize: 3, + }] as unknown as NonNullable; + const reply = (id: string, runId: string) => ({ + id, companyId: "company", issueId: "issue", authorType: "agent" as const, authorAgentId: "agent", authorUserId: null, + createdByRunId: runId, runId, presentation: null, metadata: null, createdAt: new Date(at.getTime() + 9_000), updatedAt: at, + body: `Created v1.txt.\n\n**Download**: [v1.txt](/api/attachments/${fileId}/content)`, + }); + const chips = () => container.querySelectorAll('[data-testid="task-chat-bubble-attachments"], [data-testid="task-chat-bubble-artifacts-v1"]').length; + + render( {}} issueStatus="done" />); + await settleThreadLayout(); + expect(container.textContent).toContain("Created v1.txt."); + expect(chips()).toBe(0); + + render( {}} issueStatus="done" />); + await settleThreadLayout(); + expect(chips()).toBe(1); + }); + it("aligns the desktop thread header with the side-panel tab row", () => { renderThread({ comments: [ diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index 1e5e8a8b608..6ec17795c6d 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -4,7 +4,8 @@ import { presentationDecisionCommentId, semanticProgressCommentIds, } from "@/lib/run-answer-visibility"; -import { preparationReceiptIds } from "./task-chat/image-resources"; +import { preparationReceiptIds, runFileCardAttachments } from "./task-chat/image-resources"; +import { RunFileCardsContext } from "./task-chat/RunFileCardsContext"; import type { ScrollingHistory } from "@/components/task-chat/TaskMessageScroller"; import { TaskChatShimmerScope } from "@/components/task-chat/TaskChatShimmer"; import { useRunnerSubmission } from "@/hooks/useRunnerSubmission"; @@ -902,6 +903,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { () => preparationReceiptIds(comments, attachments, workProducts), [comments, attachments, workProducts], ); + const runFileCards = useMemo(() => runFileCardAttachments(workProducts), [workProducts]); const projectedComments = useMemo( () => comments.flatMap((comment) => { @@ -3449,6 +3451,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { ) : null} ) : ( + + )} ) : null} diff --git a/ui/src/components/task-chat/RunFileCardsContext.ts b/ui/src/components/task-chat/RunFileCardsContext.ts new file mode 100644 index 00000000000..e5434802ebe --- /dev/null +++ b/ui/src/components/task-chat/RunFileCardsContext.ts @@ -0,0 +1,3 @@ +import { createContext } from "react"; + +export const RunFileCardsContext = createContext>(new Map()); diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx index 60e1c8f0a26..30a9765074b 100644 --- a/ui/src/components/task-chat/TaskChatBubble.tsx +++ b/ui/src/components/task-chat/TaskChatBubble.tsx @@ -33,6 +33,7 @@ import { AttachmentTrigger, } from "@/components/ui/attachment"; import { + attachmentIdFromUrl, extractAttachmentRefs, extractImageRefs, fileKindForAttachment, @@ -44,6 +45,7 @@ import { } from "./task-chat-attachments"; import { TaskChatBubbleActions } from "./TaskChatBubbleActions"; import { TaskChatSystemNotice } from "./TaskChatSystemNotice"; +import { RunFileCardsContext } from "./RunFileCardsContext"; import type { TaskChatMessageItem } from "./task-chat-model"; import { safeNavigableUrl } from "@/lib/safe-url"; @@ -171,6 +173,7 @@ function TaskChatBubbleContent({ ? : item.timestamp; const { enabled: artifactsV1 } = useArtifactsV1Enabled(); const openText = useContext(TextAttachmentContext); + const runFileCards = useContext(RunFileCardsContext); // Task attachments share the page gallery; standalone images retain the bubble viewer. const openIssueGallery = useContext(IssueGalleryContext); const [lightboxSrc, setLightboxSrc] = useState(null); @@ -239,15 +242,19 @@ function TaskChatBubbleContent({ openPath: attachment.openPath, downloadPath: attachment.downloadPath, })); + const notRunFileCard = (ref: AttachmentRef) => { + const id = ref.id ?? attachmentIdFromUrl(ref.url); + return !(item.author === "agent" && item.sourceRunId && id && runFileCards.get(id) === item.sourceRunId); + }; const imageRefs = uniqueAttachmentRefs([ ...hydratedEmbeddedRefs, ...hydratedLinkedRefs.filter(isImageAttachment), ...boundAttachmentRefs.filter(isImageAttachment), - ]); + ]).filter(notRunFileCard); const attachmentRefs = uniqueAttachmentRefs([ ...hydratedLinkedRefs.filter((ref) => !isImageAttachment(ref)), ...boundAttachmentRefs.filter((ref) => !isImageAttachment(ref)), - ]); + ]).filter(notRunFileCard); const mediaRefs = [...imageRefs, ...attachmentRefs.filter((ref) => isVideoLikeOutput(ref.contentType, ref.name))]; const galleryItems: GalleryMediaItem[] = lightboxSrc !== null && !mediaRefs.some((ref) => ref.url === lightboxSrc) diff --git a/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx b/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx index aba80124329..8c7edba09da 100644 --- a/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx +++ b/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx @@ -31,7 +31,7 @@ import { import { TaskChatUsageReadout } from "./TaskChatUsageReadout"; import { TaskChatReasoningSummary } from "./TaskChatReasoningSummary"; import { latestReasoningHeadline } from "./reasoning-summary"; -import { retriedLabel, SUBJECT_FAMILIES, subjectRowLabel, toolActivityPresentation, type ToolIcon } from "./tool-taxonomy"; +import { retriedLabel, sentenceRowLabel, SUBJECT_FAMILIES, subjectRowLabel, toolActivityPresentation, type ToolIcon } from "./tool-taxonomy"; import { useTaskChatShimmer } from "./TaskChatShimmer"; import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView"; import { useTaskReferenceLabel, withTaskReference } from "./task-reference"; @@ -124,9 +124,11 @@ function presentation(item: Activity, active: boolean, taskLabel?: string): Acti // A finished command needs no verb at all: the icon and "$" say it ran. // A failure or stop keeps its marker ("Read · failed") unless an exit // chip already says how a command ended. Live rows use the same helper. - const verb = subject && SUBJECT_FAMILIES.has(tool.family) - ? subjectRowLabel(label, terminal && !running && (item.status === "completed" || item.exitCode != null)) - : label; + const verb = subject && tool.sentenceSubject + ? sentenceRowLabel(label) + : subject && SUBJECT_FAMILIES.has(tool.family) + ? subjectRowLabel(label, terminal && !running && (item.status === "completed" || item.exitCode != null)) + : label; // Exit 0 is only news for commands; for reads and searches it is noise. const exitCode = item.exitCode ?? null; const shownExit = exitCode === 0 && !terminal ? null : exitCode; diff --git a/ui/src/components/task-chat/antigravity-thread.test.tsx b/ui/src/components/task-chat/antigravity-thread.test.tsx index f2d5b2cf2f7..e516214895d 100644 --- a/ui/src/components/task-chat/antigravity-thread.test.tsx +++ b/ui/src/components/task-chat/antigravity-thread.test.tsx @@ -64,27 +64,27 @@ describe("an Antigravity swarm run's task thread", () => { it("reads in plain language after the run", () => { expect(settled()).toEqual([ - "Swarm Swarm started in the task folder with Gemini 3.8 Flash (Low) on Google's default channel (Antigravity CLI 1.5.15). Helper changes inside the task folder are approved automatically; anything else is blocked.", - "Swarm This swarm runs on the Google account of this agent's Google connection.", - "Swarm Goal: Create and verify u1.txt and u2.txt", - "Swarm Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly \"one\"", - "Swarm Started helper writer2: Create a file named u2.txt in the current workspace directory containing exactly \"two\"", - "Swarm Started helper verifier: You are the verifier", - "Swarm Started a helper that watches for stalls", - "Swarm Checked on the helpers", - "Swarm Checked on the helpers", + "Swarm started in the task folder with Gemini 3.8 Flash (Low) on Google's default channel (Antigravity CLI 1.5.15). Helper changes inside the task folder are approved automatically; anything else is blocked.", + "This swarm runs on the Google account of this agent's Google connection.", + "Goal: Create and verify u1.txt and u2.txt", + "Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly \"one\"", + "Started helper writer2: Create a file named u2.txt in the current workspace directory containing exactly \"two\"", + "Started helper verifier: You are the verifier", + "Started a helper that watches for stalls", + "Checked on the helpers", + "Checked on the helpers", // The CLI's first reads used a relative path and were refused; the same reads then succeeded. "Read · retried u1.txt", "Read · retried u2.txt", "Read u1.txt", "Read u2.txt", - "Swarm Coordinator: All files u1.txt and u2.txt created and verified successfully", + "Coordinator: All files u1.txt and u2.txt created and verified successfully", "$ shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt", // One row per file, with the file's name, never the bridge's arguments or a digest. "Attached u1.txt", "Attached u2.txt", - "Swarm Files changed in the task folder: u1.txt, u2.txt", - "Swarm Token usage is the coordinator's total and includes the helpers; Google does not report it per helper", + "Files changed in the task folder: u1.txt, u2.txt", + "Token usage is the coordinator's total and includes the helpers; Google does not report it per helper", ]); }); diff --git a/ui/src/components/task-chat/image-resources.ts b/ui/src/components/task-chat/image-resources.ts index 260ff2ea295..a9d6cf3638d 100644 --- a/ui/src/components/task-chat/image-resources.ts +++ b/ui/src/components/task-chat/image-resources.ts @@ -69,3 +69,12 @@ export function groupImageResources(items: readonly T[]) } return rows; } + +export function runFileCardAttachments(products: readonly IssueWorkProduct[]): ReadonlyMap { + const byAttachment = new Map(); + for (const product of products) { + const attachmentId = fileRowSourceFromWorkProduct(product)?.attachmentId; + if (attachmentId && product.createdByRunId) byAttachment.set(attachmentId, product.createdByRunId); + } + return byAttachment; +} diff --git a/ui/src/components/task-chat/task-chat-activity-presentation.ts b/ui/src/components/task-chat/task-chat-activity-presentation.ts index fd7c3576ce4..20b5b2bd986 100644 --- a/ui/src/components/task-chat/task-chat-activity-presentation.ts +++ b/ui/src/components/task-chat/task-chat-activity-presentation.ts @@ -30,6 +30,7 @@ import { humanizeToolName, isGenericToolName, retriedLabel, + sentenceRowLabel, SUBJECT_FAMILIES, subjectRowLabel, toolActivityPresentation, @@ -140,6 +141,16 @@ export function providerActivityPresentation(item: TaskChatProviderActivityItem) // "$ npm test" (TaskChatRunnerActivityGroup's tool rows). // Settled rows classify by the name alone (TaskChatRunnerActivityGroup). const settled = toolActivityPresentation({ name, target }); + if (settled.sentenceSubject && subject && boundedActivity === subject) { + return { + icon: settled.icon, + runningLabel: sentenceRowLabel(settled.runningLabel), + completedLabel: sentenceRowLabel(settled.completedLabel), + failedLabel: sentenceRowLabel(settled.failedLabel), + interruptedLabel: sentenceRowLabel(settled.interruptedLabel), + detail: [subject, source].filter(Boolean).join(" · "), + }; + } const concrete = Boolean(boundedActivity && (boundedActivity === subject || boundedActivity === meaningfulToolDetail(target))) && SUBJECT_FAMILIES.has(settled.family); if (concrete) { diff --git a/ui/src/components/task-chat/task-chat-attachments.ts b/ui/src/components/task-chat/task-chat-attachments.ts index 8c702e4d76d..ee53140df71 100644 --- a/ui/src/components/task-chat/task-chat-attachments.ts +++ b/ui/src/components/task-chat/task-chat-attachments.ts @@ -157,7 +157,7 @@ export interface AttachmentRef { downloadPath?: string; } -function attachmentIdFromUrl(url: string): string | null { +export function attachmentIdFromUrl(url: string): string | null { return /\/api\/(?:attachments|assets)\/([^/?]+)\/content/.exec(url)?.[1] ?? null; } diff --git a/ui/src/components/task-chat/tool-taxonomy.ts b/ui/src/components/task-chat/tool-taxonomy.ts index 71aa31f105a..e4fae95a004 100644 --- a/ui/src/components/task-chat/tool-taxonomy.ts +++ b/ui/src/components/task-chat/tool-taxonomy.ts @@ -79,6 +79,7 @@ export interface ToolActivityPresentation { technicalName?: string; confidence: ToolClassificationConfidence; summaryGroup: ToolSummaryGroup; + sentenceSubject?: boolean; } /** Families whose rows read as " ", for example "Read README.md". */ @@ -95,6 +96,10 @@ export function subjectRowLabel(label: string, settledCommand: boolean): string return `${action!.split(" ")[0]}${marker ? ` · ${marker}` : ""}`; } +export function sentenceRowLabel(label: string): string { + return label.includes(" · ") ? label : ""; +} + /** "Read · failed" → "Read · retried", for a failure a later call of the same tool recovered. */ export function retriedLabel(failedLabel: string): string { return failedLabel.replace(/ · failed$/, " · retried"); @@ -167,9 +172,10 @@ interface ExactAction { completed?: string; group?: ToolSummaryGroup; family?: ToolFamily; + sentence?: boolean; } -const group = (key: string, singular: string, plural: string): ToolSummaryGroup => ({ key, singular, plural }); +const group =(key: string, singular: string, plural: string): ToolSummaryGroup => ({ key, singular, plural }); const EXACT_ACTIONS: Record = { bash: { action: "run" }, @@ -227,7 +233,7 @@ const EXACT_ACTIONS: Record = { // With the file as its subject the row reads "Attached u1.txt". register_deliverable: { action: "create", running: "Attaching a file", completed: "Attached a file" }, // Antigravity's swarm progress lines; the subject is the whole plain sentence. - swarm_update: { action: "other", running: "Swarm", completed: "Swarm", family: "agent", group: group("swarm_update", "swarm update", "swarm updates") }, + swarm_update: { action: "other", running: "Swarm", completed: "Swarm", family: "agent", sentence: true, group: group("swarm_update", "swarm update", "swarm updates") }, finish_task: { action: "finish", running: "Reporting completion", completed: "Reported completion" }, paperclip_finish: { action: "finish", running: "Reporting completion", completed: "Reported completion" }, block_task: { action: "block", running: "Reporting a blocker", completed: "Reported a blocker" }, @@ -439,6 +445,7 @@ export function toolActivityPresentation(input: ToolActivityPresentationInput): technicalName: rawName || undefined, confidence, summaryGroup, + ...(exact?.sentence ? { sentenceSubject: true } : {}), }; }