fix(antigravity): make the task thread read in plain language (#22886)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task thread shows what an agent did during a run, as a list of
activity rows under its reply
> - Google Antigravity runs (ordinary and `/swarm`) send no tool
identity, so each row was named after the CLI's display title
> - Users saw rows like "Ran a command · failed Run
mcp_paperclip_paperclip_finish", "Ran File runtime paperclip runner acpx
…", lowercased sentences, and a sha256 dump
> - Each attached file also showed twice, nothing marked a message as a
swarm request, and a refused send only showed a short toast
> - This pull request gives Antigravity tool calls the identity other
harnesses send, and makes the thread read the same live and after the
run
> - The benefit is a task thread that reads in plain language for
Antigravity, with fixes that also help other harnesses

## Linked Issues or Issue Description

**What happened?**
In a live Antigravity `/swarm` run, the task thread showed raw tool
names and internal paths. Examples: "Run mcp_paperclip_paperclip_finish
· failed", "Ran File runtime paperclip runner acpx 5230… antigravity
home … SKILL md", "Ran Swarm started in the task folder with gemini 3 8
flash low …" (lowercased, punctuation removed), "Registered title:
u1.txt, sha256: 7692…". The live list and the finished list used
different words. The CLI's first reads of u1.txt failed ("must be an
absolute path") and were read again successfully, but the thread showed
"failed". Each file showed twice: a file card, and an agent message
"Prepared u1.txt for this response." with a second card. The user's
bubble did not show that the message was a swarm request. When the
server refused a send (for example `/swarm` in Plan mode), only a short
toast explained it.

**Expected behavior**
Rows say what the agent did in plain words, the same while live and
after the run. No raw tool names, internal paths, hashes or key/value
dumps. The refused-then-accepted completion call is hidden as for every
other harness. A failure that a later call recovered reads as "retried".
Each file shows once. A swarm request has a small "Swarm" marker. A
refused send keeps an inline, dismissible error under the composer.

**Steps to reproduce**
1. Assign a task to a Google Antigravity agent with the experimental
swarm setting on.
2. Send `/swarm Create u1.txt containing "one" and u2.txt containing
"two", one helper per file, then verify both.`
3. Expand the activity list while the run is live, and again after it
finishes.
4. Put another task in Plan mode and send `/swarm do something`.

## What Changed

- Runner (Antigravity-owned): new `antigravity-tool-identity.ts` names
each call. Paperclip bridge tools become
`mcp__paperclip__<canonicalRunnerToolName(tool)>` (from the CLI's
`mcp_paperclip_<tool>`, an ordinary run's `paperclip_<tool>` title, or
ACP `_meta.mcp`). Native CLI tools keep their own names (`run_command`,
`view_file`, …) with the command as the subject. Reads of the CLI's own
built-in files (its private Antigravity home) are dropped. Swarm
progress lines get one neutral identity (`swarm_update`) whose subject
is the plain sentence. Swarm file locations are task-relative.
- Runner: a narrow activity-adapter hook (`createToolEventProjection`)
applies this in both places that pump an ACPX turn (in-process driver
and sidecar). The sidecar now keeps a provider-supplied tool detail
instead of overwriting it.
- UI: live rows use the call's subject, drop raw technical names
(Paperclip's own tools need no source label), and use the same "verb +
subject" form as settled rows, so both lists read the same.
- UI: a bridge call recorded under its own id (providers that pass no
tool-use id) joins the provider's row for the same Paperclip tool, in
the live log and in stored events. `register_deliverable` reads
"Attached u1.txt"; content digests never show in an input summary.
- UI: a failed call whose later call of the same tool on the same target
succeeded shows as "· retried" (token-only, same muted style).
Unrecovered failures stay "· failed".
- UI: generated "Prepared <file> for this response." receipts are hidden
for any file that already shows as the run's file card (before, only
images).
- Server + shared + UI: `IssueComment.nativeCommand` ("swarm") is
derived read-only from the server's own activity record on comment list,
get and the POST response. The user's bubble shows a small "Swarm" note.
The `/swarm` eligibility rule (`isAntigravityAgent`,
`antigravitySwarmAvailable`) now lives in `packages/shared`; the
composer shows a light hint when the text starts with `/swarm` and the
assignee can run a swarm.
- UI: the composer keeps the server's message as an inline, dismissible
error after any 4xx refusal, until dismissed or the next send. The
optimistic "Working" row behaviour is unchanged.

Not changed, by design: after a reload, a settled run's activity is
deferred behind "More run output" for every native harness (cold-load
speed), so Antigravity already matches the others.

## Verification

- Red/green runner test `antigravity-tool-identity.test.ts` with a
fixture rebuilt from a live swarm run's updates (ids, paths and hashes
replaced): names, subjects, dropped internal reads, hidden finish
identity, ordinary-run titles and `_meta.mcp`.
- Red/green UI test `antigravity-thread.test.tsx` renders the real run's
stored events (settled) and the same events through the live run-log
parser. It asserts the exact rows, "retried" reads, one "Attached" row
per file, no finish rows, no raw names/paths/hashes, and live ==
settled. It fails on master (raw "Ran Swarm update …", "Read · failed",
"Registered title: …, sha256: …").
- Red/green `TaskChatThread.test.tsx`: a prepared text file shows once;
a refused send shows the server message inline until dismissed and the
Working row clears; only a server-marked comment shows "Swarm".
- `TaskChatComposer.test.tsx`: the `/swarm` hint shows only for an
Antigravity assignee with the setting on.
- Server `antigravity-swarm-request-path.test.ts` (embedded Postgres):
only the user's recorded request is marked; text, metadata, another
user's or an agent's comment are not.
- Local: paperclip-runner acpx/sidecar/provider-events suites, UI
task-chat/transcript/adapters/thread/hooks suites (1630 tests), server
swarm suite, and shared/server/ui/runner typechecks pass. `pnpm verify`
exited 2 (broad input), so CI supplies the broad coverage.

Before (live swarm run, done state):

```
Ran This swarm runs on the google account of this agent s google connection
Ran File runtime paperclip runner acpx 523076a3 3689 4b28 9910 c101bc6b64d8 97d9fb76f6aa11b6 a…
Ran File u1 txt · failed  u1.txt
Ran a command · failed
Registered title: u1.txt, sha256: 7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0…
```

After (same events, settled and live):

```
Swarm  This swarm runs on the Google account of this agent's Google connection.
Swarm  Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly "one"
Read · retried  u1.txt
Read  u1.txt
$ shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt
Attached  u1.txt
Swarm  Files changed in the task folder: u1.txt, u2.txt
```

## Risks

- Live tool rows for all harnesses no longer show a raw technical name
("Paperclip · search_tasks", "Bash") next to the activity. Rows with a
concrete subject now read like settled rows ("Read README.md", "$ npm
test"). This is a deliberate wording change.
- `register_deliverable` reads "Attached <file>" for all harnesses.
- Generated file receipts are hidden for any file with its own card, not
only images. Human text and agent progress with attachments stay visible
(the same marker and link checks as for images).
- Bridge-call pairing is display only and matches only a Paperclip tool
of the same name that is in flight. Claude already shares one id and is
unchanged.
- One extra indexed activity-log query per comment list or get. No
schema change.

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

## Model Used

- 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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 01:45:06 -06:00
1 parent f1dd9288d1
commit 3fbf872d9e
39 files changed
+3644 -91

No files matched your search

@@ -766,9 +766,13 @@ function createRuntimeEventStep(
const trackSubagents = initializedAgent === "claude"
? createClaudeSubagentLineageTracker<AcpRuntimeEventShape>((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)
@@ -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<string, unknown> =>
@@ -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(): <T extends { type: string }>(event: T) => T | null {
const hidden = new Set<string>();
return <T extends { type: string }>(event: T): T | null => {
if (event.type !== "tool_call") return event;
const value = event as unknown as Record<string, unknown>;
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<AcpxActivityAdapter>({
createToolEventProjection: createAntigravityToolEventProjection,
usageNotice: (before, after, requestId, turnId) => antigravitySwarmReceiptNotice(before, after, requestId, `${turnId}:antigravity-swarm-receipt`),
});
@@ -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", () => {
@@ -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;
}
@@ -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;
@@ -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<string, unknown>[];
};
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<AcpRuntimeEventShape | null>): ToolPayload[] {
const normalize = createAcpxToolEventNormalizer<AcpRuntimeEventShape>({ 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 `<server>_<tool>` 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();
});
});
@@ -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__<tool>`, 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<string, unknown>;
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 `<server>_<tool>`; the CLI says `Run mcp_<server>_<tool>`. */
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<Record<string, string>> = { 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) } : {}) };
}
@@ -1521,8 +1521,11 @@ class CodexAcpxSession implements HarnessSession {
const trackSubagents = this.#agent === "claude"
? createClaudeSubagentLineageTracker<AcpRuntimeEvent>(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);
@@ -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?(): <T extends { type: string }>(event: T) => T | null;
toolExecutionId?(nativeId: string): string;
inputToolIdentity?(input: AcpxExtensionInput): string | undefined;
createToolEvidence?(binding: AcpxToolEvidenceBinding): AcpxToolEvidence;
@@ -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" } }
]
}
+1 -1
View File
@@ -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";
@@ -40,3 +40,29 @@ export function parseLeadingUserCommand<Name extends string>(
* 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<string, unknown> : {};
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);
}
+6
View File
@@ -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;
}
@@ -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<typeof issueComments.$inferInsert>) => 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();
});
});
@@ -165,6 +165,9 @@ vi.mock("../services/access.js", () => ({
const mockSwarm = vi.hoisted(() => ({
refusal: vi.fn(async (): Promise<string | null> => 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<Record<string, unknown>>) =>
comments.map(comment => ({ ...comment, nativeCommand: "swarm" }))),
}));
vi.mock("../services/antigravity-swarm.js", async () => ({
...await vi.importActual<object>("../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();
});
+13 -5
View File
@@ -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);
},
);
@@ -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<string, unknown> : {};
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";
+17 -2
View File
@@ -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<T extends { id: string; authorUserId: string | null; authorAgentId: string | null }>(
db: Db, companyId: string, issueId: string, comments: readonly T[],
): Promise<Array<T & { nativeCommand?: typeof ANTIGRAVITY_SWARM_COMMAND }>> {
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<void> {
await logActivity(db, {
companyId: input.companyId, actorType: "user", actorId: input.userId, issueId: input.issueId,
@@ -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",
+38
View File
@@ -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<string, unknown>;
@@ -15,6 +17,28 @@ interface PaperclipRunnerParserState {
structuredFinalItemIds: Set<string>;
runtimeRequests: Map<string, Extract<TranscriptEntry, { kind: "runtime_request" }>>;
previousPiRuntimeFailure: string | null;
bridgeCalls: BridgeCallPairing;
/** The latest row of each Paperclip tool call in flight, for a bridge call that joins it. */
paperclipExecutions: Map<string, { ts: string; eventType: string; summary: string; payload: JsonRecord }>;
}
/**
* 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(),
};
}
+53
View File
@@ -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(<TaskChatThread comments={[comment("swarm", "Create u1.txt and u2.txt", "swarm"), comment("plain", "/swarm pasted as text")]}
issueId="issue" issueStatus="done" onAdd={async () => {}} />);
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<ComponentProps<typeof TaskChatThread>["onAdd"]>(() => new Promise<void>((_, 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(<TaskChatThread comments={[]} issueId="issue" issueAssigneeAgentId="agent" currentAssigneeValue="agent:agent" issueStatus="todo" onAdd={onAdd}
agentMap={new Map([["agent", { id: "agent", name: "Worker", adapterType: "paperclip_runner" } as Agent]])} />);
await act(async () => { editorCallbacks.change("do something"); });
await act(async () => { container.querySelector<HTMLButtonElement>('[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<HTMLButtonElement>('[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<typeof TaskChatThread>;
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<Props["workProducts"]>;
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<Props["attachments"]>;
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(<TaskChatThread comments={[receipt]} workProducts={workProducts} attachments={attachments} onAdd={async () => {}} 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: [
+2 -2
View File
@@ -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(
+19 -7
View File
@@ -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) => (
<span key={note} data-testid={note === "Swarm" ? "task-chat-swarm-marker" : undefined}>
{index > 0 ? " · " : null}{note}
</span>
))}
{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({
<TaskChatBubbleActions copyText={item.text} />
</div>
<span className="px-1 text-(length:--text-micro) text-muted-foreground">
{sentFromIMessage ? "Sent from iMessage" : null}
{sentFromIMessage && timestamp ? " · " : null}
{timestamp}
{footerLine}
</span>
</div>
) : actions ? (
@@ -464,12 +478,10 @@ function TaskChatBubbleContent({
) : null}
</div>
)
) : timestamp || sentFromIMessage ? (
) : timestamp || footerNotes.length > 0 ? (
// Timestamps are always visible (round 9) — no longer hover-revealed.
<span className="px-1 text-(length:--text-micro) text-muted-foreground">
{sentFromIMessage ? "Sent from iMessage" : null}
{sentFromIMessage && timestamp ? " · " : null}
{timestamp}
{footerLine}
</span>
) : null}
{artifactsV1 && imageRefs.length + attachmentRefs.length > 0 ? (
@@ -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(<QueryClientProvider client={client}>
<TaskChatComposer onAdd={vi.fn()} workMode={workMode} currentAssigneeValue="agent:agent-1" modelAgents={new Map([["agent-1", agent]])} />
</QueryClientProvider>);
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() });
@@ -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({
</div>
{actionError ? (
<p
className="px-1 text-xs text-destructive"
role="alert"
data-testid={creation ? "task-chat-create-error" : queuedEdit ? "task-chat-queued-edit-error" : "task-chat-goal-error"}
>
{actionError}
<div className="flex items-start gap-1 px-1">
<p
className="min-w-0 flex-1 text-xs text-destructive"
role="alert"
data-testid={creation ? "task-chat-create-error" : queuedEdit ? "task-chat-queued-edit-error" : "task-chat-goal-error"}
>
{actionError}
</p>
<Button
type="button"
variant="ghost"
size="icon-xs"
className="shrink-0 text-muted-foreground"
aria-label="Dismiss"
data-testid="task-chat-composer-error-dismiss"
onClick={() => setActionError(null)}
>
<X aria-hidden />
</Button>
</div>
) : showSwarmHint ? (
<p className="px-1 text-xs text-muted-foreground" data-testid="task-chat-swarm-hint">
Sends as a swarm: helpers work on this together in the task folder.
</p>
) : null}
@@ -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<Activity, { kind: "tool" }>;
/** Families whose rows read as "<verb> <subject>", 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;
@@ -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 "<label> <subject>". */
function renderedRows(entries: TranscriptEntry[]): string[] {
const items = paperclipRunnerActivityItems(transcriptToTaskChatItems(entries, { runId: fixture.runId, running: false }));
const phase: TaskChatActivityPhaseItem = {
id: "phase-1",
kind: "activity_phase",
items: items as TaskChatActivityPhaseItem["items"],
summary: "",
active: false,
};
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
act(() => root!.render(<TaskChatRunnerActivityGroup item={phase} defaultExpanded />));
const rows = [...container.querySelectorAll("[data-activity-row]")].map((row) => {
const text = row.querySelector("[data-activity-icon] + span");
return [...(text?.children ?? [])].map((part) => part.textContent?.trim()).filter(Boolean).join(" ");
});
act(() => root!.unmount());
container.remove();
root = null;
return rows;
}
/** The same events as the run log streams them while the run is live. */
function liveEntries(): TranscriptEntry[] {
const parser = paperclipRunnerUIAdapter.createStdoutParser!();
return fixture.events.flatMap((event) => parser.parseLine(
JSON.stringify({ type: "paperclip.prp.event", event: (event.payload as { prpEvent: unknown }).prpEvent }),
event.createdAt as unknown as string,
));
}
describe("an Antigravity swarm run's task thread", () => {
const settled = () => renderedRows(nativeRunEventsToTranscript(fixture.events));
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",
// 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",
"$ 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",
]);
});
it("hides the finish tool, including the attempt Paperclip refused", () => {
expect(settled().join("\n")).not.toMatch(/finish|completion|· failed/i);
});
it("reads the same while the run is live", () => {
expect(renderedRows(liveEntries())).toEqual(settled());
});
it("shows a paired bridge call's arguments live, as the settled row does", () => {
const parser = paperclipRunnerUIAdapter.createStdoutParser!();
const line = (event: Record<string, unknown>) => parser.parseLine(JSON.stringify({ type: "paperclip.prp.event", event }), "2026-11-25T05:51:00Z");
line({ eventType: "tool.execution.started", itemId: "item-1", payload: { schema: "paperclip.tool.execution.v1", executionId: "call_1",
name: "search_tasks", namespace: "paperclip", transport: "mcp", operation: "search", status: "running" } });
const paired = line({ eventType: "item.started", itemId: "7", payload: { kind: "dynamicToolCall",
item: { id: "7", type: "tool_use", name: "search_tasks", input: { query: "open bugs", limit: 5 } } } });
expect(paired).toEqual([expect.objectContaining({ kind: "provider_activity", payload: expect.objectContaining({ executionId: "call_1", subject: "open bugs" }) })]);
});
it("never calls a failure retried when the shortened subjects only look alike", () => {
const tool = (id: string, status: "failed" | "completed", target: string) =>
({ id, kind: "tool", name: "run_command", status, target }) as Parameters<typeof markRetriedTools>[0][number];
const clipped = `${"x".repeat(399)}…`;
expect(markRetriedTools([tool("a", "failed", clipped), tool("b", "completed", clipped)])[0]).not.toHaveProperty("retried");
expect(markRetriedTools([tool("a", "failed", "npm test"), tool("b", "completed", "npm test")])[0]).toHaveProperty("retried", true);
});
it("never shows raw tool names, internal paths or hashes", () => {
const text = [...settled(), ...renderedRows(liveEntries())].join("\n");
expect(text).not.toMatch(/mcp_|paperclip_|register_deliverable|view_file|run_command|swarm_update|\.\.\/|antigravity-home|sha256|[0-9a-f]{40}/);
});
});
+14 -9
View File
@@ -4,28 +4,33 @@ import type { TaskChatItem, TaskChatMaterializedResourceItem } from "./task-chat
import type { IssueAttachment, IssueWorkProduct } from "@paperclipai/shared";
import type { IssueChatComment } from "@/lib/issue-chat-messages";
export function imagePreparationReceiptIds(
/**
* Generated "Prepared <file> for this response." receipts whose file already
* shows as the run's own card (an image tile or a file row). The receipt and
* its attachment would repeat that file, so the thread hides them.
*/
export function preparationReceiptIds(
comments: readonly IssueChatComment[], attachments: readonly IssueAttachment[], products: readonly IssueWorkProduct[],
): Set<string> {
const commentsById = new Map(comments.map(comment => [comment.id, comment]));
const imagesByAttachment = new Map<string, IssueWorkProduct>();
const filesByAttachment = new Map<string, { product: IssueWorkProduct; image: boolean }>();
for (const product of products) {
const source = fileRowSourceFromWorkProduct(product);
if (source?.attachmentId && isImageLikeOutput(source.contentType, source.filename)) {
imagesByAttachment.set(source.attachmentId, product);
if (source?.attachmentId) {
filesByAttachment.set(source.attachmentId, { product, image: isImageLikeOutput(source.contentType, source.filename) });
}
}
const ids = new Set<string>();
for (const attachment of attachments) {
const comment = attachment.issueCommentId ? commentsById.get(attachment.issueCommentId) : undefined;
const image = imagesByAttachment.get(attachment.id);
const file = filesByAttachment.get(attachment.id);
const receiptAttachmentId = comment?.metadata?.attachmentPreparation?.attachmentId;
// Older receipts predate the marker. Keep their exact historical format as
// a compatibility fallback; new receipts do not depend on wording or title.
// Older image receipts predate the marker. Keep their exact historical
// format as a compatibility fallback; new receipts do not depend on wording or title.
const isPreparation = receiptAttachmentId === attachment.id ||
(receiptAttachmentId == null && image && comment?.body === `Prepared ${image.title} for this response.`);
(receiptAttachmentId == null && file?.image && comment?.body === `Prepared ${file.product.title} for this response.`);
if (comment && comment.authorType === "agent" && attachment.originatingRunId &&
image?.createdByRunId === attachment.originatingRunId && isPreparation &&
file?.product.createdByRunId === attachment.originatingRunId && isPreparation &&
(comment.runId ?? comment.createdByRunId) === attachment.originatingRunId &&
comment.authorAgentId === attachment.createdByAgentId &&
comment.metadata?.authorizationReason === "paperclip_runner_protocol") ids.add(comment.id);
@@ -29,7 +29,9 @@ import type {
import {
humanizeToolName,
isGenericToolName,
mcpToolIdentity,
retriedLabel,
SUBJECT_FAMILIES,
subjectRowLabel,
toolActivityPresentation,
type ToolIcon,
} from "./tool-taxonomy";
@@ -123,25 +125,41 @@ export function providerActivityPresentation(item: TaskChatProviderActivityItem)
target,
progress,
});
const boundedActivity = meaningfulToolDetail(item.summary)
?? meaningfulToolDetail(progress)
?? meaningfulToolDetail(target);
const activityIsIdentity = Boolean(
boundedActivity && name && humanizeToolName(boundedActivity) === humanizeToolName(name),
);
const technicalName = name ? mcpToolIdentity(name)?.name ?? name : tool.displayName;
const source = tool.sourceLabel
? `${tool.sourceLabel} · ${technicalName}`
: name && !isGenericToolName(name) && humanizeToolName(name) !== tool.runningLabel.replace(/^Running /, "")
? name
: undefined;
const subject = meaningfulToolDetail(providerDetail(item, "Subject"));
// The tool's own name repeated as its activity says nothing new.
const describes = (value: string | undefined) =>
value && !(name && humanizeToolName(value) === humanizeToolName(name)) ? value : undefined;
const boundedActivity = describes(subject)
?? describes(meaningfulToolDetail(item.summary))
?? describes(meaningfulToolDetail(progress))
?? describes(meaningfulToolDetail(target));
// People read what a tool did, never its technical name; another
// server's tools still say where they came from.
const source = tool.sourceLabel && tool.sourceLabel !== "Paperclip" ? tool.sourceLabel : undefined;
// With a concrete subject the row reads like a settled one: "Read u1.txt",
// "$ npm test" (TaskChatRunnerActivityGroup's tool rows).
// Settled rows classify by the name alone (TaskChatRunnerActivityGroup).
const settled = toolActivityPresentation({ name, target });
const concrete = Boolean(boundedActivity && (boundedActivity === subject || boundedActivity === meaningfulToolDetail(target)))
&& SUBJECT_FAMILIES.has(settled.family);
if (concrete) {
const terminal = settled.family === "terminal";
return {
icon: settled.icon,
runningLabel: subjectRowLabel(settled.runningLabel, false),
completedLabel: subjectRowLabel(settled.completedLabel, terminal),
failedLabel: subjectRowLabel(settled.failedLabel, false),
interruptedLabel: subjectRowLabel(settled.interruptedLabel, false),
detail: [terminal ? `$ ${boundedActivity}` : boundedActivity, source].filter(Boolean).join(" · "),
};
}
return {
icon: tool.icon,
runningLabel: tool.runningLabel,
completedLabel: tool.completedLabel,
failedLabel: tool.failedLabel,
interruptedLabel: tool.interruptedLabel,
detail: [activityIsIdentity ? undefined : boundedActivity, source].filter(Boolean).join(" · ") || undefined,
detail: [boundedActivity, source].filter(Boolean).join(" · ") || undefined,
};
}
case "plan_proposal":
@@ -266,7 +284,10 @@ export function protocolActivityLabel(item: TaskChatProtocolItem, presentation:
if (item.surface !== "provider_activity") {
return protocolActivityIsRunning(item) ? presentation.runningLabel : presentation.completedLabel;
}
if (item.status === "failed") return presentation.failedLabel ?? `${presentation.completedLabel} · failed`;
if (item.status === "failed") {
const failed = presentation.failedLabel ?? `${presentation.completedLabel} · failed`;
return item.retried ? retriedLabel(failed) : failed;
}
if (item.status === "interrupted") return presentation.interruptedLabel ?? `${presentation.completedLabel} · interrupted`;
return item.status === "running" ? presentation.runningLabel : presentation.completedLabel;
}
@@ -138,6 +138,7 @@ export function commentsToTaskChatItems(
origin: comment.origin ?? "comment",
chatMessage: comment.metadata?.chatMessage,
sourceChannel: kind === "human" ? comment.metadata?.sourceChannel : undefined,
...(kind === "human" && comment.nativeCommand === "swarm" ? { nativeCommand: "swarm" as const } : {}),
timestamp: formatTaskChatCommentTimestamp(comment, kind),
optimistic,
queueTargetRunId: queued ? comment.queueTargetRunId ?? null : null,
@@ -139,6 +139,8 @@ export interface TaskChatMessageItem {
channel?: "progress" | "final" | "unknown";
/** Transport attribution for an inbound human comment. */
sourceChannel?: IssueCommentMetadata["sourceChannel"];
/** Server-derived: this human message asked the assignee's native command (`/swarm`). */
nativeCommand?: "swarm";
timestamp?: string;
/** Show a streaming cursor and suppress collapse while true. */
streaming?: boolean;
@@ -259,6 +261,8 @@ export interface TaskChatToolItem {
blockedReason?: string;
/** Execution id of the delegation (subagent) that made this call. */
parentToolUseId?: string;
/** A failed call the agent repeated on the same target and the repeat succeeded. */
retried?: boolean;
}
/**
@@ -450,6 +454,8 @@ export interface TaskChatProviderActivityItem {
startedAt?: string;
/** Automatic approval review that let this tool execution run. */
autoReview?: TaskChatAutoReview;
/** A failed tool execution the agent repeated on the same target and the repeat succeeded. */
retried?: boolean;
}
export type TaskChatSubagentStatus = "running" | "completed" | "failed" | "cancelled";
@@ -153,3 +153,19 @@ describe("status and placeholder helpers", () => {
expect(isGenericToolName("mcp__linear__search_issues")).toBe(false);
});
});
describe("subject rows", () => {
it("keeps only the verb and outcome beside a subject, live and settled alike", async () => {
const { subjectRowLabel } = await import("./tool-taxonomy");
expect(subjectRowLabel("Read a file", false)).toBe("Read");
expect(subjectRowLabel("Read a file · failed", false)).toBe("Read · failed");
expect(subjectRowLabel("Read a file · retried", false)).toBe("Read · retried");
expect(subjectRowLabel("Ran a command", true)).toBe("");
});
it("names a deleted or moved file as such, never as an edit", async () => {
const { toolActivityPresentation } = await import("./tool-taxonomy");
expect(toolActivityPresentation({ name: "delete_file" }).completedLabel).toBe("Deleted file");
expect(toolActivityPresentation({ name: "move_file" }).completedLabel).toBe("Moved file");
});
});
+23 -1
View File
@@ -81,6 +81,25 @@ export interface ToolActivityPresentation {
summaryGroup: ToolSummaryGroup;
}
/** Families whose rows read as "<verb> <subject>", for example "Read README.md". */
export const SUBJECT_FAMILIES: ReadonlySet<ToolFamily> = new Set(["terminal", "read", "edit", "grep", "search", "web"]);
/**
* The label of a row that shows a concrete subject, for live and settled rows
* alike: only the verb and any outcome ("Read · failed" beside "u1.txt"), or
* nothing for a settled command, whose "$ " subject says it ran.
*/
export function subjectRowLabel(label: string, settledCommand: boolean): string {
if (settledCommand) return "";
const [action, marker] = label.split(" · ");
return `${action!.split(" ")[0]}${marker ? ` · ${marker}` : ""}`;
}
/** "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");
}
/** ACPX's placeholder title must never displace real lifecycle identity. */
const GENERIC_TOOL_NAMES = new Set(["tool", "tool call", "tool_call", "acp_tool"]);
@@ -205,7 +224,10 @@ const EXACT_ACTIONS: Record<string, ExactAction> = {
report_progress: { action: "post", running: "Reporting progress", completed: "Reported progress" },
answer_status_question: { action: "post", running: "Answering a status question", completed: "Answered a status question" },
write_document: { action: "update", running: "Writing a document", completed: "Wrote a document" },
register_deliverable: { action: "create", running: "Registering a deliverable", completed: "Registered a deliverable" },
// 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") },
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" },
@@ -650,7 +650,8 @@ describe("transcriptToTaskChatItems protocol surfaces", () => {
expect(providerActivityPresentation(item)).toMatchObject({
runningLabel: "Searching tasks",
completedLabel: "Searched tasks",
detail: "Searching the task index · Paperclip · search_tasks",
// Paperclip's own tools need no source, and raw tool names are never shown.
detail: "Searching the task index",
});
});
@@ -180,6 +180,9 @@ const TARGET_KEYS = [
"description",
"skill",
"subject",
// A file a tool attaches or saves ("Attached u1.txt").
"filename",
"title",
] as const;
const TARGET_MAX = 96;
@@ -190,8 +193,11 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
const TASK_REF_KEYS = ["taskId", "task_id", "issueId", "issue_id"] as const;
/** A raw id is an internal handle, never something a person reads. */
/** A content digest ("7692c3ad…", "sha256:…") identifies bytes, not anything a person reads. */
const DIGEST_RE = /^(?:sha(?:1|256|512):)?[0-9a-f]{40,128}$/i;
function isOpaqueId(value: unknown): boolean {
return typeof value === "string" && UUID_RE.test(value.trim());
return typeof value === "string" && (UUID_RE.test(value.trim()) || DIGEST_RE.test(value.trim()));
}
/**
@@ -214,7 +220,7 @@ export function toolInputTaskRef(input: unknown): string | undefined {
const record = input as Record<string, unknown>;
for (const key of TASK_REF_KEYS) {
const value = record[key];
if (isOpaqueId(value)) return (value as string).trim();
if (typeof value === "string" && UUID_RE.test(value.trim())) return value.trim();
}
return undefined;
}
@@ -340,6 +346,7 @@ const PROVIDER_DETAIL_KEYS: Record<
"transport",
"operation",
"name",
"subject",
"target",
"namespace",
"readOnly",
@@ -451,6 +458,8 @@ function providerActivityItem(
(entry.family === "verification" && key === "detail")
? 4000
: key === "message" || key === "summary" || key === "reason" ? 320
// As long as a settled tool row's subject (applyToolDetail).
: key === "subject" ? 400
: entry.family === "safety" && key === "action" ? 1000 : 160,
),
mono: /(?:id|model|target|reference|url|code|bytes)$/i.test(key),
@@ -1467,7 +1476,7 @@ export function paperclipRunnerActivityItems(
const hasAggregateWorkspaceChange = parsed.some(
(item) => item.kind === "protocol" && item.surface === "workspace_change",
);
return parsed.filter((item) => {
return markRetriedTools(parsed.filter((item) => {
switch (item.kind) {
case "message":
return Boolean(item.interstitial && item.text.trim());
@@ -1527,7 +1536,7 @@ export function paperclipRunnerActivityItems(
case "plan_document":
return false;
}
});
}));
}
/**
@@ -1551,13 +1560,50 @@ export function paperclipRunnerTimelineItems(
const activityIds = new Set(
paperclipRunnerActivityItems(parsed).map((item) => item.id),
);
return parsed.filter(
return markRetriedTools(parsed.filter(
(item) =>
activityIds.has(item.id) ||
(item.kind === "thinking" && Boolean(item.streaming)) ||
item.kind === "plan_document" ||
(item.kind === "protocol" && item.surface === "runtime_request"),
);
));
}
/**
* A tool row's identity and subject, for matching a retry of the same call.
* A shortened subject ("…") no longer identifies the call, so it never matches.
*/
function retryKey(item: TaskChatItem): string | null {
const key = (name: string | undefined, target: string | undefined) => {
const subject = target?.trim();
return name && subject && !subject.endsWith("…") ? `${name.toLowerCase()}\u0000${subject}` : null;
};
if (item.kind === "tool") return item.blockedReason ? null : key(item.rawName ?? item.name, item.target);
if (item.kind === "protocol" && item.surface === "provider_activity" && item.family === "tool_execution") {
return key(providerItemDetail(item, "Name"), providerItemDetail(item, "Subject") ?? providerItemDetail(item, "Target"));
}
return null;
}
/**
* A failed call is "retried", not "failed", when a later call of the same tool
* on the same target succeeded in the run (for example a read the CLI first
* tried with a relative path). A failure nothing recovered stays failed.
*/
export function markRetriedTools(items: TaskChatItem[]): TaskChatItem[] {
const lastSuccess = new Map<string, number>();
items.forEach((item, index) => {
const key = retryKey(item);
if (key && "status" in item && item.status === "completed") lastSuccess.set(key, index);
});
if (lastSuccess.size === 0) return items;
return items.map((item, index) => {
if (!("status" in item) || item.status !== "failed") return item;
const key = retryKey(item);
return key && (lastSuccess.get(key) ?? -1) > index && (item.kind === "tool" || item.kind === "protocol")
? { ...item, retried: true } as TaskChatItem
: item;
});
}
/**
@@ -0,0 +1,60 @@
/**
* A Paperclip tool call can reach a run record twice: once as the provider's
* own tool lifecycle (`tool.execution.*`, namespace `paperclip`) and once as
* the Paperclip bridge's call (`item.*` tool_use/tool_result, with the
* arguments). Claude passes its tool-use id to the bridge, so both share one
* id and already show as one row. A provider that passes none (Antigravity)
* gets a separate bridge id. This pairs such a bridge call with the provider
* call of the same Paperclip tool that is in flight when it starts, so the
* thread shows one row with the arguments. Display only.
*/
export interface BridgeCallPairing {
/** Record one `tool.execution.*` payload, in run order. */
execution(eventType: string, payload: Record<string, unknown>): void;
/** The provider execution a new bridge call belongs to, if one is in flight. */
bridgeCall(callId: string, toolName: string | null | undefined): string | undefined;
/** The provider execution an already paired bridge call belongs to. */
pairedExecution(callId: string): string | undefined;
}
const PAPERCLIP_NAMESPACE = "paperclip";
export function createBridgeCallPairing(): BridgeCallPairing {
const executions = new Set<string>();
const inFlight = new Map<string, string[]>();
const paired = new Map<string, string>();
const nameOf = new Map<string, string>();
const remove = (executionId: string) => {
const name = nameOf.get(executionId);
const queue = name === undefined ? undefined : inFlight.get(name);
if (queue) inFlight.set(name!, queue.filter((id) => id !== executionId));
};
return {
execution(eventType, payload) {
const executionId = typeof payload.executionId === "string" ? payload.executionId : "";
const name = typeof payload.name === "string" ? payload.name : "";
if (!executionId) return;
const first = !executions.has(executionId);
executions.add(executionId);
if (eventType === "tool.execution.completed") {
remove(executionId);
return;
}
if (!first || payload.namespace !== PAPERCLIP_NAMESPACE || !name) return;
nameOf.set(executionId, name);
inFlight.set(name, [...(inFlight.get(name) ?? []), executionId]);
},
bridgeCall(callId, toolName) {
if (paired.has(callId)) return paired.get(callId);
if (!toolName || executions.has(callId)) return undefined;
const executionId = inFlight.get(toolName)?.[0];
if (!executionId) return undefined;
paired.set(callId, executionId);
remove(executionId);
return executionId;
},
pairedExecution(callId) {
return paired.get(callId);
},
};
}
File diff suppressed because it is too large. Load diff
@@ -3,6 +3,7 @@ import type { TranscriptEntry } from "@/adapters";
type TranscriptToolDetail = NonNullable<Extract<TranscriptEntry, { kind: "tool_call" }>["detail"]>;
import { isRunLogOnlyProviderEvent } from "./run-log-only-events";
import { createBridgeCallPairing } from "./bridge-call-pairing";
import { workspaceChangeEntry } from "@/adapters/paperclip-runner";
import { createUnifiedDiffClassifier } from "@/components/task-chat/diff-lines";
@@ -921,6 +922,17 @@ export function nativeRunEventsToTranscript(events: readonly HeartbeatRunEvent[]
fileChangesByExecutionId.set(executionId, payload.fileChanges);
}
}
// A bridge call under its own id joins the provider's row for the same call.
const bridgeCalls = createBridgeCallPairing();
for (const event of orderedEvents) {
const payload = record(record(event.payload?.prpEvent)?.payload);
if (!payload) continue;
if (event.eventType.startsWith("tool.execution.")) bridgeCalls.execution(event.eventType, payload);
else if (event.eventType === "item.started") {
const tool = nativeToolItemDetails(payload);
if (tool?.kind === "tooluse" && tool.id) bridgeCalls.bridgeCall(tool.id, tool.details.name);
}
}
for (const event of orderedEvents) {
if (!isItemIdentityEvent(event.eventType)) continue;
const envelope = record(event.payload?.prpEvent);
@@ -937,7 +949,7 @@ export function nativeRunEventsToTranscript(events: readonly HeartbeatRunEvent[]
if (!itemId) continue;
const toolItem = nativeToolItemDetails(payload);
if (toolItem) {
const toolId = toolItem.id ?? itemId;
const toolId = (toolItem.id && bridgeCalls.pairedExecution(toolItem.id)) ?? toolItem.id ?? itemId;
const previous = nativeToolItemsById.get(toolId);
nativeToolItemsById.set(toolId, {
name: toolItem.details.name ?? previous?.name ?? null,
@@ -1109,6 +1121,8 @@ export function nativeRunEventsToTranscript(events: readonly HeartbeatRunEvent[]
if (nativeToolEvent) {
const toolId = nativeToolEvent.id ?? itemId;
if (!toolId) continue;
// Shown on the provider's own row for the same call.
if (bridgeCalls.pairedExecution(toolId)) continue;
const nativeToolItem = nativeToolItemsById.get(toolId)
?? nativeToolEvent.details;
const presentation = toolPresentation({}, nativeToolItem);
@@ -0,0 +1,24 @@
import { useContext } from "react";
import { QueryClient, QueryClientContext, useQuery } from "@tanstack/react-query";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { queryKeys } from "@/lib/queryKeys";
let detachedClient: QueryClient | null = null;
/**
* The instance's experimental Antigravity swarm setting, for
* `antigravitySwarmAvailable` (packages/shared). Off until loaded and when
* there is no query client; the server decides on send either way.
*/
export function useAntigravitySwarmSetting(): { enableAntigravitySwarm: boolean } {
const contextClient = useContext(QueryClientContext);
const { data } = useQuery(
{
queryKey: queryKeys.instance.experimentalSettings,
queryFn: () => instanceSettingsApi.getExperimental(),
enabled: contextClient != null,
},
contextClient ?? (detachedClient ??= new QueryClient()),
);
return { enableAntigravitySwarm: contextClient != null && data?.enableAntigravitySwarm === true };
}