diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index 5509c0ad636..176cab0cddb 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -766,9 +766,13 @@ function createRuntimeEventStep( const trackSubagents = initializedAgent === "claude" ? createClaudeSubagentLineageTracker((id) => stableProviderIdentity(id, "tool")) : null; - const accept = (event: AcpRuntimeEvent): void => { - toolUseAdmission?.observe(currentTurnId, event); - toolEvidence?.tool(event); + const projectToolEvent = acpxProfileActivity(openParams?.agent ?? initializedAgent).createToolEventProjection?.() + ?? ((event: AcpRuntimeEvent) => event); + const accept = (raw: AcpRuntimeEvent): void => { + toolUseAdmission?.observe(currentTurnId, raw); + toolEvidence?.tool(raw); + const event = projectToolEvent(raw); + if (!event) return; // Claude hook lifecycle rides on session_info_update `_meta`; publish it // as schema-validated display activity rather than a raw status event. const hook = claudeHookCanonicalEvent(event); @@ -1330,7 +1334,8 @@ type BoundedRuntimeToolEvent = AcpRuntimeEvent & { */ function withSidecarToolDetail(raw: AcpRuntimeEvent, bounded: AcpRuntimeEvent): AcpRuntimeEvent { if (raw.type !== "tool_call" || bounded.type !== "tool_call") return bounded; - const detail = acpxToolDetailFromRuntimeEvent(raw); + // A provider projection (profile-activity.ts) may already name the tool. + const detail = { ...acpxToolDetailFromRuntimeEvent(raw), ...record(record(raw).paperclipToolDetail) }; const inputPath = bounded.locations?.length ? undefined : acpxToolInputPath(raw); const locations = inputPath ? safeAcpxLocations([{ path: inputPath }], openParams?.workingDirectory, bounded.kind, bounded.title) diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts index c895acd1625..1bf1ae2bfa4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts @@ -1,5 +1,6 @@ import type { CanonicalProviderEvent } from "../../provider-events.js"; import { antigravitySwarmChannelLabel } from "./antigravity-swarm-route.js"; +import { antigravityToolDetail, isAntigravityInternalRead } from "./antigravity-tool-identity.js"; import type { AcpxActivityAdapter } from "./profile-activity.js"; const record = (value: unknown): Record => @@ -42,6 +43,31 @@ export function antigravitySwarmReceiptNotice(before: unknown, after: unknown, r }; } +/** + * Antigravity names no tool (its ACP titles are display text), so each call + * gets the identity other harnesses send. A swarm turn's events already carry + * theirs (antigravity-swarm-presentation.ts); reads of the CLI's own built-in + * files are dropped, with every later update of the same call. + */ +export function createAntigravityToolEventProjection(): (event: T) => T | null { + const hidden = new Set(); + return (event: T): T | null => { + if (event.type !== "tool_call") return event; + const value = event as unknown as Record; + const id = typeof value.toolCallId === "string" ? value.toolCallId : null; + if (id && hidden.has(id)) return null; + if (isAntigravityInternalRead(value)) { + if (id && hidden.size < 1_024) hidden.add(id); + return null; + } + if (text(record(value.paperclipToolDetail).toolName)) return event; + const detail = antigravityToolDetail(value); + // The title is display text such as `paperclip_set_task_title`; a named call's progress is its subject. + return detail ? { ...event, text: detail.subject ?? "", paperclipToolDetail: { ...record(value.paperclipToolDetail), ...detail } } : event; + }; +} + export const antigravityActivityAdapter: AcpxActivityAdapter = Object.freeze({ + createToolEventProjection: createAntigravityToolEventProjection, usageNotice: (before, after, requestId, turnId) => antigravitySwarmReceiptNotice(before, after, requestId, `${turnId}:antigravity-swarm-receipt`), }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts index 3ea3b82c3ad..1f6c59d9163 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts @@ -21,7 +21,7 @@ describe("Antigravity swarm activity, in plain language", () => { expect(antigravitySwarmEvent(tool("post_message", { text: "@verifier [done] Verification verified: checked 2 files" }), WORKSPACE)) .toMatchObject({ title: "Coordinator: Verification verified: checked 2 files" }); expect(antigravitySwarmEvent(tool("swarm", { action: "title", title: "Two writers and a verifier" }), WORKSPACE)) - .toMatchObject({ title: "Swarm: Two writers and a verifier" }); + .toMatchObject({ title: "Goal: Two writers and a verifier", paperclipToolDetail: { toolName: "swarm_update", subject: "Goal: Two writers and a verifier" } }); }); it("keeps the opening title on later updates of the same call", () => { diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts index e67fe1d9f14..67fb5d42ca8 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts @@ -1,4 +1,5 @@ import type { AcpRuntimeEvent } from "acpx/runtime"; +import { ANTIGRAVITY_SWARM_UPDATE_TOOL, antigravityToolDetail, isAntigravityInternalRead } from "./antigravity-tool-identity.js"; /** * The Antigravity CLI coordinator reports its swarm through its own tools @@ -81,13 +82,20 @@ function swarmTitle(name: string, args: Json, workspace: string): string | null return typeof args.brief === "string" && args.brief.trim() ? `Started helper ${helper || "(unnamed)"}: ${plain(args.brief, workspace)}` : `Started helper ${helper || "(unnamed)"}`; - case "title": return typeof args.title === "string" ? `Swarm: ${plain(args.title, workspace)}` : "Named the swarm"; + case "title": return typeof args.title === "string" ? `Goal: ${plain(args.title, workspace)}` : "Named the swarm"; case "remove": case "kill": case "stop": return helper ? `Stopped helper ${helper}` : "Stopped a helper"; case "status": return "Checked on the helpers"; default: return "Coordinated the helpers"; } } +/** A location inside the task folder as a task-relative path, the way the run record names files. */ +function taskRelative(location: unknown, workspace: string): unknown { + const value = record(location); + const prefix = `${workspace.replace(/\/+$/, "")}/`; + return typeof value.path === "string" && value.path.startsWith(prefix) ? { ...value, path: value.path.slice(prefix.length) } : location; +} + /** One ACP `session/update` as a runtime event, or null when it carries nothing to show. */ export function antigravitySwarmEvent(update: unknown, workspace: string): AcpRuntimeEvent | null { const value = record(update); @@ -107,16 +115,31 @@ export function antigravitySwarmEvent(update: unknown, workspace: string): AcpRu const status = typeof value.status === "string" ? value.status : undefined; if (SWARM_TOOLS.has(name)) { const title = swarmTitle(name, args, workspace) ?? "Coordinated the helpers"; - return { type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title, kind: "other", ...(status ? { status } : {}) }; + return antigravitySwarmLine(value.toolCallId, title, kind, status); } + if (isAntigravityInternalRead(value)) return null; const title = typeof value.title === "string" ? value.title.split(workspace).join(".") : name || "Tool call"; + const detail = antigravityToolDetail({ ...value, title }); return { - type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title, + // A named call's title is display text (`Run mcp_paperclip_…`); its progress is its subject. + type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: detail ? detail.subject ?? "" : title, title, + ...(detail ? { paperclipToolDetail: detail } : {}), ...(typeof value.kind === "string" ? { kind: value.kind as never } : {}), ...(status ? { status } : {}), ...(value.rawInput !== undefined ? { rawInput: value.rawInput } : {}), ...(value.rawOutput !== undefined ? { rawOutput: value.rawOutput } : {}), ...(Array.isArray(value.content) ? { content: value.content as never } : {}), - ...(Array.isArray(value.locations) ? { locations: value.locations as never } : {}), + ...(Array.isArray(value.locations) ? { locations: value.locations.map(location => taskRelative(location, workspace)) as never } : {}), }; } + +/** + * One swarm progress line as a tool call with a neutral identity: the sentence + * is its subject, so it reads the same while the run is live and afterwards. + */ +export function antigravitySwarmLine(toolCallId: string, sentence: string, tag: "tool_call" | "tool_call_update" = "tool_call", status?: string): AcpRuntimeEvent { + return { + type: "tool_call", tag, toolCallId, text: sentence, title: sentence, kind: "other", ...(status ? { status } : {}), + paperclipToolDetail: { toolName: ANTIGRAVITY_SWARM_UPDATE_TOOL, subject: sentence }, + } as AcpRuntimeEvent; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index 4c89d8e28f5..155edda7e86 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -14,7 +14,7 @@ import { type AntigravitySwarmReceipt, } from "./antigravity-swarm-guard.js"; import { GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL, GENERATED_ANTIGRAVITY_SWARM_ENVELOPE_SCHEMA, GENERATED_ANTIGRAVITY_SWARM_REQUEST_FIELD, GENERATED_ANTIGRAVITY_SWARM_REQUEST_MAX_CHARS } from "./generated-sidecar-contract.js"; -import { antigravitySwarmEvent, createAntigravityTerminalHintFilter } from "./antigravity-swarm-presentation.js"; +import { antigravitySwarmEvent, antigravitySwarmLine, createAntigravityTerminalHintFilter } from "./antigravity-swarm-presentation.js"; import { acpRuntimeEventFromValidatedSessionUpdate } from "./acp-session-update-event.js"; import { awaitVerifiedAcpxProviderOwnership } from "./installation-integrity.js"; import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; @@ -316,8 +316,7 @@ function failed(code: string, message: string): AcpRuntimeTurnResult { return { status: "failed", error: { code, message, retryable: false } }; } -const line = (id: string, title: string): AcpRuntimeEvent => - ({ type: "tool_call", tag: "tool_call", toolCallId: `paperclip-swarm-${id}`, text: title, title, kind: "other", status: "completed" }); +const line = (id: string, title: string): AcpRuntimeEvent => antigravitySwarmLine(`paperclip-swarm-${id}`, title, "tool_call", "completed"); export type AntigravityCliAccountMatch = "matches" | "does_not_match" | "unknown"; const CLI_LOG_TAIL_BYTES = 512 * 1024; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.test.ts new file mode 100644 index 00000000000..a527ea08956 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.test.ts @@ -0,0 +1,126 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { + canonicalProviderEventsFromAcpxRuntimeEvent, + createAcpxToolEventNormalizer, + type AcpRuntimeEventShape, +} from "../../provider-events.js"; +import { createAntigravityToolEventProjection } from "./antigravity-activity.js"; +import { antigravitySwarmEvent, antigravitySwarmLine } from "./antigravity-swarm-presentation.js"; +import { antigravityToolDetail } from "./antigravity-tool-identity.js"; + +const fixture = JSON.parse(readFileSync(new URL("../../../test-fixtures/antigravity-cli/swarm-thread.updates.json", import.meta.url), "utf8")) as { + workspace: string; + updates: Record[]; +}; + +type ToolPayload = { name: string | null; namespace: string | null; transport: string; status: string; subject?: string; target: string | null }; + +/** What the run record stores for each tool update, the way the runner maps it. */ +function storedTools(events: Iterable): ToolPayload[] { + const normalize = createAcpxToolEventNormalizer({ now: () => 0 }); + const tools: ToolPayload[] = []; + for (const event of events) { + if (!event) continue; + for (const mapped of canonicalProviderEventsFromAcpxRuntimeEvent(normalize(event), "item-1", "turn-1", { workingDirectory: fixture.workspace })) { + if (mapped.eventType.startsWith("tool.execution.")) tools.push(mapped.payload as unknown as ToolPayload); + } + } + return tools; +} + +const completed = (tools: ToolPayload[]) => tools.filter(tool => tool.status !== "running"); + +describe("Antigravity tool identity", () => { + it("names a swarm's Paperclip tools the way every other harness does, not after the CLI's title", () => { + const all = storedTools(fixture.updates.map(update => antigravitySwarmEvent(update, fixture.workspace) as AcpRuntimeEventShape | null)); + // Not even as live progress: the CLI's titles are display text. + expect(JSON.stringify(all)).not.toMatch(/Run mcp_|mcp_paperclip_|File \.\.\//); + const tools = completed(all); + const finish = tools.filter(tool => tool.name === "paperclip_finish"); + // The refused first attempt and the accepted second one are both the canonical finish tool, + // so the task thread hides both exactly as it does for Claude or Codex. + expect(finish).toEqual([ + expect.objectContaining({ namespace: "paperclip", transport: "mcp", status: "failed" }), + expect.objectContaining({ namespace: "paperclip", transport: "mcp", status: "completed" }), + ]); + expect(tools).toContainEqual(expect.objectContaining({ name: "register_deliverable", namespace: "paperclip", transport: "mcp" })); + expect(tools.map(tool => tool.name)).not.toContainEqual(expect.stringMatching(/^Run |mcp_paperclip|^File /)); + }); + + it("names the CLI's own tools by their native name, with the command as the subject and no internal paths", () => { + const tools = completed(storedTools(fixture.updates.map(update => antigravitySwarmEvent(update, fixture.workspace) as AcpRuntimeEventShape | null))); + expect(tools).toContainEqual(expect.objectContaining({ name: "run_command", subject: "shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt" })); + expect(tools.filter(tool => tool.name === "view_file")).toEqual([ + expect.objectContaining({ status: "failed", target: "u1.txt" }), + expect.objectContaining({ status: "completed", target: "u1.txt" }), + ]); + // The CLI loading its own built-in skill is not work on the task. + expect(JSON.stringify(tools)).not.toMatch(/antigravity-home|SKILL\.md|\.\.\//); + }); + + it("gives swarm progress lines one neutral identity whose subject is the plain sentence", () => { + const tools = completed(storedTools([ + ...fixture.updates.slice(2, 5).map(update => antigravitySwarmEvent({ ...update, sessionUpdate: "tool_call_update", status: "completed" }, fixture.workspace) as AcpRuntimeEventShape | null), + antigravitySwarmLine("paperclip-swarm-files", "Files changed in the task folder: u1.txt, u2.txt", "tool_call", "completed") as AcpRuntimeEventShape, + ])); + expect(tools.map(tool => [tool.name, tool.subject])).toEqual([ + ["swarm_update", "Goal: Create and verify u1.txt and u2.txt"], + ["swarm_update", "Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly \"one\""], + ["swarm_update", "Checked on the helpers"], + ["swarm_update", "Files changed in the task folder: u1.txt, u2.txt"], + ]); + }); + + it("names an ordinary run's Paperclip tools from their `_` title or ACP MCP metadata", () => { + const project = createAntigravityToolEventProjection(); + const updates: AcpRuntimeEventShape[] = [ + { type: "tool_call", tag: "tool_call", toolCallId: "t1", title: "paperclip_set_task_title", kind: "other", status: "in_progress" }, + { type: "tool_call", tag: "tool_call_update", toolCallId: "t1", title: "paperclip_set_task_title", kind: "other", status: "completed", rawOutput: "Set task title" }, + { type: "tool_call", tag: "tool_call", toolCallId: "t2", title: "paperclip_paperclip_finish", kind: "other", status: "in_progress" }, + { type: "tool_call", tag: "tool_call_update", toolCallId: "t2", title: "paperclip_paperclip_finish", kind: "other", status: "failed" }, + { type: "tool_call", tag: "tool_call", toolCallId: "t3", title: "paperclip_write_document", kind: "other", status: "completed", + _meta: { mcp: { tool: "write_document", server: "paperclip" }, is_mcp_tool_call: true } }, + { type: "tool_call", tag: "tool_call", toolCallId: "t4", title: "touch greeting.txt", kind: "execute", status: "completed", rawInput: { CommandLine: "touch greeting.txt" } }, + ]; + const all = storedTools(updates.map(update => project(update))); + expect(JSON.stringify(all)).not.toMatch(/"progress":"paperclip_/); + const tools = completed(all); + expect(tools.map(tool => [tool.name, tool.namespace, tool.subject])).toEqual([ + ["set_task_title", "paperclip", undefined], + ["paperclip_finish", "paperclip", undefined], + ["write_document", "paperclip", undefined], + ["run_command", null, "touch greeting.txt"], + ]); + }); + + it("drops every update of a read of the CLI's own files, even one that no longer names the path", () => { + const project = createAntigravityToolEventProjection(); + expect(project({ type: "tool_call", toolCallId: "s1", kind: "read", status: "in_progress", + title: "File ../../runtime/paperclip-runner/acpx/acpx/session-1/antigravity-home/antigravity-cli/antigravity-cli/builtin/skills/a/SKILL.md" })).toBeNull(); + expect(project({ type: "tool_call", toolCallId: "s1", kind: "read", status: "completed" })).toBeNull(); + expect(project({ type: "text_delta", text: "hi" })).toEqual({ type: "text_delta", text: "hi" }); + }); + + it("keeps work on a task folder that happens to be named antigravity-home, and any command or edit", () => { + const project = createAntigravityToolEventProjection(); + const shown = [ + { type: "tool_call", toolCallId: "t1", kind: "read", status: "completed", title: "File antigravity-home/notes.md", locations: [{ path: "antigravity-home/notes.md" }] }, + { type: "tool_call", toolCallId: "t2", kind: "execute", status: "completed", title: "mkdir -p antigravity-home/config", rawInput: { CommandLine: "mkdir -p antigravity-home/config" } }, + { type: "tool_call", toolCallId: "t3", kind: "edit", status: "completed", title: "Write file", + locations: [{ path: "/runtime/paperclip-runner/acpx/s/antigravity-home/antigravity-cli/settings.json" }] }, + ]; + for (const event of shown) expect(project(event)).not.toBeNull(); + }); + + it("names a deletion and a move as what they are, never as an edit", () => { + expect(antigravityToolDetail({ title: "Delete old.txt", kind: "delete" })).toEqual({ toolName: "delete_file" }); + expect(antigravityToolDetail({ title: "Move a.txt", kind: "move" })).toEqual({ toolName: "move_file" }); + expect(antigravityToolDetail({ title: "Write a.txt", kind: "edit" })).toEqual({ toolName: "edit_file" }); + }); + + it("leaves a call it cannot name unchanged", () => { + expect(antigravityToolDetail({ title: "Something", kind: "other" })).toBeNull(); + expect(antigravityToolDetail({ title: "runner_extra_write_file", kind: "other", _meta: { mcp: { tool: "write_file", server: "runner_extra" } } })).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.ts new file mode 100644 index 00000000000..83934e84eed --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-tool-identity.ts @@ -0,0 +1,99 @@ +import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; +import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER } from "./antigravity-plan-mode.js"; + +/** + * Antigravity sends no tool identity Paperclip can show: ACP titles are display + * text ("Run mcp_paperclip_paperclip_finish", "File ../../u1.txt", a command + * line), so without this every row was named after its title. This module + * gives each call the identity other harnesses send in `paperclipToolDetail`: + * Paperclip's own tools as `mcp__paperclip__`, the CLI's native tools + * under their own names with the command as the subject, and the swarm's + * progress lines one neutral identity whose subject is the plain sentence. + */ +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; +const string = (value: unknown): string | undefined => + typeof value === "string" && value.trim() ? value.trim() : undefined; + +/** The one identity of every swarm progress line; its subject is the sentence. */ +export const ANTIGRAVITY_SWARM_UPDATE_TOOL = "swarm_update"; + +export interface AntigravityToolDetail { + toolName: string; + subject?: string; +} + +const NATIVE_TOOL = /^[a-z][a-z0-9_]{1,63}$/; +const CLI_PAPERCLIP_PREFIX = `mcp_${ANTIGRAVITY_PAPERCLIP_MCP_SERVER}_`; +/** Ordinary runs title an MCP call `_`; the CLI says `Run mcp__`. */ +const TITLED_PAPERCLIP = new RegExp(`^(?:Run )?(?:mcp_)?${ANTIGRAVITY_PAPERCLIP_MCP_SERVER}_([a-z][a-z0-9_]{0,127})\\??$`); +/** Command-line arguments the CLI's shell tools carry. */ +const COMMAND_KEYS = ["CommandLine", "commandLine", "command", "Command"]; +/** Kinds whose native name an ordinary run never sends, named the way the CLI names them. */ +const KIND_TOOLS: Readonly> = { execute: "run_command", read: "view_file", edit: "edit_file", delete: "delete_file", move: "move_file" }; + +function paperclipTool(tool: string): string { + return `mcp__${ANTIGRAVITY_PAPERCLIP_MCP_SERVER}__${canonicalRunnerToolName(tool)}`; +} + +/** The Paperclip bridge tool a call names, from the CLI's native name, ACP `_meta.mcp`, or its title. */ +export function antigravityPaperclipToolName(call: { name?: unknown; title?: unknown; _meta?: unknown }): string | null { + const name = string(call.name); + if (name?.startsWith(CLI_PAPERCLIP_PREFIX)) return paperclipTool(name.slice(CLI_PAPERCLIP_PREFIX.length)); + const mcp = record(record(call._meta).mcp); + if (mcp.server === ANTIGRAVITY_PAPERCLIP_MCP_SERVER && string(mcp.tool)) return paperclipTool(string(mcp.tool)!); + const titled = string(call.title) ? TITLED_PAPERCLIP.exec(string(call.title)!)?.[1] : undefined; + return titled ? paperclipTool(titled) : null; +} + +function command(call: Json): string | undefined { + const input = { ...record(call.rawInput), ...record(call.args) }; + for (const key of COMMAND_KEYS) { + const value = string(input[key]); + if (value) return value; + } + return undefined; +} + +/** + * Reads of the CLI's own installation (its built-in skills under the run's + * private Antigravity home) are the CLI loading itself, not work on the task. + */ +export function isAntigravityInternalRead(call: { name?: unknown; kind?: unknown; title?: unknown; locations?: unknown; rawInput?: unknown; args?: unknown }): boolean { + // Only a read is the CLI loading itself; a command or edit stays visible wherever it points. + const name = string(call.name); + if (call.kind !== "read" && !(name && READ_TOOL.test(name))) return false; + const paths = [ + string(call.title), + ...(Array.isArray(call.locations) ? call.locations.map(location => string(record(location).path)) : []), + ...Object.values({ ...record(call.rawInput), ...record(call.args) }).map(string), + ]; + return paths.some(path => path !== undefined && PRIVATE_CLI_HOME.test(path)); +} + +const READ_TOOL = /^(?:view|read)_/; +/** + * The run's private Antigravity home, inside the Runner's own ACPX runtime + * folder (`…/paperclip-runner/acpx/…/antigravity-home/antigravity-cli/…`). A + * task folder that merely has a directory named `antigravity-home` is not it. + */ +const PRIVATE_CLI_HOME = /(?:^|[\\/ ])paperclip-runner[\\/]acpx[\\/](?:[^\\/]+[\\/])*?antigravity-home[\\/]antigravity-(?:cli|acp)[\\/]/; + +/** + * The identity of one Antigravity tool call. `name` is the CLI's native tool + * name (the swarm route reads it from the raw update; ACPX drops it), so an + * ordinary run falls back to the ACP kind. Null leaves the call unchanged. + */ +export function antigravityToolDetail(call: Json): AntigravityToolDetail | null { + const paperclip = antigravityPaperclipToolName(call); + if (paperclip) return { toolName: paperclip }; + const kind = string(call.kind); + const native = string(call.name); + const toolName = native && NATIVE_TOOL.test(native) ? native : kind ? KIND_TOOLS[kind] : undefined; + if (!toolName) return null; + // A shell call's title is its command line; other titles are display text. + const title = string(call.title); + const subject = command(call) ?? (kind === "execute" && title && !/^run command$/i.test(title) ? title : undefined); + return { toolName, ...(subject ? { subject: subject.slice(0, 4_000) } : {}) }; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts index fb26b126cd0..c880996b30b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts @@ -1521,8 +1521,11 @@ class CodexAcpxSession implements HarnessSession { const trackSubagents = this.#agent === "claude" ? createClaudeSubagentLineageTracker(activity.toolExecutionId ?? ((id) => id)) : (event: AcpRuntimeEvent) => event; - for await (const event of turn.events) { - toolEvidence?.tool(event); + const projectToolEvent = activity.createToolEventProjection?.() ?? ((event: AcpRuntimeEvent) => event); + for await (const raw of turn.events) { + toolEvidence?.tool(raw); + const event = projectToolEvent(raw); + if (!event) continue; const projected = activity.toolExecutionId && event.type === "tool_call" && typeof event.toolCallId === "string" ? { ...event, toolCallId: activity.toolExecutionId(event.toolCallId) } : event; this.#mapRuntimeEvent(normalizeMessage(trackSubagents(normalizeToolEvent(projected))), turnId, ++index); diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts index dad1e366508..a6e3d47fca1 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts @@ -21,6 +21,12 @@ export interface AcpxToolEvidenceBinding { /** Provider-owned identity and diagnostic projection; never permission authority. */ export interface AcpxActivityAdapter { toolIdentity?(nativeId: string): string; + /** + * One turn's display identity for raw ACP tool updates, for a provider that + * names no tool: each event with `paperclipToolDetail` added, or null when the + * call is the provider's own bookkeeping and is not shown. Display only. + */ + createToolEventProjection?(): (event: T) => T | null; toolExecutionId?(nativeId: string): string; inputToolIdentity?(input: AcpxExtensionInput): string | undefined; createToolEvidence?(binding: AcpxToolEvidenceBinding): AcpxToolEvidence; diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/swarm-thread.updates.json b/packages/paperclip-runner/test-fixtures/antigravity-cli/swarm-thread.updates.json new file mode 100644 index 00000000000..a4cfb0aa8ca --- /dev/null +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/swarm-thread.updates.json @@ -0,0 +1,43 @@ +{ + "recorded": "Shapes of one /swarm turn's session/update tool calls (agy acp 1.5.15, gemini-3.8-flash-low), reconstructed from a live run's stored events: names, kinds, statuses, titles and outputs as the CLI sent them; local paths, ids and hashes replaced. The task folder is /work/task.", + "workspace": "/work/task", + "updates": [ + { "sessionUpdate": "tool_call", "toolCallId": "call_1001", "name": "view_file", "kind": "read", "status": "in_progress", + "title": "File ../../../runtime/paperclip-runner/acpx/session-1/antigravity-home/antigravity-cli/antigravity-cli/builtin/skills/native_swarm/SKILL.md", + "locations": [{ "path": "/work/runtime/paperclip-runner/acpx/session-1/antigravity-home/antigravity-cli/antigravity-cli/builtin/skills/native_swarm/SKILL.md" }] }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1001", "name": "view_file", "kind": "read", "status": "completed", + "title": "File ../../../runtime/paperclip-runner/acpx/session-1/antigravity-home/antigravity-cli/antigravity-cli/builtin/skills/native_swarm/SKILL.md", + "locations": [{ "path": "/work/runtime/paperclip-runner/acpx/session-1/antigravity-home/antigravity-cli/antigravity-cli/builtin/skills/native_swarm/SKILL.md" }] }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1002", "name": "swarm", "kind": "other", "status": "in_progress", "title": "Run swarm", + "args": { "action": "title", "title": "Create and verify u1.txt and u2.txt" } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1003", "name": "swarm", "kind": "other", "status": "in_progress", "title": "Run swarm", + "args": { "action": "add", "name": "writer1", "workspace": "inherit", "brief": "Create a file named u1.txt in the current workspace directory containing exactly \"one\". Then post to the board: '@verifier [done] u1.txt written'." } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1004", "name": "read_board", "kind": "other", "status": "in_progress", "title": "Run read_board", "args": { "since": 0 } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1005", "name": "view_file", "kind": "read", "status": "in_progress", "title": "File u1.txt", + "locations": [{ "path": "u1.txt" }], "rawInput": { "AbsolutePath": "u1.txt" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1005", "name": "view_file", "kind": "read", "status": "failed", "title": "File ../../../../../../../../u1.txt", + "locations": [{ "path": "u1.txt" }], "rawInput": { "AbsolutePath": "u1.txt" }, + "rawOutput": "declaring permissions: failed to parse path: u1.txt must be an absolute path: path is not absolute" }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1006", "name": "view_file", "kind": "read", "status": "in_progress", "title": "File /work/task/u1.txt", + "locations": [{ "path": "/work/task/u1.txt" }], "rawInput": { "AbsolutePath": "/work/task/u1.txt" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1006", "name": "view_file", "kind": "read", "status": "completed", "title": "File /work/task/u1.txt", + "locations": [{ "path": "/work/task/u1.txt" }], "rawInput": { "AbsolutePath": "/work/task/u1.txt" } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1007", "name": "mcp_paperclip_paperclip_finish", "kind": "other", "status": "in_progress", + "title": "Run mcp_paperclip_paperclip_finish", "args": { "toolSummary": "Finish the task" }, "rawInput": { "toolSummary": "Finish the task" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1007", "name": "mcp_paperclip_paperclip_finish", "kind": "other", "status": "failed", + "title": "Run mcp_paperclip_paperclip_finish", "args": { "toolSummary": "Finish the task" }, "rawInput": { "toolSummary": "Finish the task" }, + "rawOutput": "Completion cites a workspace-only file that the user cannot download. Before finishing, use register_deliverable for requested file outputs." }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1008", "name": "run_command", "kind": "execute", "status": "in_progress", + "title": "shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt", "rawInput": { "CommandLine": "shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt", "Cwd": "/work/task" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1008", "name": "run_command", "kind": "execute", "status": "completed", + "title": "shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt", "rawInput": { "CommandLine": "shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt", "Cwd": "/work/task" } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1009", "name": "mcp_paperclip_register_deliverable", "kind": "other", "status": "in_progress", + "title": "Run mcp_paperclip_register_deliverable", "args": { "toolSummary": "Attach u1.txt" }, "rawInput": { "toolSummary": "Attach u1.txt" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1009", "name": "mcp_paperclip_register_deliverable", "kind": "other", "status": "completed", + "title": "Run mcp_paperclip_register_deliverable", "args": { "toolSummary": "Attach u1.txt" }, "rawInput": { "toolSummary": "Attach u1.txt" } }, + { "sessionUpdate": "tool_call", "toolCallId": "call_1010", "name": "mcp_paperclip_paperclip_finish", "kind": "other", "status": "in_progress", + "title": "Run mcp_paperclip_paperclip_finish", "args": { "toolSummary": "Finish the task" }, "rawInput": { "toolSummary": "Finish the task" } }, + { "sessionUpdate": "tool_call_update", "toolCallId": "call_1010", "name": "mcp_paperclip_paperclip_finish", "kind": "other", "status": "completed", + "title": "Run mcp_paperclip_paperclip_finish", "args": { "toolSummary": "Finish the task" }, "rawInput": { "toolSummary": "Finish the task" } } + ] +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 4be2761402a..09acd480368 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3154,4 +3154,4 @@ export * from "./tool-call-progress.js"; export * from "./mcp-skills.js"; export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscale.js"; export * from "./agent-setup-progress.js"; -export { parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js"; +export { antigravitySwarmAvailable, antigravitySwarmWorkModeAllows, isAntigravityAgent, parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js"; diff --git a/packages/shared/src/leading-user-command.ts b/packages/shared/src/leading-user-command.ts index a711a05c735..d4bea3d1d76 100644 --- a/packages/shared/src/leading-user-command.ts +++ b/packages/shared/src/leading-user-command.ts @@ -40,3 +40,29 @@ export function parseLeadingUserCommand( * front; the Paperclip Runner enforces the same bound on its own. */ export const SWARM_REQUEST_MAX_CHARS = 16_000; + +/** A Google Antigravity agent: the only kind of agent that runs a /swarm. */ +export function isAntigravityAgent(agent: { adapterType: string; adapterConfig: unknown } | null | undefined): boolean { + const config = agent?.adapterConfig !== null && typeof agent?.adapterConfig === "object" && !Array.isArray(agent.adapterConfig) + ? agent.adapterConfig as Record : {}; + return agent?.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity"; +} + +/** Helpers change files, so only a standard task runs a swarm (an allow-list; Plan, Ask and others never do). */ +export function antigravitySwarmWorkModeAllows(workMode: string | null | undefined): boolean { + return workMode === "standard"; +} + +/** + * Whether `/swarm` reaches this assignee as a swarm: a Google Antigravity agent, + * the instance's experimental Antigravity swarm setting on, and a standard + * task. The composer uses it for its hint; the server checks the same rule + * (and more, such as a remote environment) on send. + */ +export function antigravitySwarmAvailable( + agent: { adapterType: string; adapterConfig: unknown } | null | undefined, + experimental: { enableAntigravitySwarm?: boolean } | null | undefined, + workMode: string | null | undefined, +): boolean { + return experimental?.enableAntigravitySwarm === true && isAntigravityAgent(agent) && antigravitySwarmWorkModeAllows(workMode); +} diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 849b293fb22..fe78765782a 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -1158,6 +1158,12 @@ export interface IssueComment { deletedByRunId?: string | null; sourceTrust?: SourceTrustMetadata | null; followUpRequested?: boolean; + /** + * Server-derived and read-only: the user's message asked the assignee's + * native command (Google Antigravity's `/swarm`), as recorded by the server + * when it accepted the request. Never taken from comment text or metadata. + */ + nativeCommand?: "swarm"; createdAt: Date; updatedAt: Date; } diff --git a/server/src/__tests__/antigravity-swarm-request-path.test.ts b/server/src/__tests__/antigravity-swarm-request-path.test.ts index 1e442ec9074..540c109f622 100644 --- a/server/src/__tests__/antigravity-swarm-request-path.test.ts +++ b/server/src/__tests__/antigravity-swarm-request-path.test.ts @@ -3,7 +3,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; import { antigravitySwarmRequestText } from "../../../packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.js"; import { buildNativeModelEnvelope } from "../vendor/paperclip-runner/index.js"; -import { recordAntigravitySwarmRequest, resolveAntigravitySwarmRun } from "../services/antigravity-swarm.js"; +import { recordAntigravitySwarmRequest, resolveAntigravitySwarmRun, withAntigravitySwarmMarkers } from "../services/antigravity-swarm.js"; import { instanceSettingsService } from "../services/instance-settings.js"; import { buildNativeExecutionInput } from "../services/native-runtime/native-execution-input.js"; import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js"; @@ -80,4 +80,26 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => expect(sent).not.toContain(AGENT_COMMENT); expect(sent).not.toContain(DESCRIPTION); }); + + it("marks only the user's recorded request as a swarm, never from the comment's own text or metadata", async () => { + const [company] = await db.insert(companies).values({ name: "Swarm marker", issuePrefix: `M${randomUUID().slice(0, 4)}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); + const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Swarm", status: "todo", assigneeAgentId: agent!.id }).returning(); + const insert = (values: Partial) => db.insert(issueComments) + .values({ companyId: company!.id, issueId: issue!.id, authorType: "user", authorUserId: USER, body: "write a.txt", ...values }).returning().then(rows => rows[0]!); + const requested = await insert({}); + const ordinary = await insert({ body: "/swarm typed but not sent as a command", metadata: { nativeCommand: "swarm" } as never }); + const otherUser = await insert({ authorUserId: "someone-else" }); + const agentComment = await insert({ authorType: "agent", authorUserId: null, authorAgentId: agent!.id }); + await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id, commentId: requested.id, userId: USER }); + // A record by one user never marks another user's comment. + await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id, commentId: otherUser.id, userId: USER }); + await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id, commentId: agentComment.id, userId: USER }); + + const marked = await withAntigravitySwarmMarkers(db, company!.id, issue!.id, [requested, ordinary, otherUser, agentComment]); + expect(marked.map(comment => comment.nativeCommand)).toEqual(["swarm", undefined, undefined, undefined]); + // The record belongs to its task. + expect((await withAntigravitySwarmMarkers(db, company!.id, randomUUID(), [requested]))[0]!.nativeCommand).toBeUndefined(); + }); }); diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts index b08805f2739..66fd8f24682 100644 --- a/server/src/__tests__/issue-comment-reopen-routes.test.ts +++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts @@ -165,6 +165,9 @@ vi.mock("../services/access.js", () => ({ const mockSwarm = vi.hoisted(() => ({ refusal: vi.fn(async (): Promise => null), record: vi.fn(async () => undefined), + // Stands in for the stored request record: marks every comment it is given. + markers: vi.fn(async (_db: unknown, _companyId: string, _issueId: string, comments: Array>) => + comments.map(comment => ({ ...comment, nativeCommand: "swarm" }))), })); vi.mock("../services/antigravity-swarm.js", async () => ({ ...await vi.importActual("../services/antigravity-swarm.js"), @@ -172,6 +175,7 @@ vi.mock("../services/antigravity-swarm.js", async () => ({ ANTIGRAVITY_SWARM_UNAVAILABLE: "antigravity_swarm_unavailable", antigravitySwarmCommentRefusal: mockSwarm.refusal, recordAntigravitySwarmRequest: mockSwarm.record, + withAntigravitySwarmMarkers: mockSwarm.markers, })); vi.mock("../services/activity-log.js", () => ({ @@ -1321,6 +1325,7 @@ describe("issue comment reopen routes", () => { .post("/api/issues/11111111-1111-4111-8111-111111111111/comments") .send({ body: "two helpers write a.txt and b.txt", nativeCommand: "swarm" }); expect(res.status).toBe(201); + expect(res.body).toMatchObject({ id: "comment-1", nativeCommand: "swarm" }); // Written in the same transaction as the comment, so neither can exist without the other. expect(mockSwarm.record).toHaveBeenCalledWith(mockTx, expect.objectContaining({ commentId: "comment-1", userId: "local-board" })); expect(mockIssueService.addComment).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.anything(), expect.anything(), mockTx); @@ -1382,6 +1387,9 @@ describe("issue comment reopen routes", () => { .send({ body: "two helpers", nativeCommand: "swarm", clientRequestId: "77777777-7777-4777-8777-777777777777" }); expect(response.status).toBe(201); expect(response.body.id).toBe("comment-1"); + // The resent receipt carries the same marker as the first send, from the stored record. + expect(response.body.nativeCommand).toBe("swarm"); + expect(mockSwarm.markers).toHaveBeenCalledWith(expect.anything(), issue.companyId, issue.id, [expect.objectContaining({ id: "comment-1" })]); expect(mockSwarm.record).not.toHaveBeenCalled(); expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); }); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 8a7bd2b8d45..686d6f6d714 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -78,7 +78,7 @@ import { z } from "zod"; import { and, asc, desc, eq, inArray, isNull, notInArray, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import type { ChatChannelService } from "../services/chat-channels.js"; -import { ANTIGRAVITY_SWARM_COMMAND, ANTIGRAVITY_SWARM_UNAVAILABLE, antigravitySwarmCommentRefusal, antigravitySwarmRequestFromComment, antigravitySwarmRequestRefusal, recordAntigravitySwarmRequest } from "../services/antigravity-swarm.js"; +import { ANTIGRAVITY_SWARM_COMMAND, ANTIGRAVITY_SWARM_UNAVAILABLE, antigravitySwarmCommentRefusal, antigravitySwarmRequestFromComment, antigravitySwarmRequestRefusal, recordAntigravitySwarmRequest, withAntigravitySwarmMarkers } from "../services/antigravity-swarm.js"; import { activityLog, agentWakeupRequests, @@ -17452,7 +17452,8 @@ export function issueRoutes( limit, }); res.json( - await runRedactions.redactForIssue(issue.companyId, issue.id, comments), + await runRedactions.redactForIssue(issue.companyId, issue.id, + await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, comments)), ); }); @@ -18981,8 +18982,9 @@ export function issueRoutes( res.status(404).json({ error: "Comment not found" }); return; } + const [marked] = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, [comment]); res.json( - await runRedactions.redactForIssue(issue.companyId, issue.id, comment), + await runRedactions.redactForIssue(issue.companyId, issue.id, marked), ); }); @@ -19481,7 +19483,9 @@ export function issueRoutes( }), }); await externalObjectsSvc.syncCommentSafely(receipt.id); - res.status(201).json(receipt); + // A resent /swarm request answers with the same marker as its first send. + const [marked] = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, [receipt]); + res.status(201).json(marked); return; } } @@ -20442,7 +20446,11 @@ export function issueRoutes( await queueTaskWatchdogEvaluation(currentIssue, actor.runId); - res.status(201).json(comment); + // The swarm marker comes from the request record committed with the comment. + const [response] = swarmRequested + ? await withAntigravitySwarmMarkers(db, currentIssue.companyId, currentIssue.id, [comment]) + : [comment]; + res.status(201).json(response); }, ); diff --git a/server/src/services/antigravity-swarm-refusal.ts b/server/src/services/antigravity-swarm-refusal.ts index f207c3a6af6..294bc6f526d 100644 --- a/server/src/services/antigravity-swarm-refusal.ts +++ b/server/src/services/antigravity-swarm-refusal.ts @@ -16,9 +16,5 @@ export const ANTIGRAVITY_CLI_QUOTA_SCOPE = "antigravity_cli"; /** The activity a signed-in user's /swarm request records (the request's only proof). */ export const ANTIGRAVITY_SWARM_REQUESTED_ACTION = "issue.antigravity_swarm_requested"; -/** A Google Antigravity agent: the only kind of agent that runs a /swarm. */ -export function isAntigravityAgent(agent: { adapterType: string; adapterConfig: unknown } | null): boolean { - const config = agent?.adapterConfig !== null && typeof agent?.adapterConfig === "object" && !Array.isArray(agent.adapterConfig) - ? agent.adapterConfig as Record : {}; - return agent?.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity"; -} +/** A Google Antigravity agent: the only kind of agent that runs a /swarm (the one rule, packages/shared). */ +export { isAntigravityAgent } from "@paperclipai/shared"; diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index bd2fc659022..adfea2d4e97 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -1,5 +1,5 @@ import { and, desc, eq, gt, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; -import { SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; +import { antigravitySwarmWorkModeAllows, SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; import { activityLog, agentWakeupRequests, agents, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; import { logActivity } from "./activity-log.js"; import { instanceSettingsService } from "./instance-settings.js"; @@ -47,7 +47,7 @@ export function antigravitySwarmRefusal(input: { } if (!isAntigravityAgent(input.agent)) return "Swarm works only for tasks assigned to a Google Antigravity agent."; if (input.planning || input.workMode === "planning") return "Swarm is not available while the task is in Plan mode: helpers change files. Approve the plan first, then send /swarm."; - if (input.workMode !== undefined && input.workMode !== "standard") { + if (input.workMode !== undefined && !antigravitySwarmWorkModeAllows(input.workMode)) { return "Swarm works only in a standard task: helpers change files, and this task's mode does not allow changes. Switch the task to Standard, then send /swarm."; } if (input.remote) return "Swarm is not available for this agent: it runs only on this computer, not in a cloud or remote environment."; @@ -131,6 +131,21 @@ async function pendingSwarmCommentId(db: Db, companyId: string, issueId: string) return latest && !latest.deletedAt ? latest.id : null; } +/** + * Read-only `nativeCommand: "swarm"` on the comments that are recorded /swarm + * requests: the server's own activity record for that user and comment, never + * the comment's client-writable metadata or its text. + */ +export async function withAntigravitySwarmMarkers( + db: Db, companyId: string, issueId: string, comments: readonly T[], +): Promise> { + const candidates = comments.filter(comment => comment.authorUserId && !comment.authorAgentId).map(comment => comment.id); + if (candidates.length === 0) return [...comments]; + // The one definition of a recorded request (recordedSwarmRequestSql), read from the stored rows. + const requests = new Set(await recordedSwarmRequestIds(db, companyId, issueId, candidates)); + return comments.map(comment => requests.has(comment.id) ? { ...comment, nativeCommand: ANTIGRAVITY_SWARM_COMMAND } : comment); +} + export async function recordAntigravitySwarmRequest(db: Db, input: { companyId: string; issueId: string; commentId: string; userId: string }): Promise { await logActivity(db, { companyId: input.companyId, actorType: "user", actorId: input.userId, issueId: input.issueId, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 287de1fd78a..8d493c7e7bf 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -278,7 +278,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "4be2761402a84946e28007115841a01ba52ee0db", + "packages/shared/src/index.ts": "09acd480368d0cc4f0220b8b71296ca97e61dbbf", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -292,7 +292,7 @@ "packages/shared/src/issue-write-denial.test.ts": "e21b93aa79e6635c019ac338eff954ec618a98ed", "packages/shared/src/issue-write-denial.ts": "e6b4d72a83f6e4e76e85e34a80f88d1d69b7dfe4", "packages/shared/src/leading-user-command.test.ts": "3990464c95e6f7e1de078b817f3a296a50e53f78", - "packages/shared/src/leading-user-command.ts": "a711a05c7354ae1cfaa36f381e70aa5c33bbf87e", + "packages/shared/src/leading-user-command.ts": "d4bea3d1d76fcbf721f846f5adb47a58004a0497", "packages/shared/src/link-preview.test.ts": "136041c928343ad6272f43701b39cf95be255f3e", "packages/shared/src/link-preview.ts": "b7431d4c30a12067e80e6806728b3ae7c7541f8f", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", @@ -439,7 +439,7 @@ "packages/shared/src/types/index.ts": "60366f789182ba3a4fb6895f91454ec386988496", "packages/shared/src/types/instance.ts": "ddfef2455723757a5ecffaf3bab56ec47c287267", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "849b293fb2263ed41d9a0a74276534ad5c2ff7b8", + "packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", diff --git a/ui/src/adapters/paperclip-runner/index.ts b/ui/src/adapters/paperclip-runner/index.ts index 9f7168bc35f..5a767a317e9 100644 --- a/ui/src/adapters/paperclip-runner/index.ts +++ b/ui/src/adapters/paperclip-runner/index.ts @@ -3,6 +3,8 @@ import type { UIAdapterModule } from "../types"; import { parseCodexStdoutLine, buildPaperclipRunnerConfig } from "@paperclipai/adapter-codex-local/ui"; import { CodexLocalConfigFields } from "../codex-local/config-fields"; import { isRunLogOnlyProviderEvent } from "@/components/transcript/run-log-only-events"; +import { createBridgeCallPairing, type BridgeCallPairing } from "@/components/transcript/bridge-call-pairing"; +import { summarizeToolInput } from "@/components/task-chat/transcript-adapter"; type JsonRecord = Record; @@ -15,6 +17,28 @@ interface PaperclipRunnerParserState { structuredFinalItemIds: Set; runtimeRequests: Map>; previousPiRuntimeFailure: string | null; + bridgeCalls: BridgeCallPairing; + /** The latest row of each Paperclip tool call in flight, for a bridge call that joins it. */ + paperclipExecutions: Map; +} + +/** + * A bridge call that belongs to an in-flight provider call (bridge-call-pairing.ts) + * shows on that call's row: its start adds the subject, its result adds nothing. + */ +function pairedBridgeEntries(event: JsonRecord, item: JsonRecord, phase: "started" | "completed", state: PaperclipRunnerParserState): TranscriptEntry[] | null { + const type = text(item.type).replaceAll("_", "").toLowerCase(); + const id = type === "toolresult" ? text(item.tool_use_id, itemId(event, item)) : itemId(event, item); + const executionId = phase === "started" && type !== "toolresult" + ? state.bridgeCalls.bridgeCall(id, text(item.name, text(item.tool)) || null) + : state.bridgeCalls.pairedExecution(id); + if (!executionId) return null; + const row = state.paperclipExecutions.get(executionId); + // The same summary the settled row shows for these arguments ("u1.txt", a search query). + const subject = phase === "started" ? summarizeToolInput(item.input ?? item.arguments) : undefined; + if (!row || !subject) return []; + return [{ kind: "provider_activity", ts: row.ts, family: "tool_execution", eventType: row.eventType, status: "running", + title: "Tool execution", summary: row.summary, payload: { ...row.payload, subject } }]; } function itemChannel(payload: JsonRecord): "progress" | "final" | "summary" | "detail" | "unknown" { @@ -254,6 +278,10 @@ function parseItemEvent( return entries; } if (type === "filechange") return fileChangeEntries(event, item, phase, ts); + if (type === "dynamictoolcall" || type === "tooluse" || type === "toolresult") { + const paired = pairedBridgeEntries(event, item, phase, state); + if (paired) return paired; + } if (type === "dynamictoolcall") return dynamicToolEntries(event, item, phase, ts); if (type === "tooluse" || type === "toolresult" || type === "mcptoolcall") { return genericToolEntries(event, item, phase, ts); @@ -719,6 +747,14 @@ function parsePrpEvent( const summary = family === "model_identity" ? text(payload.summary, text(payload.effectiveModel, text(payload.requestedModel, text(payload.provider, eventType)))) : text(payload.summary, text(payload.name, text(payload.query, eventType))); + if (family === "tool_execution") { + state.bridgeCalls.execution(eventType, payload); + const executionId = text(payload.executionId); + if (executionId && payload.namespace === "paperclip") { + if (status === "running") state.paperclipExecutions.set(executionId, { ts, eventType, summary, payload }); + else state.paperclipExecutions.delete(executionId); + } + } return [{ kind: "provider_activity", ts, family, eventType, status, title, summary, payload }]; } if (eventType === "workspace.change.updated" || eventType === "workspace.diff.recorded") { @@ -793,6 +829,8 @@ function createParserState(): PaperclipRunnerParserState { structuredFinalItemIds: new Set(), runtimeRequests: new Map(), previousPiRuntimeFailure: null, + bridgeCalls: createBridgeCallPairing(), + paperclipExecutions: new Map(), }; } diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index aba8fecc53a..e48d3ee3f6d 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -30,6 +30,7 @@ import { CoordinatorPresentation } from "./coordinator/CoordinatorPresentation"; import type { HeartbeatRunEvent } from "@paperclipai/shared"; import type { HeartbeatRun } from "@paperclipai/shared"; import { waitForStoppedRuns } from "@/lib/wait-for-stopped-runs"; +import { ApiError } from "@/api/api-error"; const transcriptState = vi.hoisted(() => ({ transcriptByRun: new Map(), @@ -639,6 +640,35 @@ it.each((["task", "legacy"] as const).flatMap(surface => } }); +it("marks a message the server recorded as a /swarm request, and no other", () => { + const comment = (id: string, body: string, nativeCommand?: "swarm") => ({ id, companyId: "company", issueId: "issue", authorType: "user" as const, + authorAgentId: null, authorUserId: "board", body, presentation: null, metadata: null, ...(nativeCommand ? { nativeCommand } : {}), + createdAt: new Date("2026-11-25T05:51:00Z"), updatedAt: new Date("2026-11-25T05:51:00Z") }); + render( {}} />); + const markers = [...container.querySelectorAll('[data-testid="task-chat-swarm-marker"]')]; + expect(markers.map(marker => marker.textContent)).toEqual(["Swarm"]); + expect(markers[0]!.closest("[data-conversation-message]")?.textContent).toContain("Create u1.txt and u2.txt"); +}); + +it("explains a refused send under the composer until dismissed, and clears the optimistic Working row", async () => { + let refuse!: (error: unknown) => void; + const onAdd = vi.fn["onAdd"]>(() => new Promise((_, reject) => { refuse = reject; })); + const message = "Swarm is not available while the task is in Plan mode: helpers change files. Approve the plan first, then send /swarm."; + render(); + await act(async () => { editorCallbacks.change("do something"); }); + await act(async () => { container.querySelector('[data-testid="task-chat-composer-send"]')!.click(); }); + // Sends stay instant: the Working row appears before the server answers. + expect(container.textContent).toContain("Working"); + await act(async () => { refuse(new ApiError(message, 422, { error: message })); }); + expect(container.textContent).not.toContain("Working"); + const error = () => container.querySelector('[data-testid="task-chat-goal-error"]'); + expect(error()?.textContent).toBe(message); + await act(async () => { container.querySelector('[data-testid="task-chat-composer-error-dismiss"]')!.click(); }); + expect(error()).toBeNull(); +}); + it.each((["task", "legacy"] as const).flatMap(surface => ["done", "cancelled", "old-intent"].map(previous => ({ surface, previous })), ))("keeps $surface follow-up identity while $previous state catches up", async ({ surface, previous }) => { @@ -1480,6 +1510,29 @@ describe("TaskChatThread draft pass-through", () => { expect(container.textContent).toContain("Keep this image context"); }); + it("shows a run's prepared text file once, as its file card, without the generated receipt", async () => { + type Props = ComponentProps; + const attachmentId = "00000000-0000-4000-8000-000000000011"; + const at = new Date("2026-11-25T05:51:50Z"); + const workProducts = [{ + id: "file-1", type: "artifact", provider: "paperclip", title: "u1.txt", status: "active", reviewState: "none", healthStatus: "unknown", + createdByRunId: "swarm-run", createdAt: at, updatedAt: at, + metadata: { attachmentId, originalFilename: "u1.txt", contentType: "text/plain", byteSize: 3, contentPath: `/api/attachments/${attachmentId}/content`, openPath: `/api/attachments/${attachmentId}/content`, downloadPath: `/api/attachments/${attachmentId}/content?download=1` }, + }] as unknown as NonNullable; + const attachments = [{ id: attachmentId, issueCommentId: "receipt-1", originatingRunId: "swarm-run", createdByAgentId: "agent", + originalFilename: "u1.txt", contentType: "text/plain", contentPath: `/api/attachments/${attachmentId}/content`, createdAt: at, updatedAt: at, byteSize: 3, + }] as unknown as NonNullable; + const receipt = { + id: "receipt-1", body: "Prepared u1.txt for this response.", companyId: "company", issueId: "issue", authorType: "agent" as const, + authorAgentId: "agent", authorUserId: null, createdByRunId: "swarm-run", createdAt: new Date(at.getTime() + 100), updatedAt: at, presentation: null, + metadata: { version: 1 as const, sections: [], authorizationReason: "paperclip_runner_protocol", attachmentPreparation: { attachmentId } }, + }; + render( {}} issueStatus="done" />); + await settleThreadLayout(); + expect(container.textContent).not.toContain("Prepared u1.txt for this response."); + expect(container.textContent).toContain("u1.txt"); + }); + 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 6009143e519..1e5e8a8b608 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -4,7 +4,7 @@ import { presentationDecisionCommentId, semanticProgressCommentIds, } from "@/lib/run-answer-visibility"; -import { imagePreparationReceiptIds } from "./task-chat/image-resources"; +import { preparationReceiptIds } from "./task-chat/image-resources"; import type { ScrollingHistory } from "@/components/task-chat/TaskMessageScroller"; import { TaskChatShimmerScope } from "@/components/task-chat/TaskChatShimmer"; import { useRunnerSubmission } from "@/hooks/useRunnerSubmission"; @@ -899,7 +899,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { // prefers the accepted semantic result so runs such as DOT-20 recover their // real upstream response without a data migration. const imageReceipts = useMemo( - () => imagePreparationReceiptIds(comments, attachments, workProducts), + () => preparationReceiptIds(comments, attachments, workProducts), [comments, attachments, workProducts], ); const projectedComments = useMemo( diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx index 56f4177d7e2..60e1c8f0a26 100644 --- a/ui/src/components/task-chat/TaskChatBubble.tsx +++ b/ui/src/components/task-chat/TaskChatBubble.tsx @@ -201,6 +201,22 @@ function TaskChatBubbleContent({ const isHuman = item.author === "human"; const isOwnMessage = isHuman && item.isCurrentUser === true; const sentFromIMessage = isHuman && item.sourceChannel === "imessage-photon"; + // Short notes before the timestamp: the message ran as a swarm, or came from iMessage. + const footerNotes = [ + isHuman && item.nativeCommand === "swarm" ? "Swarm" : null, + sentFromIMessage ? "Sent from iMessage" : null, + ].filter((note): note is string => note !== null); + const footerLine = ( + <> + {footerNotes.map((note, index) => ( + + {index > 0 ? " · " : null}{note} + + ))} + {footerNotes.length > 0 && timestamp ? " · " : null} + {timestamp} + + ); // Non-image file references ("[name](/api/attachments/…/content)") render as // attachment chips under the bubble; link-only lines leave the body text. const { refs: linkedRefs, text: bodyWithoutAttachmentLinks } = @@ -439,9 +455,7 @@ function TaskChatBubbleContent({ - {sentFromIMessage ? "Sent from iMessage" : null} - {sentFromIMessage && timestamp ? " · " : null} - {timestamp} + {footerLine} ) : actions ? ( @@ -464,12 +478,10 @@ function TaskChatBubbleContent({ ) : null} ) - ) : timestamp || sentFromIMessage ? ( + ) : timestamp || footerNotes.length > 0 ? ( // Timestamps are always visible (round 9) — no longer hover-revealed. - {sentFromIMessage ? "Sent from iMessage" : null} - {sentFromIMessage && timestamp ? " · " : null} - {timestamp} + {footerLine} ) : null} {artifactsV1 && imageRefs.length + attachmentRefs.length > 0 ? ( diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index 1ca49a6bb1b..af2f5b2adc2 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -2024,6 +2024,27 @@ describe("TaskChatComposer", () => { expect(onAdd).toHaveBeenCalledWith("two helpers write a.txt and b.txt", undefined, undefined, undefined, expect.any(String), undefined, "swarm"); }); + it.each([ + ["an Antigravity assignee with swarm on", "antigravity", true, true, "standard", "/swarm write a.txt"], + ["swarm turned off", "antigravity", false, false, "standard", "/swarm write a.txt"], + ["another kind of agent", "claude", true, false, "standard", "/swarm write a.txt"], + ["a bare /swarm with no request", "antigravity", true, false, "standard", "/swarm"], + ["a task in Plan mode", "antigravity", true, false, "planning", "/swarm write a.txt"], + ["a task in Ask mode", "antigravity", true, false, "ask", "/swarm write a.txt"], + ] as const)("hints that /swarm starts a swarm only for %s", (_case, acpxAgent, enabled, hinted, workMode, text) => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(queryKeys.instance.experimentalSettings, { enableAntigravitySwarm: enabled }); + const agent = { id: "agent-1", name: "Gemma", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent } } as unknown as Agent; + render( + + ); + const hint = () => container.querySelector('[data-testid="task-chat-swarm-hint"]'); + typeText("write a.txt"); + expect(hint()).toBeNull(); + typeText(text); + expect(Boolean(hint())).toBe(hinted); + }); + it("asks for a request instead of sending a bare /swarm", async () => { const onAdd = vi.fn().mockResolvedValue(undefined); renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() }); diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index 1c6220c36a9..ce05e5a9686 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -32,7 +32,7 @@ import { type ComposerSendRequest, } from "@/lib/composer-draft"; import { classifySendFailure, type SendOutcome } from "@/lib/pending-send"; -import { describeError } from "@/api/errors"; +import { describeError, errorStatus } from "@/api/errors"; import { useAutoResend } from "@/hooks/useDurableSubmit"; import { useDraftOwner } from "@/hooks/useDraftOwner"; import { useRequestOwnerBinding } from "@/hooks/useRequestOwnerBinding"; @@ -72,7 +72,8 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import type { MentionOption } from "@/components/MarkdownEditor"; import type { IssueAttachment, IssueWorkMode } from "@paperclipai/shared"; import type { RunnerGoalCapability } from "@paperclipai/shared"; -import { SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; +import { antigravitySwarmAvailable, SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; +import { useAntigravitySwarmSetting } from "@/hooks/useAntigravitySwarmSetting"; import { parseRunnerGoalCommand, parseSwarmCommand, planSubmission, swarmRunSettingsRefusal, type RunnerGoalComposerCommand } from "./composer-commands"; import type { ActionCommandOption } from "@/context/EditorAutocompleteContext"; import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeoverContext"; @@ -618,6 +619,12 @@ export function TaskChatComposer({ ); const assigneeValue = creation || conversationMode ? currentAssigneeValue : pendingAssignee ?? suggestedAssigneeValue ?? currentAssigneeValue; const showConversationModel = coordinator && conversationMode && supportsComposerModel(modelAgents?.get(assigneeValue.slice(6))); + const swarmSetting = useAntigravitySwarmSetting(); + // A light hint that the message will start a swarm (the server decides on send). + // A bare /swarm is refused on send, so it gets no hint. + const showSwarmHint = !creation && !queuedEdit && !conversationMode && assigneeValue.startsWith("agent:") && + antigravitySwarmAvailable(modelAgents?.get(assigneeValue.slice(6)), swarmSetting, pendingMode) && + Boolean(parseSwarmCommand(body)?.request); const assigneeLabel = reassignOptions?.find((o) => o.id === assigneeValue)?.label ?? "Unassigned"; const assigneeName = @@ -1049,6 +1056,8 @@ export function TaskChatComposer({ setBody(""); setSendingAttachmentIds(new Set(submittedAttachments.map(item => item.id))); setSubmitting(true); + // A new send replaces the previous refusal. + setActionError(null); let attemptId: string | null = null; let request: ComposerSendRequest | null = null; const requestOwner = draftOwner; @@ -1150,6 +1159,13 @@ export function TaskChatComposer({ saveDraftSubmission(draftKey, uncertain); } else if (draftKey && attemptId) clearDraftSubmission(draftKey, attemptId); + // A refusal (for example /swarm while the task is in Plan mode) stays + // under the restored text until dismissed or the next send; a toast alone + // disappears before it can be read. + const status = errorStatus(error); + if (status !== null && status >= 400 && status < 500 && classifySendFailure(error) === "rejected") { + setActionError(describeError(error).body); + } // Restore the failed message for retry without discarding a next draft // that was entered while the request was pending. const restoredBody = nextDraft @@ -1461,12 +1477,29 @@ export function TaskChatComposer({ {actionError ? ( -

- {actionError} +

+

+ {actionError} +

+ +
+ ) : showSwarmHint ? ( +

+ Sends as a swarm: helpers work on this together in the task folder.

) : null} diff --git a/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx b/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx index 852fcea5671..aba80124329 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 { toolActivityPresentation, type ToolIcon } from "./tool-taxonomy"; +import { retriedLabel, SUBJECT_FAMILIES, subjectRowLabel, toolActivityPresentation, type ToolIcon } from "./tool-taxonomy"; import { useTaskChatShimmer } from "./TaskChatShimmer"; import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView"; import { useTaskReferenceLabel, withTaskReference } from "./task-reference"; @@ -40,8 +40,6 @@ import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type Activity = TaskChatActivityPhaseItem["items"][number]; type ToolActivity = Extract; -/** Families whose rows read as " ", for example "Ran $ node --test". */ -const SUBJECT_FAMILIES = new Set(["terminal", "read", "edit", "grep", "search", "web"]); const READ_RUN_MIN = 3; /** "120ms", "1.2s", "14s", "2m 03s". */ @@ -114,7 +112,7 @@ function presentation(item: Activity, active: boolean, taskLabel?: string): Acti active && (item.status === "pending" || item.status === "in_progress"); const label = item.status === "failed" - ? tool.failedLabel + ? item.retried ? retriedLabel(tool.failedLabel) : tool.failedLabel : item.status === "interrupted" ? tool.interruptedLabel : running @@ -125,12 +123,9 @@ function presentation(item: Activity, active: boolean, taskLabel?: string): Acti // With a concrete subject, the verb alone reads better: "Read README.md". // 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. - const marker = item.status === "failed" || item.status === "interrupted" ? label.split(" · ").at(1) : undefined; + // chip already says how a command ended. Live rows use the same helper. const verb = subject && SUBJECT_FAMILIES.has(tool.family) - ? terminal && !running && (item.status === "completed" || item.exitCode != null) - ? "" - : `${label.split(" ")[0]!}${marker ? ` · ${marker}` : ""}` + ? 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; diff --git a/ui/src/components/task-chat/antigravity-thread.test.tsx b/ui/src/components/task-chat/antigravity-thread.test.tsx new file mode 100644 index 00000000000..f2d5b2cf2f7 --- /dev/null +++ b/ui/src/components/task-chat/antigravity-thread.test.tsx @@ -0,0 +1,121 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import swarmRun from "../transcript/fixtures/antigravity-swarm-run.json"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it } from "vitest"; +import type { HeartbeatRunEvent } from "@paperclipai/shared"; +import { paperclipRunnerUIAdapter } from "@/adapters/paperclip-runner"; +import type { TranscriptEntry } from "@/adapters"; +import { nativeRunEventsToTranscript } from "@/components/transcript/native-run-events"; +import { TaskChatRunnerActivityGroup } from "./TaskChatRunnerActivityGroup"; +import type { TaskChatActivityPhaseItem } from "./task-chat-model"; +import { markRetriedTools, paperclipRunnerActivityItems, transcriptToTaskChatItems } from "./transcript-adapter"; + +/** One live Antigravity /swarm run's tool, bridge-call and final-message events (see the fixture's provenance). */ +const fixture = swarmRun as unknown as { runId: string; events: HeartbeatRunEvent[] }; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +/** The activity rows a person reads, as "