From c3d5dbfd3c5e5961fc69a9eb4c950c776cce30f1 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:06:03 +0100 Subject: [PATCH 1/6] feat(antigravity): show /swarm as a workflow with a row per worker Antigravity's /swarm runs its workers outside ACP: the coordinator only reports `Run swarm` tool calls, and workers talk on a board under its session. T3 showed those calls as bare tool rows, so the swarm itself was invisible. The Antigravity adapter now reads the swarm's members.json, board.jsonl and each worker's transcript tail, and the ACP adapter projects them as one workflow subagent through a new `nativeWorkflow` flavor hook: the swarm's title, a row and child thread per worker with its brief, model, state and [done] result. The swarm holds the run open while any worker works. The Work dialog reads a worker's own transcript. invoke_subagent batches keep their existing path. --- .../Adapters/AntigravityAdapterV2.test.ts | 135 +++++++ .../Adapters/AntigravityAdapterV2.ts | 22 ++ .../NativeChildWorkQuery.test.ts | 86 +++++ .../orchestration-v2/NativeChildWorkQuery.ts | 52 ++- .../src/provider/acp/AntigravityChildWork.ts | 34 ++ .../src/provider/acp/AntigravitySwarm.test.ts | 197 ++++++++++ .../src/provider/acp/AntigravitySwarm.ts | 350 ++++++++++++++++++ docs/user/providers-antigravity.md | 11 + packages/provider-acp/src/server/adapter.ts | 303 ++++++++++++++- 9 files changed, 1180 insertions(+), 10 deletions(-) create mode 100644 apps/server/src/provider/acp/AntigravitySwarm.test.ts create mode 100644 apps/server/src/provider/acp/AntigravitySwarm.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 9924d6c831833..e370c8c7ee903 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2429,6 +2429,141 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // Frames and files as agy 1.5.14 wrote them for `/swarm`: the coordinator's `swarm` calls + // arrive as `Run swarm`, and workers report only on the board below its session. + it.effect("shows a swarm as one workflow that runs until its workers park", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-swarm-", + }); + const brain = (conversationId: string, ...rest: ReadonlyArray) => + path.join( + profile, + "antigravity-acp", + "brain", + conversationId, + ".system_generated", + ...rest, + ); + const writeLines = (file: string, values: ReadonlyArray) => + fileSystem + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen( + fileSystem.writeFileString( + file, + values.map((value) => JSON.stringify(value)).join("\n") + "\n", + ), + ), + ); + yield* fileSystem.makeDirectory(brain("mock-session-1", "swarm"), { recursive: true }); + yield* fileSystem.writeFileString( + brain("mock-session-1", "swarm", "members.json"), + JSON.stringify({ + title: "Compute 6*7", + members: { + coordinator: { conversation_id: "mock-session-1", role: "coordinator" }, + "mul-a": { conversation_id: "worker-1", role: "worker", model: "gemini-test-low" }, + }, + }), + ); + const brief = { + seq: 1, + agent: "coordinator", + text: "@mul-a Compute 6*7.", + time: "2026-11-23 17:23:18", + kind: "brief", + }; + yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [brief]); + const transcript = brain("worker-1", "logs", "transcript.jsonl"); + yield* writeLines(transcript, [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, + ]); + const swarmCall = (toolCallId: string, rawInput: Record) => + ({ + sessionUpdate: "tool_call", + toolCallId, + kind: "other", + title: "Run swarm", + status: "completed", + rawInput, + }) as const; + const { startTurn, until, throughPromptSettled, scheduledFinalizes } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [ + swarmCall("call_title", { action: "title", title: "Compute 6*7" }), + swarmCall("call_add", { action: "add", name: "mul-a", brief: "Compute 6*7." }), + ], + }); + yield* startTurn(1, false); + const workflows = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "subagent.updated" && event.subagent.workflow !== undefined + ? [event.subagent] + : [], + ); + const prompt = [ + ...(yield* throughPromptSettled), + ...(yield* until((event) => workflows([event]).length > 0)), + ]; + const running = workflows(prompt).at(-1); + assert.equal(running?.status, "running"); + assert.equal(running?.workflow?.name, "Compute 6*7"); + assert.deepEqual( + running?.workflow?.agents.map(({ label, state, prompt: brief }) => [label, state, brief]), + [["mul-a", "running", "Compute 6*7."]], + ); + assert.isFalse( + JSON.stringify(prompt).includes("Run swarm"), + "swarm calls fold into the workflow instead of showing as tools", + ); + + yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [ + brief, + { seq: 2, agent: "mul-a", text: "@coordinator [done] 42", time: "2026-11-23 17:23:21" }, + ]); + yield* writeLines(transcript, [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE" }, + { step_index: 3, type: "GENERIC", status: "DONE" }, + ]); + // One poll reads the parked worker; the idle swarm then schedules the turn's end. + yield* TestClock.adjust("2 seconds"); + const parkedRun = yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* Queue.take(scheduledFinalizes); + yield* TestClock.adjust("5 seconds"); + const run = [...parkedRun, ...(yield* until((event) => event.type === "turn.terminal"))]; + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + const done = workflows(run).at(-1); + assert.equal(done?.status, "completed"); + assert.deepEqual( + done?.workflow?.agents.map(({ state, result }) => [state, result]), + [["completed", "@coordinator [done] 42"]], + ); + const memberThread = done?.workflow?.agents[0]?.childThreadId; + assert.isTrue( + run.some( + (event) => + event.type === "message.updated" && + event.message.threadId === memberThread && + event.message.text === "@coordinator [done] 42", + ), + "the worker's result reaches its own thread", + ); + }).pipe(Effect.provide(layerSession)), + ); + it.effect.each([ // session/cancel ends the agent's commands, so only Stop may send it. { ending: "Stop", cancels: 1, status: "interrupted" }, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c20afa04e31b8..b1a5d42fc00a6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -37,6 +37,11 @@ import { readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; +import { + antigravitySwarmTaskId, + isAntigravitySwarmToolCall, + readAntigravitySwarm, +} from "../../provider/acp/AntigravitySwarm.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, @@ -317,6 +322,23 @@ export function makeAntigravityAcpAdapterFlavor( profileDirectory, sessionId, }), + nativeWorkflow: { + isTool: isAntigravitySwarmToolCall, + read: (sessionId: string) => + readAntigravitySwarm({ profileDirectory, sessionId }).pipe( + Effect.map((swarm) => + swarm === undefined + ? undefined + : { + nativeTaskId: antigravitySwarmTaskId(sessionId), + title: swarm.workflow.name ?? "Swarm", + prompt: swarm.prompt, + workflow: swarm.workflow, + active: swarm.active, + }, + ), + ), + }, }), }; } diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts index 1b7c95336629f..f9eeac5ee592f 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts @@ -136,3 +136,89 @@ it.layer( }), ); }); + +const memberThreadId = ThreadId.make("thread-swarm-member"); +const swarmThreadId = ThreadId.make("thread-swarm"); +// A swarm worker's thread hangs off the swarm thread, whose workflow names the worker's session. +const swarmRecords = (threadId: string) => + threadId === memberThreadId + ? { + thread: { + id: memberThreadId, + creationSource: "provider", + lineage: { parentThreadId: swarmThreadId, relationshipToParent: "subagent" }, + forkedFrom: { type: "node", nodeId: "member-node" }, + }, + } + : threadId === swarmThreadId + ? { + thread: { id: swarmThreadId, lineage: { parentThreadId: "thread-root" } }, + subagents: [ + { + id: "member-node", + childThreadId: memberThreadId, + driver: "antigravity", + providerInstanceId: instanceId, + runId: null, + prompt: "Read it", + }, + ], + } + : { + subagents: [ + { + childThreadId: swarmThreadId, + driver: "antigravity", + providerInstanceId: instanceId, + workflow: { + phases: [], + agents: [ + { + index: 0, + label: "reader", + state: "completed", + agentId: CHILD, + childThreadId: memberThreadId, + prompt: "Read README.md and report the marker", + }, + ], + }, + }, + ], + }; + +it.layer( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + ServerConfig.layerTest(process.cwd(), { prefix: "native-swarm-work-" }).pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), +)("NativeChildWorkQuery swarm", (it) => { + it.effect("reads a swarm worker's own transcript", () => + Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const { profile } = yield* resolveAntigravityInstanceDirectories(stateDir, instanceId); + yield* makeProfile({ profile, steps: () => [] }); + const children = yield* Effect.gen(function* () { + const query = yield* NativeChildWorkQuery.NativeChildWorkQuery; + return (yield* query.getNativeChildWork({ threadId: memberThreadId })).children; + }).pipe( + Effect.provide( + NativeChildWorkQuery.layer.pipe( + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadRecords: (threadId) => Effect.succeed(swarmRecords(threadId) as never), + }), + ), + ), + ), + ); + expect(children.map(({ conversationId, role }) => [conversationId, role])).toEqual([ + [CHILD, "reader"], + ]); + expect(children[0]?.steps?.at(-1)?.text).toBe("marker 4242 found"); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts index 389ae6c408273..37019e3fbb3b8 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts @@ -1,5 +1,7 @@ import { isProviderNativeSubagentThread, + type OrchestrationV2Subagent, + type ThreadId, OrchestrationV2GetNativeChildWorkError, type OrchestrationV2GetNativeChildWorkInput, type OrchestrationV2GetNativeChildWorkResult, @@ -11,7 +13,10 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; -import { readAntigravityChildWork } from "../provider/acp/AntigravityChildWork.ts"; +import { + readAntigravityChildWork, + readAntigravitySwarmMemberWork, +} from "../provider/acp/AntigravityChildWork.ts"; import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; @@ -36,6 +41,42 @@ const make = Effect.gen(function* () { const digest = yield* Digest.Digest; const path = yield* Path.Path; + const profileOf = (providerInstanceId: OrchestrationV2Subagent["providerInstanceId"]) => + resolveAntigravityInstanceDirectories(stateDir, providerInstanceId).pipe( + Effect.provideService(Digest.Digest, digest), + Effect.provideService(Path.Path, path), + Effect.map((directories) => directories.profile), + ); + + // A swarm worker's thread hangs off the swarm's thread; the workflow record names its session. + const swarmMemberWork = Effect.fn("NativeChildWorkQuery.swarmMemberWork")(function* ( + memberThreadId: ThreadId, + swarmThreadId: ThreadId, + member: OrchestrationV2Subagent, + ) { + const { thread: swarmThread } = yield* threads.getThreadRecords(swarmThreadId, []); + const rootThreadId = swarmThread.lineage.parentThreadId; + if (rootThreadId === null) return NO_CHILDREN; + const { subagents } = yield* threads.getThreadRecords(rootThreadId, ["subagents"]); + const swarm = subagents.find( + (candidate) => + candidate.childThreadId === swarmThreadId && + candidate.driver === "antigravity" && + candidate.providerInstanceId === member.providerInstanceId, + ); + const agent = swarm?.workflow?.agents.find( + (candidate) => candidate.childThreadId === memberThreadId, + ); + if (agent?.agentId === undefined) return NO_CHILDREN; + const children = yield* readAntigravitySwarmMemberWork({ + profileDirectory: yield* profileOf(member.providerInstanceId), + conversationId: agent.agentId, + role: agent.label, + prompt: agent.prompt ?? member.prompt, + }); + return { children }; + }); + const getNativeChildWork = Effect.fn("NativeChildWorkQuery.getNativeChildWork")( function* (input: OrchestrationV2GetNativeChildWorkInput) { const { thread } = yield* threads.getThreadRecords(input.threadId, []); @@ -53,6 +94,9 @@ const make = Effect.gen(function* () { (candidate) => candidate.id === subagentId && candidate.childThreadId === thread.id, ); const nativeTaskId = subagent?.nativeTaskRef?.nativeId; + if (subagent?.driver === "antigravity" && subagent.runId === null) { + return yield* swarmMemberWork(thread.id, parentThreadId, subagent); + } if ( subagent?.driver !== "antigravity" || subagent.origin !== "provider_native" || @@ -93,12 +137,8 @@ const make = Effect.gen(function* () { if (!rootSessionId || providerThread?.providerInstanceId !== subagent.providerInstanceId) { return NO_CHILDREN; } - const directories = yield* resolveAntigravityInstanceDirectories( - stateDir, - subagent.providerInstanceId, - ).pipe(Effect.provideService(Digest.Digest, digest), Effect.provideService(Path.Path, path)); const children = yield* readAntigravityChildWork({ - profileDirectory: directories.profile, + profileDirectory: yield* profileOf(subagent.providerInstanceId), rootSessionId, nativeTaskId, launch: { title: subagent.title, prompt: subagent.prompt }, diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index aa0932cf0f41a..89fc7d9e22921 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -820,3 +820,37 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA }).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); }, ); + +/** A swarm worker's own transcript; the board, not a launching tool call, proves it belongs. */ +export const readAntigravitySwarmMemberWork = Effect.fn("readAntigravitySwarmMemberWork")( + function* (input: { + readonly profileDirectory: string; + readonly conversationId: string; + readonly role: string; + readonly prompt: string; + }) { + if (!NATIVE_ID.test(input.conversationId)) return []; + return yield* Effect.tryPromise({ + try: async (): Promise> => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return []; + const transcript = await readChildTranscript( + profileRoot, + { conversationId: input.conversationId }, + input.prompt, + TRANSCRIPT_BYTE_CAP, + ); + return [ + { + conversationId: input.conversationId, + role: input.role, + prompt: input.prompt, + steps: transcript?.steps ?? null, + truncated: transcript?.truncated ?? false, + }, + ]; + }, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }); + }, +); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts new file mode 100644 index 0000000000000..343caed79cd16 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -0,0 +1,197 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { readAntigravitySwarm } from "./AntigravitySwarm.ts"; + +const COORDINATOR = "e1eca26b-11b5-41f8-9d9b-bb8a692b2125"; +const ADD_A = "a82657e1-5a66-4505-aecc-6844eec6d066"; +const ADD_B = "60c330fe-87ec-457b-9fba-9e062cfc58d7"; + +const member = (conversationId: string, role: string, extra: object = {}) => ({ + conversation_id: conversationId, + role, + model: "gemini-3.8-flash-low", + wake_mode: "mentions", + killed: false, + ...extra, +}); + +// Shapes captured from a real `agy` 1.5.14 `/swarm` run. +const writeSwarm = Effect.fn("writeSwarm")(function* (input: { + readonly members: Record; + readonly board: ReadonlyArray; + readonly transcripts: Record>; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-" }); + const brain = path.join(profile, "antigravity-acp", "brain"); + const swarm = path.join(brain, COORDINATOR, ".system_generated", "swarm"); + yield* fs.makeDirectory(swarm, { recursive: true }); + yield* fs.writeFileString( + path.join(swarm, "members.json"), + JSON.stringify({ title: "simple arithmetic addition", members: input.members }), + ); + yield* fs.writeFileString( + path.join(swarm, "board.jsonl"), + input.board.map((post) => JSON.stringify(post)).join("\n") + "\n", + ); + for (const [conversationId, steps] of Object.entries(input.transcripts)) { + const logs = path.join(brain, conversationId, ".system_generated", "logs"); + yield* fs.makeDirectory(logs, { recursive: true }); + yield* fs.writeFileString( + path.join(logs, "transcript.jsonl"), + steps.map((step) => JSON.stringify(step)).join("\n") + "\n", + ); + } + return profile; +}); + +const briefs = [ + { + seq: 1, + agent: "coordinator", + text: "@add-a Compute 2 + 3. Post @coordinator [done] 5 to the board.", + time: "2026-11-23 17:23:18", + kind: "brief", + }, + { + seq: 2, + agent: "coordinator", + text: "@add-b Compute 4 + 5. Post @coordinator [done] 9 to the board.", + time: "2026-11-23 17:23:18", + kind: "brief", + }, +]; + +const started = { + step_index: 0, + type: "SYSTEM_MESSAGE", + status: "DONE", + created_at: "2026-11-23T16:23:18Z", +}; + +const parked = [ + started, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + created_at: "2026-11-23T16:23:18Z", + input_tokens: 100, + output_tokens: 20, + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE", created_at: "2026-11-23T16:23:21Z" }, + { step_index: 3, type: "GENERIC", status: "DONE", created_at: "2026-11-23T16:23:21Z" }, +]; + +const working = [ + started, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + created_at: "2026-11-23T16:23:19Z", + tool_calls: [{ name: "run_command" }], + }, +]; + +it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { + it.effect("shows each worker with its brief, state and [done] result", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + "add-a": member(ADD_A, "worker"), + "add-b": member(ADD_B, "worker"), + coordinator: member(COORDINATOR, "coordinator"), + narrator: member("bb91cb60-3240-44a0-a20d-966af04a49a3", "narrator"), + }, + board: [ + ...briefs, + { seq: 3, agent: "add-a", text: "@coordinator [done] 5", time: "2026-11-23 17:23:21" }, + ], + transcripts: { [ADD_A]: parked, [ADD_B]: working }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.active).toBe(true); + expect(swarm?.head).toBe(3); + expect(swarm?.workflow.name).toBe("simple arithmetic addition"); + expect( + swarm?.workflow.agents.map(({ label, state, prompt, result, model, totalTokens }) => ({ + label, + state, + prompt, + result, + model, + totalTokens, + })), + ).toEqual([ + { + label: "add-a", + state: "completed", + prompt: "Compute 2 + 3. Post @coordinator [done] 5 to the board.", + result: "@coordinator [done] 5", + model: "gemini-3.8-flash-low", + totalTokens: 120, + }, + { + label: "add-b", + state: "running", + prompt: "Compute 4 + 5. Post @coordinator [done] 9 to the board.", + result: undefined, + model: "gemini-3.8-flash-low", + totalTokens: 0, + }, + ]); + }), + ); + + it.effect("ends when every worker parked, failed or was killed", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + "add-a": member(ADD_A, "worker"), + "add-b": member(ADD_B, "worker", { killed: true }), + }, + board: briefs, + transcripts: { + [ADD_A]: [ + ...working, + { + step_index: 2, + type: "ERROR_MESSAGE", + status: "DONE", + error: "RESOURCE_EXHAUSTED", + }, + ], + [ADD_B]: working, + }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.active).toBe(false); + expect(swarm?.workflow.agents.map(({ state, result }) => ({ state, result }))).toEqual([ + { state: "failed", result: "RESOURCE_EXHAUSTED" }, + { state: "completed", result: undefined }, + ]); + }), + ); + + it.effect("reads only the swarm this session coordinates", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { coordinator: member(ADD_A, "coordinator") }, + board: [], + transcripts: {}, + }); + expect( + yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }), + ).toBeUndefined(); + expect(yield* readAntigravitySwarm({ profileDirectory, sessionId: ADD_B })).toBeUndefined(); + }), + ); +}); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts new file mode 100644 index 0000000000000..f2f62bad3199e --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -0,0 +1,350 @@ +// @effect-diagnostics nodeBuiltinImport:off -- reads the native swarm board files without following links. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; + +import type { + OrchestrationV2SubagentWorkflow, + OrchestrationV2WorkflowAgent, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; + +const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; +const MAX_ROSTER_BYTES = 256 * 1024; +const BOARD_TAIL_BYTES = 512 * 1024; +const TRANSCRIPT_TAIL_BYTES = 64 * 1024; +const MAX_MEMBERS = 64; +const TEXT_CAP = 4_000; +// The swarm's own helpers, not task workers; the board view leaves them out the same way. +const SUPPORT_ROLE = /^(narrator|monitor)(-\d+)?$/; +const DONE_MARK = /\[done\]/i; + +/** Native task id T3 gives a swarm, so its record survives every turn of the coordinator thread. */ +export const antigravitySwarmTaskId = (sessionId: string) => `swarm:${sessionId}`; + +const SwarmToolInput = Schema.Struct({ action: Schema.String }); +const decodeSwarmToolInput = Schema.decodeUnknownOption(SwarmToolInput); + +/** The coordinator's `swarm` tool. ACP reports it as `Run swarm` with the action as input. */ +export function isAntigravitySwarmToolCall(toolCall: { + readonly kind?: string; + readonly title?: string; + readonly data: Record; +}): boolean { + if (toolCall.kind !== undefined && toolCall.kind !== "other") return false; + if (toolCall.title !== "Run swarm" && toolCall.title !== "Run swarm?") return false; + return Option.isSome(decodeSwarmToolInput(toolCall.data.rawInput)); +} + +const Member = Schema.Struct({ + conversation_id: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + applied_model: Schema.optional(Schema.String), + desired_model: Schema.optional(Schema.String), + desired_state: Schema.optional(Schema.String), + phase: Schema.optional(Schema.String), + killed: Schema.optional(Schema.Boolean), +}); +const decodeRoster = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + title: Schema.optional(Schema.String), + members: Schema.Record(Schema.String, Member), + }), + ), +); +const Post = Schema.Struct({ + seq: Schema.Int, + agent: Schema.String, + text: Schema.String, + time: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), +}); +type Post = typeof Post.Type; +const decodePost = Schema.decodeUnknownOption(Schema.fromJsonString(Post)); +const Step = Schema.Struct({ + type: Schema.String, + status: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), + created_at: Schema.optional(Schema.String), + input_tokens: Schema.optional(Schema.Number), + output_tokens: Schema.optional(Schema.Number), + tool_calls: Schema.optional(Schema.Array(Schema.Struct({ name: Schema.String }))), +}); +type Step = typeof Step.Type; +const decodeStep = Schema.decodeUnknownOption(Schema.fromJsonString(Step)); + +async function readTail( + path: string, + maxBytes: number, +): Promise<{ readonly text: string; readonly whole: boolean } | undefined> { + const handle = await NodeFSP.open( + path, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) return undefined; + const start = Math.max(0, stat.size - maxBytes); + const buffer = Buffer.alloc(stat.size - start); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, start); + const text = buffer.toString("utf8", 0, bytesRead); + // A cut first line is not a whole record. + return start === 0 + ? { text, whole: true } + : { text: text.slice(text.indexOf("\n") + 1), whole: false }; + } finally { + await handle.close(); + } +} + +const brainFile = (conversationId: string, ...rest: ReadonlyArray) => [ + "antigravity-acp", + "brain", + conversationId, + ".system_generated", + ...rest, +]; + +function lines(text: string, decode: (line: string) => Option.Option): ReadonlyArray { + return text.split("\n").flatMap((line) => Option.toArray(decode(line))); +} + +// Board and transcript times are the runtime's local wall clock without a zone. +function epochMillis(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const millis = Date.parse(value.includes("T") ? value : value.replace(" ", "T")); + return Number.isFinite(millis) ? millis : undefined; +} + +const capText = (value: string) => + value.length <= TEXT_CAP ? value : `${value.slice(0, TEXT_CAP)}…`; + +/** Whether the member's newest turn has ended: a final reply, or a batch that parked in `swarm_wait`. */ +function turnEnded(steps: ReadonlyArray): boolean { + let results = 0; + for (let index = steps.length - 1; index >= 0; index -= 1) { + const step = steps[index]; + if (step === undefined) return false; + if (step.type === "GENERIC") { + results += 1; + continue; + } + if (step.type !== "PLANNER_RESPONSE") return false; + const calls = step.tool_calls ?? []; + if (calls.length === 0) return results === 0; + const wait = calls.findIndex((call) => call.name === "swarm_wait"); + if (wait < 0 || results < calls.length) return false; + return steps[index + 1 + wait]?.status === "DONE"; + } + return false; +} + +interface MemberActivity { + readonly ended: boolean; + readonly failed: string | undefined; + readonly startedAt: number | undefined; + readonly lastAt: number | undefined; + /** Only when the whole transcript was read; a tail would undercount. */ + readonly usage: { readonly totalTokens: number; readonly toolCalls: number } | undefined; +} + +async function readActivity( + profileRoot: string, + conversationId: string, +): Promise { + const file = await antigravityManagedPath( + profileRoot, + brainFile(conversationId, "logs", "transcript.jsonl"), + "file", + ); + if (file === undefined) return undefined; + const tail = await readTail(file.path, TRANSCRIPT_TAIL_BYTES).catch(() => undefined); + if (tail === undefined) return undefined; + const steps = lines(tail.text, decodeStep); + const last = steps.at(-1); + let tokens = 0; + let toolCalls = 0; + for (const step of steps) { + tokens += (step.input_tokens ?? 0) + (step.output_tokens ?? 0); + toolCalls += step.tool_calls?.length ?? 0; + } + return { + ended: turnEnded(steps), + failed: + last?.type === "ERROR_MESSAGE" + ? (last.error ?? "The agent stopped on a model error.") + : undefined, + startedAt: epochMillis(steps[0]?.created_at), + lastAt: epochMillis(last?.created_at), + usage: tail.whole ? { totalTokens: tokens, toolCalls } : undefined, + }; +} + +const memberModel = (member: typeof Member.Type) => + [member.model, member.applied_model, member.desired_model].find( + (model) => model !== undefined && model.trim() !== "", + ); + +const killed = (member: typeof Member.Type) => + member.killed === true || member.desired_state === "KILLED" || member.phase === "KILLED"; + +class AntigravitySwarmReadError extends Schema.TaggedError()( + "AntigravitySwarmReadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the Antigravity swarm board."; + } +} + +export interface AntigravitySwarmSnapshot { + readonly workflow: OrchestrationV2SubagentWorkflow; + /** The coordinator's brief to each worker, in the order they joined. */ + readonly prompt: string; + /** True while any worker still works; parked and killed workers do not count. */ + readonly active: boolean; + /** Board head, so callers can skip unchanged snapshots cheaply. */ + readonly head: number; +} + +/** + * Reads the coordinator session's swarm board: the roster, the board feed and each worker's + * transcript tail. Workers become workflow agents; the coordinator and helpers are left out. + * Returns undefined when this session coordinates no swarm or its records cannot be read. + */ +export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; +}) { + if (!NATIVE_ID.test(input.sessionId)) return undefined; + const read = async (): Promise => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return undefined; + const rosterFile = await antigravityManagedPath( + profileRoot, + brainFile(input.sessionId, "swarm", "members.json"), + "file", + ); + if (rosterFile === undefined || rosterFile.info.size > MAX_ROSTER_BYTES) return undefined; + const roster = Option.getOrUndefined( + decodeRoster(await NodeFSP.readFile(rosterFile.path, "utf8")), + ); + if (roster === undefined) return undefined; + const coordinator = Object.entries(roster.members).find( + ([, member]) => member.role === "coordinator", + ); + // Only the swarm this session coordinates; a worker's own board view belongs to its coordinator. + if (coordinator === undefined || coordinator[1].conversation_id !== input.sessionId) { + return undefined; + } + const boardFile = await antigravityManagedPath( + profileRoot, + brainFile(input.sessionId, "swarm", "board.jsonl"), + "file", + ); + const board: ReadonlyArray = + boardFile === undefined + ? [] + : lines((await readTail(boardFile.path, BOARD_TAIL_BYTES))?.text ?? "", decodePost); + const coordinatorName = coordinator[0]; + const briefs = new Map(); + const results = new Map(); + for (const post of board) { + if (post.agent === coordinatorName && post.kind === "brief") { + const named = /^@([A-Za-z0-9._-]+)/.exec(post.text)?.[1]; + if (named !== undefined && !briefs.has(named)) briefs.set(named, post); + } else if (post.agent !== coordinatorName && DONE_MARK.test(post.text)) { + results.set(post.agent, post); + } + } + const workers = Object.entries(roster.members) + .filter( + ([name, member]) => + member.role !== "coordinator" && + !SUPPORT_ROLE.test(member.role ?? "") && + !(member.role === undefined && SUPPORT_ROLE.test(name)), + ) + .sort( + ([left], [right]) => + (briefs.get(left)?.seq ?? Number.MAX_SAFE_INTEGER) - + (briefs.get(right)?.seq ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right), + ) + .slice(0, MAX_MEMBERS); + let active = false; + let totalTokens: number | undefined = 0; + let toolCalls = 0; + const agents: Array = []; + for (const [index, [name, member]] of workers.entries()) { + const conversationId = member.conversation_id; + const activity = + conversationId !== undefined && NATIVE_ID.test(conversationId) + ? await readActivity(profileRoot, conversationId).catch(() => undefined) + : undefined; + const brief = briefs.get(name); + const result = results.get(name); + const isKilled = killed(member); + const state: OrchestrationV2WorkflowAgent["state"] = + activity?.failed !== undefined + ? "failed" + : activity === undefined + ? isKilled + ? "completed" + : "queued" + : activity.ended || isKilled + ? "completed" + : "running"; + if (state === "running" || state === "queued") active = true; + if (activity?.usage === undefined) totalTokens = undefined; + else if (totalTokens !== undefined) { + totalTokens += activity.usage.totalTokens; + toolCalls += activity.usage.toolCalls; + } + const prompt = brief?.text.replace(/^@[A-Za-z0-9._-]+\s*/, "").trim(); + const resultText = (activity?.failed ?? result?.text)?.trim(); + const startedAt = activity?.startedAt ?? epochMillis(brief?.time); + const completedAt = + state === "completed" || state === "failed" + ? (epochMillis(result?.time) ?? activity?.lastAt) + : undefined; + const model = memberModel(member); + agents.push({ + index, + label: name, + ...(conversationId === undefined || conversationId === "" + ? {} + : { agentId: conversationId }), + state, + ...(model === undefined ? {} : { model }), + ...activity?.usage, + ...(startedAt === undefined ? {} : { startedAt }), + ...(completedAt === undefined ? {} : { completedAt }), + ...(prompt === undefined || prompt === "" ? {} : { prompt: capText(prompt) }), + ...(resultText === undefined || resultText === "" ? {} : { result: capText(resultText) }), + }); + } + const title = roster.title?.trim(); + return { + workflow: { + ...(title === undefined || title === "" ? {} : { name: title }), + phases: [], + agents, + ...(agents.length === 0 || totalTokens === undefined ? {} : { totalTokens, toolCalls }), + }, + prompt: agents + .flatMap((agent) => (agent.prompt === undefined ? [] : [`@${agent.label} ${agent.prompt}`])) + .join("\n\n"), + active, + head: board.at(-1)?.seq ?? 0, + }; + }; + // An unreadable board means no swarm view this poll; the next poll reads again. + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravitySwarmReadError({ cause }), + }).pipe(Effect.orElseSucceed((): AntigravitySwarmSnapshot | undefined => undefined)); +}); diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 614fda68f2c1d..1d6de19aaddda 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -121,6 +121,17 @@ which children a batch started, the view says so. See [agent work](./thread-sidebar.md#inspect-agent-work) for where to inspect activity. +### Swarms + +Start a swarm with `/swarm `. The thread shows it as one workflow, titled with +the swarm's name, with a row for each worker: its brief, model, state, and the +result it posted. Open a worker to read its brief and result, and select **Work** +to see its recent steps. The run stays open while any worker is still working. + +Talk to the swarm through the thread; the coordinator relays your messages to +the workers. **Stop** ends the coordinator's turn but does not remove workers; ask +the coordinator to remove them. The swarm's narrator and monitor are not shown. + ## Accounts and removal Add an Antigravity provider instance for each Google account in diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c4b90adc0c3d1..03808a0368ae7 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ProviderTurn, type OrchestrationV2RuntimeRequest, type OrchestrationV2Subagent, + type OrchestrationV2SubagentWorkflow, type OrchestrationV2TurnItem, type OrchestrationV2UserInputQuestion, type OrchestrationV2WebSearchResult, @@ -155,6 +156,7 @@ const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; // Agents such as omp advertise a loaded session's commands shortly after answering session/load. const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds"; const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; +const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -694,6 +696,15 @@ export interface AcpAdapterV2Flavor { * through `ACP_OPEN_REPLY_QUIET_LIMIT` instead of closing early. */ readonly hasPendingReply?: (sessionId: string) => Effect.Effect; + /** + * A team the agent runs from this session outside ACP (Antigravity `/swarm`), shown as one + * workflow subagent read from the agent's own records. `isTool` names the tool calls that + * manage it; they fold into the workflow instead of showing as tools. + */ + readonly nativeWorkflow?: { + readonly isTool: (toolCall: AcpToolCallState) => boolean; + readonly read: (sessionId: string) => Effect.Effect; + }; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -811,6 +822,16 @@ export interface AcpAdapterV2SubagentUpdate { readonly childSessionId: string | null; readonly result: string | null; readonly suppressNormalTool?: boolean; + readonly workflow?: OrchestrationV2SubagentWorkflow; +} + +export interface AcpNativeWorkflowSnapshot { + readonly nativeTaskId: string; + readonly title: string; + readonly prompt: string; + readonly workflow: OrchestrationV2SubagentWorkflow; + /** Any member still works; holds the turn open like a running subagent. */ + readonly active: boolean; } export interface AcpAdapterV2Options { @@ -1787,6 +1808,11 @@ interface ActiveAcpTurn { /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */ lastProgressAt: number; inactivityWatchdog: Fiber.Fiber | undefined; + nativeWorkflowWatching: boolean; + /** The turn called a `nativeWorkflow` tool, so the workflow belongs to it even if unchanged. */ + nativeWorkflowToolSeen: boolean; + /** The watch has read the agent's records since the last native workflow call. */ + nativeWorkflowRead: boolean; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -3723,10 +3749,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? context.subagentsBySessionId.get(update.childSessionId) : undefined); const updateIsTerminal = acpSubagentStatusIsTerminal(update.status); + // A native workflow can take on more work after its members all parked. if ( existing !== undefined && acpSubagentStatusIsTerminal(existing.task.status) && - !updateIsTerminal + !updateIsTerminal && + update.workflow === undefined ) { return; } @@ -3734,7 +3762,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( existing !== undefined && existing.task.status === update.status && updateIsTerminal && - existing.terminalStatusProjected + existing.terminalStatusProjected && + update.workflow === undefined ) { return; } @@ -3785,6 +3814,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( startedAt: now, }), model: update.model?.trim() || existing?.task.model || null, + ...(update.workflow === undefined ? {} : { workflow: update.workflow }), status: taskStatus, result: update.result ?? existing?.task.result ?? null, completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null, @@ -3999,6 +4029,255 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + // Last projected state per native workflow and member, across turns of this session. + const nativeWorkflowProjected = new Map>(); + + const projectNativeWorkflowMembers = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + coordinator: ActiveAcpSubagent, + workflow: OrchestrationV2SubagentWorkflow, + ) { + const parentThread = { ...context.input.appThread, id: coordinator.childThreadId }; + const providerInstanceId = context.input.modelSelection.instanceId; + for (const member of workflow.agents) { + const childThreadId = member.childThreadId; + if (childThreadId === undefined) continue; + const memberKey = `${coordinator.childThreadId}:agent:${member.label}`; + const status = + (member.state === "queued" || member.state === "running") && + coordinator.task.status !== "running" + ? coordinator.task.status + : member.state === "queued" + ? "pending" + : member.state; + const prompt = member.prompt ?? member.label; + const result = member.result ?? null; + const model = member.model ?? context.input.modelSelection.model; + const previous = nativeWorkflowProjected.get(memberKey); + const next = [status, model, prompt, result]; + if (previous !== undefined && Equal.equals(previous, next)) continue; + const [, previousModel, previousPrompt, previousResult] = previous ?? []; + nativeWorkflowProjected.set(memberKey, next); + const now = yield* DateTime.now; + const nodeId = providerNodeId(memberKey); + const childRootNodeId = providerNodeId(`${memberKey}:thread-root`); + const nativeItemRef = { driver, nativeId: memberKey, strength: "strong" as const }; + if (previous === undefined || previousModel !== model) { + yield* emitProviderEvent({ + type: "app_thread.created", + driver, + appThread: makeSubagentChildThread({ + parentThread, + childThreadId, + parentNodeId: nodeId, + activeProviderThreadId: null, + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model }, + title: member.label, + now, + createdBy: "agent", + creationSource: "provider", + }), + }); + } + for (const [role, text, ordinal, changed] of [ + ["user", prompt, 100, previousPrompt !== prompt], + ["assistant", result, 200, result !== null && previousResult !== result], + ] as const) { + if (!changed || text === null) continue; + const nativeId = `${memberKey}:${role}`; + const artifacts = makeSubagentConversationArtifacts({ + ...(role === "user" ? { senderThreadId: coordinator.childThreadId } : {}), + messageId: providerMessageId(nativeId), + turnItemId: providerTurnItemId(nativeId), + threadId: childThreadId, + rootNodeId: childRootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: { driver, nativeId, strength: "weak" }, + role, + text, + ordinal, + now, + }); + yield* emitProviderEvent({ + type: "message.updated", + driver, + message: artifacts.message, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver, + turnItem: artifacts.turnItem, + }); + } + const startedAt = + member.startedAt === undefined ? now : DateTime.makeUnsafe(member.startedAt); + const completedAt = acpSubagentStatusIsTerminal(status) + ? member.completedAt === undefined + ? now + : DateTime.makeUnsafe(member.completedAt) + : null; + const nodeBase = { + runId: null, + status, + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }; + yield* emitProviderEvent({ + type: "node.updated", + driver, + node: { + ...nodeBase, + id: nodeId, + threadId: coordinator.childThreadId, + parentNodeId: coordinator.childRootNodeId, + rootNodeId: coordinator.childRootNodeId, + kind: "subagent", + }, + }); + yield* emitProviderEvent({ + type: "node.updated", + driver, + node: { + ...nodeBase, + id: childRootNodeId, + threadId: childThreadId, + parentNodeId: null, + rootNodeId: childRootNodeId, + kind: "root_turn", + }, + }); + yield* emitProviderEvent({ + type: "subagent.updated", + driver, + subagent: { + id: nodeId, + threadId: coordinator.childThreadId, + runId: null, + parentNodeId: coordinator.childRootNodeId, + origin: "provider_native", + createdBy: "agent", + driver, + providerInstanceId, + providerThreadId: null, + childThreadId, + nativeTaskRef: nativeItemRef, + prompt, + title: member.label, + model, + status, + result, + startedAt, + completedAt, + updatedAt: now, + }, + }); + } + }); + + /** Returns whether the session has a native workflow. */ + const syncNativeWorkflow = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if (flavor.nativeWorkflow === undefined) return false; + const snapshot = yield* flavor.nativeWorkflow.read(context.nativeThreadId); + if (snapshot === undefined) return false; + const { nativeTaskId } = snapshot; + const owned = context.subagents.has(nativeTaskId); + const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; + const previous = nativeWorkflowProjected.get(nativeTaskId); + // A finished or unchanged workflow joins a later turn only when that turn manages it. + if ( + (!snapshot.active && !owned && !context.nativeWorkflowToolSeen) || + (previous !== undefined && + Equal.equals(previous, key) && + (owned || !context.nativeWorkflowToolSeen)) + ) { + return true; + } + const coordinatorThreadId = + context.subagents.get(nativeTaskId)?.childThreadId ?? + idAllocator.derive.subagentThread({ + driver, + providerInstanceId: context.input.modelSelection.instanceId, + nativeThreadId: `${context.nativeThreadId}:task:${nativeTaskId}`, + }); + const workflow: OrchestrationV2SubagentWorkflow = { + ...snapshot.workflow, + agents: snapshot.workflow.agents.map((member) => ({ + ...member, + childThreadId: idAllocator.derive.subagentThread({ + driver, + providerInstanceId: context.input.modelSelection.instanceId, + nativeThreadId: `${coordinatorThreadId}:agent:${member.label}`, + }), + })), + }; + const results = workflow.agents.flatMap((member) => + member.result === undefined ? [] : [`${member.label}: ${member.result}`], + ); + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + if (context.finalized) return; + // Members working on the board are the prompt's progress. + context.lastProgressAt = yield* Clock.currentTimeMillis; + yield* emitSubagent(context, { + nativeTaskId, + prompt: snapshot.prompt || snapshot.title, + title: snapshot.title, + model: null, + status: snapshot.active ? "running" : "completed", + childSessionId: null, + result: snapshot.active || results.length === 0 ? null : results.join("\n\n"), + workflow, + }); + const coordinator = context.subagents.get(nativeTaskId); + if (coordinator !== undefined) { + yield* projectNativeWorkflowMembers(context, coordinator, workflow); + } + nativeWorkflowProjected.set(nativeTaskId, key); + yield* rearmDeferredFinalize(context); + }), + ); + return true; + }); + + const watchNativeWorkflow = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if ( + flavor.nativeWorkflow === undefined || + context.nativeWorkflowWatching || + context.finalized + ) { + return; + } + context.nativeWorkflowWatching = true; + yield* Effect.gen(function* () { + while (!context.finalized) { + const exists = yield* syncNativeWorkflow(context); + if (context.nativeWorkflowToolSeen && !context.nativeWorkflowRead) { + context.nativeWorkflowRead = true; + yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); + } + // A turn that never touched a native workflow stops looking once none exists. + if (!exists && !context.nativeWorkflowToolSeen) return; + yield* Effect.sleep(ACP_NATIVE_WORKFLOW_POLL); + } + }).pipe( + Effect.ensuring( + Effect.sync(() => { + context.nativeWorkflowWatching = false; + }), + ), + Effect.ignore, + Effect.forkIn(sessionScope), + ); + }); + const nativeChild = (sessionId: string) => { let child = nativeChildren.get(sessionId); if (child === undefined) { @@ -4350,6 +4629,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ignoreTool?: (tool: AcpToolCallState) => boolean, ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; + // A native workflow call holds the turn until the watch has read its records. + if (context.nativeWorkflowToolSeen && !context.nativeWorkflowRead) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { @@ -4389,8 +4670,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (flavor.subagentsOutlivingPrompt === undefined) return; const nativeTaskId = (subagent: ActiveAcpSubagent) => subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); - const running = [...context.subagents.values()].filter((subagent) => - acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + // The native workflow watch owns its own status. + const running = [...context.subagents.values()].filter( + (subagent) => + subagent.task.workflow === undefined && + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), ); if (running.length === 0) return; const atWork = yield* flavor.subagentsOutlivingPrompt({ @@ -4654,6 +4938,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } + if (flavor.nativeWorkflow?.isTool(toolCall) === true) { + context.nativeWorkflowToolSeen = true; + context.nativeWorkflowRead = false; + yield* watchNativeWorkflow(context); + yield* rearmDeferredFinalize(context); + return; + } // Monitor TaskOutput resembles subagent hydration; do not invent a subagent. const subagentUpdate = hydratedRegisteredMonitor ? undefined @@ -9848,6 +10139,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativePromptId: undefined, lastProgressAt: 0, inactivityWatchdog: undefined, + nativeWorkflowWatching: false, + nativeWorkflowToolSeen: false, + nativeWorkflowRead: false, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; @@ -9865,6 +10159,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); + yield* watchNativeWorkflow(context); const runningTurn = providerTurnPayload(context, "running", null); yield* emitProviderEvent({ type: "provider_turn.updated", From 4b1fc32cb73c02696c9c2ec61186af5f5f7d52c7 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:48:56 +0100 Subject: [PATCH 2/6] fix(antigravity): swarm workflow holds up across turns, big outputs and unreadable boards Review fixes for the /swarm workflow: - A worker parked after a large tool result is read as parked: the reader rereads past the 64 KiB tail when it holds only tool results. - A swarm still at work holds every turn open, not only turns that call it; a read that began before the latest swarm call does not release that hold. - A later turn that takes the workflow over re-announces its worker threads, so its run routes their updates. - The swarm thread opens on its plan like a workflow, and the plan updates when briefs arrive after the title. - Briefs and results that scroll out of the board tail stay on the workflow. - Records unreadable for a minute stop holding the turn open. - A failed `Run swarm` call keeps its tool row; only `[done]` at the start of a post counts as a result; tail and roster reads keep whole records within their caps; bad token counts are skipped; failed workers keep their failure time; the Work dialog shows a worker whose transcript cannot be opened. --- .../Adapters/AntigravityAdapterV2.test.ts | 32 +++- .../src/provider/acp/AntigravityChildWork.ts | 2 +- .../src/provider/acp/AntigravitySwarm.test.ts | 9 +- .../src/provider/acp/AntigravitySwarm.ts | 60 +++++--- docs/user/providers-antigravity.md | 3 +- packages/provider-acp/src/server/adapter.ts | 138 +++++++++++++++--- 6 files changed, 190 insertions(+), 54 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index e370c8c7ee903..781fd11441b54 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2491,7 +2491,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { status: "completed", rawInput, }) as const; - const { startTurn, until, throughPromptSettled, scheduledFinalizes } = + const { startTurn, until, throughPromptSettled, scheduledFinalizes, send } = yield* openSessionWithRunningCommand({}, undefined, undefined, { profileDirectory: profile, initialToolCalls: [ @@ -2506,10 +2506,12 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { ? [event.subagent] : [], ); - const prompt = [ - ...(yield* throughPromptSettled), - ...(yield* until((event) => workflows([event]).length > 0)), - ]; + const settled = yield* throughPromptSettled; + // The first board read can land before or after the reply settles. + const prompt = + workflows(settled).length > 0 + ? settled + : [...settled, ...(yield* until((event) => workflows([event]).length > 0))]; const running = workflows(prompt).at(-1); assert.equal(running?.status, "running"); assert.equal(running?.workflow?.name, "Compute 6*7"); @@ -2521,6 +2523,15 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { JSON.stringify(prompt).includes("Run swarm"), "swarm calls fold into the workflow instead of showing as tools", ); + assert.isTrue( + prompt.some( + (event) => + event.type === "message.updated" && + event.message.threadId === running?.childThreadId && + event.message.workflowScript === true, + ), + "the swarm's thread opens on its plan, like a workflow", + ); yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [ brief, @@ -2561,6 +2572,17 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { ), "the worker's result reaches its own thread", ); + + // A later turn that checks on the swarm takes its card and announces its worker threads, + // so that run routes their updates. + yield* startTurn(2, false); + yield* send(swarmCall("call_status", { action: "status" })); + const later = yield* until((event) => workflows([event]).length > 0); + assert.equal(workflows(later).at(-1)?.runId, "run-antigravity-wake-2"); + const announced = yield* until( + (event) => event.type === "app_thread.created" && event.appThread.id === memberThread, + ); + assert.isNotEmpty(announced); }).pipe(Effect.provide(layerSession)), ); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 89fc7d9e22921..62e960fcf9c0f 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -839,7 +839,7 @@ export const readAntigravitySwarmMemberWork = Effect.fn("readAntigravitySwarmMem { conversationId: input.conversationId }, input.prompt, TRANSCRIPT_BYTE_CAP, - ); + ).catch(() => undefined); return [ { conversationId: input.conversationId, diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 343caed79cd16..2f0fb2d8830f6 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -114,11 +114,16 @@ it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { ...briefs, { seq: 3, agent: "add-a", text: "@coordinator [done] 5", time: "2026-11-23 17:23:21" }, ], - transcripts: { [ADD_A]: parked, [ADD_B]: working }, + // A large result after the parking batch pushes its planner step out of a short tail. + transcripts: { + [ADD_A]: parked.map((step) => + step.step_index === 2 ? { ...step, content: "x".repeat(70_000) } : step, + ), + [ADD_B]: working, + }, }); const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); expect(swarm?.active).toBe(true); - expect(swarm?.head).toBe(3); expect(swarm?.workflow.name).toBe("simple arithmetic addition"); expect( swarm?.workflow.agents.map(({ label, state, prompt, result, model, totalTokens }) => ({ diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index f2f62bad3199e..a367ae2379611 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -15,12 +15,13 @@ import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityPro const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; const MAX_ROSTER_BYTES = 256 * 1024; const BOARD_TAIL_BYTES = 512 * 1024; -const TRANSCRIPT_TAIL_BYTES = 64 * 1024; +const TRANSCRIPT_TAIL_BYTES = [64 * 1024, 1024 * 1024]; const MAX_MEMBERS = 64; const TEXT_CAP = 4_000; // The swarm's own helpers, not task workers; the board view leaves them out the same way. const SUPPORT_ROLE = /^(narrator|monitor)(-\d+)?$/; -const DONE_MARK = /\[done\]/i; +// Workers open a final result with `[done]`, after the @mention that wakes its reader. +const DONE_MARK = /^(?:@[A-Za-z0-9._-]+\s+)*\[done\]/i; /** Native task id T3 gives a swarm, so its record survives every turn of the coordinator thread. */ export const antigravitySwarmTaskId = (sessionId: string) => `swarm:${sessionId}`; @@ -71,8 +72,8 @@ const Step = Schema.Struct({ status: Schema.optional(Schema.String), error: Schema.optional(Schema.String), created_at: Schema.optional(Schema.String), - input_tokens: Schema.optional(Schema.Number), - output_tokens: Schema.optional(Schema.Number), + input_tokens: Schema.optional(Schema.Unknown), + output_tokens: Schema.optional(Schema.Unknown), tool_calls: Schema.optional(Schema.Array(Schema.Struct({ name: Schema.String }))), }); type Step = typeof Step.Type; @@ -90,13 +91,14 @@ async function readTail( const stat = await handle.stat(); if (!stat.isFile()) return undefined; const start = Math.max(0, stat.size - maxBytes); - const buffer = Buffer.alloc(stat.size - start); - const { bytesRead } = await handle.read(buffer, 0, buffer.length, start); - const text = buffer.toString("utf8", 0, bytesRead); - // A cut first line is not a whole record. - return start === 0 - ? { text, whole: true } - : { text: text.slice(text.indexOf("\n") + 1), whole: false }; + // One byte before the window tells a record boundary from a cut record. + const readStart = Math.max(0, start - 1); + const buffer = Buffer.alloc(stat.size - readStart); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, readStart); + const bytes = buffer.subarray(0, bytesRead); + if (start === 0) return { text: bytes.toString("utf8"), whole: true }; + const newline = bytes.indexOf(0x0a); + return { text: newline === -1 ? "" : bytes.toString("utf8", newline + 1), whole: false }; } finally { await handle.close(); } @@ -121,6 +123,9 @@ function epochMillis(value: string | undefined): number | undefined { return Number.isFinite(millis) ? millis : undefined; } +const tokenCount = (value: unknown) => + typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0; + const capText = (value: string) => value.length <= TEXT_CAP ? value : `${value.slice(0, TEXT_CAP)}…`; @@ -163,14 +168,21 @@ async function readActivity( "file", ); if (file === undefined) return undefined; - const tail = await readTail(file.path, TRANSCRIPT_TAIL_BYTES).catch(() => undefined); + let tail: Awaited>; + let steps: ReadonlyArray = []; + // A large tool result can push the planner step that called it out of a short tail. + for (const bytes of TRANSCRIPT_TAIL_BYTES) { + tail = await readTail(file.path, bytes).catch(() => undefined); + if (tail === undefined) return undefined; + steps = lines(tail.text, decodeStep); + if (tail.whole || steps.some((step) => step.type !== "GENERIC")) break; + } if (tail === undefined) return undefined; - const steps = lines(tail.text, decodeStep); const last = steps.at(-1); let tokens = 0; let toolCalls = 0; for (const step of steps) { - tokens += (step.input_tokens ?? 0) + (step.output_tokens ?? 0); + tokens += tokenCount(step.input_tokens) + tokenCount(step.output_tokens); toolCalls += step.tool_calls?.length ?? 0; } return { @@ -208,8 +220,6 @@ export interface AntigravitySwarmSnapshot { readonly prompt: string; /** True while any worker still works; parked and killed workers do not count. */ readonly active: boolean; - /** Board head, so callers can skip unchanged snapshots cheaply. */ - readonly head: number; } /** @@ -230,10 +240,11 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* brainFile(input.sessionId, "swarm", "members.json"), "file", ); - if (rosterFile === undefined || rosterFile.info.size > MAX_ROSTER_BYTES) return undefined; - const roster = Option.getOrUndefined( - decodeRoster(await NodeFSP.readFile(rosterFile.path, "utf8")), - ); + if (rosterFile === undefined) return undefined; + // The cap holds at read time; a roster that outgrew it is not parsed cut. + const rosterText = await readTail(rosterFile.path, MAX_ROSTER_BYTES); + if (rosterText?.whole !== true) return undefined; + const roster = Option.getOrUndefined(decodeRoster(rosterText.text)); if (roster === undefined) return undefined; const coordinator = Object.entries(roster.members).find( ([, member]) => member.role === "coordinator", @@ -308,9 +319,11 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* const resultText = (activity?.failed ?? result?.text)?.trim(); const startedAt = activity?.startedAt ?? epochMillis(brief?.time); const completedAt = - state === "completed" || state === "failed" - ? (epochMillis(result?.time) ?? activity?.lastAt) - : undefined; + state === "failed" + ? activity?.lastAt + : state === "completed" + ? (epochMillis(result?.time) ?? activity?.lastAt) + : undefined; const model = memberModel(member); agents.push({ index, @@ -339,7 +352,6 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* .flatMap((agent) => (agent.prompt === undefined ? [] : [`@${agent.label} ${agent.prompt}`])) .join("\n\n"), active, - head: board.at(-1)?.seq ?? 0, }; }; // An unreadable board means no swarm view this poll; the next poll reads again. diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 1d6de19aaddda..24bcb9d422b97 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -129,7 +129,8 @@ result it posted. Open a worker to read its brief and result, and select **Work* to see its recent steps. The run stays open while any worker is still working. Talk to the swarm through the thread; the coordinator relays your messages to -the workers. **Stop** ends the coordinator's turn but does not remove workers; ask +the workers. A message sent while the swarm works waits for the coordinator's turn +to end unless you steer it. **Stop** ends the coordinator's turn but does not remove workers; ask the coordinator to remove them. The swarm's narrator and monitor are not shown. ## Accounts and removal diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 03808a0368ae7..298b5983de77e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -157,6 +157,8 @@ const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds"; const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); +// One minute of polls. +const ACP_NATIVE_WORKFLOW_UNREADABLE_POLLS = 40; const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -1813,6 +1815,12 @@ interface ActiveAcpTurn { nativeWorkflowToolSeen: boolean; /** The watch has read the agent's records since the last native workflow call. */ nativeWorkflowRead: boolean; + /** Counts native workflow calls, so a read that began before the latest call does not count. */ + nativeWorkflowCalls: number; + /** Native workflow member threads this turn has announced, so its run routes their updates. */ + readonly nativeWorkflowMembers: Set; + /** Polls in a row that could not read a workflow this turn is holding open. */ + nativeWorkflowMisses: number; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -3814,7 +3822,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( startedAt: now, }), model: update.model?.trim() || existing?.task.model || null, - ...(update.workflow === undefined ? {} : { workflow: update.workflow }), + ...(update.workflow === undefined + ? {} + : { workflow: update.workflow, prompt: update.prompt }), status: taskStatus, result: update.result ?? existing?.task.result ?? null, completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null, @@ -3846,6 +3856,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( subagent.task = task; context.subagents.set(nativeTaskId, subagent); + const writesPrompt = + existing === undefined || + (update.workflow !== undefined && update.prompt !== existing.task.prompt); if (existing === undefined) { yield* emitProviderEvent({ type: "app_thread.created", @@ -3871,6 +3884,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( creationSource: "provider", }), }); + } + if (writesPrompt) { const promptNativeItemId = `${nativeTaskId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ senderThreadId: context.input.threadId, @@ -3883,6 +3898,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeItemRef: { driver, nativeId: promptNativeItemId, strength: "weak" }, role: "user", text: update.prompt, + ...(update.workflow === undefined ? {} : { workflowScript: true }), ordinal: 100, now, }); @@ -4054,15 +4070,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const result = member.result ?? null; const model = member.model ?? context.input.modelSelection.model; const previous = nativeWorkflowProjected.get(memberKey); - const next = [status, model, prompt, result]; - if (previous !== undefined && Equal.equals(previous, next)) continue; + const next = [status, model, prompt, result, member.startedAt, member.completedAt]; + if ( + previous !== undefined && + Equal.equals(previous, next) && + context.nativeWorkflowMembers.has(memberKey) + ) + continue; const [, previousModel, previousPrompt, previousResult] = previous ?? []; nativeWorkflowProjected.set(memberKey, next); const now = yield* DateTime.now; const nodeId = providerNodeId(memberKey); const childRootNodeId = providerNodeId(`${memberKey}:thread-root`); const nativeItemRef = { driver, nativeId: memberKey, strength: "strong" as const }; - if (previous === undefined || previousModel !== model) { + // A later turn that takes the workflow over re-announces its members' threads. + if ( + previous === undefined || + previousModel !== model || + !context.nativeWorkflowMembers.has(memberKey) + ) { + context.nativeWorkflowMembers.add(memberKey); yield* emitProviderEvent({ type: "app_thread.created", driver, @@ -4182,24 +4209,77 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + // A workflow whose records stay unreadable this long stops holding the turn open. + const releaseUnreadableNativeWorkflow = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + ) { + const held = [...context.subagents.values()].find( + (subagent) => + subagent.task.workflow !== undefined && + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + ); + if (held === undefined) return; + context.nativeWorkflowMisses += 1; + if (context.nativeWorkflowMisses < ACP_NATIVE_WORKFLOW_UNREADABLE_POLLS) return; + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + if (context.finalized) return; + yield* emitSubagent(context, { + nativeTaskId: held.task.nativeTaskRef?.nativeId ?? held.task.id, + prompt: held.task.prompt, + title: held.task.title, + model: held.task.model, + status: "idle", + childSessionId: null, + result: null, + }); + yield* rearmDeferredFinalize(context); + }), + ); + }); + /** Returns whether the session has a native workflow. */ const syncNativeWorkflow = Effect.fnUntraced(function* (context: ActiveAcpTurn) { if (flavor.nativeWorkflow === undefined) return false; - const snapshot = yield* flavor.nativeWorkflow.read(context.nativeThreadId); - if (snapshot === undefined) return false; - const { nativeTaskId } = snapshot; + const read = yield* flavor.nativeWorkflow.read(context.nativeThreadId); + if (read === undefined) { + yield* releaseUnreadableNativeWorkflow(context); + return false; + } + context.nativeWorkflowMisses = 0; + const { nativeTaskId } = read; + // A brief or result can scroll out of the board's tail; keep what an earlier poll saw. + const earlier = ( + nativeWorkflowProjected.get(nativeTaskId)?.[3] as + | OrchestrationV2SubagentWorkflow + | undefined + )?.agents; + const snapshot = { + ...read, + workflow: { + ...read.workflow, + agents: read.workflow.agents.map((member) => { + const seen = earlier?.find((candidate) => candidate.label === member.label); + return { + ...member, + ...(member.prompt === undefined && seen?.prompt !== undefined + ? { prompt: seen.prompt } + : {}), + ...(member.result === undefined && seen?.result !== undefined + ? { result: seen.result } + : {}), + }; + }), + }, + }; const owned = context.subagents.has(nativeTaskId); const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; const previous = nativeWorkflowProjected.get(nativeTaskId); - // A finished or unchanged workflow joins a later turn only when that turn manages it. - if ( - (!snapshot.active && !owned && !context.nativeWorkflowToolSeen) || - (previous !== undefined && - Equal.equals(previous, key) && - (owned || !context.nativeWorkflowToolSeen)) - ) { - return true; - } + // A working swarm joins every turn; a finished one only a turn that manages it. + const joins = owned + ? previous === undefined || !Equal.equals(previous, key) + : snapshot.active || context.nativeWorkflowToolSeen; + if (!joins) return true; const coordinatorThreadId = context.subagents.get(nativeTaskId)?.childThreadId ?? idAllocator.derive.subagentThread({ @@ -4258,10 +4338,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.nativeWorkflowWatching = true; yield* Effect.gen(function* () { while (!context.finalized) { + const calls = context.nativeWorkflowCalls; const exists = yield* syncNativeWorkflow(context); - if (context.nativeWorkflowToolSeen && !context.nativeWorkflowRead) { + if (calls === context.nativeWorkflowCalls && !context.nativeWorkflowRead) { context.nativeWorkflowRead = true; - yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); + if (exists || context.nativeWorkflowToolSeen) { + yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); + } } // A turn that never touched a native workflow stops looking once none exists. if (!exists && !context.nativeWorkflowToolSeen) return; @@ -4629,8 +4712,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ignoreTool?: (tool: AcpToolCallState) => boolean, ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; - // A native workflow call holds the turn until the watch has read its records. - if (context.nativeWorkflowToolSeen && !context.nativeWorkflowRead) return true; + // A turn waits for the watch to read the agent's records after a native workflow call, + // and at its start once this session has one, so a swarm still at work holds it. + if ( + (context.nativeWorkflowToolSeen || nativeWorkflowProjected.size > 0) && + !context.nativeWorkflowRead + ) + return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { @@ -4938,7 +5026,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } - if (flavor.nativeWorkflow?.isTool(toolCall) === true) { + // A call that failed has no workflow to show its error, so it stays a tool row. + if ( + flavor.nativeWorkflow?.isTool(toolCall) === true && + toolStatus(toolCall.status) !== "failed" + ) { + context.nativeWorkflowCalls += 1; context.nativeWorkflowToolSeen = true; context.nativeWorkflowRead = false; yield* watchNativeWorkflow(context); @@ -10142,6 +10235,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeWorkflowWatching: false, nativeWorkflowToolSeen: false, nativeWorkflowRead: false, + nativeWorkflowCalls: 0, + nativeWorkflowMembers: new Set(), + nativeWorkflowMisses: 0, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; From b73f2dc2bc46357d2acb291cafbae03fcf7ac29b Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:06:32 +0100 Subject: [PATCH 3/6] feat(antigravity): a Swarm toggle sends messages as /swarm, and mobile opens idle workers Swarm is now a model option for every Antigravity model, shown beside Claude's Ultracode in the web picker footer and composer label, and as a switch in the mobile thread settings. While it is on, each message that does not start with a command is sent as `/swarm `. T3 applies it itself, so it never reaches the agent as a session option. On mobile, the agents sheet could not open a workflow member whose thread the shell left out as idle. It now reads the member's thread family, as other screens do, so finished swarm workers and Claude workflow members open. --- .../src/features/threads/ThreadWorkflowGroup.tsx | 12 +++++++++++- .../Adapters/AntigravityAdapterV2.ts | 15 +++++++++++++++ .../src/provider/AntigravityProvider.test.ts | 10 ++++++++-- apps/server/src/provider/AntigravityProvider.ts | 16 +++++++++++++--- .../src/provider/acp/AntigravitySwarm.test.ts | 9 ++++++++- apps/server/src/provider/acp/AntigravitySwarm.ts | 6 ++++++ .../src/components/chat/ComposerModelEffort.tsx | 6 ++++-- docs/user/providers-antigravity.md | 3 ++- packages/client-runtime/src/modelTraits.ts | 5 ++++- 9 files changed, 71 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index 336a904fff5ba..5e860542b373e 100644 --- a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx +++ b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx @@ -24,6 +24,8 @@ import { ListSection } from "../../components/ui/ListSection"; import { RowPressable } from "../../components/ui/RowPressable"; import { cn } from "../../lib/cn"; import { useEnvironmentServerConfig, useThreadShell } from "../../state/entities"; +import { useEnvironmentQuery } from "../../state/query"; +import { threadFamilies } from "../../state/threads"; import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot"; import { SubagentStopButton } from "./SubagentStopButton"; import { @@ -173,7 +175,15 @@ function WorkflowMemberRow(props: { const shell = useThreadShell( threadId === null ? null : scopeThreadRef(props.environmentId, threadId), ); - const canOpen = threadId !== null && shell !== null; + // The shell omits idle subagent threads; their family read still carries the row. + const family = useEnvironmentQuery( + threadId !== null && shell === null + ? threadFamilies.familyAtom(props.environmentId, threadId) + : null, + ); + const canOpen = + threadId !== null && + (shell !== null || family.data?.threads.some((row) => row.id === threadId) === true); const presentation = resolveSubagentRowPresentation( { title: member.title, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b1a5d42fc00a6..e7289166754c8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -5,6 +5,7 @@ import { type OrchestrationV2ProviderCapabilities, type ProviderSetupError, } from "@t3tools/contracts"; +import { getModelSelectionBooleanOptionValue } from "@t3tools/shared/model"; import type { SelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -38,10 +39,12 @@ import { } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { + antigravitySwarmPrompt, antigravitySwarmTaskId, isAntigravitySwarmToolCall, readAntigravitySwarm, } from "../../provider/acp/AntigravitySwarm.ts"; +import { ANTIGRAVITY_SWARM_OPTION } from "../../provider/AntigravityProvider.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, @@ -297,6 +300,18 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, + // The Swarm toggle is T3's, not an agent option: it starts each message with `/swarm`. + ownedModelOptionIds: [ANTIGRAVITY_SWARM_OPTION.id], + rewriteUserText: (text, turnInput) => + Effect.succeed( + antigravitySwarmPrompt( + text, + getModelSelectionBooleanOptionValue( + turnInput.modelSelection, + ANTIGRAVITY_SWARM_OPTION.id, + ), + ), + ), extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, compactViaAdvertisedCommand: true, diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 88589d1c9a773..3c00b4828f564 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -289,14 +289,20 @@ describe("Antigravity model catalog", () => { ["plain", null], ]), ); - const thinkingOf = (slug: string) => - models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors?.[0]; + const descriptorOf = (slug: string, id: string) => + models + .find((model) => model.slug === slug) + ?.capabilities?.optionDescriptors?.find((descriptor) => descriptor.id === id); + const thinkingOf = (slug: string) => descriptorOf(slug, "thinking_level"); expect(thinkingOf("gemini")).toMatchObject({ id: "thinking_level", currentValue: "high" }); expect(thinkingOf("claude")).toMatchObject({ id: "thinking_level", currentValue: "low" }); expect(thinkingOf("plain")).toBeUndefined(); expect(thinkingOf("unseen")).toMatchObject({ id: "thinking_level" }); expect(thinkingOf("unseen")).not.toHaveProperty("currentValue"); + for (const { slug } of models) { + expect(descriptorOf(slug, "swarm")).toMatchObject({ type: "boolean", label: "Swarm" }); + } }); }); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index f5e18f6bece9d..f785757cadf22 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -44,7 +44,6 @@ import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usag import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; -const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; const HEALTH_CHECK_TIMEOUT_MS = 90_000; const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity."; @@ -65,14 +64,25 @@ type ThinkingConfig = NonNullable>; /** Thinking options each model reported when selected; `null` means it has none. */ export type AntigravityThinkingLevels = ReadonlyMap; +/** Sends each message as `/swarm`, so the agent runs it with a team of workers. */ +export const ANTIGRAVITY_SWARM_OPTION = { + id: "swarm", + label: "Swarm", + type: "boolean", +} as const; + function thinkingCapabilities(config: ThinkingConfig | null | undefined, observed: boolean) { const descriptor = config ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0] : undefined; - if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES; + if (descriptor?.type !== "select") { + return createModelCapabilities({ optionDescriptors: [ANTIGRAVITY_SWARM_OPTION] }); + } // Another model's selected level is not this model's default. const { currentValue: _currentValue, ...unobserved } = descriptor; - return createModelCapabilities({ optionDescriptors: [observed ? descriptor : unobserved] }); + return createModelCapabilities({ + optionDescriptors: [observed ? descriptor : unobserved, ANTIGRAVITY_SWARM_OPTION], + }); } export function buildAntigravityModelsFromSession( diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 2f0fb2d8830f6..434dc15a3df1b 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -4,7 +4,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import { readAntigravitySwarm } from "./AntigravitySwarm.ts"; +import { antigravitySwarmPrompt, readAntigravitySwarm } from "./AntigravitySwarm.ts"; const COORDINATOR = "e1eca26b-11b5-41f8-9d9b-bb8a692b2125"; const ADD_A = "a82657e1-5a66-4505-aecc-6844eec6d066"; @@ -200,3 +200,10 @@ it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { }), ); }); + +it("starts a message as /swarm only when the toggle is on and no command is typed", () => { + expect(antigravitySwarmPrompt("fix the tests", true)).toBe("/swarm fix the tests"); + expect(antigravitySwarmPrompt("fix the tests", false)).toBe("fix the tests"); + expect(antigravitySwarmPrompt("/goal ship it", true)).toBe("/goal ship it"); + expect(antigravitySwarmPrompt(" ", true)).toBe(" "); +}); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index a367ae2379611..ed17487d9f7e1 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -23,6 +23,12 @@ const SUPPORT_ROLE = /^(narrator|monitor)(-\d+)?$/; // Workers open a final result with `[done]`, after the @mention that wakes its reader. const DONE_MARK = /^(?:@[A-Za-z0-9._-]+\s+)*\[done\]/i; +/** With the Swarm toggle on, a message the user did not start with a command runs as `/swarm`. */ +export function antigravitySwarmPrompt(text: string, swarm: boolean | undefined): string { + const trimmed = text.trimStart(); + return swarm === true && trimmed !== "" && !trimmed.startsWith("/") ? `/swarm ${text}` : text; +} + /** Native task id T3 gives a swarm, so its record survives every turn of the coordinator thread. */ export const antigravitySwarmTaskId = (sessionId: string) => `swarm:${sessionId}`; diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index b5d5a519a3410..e4f0376a3340d 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -38,14 +38,16 @@ import { type SelectDescriptor = Extract; type BooleanDescriptor = Extract; -/** Service tiers, Claude's Fast mode, and Ultracode sit in the footer, not the column. */ +/** Service tiers, Claude's Fast mode, and team modes (Ultracode, Swarm) sit in the footer. */ function splitSpeed( selects: ReadonlyArray, toggles: ReadonlyArray, ) { const speedSelect = selects.find((descriptor) => descriptor.id === "serviceTier") ?? null; const fastToggle = toggles.find((descriptor) => descriptor.id === "fastMode") ?? null; - const ultracodeToggle = toggles.find((descriptor) => descriptor.id === "ultracode") ?? null; + const ultracodeToggle = + toggles.find((descriptor) => descriptor.id === "ultracode" || descriptor.id === "swarm") ?? + null; return { speedSelect, fastToggle, diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 24bcb9d422b97..be19c82638371 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -123,7 +123,8 @@ activity. ### Swarms -Start a swarm with `/swarm `. The thread shows it as one workflow, titled with +Start a swarm with `/swarm `, or turn on **Swarm** in the model picker to send every +message as a swarm. The thread shows it as one workflow, titled with the swarm's name, with a row for each worker: its brief, model, state, and the result it posted. Open a worker to read its brief and result, and select **Work** to see its recent steps. The run stays open while any worker is still working. diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index da2387da30278..c56396322126e 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -134,7 +134,10 @@ export function buildTraitsTriggerDisplay( speedLabel ?? resolve(msg("Normal", { $context: "model speed tier" })); continue; } - if (descriptor.id === "ultracode" && descriptor.type === "boolean") { + if ( + (descriptor.id === "ultracode" || descriptor.id === "swarm") && + descriptor.type === "boolean" + ) { if (descriptor.currentValue === true) { ultracodeLabelIndex = labels.length; labels.push(descriptor.label); From 4d5bb0b215033f441216681eff6170fa54d33279 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:49:54 +0100 Subject: [PATCH 4/6] fix(antigravity): swarm turns settle and recover reliably; mobile reads one family per workflow Review fixes for the swarm workflow: - A turn that takes over a running swarm after Stop keeps watching its board through failed reads, and settles once the workers park. - Records unreadable for a minute release the hold and idle the worker rows; a running snapshot read after that brings the hold back. - The swarm's plan is rebuilt from every worker's brief, including briefs that scrolled out of the board tail, and updates when briefs arrive after the title. - Workers past the 64 shown still keep the swarm active. - A message the Swarm toggle turns into `/swarm` keeps the app context and instructions the plain message would carry. - Usage is left out when the transcript has an invalid token count. - The mobile agents sheet reads the workflow's thread family once, not once per idle worker. --- .../features/threads/ThreadWorkflowGroup.tsx | 21 +- .../Adapters/AntigravityAdapterV2.test.ts | 286 ++++++++++++------ .../src/provider/acp/AntigravitySwarm.test.ts | 21 ++ .../src/provider/acp/AntigravitySwarm.ts | 32 +- packages/provider-acp/src/server/adapter.ts | 60 ++-- 5 files changed, 298 insertions(+), 122 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index 5e860542b373e..472bc59bdb37a 100644 --- a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx +++ b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx @@ -63,6 +63,15 @@ export function ThreadWorkflowGroup(props: { const open = rail.find((item) => item.key === selected); const label = group.workflow.workflowName ?? group.workflow.title; const statusLabel = resolveSubagentRowPresentation(props.subagent, false, m).statusLabel; + // The shell omits idle subagent threads. One read of the workflow's thread family carries + // every member's row, since members share the coordinator's root thread. + const coordinatorThreadId = props.subagent.childThreadId; + const family = useEnvironmentQuery( + open !== undefined && coordinatorThreadId !== null + ? threadFamilies.familyAtom(props.environmentId, ThreadId.make(coordinatorThreadId)) + : null, + ); + const familyThreadIds = new Set(family.data?.threads.map((row) => row.id)); return ( @@ -152,6 +161,7 @@ export function ThreadWorkflowGroup(props: { key={member.id} environmentId={props.environmentId} member={member} + inFamily={member.childThreadId !== null && familyThreadIds.has(member.childThreadId)} provider={provider} onOpen={props.onOpen} /> @@ -165,6 +175,7 @@ export function ThreadWorkflowGroup(props: { function WorkflowMemberRow(props: { readonly environmentId: EnvironmentId; readonly member: RuntimeSubagent; + readonly inFamily: boolean; readonly provider: ServerProvider | undefined; readonly onOpen: (threadId: ThreadId) => void; }) { @@ -175,15 +186,7 @@ function WorkflowMemberRow(props: { const shell = useThreadShell( threadId === null ? null : scopeThreadRef(props.environmentId, threadId), ); - // The shell omits idle subagent threads; their family read still carries the row. - const family = useEnvironmentQuery( - threadId !== null && shell === null - ? threadFamilies.familyAtom(props.environmentId, threadId) - : null, - ); - const canOpen = - threadId !== null && - (shell !== null || family.data?.threads.some((row) => row.id === threadId) === true); + const canOpen = threadId !== null && (shell !== null || props.inFamily); const presentation = resolveSubagentRowPresentation( { title: member.title, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 781fd11441b54..5ca0382602655 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1575,6 +1575,99 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }; }); +// Frames and files as agy 1.5.14 wrote them for `/swarm`: the coordinator's `swarm` calls +// arrive as `Run swarm`, and workers report only on the board below its session. +const openSwarmSession = Effect.fn("openSwarmSession")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-swarm-", + }); + const brain = (conversationId: string, ...rest: ReadonlyArray) => + path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", ...rest); + const writeLines = (file: string, values: ReadonlyArray) => + fileSystem + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen( + fileSystem.writeFileString( + file, + values.map((value) => JSON.stringify(value)).join("\n") + "\n", + ), + ), + ); + yield* fileSystem.makeDirectory(brain("mock-session-1", "swarm"), { recursive: true }); + yield* fileSystem.writeFileString( + brain("mock-session-1", "swarm", "members.json"), + JSON.stringify({ + title: "Compute 6*7", + members: { + coordinator: { conversation_id: "mock-session-1", role: "coordinator" }, + "mul-a": { conversation_id: "worker-1", role: "worker", model: "gemini-test-low" }, + }, + }), + ); + const brief = { + seq: 1, + agent: "coordinator", + text: "@mul-a Compute 6*7.", + time: "2026-11-23 17:23:18", + kind: "brief", + }; + yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [brief]); + const transcript = brain("worker-1", "logs", "transcript.jsonl"); + yield* writeLines(transcript, [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, + ]); + const swarmCall = (toolCallId: string, rawInput: Record) => + ({ + sessionUpdate: "tool_call", + toolCallId, + kind: "other", + title: "Run swarm", + status: "completed", + rawInput, + }) as const; + const opened = yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [ + swarmCall("call_title", { action: "title", title: "Compute 6*7" }), + swarmCall("call_add", { action: "add", name: "mul-a", brief: "Compute 6*7." }), + ], + }); + const parked = [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE" }, + { step_index: 3, type: "GENERIC", status: "DONE" }, + ]; + const workflows = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "subagent.updated" && event.subagent.workflow !== undefined + ? [event.subagent] + : [], + ); + return { + ...opened, + brain, + brief, + transcript, + writeLines, + swarmCall, + parked, + workflows, + board: brain("mock-session-1", "swarm", "board.jsonl"), + roster: brain("mock-session-1", "swarm", "members.json"), + fileSystem, + }; +}); + describe("AntigravityAdapterV2 work after the prompt ends", () => { // agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies // with no prompt open. @@ -2429,83 +2522,11 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); - // Frames and files as agy 1.5.14 wrote them for `/swarm`: the coordinator's `swarm` calls - // arrive as `Run swarm`, and workers report only on the board below its session. it.effect("shows a swarm as one workflow that runs until its workers park", () => Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const profile = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-antigravity-swarm-", - }); - const brain = (conversationId: string, ...rest: ReadonlyArray) => - path.join( - profile, - "antigravity-acp", - "brain", - conversationId, - ".system_generated", - ...rest, - ); - const writeLines = (file: string, values: ReadonlyArray) => - fileSystem - .makeDirectory(path.dirname(file), { recursive: true }) - .pipe( - Effect.andThen( - fileSystem.writeFileString( - file, - values.map((value) => JSON.stringify(value)).join("\n") + "\n", - ), - ), - ); - yield* fileSystem.makeDirectory(brain("mock-session-1", "swarm"), { recursive: true }); - yield* fileSystem.writeFileString( - brain("mock-session-1", "swarm", "members.json"), - JSON.stringify({ - title: "Compute 6*7", - members: { - coordinator: { conversation_id: "mock-session-1", role: "coordinator" }, - "mul-a": { conversation_id: "worker-1", role: "worker", model: "gemini-test-low" }, - }, - }), - ); - const brief = { - seq: 1, - agent: "coordinator", - text: "@mul-a Compute 6*7.", - time: "2026-11-23 17:23:18", - kind: "brief", - }; - yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [brief]); - const transcript = brain("worker-1", "logs", "transcript.jsonl"); - yield* writeLines(transcript, [ - { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, - { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, - ]); - const swarmCall = (toolCallId: string, rawInput: Record) => - ({ - sessionUpdate: "tool_call", - toolCallId, - kind: "other", - title: "Run swarm", - status: "completed", - rawInput, - }) as const; - const { startTurn, until, throughPromptSettled, scheduledFinalizes, send } = - yield* openSessionWithRunningCommand({}, undefined, undefined, { - profileDirectory: profile, - initialToolCalls: [ - swarmCall("call_title", { action: "title", title: "Compute 6*7" }), - swarmCall("call_add", { action: "add", name: "mul-a", brief: "Compute 6*7." }), - ], - }); + const swarm = yield* openSwarmSession(); + const { startTurn, until, throughPromptSettled, scheduledFinalizes, send, workflows } = swarm; yield* startTurn(1, false); - const workflows = (events: ReadonlyArray) => - events.flatMap((event) => - event.type === "subagent.updated" && event.subagent.workflow !== undefined - ? [event.subagent] - : [], - ); const settled = yield* throughPromptSettled; // The first board read can land before or after the reply settles. const prompt = @@ -2533,21 +2554,11 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { "the swarm's thread opens on its plan, like a workflow", ); - yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [ - brief, + yield* swarm.writeLines(swarm.board, [ + swarm.brief, { seq: 2, agent: "mul-a", text: "@coordinator [done] 42", time: "2026-11-23 17:23:21" }, ]); - yield* writeLines(transcript, [ - { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, - { - step_index: 1, - type: "PLANNER_RESPONSE", - status: "DONE", - tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], - }, - { step_index: 2, type: "GENERIC", status: "DONE" }, - { step_index: 3, type: "GENERIC", status: "DONE" }, - ]); + yield* swarm.writeLines(swarm.transcript, swarm.parked); // One poll reads the parked worker; the idle swarm then schedules the turn's end. yield* TestClock.adjust("2 seconds"); const parkedRun = yield* until((event) => workflows([event]).at(-1)?.status === "completed"); @@ -2576,7 +2587,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { // A later turn that checks on the swarm takes its card and announces its worker threads, // so that run routes their updates. yield* startTurn(2, false); - yield* send(swarmCall("call_status", { action: "status" })); + yield* send(swarm.swarmCall("call_status", { action: "status" })); const later = yield* until((event) => workflows([event]).length > 0); assert.equal(workflows(later).at(-1)?.runId, "run-antigravity-wake-2"); const announced = yield* until( @@ -2586,6 +2597,105 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.effect("rewrites the swarm's plan when briefs arrive after its title", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* swarm.writeLines(swarm.board, []); + yield* startTurn(1, false); + const plan = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "message.updated" && event.message.workflowScript === true + ? [event.message.text] + : [], + ); + const first = yield* until((event) => plan([event]).length > 0); + assert.equal(plan(first).at(-1), "Compute 6*7"); + yield* swarm.writeLines(swarm.board, [swarm.brief]); + yield* TestClock.adjust("2 seconds"); + const rewritten = yield* until((event) => plan([event]).length > 0); + assert.equal(plan(rewritten).at(-1), "@mul-a Compute 6*7."); + // A brief that scrolls out of the board's tail stays on the plan and the worker. + yield* swarm.writeLines(swarm.board, []); + yield* swarm.writeLines(swarm.transcript, [ + ...swarm.parked.slice(0, 1), + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + input_tokens: 5, + tool_calls: [{ name: "y" }], + }, + ]); + yield* TestClock.adjust("2 seconds"); + const kept = yield* until((event) => workflows([event]).at(-1)?.workflow?.totalTokens === 5); + assert.equal(workflows(kept).at(-1)?.prompt, "@mul-a Compute 6*7."); + assert.equal(workflows(kept).at(-1)?.workflow?.agents[0]?.prompt, "Compute 6*7."); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a turn after Stop waits for a swarm still at work, through unreadable polls", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows, fileSystem, session, providerThread } = swarm; + yield* startTurn(1, false); + const started = yield* until((event) => workflows([event]).at(-1)?.status === "running"); + const turn = started.find((event) => event.type === "provider_turn.updated"); + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); + yield* session.interruptTurn({ providerThread, providerTurnId: turn.providerTurn.id }); + yield* until((event) => event.type === "turn.terminal"); + // Turn 2 makes no swarm call; the workers still work, so the turn stays open. + yield* startTurn(2, false); + yield* swarm.releaseSteer; + yield* until((event) => workflows([event]).at(-1)?.runId === "run-antigravity-wake-2"); + // One unreadable poll must not end the watch while the swarm holds the turn. + const roster = yield* fileSystem.readFileString(swarm.roster); + yield* fileSystem.writeFileString(swarm.roster, "{"); + yield* TestClock.adjust("2 seconds"); + yield* TestClock.withLive(Effect.sleep("50 millis")); + yield* fileSystem.writeFileString(swarm.roster, roster); + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* TestClock.adjust("2 seconds"); + yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* Queue.take(swarm.scheduledFinalizes); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a swarm whose records stay unreadable stops holding the turn", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows, fileSystem } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + const roster = yield* fileSystem.readFileString(swarm.roster); + yield* fileSystem.writeFileString(swarm.roster, "{"); + // Polls step the test clock: the first unreadable one starts the minute, a later one ends it. + yield* TestClock.adjust("2 seconds"); + yield* TestClock.withLive(Effect.sleep("50 millis")); + yield* TestClock.adjust("61 seconds"); + const released = yield* until( + (event) => + event.type === "subagent.updated" && + event.subagent.title === "mul-a" && + event.subagent.status === "idle", + ); + assert.equal(workflows(released).at(-1)?.status, "idle"); + // Records readable again with the worker still at work bring the hold back. + yield* fileSystem.writeFileString(swarm.roster, roster); + yield* TestClock.adjust("2 seconds"); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* TestClock.adjust("2 seconds"); + yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + it.effect.each([ // session/cancel ends the agent's commands, so only Stop may send it. { ending: "Stop", cancels: 1, status: "interrupted" }, diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 434dc15a3df1b..7a0b4f4068dbb 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -186,6 +186,27 @@ it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { }), ); + it.effect("leaves usage out when a count is not a valid number", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + "add-a": member(ADD_A, "worker"), + }, + board: briefs, + transcripts: { + [ADD_A]: [ + started, + { step_index: 1, type: "PLANNER_RESPONSE", input_tokens: -1, output_tokens: 5 }, + ], + }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.workflow.agents[0]?.totalTokens).toBeUndefined(); + expect(swarm?.workflow.totalTokens).toBeUndefined(); + }), + ); + it.effect("reads only the swarm this session coordinates", () => Effect.gen(function* () { const profileDirectory = yield* writeSwarm({ diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index ed17487d9f7e1..f6a888f15da6f 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -130,7 +130,11 @@ function epochMillis(value: string | undefined): number | undefined { } const tokenCount = (value: unknown) => - typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0; + value === undefined + ? 0 + : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : undefined; const capText = (value: string) => value.length <= TEXT_CAP ? value : `${value.slice(0, TEXT_CAP)}…`; @@ -185,10 +189,16 @@ async function readActivity( } if (tail === undefined) return undefined; const last = steps.at(-1); - let tokens = 0; + // An invalid count makes the total unknown, not smaller. + let tokens: number | undefined = 0; let toolCalls = 0; for (const step of steps) { - tokens += tokenCount(step.input_tokens) + tokenCount(step.output_tokens); + const input = tokenCount(step.input_tokens); + const output = tokenCount(step.output_tokens); + tokens = + tokens === undefined || input === undefined || output === undefined + ? undefined + : tokens + input + output; toolCalls += step.tool_calls?.length ?? 0; } return { @@ -199,7 +209,7 @@ async function readActivity( : undefined, startedAt: epochMillis(steps[0]?.created_at), lastAt: epochMillis(last?.created_at), - usage: tail.whole ? { totalTokens: tokens, toolCalls } : undefined, + usage: tail.whole && tokens !== undefined ? { totalTokens: tokens, toolCalls } : undefined, }; } @@ -290,13 +300,12 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* ([left], [right]) => (briefs.get(left)?.seq ?? Number.MAX_SAFE_INTEGER) - (briefs.get(right)?.seq ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right), - ) - .slice(0, MAX_MEMBERS); + ); let active = false; let totalTokens: number | undefined = 0; let toolCalls = 0; const agents: Array = []; - for (const [index, [name, member]] of workers.entries()) { + for (const [index, [name, member]] of workers.slice(0, MAX_MEMBERS).entries()) { const conversationId = member.conversation_id; const activity = conversationId !== undefined && NATIVE_ID.test(conversationId) @@ -346,6 +355,15 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* ...(resultText === undefined || resultText === "" ? {} : { result: capText(resultText) }), }); } + // Workers past the cap are not shown, but one still at work keeps the swarm active. + for (const [, member] of workers.slice(MAX_MEMBERS)) { + if (active || killed(member) || member.conversation_id === undefined) continue; + if (!NATIVE_ID.test(member.conversation_id)) continue; + const activity = await readActivity(profileRoot, member.conversation_id).catch( + () => undefined, + ); + if (activity !== undefined && !activity.ended && activity.failed === undefined) active = true; + } const title = roster.title?.trim(); return { workflow: { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 298b5983de77e..1e1dbe8c87ee1 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -157,8 +157,7 @@ const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds"; const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); -// One minute of polls. -const ACP_NATIVE_WORKFLOW_UNREADABLE_POLLS = 40; +const ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS = 60_000; const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -1819,8 +1818,8 @@ interface ActiveAcpTurn { nativeWorkflowCalls: number; /** Native workflow member threads this turn has announced, so its run routes their updates. */ readonly nativeWorkflowMembers: Set; - /** Polls in a row that could not read a workflow this turn is holding open. */ - nativeWorkflowMisses: number; + /** Clock millis when reads of a workflow this turn holds open began to fail, if they fail. */ + nativeWorkflowUnreadableSince: number | undefined; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -3803,6 +3802,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const turnItemOrdinal = existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(context, nativeTaskId)); const taskStatus = update.status; + const writesPrompt = + existing === undefined || + (update.workflow !== undefined && update.prompt !== existing.task.prompt); const task: OrchestrationV2Subagent = { ...(existing?.task ?? { id: nodeId, @@ -3856,9 +3858,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( subagent.task = task; context.subagents.set(nativeTaskId, subagent); - const writesPrompt = - existing === undefined || - (update.workflow !== undefined && update.prompt !== existing.task.prompt); if (existing === undefined) { yield* emitProviderEvent({ type: "app_thread.created", @@ -4219,8 +4218,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( acpSubagentStatusBlocksTurnSettlement(subagent.task.status), ); if (held === undefined) return; - context.nativeWorkflowMisses += 1; - if (context.nativeWorkflowMisses < ACP_NATIVE_WORKFLOW_UNREADABLE_POLLS) return; + const now = yield* Clock.currentTimeMillis; + context.nativeWorkflowUnreadableSince ??= now; + if (now - context.nativeWorkflowUnreadableSince < ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS) { + return; + } yield* runtimeCallbackPermit.withPermit( Effect.gen(function* () { if (context.finalized) return; @@ -4233,6 +4235,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( childSessionId: null, result: null, }); + // Workers still shown as working take the coordinator's idle status with it. + if (held.task.workflow !== undefined) { + yield* projectNativeWorkflowMembers(context, held, held.task.workflow); + } + // A readable snapshot after this projects again, even one that matches the last. + nativeWorkflowProjected.delete(held.task.nativeTaskRef?.nativeId ?? held.task.id); yield* rearmDeferredFinalize(context); }), ); @@ -4246,7 +4254,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* releaseUnreadableNativeWorkflow(context); return false; } - context.nativeWorkflowMisses = 0; + context.nativeWorkflowUnreadableSince = undefined; const { nativeTaskId } = read; // A brief or result can scroll out of the board's tail; keep what an earlier poll saw. const earlier = ( @@ -4254,7 +4262,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( | OrchestrationV2SubagentWorkflow | undefined )?.agents; - const snapshot = { + const merged = { ...read, workflow: { ...read.workflow, @@ -4272,6 +4280,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }), }, }; + // The plan lists every brief, so it is built from the members after the merge. + const briefs = merged.workflow.agents.flatMap((member) => + member.prompt === undefined ? [] : [`@${member.label} ${member.prompt}`], + ); + const snapshot = { + ...merged, + prompt: briefs.length === 0 ? merged.prompt : briefs.join("\n\n"), + }; const owned = context.subagents.has(nativeTaskId); const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; const previous = nativeWorkflowProjected.get(nativeTaskId); @@ -4340,14 +4356,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( while (!context.finalized) { const calls = context.nativeWorkflowCalls; const exists = yield* syncNativeWorkflow(context); + const held = [...context.subagents.values()].some( + (subagent) => + subagent.task.workflow !== undefined && + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + ); if (calls === context.nativeWorkflowCalls && !context.nativeWorkflowRead) { + const waited = context.nativeWorkflowToolSeen || nativeWorkflowProjected.size > 0; context.nativeWorkflowRead = true; - if (exists || context.nativeWorkflowToolSeen) { - yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); - } + // The read held this turn open; it may settle now. + if (waited) yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); } - // A turn that never touched a native workflow stops looking once none exists. - if (!exists && !context.nativeWorkflowToolSeen) return; + // A turn that never touched a native workflow stops looking once none exists; one a + // workflow holds open keeps looking until it ends or its records stay unreadable. + if (!exists && !context.nativeWorkflowToolSeen && !held) return; yield* Effect.sleep(ACP_NATIVE_WORKFLOW_POLL); } }).pipe( @@ -9629,7 +9651,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); - const isNativeSlashCommand = userText.trimStart().startsWith("/"); + // A message the flavor turned into a command (Antigravity's Swarm toggle) still carries + // the context and instructions the user's own message would. + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); const attachmentBlocks = yield* promptAttachmentBlocks( messageText, turnInput.message.attachments, @@ -10237,7 +10261,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeWorkflowRead: false, nativeWorkflowCalls: 0, nativeWorkflowMembers: new Set(), - nativeWorkflowMisses: 0, + nativeWorkflowUnreadableSince: undefined, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; From 21498056a3c869261759f162693b58510d4c1466 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:28:20 +0100 Subject: [PATCH 5/6] =?UTF-8?q?fix(antigravity):=20swarm=20review=20round?= =?UTF-8?q?=204=20=E2=80=94=20commands,=20recovery=20and=20stalled=20board?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Grok's `$deploy` rewrite is a bare command again: only a rewrite that keeps the user's message (Antigravity's Swarm toggle) keeps context and T3 instructions, and those go in blocks after `/swarm` so it stays first. - A swarm released as unreadable keeps the briefs and results it had, and the turn keeps watching so a recovery holds it again. - A swarm whose readable records stop changing for 15 minutes, as long as a prompt may go silent, stops holding the turn. - A worker past the 64 shown that has not started keeps the swarm active. - Worker rows still open show idle when their workflow goes idle. - Swarm tests wait for the watch's reads instead of sleeping. --- .../Adapters/AntigravityAdapterV2.test.ts | 78 +++++++++++-- .../Adapters/AntigravityAdapterV2.ts | 1 + .../src/provider/acp/AntigravitySwarm.test.ts | 20 ++++ .../src/provider/acp/AntigravitySwarm.ts | 17 +-- .../src/state/subagentRuntime.test.ts | 13 +++ .../src/state/subagentRuntime.ts | 3 +- packages/provider-acp/src/server/adapter.ts | 105 +++++++++++++----- 7 files changed, 193 insertions(+), 44 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5ca0382602655..5c6bd24a1bca9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1364,6 +1364,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; const offers: Array = []; const scheduledFinalizes = yield* Queue.unbounded(); + const workflowReads = yield* Queue.unbounded(); const instanceId = ProviderInstanceId.make("antigravity-wake-test"); const threadId = ThreadId.make("thread-antigravity-wake"); const selfInvocation = yield* resolveSelfInvocation(); @@ -1463,6 +1464,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") : { continuationRequests: adapterOptions.continuationRequests }), testHooks: { onDeferredFinalizeScheduled: (debounce) => Queue.offer(scheduledFinalizes, debounce), + afterNativeWorkflowRead: () => Queue.offer(workflowReads, undefined), }, }); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ @@ -1497,7 +1499,11 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") runtimePolicy, }); const now = yield* DateTime.now; - const startTurn = (ordinal: number, continuation: boolean) => + const startTurn = ( + ordinal: number, + continuation: boolean, + extra?: Pick, + ) => session.startTurn({ appThread: { createdBy: "user", @@ -1539,6 +1545,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }, modelSelection, runtimePolicy, + ...extra, }); return { @@ -1548,6 +1555,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") usage, offers, scheduledFinalizes, + workflowReads, send, startTurn, until, @@ -1653,8 +1661,15 @@ const openSwarmSession = Effect.fn("openSwarmSession")(function* () { ? [event.subagent] : [], ); + // The watch reads files off the test clock: step to its next poll and wait for that read. + const readAfterPoll = Effect.gen(function* () { + yield* Queue.clear(opened.workflowReads); + yield* TestClock.adjust("2 seconds"); + yield* Queue.take(opened.workflowReads); + }); return { ...opened, + readAfterPoll, brain, brief, transcript, @@ -2597,6 +2612,32 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.effect("the Swarm toggle sends a plain message as /swarm with its app context", () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({}); + yield* opened.startTurn(1, false, { + modelSelection: { + instanceId: ProviderInstanceId.make("antigravity-wake-test"), + model: "gemini-test-low", + options: [{ id: "swarm", value: true }], + }, + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* opened.throughPromptSettled; + const sent = opened.prompts[0]!.prompt.flatMap((block) => + block.type === "text" ? [block.text] : [], + ); + assert.isTrue( + sent.some((text) => text.startsWith("/swarm chart the throughput")), + "the message runs as a swarm", + ); + assert.isTrue( + sent.some((text) => text.includes("Created Jira issue PROJ-42")), + "the swarm gets the context the plain message would", + ); + }).pipe(Effect.provide(layerSession)), + ); + it.effect("rewrites the swarm's plan when briefs arrive after its title", () => Effect.gen(function* () { const swarm = yield* openSwarmSession(); @@ -2651,8 +2692,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { // One unreadable poll must not end the watch while the swarm holds the turn. const roster = yield* fileSystem.readFileString(swarm.roster); yield* fileSystem.writeFileString(swarm.roster, "{"); - yield* TestClock.adjust("2 seconds"); - yield* TestClock.withLive(Effect.sleep("50 millis")); + yield* swarm.readAfterPoll; yield* fileSystem.writeFileString(swarm.roster, roster); yield* swarm.writeLines(swarm.transcript, swarm.parked); yield* TestClock.adjust("2 seconds"); @@ -2664,6 +2704,23 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.effect("a swarm whose records stop changing stops holding the turn", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + // A worker whose transcript cannot be read stays queued with nothing on the board changing. + yield* swarm.readAfterPoll; + yield* TestClock.adjust("15 minutes"); + yield* swarm.readAfterPoll; + yield* until((event) => workflows([event]).at(-1)?.status === "idle"); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + it.effect("a swarm whose records stay unreadable stops holding the turn", () => Effect.gen(function* () { const swarm = yield* openSwarmSession(); @@ -2672,10 +2729,10 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* until((event) => workflows([event]).at(-1)?.status === "running"); const roster = yield* fileSystem.readFileString(swarm.roster); yield* fileSystem.writeFileString(swarm.roster, "{"); - // Polls step the test clock: the first unreadable one starts the minute, a later one ends it. - yield* TestClock.adjust("2 seconds"); - yield* TestClock.withLive(Effect.sleep("50 millis")); - yield* TestClock.adjust("61 seconds"); + // The first unreadable read starts the minute; one a minute later ends it. + yield* swarm.readAfterPoll; + yield* TestClock.adjust("59 seconds"); + yield* swarm.readAfterPoll; const released = yield* until( (event) => event.type === "subagent.updated" && @@ -2683,10 +2740,13 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { event.subagent.status === "idle", ); assert.equal(workflows(released).at(-1)?.status, "idle"); - // Records readable again with the worker still at work bring the hold back. + // Records readable again with the worker still at work bring the hold back, keeping the + // brief that has since left the board's tail. yield* fileSystem.writeFileString(swarm.roster, roster); + yield* swarm.writeLines(swarm.board, []); yield* TestClock.adjust("2 seconds"); - yield* until((event) => workflows([event]).at(-1)?.status === "running"); + const resumed = yield* until((event) => workflows([event]).at(-1)?.status === "running"); + assert.equal(workflows(resumed).at(-1)?.prompt, "@mul-a Compute 6*7."); yield* swarm.writeLines(swarm.transcript, swarm.parked); yield* TestClock.adjust("2 seconds"); yield* until((event) => workflows([event]).at(-1)?.status === "completed"); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index e7289166754c8..c169f3e213522 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -302,6 +302,7 @@ export function makeAntigravityAcpAdapterFlavor( normalizeToolCall: normalizeAntigravityToolCall, // The Swarm toggle is T3's, not an agent option: it starts each message with `/swarm`. ownedModelOptionIds: [ANTIGRAVITY_SWARM_OPTION.id], + rewriteKeepsUserMessage: true, rewriteUserText: (text, turnInput) => Effect.succeed( antigravitySwarmPrompt( diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 7a0b4f4068dbb..c6ab2815ebf85 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -207,6 +207,26 @@ it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { }), ); + it.effect("a worker past the shown 64 that has not started keeps the swarm active", () => + Effect.gen(function* () { + const finished = Object.fromEntries( + Array.from({ length: 64 }, (_, index) => [`w-${index}`, member(ADD_A, "worker")]), + ); + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + ...finished, + "zz-late": member("cccccccc-0000-0000-0000-000000000000", "worker"), + }, + board: [], + transcripts: { [ADD_A]: parked }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.workflow.agents).toHaveLength(64); + expect(swarm?.active).toBe(true); + }), + ); + it.effect("reads only the swarm this session coordinates", () => Effect.gen(function* () { const profileDirectory = yield* writeSwarm({ diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index f6a888f15da6f..93bef04b4f26a 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -355,14 +355,17 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* ...(resultText === undefined || resultText === "" ? {} : { result: capText(resultText) }), }); } - // Workers past the cap are not shown, but one still at work keeps the swarm active. + // Workers past the cap are not shown, but one queued or at work keeps the swarm active. for (const [, member] of workers.slice(MAX_MEMBERS)) { - if (active || killed(member) || member.conversation_id === undefined) continue; - if (!NATIVE_ID.test(member.conversation_id)) continue; - const activity = await readActivity(profileRoot, member.conversation_id).catch( - () => undefined, - ); - if (activity !== undefined && !activity.ended && activity.failed === undefined) active = true; + if (active || killed(member)) continue; + const conversationId = member.conversation_id; + const activity = + conversationId !== undefined && NATIVE_ID.test(conversationId) + ? await readActivity(profileRoot, conversationId).catch(() => undefined) + : undefined; + if (activity === undefined || (!activity.ended && activity.failed === undefined)) { + active = true; + } } const title = roster.title?.trim(); return { diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 3512956af25fc..ae85009a1a939 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -210,6 +210,19 @@ describe("deriveWorkflowGroups over a dynamic workflow", () => { expect(groups[0]?.phases[0]?.title).toBe("Review"); }); + it("shows open members idle once their workflow goes idle", () => { + const [, open, done] = projectedSubagentsToRuntime([ + subagent({ + status: "idle", + workflow: { + phases: [], + agents: [member(), member({ index: 2, label: "beta", state: "completed" })], + }, + }), + ]); + expect([open?.status, done?.status]).toEqual(["idle", "completed"]); + }); + it("keeps unphased members with their workflow and excludes unrelated agents", () => { const runtime = projectedSubagentsToRuntime([ subagent({ id: "ordinary" }), diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index b6efb9cac132e..00f25dc00beab 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -141,9 +141,10 @@ function workflowMembersToRuntime( workflow: OrchestrationV2SubagentWorkflow, ): ReadonlyArray { return workflow.agents.map((agent) => { + // A workflow that stopped (or went idle with nothing left to watch) stops its open members. const status = (agent.state === "queued" || agent.state === "running") && - isTerminalSubagentStatus(coordinator.status) + (isTerminalSubagentStatus(coordinator.status) || coordinator.status === "idle") ? coordinator.status : agent.state === "queued" ? "pending" diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 1e1dbe8c87ee1..37933486c95a1 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -158,6 +158,8 @@ const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds"; const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); const ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS = 60_000; +// As long as an open prompt may go silent: a workflow whose records stop changing stops holding. +const ACP_NATIVE_WORKFLOW_STALL_MILLIS = 15 * 60_000; const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -443,6 +445,8 @@ export interface AcpAdapterV2Flavor { text: string, turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, ) => Effect.Effect; + /** The rewrite only wraps the user's message, so it is treated as the message it wraps. */ + readonly rewriteKeepsUserMessage?: boolean; readonly driver: ProviderDriverKind; readonly capabilities: OrchestrationV2ProviderCapabilities; readonly supportsNativeGoals?: Effect.Effect; @@ -856,6 +860,8 @@ export interface AcpAdapterV2Options { readonly afterPromptWireSettled?: () => Effect.Effect; readonly afterPromptSettledWithBackgroundWork?: () => Effect.Effect; readonly afterPromptCallback?: () => Effect.Effect; + /** The native workflow watch finished one read of the agent's records. */ + readonly afterNativeWorkflowRead?: () => Effect.Effect; readonly onNativeResponseLifecycle?: (event: { readonly generation?: number; readonly requestId?: string; @@ -1820,6 +1826,8 @@ interface ActiveAcpTurn { readonly nativeWorkflowMembers: Set; /** Clock millis when reads of a workflow this turn holds open began to fail, if they fail. */ nativeWorkflowUnreadableSince: number | undefined; + /** Clock millis when the workflow's records last changed during this turn. */ + nativeWorkflowChangedAt: number | undefined; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -4209,20 +4217,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); // A workflow whose records stay unreadable this long stops holding the turn open. - const releaseUnreadableNativeWorkflow = Effect.fnUntraced(function* ( - context: ActiveAcpTurn, - ) { - const held = [...context.subagents.values()].find( + const heldNativeWorkflow = (context: ActiveAcpTurn) => + [...context.subagents.values()].find( (subagent) => subagent.task.workflow !== undefined && acpSubagentStatusBlocksTurnSettlement(subagent.task.status), ); - if (held === undefined) return; + + const releaseUnreadableNativeWorkflow = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + ) { + if (heldNativeWorkflow(context) === undefined) return; const now = yield* Clock.currentTimeMillis; context.nativeWorkflowUnreadableSince ??= now; if (now - context.nativeWorkflowUnreadableSince < ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS) { return; } + yield* releaseNativeWorkflowHold(context); + }); + + // The workflow goes idle with its workers, so the turn settles; a later read that shows + // it at work holds the turn again. + const releaseNativeWorkflowHold = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + const held = heldNativeWorkflow(context); + if (held === undefined) return; yield* runtimeCallbackPermit.withPermit( Effect.gen(function* () { if (context.finalized) return; @@ -4239,8 +4257,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (held.task.workflow !== undefined) { yield* projectNativeWorkflowMembers(context, held, held.task.workflow); } - // A readable snapshot after this projects again, even one that matches the last. - nativeWorkflowProjected.delete(held.task.nativeTaskRef?.nativeId ?? held.task.id); yield* rearmDeferredFinalize(context); }), ); @@ -4254,7 +4270,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* releaseUnreadableNativeWorkflow(context); return false; } + const recovered = context.nativeWorkflowUnreadableSince !== undefined; context.nativeWorkflowUnreadableSince = undefined; + // Records that read again after a failure count as a change for the stall clock. + if (recovered) context.nativeWorkflowChangedAt = undefined; const { nativeTaskId } = read; // A brief or result can scroll out of the board's tail; keep what an earlier poll saw. const earlier = ( @@ -4291,9 +4310,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const owned = context.subagents.has(nativeTaskId); const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; const previous = nativeWorkflowProjected.get(nativeTaskId); + const changed = previous === undefined || !Equal.equals(previous, key); + const now = yield* Clock.currentTimeMillis; + if (changed || context.nativeWorkflowChangedAt === undefined) { + context.nativeWorkflowChangedAt = now; + } else if (now - context.nativeWorkflowChangedAt >= ACP_NATIVE_WORKFLOW_STALL_MILLIS) { + // Records that read fine but stop changing (a worker whose transcript cannot be + // read stays queued) must not hold the turn forever. + yield* releaseNativeWorkflowHold(context); + return true; + } // A working swarm joins every turn; a finished one only a turn that manages it. + // One released as unreadable resumes once its records show it at work again. + const card = context.subagents.get(nativeTaskId); + const resumes = + snapshot.active && + card !== undefined && + !acpSubagentStatusBlocksTurnSettlement(card.task.status) && + context.nativeWorkflowUnreadableSince === undefined && + now - context.nativeWorkflowChangedAt < ACP_NATIVE_WORKFLOW_STALL_MILLIS; const joins = owned - ? previous === undefined || !Equal.equals(previous, key) + ? changed || resumes : snapshot.active || context.nativeWorkflowToolSeen; if (!joins) return true; const coordinatorThreadId = @@ -4356,10 +4393,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( while (!context.finalized) { const calls = context.nativeWorkflowCalls; const exists = yield* syncNativeWorkflow(context); - const held = [...context.subagents.values()].some( - (subagent) => - subagent.task.workflow !== undefined && - acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + yield* options.testHooks?.afterNativeWorkflowRead?.() ?? Effect.void; + const owns = [...context.subagents.values()].some( + (subagent) => subagent.task.workflow !== undefined, ); if (calls === context.nativeWorkflowCalls && !context.nativeWorkflowRead) { const waited = context.nativeWorkflowToolSeen || nativeWorkflowProjected.size > 0; @@ -4367,9 +4403,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // The read held this turn open; it may settle now. if (waited) yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); } - // A turn that never touched a native workflow stops looking once none exists; one a - // workflow holds open keeps looking until it ends or its records stay unreadable. - if (!exists && !context.nativeWorkflowToolSeen && !held) return; + // A turn that never touched a native workflow stops looking once none exists; one + // that shows a workflow keeps looking until it settles, so it sees a recovery. + if (!exists && !context.nativeWorkflowToolSeen && !owns) return; yield* Effect.sleep(ACP_NATIVE_WORKFLOW_POLL); } }).pipe( @@ -9651,9 +9687,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); - // A message the flavor turned into a command (Antigravity's Swarm toggle) still carries - // the context and instructions the user's own message would. - const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); + // A rewrite that keeps the user's message as the command's task (Antigravity's Swarm + // toggle) still carries the context and instructions that message would. + const isNativeSlashCommand = ( + flavor.rewriteKeepsUserMessage === true ? turnInput.message.text : userText + ) + .trimStart() + .startsWith("/"); const attachmentBlocks = yield* promptAttachmentBlocks( messageText, turnInput.message.attachments, @@ -9668,13 +9708,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( deliveredContext, isNativeSlashCommand, ); - const text = t3AcpPromptWithInstructions({ - prompt: messageText, + // A command a rewrite made keeps its first block; its instructions follow in another. + const commandFromRewrite = !isNativeSlashCommand && userText.trimStart().startsWith("/"); + const wrapped = t3AcpPromptWithInstructions({ + prompt: commandFromRewrite ? "" : messageText, state: instructionState, ...(previousInstructionState === undefined || compactionMarker !== undefined ? {} : { previousState: previousInstructionState }), }); + const instructionsBlock = commandFromRewrite && wrapped !== "" ? wrapped : undefined; + const text = commandFromRewrite ? messageText : wrapped; const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", @@ -9701,19 +9745,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (appContextEntries.length > 0) { - prompt.unshift( - ...appContextEntries.map((entry) => ({ - type: "text" as const, - text: formatAcpAppContextEntry(entry), - })), - ); + const contextBlocks = appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })); + if (commandFromRewrite) prompt.push(...contextBlocks); + else prompt.unshift(...contextBlocks); + } + if (instructionsBlock !== undefined) { + prompt.push({ type: "text", text: instructionsBlock }); } if (sendRuntimeInstructions) { prompt.push({ type: "text", text: runtimeInstructions }); } return { prompt, - instructionState: text === messageText ? undefined : instructionState, + instructionState: + text === messageText && instructionsBlock === undefined + ? undefined + : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, appContextEntries, compactionMarker, @@ -10262,6 +10312,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeWorkflowCalls: 0, nativeWorkflowMembers: new Set(), nativeWorkflowUnreadableSince: undefined, + nativeWorkflowChangedAt: undefined, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; From 73fbbad007f8398710b54a9fdfe5fd54f42f7967 Mon Sep 17 00:00:00 2001 From: Bil0000 <62337003+Bil0000@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:02:19 +0100 Subject: [PATCH 6/6] fix(antigravity): a swarm whose workers keep stepping is not stalled The stall release compared only what the workflow shows, so a worker adding transcript steps without changing that view could be released after 15 minutes while still at work. The reader now reports each worker's newest step, including workers past the 64 shown, and any new step resets the stall clock. A read that fails after a stall released the hold is recorded too, so the next readable read starts the stall clock fresh. The stall clock is wall-clock on purpose; after a host sleep the next turn picks a swarm still at work back up. --- .../Adapters/AntigravityAdapterV2.test.ts | 23 +++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 1 + .../src/provider/acp/AntigravitySwarm.ts | 13 ++++++++++- packages/provider-acp/src/server/adapter.ts | 17 ++++++++++++-- 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5c6bd24a1bca9..e39620f2184af 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2704,6 +2704,29 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.effect("a worker still adding steps keeps holding the turn past the stall limit", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + // Each step leaves the shown workflow unchanged, but proves the worker is at work. + for (const step of [2, 3]) { + yield* swarm.writeLines(swarm.transcript, [ + ...swarm.parked.slice(0, 1), + { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, + { step_index: step, type: "GENERIC", status: "DONE" }, + ]); + yield* TestClock.adjust("8 minutes"); + yield* swarm.readAfterPoll; + } + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* swarm.readAfterPoll; + const done = yield* until((event) => workflows([event]).length > 0); + assert.equal(workflows(done).at(-1)?.status, "completed", "the swarm finished, not stalled"); + }).pipe(Effect.provide(layerSession)), + ); + it.effect("a swarm whose records stop changing stops holding the turn", () => Effect.gen(function* () { const swarm = yield* openSwarmSession(); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c169f3e213522..68e22aa3da9f4 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -351,6 +351,7 @@ export function makeAntigravityAcpAdapterFlavor( prompt: swarm.prompt, workflow: swarm.workflow, active: swarm.active, + progress: swarm.progress, }, ), ), diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index 93bef04b4f26a..3706e2779d5db 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -74,6 +74,7 @@ const Post = Schema.Struct({ type Post = typeof Post.Type; const decodePost = Schema.decodeUnknownOption(Schema.fromJsonString(Post)); const Step = Schema.Struct({ + step_index: Schema.optional(Schema.Number), type: Schema.String, status: Schema.optional(Schema.String), error: Schema.optional(Schema.String), @@ -164,6 +165,8 @@ interface MemberActivity { readonly failed: string | undefined; readonly startedAt: number | undefined; readonly lastAt: number | undefined; + /** The newest step's index: it moves whenever the worker does anything. */ + readonly lastStep: number | undefined; /** Only when the whole transcript was read; a tail would undercount. */ readonly usage: { readonly totalTokens: number; readonly toolCalls: number } | undefined; } @@ -209,6 +212,7 @@ async function readActivity( : undefined, startedAt: epochMillis(steps[0]?.created_at), lastAt: epochMillis(last?.created_at), + lastStep: last?.step_index, usage: tail.whole && tokens !== undefined ? { totalTokens: tokens, toolCalls } : undefined, }; } @@ -236,6 +240,8 @@ export interface AntigravitySwarmSnapshot { readonly prompt: string; /** True while any worker still works; parked and killed workers do not count. */ readonly active: boolean; + /** Changes whenever any worker records a step, shown or not: proof the swarm progresses. */ + readonly progress: string; } /** @@ -302,6 +308,8 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* (briefs.get(right)?.seq ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right), ); let active = false; + // Every worker's newest step, so steps that change nothing shown still count as progress. + const progress: Array = []; let totalTokens: number | undefined = 0; let toolCalls = 0; const agents: Array = []; @@ -311,6 +319,7 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* conversationId !== undefined && NATIVE_ID.test(conversationId) ? await readActivity(profileRoot, conversationId).catch(() => undefined) : undefined; + progress.push(`${name}:${activity?.lastStep ?? ""}`); const brief = briefs.get(name); const result = results.get(name); const isKilled = killed(member); @@ -357,12 +366,13 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* } // Workers past the cap are not shown, but one queued or at work keeps the swarm active. for (const [, member] of workers.slice(MAX_MEMBERS)) { - if (active || killed(member)) continue; + if (killed(member)) continue; const conversationId = member.conversation_id; const activity = conversationId !== undefined && NATIVE_ID.test(conversationId) ? await readActivity(profileRoot, conversationId).catch(() => undefined) : undefined; + progress.push(`${activity?.lastStep ?? ""}`); if (activity === undefined || (!activity.ended && activity.failed === undefined)) { active = true; } @@ -379,6 +389,7 @@ export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* .flatMap((agent) => (agent.prompt === undefined ? [] : [`@${agent.label} ${agent.prompt}`])) .join("\n\n"), active, + progress: progress.join(","), }; }; // An unreadable board means no swarm view this poll; the next poll reads again. diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 37933486c95a1..2a17b0d39153a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -159,6 +159,8 @@ const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); const ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS = 60_000; // As long as an open prompt may go silent: a workflow whose records stop changing stops holding. +// Wall-clock on purpose: after a host sleep this can settle the turn early, and the next turn +// picks a swarm still at work back up from its records. const ACP_NATIVE_WORKFLOW_STALL_MILLIS = 15 * 60_000; const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; @@ -837,6 +839,8 @@ export interface AcpNativeWorkflowSnapshot { readonly workflow: OrchestrationV2SubagentWorkflow; /** Any member still works; holds the turn open like a running subagent. */ readonly active: boolean; + /** Changes whenever the team makes progress, shown or not; a stall clock reads it. */ + readonly progress?: string; } export interface AcpAdapterV2Options { @@ -1828,6 +1832,7 @@ interface ActiveAcpTurn { nativeWorkflowUnreadableSince: number | undefined; /** Clock millis when the workflow's records last changed during this turn. */ nativeWorkflowChangedAt: number | undefined; + nativeWorkflowProgress: string | undefined; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -4227,9 +4232,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const releaseUnreadableNativeWorkflow = Effect.fnUntraced(function* ( context: ActiveAcpTurn, ) { - if (heldNativeWorkflow(context) === undefined) return; + const owns = [...context.subagents.values()].some( + (subagent) => subagent.task.workflow !== undefined, + ); + if (!owns) return; const now = yield* Clock.currentTimeMillis; + // Recorded even after a stall released the hold, so the next readable read starts fresh. context.nativeWorkflowUnreadableSince ??= now; + if (heldNativeWorkflow(context) === undefined) return; if (now - context.nativeWorkflowUnreadableSince < ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS) { return; } @@ -4311,8 +4321,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; const previous = nativeWorkflowProjected.get(nativeTaskId); const changed = previous === undefined || !Equal.equals(previous, key); + const progressed = read.progress !== context.nativeWorkflowProgress; + context.nativeWorkflowProgress = read.progress; const now = yield* Clock.currentTimeMillis; - if (changed || context.nativeWorkflowChangedAt === undefined) { + if (changed || progressed || context.nativeWorkflowChangedAt === undefined) { context.nativeWorkflowChangedAt = now; } else if (now - context.nativeWorkflowChangedAt >= ACP_NATIVE_WORKFLOW_STALL_MILLIS) { // Records that read fine but stop changing (a worker whose transcript cannot be @@ -10313,6 +10325,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeWorkflowMembers: new Set(), nativeWorkflowUnreadableSince: undefined, nativeWorkflowChangedAt: undefined, + nativeWorkflowProgress: undefined, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = [];