fix(antigravity): wait for backgrounded foreground commands to settle #38834
ClosedMchicao(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/38834/headopened View on GitHubMchicao(GitHub profile, opens in a new tab) linked this to fix #36105
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -1276,0 +1527,21 @@1527+ sessionId,1528+ onPrompt: ({ promptIndex, emit }) =>1529+ Effect.gen(function* () {1530+ if (promptIndex === 1) {1531+ yield* emit({1532+ sessionUpdate: "tool_call",1533+ toolCallId: "call_dev",1534+ title: "Dev server",1535+ kind: "execute",1536+ status: "in_progress",1537+ rawInput: { CommandLine: "npm run dev", IsDaemon: true },1538+ });1539+ yield* emit({1540+ sessionUpdate: "tool_call",1541+ toolCallId: "call_build",1542+ title: "Build",1543+ kind: "execute",1544+ status: "in_progress",1545+ rawInput: { CommandLine: "npm run build", IsDaemon: false },1546+ });1547+ yield* Deferred.succeed(firstPromptReturned, undefined);@@ -1276,0 +1700,21 @@1700+ sessionUpdate: "tool_call",1701+ toolCallId: "call_late_acp",1702+ title: "Late ACP command",1703+ kind: "execute",1704+ status: "in_progress",1705+ rawInput: { CommandLine: "npm run test", IsDaemon: false },1706+ });1707+ firstPromptDone = true;1708+ return { stopReason: "end_turn" as const };1709+ }1710+ yield* emit({1711+ sessionUpdate: "agent_message_chunk",1712+ content: { type: "text", text: "Late ACP result delivered." },1713+ });1714+ return { stopReason: "end_turn" as const };1715+ }),1716+ });1717+1718+ yield* fixture.startTurn();1719+ yield* Deferred.await(enteredWait);1720+ yield* Effect.sleep("50 millis");@@ -1276,0 +1738,21 @@1738+ assert.include(assistantText, "Late ACP result delivered.");1739+ }).pipe(Effect.provide(layerSession), Effect.scoped),1740+ );1741+1742+ it.live(1743+ "keeps waiting when native status reader throws or returns empty, never mislabels interrupted, and sends still_running continuation on maxWait",1744+ () =>1745+ Effect.gen(function* () {1746+ const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa5";1747+ const fileSystem = yield* FileSystem.FileSystem;1748+ const emptyProfile = yield* fileSystem.makeTempDirectoryScoped({1749+ prefix: "t3-ag-empty-profile-",1750+ });1751+ let readerCalls = 0;1752+ const fixture = yield* makeForegroundFixture({1753+ name: "fg-reader-errors",1754+ profileDirectory: emptyProfile,1755+ sessionId,1756+ foregroundCommandSettlement: {1757+ maxWait: "120 millis",1758+ pollInterval: "25 millis",@@ -220,0 +240,21 @@240+ }),241+ ...options.foregroundCommandSettlement,242+ buildContinuationPrompt: ({ settled, stillRunning }) => {243+ const formatSummary = (244+ tools: ReadonlyArray<{ readonly command?: string; readonly title?: string }>,245+ ) => {246+ const commands = tools247+ .map((tool) => tool.command ?? tool.title)248+ .filter((value): value is string => Boolean(value?.trim()))249+ .slice(0, 3);250+ return commands.length > 0 ? ` (${commands.join("; ")})` : "";251+ };252+ const lines: Array<string> = [];253+ if (settled.length > 0) {254+ lines.push(255+ `The background command${formatSummary(settled)} finished without delivering a final wakeup reply over ACP. Report its verified result without re-running completed commands.`,256+ );257+ }258+ if (stillRunning.length > 0) {259+ lines.push(260+ `The background command${formatSummary(stillRunning)} was still running when your turn ended. Check its status in this turn and report its result once complete.`,@@ -478,0 +612,21 @@612+ unresolved.set(lookupCallId, toolCallId);613+ }614+615+ if (unresolved.size > 0) {616+ let scannedBytes = 0;617+ let scannedRows = 0;618+ let scannedMaxIdx = lastScannedMaxIdx;619+ let hitScanCap = false;620+ let sawUnmappedRow = false;621+ const query = hasMetadata622+ ? database.prepare(623+ "SELECT idx, status, CASE WHEN length(metadata) <= ? THEN metadata END AS metadata FROM steps WHERE step_type IN (21, 132) AND step_format = 0 AND idx > ? ORDER BY idx DESC LIMIT ?",624+ )625+ : database.prepare(626+ "SELECT idx, status, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type IN (21, 132) AND step_format = 0 AND idx > ? ORDER BY idx DESC LIMIT ?",627+ );628+ for (const row of query.iterate(629+ MAX_STEP_BYTES,630+ lastScannedMaxIdx,631+ MAX_COMMAND_SCAN_ROWS,632+ )) {@@ -8905,0 +8967,21 @@8967+ let currentPrompt: ReadonlyArray<EffectAcpSchema.ContentBlock> = promptParts!.prompt;8968+ let isInitialPrompt = true;8969+ let continuations = 0;8970+8971+ while (true) {8972+ const checkPromptOutcome =8973+ flavor.watchPromptOutcome === undefined8974+ ? undefined8975+ : yield* flavor.watchPromptOutcome(requestedSessionId);8976+ if (context.interrupted || context.finalized) {8977+ return {8978+ result: { stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse,8979+ hiddenFailure: undefined,8980+ };8981+ }8982+ if (!isInitialPrompt) {8983+ context.outgoingPrompt = currentPrompt;8984+ context.consumedPromptMessageId = undefined;8985+ }8986+ context.promptSentAt = yield* Clock.currentTimeMillis;8987+ const result = yield* sendPromptWhenIdle(context, () =>@@ -8907,0 +9008,21 @@9008+ ? undefined9009+ : yield* checkPromptOutcome(result);9010+9011+ if (9012+ settlement === undefined ||9013+ context.interrupted ||9014+ context.finalized ||9015+ hiddenFailure !== undefined ||9016+ result.stopReason !== "end_turn"9017+ ) {9018+ return { result, hiddenFailure };9019+ }9020+9021+ yield* runtime.drainEvents;9022+ if (context.interrupted || context.finalized) return { result, hiddenFailure };9023+9024+ const openTools = () =>9025+ [...context.tools.values()].filter(settlement.isOpenForegroundCommand);9026+ const initialOpen = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools));9027+ if (initialOpen.length === 0) {9028+ return { result, hiddenFailure };@@ -8907,0 +9016,21 @@9016+ result.stopReason !== "end_turn"9017+ ) {9018+ return { result, hiddenFailure };9019+ }9020+9021+ yield* runtime.drainEvents;9022+ if (context.interrupted || context.finalized) return { result, hiddenFailure };9023+9024+ const openTools = () =>9025+ [...context.tools.values()].filter(settlement.isOpenForegroundCommand);9026+ const initialOpen = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools));9027+ if (initialOpen.length === 0) {9028+ return { result, hiddenFailure };9029+ }9030+9031+ const lastKnownNativeStates = new Map<9032+ string,9033+ "running" | "completed" | "failed" | "cancelled"9034+ >();9035+ const waitLoop = Effect.gen(function* () {9036+ while (!context.interrupted && !context.finalized) {@@ -8907,0 +9032,21 @@9032+ string,9033+ "running" | "completed" | "failed" | "cancelled"9034+ >();9035+ const waitLoop = Effect.gen(function* () {9036+ while (!context.interrupted && !context.finalized) {9037+ const pending = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools));9038+ if (pending.length === 0) return;9039+ if (readNativeStatuses !== undefined) {9040+ const polled = yield* readNativeStatuses(pending).pipe(9041+ Effect.orElseSucceed(() => undefined),9042+ );9043+ if (polled !== undefined) {9044+ for (const [toolCallId, state] of polled) {9045+ lastKnownNativeStates.set(toolCallId, state);9046+ }9047+ }9048+ const allSettledNatively = pending.every((tool) => {9049+ const state = lastKnownNativeStates.get(tool.toolCallId);9050+ return state !== undefined && state !== "running";9051+ });9052+ if (allSettledNatively) return;@@ -8907,0 +9105,21 @@9105+ const acpSettled = initialOpen.filter((tool) => {9106+ if (detachedSettledIds.has(tool.toolCallId)) return false;9107+ const latest = context.tools.get(tool.toolCallId);9108+ return latest !== undefined && !settlement.isOpenForegroundCommand(latest);9109+ });9110+ const settled = [...detachedSettled, ...acpSettled];9111+9112+ if (continuations >= maxContinuations) {9113+ if (stillRunning.length > 0) {9114+ yield* runtimeCallbackPermit.withPermit(9115+ Effect.forEach(9116+ stillRunning,9117+ (tool) => {9118+ const notice =9119+ lastKnownNativeStates.get(tool.toolCallId) === "running"9120+ ? "\n[T3 stopped waiting after continuation limit; command may still be running natively]"9121+ : "\n[T3 stopped waiting after continuation limit; final command status was not delivered over ACP]";9122+ return emitTool(9123+ context,9124+ appendToolOutputText({ ...tool, status: "failed" }, notice),9125+ "interrupted",
juliusmarminge added labelstakeover:in-progress
Pushedb327ac4
Pushed42166d6
Pushed6aa7278
- @@ -8942,0 +9161,21 @@9161+ return latest !== undefined && !settlement.isOpenForegroundCommand(latest);9162+ });9163+ const settled = [...detachedSettled, ...acpSettled];9164+9165+ if (continuations >= maxContinuations) {9166+ if (stillRunning.length > 0) {9167+ yield* runtimeCallbackPermit.withPermit(9168+ Effect.forEach(9169+ stillRunning,9170+ (tool) => {9171+ const latest = context.tools.get(tool.toolCallId);9172+ if (latest === undefined || !settlement.isOpenForegroundCommand(latest)) {9173+ return Effect.void;9174+ }9175+ const notice =9176+ lastKnownNativeStates.get(tool.toolCallId) === "running"9177+ ? "\n[T3 stopped waiting after continuation limit; command may still be running natively]"9178+ : "\n[T3 stopped waiting after continuation limit; final command status was not delivered over ACP]";9179+ return emitTool(9180+ context,9181+ appendToolOutputText({ ...latest, status: "failed" }, notice),
juliusmarminge added labelstakeover:needs-julius
juliusmarminge removed labelstakeover:in-progress
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough
The shared ACP adapter now waits for open foreground commands after
end_turnand can send bounded continuation prompts. Antigravity tool-call handling identifies foreground commands and reads native command statuses from SQLite. Prompt usage accumulates across continuation prompts.Changes: Foreground command settlement
packages/provider-acp/src/server/adapter.tsapps/server/src/provider/acp/AntigravityProtocol.ts,apps/server/src/provider/acp/AntigravityChildWork.ts,apps/server/src/provider/acp/AntigravityProtocol.test.ts,apps/server/src/provider/acp/AntigravityChildWork.test.tsapps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts,apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.tsEstimated code review effort: 4 (Complex) | ~45 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)#
Possibly related issues
Possibly related PRs
session/promptreturnsend_turn.Suggested labels:
bugfixSuggested reviewers:
t3dotgg,macroscopeapp,juliusmarmingeMerge Risk:
Moderate · up to
6aa72The change keeps an Antigravity turn open until backgrounded foreground commands settle. Several edge cases remain: a command finishing right after the prompt returns, the continuation limit, and long-history sessions. In these cases a turn can end early, mislabel a command's state, or hide earlier command output. Resolve these edge cases and the timing-sensitive tests before merging.
Pre-merge checks:
4
#36105), and Verification (live end-to-end run plus named automated test results). It …#36105] requires that a finite background shell command on Antigravity 1.5.7 to 1.5.11 does not close the run early. The wakeup reply must also reach T3 in the same run. The current summary shows the…Full details: Title check
Explanation
The title "fix(antigravity): wait for backgrounded foreground commands to settle" names the main change. The changeset adds settlement waiting for open foreground commands in the Antigravity adapter and the shared ACP adapter loop, which matches the title. It follows the conventional commit format the template asks for.
Full details: Description check
Explanation
The description follows the template's main sections: Problem (Root cause), Change (Fix), Scope (references Fixes
#36105), and Verification (live end-to-end run plus named automated test results). It also names the model and harness that did the work. The Scope section does not explain why the fix is a bug fix rather than a feature, and it does not state that a maintainer requested the PR. The Problem section gives reproduction context but no explicit expected-behavior statement. These are minor gaps, so the description is mostly complete.Full details: Linked Issues check
Explanation
[
#36105] requires that a finite background shell command on Antigravity 1.5.7 to 1.5.11 does not close the run early. The wakeup reply must also reach T3 in the same run. The current summary shows these changes. (1) AntigravityProtocol.ts preserves IsDaemon, isDaemon, and is_daemon. It exports isAntigravityOpenForegroundCommand, which ignores daemon commands, so the#16442infinite-daemon case is excluded. (2) packages/provider-acp/src/server/adapter.ts adds the foregroundCommandSettlement hook and a bounded runPromptLoop. After end_turn with an open foreground command, the loop waits for ACP updates or a known native terminal status before finalizing. (3) AntigravityChildWork.ts makeAntigravityCommandStatusReader reads native steps.status from the session SQLite database. Settlement does not depend only on ACP updates. (4) When a command settles, the loop sends a continuation prompt (maxContinuations = 2). This keeps a session/prompt attached, which the issue states is needed for wakeup updates and tool confirmations. The PR reports a live agy 1.5.11 run where a 12 s command completed in one turn with one continuation. The PR also reports unit tests for detached completion, failure, Stop, late ACP updates, reader errors, mixed outcomes, and usage merging. I did not run these tests or the live run. The verdict relies on the summary and the reported results. The issue's default-mode confirmation problem is not addressed by a separate change. The PR's approach depends on keeping the prompt attached, which the issue identifies as the required condition.Full details: Out of Scope Changes check
Explanation
Antigravity-specific files cover command-input parsing (AntigravityProtocol.ts), the native status reader (AntigravityChildWork.ts), settlement wiring and continuation prompt text (AntigravityAdapterV2.ts), and tests. Shared changes in packages/provider-acp/src/server/adapter.ts support the settlement loop. These include waiter signalling, per-prompt outcome checks, and usage accumulation through mergeAcpPromptUsage, which continuation prompts need. The PR also changes non-Antigravity flavors. It adds a pre-send interrupted/finalized short-circuit and moves promptSentAt and watchPromptOutcome into the loop. The PR discloses these changes. The PR reports 138/138 AcpAdapterV2 tests passing, which gives some evidence that the shared behavior is preserved. I did not inspect the shared adapter diff directly, so the effect on other flavors rests on the summary and reported tests. No file in ignored_files was excluded. The PR does not change agentContextBudget.json or global ThreadManagementService timeouts.
Finishing Touches
Generate unit tests (beta)