From d784f1f7bdff085177f4470479b91cec5d43fa6e Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Mon, 9 Nov 2026 08:13:58 +0900 Subject: [PATCH] feat(agy): run Antigravity over agy acp with mid-turn Steer (#2319) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(agy): isolate the stream-json transport in its own module Move everything only the stream-json driver uses into cli/src/agy/legacyStreamJson/: the driver and stream process, the NDJSON parser, the conversation-DB model and title readers, the transcript entry types, and the agy transcript producer that lived on ApiSessionClient as sendAgySessionMessage. The driver now registers its own queued-message cancel handler for batches held in its retry backoff instead of reaching through AgySession. The loop runs the remote session through agyRemoteLauncher, the one place that picks a transport; it is the only importer of the new module. No behavior change. * feat(acp): report soft-steer usage and prompt timing to the caller Antigravity ends a steered session/prompt request early and reports each request's share of the turn in its own response. Let soft-steer callers receive that usage so they can total it for the turn. prompt() waits for earlier output before it sends and for late output after the answer. Callers can now learn when the request was sent and answered, and a soft steer exposes when it was answered, so they can time the agent itself and run their own timers on its answers. * fix(acp): keep the JSON-RPC error code on failed requests A rejected request lost the agent's error code, and the soft-steer failure log printed the Error as {}. The rejection now carries code and data, and the log keeps the message and code. * feat(agy): run Antigravity on agy acp when agy supports it agy 1.5.0 added an ACP server. When `agy --version` reports 1.5.0 or newer, agyRemoteLauncher runs the session on a new ACP launcher over the shared AcpSdkBackend; older agy, or a version that cannot be read (pre-release of 1.5.0, missing binary, no answer), keeps the stream-json driver and says why in the session. The check and the stream-json launcher live in legacyStreamJson/, behind one call. On ACP, one agy acp process serves the session. The agy conversation id is the ACP session id, so stored agySessionId values resume through session/resume without replay, whichever transport started them. The launcher marks the session with agyProtocol 'acp' in metadata; the stream-json launcher removes a stale marker. - Model and effort apply per turn through session/set_model with agy's - ids; clearing the model returns to agy's default. The mode is sent every turn, since agy can change it on its own. - A queued message counts as delivered once agy takes it (its echo, output, or answer), or when it goes back to the composer. - Permission modes map to ACP session modes. agy approval requests reach HAPI through the shared ACP permission handler. agy titles a run_command request with the command line, so the handler's name hints for HAPI's own MCP tools (change_title, think, ...) are turned off for agy; otherwise a command such as `grep think notes.md` would skip the approval prompt. Automatic approvals pick a one-time option, because the agy process outlives mode switches, and agy question requests always wait for the user. - Titles come from session_info_update, and each turn reports one usage total built from the prompt responses. - If the agy process dies, the next turn restarts it and resumes the conversation (the transport now reports whether its process is alive). A restart that fails part way leaves no half-started process in use; the next turn tries again. A prompt agy never started is restored to the composer. * feat(agy): add accept-edits and plan permission modes agy has default, accept-edits, and plan execution modes. Expose accept-edits and plan as acceptEdits and plan next to request-review (agy's default mode) and always-proceed. On agy acp they switch per turn through session/set_mode without restarting agy; the stream-json driver passes them as --mode, so a change restarts its process like other launch settings. The iOS and Android catalogs mirror the new list. * feat(agy): steer queued messages into the running turn agy acp folds a second session/prompt into the running turn. Register the SteerQueuedMessage handler in the agy ACP launcher and open the steering gate for agy sessions whose metadata says agyProtocol 'acp'; stream-json sessions stay queue-only. The launcher publishes the marker and registers the handler before it starts agy, so the hub knows the protocol before any turn can take a steer; until then the hub tells a steer on an agy session that Steer is not available yet, rather than listing other flavors. agy answers the request a steer interrupts at once (end_turn) while the turn continues under the steer, and it lets a running tool call finish. So the launcher keeps the turn, its steeringActive state, and thinking until every open prompt request settles, and totals usage across them; usage from a steer answered after its turn ended is not reported again. agy echoes a steer as a user_message_chunk when it folds it in. The ACP backend now reports those echoes after flushing the output before them, and the launcher commits the steer when the echo text that follows the prompt's own echo matches it (whitespace-insensitive; the longest steer text wins when one contains another), so the message lands in the transcript where it entered the turn rather than after the final answer. Each steer resolves once (echoed or answered, held, or put back). agy rejects a prompt while an approval is open, so a steer is refused then and the message stays queued. Stop applies to the whole turn lifetime. It withdraws Steer at once and refuses steers that arrive after it. The turn is registered before agy restarts or switches settings, so a Stop before the prompt is sent puts it back in the composer, and a prompt still waiting to send is cancelled as soon as it reaches agy. agy answers a cancelled prompt with a normal `cancelled` result; when it produced no output, the prompt also goes back to the composer. agy answers open requests with `cancelled` and ends open tool calls; the turn's handler stays active so those final tool updates still render. A steer cancelled before its echo is held for an explicit Retry or Cancel, as for Cursor. A steer agy never answers is dropped after a grace period: its row is held the same way and the agy process is stopped (late permission requests are cancelled, not approved), and the next turn restarts it. If agy ignores the cancel, its process is stopped after a timeout in the same way. * feat(agy): report and fall back when agy acp fails to start An agy older than 1.5.0 never reaches this path: the version check in the selection seam already runs it on stream-json. On 1.5.0 or newer, agy acp can still fail to start or to open the conversation, for example when agy is not signed in, the ACP install is broken, or the process exits during start-up. The session used to end as crashed, without the reason. The launcher now sends the reason to the chat, and the selection seam runs the session on the stream-json driver instead, saying in the session that Steer is not available. Only start failures fall back: errors after agy acp is up end the session as before, and a kill during start-up is neither reported as a failure nor falls back. The fallback stays in the selection seam and legacyStreamJson/. * feat(agy): show per-turn usage in the response footer On agy acp each turn ends with a round summary: input, output, thinking, cache-read and total tokens (summed across the requests of a steered turn), the model, and agy's own time from sending the prompt to its last answer (HAPI's waits before sending and for late output are left out), and tok/s. agy reports no per-step timing, so generation time is that round time minus the spans spent running tools or waiting for the user (overlaps counted once), and generated tokens are output plus thinking, as for OpenCode. The web footer renders it like the other round summaries. agy's usage adds up every model call of a request and agy sends no usage_update, so it is not a context size. The turn's usage therefore no longer goes out as a token_count for the context indicator, which stays empty as it is for agy on stream-json. * fix(agy): keep the session when Stop arrives while no turn is running Stop aborts the queue wait and replaces the abort controller. The main loop then checked the new controller's signal, found it not aborted, and left the loop, so a late or repeated Stop after a turn had ended closed the session and disconnected agy. The loop now checks the signal its wait used and keeps waiting for the next message. * fix(agy): confirm a steer only at its echo A later steer makes agy answer an earlier steer's request at once (end_turn) while the tool call and the turn go on, before agy has folded the earlier steer in. Taking that answer as delivery marked the message consumed, so a Stop before its echo left it without Retry or Cancel. A steer is now confirmed when agy echoes it. An answer without an echo counts only when the turn ends: confirmed if the turn ended without a Stop, held for Retry or Cancel after one. * fix(agy): hold unechoed steers when agy is lost mid-turn An early-answered steer was confirmed when its turn ended without a Stop. If agy exited before echoing it (for example when a later steer answered its request and then the process died), the turn still ended without a Stop, so the steer was marked consumed although agy may never have folded it in, and Retry or Cancel was gone. A steer request that fails with a lost transport now marks agy as lost for the turn, and an early-answered steer without an echo is confirmed only when the turn ends cleanly: no Stop and no lost agy process. Otherwise it is held for Retry or Cancel. * test(agy): pin how each steer outcome is decided Cover the steer paths that had no test: a control command or a message that left the queue is refused; a steer whose delivery state cannot be recorded, or whose request agy loses while starting or writing it, is held for Retry or Cancel; a steer sent while agy restarts stays queued and runs next; an early-answered steer echoed before a Stop stays confirmed; a steer agy rejects after a Stop goes back to the queue; the main prompt stays delivered when Stop leaves a steer agy may have taken; and an open steer is held when agy ignores the cancel or the session is killed. * fix(agy): confirm every steer that one echo chunk carries When agy echoed two pending steers in one user_message_chunk, the first match cleared every steer's echo text, so the other steer was not confirmed at its echo. It was confirmed only when the turn ended, and a Stop before then held it for Retry although agy had taken it. A match now uses up only its own text, and the remaining steers keep matching. * fix(agy): keep matching the prompt's echo after a stray echo An echo chunk that did not continue the prompt (for example a late echo from the previous turn) ended the wait for the prompt's own echo. The prompt's echo that followed was then matched against the steers, so a steer whose text the prompt contains could be confirmed before agy took it. Such a chunk is now checked against the steers only, and the prompt's echo is still recognized when it comes. * fix(agy): settle the running turn before a kill returns The runner ends the session and closes the client as soon as kill() returns. kill() only cancelled the turn and disconnected agy, so a prompt that was still waiting to send, or whose cancelled answer was still draining, put itself back in the composer (or was confirmed) only after that, and those events were lost; the session end could then record the prompt as delivered without restoring it. kill() now waits for the running turn to settle after disconnecting agy, bounded to a few seconds so an agy that never settles cannot hold the session end. Archive and runner stop both end the session through kill(); leaving remote mode does not apply to agy, and a normal exit waits for the turn in the main loop. * fix(web): choose the Antigravity permission mode when creating a session The create form still showed Antigravity's old YOLO toggle, so a new session could only start in request-review or always-proceed, although the session mode picker offers request-review, acceptEdits, plan and always-proceed. Antigravity now uses the same native permission select as the other agents, filled from the shared mode catalog, and the chosen mode is sent with the spawn. The default stays as before: a stored YOLO toggle carries over (on → always-proceed, off → request-review), otherwise the hub's default applies, mapped onto agy's modes. Fallbacks that used the literal 'default' mode, which agy does not have, now ask the shared catalog for the flavor's default instead. --- .../kotlin/app/hapi/protocol/catalog/Modes.kt | 5 +- .../app/hapi/protocol/catalog/CatalogTest.kt | 2 +- cli/README.md | 4 +- .../agent/backends/acp/AcpSdkBackend.test.ts | 169 ++ cli/src/agent/backends/acp/AcpSdkBackend.ts | 58 +- .../backends/acp/AcpStdioTransport.test.ts | 27 + .../agent/backends/acp/AcpStdioTransport.ts | 9 +- .../acp/__fixtures__/agy-steered-turn.json | 220 ++ .../agy/agyAcpRemoteLauncher.replay.test.ts | 206 ++ cli/src/agy/agyAcpRemoteLauncher.test.ts | 1903 +++++++++++++++++ cli/src/agy/agyAcpRemoteLauncher.ts | 949 ++++++++ cli/src/agy/agyRemoteLauncher.ts | 14 + .../agyConversationModel.test.ts | 0 .../agyConversationModel.ts | 0 .../agyHeadlessDriver.test.ts | 45 +- .../agyHeadlessDriver.ts | 20 +- .../agyMessageText.ts | 0 .../agyNdjsonParser.test.ts | 0 .../agyNdjsonParser.ts | 4 +- .../agyPersistentDriver.test.ts | 13 +- .../agySessionTitle.test.ts | 0 .../agySessionTitle.ts | 0 .../agyStreamProcess.ts | 0 .../legacyStreamJson/agyTranscript.test.ts | 63 + cli/src/agy/legacyStreamJson/agyTranscript.ts | 67 + .../agyTranscriptTypes.ts | 0 cli/src/agy/legacyStreamJson/agyVersion.ts | 90 + cli/src/agy/legacyStreamJson/index.ts | 44 + .../transportSelection.test.ts | 214 ++ cli/src/agy/loop.ts | 4 +- cli/src/agy/runAgy.test.ts | 12 + cli/src/agy/runAgy.ts | 8 +- cli/src/agy/session.ts | 8 +- cli/src/agy/utils/agyAcpBackend.ts | 28 + cli/src/api/apiSession.test.ts | 34 - cli/src/api/apiSession.ts | 73 - cli/src/commands/agy.test.ts | 4 + cli/src/commands/pingPeer.ts | 3 +- .../permission/AcpPermissionHandler.test.ts | 154 ++ .../common/permission/AcpPermissionHandler.ts | 49 +- cli/src/modules/pingPeer/pingPeer.ts | 2 +- cli/src/runner/buildCliArgs.test.ts | 10 + docs/guide/agents.md | 54 +- hub/src/sync/steerQueuedMessage.test.ts | 28 +- hub/src/sync/syncEngine.ts | 11 +- .../Catalog/PermissionModes.swift | 2 +- .../HapiProtocolTests/CatalogTests.swift | 2 +- shared/fixtures/catalogs/modes.json | 10 + shared/src/modes.test.ts | 34 +- shared/src/modes.ts | 12 +- shared/src/schemas.ts | 2 + shared/src/sessionCitation.ts | 2 +- web/scripts/fixtures/cases/agy.ts | 2 +- .../chat/normalizeAgent.roundSummary.test.ts | 49 + web/src/chat/normalizeAgent.ts | 28 +- web/src/chat/reconcile.roundSummary.test.ts | 23 + web/src/chat/reconcile.ts | 8 +- web/src/chat/types.ts | 7 +- .../messages/MessageMetadata.test.ts | 38 + .../messages/MessageMetadata.tsx | 45 +- .../NewSession/PermissionField.test.tsx | 21 +- web/src/components/NewSession/index.test.tsx | 40 +- web/src/components/NewSession/index.tsx | 6 +- .../NewSession/newSessionFormDraft.test.ts | 7 + .../NewSession/newSessionFormDraft.ts | 3 +- web/src/components/NewSession/preferences.ts | 6 +- web/src/lib/codexFamilyPermissionAgents.ts | 7 +- 67 files changed, 4738 insertions(+), 224 deletions(-) create mode 100644 cli/src/agent/backends/acp/__fixtures__/agy-steered-turn.json create mode 100644 cli/src/agy/agyAcpRemoteLauncher.replay.test.ts create mode 100644 cli/src/agy/agyAcpRemoteLauncher.test.ts create mode 100644 cli/src/agy/agyAcpRemoteLauncher.ts create mode 100644 cli/src/agy/agyRemoteLauncher.ts rename cli/src/agy/{utils => legacyStreamJson}/agyConversationModel.test.ts (100%) rename cli/src/agy/{utils => legacyStreamJson}/agyConversationModel.ts (100%) rename cli/src/agy/{headless => legacyStreamJson}/agyHeadlessDriver.test.ts (97%) rename cli/src/agy/{headless => legacyStreamJson}/agyHeadlessDriver.ts (97%) rename cli/src/agy/{utils => legacyStreamJson}/agyMessageText.ts (100%) rename cli/src/agy/{headless => legacyStreamJson}/agyNdjsonParser.test.ts (100%) rename cli/src/agy/{headless => legacyStreamJson}/agyNdjsonParser.ts (98%) rename cli/src/agy/{headless => legacyStreamJson}/agyPersistentDriver.test.ts (97%) rename cli/src/agy/{utils => legacyStreamJson}/agySessionTitle.test.ts (100%) rename cli/src/agy/{utils => legacyStreamJson}/agySessionTitle.ts (100%) rename cli/src/agy/{headless => legacyStreamJson}/agyStreamProcess.ts (100%) create mode 100644 cli/src/agy/legacyStreamJson/agyTranscript.test.ts create mode 100644 cli/src/agy/legacyStreamJson/agyTranscript.ts rename cli/src/agy/{utils => legacyStreamJson}/agyTranscriptTypes.ts (100%) create mode 100644 cli/src/agy/legacyStreamJson/agyVersion.ts create mode 100644 cli/src/agy/legacyStreamJson/index.ts create mode 100644 cli/src/agy/legacyStreamJson/transportSelection.test.ts create mode 100644 cli/src/agy/utils/agyAcpBackend.ts create mode 100644 cli/src/modules/common/permission/AcpPermissionHandler.test.ts diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt index 17b42592..784daada 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt @@ -46,7 +46,10 @@ enum class PermissionMode( object PermissionModes { /** `AGY_PERMISSION_MODES`. */ - val AGY = listOf(PermissionMode.RequestReview, PermissionMode.AlwaysProceed) + val AGY = listOf( + PermissionMode.RequestReview, PermissionMode.AcceptEdits, + PermissionMode.Plan, PermissionMode.AlwaysProceed, + ) /** `CLAUDE_PERMISSION_MODES`. */ val CLAUDE = listOf( diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt index 7f821435..b3ee60f8 100644 --- a/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt @@ -69,7 +69,7 @@ class CatalogTest { PermissionModes.forFlavor("opencode").map { it.wireId } ) assertEquals( - listOf("request-review", "always-proceed"), + listOf("request-review", "acceptEdits", "plan", "always-proceed"), PermissionModes.forFlavor("agy").map { it.wireId } ) assertEquals( diff --git a/cli/README.md b/cli/README.md index caf163e2..460288fb 100644 --- a/cli/README.md +++ b/cli/README.md @@ -50,8 +50,8 @@ Choose a supported coding agent from your terminal and control its sessions remo Peer messages default to `auto`: use the target's live capabilities and turn state to steer an active, eligible turn; otherwise queue. Inactive peers require explicit `wake: true`; awakened peers enter the ordinary queue. This applies to every steering-supported -flavor: remote Claude, Pi, Codex, OpenCode, and Cursor ACP. Unsupported agents and -legacy Cursor sessions queue instead. Prefer auto for routine collaboration +flavor: remote Claude, Pi, Codex, OpenCode, Antigravity on agy acp, and Cursor ACP. +Unsupported agents and legacy Cursor sessions queue instead. Prefer auto for routine collaboration when queueing is an acceptable fallback. Use explicit `queue` for non-urgent updates that can wait. Use `steer` for diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.test.ts b/cli/src/agent/backends/acp/AcpSdkBackend.test.ts index 500789ba..3a6f2211 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.test.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.test.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; +import agySteeredTurn from './__fixtures__/agy-steered-turn.json'; import type { AgentMessage } from '@/agent/types'; +import { logger } from '@/ui/logger'; import { AcpSdkBackend } from './AcpSdkBackend'; import { AcpMessageHandler } from './AcpMessageHandler'; import { buildAcpStdioSpawnOptions } from './AcpStdioTransport'; @@ -78,6 +80,40 @@ describe('AcpSdkBackend', () => { expect(updates).toEqual([{ sessionId: 'session-1', title: 'Native session title' }]); }); + it('reports echoed user prompts after flushing the output before them', async () => { + const backend = new AcpSdkBackend({ command: 'agy' }); + const events: string[] = []; + backend.setUserMessageChunkListener((text) => events.push(`echo:${text}`)); + const backendInternal = backend as unknown as { + handleSessionUpdate: (params: unknown) => void; + sessionUpdateQueue: Promise; + messageHandler: { handleUpdate: (update: unknown) => Promise; drainBuffers: () => void } | null; + }; + backendInternal.messageHandler = { + handleUpdate: async (update) => { + events.push(`update:${(update as { sessionUpdate: string }).sessionUpdate}`); + }, + drainBuffers: () => events.push('drain') + }; + + backendInternal.handleSessionUpdate({ + sessionId: 'session-1', + update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Working' } } + }); + backendInternal.handleSessionUpdate({ + sessionId: 'session-1', + update: { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'also lint' } } + }); + await backendInternal.sessionUpdateQueue; + + expect(events).toEqual([ + 'update:agent_message_chunk', + 'update:user_message_chunk', + 'drain', + 'echo:also lint' + ]); + }); + it('refreshes native titles through ACP session/list', async () => { const backend = new AcpSdkBackend({ command: 'opencode' }); const calls: Array<{ method: string; params: unknown; options: unknown }> = []; @@ -769,6 +805,31 @@ describe('AcpSdkBackend', () => { ]); }); + it('reports when the prompt is sent and answered, apart from its own waits', async () => { + const backend = new AcpSdkBackend({ command: 'agent' }); + const events: string[] = []; + const backendInternal = backend as unknown as { + transport: { sendRequest: () => Promise; close: () => Promise } | null; + waitForSessionUpdateQuiet: (quietMs: number, timeoutMs: number) => Promise; + }; + backendInternal.waitForSessionUpdateQuiet = async () => { events.push('wait'); }; + backendInternal.transport = { + sendRequest: async () => { + events.push('request'); + return { stopReason: 'end_turn' }; + }, + close: async () => {} + }; + + await backend.prompt('session-1', [{ type: 'text', text: 'hello' }], () => {}, { + onSent: () => events.push('sent'), + onAnswered: () => events.push('answered') + }); + events.push('resolved'); + + expect(events).toEqual(['wait', 'request', 'sent', 'answered', 'wait', 'resolved']); + }); + it('seals a Cursor done footer before quiet drain so harness text stays separate (#2268)', async () => { backendStatics.UPDATE_QUIET_PERIOD_MS = 40; backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200; @@ -1439,6 +1500,67 @@ describe('AcpSdkBackend', () => { }]); }); + it('logs why a soft-steer prompt failed', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}); + const backend = new AcpSdkBackend({ command: 'agent' }); + const backendInternal = backend as unknown as { + transport: { + sendRequestWithDispatch: () => { dispatched: Promise; completed: Promise }; + sendNotification: () => void; + close: () => Promise; + } | null; + isProcessingMessage: boolean; + }; + backendInternal.isProcessingMessage = true; + const failure = Object.assign(new Error('waiting for a permission answer'), { code: -32603 }); + backendInternal.transport = { + sendRequestWithDispatch: () => ({ dispatched: Promise.resolve(), completed: Promise.reject(failure) }), + sendNotification: () => {}, + close: async () => {} + }; + + await expect(backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]).completed) + .rejects.toBe(failure); + + expect(warn).toHaveBeenCalledWith('[ACP] soft-steer session/prompt failed', { + message: 'waiting for a permission answer', + code: -32603 + }); + warn.mockRestore(); + }); + + it('beginSoftSteerPrompt settles answered before it drains late output', async () => { + const backend = new AcpSdkBackend({ command: 'agent' }); + const events: string[] = []; + const backendInternal = backend as unknown as { + transport: { + sendRequestWithDispatch: () => { dispatched: Promise; completed: Promise }; + close: () => Promise; + } | null; + isProcessingMessage: boolean; + waitForSessionUpdateQuiet: (quietMs: number, timeoutMs: number) => Promise; + drainLateBuffers: () => Promise; + }; + backendInternal.isProcessingMessage = true; + let releaseDrain!: () => void; + backendInternal.waitForSessionUpdateQuiet = () => new Promise((resolve) => { releaseDrain = resolve; }); + backendInternal.drainLateBuffers = async () => {}; + backendInternal.transport = { + sendRequestWithDispatch: () => ({ dispatched: Promise.resolve(), completed: Promise.resolve({ stopReason: 'end_turn' }) }), + close: async () => {} + }; + + const steer = backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]); + void steer.completed.then(() => events.push('completed')); + await steer.answered; + events.push('answered'); + await vi.waitFor(() => expect(releaseDrain).toBeTypeOf('function')); + expect(events).toEqual(['answered']); + releaseDrain(); + await steer.completed; + expect(events).toEqual(['answered', 'completed']); + }); + it('beginSoftSteerPrompt drains buffered output after completion', async () => { const backend = new AcpSdkBackend({ command: 'agent' }); const backendInternal = backend as unknown as { @@ -1475,6 +1597,53 @@ describe('AcpSdkBackend', () => { expect(events).toEqual(['request', 'quiet', 'drain', 'late', 'drain']); }); + it('beginSoftSteerPrompt reports the steered prompt usage with the latest context size', async () => { + // agy 1.5.2 answers each request of a steered turn with only its own share. + const steerResponse = agySteeredTurn.frames + .filter((frame) => frame.direction === 'agy->client' && 'result' in frame.message) + .map((frame) => (frame.message as { result: unknown }).result) + .at(-1); + const backend = new AcpSdkBackend({ command: 'agent' }); + const backendInternal = backend as unknown as { + transport: { + sendRequestWithDispatch: (method: string, params: unknown, options?: { timeoutMs?: number }) => { dispatched: Promise; completed: Promise }; + close: () => Promise; + } | null; + isProcessingMessage: boolean; + latestUsageUpdate: { contextTokens: number | undefined; contextWindow: number | undefined } | null; + waitForSessionUpdateQuiet: (quietMs: number, timeoutMs: number) => Promise; + drainLateBuffers: () => Promise; + }; + backendInternal.isProcessingMessage = true; + backendInternal.latestUsageUpdate = { contextTokens: 15_300, contextWindow: 1_000_000 }; + backendInternal.transport = { + sendRequestWithDispatch: () => ({ dispatched: Promise.resolve(), completed: Promise.resolve(steerResponse) }), + close: async () => {} + }; + backendInternal.waitForSessionUpdateQuiet = async () => {}; + backendInternal.drainLateBuffers = async () => {}; + const usages: unknown[] = []; + + const stopReason = await backend.beginSoftSteerPrompt( + 'session-1', + [{ type: 'text', text: 'pivot now' }], + { onUsage: (usage) => usages.push(usage) } + ).completed; + + expect(stopReason).toBe('end_turn'); + expect(usages).toEqual([{ + type: 'usage', + inputTokens: 15286, + outputTokens: 14, + totalTokens: 15300, + thoughtTokens: 0, + cacheReadTokens: 0, + cacheCreationTokens: 0, + contextTokens: 15_300, + contextWindow: 1_000_000 + }]); + }); + it('beginSoftSteerPrompt returns a pending promise without blocking the caller', async () => { const backend = new AcpSdkBackend({ command: 'agent' }); let resolvePrompt: ((value: unknown) => void) | null = null; diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.ts b/cli/src/agent/backends/acp/AcpSdkBackend.ts index 3427d8c0..a0aa8534 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.ts @@ -88,6 +88,12 @@ type AcpInitializeResult = { }; }; +function userMessageChunkText(update: unknown): string | null { + if (!isObject(update) || update.sessionUpdate !== 'user_message_chunk') return null; + const content = update.content; + return isObject(content) && content.type === 'text' ? asString(content.text) : null; +} + export class AcpSdkBackend implements AgentBackend { private transport: AcpStdioTransport | null = null; private permissionHandler: ((request: PermissionRequest) => void) | null = null; @@ -120,6 +126,7 @@ export class AcpSdkBackend implements AgentBackend { private promptUsageCallback: ((msg: AgentMessage) => void) | null = null; private usageUpdateListener: ((msg: AgentMessage) => void) | null = null; private sessionInfoUpdateListener: ((update: AcpSessionInfoUpdate) => void) | null = null; + private userMessageChunkListener: ((text: string) => void) | null = null; /** Fired on foreground ACP state / permission so launchers can bump hub thinking (#1470). */ private agentActivityListener: ((thinking: boolean) => void) | null = null; /** Debounce timer for state_update running → thinking (#1502 chatter). */ @@ -618,6 +625,11 @@ export class AcpSdkBackend implements AgentBackend { this.sessionInfoUpdateListener = listener; } + /** Called in order with agent output: text buffered before an echo is flushed first. */ + setUserMessageChunkListener(listener: ((text: string) => void) | null): void { + this.userMessageChunkListener = listener; + } + /** * Called when ACP reports foreground state / permission for harness wake (#1470 / #1502). * `true` = sustained `running` (debounced), `requires_action`, or permission. @@ -682,7 +694,10 @@ export class AcpSdkBackend implements AgentBackend { async prompt( sessionId: string, content: PromptContent[], - onUpdate: (msg: AgentMessage) => void + onUpdate: (msg: AgentMessage) => void, + // prompt() waits for earlier output before it sends and for late output + // after the answer; callers timing the agent itself need both moments. + timing?: { onSent?: () => void; onAnswered?: () => void } ): Promise { if (!this.transport) { throw new Error('ACP transport not initialized'); @@ -722,12 +737,15 @@ export class AcpSdkBackend implements AgentBackend { this.promptRequestInFlight = true; let response: unknown; try { - response = await this.transport.sendRequest('session/prompt', { + const request = this.transport.sendRequest('session/prompt', { sessionId, prompt: content }, { timeoutMs: Infinity }); + timing?.onSent?.(); + response = await request; } finally { this.promptRequestInFlight = false; + timing?.onAnswered?.(); } stopReason = isObject(response) ? asString(response.stopReason) : null; @@ -848,8 +866,14 @@ export class AcpSdkBackend implements AgentBackend { * Separates transport dispatch from prompt completion so callers can commit * queue state only after stdin accepted the request without waiting for the turn. */ - beginSoftSteerPrompt(sessionId: string, content: PromptContent[]): { + beginSoftSteerPrompt(sessionId: string, content: PromptContent[], options?: { + // Agents that answer each request with its own share (Antigravity) + // need every response's usage to total the turn. + onUsage?: (usage: Extract) => void; + }): { dispatched: Promise; + /** Settles when the agent answers, before late output is drained. */ + answered: Promise; /** Resolves with the ACP stopReason (`cancelled` after session/cancel). */ completed: Promise; } { @@ -869,6 +893,16 @@ export class AcpSdkBackend implements AgentBackend { const completed = (async () => { try { const response = await request.completed; + const usage = options?.onUsage ? this.extractPromptUsage(response) : null; + if (usage) { + const context = this.readLatestUsageUpdate(); + options?.onUsage?.({ + type: 'usage', + ...usage, + contextTokens: context?.contextTokens, + contextWindow: context?.contextWindow + }); + } return isObject(response) ? asString(response.stopReason) : null; } finally { try { @@ -886,10 +920,15 @@ export class AcpSdkBackend implements AgentBackend { })(); void completed.catch((error) => { - logger.warn('[ACP] soft-steer session/prompt failed', error); + // An Error logs as `{}`. + logger.warn('[ACP] soft-steer session/prompt failed', { + message: error instanceof Error ? error.message : String(error), + code: (error as { code?: unknown } | null)?.code + }); }); - return { dispatched: request.dispatched, completed }; + const answered = request.completed.then(() => {}, () => {}); + return { dispatched: request.dispatched, answered, completed }; } async respondToPermission( @@ -1004,6 +1043,10 @@ export class AcpSdkBackend implements AgentBackend { return this.promptGeneration; } + isTransportAlive(): boolean { + return this.transport?.isAlive() ?? false; + } + /** PID of the spawned ACP agent process, when known (used by the opencode v2 REST discovery). */ getProcessPid(): number | null { return this.transport ? this.transport.getProcessPid() : null; @@ -1207,9 +1250,14 @@ export class AcpSdkBackend implements AgentBackend { // update into the restored handler if earlier async image work kept // the queue busy past restore. const handler = this.messageHandler; + const echoedText = this.userMessageChunkListener ? userMessageChunkText(update) : null; this.sessionUpdateQueue = this.sessionUpdateQueue .then(async () => { await handler?.handleUpdate(update); + if (echoedText !== null) { + handler?.drainBuffers(); + this.userMessageChunkListener?.(echoedText); + } }) .catch((error) => { logger.debug( diff --git a/cli/src/agent/backends/acp/AcpStdioTransport.test.ts b/cli/src/agent/backends/acp/AcpStdioTransport.test.ts index 5013618a..86e3c2f3 100644 --- a/cli/src/agent/backends/acp/AcpStdioTransport.test.ts +++ b/cli/src/agent/backends/acp/AcpStdioTransport.test.ts @@ -187,6 +187,16 @@ describe('AcpStdioTransport plain-text stdout', () => { spawnState.stdoutDataHandlers = []; }); + test('reports itself dead once the agent process exits', async () => { + const transport = await AcpStdioTransport.create({ command: 'agy', args: ['acp'] }); + expect(transport.isAlive()).toBe(true); + + for (const handler of spawnState.exitHandlers) handler(null, 'SIGKILL'); + + expect(transport.isAlive()).toBe(false); + await transport.close(); + }); + test('ignores Cursor worktree banner and keeps JSON-RPC session alive', async () => { const transport = await AcpStdioTransport.create({ command: 'agent', args: ['acp'] }); const notifications: Array<{ method: string; params: unknown }> = []; @@ -220,6 +230,23 @@ describe('AcpStdioTransport plain-text stdout', () => { await transport.close(); }); + test('keeps the JSON-RPC error code on a rejected request', async () => { + const transport = await AcpStdioTransport.create({ command: 'agy', args: ['acp'] }); + const pending = transport.sendRequest('session/prompt'); + + emitStdout(`${JSON.stringify({ + jsonrpc: '2.0', + id: 1, + error: { code: -32603, message: 'the running prompt is waiting for a permission or question answer' } + })}\n`); + + await expect(pending).rejects.toMatchObject({ + message: 'the running prompt is waiting for a permission or question answer', + code: -32603 + }); + await transport.close(); + }); + test('ignores non-object JSON lines without killing the session', async () => { const transport = await AcpStdioTransport.create({ command: 'gemini' }); const pending = transport.sendRequest('initialize'); diff --git a/cli/src/agent/backends/acp/AcpStdioTransport.ts b/cli/src/agent/backends/acp/AcpStdioTransport.ts index 925496ff..5e728692 100644 --- a/cli/src/agent/backends/acp/AcpStdioTransport.ts +++ b/cli/src/agent/backends/acp/AcpStdioTransport.ts @@ -249,6 +249,10 @@ export class AcpStdioTransport { this.notificationHandler = handler; } + isAlive(): boolean { + return !this.closed && !this.exited; + } + /** PID of the spawned ACP agent process, when known. */ getProcessPid(): number | null { return typeof this.process.pid === 'number' ? this.process.pid : this.childPid; @@ -549,7 +553,10 @@ export class AcpStdioTransport { this.pending.delete(response.id); if (response.error) { - pending.reject(new Error(response.error.message)); + pending.reject(Object.assign(new Error(response.error.message), { + code: response.error.code, + ...(response.error.data !== undefined ? { data: response.error.data } : {}) + })); return; } diff --git a/cli/src/agent/backends/acp/__fixtures__/agy-steered-turn.json b/cli/src/agent/backends/acp/__fixtures__/agy-steered-turn.json new file mode 100644 index 00000000..39402e4b --- /dev/null +++ b/cli/src/agent/backends/acp/__fixtures__/agy-steered-turn.json @@ -0,0 +1,220 @@ +{ + "source": "agy 1.5.2 `agy acp`, Gemini 3.8 Flash (Low), recorded 2026-11-07: a steer sent while run_command runs", + "frames": [ + { + "t": 10.8, + "direction": "client->agy", + "message": { + "id": 104, + "method": "session/prompt", + "params": { + "sessionId": "agy-conv-1", + "prompt": [ + { + "type": "text", + "text": "Respond in English only. Use your terminal tool to run exactly: sleep 6 && echo first-done . Then report its output in one short sentence." + } + ] + } + } + }, + { + "t": 10.9, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "user_message_chunk", + "content": { + "type": "text", + "text": "Respond in English only. Use your terminal tool to run exactly: sleep 6 && echo first-done . Then report its output in one short sentence." + } + } + } + } + }, + { + "t": 14.22, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call", + "toolCallId": "call_1", + "name": "run_command", + "args": { + "CommandLine": "sleep 6 && echo first-done", + "WaitMsBeforeAsync": 8000, + "toolSummary": "Run sleep and echo command" + }, + "status": "in_progress", + "kind": "execute", + "title": "sleep 6 && echo first-done", + "rawInput": { + "CommandLine": "sleep 6 && echo first-done", + "WaitMsBeforeAsync": 8000, + "toolSummary": "Run sleep and echo command" + } + } + } + } + }, + { + "t": 15.72, + "direction": "client->agy", + "message": { + "id": 105, + "method": "session/prompt", + "params": { + "sessionId": "agy-conv-1", + "prompt": [ + { + "type": "text", + "text": "Additional instructions:\n- End your final sentence with the word BANANA.\n- Keep it short. " + } + ] + } + } + }, + { + "t": 15.72, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "result": { + "stopReason": "end_turn", + "usage": { + "inputTokens": 15172, + "outputTokens": 44, + "cachedReadTokens": 0, + "cachedWriteTokens": 0, + "thoughtTokens": 0, + "totalTokens": 15216 + } + }, + "id": 104 + } + }, + { + "t": 20.47, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "call_1", + "name": "run_command", + "args": { + "CommandLine": "sleep 6 && echo first-done", + "WaitMsBeforeAsync": 8000, + "toolSummary": "Run sleep and echo command" + }, + "status": "completed", + "kind": "execute", + "title": "sleep 6 && echo first-done", + "rawInput": { + "CommandLine": "sleep 6 && echo first-done", + "WaitMsBeforeAsync": 8000, + "toolSummary": "Run sleep and echo command" + }, + "rawOutput": { + "output": "Command exited with code 0.\n\nCommand output:\nfirst-done\r\n", + "exit_code": 0 + }, + "content": [ + { + "type": "content", + "content": { + "type": "text", + "text": "Command exited with code 0.\n\nCommand output:\nfirst-done\r\n" + } + } + ] + } + } + } + }, + { + "t": 20.6, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "user_message_chunk", + "content": { + "type": "text", + "text": "Additional instructions:\n- End your final sentence with the word BANANA.\n- Keep it short. " + } + } + } + } + }, + { + "t": 23.22, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { + "type": "text", + "text": "The command" + } + } + } + } + }, + { + "t": 23.27, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { + "type": "text", + "text": " executed successfully and printed `first-done` BANANA." + } + } + } + } + }, + { + "t": 23.43, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "result": { + "stopReason": "end_turn", + "usage": { + "inputTokens": 15286, + "outputTokens": 14, + "cachedReadTokens": 0, + "cachedWriteTokens": 0, + "thoughtTokens": 0, + "totalTokens": 15300 + } + }, + "id": 105 + } + } + ] +} \ No newline at end of file diff --git a/cli/src/agy/agyAcpRemoteLauncher.replay.test.ts b/cli/src/agy/agyAcpRemoteLauncher.replay.test.ts new file mode 100644 index 00000000..329ef912 --- /dev/null +++ b/cli/src/agy/agyAcpRemoteLauncher.replay.test.ts @@ -0,0 +1,206 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { MessageQueue2 } from '@/utils/MessageQueue2'; +import { hashObject } from '@/utils/deterministicJson'; +import type { ApiSessionClient } from '@/api/apiSession'; +import { AcpSdkBackend } from '@/agent/backends/acp'; +import { AcpStdioTransport } from '@/agent/backends/acp/AcpStdioTransport'; +import agySteeredTurn from '@/agent/backends/acp/__fixtures__/agy-steered-turn.json'; +import { AgySession } from './session'; +import type { AgyMode } from './types'; +import { AgyAcpRemoteLauncher } from './agyAcpRemoteLauncher'; + +vi.mock('@/ui/ink/RemoteModeDisplay', () => ({ RemoteModeDisplay: () => null })); +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } })); + +type Frame = { t: number; direction: string; message: Record }; +const frames = agySteeredTurn.frames as Frame[]; +const promptText = (frame: Frame) => + ((frame.message.params as { prompt: Array<{ text: string }> }).prompt)[0]!.text; +const requests = frames.filter((frame) => frame.direction === 'client->agy'); +const mainPrompt = promptText(requests[0]!); +const steerText = promptText(requests[1]!); +const resultOf = (id: number) => (frames.find((frame) => frame.message.id === id && 'result' in frame.message)! + .message as { result: unknown }).result; +const updatesBetween = (from: number, to: number) => frames + .filter((frame) => frame.direction === 'agy->client' && frame.message.method === 'session/update' + && frame.t > from && frame.t < to); +const resultTime = (id: number) => frames.find((frame) => frame.message.id === id && 'result' in frame.message)!.t; +// Recorded seconds play back as 50 ms each. +const MS_PER_SECOND = 50; +const sleep = (seconds: number) => new Promise((resolve) => setTimeout(resolve, Math.max(0, seconds) * MS_PER_SECOND)); + +/** + * Plays agy's side of the recorded steered turn: the frames before the steer, + * the early answer to the interrupted request once the steer arrives, then + * the rest of the turn and the steer's answer. + */ +class ReplayTransport { + private notify: (method: string, params: unknown) => void = () => {}; + private steerArrived!: () => void; + private readonly steerReceived = new Promise((resolve) => { this.steerArrived = resolve; }); + readonly methods: string[] = []; + + onNotification(handler: (method: string, params: unknown) => void): void { + this.notify = handler; + } + onStderrError(): void {} + registerRequestHandler(): void {} + isAlive(): boolean { + return true; + } + sendNotification(method: string): void { + this.methods.push(method); + } + async close(): Promise {} + + /** Plays the frames with their recorded spacing, starting from `from`. */ + private async play(updates: Frame[], from: number): Promise { + let at = from; + for (const frame of updates) { + await sleep(frame.t - at); + at = frame.t; + this.notify('session/update', frame.message.params); + } + return at; + } + + async sendRequest(method: string): Promise { + this.methods.push(method); + switch (method) { + case 'initialize': + return { protocolVersion: 1, agentCapabilities: { loadSession: true } }; + case 'session/new': + return { + sessionId: 'agy-conv-1', + models: { availableModels: [{ modelId: 'gemini-3.8-flash-low', name: 'Gemini 3.8 Flash (Low)' }], currentModelId: 'gemini-3.8-flash-low' } + }; + case 'session/prompt': + await this.play(updatesBetween(requests[0]!.t, requests[1]!.t), requests[0]!.t); + await this.steerReceived; + return resultOf(104); + default: + return {}; + } + } + + sendRequestWithDispatch(method: string): { dispatched: Promise; completed: Promise } { + this.methods.push(method); + this.steerArrived(); + const completed = (async () => { + const last = await this.play(updatesBetween(requests[1]!.t, resultTime(105)), requests[1]!.t); + await sleep(resultTime(105) - last); + return resultOf(105); + })(); + return { dispatched: Promise.resolve(), completed }; + } +} + +function makeClient() { + const handlers = new Map Promise>(); + return { + sessionId: 'hapi-session', + rpcHandlerManager: { + handlers, + registerHandler: vi.fn((method: string, handler: (payload?: unknown) => Promise) => { + handlers.set(method, handler); + }), + unregisterHandler: vi.fn() + }, + updateMetadata: vi.fn(), + updateAgentState: vi.fn(), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage: vi.fn(), + emitMessagesConsumed: vi.fn(), + emitSteerIndeterminate: vi.fn(), + setSteerDeliveryState: vi.fn(async () => true), + getMetadata: vi.fn(() => null), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + }; +} + +describe('AgyAcpRemoteLauncher replaying a recorded agy 1.5.2 steered turn', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('places the steer, the answer and the usage as agy reported them', async () => { + const transport = new ReplayTransport(); + vi.spyOn(AcpStdioTransport, 'create').mockResolvedValue(transport as unknown as AcpStdioTransport); + const queue = new MessageQueue2((mode) => hashObject(mode)); + const client = makeClient(); + const session = new AgySession({ + api: {} as never, + client: client as unknown as ApiSessionClient, + path: '/tmp/agy-project', + logPath: '/tmp/agy.log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + permissionMode: 'always-proceed' + }); + const mode: AgyMode = { permissionMode: 'always-proceed' }; + queue.push(mainPrompt, mode, 'first'); + const launcher = new AgyAcpRemoteLauncher(session, { + createBackend: () => new AcpSdkBackend({ command: 'agy', args: ['acp'], flavor: 'agy' }) + }); + const run = launcher.launch(); + + // Steer once agy reports the running tool call. + await vi.waitFor(() => expect(client.sendAgentMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'tool-call', callId: 'call_1' }) + ), { timeout: 5000 }); + queue.push(steerText, mode, 'steer-1'); + const steer = client.rpcHandlerManager.handlers.get(RPC_METHODS.SteerQueuedMessage)!; + expect(await steer({ localId: 'steer-1' })).toEqual({ steered: true }); + + await vi.waitFor(() => expect(client.sendSessionEvent).toHaveBeenCalledWith({ type: 'ready' }), { timeout: 10_000 }); + queue.close(); + await run; + + const order = (fn: { mock: { invocationCallOrder: number[] } }, index: number) => fn.mock.invocationCallOrder[index]!; + const sent = client.sendAgentMessage.mock.calls.map(([message]) => message as { type: string; message?: string }); + const answerIndex = sent.findIndex((message) => message.type === 'message' && message.message?.includes('BANANA')); + const steerConsumed = client.emitMessagesConsumed.mock.calls.findIndex(([ids, opts]) => + (ids as string[])[0] === 'steer-1' && (opts as { steered?: boolean } | undefined)?.steered === true); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['first']); + expect(steerConsumed).toBeGreaterThanOrEqual(0); + expect(answerIndex).toBeGreaterThanOrEqual(0); + // The steer enters the transcript at agy's echo, before the answer to it. + expect(order(client.emitMessagesConsumed, steerConsumed)).toBeLessThan(order(client.sendAgentMessage, answerIndex)); + const summaries = sent.filter((message) => message.type === 'round-summary'); + expect(summaries).toMatchObject([{ + type: 'round-summary', + summary: { + provider: 'agy', + model: 'gemini-3.8-flash-low', + agy_usage: { + input_tokens: 15172 + 15286, + output_tokens: 44 + 14, + thinking_tokens: 0, + cache_read_tokens: 0, + total_tokens: 15216 + 15300 + }, + duration_ms: expect.any(Number) + } + }]); + // Generation time is the round minus the run_command window: in the + // recording 12.63 s - 6.25 s = 6.38 s. When the test sends the steer + // does not matter, since it moves the round's end and the tool's end + // alike. + const toolCall = frames.find((frame) => (frame.message.params as { update?: { sessionUpdate?: string } } | undefined) + ?.update?.sessionUpdate === 'tool_call')!.t; + const toolDone = frames.find((frame) => (frame.message.params as { update?: { sessionUpdate?: string } } | undefined) + ?.update?.sessionUpdate === 'tool_call_update')!.t; + const expected = ((resultTime(105) - requests[0]!.t) - (toolDone - toolCall)) * MS_PER_SECOND; + const summary = (summaries[0] as unknown as { summary: { generation_ms: number; generation_output_tokens: number } }).summary; + expect(Math.abs(summary.generation_ms - expected)).toBeLessThan(60); + expect(summary.generation_output_tokens).toBe(44 + 14); + expect(transport.methods.filter((method) => method === 'session/prompt')).toHaveLength(2); + expect(transport.methods).not.toContain('session/cancel'); + }, 20_000); +}); diff --git a/cli/src/agy/agyAcpRemoteLauncher.test.ts b/cli/src/agy/agyAcpRemoteLauncher.test.ts new file mode 100644 index 00000000..640bb6aa --- /dev/null +++ b/cli/src/agy/agyAcpRemoteLauncher.test.ts @@ -0,0 +1,1903 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { MessageQueue2 } from '@/utils/MessageQueue2'; +import { hashObject } from '@/utils/deterministicJson'; +import type { ApiSessionClient } from '@/api/apiSession'; +import type { AgentMessage, PermissionRequest, PromptContent } from '@/agent/types'; +import type { AcpSdkBackend } from '@/agent/backends/acp'; +import { ACP_INDETERMINATE_SYMBOL } from '@/agent/backends/acp/AcpStdioTransport'; +import agySteeredTurn from '@/agent/backends/acp/__fixtures__/agy-steered-turn.json'; +import { AgySession } from './session'; +import type { AgyMode } from './types'; +import { + AgyAcpRemoteLauncher, + addAgyUsage, + agyAcpModeForPermission, + agyGenerationMs, + agyRoundSummary, + resolveAgyAcpModelId +} from './agyAcpRemoteLauncher'; + +vi.mock('@/ui/ink/RemoteModeDisplay', () => ({ RemoteModeDisplay: () => null })); +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } })); + +type PromptScript = (onUpdate: (message: AgentMessage) => void) => Promise; + +class FakeAgyBackend { + readonly calls: string[] = []; + readonly prompts: PromptContent[][] = []; + readonly setModeCalls: string[] = []; + readonly setModelCalls: string[] = []; + readonly resumeCalls: string[] = []; + readonly cancelCalls: string[] = []; + currentModelId = 'gemini-4-argon-medium'; + resumeError: Error | null = null; + setModelError: Error | null = null; + promptScripts: PromptScript[] = []; + disconnected = false; + + initializeGate: Promise | null = null; + async initialize(): Promise { + this.calls.push('initialize'); + if (this.initializeGate) await this.initializeGate; + } + alive = true; + isTransportAlive(): boolean { + return this.alive; + } + supportsSessionResume(): boolean { + return true; + } + newSessionError: Error | null = null; + async newSession(): Promise { + this.calls.push('newSession'); + if (this.newSessionError) throw this.newSessionError; + return 'agy-conv-new'; + } + async resumeSession(config: { sessionId: string }): Promise { + this.resumeCalls.push(config.sessionId); + if (this.resumeError) throw this.resumeError; + return config.sessionId; + } + getSessionModelsMetadata() { + return { availableModels: [], currentModelId: this.currentModelId }; + } + async setMode(_sessionId: string, modeId: string): Promise { + this.setModeCalls.push(modeId); + } + setModelGate: Promise | null = null; + async setModel(_sessionId: string, modelId: string): Promise { + if (this.setModelGate) await this.setModelGate; + if (this.setModelError) throw this.setModelError; + this.setModelCalls.push(modelId); + } + promptInFlight = false; + // Like AcpSdkBackend: prompt() waits for the previous turn's output before + // it sends, and drains late output after the answer while still counting + // as an open request (a steer is accepted then). + preSendDelayMs = 0; + postResponseDrainMs = 0; + private draining = false; + private openSteers = 0; + isPromptRequestInFlight(): boolean { + return this.promptInFlight; + } + get processingMessage(): boolean { + return this.promptInFlight || this.draining || this.openSteers > 0; + } + async prompt( + _sessionId: string, + content: PromptContent[], + onUpdate: (message: AgentMessage) => void, + timing?: { onSent?: () => void; onAnswered?: () => void } + ): Promise { + if (this.preSendDelayMs) await new Promise((resolve) => setTimeout(resolve, this.preSendDelayMs)); + if (this.disconnected) { + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + throw error; + } + this.prompts.push(content); + this.promptInFlight = true; + timing?.onSent?.(); + try { + const script = this.promptScripts.shift(); + if (script) { + await script(onUpdate); + } else { + onUpdate({ type: 'text', text: 'answer' }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + } + } finally { + this.promptInFlight = false; + timing?.onAnswered?.(); + } + if (this.postResponseDrainMs) { + this.draining = true; + await new Promise((resolve) => setTimeout(resolve, this.postResponseDrainMs)); + this.draining = false; + } + } + async cancelPrompt(sessionId: string): Promise { + this.cancelCalls.push(sessionId); + this.onCancel?.(); + } + onCancel: (() => void) | null = null; + readonly steerPrompts: PromptContent[][] = []; + steerDispatchError: Error | null = null; + steerStartError: Error | null = null; + steerCompletions: Array<{ + resolve: (stopReason: string | null) => void; + reject: (error: unknown) => void; + // agy answered, but HAPI is still draining late output. + answer: () => void; + onUsage?: (usage: Extract) => void; + }> = []; + abortSoftSteersCalls = 0; + beginSoftSteerPrompt( + _sessionId: string, + content: PromptContent[], + options?: { onUsage?: (usage: Extract) => void } + ) { + if (this.steerStartError) throw this.steerStartError; + if (!this.processingMessage) throw new Error('No active ACP prompt to soft-steer into'); + this.steerPrompts.push(content); + this.openSteers += 1; + let resolve!: (stopReason: string | null) => void; + let reject!: (error: unknown) => void; + const completed = new Promise((res, rej) => { resolve = res; reject = rej; }); + void completed.then(() => { this.openSteers -= 1; }, () => { this.openSteers -= 1; }); + let answer!: () => void; + const answered = new Promise((res) => { answer = res; }); + void completed.then(answer, answer); + this.steerCompletions.push({ resolve, reject, answer, onUsage: options?.onUsage }); + const dispatched = this.steerDispatchError ? Promise.reject(this.steerDispatchError) : Promise.resolve(); + void dispatched.catch(() => {}); + return { dispatched, answered, completed }; + } + abortSoftSteers(): void { + this.abortSoftSteersCalls += 1; + } + async refreshSessionInfo(): Promise {} + setSessionInfoUpdateListener(): void {} + echo: ((text: string) => void) | null = null; + setUserMessageChunkListener(listener: ((text: string) => void) | null): void { + this.echo = listener; + } + onStderrError(): void {} + permissionHandler: ((request: PermissionRequest) => void) | null = null; + readonly permissionResponses: unknown[] = []; + onPermissionRequest(handler: (request: PermissionRequest) => void): void { + this.permissionHandler = handler; + } + async respondToPermission(_sessionId: string, _request: PermissionRequest, response: unknown): Promise { + this.permissionResponses.push(response); + } + onDisconnect: (() => void) | null = null; + async disconnect(): Promise { + this.disconnected = true; + this.onDisconnect?.(); + } +} + +const REVIEW: AgyMode = { permissionMode: 'request-review' }; + +function makeClient() { + const handlers = new Map Promise>(); + return { + sessionId: 'hapi-session', + rpcHandlerManager: { + handlers, + registerHandler: vi.fn((method: string, handler: (payload?: unknown) => Promise) => { + handlers.set(method, handler); + }), + unregisterHandler: vi.fn() + }, + updateMetadata: vi.fn(), + updateAgentState: vi.fn(), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage: vi.fn(), + emitMessagesConsumed: vi.fn(), + emitSteerIndeterminate: vi.fn(), + setSteerDeliveryState: vi.fn(async () => true), + getMetadata: vi.fn(() => null), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + }; +} + +function makeSession(sessionId: string | null = null) { + const queue = new MessageQueue2((mode) => hashObject(mode)); + const client = makeClient(); + const session = new AgySession({ + api: {} as never, + client: client as unknown as ApiSessionClient, + path: '/tmp/agy-project', + logPath: '/tmp/agy.log', + sessionId, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + permissionMode: 'request-review' + }); + return { session, queue, client }; +} + +function launch(session: AgySession, backends: FakeAgyBackend[], opts: { cancelHardStopMs?: number; killSettleMs?: number } = {}) { + const created: FakeAgyBackend[] = []; + const launcher = new AgyAcpRemoteLauncher(session, { + steerCancelGraceMs: 50, + cancelHardStopMs: opts.cancelHardStopMs ?? 2_000, + killSettleMs: opts.killSettleMs, + createBackend: () => { + const backend = backends.shift() ?? new FakeAgyBackend(); + created.push(backend); + return backend as unknown as AcpSdkBackend; + } + }); + return { run: launcher.launch(), created }; +} + +function steeringStates(client: ReturnType): boolean[] { + return client.updateAgentState.mock.calls + .map(([update]) => (update as (state: object) => { steeringActive?: boolean })({})) + .filter((state) => 'steeringActive' in state) + .map((state) => state.steeringActive === true); +} + +function agentState(client: ReturnType): { requests?: Record } { + return client.updateAgentState.mock.calls + .reduce((state, [update]) => (update as (s: object) => object)(state), {} as object); +} + +function sessionEvents(client: ReturnType): unknown[] { + return client.sendSessionEvent.mock.calls.map(([event]) => event); +} + +function roundSummaries(client: ReturnType): Array & { agy_usage: Record }> { + return client.sendAgentMessage.mock.calls + .map(([message]) => message as { type: string; summary: Record & { agy_usage: Record } }) + .filter((message) => message.type === 'round-summary') + .map((message) => message.summary); +} + +describe('AgyAcpRemoteLauncher', () => { + beforeEach(() => { + process.stdin.isTTY = false; + process.stdout.isTTY = false; + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('opens a new conversation, sends text prompts, and reports ready', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + queue.push('hello', REVIEW, 'local-1'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.calls).toEqual(['initialize', 'newSession']); + expect(session.sessionId).toBe('agy-conv-new'); + const metadata = client.updateMetadata.mock.calls + .reduce((current, [update]) => (update as (m: object) => object)(current), {}); + expect(metadata).toMatchObject({ agySessionId: 'agy-conv-new', agyProtocol: 'acp' }); + expect(backend.prompts).toEqual([[{ type: 'text', text: 'hello' }]]); + expect(client.sendAgentMessage).toHaveBeenCalledWith({ type: 'message', message: 'answer' }); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['local-1']); + expect(sessionEvents(client)).toContainEqual({ type: 'ready' }); + expect(backend.disconnected).toBe(true); + }); + + it('tells the user why agy could not start', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.initialize = async () => { throw new Error('unknown command "acp"'); }; + queue.push('hello', REVIEW, 'a'); + + await expect(launch(session, [backend]).run).rejects.toThrow('requires Antigravity CLI 1.5.0 or newer'); + + expect(sessionEvents(client)).toContainEqual({ + type: 'error', + message: 'Failed to start agy acp (requires Antigravity CLI 1.5.0 or newer): unknown command "acp"' + }); + expect(client.emitMessagesConsumed).not.toHaveBeenCalled(); + queue.close(); + }); + + it('resumes the stored conversation without replay', async () => { + const { session, queue } = makeSession('agy-conv-old'); + const backend = new FakeAgyBackend(); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.resumeCalls).toEqual(['agy-conv-old']); + expect(backend.calls).toEqual(['initialize']); + expect(session.sessionId).toBe('agy-conv-old'); + }); + + it('starts a new conversation when resume fails and says so', async () => { + const { session, queue, client } = makeSession('agy-conv-gone'); + const backend = new FakeAgyBackend(); + backend.resumeError = new Error('conversation not found'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.calls).toEqual(['initialize', 'newSession']); + expect(session.sessionId).toBe('agy-conv-new'); + expect(sessionEvents(client)).toContainEqual({ + type: 'message', + message: 'Antigravity could not resume the conversation; starting a new one.' + }); + }); + + it('applies the ACP mode every turn and the model only when it changes', async () => { + const { session, queue } = makeSession(); + const backend = new FakeAgyBackend(); + const flashLow: AgyMode = { permissionMode: 'request-review', model: 'gemini-3.8-flash', effort: 'low' }; + queue.push('one', flashLow, 'a'); + queue.push('two', { ...flashLow, permissionMode: 'always-proceed' }, 'b'); + queue.push('three', { ...flashLow, effort: 'high' }, 'c'); + queue.push('four', { ...flashLow, effort: 'high', permissionMode: 'plan' }, 'd'); + queue.push('five', { ...flashLow, effort: 'high', permissionMode: 'acceptEdits' }, 'e'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.prompts).toHaveLength(5); + expect(backend.setModeCalls).toEqual(['default', 'default', 'default', 'plan', 'accept-edits']); + expect(backend.setModelCalls).toEqual(['gemini-3.8-flash-low', 'gemini-3.8-flash-high']); + }); + + it('switches back to agy default model when the selection is cleared', async () => { + const { session, queue } = makeSession(); + const backend = new FakeAgyBackend(); + queue.push('one', { permissionMode: 'request-review', model: 'gemini-3.8-flash', effort: 'low' }, 'a'); + queue.push('two', { permissionMode: 'request-review', model: null, effort: null }, 'b'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.setModelCalls).toEqual(['gemini-3.8-flash-low', 'gemini-4-argon-medium']); + }); + + it('restores the prompt instead of running it on the wrong model', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.setModelError = new Error('unknown model'); + queue.push('hello', { permissionMode: 'request-review', model: 'gemini-9-ultra' }, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.prompts).toEqual([]); + expect(sessionEvents(client)).toContainEqual({ + type: 'error', + message: 'Failed to switch Antigravity model to gemini-9-ultra: unknown model' + }); + expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'hello' }); + }); + + it('reports one usage total per turn after the turn output', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'text', text: 'done' }); + onUpdate({ type: 'usage', inputTokens: 100, outputTokens: 5, totalTokens: 105, cacheReadTokens: 10 }); + onUpdate({ type: 'usage', inputTokens: 50, outputTokens: 2, totalTokens: 52 }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('hello', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + const sent = client.sendAgentMessage.mock.calls.map(([message]) => message as { type: string }); + // No token_count: agy's usage is not a context size. + expect(sent.map((message) => message.type)).toEqual(['message', 'round-summary']); + expect(sent[1]).toMatchObject({ + type: 'round-summary', + summary: { + provider: 'agy', + model: 'gemini-4-argon-medium', + agy_usage: { input_tokens: 150, output_tokens: 7, cache_read_tokens: 10, total_tokens: 157 }, + duration_ms: expect.any(Number) + } + }); + }); + + it('restores a prompt agy never started and relaunches after the process dies', async () => { + const { session, queue, client } = makeSession(); + const first = new FakeAgyBackend(); + first.promptScripts.push(async () => { + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + throw error; + }); + const second = new FakeAgyBackend(); + queue.push('first try', REVIEW, 'a'); + queue.push('second try', { permissionMode: 'always-proceed' }, 'b'); + queue.close(); + + const { run, created } = launch(session, [first, second]); + await run; + + expect(created).toHaveLength(2); + expect(first.disconnected).toBe(true); + expect(second.resumeCalls).toEqual(['agy-conv-new']); + expect(second.prompts).toEqual([[{ type: 'text', text: 'second try' }]]); + expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'first try' }); + }); + + it('restarts and resumes agy before a turn when the process died while idle', async () => { + const { session, queue, client } = makeSession(); + const first = new FakeAgyBackend(); + const second = new FakeAgyBackend(); + queue.push('first', REVIEW, 'a'); + const { run, created } = launch(session, [first, second]); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + + first.alive = false; + queue.push('after the crash', { permissionMode: 'always-proceed' }, 'b'); + await vi.waitFor(() => expect(second.prompts).toHaveLength(1)); + queue.close(); + await run; + + expect(created).toHaveLength(2); + expect(second.resumeCalls).toEqual(['agy-conv-new']); + expect(second.setModeCalls).toEqual(['default']); + expect(second.prompts).toEqual([[{ type: 'text', text: 'after the crash' }]]); + expect(sessionEvents(client)).not.toContainEqual({ type: 'abort-restore', text: 'after the crash' }); + }); + + it('does not restore a prompt that already produced output', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + throw new Error('quota exhausted'); + }); + queue.push('hello', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(sessionEvents(client)).toContainEqual({ + type: 'error', + message: 'Antigravity prompt failed: quota exhausted' + }); + expect(sessionEvents(client)).not.toContainEqual({ type: 'abort-restore', text: 'hello' }); + }); + + it('cancels the running turn on Stop and keeps serving the queue', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let release!: () => void; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'text', text: 'working' }); + await new Promise((resolve) => { release = resolve; }); + }); + queue.push('long task', REVIEW, 'a'); + + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + const abort = client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!; + const aborted = abort(); + await vi.waitFor(() => expect(backend.cancelCalls).toEqual(['agy-conv-new'])); + release(); + await aborted; + queue.push('next', REVIEW, 'b'); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + + expect(sessionEvents(client)).toContainEqual({ type: 'message', message: 'Turn aborted' }); + // Without steers, Stop leaves the handler running so agy's final + // updates for the cancelled tool calls still render. + expect(backend.abortSoftSteersCalls).toBe(0); + }); +}); + +describe('AgyAcpRemoteLauncher Stop', () => { + it('keeps the session when Stop arrives while no turn is running', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(client.rpcHandlerManager.handlers.has(RPC_METHODS.Abort)).toBe(true)); + + // A late or repeated Stop after the turn already ended. + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + queue.push('next', REVIEW, 'a'); + await vi.waitFor(() => expect(backend.prompts).toEqual([[{ type: 'text', text: 'next' }]])); + expect(backend.disconnected).toBe(false); + + queue.close(); + await run; + }); + + it('restores a prompt that Stop cancelled before agy answered anything', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let cancelled!: () => void; + backend.onCancel = () => cancelled?.(); + backend.promptScripts.push(async (onUpdate) => { + // agy 1.5.2 echoes the prompt, then answers a cancel with a normal + // `cancelled` result rather than an error. + backend.echo!('build it'); + await new Promise((resolve) => { cancelled = resolve; }); + onUpdate({ type: 'turn_complete', stopReason: 'cancelled' }); + }); + queue.push('build it', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'build it' }); + }); + + it('keeps a cancelled turn that already produced output', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let cancelled!: () => void; + backend.onCancel = () => cancelled?.(); + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'text', text: 'starting' }); + await new Promise((resolve) => { cancelled = resolve; }); + onUpdate({ type: 'turn_complete', stopReason: 'cancelled' }); + }); + queue.push('build it', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(sessionEvents(client)).not.toContainEqual({ type: 'abort-restore', text: 'build it' }); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['a']); + }); + + it('does not send a prompt when Stop arrives while agy switches the model', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let openGate!: () => void; + backend.setModelGate = new Promise((resolve) => { openGate = resolve; }); + queue.push('build it', { permissionMode: 'request-review', model: 'gemini-3.8-flash', effort: 'low' }, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(client.rpcHandlerManager.handlers.has(RPC_METHODS.Abort)).toBe(true)); + await vi.waitFor(() => expect(session.thinking).toBe(true)); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + openGate(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(backend.prompts).toEqual([]); + expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'build it' }); + expect(sessionEvents(client)).toContainEqual({ type: 'message', message: 'Turn aborted' }); + }); + + it('cancels again once a prompt that was still waiting to send reaches agy', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.preSendDelayMs = 150; + let release!: () => void; + backend.promptScripts.push(async () => { + await new Promise((resolve) => { release = resolve; }); + }); + backend.onCancel = () => { if (backend.promptInFlight) release(); }; + queue.push('long task', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.setModeCalls).toEqual(['default'])); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(backend.prompts).toHaveLength(1); + expect(backend.cancelCalls).toHaveLength(2); + }); + + it('restarts agy when it ignores the cancel', async () => { + const { session, queue, client } = makeSession(); + const first = new FakeAgyBackend(); + first.promptScripts.push(async () => { + await new Promise((_resolve, reject) => { + first.onDisconnect = () => { + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + reject(error); + }; + }); + }); + const second = new FakeAgyBackend(); + queue.push('stuck', REVIEW, 'a'); + const { run, created } = launch(session, [first, second], { cancelHardStopMs: 50 }); + await vi.waitFor(() => expect(first.prompts).toHaveLength(1)); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Abort)!(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(first.disconnected).toBe(true); + expect(sessionEvents(client)).toContainEqual({ type: 'message', message: 'Antigravity did not stop; restarting it.' }); + expect(sessionEvents(client).filter((event) => (event as { type: string }).type === 'error')).toEqual([]); + + queue.push('next', REVIEW, 'b'); + await vi.waitFor(() => expect(second.prompts).toHaveLength(1)); + queue.close(); + await run; + expect(created).toHaveLength(2); + expect(second.resumeCalls).toEqual(['agy-conv-new']); + }); +}); + +describe('AgyAcpRemoteLauncher steer', () => { + type Handlers = Map Promise>; + + async function startHeldTurn(backend: FakeAgyBackend, mode: AgyMode = REVIEW) { + const { session, queue, client } = makeSession(); + let releaseFirst!: () => void; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + await new Promise((resolve) => { releaseFirst = resolve; }); + onUpdate({ type: 'usage', inputTokens: 100, outputTokens: 4, totalTokens: 104 }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('run the tests', mode, 'first'); + const { run, created } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + const handlers = client.rpcHandlerManager.handlers as Handlers; + return { session, queue, client, run, created, handlers, releaseFirst: () => releaseFirst() }; + } + + it('injects a queued message into the running turn and ends the turn with the steer', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + + queue.push('also lint', REVIEW, 'steer-1'); + const result = await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + + expect(result).toEqual({ steered: true }); + expect(backend.steerPrompts).toEqual([[{ type: 'text', text: 'also lint' }]]); + expect(client.setSteerDeliveryState).toHaveBeenCalledWith(['steer-1'], 'dispatching'); + expect(queue.size()).toBe(0); + + // agy answers the interrupted request at once; the turn goes on. + releaseFirst(); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(sessionEvents(client)).not.toContainEqual({ type: 'ready' }); + expect(steeringStates(client).at(-1)).toBe(true); + + const steer = backend.steerCompletions[0]!; + steer.onUsage?.({ type: 'usage', inputTokens: 50, outputTokens: 6, totalTokens: 56 }); + steer.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + const summaries = roundSummaries(client); + expect(summaries).toHaveLength(1); + expect(summaries[0]!.agy_usage).toMatchObject({ input_tokens: 150, output_tokens: 10 }); + expect(steeringStates(client).at(-1)).toBe(false); + }); + + it('places the steer in the transcript when agy folds it in, not when the turn ends', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + + backend.echo!('run the tests'); + backend.echo!('also lint'); + + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + releaseFirst(); + backend.steerCompletions[0]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + expect(client.emitMessagesConsumed.mock.calls.filter(([ids]) => (ids as string[])[0] === 'steer-1')).toHaveLength(1); + }); + + it('keeps an echoed steer delivered when Stop cancels the turn afterwards', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + backend.echo!('also lint'); + backend.onCancel = () => { + releaseFirst(); + backend.steerCompletions[0]!.resolve('cancelled'); + }; + + await handlers.get(RPC_METHODS.Abort)!(); + + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalled(); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + queue.close(); + await run; + }); + + it('tells the hub the session runs on agy acp before agy has started', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let started!: () => void; + backend.initializeGate = new Promise((resolve) => { started = resolve; }); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.calls).toEqual(['initialize'])); + + const metadata = client.updateMetadata.mock.calls + .reduce((current, [update]) => (update as (m: object) => object)(current), {}); + expect(metadata).toMatchObject({ agyProtocol: 'acp' }); + queue.push('early', REVIEW, 'early-1'); + const steer = (client.rpcHandlerManager.handlers as Handlers).get(RPC_METHODS.SteerQueuedMessage); + expect(await steer?.({ localId: 'early-1' })).toEqual({ steered: false, error: 'No active steerable turn' }); + + started(); + await vi.waitFor(() => expect(backend.prompts).toEqual([[{ type: 'text', text: 'early' }]])); + queue.close(); + await run; + }); + + it('refuses to steer when no turn is running and keeps the message queued', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(client.rpcHandlerManager.handlers.has(RPC_METHODS.SteerQueuedMessage)).toBe(true)); + + queue.push('later', REVIEW, 'idle-1'); + const result = await (client.rpcHandlerManager.handlers as Handlers).get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'idle-1' }); + + expect(result).toEqual({ steered: false, error: 'No active steerable turn' }); + expect(backend.steerPrompts).toEqual([]); + await vi.waitFor(() => expect(backend.prompts).toEqual([[{ type: 'text', text: 'later' }]])); + queue.close(); + await run; + }); + + it('does not steer a message queued under a different mode', async () => { + const backend = new FakeAgyBackend(); + const { queue, run, handlers, releaseFirst } = await startHeldTurn(backend); + + queue.push('plan it instead', { permissionMode: 'plan' }, 'other-mode'); + const result = await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'other-mode' }); + + expect(result).toEqual({ steered: false, error: 'Queued message mode differs from the active turn' }); + expect(backend.steerPrompts).toEqual([]); + expect(queue.size()).toBe(1); + releaseFirst(); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + }); + + it('puts the message back when agy cannot take the steer', async () => { + const backend = new FakeAgyBackend(); + backend.steerDispatchError = new Error('stdin closed'); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + + queue.push('also lint', REVIEW, 'steer-1'); + const result = await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + + expect(result).toEqual({ steered: false, error: 'Failed to steer into the active turn' }); + expect(client.setSteerDeliveryState).toHaveBeenLastCalledWith(['steer-1'], 'queued'); + expect(queue.size()).toBe(1); + releaseFirst(); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + expect(backend.prompts[1]).toEqual([{ type: 'text', text: 'also lint' }]); + queue.close(); + await run; + }); + + it('Stop cancels the turn, releases an open steer, and holds it for Retry', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + backend.onCancel = () => { + releaseFirst(); + backend.steerCompletions[0]!.resolve('cancelled'); + }; + + await handlers.get(RPC_METHODS.Abort)!(); + + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(backend.cancelCalls).toEqual(['agy-conv-new']); + // agy answered the steer, so this turn's handler keeps running. + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(backend.abortSoftSteersCalls).toBe(0); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + queue.close(); + await run; + }); + + it('Stop drops a steer agy never answers and stops agy (no late approvals)', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client, run, created, handlers, releaseFirst } = await startHeldTurn(backend); + session.setPermissionMode('always-proceed'); + queue.push('also lint', REVIEW, 'steer-1'); + await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' }); + releaseFirst(); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(sessionEvents(client)).not.toContainEqual({ type: 'ready' }); + + await handlers.get(RPC_METHODS.Abort)!(); + + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + await vi.waitFor(() => expect(backend.disconnected).toBe(true)); + // A late request from the stopped process is cancelled, not auto-approved. + backend.permissionHandler!({ + id: 'late', sessionId: 'agy-conv-new', toolCallId: 'call_late', title: 'rm -rf build', kind: 'execute', + rawInput: { CommandLine: 'rm -rf build' }, + options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }] + }); + await vi.waitFor(() => expect(backend.permissionResponses.at(-1)).toEqual({ outcome: 'cancelled' })); + expect(backend.permissionResponses).not.toContainEqual({ outcome: 'selected', optionId: 'allow' }); + // Usage the dropped steer reports later is not a new turn. + const usageEvents = () => roundSummaries(client).length; + const before = usageEvents(); + backend.steerCompletions[0]!.onUsage?.({ type: 'usage', inputTokens: 9, outputTokens: 9 }); + expect(usageEvents()).toBe(before); + // The row is held for Retry/Cancel instead of staying "dispatching". + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + // agy restarts before the next turn so the abandoned request cannot leak into it. + queue.push('next', REVIEW, 'next'); + await vi.waitFor(() => expect(created).toHaveLength(2)); + queue.close(); + await run; + }); + + it('acknowledges a steer once when it is retried after a failed dispatch', async () => { + const backend = new FakeAgyBackend(); + backend.steerDispatchError = new Error('stdin closed'); + const { queue, client, run, handlers, releaseFirst } = await startHeldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' })) + .toEqual({ steered: false, error: 'Failed to steer into the active turn' }); + + backend.steerDispatchError = null; + expect(await handlers.get(RPC_METHODS.SteerQueuedMessage)!({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.echo!('also lint'); + // The failed first attempt must not swallow the retried steer's echo. + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + releaseFirst(); + backend.steerCompletions[1]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + expect(client.emitMessagesConsumed.mock.calls.filter(([ids]) => (ids as string[])[0] === 'steer-1')).toHaveLength(1); + }); +}); + +describe('AgyAcpRemoteLauncher delivery and recovery', () => { + type Handlers = Map Promise>; + const steerRpc = (client: ReturnType) => + (client.rpcHandlerManager.handlers as Handlers).get(RPC_METHODS.SteerQueuedMessage)!; + const abortRpc = (client: ReturnType) => + (client.rpcHandlerManager.handlers as Handlers).get(RPC_METHODS.Abort)!; + const indeterminate = () => { + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + return error; + }; + + async function heldTurn(backend: FakeAgyBackend, mode: AgyMode = REVIEW) { + const { session, queue, client } = makeSession(); + let release!: () => void; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + await new Promise((resolve) => { release = resolve; }); + }); + queue.push('run the tests', mode, 'first'); + const { run, created } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + return { session, queue, client, run, created, release: () => release() }; + } + + const rejected = () => Object.assign( + new Error("Can't add this prompt to session: the running prompt is waiting for a permission or question answer"), + { code: -32603 } + ); + + it('keeps a rejected steer queued and runs it next', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + + backend.steerCompletions[0]!.reject(rejected()); + await vi.waitFor(() => expect(queue.size()).toBe(1)); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + + release(); + await vi.waitFor(() => expect(backend.prompts).toEqual([ + [{ type: 'text', text: 'run the tests' }], + [{ type: 'text', text: 'also lint' }] + ])); + queue.close(); + await run; + }); + + it("does not take the prompt's own echo for a steer whose text it contains", async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let release!: () => void; + backend.promptScripts.push(async () => { + await new Promise((resolve) => { release = resolve; }); + }); + queue.push('run the tests and then lint', REVIEW, 'first'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + + // The steer is sent before agy echoes the prompt. + queue.push('lint', REVIEW, 'steer-1'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.echo!('run the tests and then lint'); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + + backend.steerCompletions[0]!.reject(rejected()); + await vi.waitFor(() => expect(queue.size()).toBe(1)); + release(); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + }); + + it('credits an echo to the steer it spells out when another steer is a substring of it', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('lint', REVIEW, 'short'); + queue.push('fix lint errors', REVIEW, 'long'); + expect(await steerRpc(client)({ localId: 'short' })).toEqual({ steered: true }); + expect(await steerRpc(client)({ localId: 'long' })).toEqual({ steered: true }); + + backend.echo!('fix lint errors'); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['long'], { steered: true }); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['short'], { steered: true }); + backend.echo!('lint'); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['short'], { steered: true }); + + release(); + for (const steer of backend.steerCompletions) steer.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + }); + + it('restores the prompt after Stop when the only steer was rejected', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client } = makeSession(); + let cancelled!: () => void; + backend.onCancel = () => cancelled?.(); + backend.promptScripts.push(async (onUpdate) => { + await new Promise((resolve) => { cancelled = resolve; }); + onUpdate({ type: 'turn_complete', stopReason: 'cancelled' }); + }); + queue.push('build it', REVIEW, 'first'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.steerCompletions[0]!.reject(rejected()); + await vi.waitFor(() => expect(queue.size()).toBe(1)); + + await abortRpc(client)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'build it' })); + queue.close(); + await run; + }); + + it('does not drop a steer agy answered while HAPI still drains its output', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release, created } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.onCancel = () => { + release(); + // agy answers the steer at once; its late output keeps HAPI busy + // past the steer grace period. + backend.steerCompletions[0]!.answer(); + }; + + await abortRpc(client)(); + await new Promise((resolve) => setTimeout(resolve, 120)); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalled(); + expect(backend.disconnected).toBe(false); + + backend.steerCompletions[0]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + expect(created).toHaveLength(1); + }); + + it('leaves the tool run and the wait for an approval out of tok/s', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let approvalAnswered!: () => void; + backend.promptScripts.push(async (onUpdate) => { + await new Promise((resolve) => setTimeout(resolve, 40)); + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + await new Promise((resolve) => setTimeout(resolve, 200)); + onUpdate({ type: 'tool_result', id: 't1', output: 'ok', status: 'completed' }); + backend.permissionHandler!({ + id: 'p1', sessionId: 'agy-conv-new', toolCallId: 'call_p1', title: 'rm -rf build', kind: 'execute', + rawInput: { CommandLine: 'rm -rf build' }, + options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }] + }); + await new Promise((resolve) => { approvalAnswered = resolve; }); + onUpdate({ type: 'text', text: 'done' }); + await new Promise((resolve) => setTimeout(resolve, 40)); + onUpdate({ type: 'usage', inputTokens: 10, outputTokens: 30, thoughtTokens: 10 }); + }); + queue.push('clean up', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(Object.keys(agentState(client).requests ?? {})).toEqual(['p1'])); + await new Promise((resolve) => setTimeout(resolve, 200)); + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Permission)!({ id: 'p1', approved: true }); + approvalAnswered(); + queue.close(); + await run; + + const summary = client.sendAgentMessage.mock.calls + .map(([message]) => message as { type: string; summary?: { duration_ms?: number; generation_ms?: number; generation_output_tokens?: number } }) + .find((message) => message.type === 'round-summary')!.summary!; + expect(summary.duration_ms).toBeGreaterThanOrEqual(480); + // About 80 ms of generation: the 200 ms tool run and the ~200 ms + // approval wait are left out. + expect(summary.generation_ms).toBeGreaterThanOrEqual(60); + expect(summary.generation_ms).toBeLessThan(200); + expect(summary.generation_output_tokens).toBe(40); + }); + + it('times the round from sending the prompt to agy answering', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.preSendDelayMs = 150; + backend.postResponseDrainMs = 150; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'text', text: 'done' }); + onUpdate({ type: 'usage', inputTokens: 10, outputTokens: 1 }); + }); + queue.push('hello', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + const summary = client.sendAgentMessage.mock.calls + .map(([message]) => message as { type: string; summary?: { duration_ms?: number } }) + .find((message) => message.type === 'round-summary')!.summary!; + expect(summary.duration_ms).toBeLessThan(100); + }); + + it('does not report a start failure or fall back when the session is killed while agy starts', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let failStart!: (error: Error) => void; + backend.initializeGate = new Promise((_resolve, reject) => { failStart = reject; }); + backend.onDisconnect = () => failStart(new Error('ACP transport closed')); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.calls).toEqual(['initialize'])); + + await session.kill(); + queue.close(); + + await expect(run).resolves.toBe('exit'); + expect(sessionEvents(client).filter((event) => (event as { type: string }).type === 'error')).toEqual([]); + }); + + it('holds steers that a later steer answered early when Stop comes before their echo', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + let cancelled = false; + backend.onCancel = () => { + if (cancelled) return; + cancelled = true; + release(); + for (const steer of backend.steerCompletions) steer.resolve('cancelled'); + }; + queue.push('also lint', REVIEW, 'steer-1'); + queue.push('and format', REVIEW, 'steer-2'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + expect(await steerRpc(client)({ localId: 'steer-2' })).toEqual({ steered: true }); + // The second steer interrupts the first one's request: agy answers it + // at once, while the tool call and the turn go on. + backend.steerCompletions[0]!.resolve('end_turn'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + + await abortRpc(client)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-2']); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + queue.close(); + await run; + }); + + it('holds an early-answered steer when agy dies before its echo', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + queue.push('and format', REVIEW, 'steer-2'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + expect(await steerRpc(client)({ localId: 'steer-2' })).toEqual({ steered: true }); + // The second steer answers the first one's request at once; then agy + // exits before echoing either. + release(); + backend.steerCompletions[0]!.resolve('end_turn'); + await new Promise((resolve) => setTimeout(resolve, 20)); + backend.alive = false; + backend.steerCompletions[1]!.reject(indeterminate()); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-2']); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + queue.close(); + await run; + }); + + it('confirms an early-answered steer at its echo, or when the turn ends without one', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + queue.push('and format', REVIEW, 'steer-2'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + expect(await steerRpc(client)({ localId: 'steer-2' })).toEqual({ steered: true }); + backend.steerCompletions[0]!.resolve('end_turn'); + + backend.echo!('run the tests'); + backend.echo!('also lint'); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-2'], { steered: true }); + + // agy never echoes the second steer; the turn still ends normally. + release(); + backend.steerCompletions[1]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-2'], { steered: true }); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalled(); + queue.close(); + await run; + }); + + it('refuses a steer that arrives after Stop and stops offering Steer at once', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + + await abortRpc(client)(); + // agy has not answered the cancel yet. + expect(steeringStates(client).at(-1)).toBe(false); + queue.push('also lint', REVIEW, 'late'); + const result = await steerRpc(client)({ localId: 'late' }); + + expect(result).toEqual({ steered: false, error: 'No active steerable turn' }); + expect(backend.steerPrompts).toEqual([]); + expect(queue.size()).toBe(1); + release(); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + }); + + it('restarts agy again after a relaunch that failed half-way', async () => { + const { session, queue, client } = makeSession(); + const first = new FakeAgyBackend(); + const broken = new FakeAgyBackend(); + broken.resumeError = new Error('conversation not found'); + broken.newSessionError = new Error('session/new failed'); + const third = new FakeAgyBackend(); + queue.push('one', REVIEW, 'a'); + const { run, created } = launch(session, [first, broken, third]); + await vi.waitFor(() => expect(first.prompts).toHaveLength(1)); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + + first.alive = false; + queue.push('two', REVIEW, 'b'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'two' })); + expect(broken.disconnected).toBe(true); + queue.push('three', REVIEW, 'c'); + await vi.waitFor(() => expect(third.prompts).toHaveLength(1)); + queue.close(); + await run; + + expect(created).toHaveLength(3); + expect(broken.prompts).toEqual([]); + expect(third.resumeCalls).toEqual(['agy-conv-new']); + expect(third.setModeCalls).toEqual(['default']); + expect(sessionEvents(client)).toContainEqual({ + type: 'error', + message: 'Failed to restart Antigravity: session/new failed' + }); + }); + + it('approves once in always-proceed even when agy offers a standing grant', async () => { + const { session, queue } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async () => { + backend.permissionHandler!({ + id: 'p1', sessionId: 'agy-conv-new', toolCallId: 'call_p1', title: 'git push', kind: 'execute', + rawInput: { CommandLine: 'git push' }, + options: [ + { optionId: 'always', name: 'Always allow', kind: 'allow_always' }, + { optionId: 'once', name: 'Allow', kind: 'allow_once' } + ] + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + queue.push('push it', { permissionMode: 'always-proceed' }, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.permissionResponses).toEqual([{ outcome: 'selected', optionId: 'once' }]); + }); + + it('leaves an agy question permission request to the user in always-proceed', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async () => { + backend.permissionHandler!({ + id: 'q1', sessionId: 'agy-conv-new', toolCallId: 'call_q', title: 'Run ask_question', kind: 'other', + rawInput: { questions: [{ question: 'RED or BLUE?', options: ['RED', 'BLUE'] }] }, + options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }] + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + queue.push('ask me', { permissionMode: 'always-proceed' }, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + // Pending for the user during the turn; the turn end answers it `cancelled`. + expect(backend.permissionResponses).toEqual([{ outcome: 'cancelled' }]); + const requested = client.updateAgentState.mock.calls + .map(([update]) => (update as (state: object) => { requests?: Record })({}).requests) + .some((requests) => requests?.q1 !== undefined); + expect(requested).toBe(true); + }); + + it('matches a steer echo split across chunks and spacing', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('Additional instructions:\n- End with BANANA.\n- Keep it short. ', REVIEW, 'steer-1'); + await steerRpc(client)({ localId: 'steer-1' }); + + backend.echo!('Additional instructions:\n- End with'); + expect(client.emitMessagesConsumed).not.toHaveBeenCalledWith(['steer-1'], { steered: true }); + backend.echo!(' BANANA.\n- Keep it short.'); + + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['steer-1'], { steered: true }); + release(); + backend.steerCompletions[0]!.resolve('end_turn'); + queue.close(); + await run; + }); + + it('confirms delivery only once agy takes the prompt', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let openGate!: () => void; + backend.setModelGate = new Promise((resolve) => { openGate = resolve; }); + backend.promptScripts.push(async (onUpdate) => { + backend.echo!('build it'); + onUpdate({ type: 'text', text: 'done' }); + }); + queue.push('build it', { permissionMode: 'request-review', model: 'gemini-3.8-flash', effort: 'low' }, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.setModeCalls).toEqual(['default'])); + + expect(client.emitMessagesConsumed).not.toHaveBeenCalled(); + openGate(); + await vi.waitFor(() => expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['a'])); + queue.close(); + await run; + expect(client.emitMessagesConsumed).toHaveBeenCalledTimes(1); + }); + + it('keeps a steer queued when the prompt has not reached agy yet', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.preSendDelayMs = 150; + queue.push('first', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.setModeCalls).toEqual(['default'])); + + queue.push('early steer', REVIEW, 'early'); + const result = await steerRpc(client)({ localId: 'early' }); + + expect(result).toEqual({ steered: false, error: 'Failed to steer into the active turn' }); + expect(queue.size()).toBe(1); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + }); + + it('keeps the HAPI turn open for a steer sent while the answer drains', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.postResponseDrainMs = 200; + queue.push('first', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + await vi.waitFor(() => expect(backend.promptInFlight).toBe(false)); + + queue.push('one more thing', REVIEW, 'late'); + expect(await steerRpc(client)({ localId: 'late' })).toEqual({ steered: true }); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(sessionEvents(client)).not.toContainEqual({ type: 'ready' }); + + backend.steerCompletions[0]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['late'], { steered: true }); + queue.close(); + await run; + }); + + it('holds a steer when agy dies after the interrupted request returned', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + await steerRpc(client)({ localId: 'steer-1' }); + release(); + await new Promise((resolve) => setTimeout(resolve, 20)); + + backend.alive = false; + backend.steerCompletions[0]!.reject(indeterminate()); + + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(sessionEvents(client)).not.toContainEqual({ type: 'abort-restore', text: 'run the tests' }); + queue.close(); + await run; + }); + + it('totals the usage agy 1.5.2 reported for a steered turn', async () => { + const results = agySteeredTurn.frames + .filter((frame) => frame.direction === 'agy->client' && 'result' in frame.message) + .map((frame) => (frame.message as unknown as { result: { usage: Record } }).result.usage); + const toUsage = (u: Record) => ({ + type: 'usage' as const, inputTokens: u.inputTokens!, outputTokens: u.outputTokens!, + totalTokens: u.totalTokens, thoughtTokens: u.thoughtTokens, cacheReadTokens: u.cachedReadTokens + }); + const backend = new FakeAgyBackend(); + let steered!: () => void; + const steerSent = new Promise((resolve) => { steered = resolve; }); + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + // agy answers the interrupted request as soon as the steer arrives. + await steerSent; + onUpdate(toUsage(results[0]!)); + }); + const { session, queue, client } = makeSession(); + queue.push('run the tests', REVIEW, 'first'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await steerRpc(client)({ localId: 'steer-1' })).toEqual({ steered: true }); + steered(); + await vi.waitFor(() => expect(backend.promptInFlight).toBe(false)); + backend.steerCompletions[0]!.onUsage?.(toUsage(results[1]!)); + backend.steerCompletions[0]!.resolve('end_turn'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + queue.close(); + await run; + + const summaries = roundSummaries(client); + expect(summaries).toHaveLength(1); + expect(summaries[0]).toMatchObject({ + provider: 'agy', + model: 'gemini-4-argon-medium', + agy_usage: { + input_tokens: 15172 + 15286, + output_tokens: 44 + 14, + thinking_tokens: 0, + cache_read_tokens: 0, + total_tokens: 15216 + 15300 + }, + duration_ms: expect.any(Number) + }); + }); +}); + +describe('AgyAcpRemoteLauncher permissions', () => { + const commandRequest = (id: string): PermissionRequest => ({ + id, + sessionId: 'agy-conv-new', + toolCallId: `call_${id}`, + title: 'grep -n think notes.md', + kind: 'execute', + rawInput: { CommandLine: 'grep -n think notes.md' }, + options: [ + { optionId: 'allow', name: 'Allow', kind: 'allow_once' }, + { optionId: 'deny', name: 'Deny', kind: 'reject_once' } + ] + }); + + it.each([ + ['request-review' as const, []], + ['always-proceed' as const, [{ outcome: 'selected', optionId: 'allow' }]] + ])('in %s, a command mentioning a HAPI tool hint gets %j', async (permissionMode, expected) => { + const { session, queue } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async () => { + backend.permissionHandler!(commandRequest('p1')); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + queue.push('hello', { permissionMode }, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + // The turn-end cancelAll answers anything still pending with cancelled. + expect(backend.permissionResponses.filter((response) => + (response as { outcome: string }).outcome === 'selected')).toEqual(expected); + }); + it('refuses a steer while agy waits for an approval, keeping the message queued', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let finish!: () => void; + backend.promptScripts.push(async () => { + backend.permissionHandler!(commandRequest('p1')); + await new Promise((resolve) => { finish = resolve; }); + }); + queue.push('run it', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(Object.keys(agentState(client).requests ?? {})).toEqual(['p1'])); + + queue.push('also lint', REVIEW, 'steer-1'); + const steer = client.rpcHandlerManager.handlers.get(RPC_METHODS.SteerQueuedMessage)!; + // agy rejects a prompt while an approval is open (-32603). + expect(await steer({ localId: 'steer-1' })).toEqual({ + steered: false, + error: 'Antigravity is waiting for an approval; answer it, then steer' + }); + expect(backend.steerPrompts).toEqual([]); + expect(client.setSteerDeliveryState).not.toHaveBeenCalled(); + expect(queue.size()).toBe(1); + + finish(); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + }); +}); + +describe('AgyAcpRemoteLauncher questions', () => { + it('never answers an agy question, even in always-proceed', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + // agy 1.5.2 asks without an elicitation capability like this: an + // ask_question tool call left pending, the question as text, end_turn. + // The user answers with the next message. + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ + type: 'tool_call', id: 'call_q', name: 'Run ask_question', kind: 'other', status: 'pending', + input: { questions: [{ question: 'RED or BLUE?', options: ['RED', 'BLUE'], is_multi_select: false }] } + }); + onUpdate({ type: 'text', text: 'RED or BLUE?\n- [1] RED\n- [2] BLUE' }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('ask me', { permissionMode: 'always-proceed' }, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(backend.permissionResponses).toEqual([]); + expect(client.sendAgentMessage).toHaveBeenCalledWith(expect.objectContaining({ + type: 'message', message: 'RED or BLUE?\n- [1] RED\n- [2] BLUE' + })); + expect(sessionEvents(client)).toContainEqual({ type: 'ready' }); + }); +}); + +describe('agy ACP helpers', () => { + it('maps HAPI permission modes to agy ACP modes', () => { + expect(agyAcpModeForPermission('request-review')).toBe('default'); + expect(agyAcpModeForPermission('always-proceed')).toBe('default'); + expect(agyAcpModeForPermission('acceptEdits')).toBe('accept-edits'); + expect(agyAcpModeForPermission('plan')).toBe('plan'); + expect(agyAcpModeForPermission(undefined)).toBe('default'); + }); + + it('builds agy model ids from the stored model and effort', () => { + expect(resolveAgyAcpModelId('gemini-3.8-flash', 'low', null)).toBe('gemini-3.8-flash-low'); + expect(resolveAgyAcpModelId('gpt-oss-120b-medium', null, null)).toBe('gpt-oss-120b-medium'); + expect(resolveAgyAcpModelId('gemini-3.8-flash-high', 'low', null)).toBe('gemini-3.8-flash-high'); + expect(resolveAgyAcpModelId(null, null, 'gemini-4-argon-medium')).toBe('gemini-4-argon-medium'); + expect(resolveAgyAcpModelId(null, 'high', 'gemini-4-argon-medium')).toBe('gemini-4-argon-high'); + expect(resolveAgyAcpModelId(undefined, undefined, null)).toBeNull(); + }); + + it('takes tool runs and waits for the user out of the generation time', () => { + // A tool run and, separately, a wait for an approval. + expect(agyGenerationMs(0, 10_000, [{ start: 1_000, end: 4_000 }, { start: 6_000, end: 7_000 }])).toBe(6_000); + // A steered turn: windows from both requests, in any order. + expect(agyGenerationMs(0, 20_000, [{ start: 12_000, end: 15_000 }, { start: 2_000, end: 8_000 }])).toBe(11_000); + // An approval wait inside a tool's span counts once. + expect(agyGenerationMs(0, 10_000, [{ start: 1_000, end: 6_000 }, { start: 2_000, end: 3_000 }, { start: 5_000, end: 8_000 }])).toBe(3_000); + // Cancelled mid-tool: the open window ends with the round; spans + // outside the round do not count. + expect(agyGenerationMs(1_000, 5_000, [{ start: 0, end: 2_000 }, { start: 3_000, end: null }])).toBe(1_000); + // No answer, or nothing left but tools. + expect(agyGenerationMs(0, null, [])).toBeNull(); + expect(agyGenerationMs(null, 5_000, [])).toBeNull(); + expect(agyGenerationMs(0, 5_000, [{ start: 0, end: 5_000 }])).toBe(0); + }); + + it('reports generation tokens, thinking included, only with a positive generation time', () => { + const usage = { type: 'usage' as const, inputTokens: 100, outputTokens: 40, thoughtTokens: 20 }; + expect(agyRoundSummary(usage, 9_000, null, 3_000.4).summary).toMatchObject({ + generation_ms: 3_000, + generation_output_tokens: 60 + }); + for (const generationMs of [null, 0, -5]) { + const summary = agyRoundSummary(usage, 9_000, null, generationMs).summary; + expect(summary).not.toHaveProperty('generation_ms'); + expect(summary).not.toHaveProperty('generation_output_tokens'); + } + expect(agyRoundSummary({ ...usage, outputTokens: 0, thoughtTokens: 0 }, 9_000, null, 3_000).summary) + .not.toHaveProperty('generation_ms'); + }); + + it('totals usage across the requests of one turn', () => { + const first = { type: 'usage' as const, inputTokens: 10, outputTokens: 1, thoughtTokens: 2 }; + const second = { type: 'usage' as const, inputTokens: 20, outputTokens: 3, cacheReadTokens: 4 }; + expect(addAgyUsage(null, first)).toBe(first); + expect(addAgyUsage(first, second)).toEqual({ + type: 'usage', + inputTokens: 30, + outputTokens: 4, + totalTokens: undefined, + thoughtTokens: 2, + cacheReadTokens: 4, + cacheCreationTokens: undefined + }); + }); +}); + +describe('AgyAcpRemoteLauncher steer state matrix', () => { + type Handlers = Map Promise>; + const rpc = (client: ReturnType, method: string) => + (client.rpcHandlerManager.handlers as Handlers).get(method)!; + const lost = () => { + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + return error; + }; + const consumedSteer = (client: ReturnType, localId: string) => + client.emitMessagesConsumed.mock.calls.some(([ids, opts]) => + (ids as string[])[0] === localId && (opts as { steered?: boolean } | undefined)?.steered === true); + + async function heldTurn(backend: FakeAgyBackend, prompt = 'run the tests') { + const { session, queue, client } = makeSession(); + let release!: () => void; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ type: 'tool_call', id: 't1', name: 'run_command', input: {}, status: 'in_progress' }); + await new Promise((resolve) => { release = resolve; }); + }); + queue.push(prompt, REVIEW, 'first'); + const { run, created } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + return { session, queue, client, run, created, release: () => release() }; + } + + it('refuses to steer a control command and keeps it queued', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.pushIsolated('/compact', REVIEW, 'control'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'control' })) + .toEqual({ steered: false, error: 'Control commands cannot be steered' }); + expect(backend.steerPrompts).toEqual([]); + expect(queue.size()).toBe(1); + release(); + queue.close(); + await run; + }); + + it('refuses to steer a message that is no longer queued', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'gone' })) + .toEqual({ steered: false, error: 'Message not in queue' }); + expect(backend.steerPrompts).toEqual([]); + release(); + queue.close(); + await run; + }); + + it('holds a steer whose delivery state the hub could not record, without sending it', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + client.setSteerDeliveryState.mockResolvedValueOnce(false); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })) + .toEqual({ steered: false, error: 'Steer state is indeterminate' }); + expect(backend.steerPrompts).toEqual([]); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + release(); + queue.close(); + await run; + }); + + it.each([ + ['starting the request', 'start'], + ['writing the request', 'dispatch'] + ])('holds a steer when agy is lost while %s', async (_label, stage) => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + if (stage === 'start') backend.steerStartError = lost(); + else backend.steerDispatchError = lost(); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })) + .toEqual({ steered: false, error: 'Steer outcome is being reconciled' }); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(consumedSteer(client, 'steer-1')).toBe(false); + expect(queue.size()).toBe(0); + release(); + queue.close(); + await run; + }); + + it('keeps a steer queued that arrives while agy restarts', async () => { + const { session, queue, client } = makeSession(); + const first = new FakeAgyBackend(); + const second = new FakeAgyBackend(); + let started!: () => void; + const { run } = launch(session, [first, second]); + queue.push('one', REVIEW, 'a'); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + first.alive = false; + second.initializeGate = new Promise((resolve) => { started = resolve; }); + queue.push('two', REVIEW, 'b'); + await vi.waitFor(() => expect(second.calls).toEqual(['initialize'])); + + queue.push('also lint', REVIEW, 'steer-1'); + const result = await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' }) as { steered: boolean }; + expect(result.steered).toBe(false); + expect(second.steerPrompts).toEqual([]); + expect(queue.size()).toBe(1); + + started(); + await vi.waitFor(() => expect(second.prompts).toEqual([ + [{ type: 'text', text: 'two' }], + [{ type: 'text', text: 'also lint' }] + ])); + queue.close(); + await run; + }); + + it('confirms two steers that agy echoes in one chunk', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('lint', REVIEW, 'short'); + queue.push('fix the types', REVIEW, 'other'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'short' })).toEqual({ steered: true }); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'other' })).toEqual({ steered: true }); + backend.echo!('run the tests'); + backend.echo!('lint\nfix the types'); + expect(consumedSteer(client, 'short')).toBe(true); + expect(consumedSteer(client, 'other')).toBe(true); + + // Stop afterwards does not undo either. + backend.onCancel = () => { + release(); + for (const steer of backend.steerCompletions) steer.resolve('cancelled'); + }; + await rpc(client, RPC_METHODS.Abort)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalled(); + queue.close(); + await run; + }); + + it('does not let a late echo from the previous turn expose the next prompt to a steer match', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client } = makeSession(); + let release!: () => void; + backend.promptScripts.push(async () => {}); + backend.promptScripts.push(async () => { + await new Promise((resolve) => { release = resolve; }); + }); + queue.push('first task', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + + queue.push('run the tests and then lint', REVIEW, 'b'); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + // A stray echo from the previous turn arrives first. + backend.echo!('an earlier steer'); + queue.push('lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.echo!('run the tests and then lint'); + expect(consumedSteer(client, 'steer-1')).toBe(false); + + backend.echo!('lint'); + expect(consumedSteer(client, 'steer-1')).toBe(true); + release(); + backend.steerCompletions[0]!.resolve('end_turn'); + queue.close(); + await run; + }); + + it('keeps an early-answered steer confirmed once echoed, even after a Stop', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + queue.push('and format', REVIEW, 'steer-2'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-2' })).toEqual({ steered: true }); + backend.steerCompletions[0]!.resolve('end_turn'); + backend.echo!('run the tests'); + backend.echo!('also lint'); + backend.onCancel = () => { + release(); + backend.steerCompletions[1]!.resolve('cancelled'); + }; + await rpc(client, RPC_METHODS.Abort)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(consumedSteer(client, 'steer-1')).toBe(true); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalledWith(['steer-1']); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-2']); + queue.close(); + await run; + }); + + it('keeps a steer that agy rejects after a Stop queued', async () => { + const backend = new FakeAgyBackend(); + const { queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.onCancel = () => { + release(); + backend.steerCompletions[0]!.reject(Object.assign(new Error('Invalid params'), { code: -32602 })); + }; + await rpc(client, RPC_METHODS.Abort)(); + // Back in the queue, it runs as the next turn. + await vi.waitFor(() => expect(backend.prompts).toEqual([ + [{ type: 'text', text: 'run the tests' }], + [{ type: 'text', text: 'also lint' }] + ])); + expect(consumedSteer(client, 'steer-1')).toBe(false); + expect(client.emitSteerIndeterminate).not.toHaveBeenCalled(); + queue.close(); + await run; + }); + + it('keeps the main prompt when Stop leaves a steer agy may have taken', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client } = makeSession(); + let cancelled!: () => void; + backend.promptScripts.push(async (onUpdate) => { + await new Promise((resolve) => { cancelled = resolve; }); + onUpdate({ type: 'turn_complete', stopReason: 'cancelled' }); + }); + queue.push('build it', REVIEW, 'first'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.onCancel = () => { + cancelled(); + backend.steerCompletions[0]!.resolve('cancelled'); + }; + await rpc(client, RPC_METHODS.Abort)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + // agy may have folded the steer into the main prompt, so neither goes + // back to the composer: the steer is held, the prompt stays delivered. + expect(sessionEvents(client)).not.toContainEqual({ type: 'abort-restore', text: 'build it' }); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['first']); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + queue.close(); + await run; + }); + + it('holds an open steer when agy ignores the cancel and is restarted', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client } = makeSession(); + backend.promptScripts.push(async () => { + await new Promise((_resolve, reject) => { + backend.onDisconnect = () => reject(lost()); + }); + }); + queue.push('stuck', REVIEW, 'first'); + const { run } = launch(session, [backend], { cancelHardStopMs: 80 }); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.steerCompletions[0]!.answer(); + + await rpc(client, RPC_METHODS.Abort)(); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(consumedSteer(client, 'steer-1')).toBe(false); + queue.close(); + await run; + }); + + it.each([ + ['still waiting to send', 'waiting'], + ['draining its cancelled answer', 'draining'] + ])('puts a prompt back before the session ends when it is killed while %s', async (_label, stage) => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + if (stage === 'waiting') { + backend.preSendDelayMs = 150; + } else { + backend.promptScripts.push(async () => { + await new Promise((resolve) => { backend.onDisconnect = resolve; }); + // HAPI still drains late output before the request fails. + await new Promise((resolve) => setTimeout(resolve, 150)); + const error = new Error('ACP transport closed'); + Object.defineProperty(error, ACP_INDETERMINATE_SYMBOL, { value: true }); + throw error; + }); + } + queue.push('build it', REVIEW, 'first'); + const { run } = launch(session, [backend]); + if (stage === 'waiting') await vi.waitFor(() => expect(session.thinking).toBe(true)); + else await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + + await session.kill(); + // The runner ends the session and closes the client right after kill(). + const eventsAtKill = sessionEvents(client).length; + const consumedAtKill = client.emitMessagesConsumed.mock.calls.length; + expect(sessionEvents(client)).toContainEqual({ type: 'abort-restore', text: 'build it' }); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['first']); + + queue.close(); + await run; + expect(sessionEvents(client)).toHaveLength(eventsAtKill); + expect(client.emitMessagesConsumed.mock.calls).toHaveLength(consumedAtKill); + }); + + it('does not let an agy that never settles hold the session end forever', async () => { + const { session, queue } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(() => new Promise(() => {})); + queue.push('build it', REVIEW, 'first'); + launch(session, [backend], { killSettleMs: 50 }); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(1)); + + const startedAt = Date.now(); + await session.kill(); + expect(Date.now() - startedAt).toBeLessThan(1_000); + expect(backend.disconnected).toBe(true); + }); + + it('holds an open steer when the session is killed mid-turn', async () => { + const backend = new FakeAgyBackend(); + const { session, queue, client, run, release } = await heldTurn(backend); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(client, RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ steered: true }); + backend.onCancel = () => release(); + backend.onDisconnect = () => backend.steerCompletions[0]!.reject(lost()); + + await session.kill(); + // Settled before kill() returns, since the runner ends the session then. + expect(client.emitSteerIndeterminate).toHaveBeenCalledWith(['steer-1']); + expect(consumedSteer(client, 'steer-1')).toBe(false); + queue.close(); + await run; + }); +}); diff --git a/cli/src/agy/agyAcpRemoteLauncher.ts b/cli/src/agy/agyAcpRemoteLauncher.ts new file mode 100644 index 00000000..53f0c01a --- /dev/null +++ b/cli/src/agy/agyAcpRemoteLauncher.ts @@ -0,0 +1,949 @@ +import React from 'react'; +import { RPC_METHODS, splitAgyModelSelection } from '@hapi/protocol'; +import { logger } from '@/ui/logger'; +import { RemoteModeDisplay } from '@/ui/ink/RemoteModeDisplay'; +import { convertAgentMessage } from '@/agent/messageConverter'; +import { createAcpSessionTitleSync, registerAcpSessionTitleSync } from '@/agent/acpSessionTitle'; +import type { AgentMessage, PermissionRequest, PromptContent } from '@/agent/types'; +import type { AcpSdkBackend } from '@/agent/backends/acp'; +import { isAcpIndeterminateError } from '@/agent/backends/acp/AcpStdioTransport'; +import { AcpPermissionHandler } from '@/modules/common/permission/AcpPermissionHandler'; +import { + RemoteLauncherBase, + type RemoteLauncherDisplayContext, + type RemoteLauncherExitReason +} from '@/modules/common/remote/RemoteLauncherBase'; +import type { SessionEffort, SessionModel } from '@/api/types'; +import type { AgySession } from './session'; +import type { AgyMode, PermissionMode } from './types'; +import { createAgyAcpBackend } from './utils/agyAcpBackend'; + +type UsageMessage = Extract; + +const STEER_CANCEL_GRACE_MS = 3_000; +const CANCEL_HARD_STOP_MS = 10_000; +// Bound on how long a kill waits for the running turn to settle. +const KILL_SETTLE_MS = 5_000; +const PROMPT_SEND_POLL_MS = 50; +const ECHO_BUFFER_LIMIT = 64 * 1024; + +/** `always-proceed` stays in agy's default mode; HAPI answers its requests. */ +export function agyAcpModeForPermission(mode: PermissionMode | undefined): string { + switch (mode) { + case 'acceptEdits': + return 'accept-edits'; + case 'plan': + return 'plan'; + case 'request-review': + case 'always-proceed': + case undefined: + return 'default'; + } +} + +/** + * agy ids carry effort as a suffix (`gemini-3.8-flash-low`) while HAPI stores + * model and effort separately. No model means agy's default, whose effort can + * still be chosen. + */ +export function resolveAgyAcpModelId( + model: SessionModel | undefined, + effort: SessionEffort | undefined, + defaultModelId: string | null +): string | null { + const selected = splitAgyModelSelection(model); + if (!selected.model) { + if (!defaultModelId) return null; + if (!effort) return defaultModelId; + const base = splitAgyModelSelection(defaultModelId).model ?? defaultModelId; + return `${base}-${effort}`; + } + const value = model!.trim(); + return selected.effort || !effort ? value : `${value}-${effort}`; +} + +function addOptional(a: number | undefined, b: number | undefined): number | undefined { + return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0); +} + +/** Each request of a steered turn reports only its own share, so they add up. */ +export function addAgyUsage(total: UsageMessage | null, next: UsageMessage): UsageMessage { + if (!total) return next; + return { + type: 'usage', + inputTokens: total.inputTokens + next.inputTokens, + outputTokens: total.outputTokens + next.outputTokens, + totalTokens: addOptional(total.totalTokens, next.totalTokens), + thoughtTokens: addOptional(total.thoughtTokens, next.thoughtTokens), + cacheReadTokens: addOptional(total.cacheReadTokens, next.cacheReadTokens), + cacheCreationTokens: addOptional(total.cacheCreationTokens, next.cacheCreationTokens) + }; +} + +type TimeWindow = { start: number; end: number | null }; + +/** + * agy reports no per-step timing, so generation time is the round minus the + * spans spent running tools or waiting for the user. Spans are clipped to the + * round and merged, so overlaps count once; an open span ends with the round. + */ +export function agyGenerationMs(sentAt: number | null, answeredAt: number | null, windows: TimeWindow[]): number | null { + if (sentAt === null || answeredAt === null || answeredAt <= sentAt) return null; + const clipped = windows + .map(({ start, end }) => ({ start: Math.max(start, sentAt), end: Math.min(end ?? answeredAt, answeredAt) })) + .filter(({ start, end }) => end > start) + .sort((a, b) => a.start - b.start); + let excluded = 0; + let coveredUntil = sentAt; + for (const { start, end } of clipped) { + const from = Math.max(start, coveredUntil); + if (end > from) excluded += end - from; + coveredUntil = Math.max(coveredUntil, end); + } + return answeredAt - sentAt - excluded; +} + +/** The turn's response-footer record; the web reads `provider: 'agy'` summaries. */ +export function agyRoundSummary( + usage: UsageMessage, + durationMs: number | null, + model: string | null, + generationMs: number | null = null +) { + // Thinking is generated too, as in OpenCode's tok/s. + const generatedTokens = usage.outputTokens + (usage.thoughtTokens ?? 0); + const generation = generationMs !== null && generationMs > 0 && generatedTokens > 0 + ? { generation_ms: Math.round(generationMs), generation_output_tokens: generatedTokens } + : {}; + return { + type: 'round-summary', + summary: { + provider: 'agy', + ...(model ? { model } : {}), + agy_usage: { + input_tokens: usage.inputTokens, + output_tokens: usage.outputTokens, + ...(usage.thoughtTokens !== undefined ? { thinking_tokens: usage.thoughtTokens } : {}), + ...(usage.cacheReadTokens !== undefined ? { cache_read_tokens: usage.cacheReadTokens } : {}), + ...(usage.totalTokens !== undefined ? { total_tokens: usage.totalTokens } : {}) + }, + ...(durationMs !== null ? { duration_ms: durationMs } : {}), + ...generation + } + } as const; +} + +function normalizeEcho(text: string): string { + return text.replace(/\s+/g, ' ').trim(); +} + +/** agy's question tool; its permission request must reach the user. */ +export function isAgyQuestionRequest(request: PermissionRequest): boolean { + const input = request.rawInput as { questions?: unknown } | undefined; + return Array.isArray(input?.questions) || /\bask_question\b/.test(request.title ?? ''); +} + +/** agy acp did not come up; the caller may fall back to another transport. */ +export class AgyAcpStartError extends Error {} + +type AgyTurn = { + modeHash: string; + aborted: boolean; + stopReason: string | null; + sentAt: number | null; + answeredAt: number | null; + // Tool runs and waits for the user, which are not generation time. + idleWindows: TimeWindow[]; + toolWindows: Map; + usage: UsageMessage | null; + // Any agent output proves agy accepted the prompt. + sawActivity: boolean; + acknowledge: () => void; + steers: Promise[]; + // Steers agy may have taken; one put back in the queue no longer counts. + steersTaken: number; + // agy's answers to the turn's requests, before HAPI drains late output. + mainAnswered: Promise; + answerMain: () => void; + steerAnswers: Promise[]; + // agy echoes the prompt first, and that echo may contain a steer's text. + promptEcho: { text: string; echo: string; done: boolean }; + unechoedSteers: Array<{ text: string; echo: string; accept: () => void }>; + // Steers agy answered without an echo; settled when the turn ends. + answeredSteers: Array<{ accept: () => void; hold: () => void }>; + abandonSteers: Array<() => void>; + releaseSteerWait: () => void; + steerWaitReleased: Promise; +}; + +/** + * Antigravity over `agy acp`. The agy conversation id is the ACP session id, + * so a stored `agySessionId` resumes through `session/resume` without replay. + */ +export class AgyAcpRemoteLauncher extends RemoteLauncherBase { + private readonly session: AgySession; + private readonly createBackend: () => AcpSdkBackend; + private readonly steerCancelGraceMs: number; + private readonly cancelHardStopMs: number; + private readonly killSettleMs: number; + private turnSettled: Promise | null = null; + private backend: AcpSdkBackend | null = null; + private permissionHandler: AcpPermissionHandler | null = null; + private acpSessionId: string | null = null; + private abortController = new AbortController(); + /** agy's own model at session start; the target of the "Default" selection. */ + private defaultModelId: string | null = null; + private currentModelId: string | null = null; + private turnPermissionMode: PermissionMode | undefined = undefined; + private turn: AgyTurn | null = null; + private backendLost = false; + + constructor(session: AgySession, opts: { + createBackend?: () => AcpSdkBackend; + steerCancelGraceMs?: number; + cancelHardStopMs?: number; + killSettleMs?: number; + } = {}) { + super(process.env.DEBUG ? session.logPath : undefined); + this.session = session; + this.createBackend = opts.createBackend ?? createAgyAcpBackend; + this.steerCancelGraceMs = opts.steerCancelGraceMs ?? STEER_CANCEL_GRACE_MS; + this.cancelHardStopMs = opts.cancelHardStopMs ?? CANCEL_HARD_STOP_MS; + this.killSettleMs = opts.killSettleMs ?? KILL_SETTLE_MS; + this.session.setKillHandler(() => this.handleKill()); + } + + async launch(): Promise { + return this.start({ onExit: () => this.handleExitFromUi() }); + } + + protected createDisplay(context: RemoteLauncherDisplayContext): React.ReactElement { + return React.createElement(RemoteModeDisplay, { ...context, agentLabel: 'Antigravity' }); + } + + protected getCurrentSessionId(): string | null { + return this.acpSessionId; + } + + protected async runMainLoop(): Promise { + const session = this.session; + session.client.updateAgentState((state) => ({ ...state, steeringActive: false })); + this.messageBuffer.addMessage( + session.sessionId ? 'Resuming agy session...' : 'Starting agy session...', + 'status' + ); + // Steering keys on this marker; published before agy starts, it reaches + // the hub before any turn can take a steer. + session.client.updateMetadata((metadata) => ({ ...metadata, agyProtocol: 'acp' })); + session.client.rpcHandlerManager.registerHandler( + RPC_METHODS.SteerQueuedMessage, + async (payload: unknown) => await this.handleSteer(payload) + ); + try { + await this.startBackend(session.sessionId); + } catch (error) { + // A kill during start-up is not a start failure. + if (this.shouldExit) return; + // Otherwise the session only ends as crashed, without the reason + // (agy not signed in, an agy release without `acp`, ...). + const message = describeAgyStartFailure(error); + this.reportTurnError(message); + throw new AgyAcpStartError(message); + } + + this.setupAbortHandlers(session.client.rpcHandlerManager, { + onAbort: () => this.handleAbort(), + // AGY is remote-only: a web-initiated switch to local has no target. + onSwitch: () => {} + }); + + while (!this.shouldExit) { + // Stop replaces the controller, so check the signal this wait used. + const signal = this.abortController.signal; + const batch = await session.queue.waitForMessagesAndGetAsString(signal); + if (!batch) { + if (signal.aborted && !this.shouldExit) continue; + break; + } + const localIds = batch.items + .map((item) => item.localId) + .filter((localId): localId is string => Boolean(localId)); + const turnRun = this.runTurn(batch.message, batch.mode, batch.hash, localIds); + this.turnSettled = turnRun.then(() => {}, () => {}); + await turnRun; + } + } + + private async startBackend(resumeSessionId: string | null): Promise { + const session = this.session; + const backend = this.createBackend(); + this.backend = backend; + this.backendLost = false; + try { + const titleSync = createAcpSessionTitleSync(session.client); + registerAcpSessionTitleSync(backend, session.client, titleSync); + backend.setUserMessageChunkListener((text) => this.handleUserEcho(text)); + backend.onStderrError((error) => { + logger.debug('[agy-acp] stderr error', error); + session.sendSessionEvent({ type: 'message', message: error.message }); + this.messageBuffer.addMessage(error.message, 'status'); + }); + + await backend.initialize(); + + let acpSessionId: string | null = null; + if (resumeSessionId) { + try { + if (!backend.supportsSessionResume()) { + throw new Error('agy acp does not advertise session/resume'); + } + acpSessionId = await backend.resumeSession({ + sessionId: resumeSessionId, + cwd: session.path, + mcpServers: [] + }); + } catch (error) { + logger.warn('[agy-acp] resume failed, starting a new conversation', error); + session.sendSessionEvent({ + type: 'message', + message: 'Antigravity could not resume the conversation; starting a new one.' + }); + } + } + if (!acpSessionId) { + acpSessionId = await backend.newSession({ cwd: session.path, mcpServers: [] }); + } + this.acpSessionId = acpSessionId; + session.onSessionFound(acpSessionId); + session.client.emitSessionReady(); + + const reported = backend.getSessionModelsMetadata(acpSessionId)?.currentModelId ?? null; + this.currentModelId = reported; + // After a relaunch the resumed conversation reports the switched + // model, not agy's default, so keep the first value. + if (this.defaultModelId === null) this.defaultModelId = reported; + + this.permissionHandler = new AcpPermissionHandler( + session.client, + backend, + () => this.turnPermissionMode ?? (session.getPermissionMode() as PermissionMode | undefined), + { + // agy titles run_command requests with the command line and + // gets no HAPI MCP tools, so the tool-name hints could only + // match command text. + autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] }, + autoApproveOnce: true, + requiresUser: isAgyQuestionRequest, + onUserWait: () => { + const turn = this.turn; + if (!turn) return () => {}; + const window: TimeWindow = { start: Date.now(), end: null }; + turn.idleWindows.push(window); + return () => { window.end ??= Date.now(); }; + } + } + ); + void backend.refreshSessionInfo(acpSessionId, session.path); + } catch (error) { + // A half-started process must not serve later turns; the next turn + // starts agy again and resumes the previous conversation. + this.backendLost = true; + if (this.backend === backend) this.backend = null; + await this.retireBackend(backend); + throw error; + } + } + + private async relaunchBackend(): Promise { + const previous = this.backend; + this.backend = null; + if (previous) await this.retireBackend(previous); + await this.startBackend(this.acpSessionId); + } + + /** Stops a backend for good: late permission requests are cancelled, not approved. */ + private async retireBackend(backend: AcpSdkBackend): Promise { + backend.onPermissionRequest((request) => { + void backend.respondToPermission(request.sessionId, request, { outcome: 'cancelled' }); + }); + const handler = this.permissionHandler; + this.permissionHandler = null; + await handler?.cancelAll('Antigravity stopped'); + try { + await backend.disconnect(); + } catch (error) { + logger.debug('[agy-acp] disconnect failed', error); + } + } + + /** Apply the batch's mode and model; false when the turn must not run. */ + private async applyTurnConfig(backend: AcpSdkBackend, acpSessionId: string, mode: AgyMode): Promise { + // Sent every turn: agy can change its mode on its own (current_mode_update), + // which HAPI does not track. + const acpMode = agyAcpModeForPermission(mode.permissionMode); + try { + await backend.setMode(acpSessionId, acpMode); + } catch (error) { + this.reportTurnError(`Failed to switch Antigravity mode: ${errorMessage(error)}`); + return false; + } + + const modelId = resolveAgyAcpModelId(mode.model, mode.effort, this.defaultModelId); + if (modelId && modelId !== this.currentModelId) { + try { + await backend.setModel(acpSessionId, modelId); + this.currentModelId = modelId; + this.messageBuffer.addMessage(`[MODEL:${modelId}]`, 'system'); + } catch (error) { + this.reportTurnError(`Failed to switch Antigravity model to ${modelId}: ${errorMessage(error)}`); + return false; + } + } + return true; + } + + private async runTurn(message: string, mode: AgyMode, modeHash: string, localIds: string[]): Promise { + const session = this.session; + session.onThinkingChange(true); + this.turnPermissionMode = mode.permissionMode; + let releaseSteerWait!: () => void; + const steerWaitReleased = new Promise((resolve) => { releaseSteerWait = resolve; }); + let acknowledged = false; + let answerMain!: () => void; + const mainAnswered = new Promise((resolve) => { answerMain = resolve; }); + const turn: AgyTurn = { + modeHash, + aborted: false, + stopReason: null, + sentAt: null, + answeredAt: null, + idleWindows: [], + toolWindows: new Map(), + usage: null, + sawActivity: false, + // AgySession does not acknowledge on dequeue: a message counts as + // delivered once agy takes it (echo, output, or answer), or when + // it goes back to the composer. + acknowledge: () => { + if (acknowledged || localIds.length === 0) return; + acknowledged = true; + session.client.emitMessagesConsumed(localIds); + }, + steers: [], + steersTaken: 0, + mainAnswered, + answerMain, + steerAnswers: [], + promptEcho: { text: normalizeEcho(message), echo: '', done: false }, + unechoedSteers: [], + answeredSteers: [], + abandonSteers: [], + releaseSteerWait, + steerWaitReleased + }; + // Registered before any await so Stop can reach the turn while agy + // restarts or switches settings. + this.turn = turn; + try { + if (this.backendLost || !this.backend || !this.backend.isTransportAlive()) { + try { + await this.relaunchBackend(); + } catch (error) { + this.reportTurnError(`Failed to restart Antigravity: ${errorMessage(error)}`); + this.restorePrompt(turn, message); + return; + } + } + const backend = this.backend; + const acpSessionId = this.acpSessionId; + if (!backend || !acpSessionId || turn.aborted) { + this.restorePrompt(turn, message); + return; + } + if (!await this.applyTurnConfig(backend, acpSessionId, mode) || turn.aborted) { + this.restorePrompt(turn, message); + return; + } + this.messageBuffer.addMessage(message, 'user'); + const prompt: PromptContent[] = [{ type: 'text', text: message }]; + session.client.updateAgentState((state) => ({ ...state, steeringActive: true })); + try { + await backend.prompt(acpSessionId, prompt, (update) => this.handleTurnUpdate(turn, update), { + onSent: () => { turn.sentAt = Date.now(); }, + onAnswered: () => { + turn.answeredAt = Date.now(); + turn.answerMain(); + } + }); + // agy answers a cancel with a normal `cancelled` result; with no + // output yet, the prompt goes back to the composer. + if (turn.stopReason === 'cancelled' && !turn.sawActivity && turn.steersTaken === 0) { + this.restorePrompt(turn, message); + } else { + turn.acknowledge(); + } + } catch (error) { + logger.warn('[agy-acp] prompt failed', error); + if (isAcpIndeterminateError(error)) this.backendLost = true; + if (!turn.aborted) { + this.reportTurnError(`Antigravity prompt failed: ${errorMessage(error)}`); + } + if (!turn.sawActivity && turn.steersTaken === 0) this.restorePrompt(turn, message); + else turn.acknowledge(); + } + // A steer makes agy answer the request it interrupts right away + // (end_turn) while the turn goes on under the steer, so the turn + // ends only when every open request has settled. Steers sent + // during this wait extend it. + await this.waitForSteers(turn); + } finally { + // After a Stop or a lost agy process, agy may have dropped a steer + // it had not echoed yet. + const endedCleanly = !turn.aborted && !this.backendLost; + for (const steer of turn.answeredSteers) { + if (endedCleanly) steer.accept(); + else steer.hold(); + } + turn.answerMain(); + if (this.turn === turn) this.turn = null; + session.client.updateAgentState((state) => ({ ...state, steeringActive: false })); + this.turnPermissionMode = undefined; + // agy's usage adds up every model call of a request, so it is not a + // context size: it goes to the response footer, not the context + // indicator (no token_count). + if (turn.usage) { + // agy's own time: HAPI's waits before sending and for late + // output are not part of it. + const durationMs = turn.sentAt !== null && turn.answeredAt !== null + ? Math.max(0, turn.answeredAt - turn.sentAt) + : null; + const generationMs = turn.sawActivity + ? agyGenerationMs(turn.sentAt, turn.answeredAt, turn.idleWindows) + : null; + session.sendAgentMessage(agyRoundSummary(turn.usage, durationMs, this.currentModelId, generationMs)); + } + session.onThinkingChange(false); + await this.permissionHandler?.cancelAll('Prompt finished'); + if (session.queue.size() === 0 && !this.shouldExit) { + session.sendSessionEvent({ type: 'ready' }); + } + } + } + + private async waitForSteers(turn: AgyTurn): Promise { + while (turn.steers.length > 0) { + const pending = [...turn.steers]; + const released = await Promise.race([ + Promise.allSettled(pending).then(() => false), + turn.steerWaitReleased.then(() => true) + ]); + if (released) return; + turn.steers = turn.steers.filter((steer) => !pending.includes(steer)); + } + } + + /** + * The hub RPC is answered once the steer request is written: the request + * itself only completes with the turn, past the hub's RPC timeout. + */ + private async handleSteer(payload: unknown): Promise<{ steered: boolean; error?: string }> { + const session = this.session; + const localId = typeof (payload as { localId?: unknown } | null)?.localId === 'string' + ? (payload as { localId: string }).localId + : ''; + if (!localId) return { steered: false, error: 'Missing localId' }; + const backend = this.backend; + const acpSessionId = this.acpSessionId; + const turn = this.turn; + if (!turn || turn.aborted || !backend || !acpSessionId || this.shouldExit) { + return { steered: false, error: 'No active steerable turn' }; + } + // agy rejects a prompt while an approval is open. + if (this.permissionHandler?.hasPendingRequests()) { + return { steered: false, error: 'Antigravity is waiting for an approval; answer it, then steer' }; + } + const taken = session.queue.takeByLocalId(localId); + if (!taken) return { steered: false, error: 'Message not in queue' }; + if (taken.item.isolate) { + session.queue.restoreReservation(taken); + return { steered: false, error: 'Control commands cannot be steered' }; + } + if (taken.item.modeHash !== turn.modeHash) { + session.queue.restoreReservation(taken); + return { steered: false, error: 'Queued message mode differs from the active turn' }; + } + if (!session.queue.beginReservationDispatch(taken)) { + return { steered: false, error: 'Steer cancelled' }; + } + if (!await session.client.setSteerDeliveryState([localId], 'dispatching')) { + session.queue.markReservationIndeterminate(taken); + session.client.emitSteerIndeterminate([localId]); + return { steered: false, error: 'Steer state is indeterminate' }; + } + let resolved = false; + let steerCounted = false; + let forgetEcho = () => {}; + const markIndeterminate = () => { + if (resolved) return; + resolved = true; + forgetEcho(); + if (session.queue.markReservationIndeterminate(taken)) { + session.client.emitSteerIndeterminate([localId]); + } + }; + const restoreQueued = async (): Promise => { + if (resolved) return; + resolved = true; + forgetEcho(); + if (steerCounted) { + steerCounted = false; + turn.steersTaken -= 1; + } + if (!taken.originIndeterminate + && !await session.client.setSteerDeliveryState([localId], 'queued')) { + if (session.queue.markReservationIndeterminate(taken)) { + session.client.emitSteerIndeterminate([localId]); + } + return; + } + if (taken.state !== 'dispatching' || !session.queue.restoreReservation(taken)) { + session.client.emitSteerIndeterminate([localId]); + } + }; + if (taken.state !== 'dispatching') { + session.client.emitSteerIndeterminate([localId]); + return { steered: false, error: 'Steer cancelled' }; + } + if (this.turn !== turn || this.backend !== backend || turn.aborted) { + await restoreQueued(); + return { steered: false, error: 'Active turn changed' }; + } + + let steer: ReturnType; + try { + steer = backend.beginSoftSteerPrompt( + acpSessionId, + [{ type: 'text', text: taken.item.message }], + { + onUsage: (usage) => { + // Answered after its turn ended: the turn's summary is already + // out, and a second one would read as another turn. + if (this.turn !== turn) return; + turn.usage = addAgyUsage(turn.usage, usage); + } + } + ); + } catch (error) { + if (isAcpIndeterminateError(error)) { + markIndeterminate(); + return { steered: false, error: 'Steer outcome is being reconciled' }; + } + // No open request to fold into (the turn just ended): keep it queued. + logger.debug('[agy-acp] steer could not start', error); + await restoreQueued(); + return { steered: false, error: 'Failed to steer into the active turn' }; + } + // Register before awaiting dispatch so the turn cannot end in between. + const settled = Promise.all([steer.dispatched, steer.completed]).then(() => {}, () => {}); + turn.steers.push(settled); + turn.steersTaken += 1; + steerCounted = true; + turn.steerAnswers.push(steer.answered.then(() => { + if (this.turn === turn) turn.answeredAt = Date.now(); + })); + // agy echoes a steer (user_message_chunk) when it folds it into the + // turn, which is the moment it belongs in the transcript; the request + // itself is only answered when the turn ends. + const accept = () => { + if (resolved) return; + resolved = true; + forgetEcho(); + session.queue.commitReservation(taken); + this.messageBuffer.addMessage(taken.item.message, 'user'); + session.client.emitMessagesConsumed([localId], { steered: true }); + }; + forgetEcho = () => { + turn.unechoedSteers = turn.unechoedSteers.filter((entry) => entry.accept !== accept); + }; + turn.unechoedSteers.push({ text: normalizeEcho(taken.item.message), echo: '', accept }); + turn.abandonSteers.push(markIndeterminate); + + try { + await steer.dispatched; + } catch (error) { + if (isAcpIndeterminateError(error)) { + markIndeterminate(); + return { steered: false, error: 'Steer outcome is being reconciled' }; + } + await restoreQueued(); + return { steered: false, error: 'Failed to steer into the active turn' }; + } + + void steer.completed.then((stopReason) => { + // Stop answers an open steer with `cancelled`; without the echo, + // agy may or may not have folded it in, so hold it for an + // explicit Retry/Cancel. + if (stopReason === 'cancelled') { + markIndeterminate(); + return; + } + // A later steer makes agy answer this one's request at once, before + // agy folds it in, so an answer alone is not delivery: without an + // echo, it counts only once the turn ends cleanly. + if (this.turn === turn) turn.answeredSteers.push({ accept, hold: markIndeterminate }); + else accept(); + }, (error) => { + if (isAcpIndeterminateError(error)) { + if (this.turn === turn) this.backendLost = true; + markIndeterminate(); + return; + } + // An explicit JSON-RPC error: agy never took the message. + void restoreQueued(); + }); + return { steered: true }; + } + + private handleUserEcho(text: string): void { + const turn = this.turn; + if (!turn) return; + turn.acknowledge(); + // Text that does not continue the prompt (a stray echo, or agy + // skipping the prompt's echo) is checked against the steers, and the + // prompt's own echo is still recognized when it comes. + const prompt = turn.promptEcho; + if (!prompt.done) { + const echoed = normalizeEcho(`${prompt.echo} ${text}`); + if (echoed && prompt.text.startsWith(echoed)) { + prompt.echo = echoed; + prompt.done = echoed === prompt.text; + return; + } + } + // An echo may arrive in several chunks, so each steer matches on the + // text echoed since it was sent, and the longest match wins when one + // steer's text contains another's. One chunk may echo several steers, + // so a match only uses up its own text. + for (const entry of turn.unechoedSteers) { + entry.echo = normalizeEcho(`${entry.echo} ${text}`).slice(-ECHO_BUFFER_LIMIT); + } + for (;;) { + const match = turn.unechoedSteers + .filter((entry) => entry.text && entry.echo.includes(entry.text)) + .sort((a, b) => b.text.length - a.text.length)[0]; + if (!match) return; + for (const entry of turn.unechoedSteers) { + if (entry !== match) entry.echo = normalizeEcho(entry.echo.replace(match.text, ' ')); + } + match.accept(); + if (turn.unechoedSteers.includes(match)) return; + } + } + + private handleTurnUpdate(turn: AgyTurn, message: AgentMessage): void { + switch (message.type) { + case 'usage': + turn.usage = addAgyUsage(turn.usage, message); + return; + case 'turn_complete': + turn.stopReason = message.stopReason; + return; + default: + turn.sawActivity = true; + turn.acknowledge(); + this.trackToolWindow(turn, message); + this.forwardAgentMessage(message); + } + } + + private trackToolWindow(turn: AgyTurn, message: AgentMessage): void { + if (message.type !== 'tool_call' && message.type !== 'tool_result') return; + const now = Date.now(); + let window = turn.toolWindows.get(message.id); + if (!window) { + window = { start: now, end: null }; + turn.toolWindows.set(message.id, window); + turn.idleWindows.push(window); + } + if (message.status === 'completed' || message.status === 'failed') window.end ??= now; + } + + private forwardAgentMessage(message: AgentMessage): void { + const converted = convertAgentMessage(message, this.currentModelId); + if (converted) this.session.sendAgentMessage(converted); + + switch (message.type) { + case 'text': + if (message.live) break; + this.messageBuffer.addMessage(message.text, 'assistant'); + break; + case 'tool_call': + if (message.status === 'pending' || message.status === 'in_progress') { + this.messageBuffer.addMessage(`Tool: ${message.title ?? message.name}`, 'tool'); + } + break; + case 'error': + this.messageBuffer.addMessage(message.message, 'status'); + break; + case 'generated_image': + case 'usage': + case 'reasoning': + case 'tool_result': + case 'plan': + case 'turn_complete': + case 'round_summary': + break; + default: { + const _exhaustive: never = message; + return _exhaustive; + } + } + } + + private reportTurnError(message: string): void { + this.session.sendSessionEvent({ type: 'error', message }); + this.messageBuffer.addMessage(message, 'status'); + } + + private restorePrompt(turn: AgyTurn, text: string): void { + turn.acknowledge(); + this.session.sendSessionEvent({ type: 'abort-restore', text }); + } + + private async cancelActiveTurn(): Promise { + const turn = this.turn; + if (turn) { + turn.aborted = true; + this.session.client.updateAgentState((state) => ({ ...state, steeringActive: false })); + } + const backend = this.backend; + const acpSessionId = this.acpSessionId; + if (backend && acpSessionId && turn && backend.isTransportAlive()) { + // ACP cancel also ends open tool calls (the hard stop, unlike steer); + // their final updates still flow to this turn's handler. + await backend.cancelPrompt(acpSessionId); + // prompt() waits for the previous turn's output to settle before it + // sends; a cancel in that window reaches agy before the prompt. + if (!backend.isPromptRequestInFlight()) this.cancelOnceSent(backend, acpSessionId, turn); + if (turn.steers.length > 0) this.dropUnansweredSteers(backend, turn); + this.restartIfCancelIgnored(backend, turn); + } + await this.permissionHandler?.cancelAll('User aborted'); + } + + private cancelOnceSent(backend: AcpSdkBackend, acpSessionId: string, turn: AgyTurn): void { + const timer = setInterval(() => { + if (this.turn !== turn || this.backend !== backend) { + clearInterval(timer); + return; + } + if (backend.isPromptRequestInFlight()) { + clearInterval(timer); + void backend.cancelPrompt(acpSessionId); + } + }, PROMPT_SEND_POLL_MS); + timer.unref?.(); + } + + private restartIfCancelIgnored(backend: AcpSdkBackend, turn: AgyTurn): void { + // Measured on agy's answers: HAPI's own wait for late output after + // them must not count as agy ignoring the cancel. + let answered = false; + void Promise.allSettled([turn.mainAnswered, ...turn.steerAnswers]).then(() => { answered = true; }); + const timer = setTimeout(() => { + if (answered || this.turn !== turn || this.backend !== backend) return; + logger.warn('[agy-acp] agy did not stop the turn after cancel; restarting it'); + this.session.sendSessionEvent({ + type: 'message', + message: 'Antigravity did not stop; restarting it.' + }); + this.backendLost = true; + for (const abandon of turn.abandonSteers) abandon(); + turn.releaseSteerWait(); + void this.retireBackend(backend); + }, this.cancelHardStopMs); + timer.unref?.(); + } + + /** + * A steer agy never answers would block the turn and the next turn's + * config calls, so it is dropped after a grace period and agy is stopped, + * so the abandoned request can neither write into the next turn nor run + * on with approvals. Not done right away: the cancelled tool calls still + * report their end through this turn's handler. + */ + private dropUnansweredSteers(backend: AcpSdkBackend, turn: AgyTurn): void { + let answered = false; + void Promise.allSettled([...turn.steerAnswers]).then(() => { answered = true; }); + const timer = setTimeout(() => { + if (answered || this.turn !== turn || this.backend !== backend) return; + logger.warn('[agy-acp] agy did not answer a steer after cancel; dropping it'); + for (const abandon of turn.abandonSteers) abandon(); + this.backendLost = true; + turn.releaseSteerWait(); + void this.retireBackend(backend); + }, this.steerCancelGraceMs); + timer.unref?.(); + } + + private async handleAbort(): Promise { + const hadTurn = this.turn !== null; + await this.cancelActiveTurn(); + this.abortController.abort(); + this.abortController = new AbortController(); + if (hadTurn) { + this.session.sendSessionEvent({ type: 'message', message: 'Turn aborted' }); + this.messageBuffer.addMessage('Turn aborted', 'status'); + } + } + + private async handleExitFromUi(): Promise { + await this.requestExit('exit', () => this.handleAbort()); + } + + private async handleKill(): Promise { + const turnSettled = this.turnSettled; + await this.requestExit('exit', () => this.handleAbort()); + await this.backend?.disconnect(); + // The runner ends the session and closes the client as soon as kill + // returns, so the turn must put its prompt back or confirm it first; + // a stuck agy only delays that by the bound. + if (turnSettled) { + let timer: ReturnType | undefined; + await Promise.race([ + turnSettled, + new Promise((resolve) => { timer = setTimeout(resolve, this.killSettleMs); }) + ]); + clearTimeout(timer); + } + } + + protected async cleanup(): Promise { + this.clearAbortHandlers(this.session.client.rpcHandlerManager); + this.session.client.rpcHandlerManager.registerHandler(RPC_METHODS.SteerQueuedMessage, async () => ({ + steered: false, + error: 'Session ending' + })); + this.session.client.updateAgentState((state) => ({ ...state, steeringActive: false })); + await this.permissionHandler?.cancelAll('Session ended'); + this.permissionHandler = null; + const backend = this.backend; + this.backend = null; + await backend?.disconnect(); + logger.debug('[agy-acp] cleanup done'); + } +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** agy releases before 1.5.0 have no `acp` subcommand, so name the floor. */ +function describeAgyStartFailure(error: unknown): string { + return `Failed to start agy acp (requires Antigravity CLI 1.5.0 or newer): ${errorMessage(error)}`; +} + +export async function agyAcpRemoteLauncher(session: AgySession): Promise<'switch' | 'exit'> { + const launcher = new AgyAcpRemoteLauncher(session); + return launcher.launch(); +} diff --git a/cli/src/agy/agyRemoteLauncher.ts b/cli/src/agy/agyRemoteLauncher.ts new file mode 100644 index 00000000..bdd242f8 --- /dev/null +++ b/cli/src/agy/agyRemoteLauncher.ts @@ -0,0 +1,14 @@ +import type { AgySession } from './session'; +import { AgyAcpStartError, agyAcpRemoteLauncher } from './agyAcpRemoteLauncher'; +import { runStreamJsonAgyAfterAcpFailure, selectLegacyStreamJsonAgy } from './legacyStreamJson'; + +export async function agyRemoteLauncher(session: AgySession): Promise<'switch' | 'exit'> { + const legacy = await selectLegacyStreamJsonAgy(); + if (legacy) return legacy(session); + try { + return await agyAcpRemoteLauncher(session); + } catch (error) { + if (!(error instanceof AgyAcpStartError)) throw error; + return runStreamJsonAgyAfterAcpFailure(session, error); + } +} diff --git a/cli/src/agy/utils/agyConversationModel.test.ts b/cli/src/agy/legacyStreamJson/agyConversationModel.test.ts similarity index 100% rename from cli/src/agy/utils/agyConversationModel.test.ts rename to cli/src/agy/legacyStreamJson/agyConversationModel.test.ts diff --git a/cli/src/agy/utils/agyConversationModel.ts b/cli/src/agy/legacyStreamJson/agyConversationModel.ts similarity index 100% rename from cli/src/agy/utils/agyConversationModel.ts rename to cli/src/agy/legacyStreamJson/agyConversationModel.ts diff --git a/cli/src/agy/headless/agyHeadlessDriver.test.ts b/cli/src/agy/legacyStreamJson/agyHeadlessDriver.test.ts similarity index 97% rename from cli/src/agy/headless/agyHeadlessDriver.test.ts rename to cli/src/agy/legacyStreamJson/agyHeadlessDriver.test.ts index 6b860ed0..3dd49d5f 100644 --- a/cli/src/agy/headless/agyHeadlessDriver.test.ts +++ b/cli/src/agy/legacyStreamJson/agyHeadlessDriver.test.ts @@ -8,6 +8,12 @@ import { AgySession } from '../session'; import { MessageQueue2 } from '@/utils/MessageQueue2'; import type { AgyMode, PermissionMode } from '../types'; +// Record transcript entries on the fake client instead of building wire messages. +vi.mock('./agyTranscript', () => ({ + sendAgyTranscriptEntry: (client: { agyTranscript: (...args: unknown[]) => void }, ...args: unknown[]) => + client.agyTranscript(...args), +})); + // A fake agy binary: emits a fixed NDJSON stream for one turn, then exits 0. function fakeAgyProcess(lines: string[], exitCode = 0): ChildProcessWithoutNullStreams { const child = spawn(process.execPath, ['-e', ` @@ -67,10 +73,16 @@ function scriptableFakeChild(chunks: string[], exitCode = 0): ChildProcessWithou return Object.assign(child as ChildProcessWithoutNullStreams, { run, feedStdout }); } +function cancelQueued(client: { onCancelQueuedMessage: ReturnType }, localId: string): unknown { + const handler = client.onCancelQueuedMessage.mock.calls.at(-1)?.[0] as ((id: string) => unknown) | undefined; + return handler?.(localId); +} + function createSession(clientOverrides: Record = {}) { const sent: unknown[] = []; const client = { - sendAgySessionMessage: (...args: unknown[]) => { sent.push(args); }, + agyTranscript: (...args: unknown[]) => { sent.push(args); }, + onCancelQueuedMessage: vi.fn(), emitMessagesConsumed: vi.fn(), emitSessionReady: vi.fn(), sendSessionEvent: vi.fn(), @@ -349,6 +361,33 @@ describe('AgyHeadlessDriver', () => { expect(spawnedArgs[0]).not.toContain('--dangerously-skip-permissions'); }); + it.each([ + ['acceptEdits', 'accept-edits'], + ['plan', 'plan'], + ] as const)('starts agy with --mode for the %s permission mode', async (permissionMode, agyMode) => { + const { session, queue } = createSession(); + const spawnedArgs: string[][] = []; + const driver = new AgyHeadlessDriver({ + session, + spawnAgy: (args) => { + spawnedArgs.push(args); + return fakeAgyProcess(FULL_TURN); + }, + }); + + queue.push('hello', { permissionMode }, 'local-1'); + const launchPromise = driver.launch(); + await new Promise((r) => setTimeout(r, 500)); + queue.close(); + session.stopKeepAlive(); + await launchPromise; + + expect(spawnedArgs.length).toBe(1); + const at = spawnedArgs[0]!.indexOf('--mode'); + expect(spawnedArgs[0]![at + 1]).toBe(agyMode); + expect(spawnedArgs[0]).not.toContain('--dangerously-skip-permissions'); + }); + it('acks the delivery when the turn completes even without a user_input step', async () => { const { session, queue, client } = createSession(); // No user_input step in the stream — but the result envelope proves the @@ -1126,7 +1165,7 @@ describe('AgyHeadlessDriver', () => { // retry backoff: the queue has nothing (batch is outside it), but the // driver-owned retry state must remove it so the retry never spawns. const removed = session.queue.cancelByLocalId('local-1'); - const retryRemoved = session.cancelRetryDelivery?.( 'local-1') ?? false; + const retryRemoved = cancelQueued(client, 'local-1'); await new Promise((r) => setTimeout(r, 2000)); queue.close(); session.stopKeepAlive(); @@ -1179,7 +1218,7 @@ describe('AgyHeadlessDriver', () => { await new Promise((r) => setTimeout(r, 400)); // Cancel the only retry item: the session must stay alive (not break) and // accept a later prompt. - session.cancelRetryDelivery?.('local-1'); + cancelQueued(client, 'local-1'); await new Promise((r) => setTimeout(r, 2000)); // A newer message queued after the cancel must still be processed. queue.push('second', { permissionMode: 'request-review' }, 'local-2'); diff --git a/cli/src/agy/headless/agyHeadlessDriver.ts b/cli/src/agy/legacyStreamJson/agyHeadlessDriver.ts similarity index 97% rename from cli/src/agy/headless/agyHeadlessDriver.ts rename to cli/src/agy/legacyStreamJson/agyHeadlessDriver.ts index aa4510af..3520f3e3 100644 --- a/cli/src/agy/headless/agyHeadlessDriver.ts +++ b/cli/src/agy/legacyStreamJson/agyHeadlessDriver.ts @@ -5,16 +5,17 @@ import { RemoteModeDisplay } from '@/ui/ink/RemoteModeDisplay'; import { AgyPlannerAccumulator, parseAgyNdjsonLine } from './agyNdjsonParser'; import type { AgySession } from '../session'; import type { AgyMode, PermissionMode } from '../types'; -import type { AgyTranscriptEntry, AgyToolCall } from '../utils/agyTranscriptTypes'; +import type { AgyTranscriptEntry, AgyToolCall } from './agyTranscriptTypes'; import { RemoteLauncherBase, type RemoteLauncherDisplayContext, type RemoteLauncherExitReason, } from '@/modules/common/remote/RemoteLauncherBase'; import { createNativeSessionTitleMetadataSync } from '@/agent/nativeSessionTitle'; -import { readAgyConversationTitle } from '../utils/agySessionTitle'; -import { resolveAgyTurnModels } from '../utils/agyConversationModel'; +import { readAgyConversationTitle } from './agySessionTitle'; +import { resolveAgyTurnModels } from './agyConversationModel'; import { AgyStreamProcess } from './agyStreamProcess'; +import { sendAgyTranscriptEntry } from './agyTranscript'; import { AGY_EFFORT_LEVELS, AGY_MODEL_LABELS, splitAgyModelSelection, type AgyEffortLevel } from '@hapi/protocol'; import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'; @@ -110,7 +111,10 @@ export class AgyHeadlessDriver extends RemoteLauncherBase { this.syncNativeTitle = createNativeSessionTitleMetadataSync(this.session.client); this.conversationId = this.session.sessionId; this.session.setKillHandler(() => this.abort()); - this.session.cancelRetryDelivery = this.cancelRetryItem; + // A batch held in the retry backoff is outside MessageQueue2, so a + // Cancel checks it before the queue (true when removed there). + this.session.client.onCancelQueuedMessage((localId) => + this.cancelRetryItem(localId) || this.session.queue.cancelByLocalId(localId)); } protected createDisplay(context: RemoteLauncherDisplayContext): React.ReactElement { @@ -376,6 +380,9 @@ export class AgyHeadlessDriver extends RemoteLauncherBase { args = buildAgyHeadlessArgs({ model: sessionModel, permissionMode: mode.permissionMode, + // A change restarts the process, like other launch settings. + mode: mode.permissionMode === 'acceptEdits' ? 'accept-edits' + : mode.permissionMode === 'plan' ? 'plan' : undefined, effort: (AGY_EFFORT_LEVELS as readonly unknown[]).includes(sessionEffort) ? sessionEffort as AgyEffortLevel : undefined, }); @@ -470,14 +477,15 @@ export class AgyHeadlessDriver extends RemoteLauncherBase { // the web's per-turn attribution survives model switches and // default-model turns still show the actual generation model. const model = await resolveModel(entry); - await this.session.client.sendAgySessionMessage( + sendAgyTranscriptEntry( + this.session.client, model ? { ...entry, model } : entry, this.conversationId ?? undefined, ); }); }; const sendTool = (entry: AgyTranscriptEntry, toolCall: AgyToolCall) => { - enqueueTranscript(() => this.session.client.sendAgySessionMessage(entry, this.conversationId ?? undefined, toolCall)); + enqueueTranscript(() => sendAgyTranscriptEntry(this.session.client, entry, this.conversationId ?? undefined, toolCall)); }; const flushPlanner = async () => { for (const entry of planner.flushAll()) { diff --git a/cli/src/agy/utils/agyMessageText.ts b/cli/src/agy/legacyStreamJson/agyMessageText.ts similarity index 100% rename from cli/src/agy/utils/agyMessageText.ts rename to cli/src/agy/legacyStreamJson/agyMessageText.ts diff --git a/cli/src/agy/headless/agyNdjsonParser.test.ts b/cli/src/agy/legacyStreamJson/agyNdjsonParser.test.ts similarity index 100% rename from cli/src/agy/headless/agyNdjsonParser.test.ts rename to cli/src/agy/legacyStreamJson/agyNdjsonParser.test.ts diff --git a/cli/src/agy/headless/agyNdjsonParser.ts b/cli/src/agy/legacyStreamJson/agyNdjsonParser.ts similarity index 98% rename from cli/src/agy/headless/agyNdjsonParser.ts rename to cli/src/agy/legacyStreamJson/agyNdjsonParser.ts index 634e8839..3663d89a 100644 --- a/cli/src/agy/headless/agyNdjsonParser.ts +++ b/cli/src/agy/legacyStreamJson/agyNdjsonParser.ts @@ -1,4 +1,4 @@ -import type { AgyTranscriptEntry, AgyToolCall } from '../utils/agyTranscriptTypes'; +import type { AgyTranscriptEntry, AgyToolCall } from './agyTranscriptTypes'; /** * agy `--output-format stream-json` NDJSON protocol (measured on agy 1.1.13). @@ -14,7 +14,7 @@ import type { AgyTranscriptEntry, AgyToolCall } from '../utils/agyTranscriptType * {"event":"result","result":{"conversation_id":"...","status":"SUCCESS","response":"OK\n","duration_seconds":3.4,"num_turns":1,"usage":{...}}} * {"event":"result","result":{"conversation_id":"...","status":"ERROR","response":"","error":"timeout waiting for response","duration_seconds":2.4,"num_turns":1,"usage":{...}}} * - * Mapping to the existing transcript-entry channel (sendAgySessionMessage): + * Mapping to the existing transcript-entry channel (sendAgyTranscriptEntry): * - init → conversation id becomes known immediately (no hook needed) * - user_input → delivery confirmation (emitMessagesConsumed); no re-emit, * the web already rendered the user's own message diff --git a/cli/src/agy/headless/agyPersistentDriver.test.ts b/cli/src/agy/legacyStreamJson/agyPersistentDriver.test.ts similarity index 97% rename from cli/src/agy/headless/agyPersistentDriver.test.ts rename to cli/src/agy/legacyStreamJson/agyPersistentDriver.test.ts index 65fd5ee2..e399b922 100644 --- a/cli/src/agy/headless/agyPersistentDriver.test.ts +++ b/cli/src/agy/legacyStreamJson/agyPersistentDriver.test.ts @@ -6,14 +6,20 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process'; import { AgyHeadlessDriver } from './agyHeadlessDriver'; import { AgySession } from '../session'; import type { AgyMode } from '../types'; + +// Record transcript entries on the fake client instead of building wire messages. +vi.mock('./agyTranscript', () => ({ + sendAgyTranscriptEntry: (client: { agyTranscript: (...args: unknown[]) => void }, ...args: unknown[]) => + client.agyTranscript(...args), +})); import { MessageQueue2 } from '@/utils/MessageQueue2'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; const modelLookup = vi.hoisted(() => vi.fn(async (_id: unknown, indexes: readonly number[]) => ( new Map(indexes.map((index) => [index, null])) ))); -vi.mock('../utils/agyConversationModel', () => ({ resolveAgyTurnModels: modelLookup })); -vi.mock('../utils/agySessionTitle', () => ({ readAgyConversationTitle: async () => null })); +vi.mock('./agyConversationModel', () => ({ resolveAgyTurnModels: modelLookup })); +vi.mock('./agySessionTitle', () => ({ readAgyConversationTitle: async () => null })); const CONVERSATION = '12345678-1234-4234-8234-123456789abc'; const MODE: AgyMode = { permissionMode: 'request-review', model: 'gemini-4-argon', effort: 'medium' }; @@ -88,7 +94,8 @@ class PersistentChild extends EventEmitter { function createHarness(configureChild?: (child: PersistentChild, index: number) => void) { const sent: unknown[][] = []; const client = { - sendAgySessionMessage: (...args: unknown[]) => { sent.push(args); }, + agyTranscript: (...args: unknown[]) => { sent.push(args); }, + onCancelQueuedMessage: vi.fn(), emitMessagesConsumed: vi.fn(), emitSessionReady: vi.fn(), sendSessionEvent: vi.fn(), diff --git a/cli/src/agy/utils/agySessionTitle.test.ts b/cli/src/agy/legacyStreamJson/agySessionTitle.test.ts similarity index 100% rename from cli/src/agy/utils/agySessionTitle.test.ts rename to cli/src/agy/legacyStreamJson/agySessionTitle.test.ts diff --git a/cli/src/agy/utils/agySessionTitle.ts b/cli/src/agy/legacyStreamJson/agySessionTitle.ts similarity index 100% rename from cli/src/agy/utils/agySessionTitle.ts rename to cli/src/agy/legacyStreamJson/agySessionTitle.ts diff --git a/cli/src/agy/headless/agyStreamProcess.ts b/cli/src/agy/legacyStreamJson/agyStreamProcess.ts similarity index 100% rename from cli/src/agy/headless/agyStreamProcess.ts rename to cli/src/agy/legacyStreamJson/agyStreamProcess.ts diff --git a/cli/src/agy/legacyStreamJson/agyTranscript.test.ts b/cli/src/agy/legacyStreamJson/agyTranscript.test.ts new file mode 100644 index 00000000..dcb6eeaa --- /dev/null +++ b/cli/src/agy/legacyStreamJson/agyTranscript.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from 'vitest' +import { sendAgyTranscriptEntry } from './agyTranscript' + +function fakeClient() { + return { sendClaudeSessionMessage: vi.fn(), sendUserMessage: vi.fn() } +} + +describe('sendAgyTranscriptEntry', () => { + it('renders only the USER_REQUEST body, not the sections agy appends', () => { + const client = fakeClient() + + // The shape agy actually writes for every terminal-typed message. + sendAgyTranscriptEntry(client as never, { + type: 'USER_INPUT', + content: [ + '', + 'hi', + '', + '', + 'The current local time is: 2026-08-04T09:00:00+09:00.', + '', + '', + 'The user changed setting `Model Selection` from None to Gemini 3.6 Flash (Low).', + '', + ].join('\n'), + }) + + expect(client.sendUserMessage).toHaveBeenCalledWith('hi') + expect(client.sendClaudeSessionMessage).not.toHaveBeenCalled() + }) + + it('sends planner prose as agy_message with the turn model', () => { + const client = fakeClient() + + sendAgyTranscriptEntry(client as never, { type: 'PLANNER_RESPONSE', content: 'OK', model: 'Gemini 3.7 Flash (Low)' }) + + expect(client.sendClaudeSessionMessage).toHaveBeenCalledWith({ + type: 'agy_message', + content: 'OK', + model: 'Gemini 3.7 Flash (Low)' + }) + }) + + it('sends tool actions as agy_tool_action keyed by conversation and step', () => { + const client = fakeClient() + + sendAgyTranscriptEntry( + client as never, + { type: 'RUN_COMMAND', content: 'hi\n', step_index: 3 }, + 'conv-1', + { name: 'run_command', args: { CommandLine: 'echo hi' } } + ) + + expect(client.sendClaudeSessionMessage).toHaveBeenCalledWith({ + type: 'agy_tool_action', + name: 'RUN_COMMAND', + content: 'hi\n', + toolUseId: 'conv-1:3', + toolName: 'run_command', + input: { CommandLine: 'echo hi' } + }) + }) +}) diff --git a/cli/src/agy/legacyStreamJson/agyTranscript.ts b/cli/src/agy/legacyStreamJson/agyTranscript.ts new file mode 100644 index 00000000..d20958a4 --- /dev/null +++ b/cli/src/agy/legacyStreamJson/agyTranscript.ts @@ -0,0 +1,67 @@ +import type { ApiSessionClient } from '@/api/apiSession'; +import type { RawJSONLines } from '@/claude/types'; +import { extractUserRequest } from './agyMessageText'; + +type AgyTranscriptClient = Pick; + +/** + * Sends one stream-json transcript entry to the hub as the agy-specific chat + * messages (`agy_message` prose, `agy_tool_action` tool cards). + */ +export function sendAgyTranscriptEntry( + client: AgyTranscriptClient, + entry: { type: string; content?: string; tool_calls?: { name: string; args: Record }[]; step_index?: number; model?: string }, + conversationId?: string, + // The tool CALL (name + args) that produced this action entry, paired by + // the driver from the preceding PLANNER_RESPONSE. agy splits the + // invocation (name/args live on the planner step) from its result (the + // action entry's `content`), so without this the tool card has no input + // to show — just the raw result. Carrying it here lets the web render a + // command/path/args like the other flavors. + toolCall?: { name: string; args: Record } +): void { + const isUser = entry.type === 'USER_INPUT' + // agy appends its own sections (, ) + // after the request block, so only the extracted request may be rendered. + const text = isUser ? (extractUserRequest(entry.content ?? '') ?? entry.content ?? '').trim() : undefined + + if (isUser && text) { + client.sendUserMessage(text) + return + } + + // agy's structured entry types map to distinct chat renderings: + // - PLANNER_RESPONSE → the agent's prose (agy_message). Its `tool_calls` + // are only the model's INTENT and are immediately followed by the real + // action entry below, so we intentionally don't render them separately + // (that produced a duplicate "view_file" + "View file" card). + // - every other type (VIEW_FILE, RUN_COMMAND, LIST_DIRECTORY, CODE_ACTION, + // …) is a tool ACTION whose `content` is its result. Render it as a + // collapsible tool card (agy_tool_action) instead of dumping the raw + // (often huge) result text as a chat bubble. + let data: Record + if (entry.type !== 'PLANNER_RESPONSE') { + // Key the tool card by conversationId:stepIdx so a gated tool's + // approval card and its result merge into one card. + const toolUseId = conversationId != null && entry.step_index != null + ? `${conversationId}:${entry.step_index}` + : undefined + data = { + type: 'agy_tool_action', + name: entry.type, + content: entry.content ?? '', + toolUseId, + // The invocation the web renders as the tool INPUT. `toolName` is + // agy's own tool id (run_command, view_file, …) which the web maps + // to a canonical presentation; `input` is the raw args. + toolName: toolCall?.name, + input: toolCall?.args + } + } else { + // Tag the agent response with the model that produced it (per-turn). + data = { type: 'agy_message', content: entry.content ?? '', model: entry.model } + } + // Sent as `{ role: 'agent', content: { type: 'output', data } }`, the + // envelope the web's agy normalizer reads. + client.sendClaudeSessionMessage(data as unknown as RawJSONLines) +} diff --git a/cli/src/agy/utils/agyTranscriptTypes.ts b/cli/src/agy/legacyStreamJson/agyTranscriptTypes.ts similarity index 100% rename from cli/src/agy/utils/agyTranscriptTypes.ts rename to cli/src/agy/legacyStreamJson/agyTranscriptTypes.ts diff --git a/cli/src/agy/legacyStreamJson/agyVersion.ts b/cli/src/agy/legacyStreamJson/agyVersion.ts new file mode 100644 index 00000000..16456892 --- /dev/null +++ b/cli/src/agy/legacyStreamJson/agyVersion.ts @@ -0,0 +1,90 @@ +import { spawn } from 'node:child_process'; +import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'; + +export const AGY_ACP_MIN_VERSION: readonly [number, number, number] = [1, 5, 0]; + +const VERSION_PROBE_TIMEOUT_MS = 10_000; +// A background child can hold stdout open after agy exits. +const STDOUT_GRACE_AFTER_EXIT_MS = 500; + +export type AgyVersionProbe = () => Promise; + +export function probeAgyVersion( + command: string = getAgentLaunchCommand('agy'), + timeoutMs: number = VERSION_PROBE_TIMEOUT_MS +): Promise { + return new Promise((resolve, reject) => { + const child = spawn(command, ['--version'], { + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: process.platform === 'win32', + }); + let output = ''; + let settled = false; + let graceTimer: ReturnType | null = null; + const settle = (fn: () => void) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (graceTimer) clearTimeout(graceTimer); + fn(); + }; + const timer = setTimeout(() => settle(() => { + child.kill('SIGTERM'); + reject(new Error(`agy --version did not answer within ${timeoutMs} ms`)); + }), timeoutMs); + // Only stdout carries the version; stderr may hold notices with other + // version numbers. + child.stdout?.on('data', (chunk: Buffer) => { output += chunk.toString(); }); + child.on('error', (error) => settle(() => reject(error))); + const finish = (code: number | null) => settle(() => { + if (code === 0) resolve(output); + else reject(new Error(`agy --version exited with code ${code}`)); + }); + child.on('close', finish); + child.on('exit', (code) => { + graceTimer = setTimeout(() => finish(code), STDOUT_GRACE_AFTER_EXIT_MS); + }); + }); +} + +type AgyVersion = { core: [number, number, number]; prerelease: boolean }; + +export function parseAgyVersion(output: string): AgyVersion | null { + const match = /(? probeAgyVersion()): Promise<{ streamJson: boolean; reason: string }> { + let output: string; + try { + output = await probe(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { streamJson: true, reason: `could not read the agy version (${message})` }; + } + const version = parseAgyVersion(output); + if (!version) { + return { streamJson: true, reason: `could not read the agy version from "${output.trim().slice(0, 80)}"` }; + } + const label = output.trim().split(/\s+/).find((word) => /\d+\.\d+/.test(word)) ?? version.core.join('.'); + if (isBefore(version, AGY_ACP_MIN_VERSION)) { + return { streamJson: true, reason: `agy ${label} predates agy acp (${AGY_ACP_MIN_VERSION.join('.')})` }; + } + return { streamJson: false, reason: `agy ${label} supports agy acp` }; +} diff --git a/cli/src/agy/legacyStreamJson/index.ts b/cli/src/agy/legacyStreamJson/index.ts new file mode 100644 index 00000000..e60d883b --- /dev/null +++ b/cli/src/agy/legacyStreamJson/index.ts @@ -0,0 +1,44 @@ +/** + * Stream-json transport, for agy releases without `agy acp` (< 1.5.0), an agy + * whose version cannot be read, and an `agy acp` that fails to start. + * + * Removal: when agy < 1.5.0 is no longer supported, delete this directory and + * its branches in ../agyRemoteLauncher.ts. Nothing else imports from here. + * Rendering of stored agy transcripts in the web and native apps does not + * depend on this directory. + */ +import { logger } from '@/ui/logger'; +import type { AgySession } from '../session'; +import { agyHeadlessDriver } from './agyHeadlessDriver'; +import { needsStreamJson, type AgyVersionProbe } from './agyVersion'; + +type AgyRemoteLaunch = (session: AgySession) => Promise<'switch' | 'exit'>; + +async function runStreamJsonAgy(session: AgySession, reason: string): Promise<'switch' | 'exit'> { + logger.warn(`[agy] using the stream-json transport: ${reason}`); + session.sendSessionEvent({ + type: 'message', + message: `Antigravity runs without agy acp (${reason}); Steer is not available.` + }); + // A session that ran on `agy acp` before must not keep the marker that + // enables steering. + session.client.updateMetadata((metadata) => { + if (metadata.agyProtocol === undefined) return metadata; + const { agyProtocol: _acp, ...rest } = metadata; + return rest; + }); + return agyHeadlessDriver(session); +} + +export async function selectLegacyStreamJsonAgy(probe?: AgyVersionProbe): Promise { + const choice = await needsStreamJson(probe); + if (!choice.streamJson) { + logger.debug(`[agy] using agy acp: ${choice.reason}`); + return null; + } + return (session) => runStreamJsonAgy(session, choice.reason); +} + +export async function runStreamJsonAgyAfterAcpFailure(session: AgySession, error: Error): Promise<'switch' | 'exit'> { + return runStreamJsonAgy(session, `agy acp failed to start: ${error.message}`); +} diff --git a/cli/src/agy/legacyStreamJson/transportSelection.test.ts b/cli/src/agy/legacyStreamJson/transportSelection.test.ts new file mode 100644 index 00000000..90bf012a --- /dev/null +++ b/cli/src/agy/legacyStreamJson/transportSelection.test.ts @@ -0,0 +1,214 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { needsStreamJson, parseAgyVersion, probeAgyVersion } from './agyVersion' + +const harness = vi.hoisted(() => ({ + agyCommand: 'agy', + acpLaunches: 0, + acpError: null as Error | null, + streamJsonLaunches: 0, + warn: vi.fn(), +})) + +vi.mock('@/agent/agentLaunchCommand', () => ({ getAgentLaunchCommand: () => harness.agyCommand })) +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), warn: harness.warn } })) +vi.mock('../agyAcpRemoteLauncher', () => { + class AgyAcpStartError extends Error {} + return { + AgyAcpStartError, + agyAcpRemoteLauncher: async () => { + harness.acpLaunches += 1 + if (harness.acpError) throw harness.acpError + return 'exit' + }, + } +}) +vi.mock('./agyHeadlessDriver', () => ({ + agyHeadlessDriver: async () => { harness.streamJsonLaunches += 1; return 'exit' }, +})) + +import { agyRemoteLauncher } from '../agyRemoteLauncher' +import { AgyAcpStartError } from '../agyAcpRemoteLauncher' + +describe('needsStreamJson', () => { + it.each([ + ['1.4.12\n', true], + ['1.5.0\n', false], + ['1.5.2\n', false], + ['agy version 2.0.0\n', false], + ['1.5.0-rc.1\n', true], + ['1.5.1-beta\n', false], + ['2.0\n', false], + ['1.4\n', true], + ['v1.4.12\n', true], + ['agy v1.5.2\n', false], + ])('reads %j', async (output, streamJson) => { + const choice = await needsStreamJson(async () => output) + expect(choice.streamJson).toBe(streamJson) + }) + + it('falls back to stream-json when the version cannot be read', async () => { + expect(await needsStreamJson(async () => { throw new Error('spawn agy ENOENT') })).toEqual({ + streamJson: true, + reason: 'could not read the agy version (spawn agy ENOENT)' + }) + expect(await needsStreamJson(async () => 'dev build')).toEqual({ + streamJson: true, + reason: 'could not read the agy version from "dev build"' + }) + }) + + it('parses dotted versions with optional patch and pre-release', () => { + expect(parseAgyVersion('1.5.2')).toEqual({ core: [1, 5, 2], prerelease: false }) + expect(parseAgyVersion('2.0')).toEqual({ core: [2, 0, 0], prerelease: false }) + expect(parseAgyVersion('1.5.0-rc.1')).toEqual({ core: [1, 5, 0], prerelease: true }) + expect(parseAgyVersion('v1.4.12')).toEqual({ core: [1, 4, 12], prerelease: false }) + expect(parseAgyVersion('none')).toBeNull() + }) +}) + +describe('agyRemoteLauncher transport selection', () => { + let dir: string + + function fakeAgy(script: string): void { + const path = join(dir, 'agy') + writeFileSync(path, `#!/bin/sh\n${script}\n`) + chmodSync(path, 0o755) + harness.agyCommand = path + } + + function fakeSession(metadata: Record = { agyProtocol: 'acp' }) { + const state = { metadata, events: [] as unknown[] } + return { + state, + session: { + sendSessionEvent: (event: unknown) => { state.events.push(event) }, + client: { + updateMetadata: (update: (current: Record) => Record) => { + state.metadata = update(state.metadata) + } + } + } + } + } + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'agy-version-')) + harness.acpLaunches = 0 + harness.acpError = null + harness.streamJsonLaunches = 0 + harness.warn.mockClear() + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + it('runs agy 1.5.0 and newer on agy acp', async () => { + fakeAgy('echo 1.5.2') + const { session, state } = fakeSession() + + await agyRemoteLauncher(session as never) + + expect(harness.acpLaunches).toBe(1) + expect(harness.streamJsonLaunches).toBe(0) + expect(state.metadata).toEqual({ agyProtocol: 'acp' }) + }) + + it('runs older agy on stream-json and drops a stale ACP marker', async () => { + fakeAgy('echo 1.4.12') + const { session, state } = fakeSession({ agySessionId: 'conv-1', agyProtocol: 'acp' }) + + await agyRemoteLauncher(session as never) + + expect(harness.streamJsonLaunches).toBe(1) + expect(harness.acpLaunches).toBe(0) + expect(state.metadata).toEqual({ agySessionId: 'conv-1' }) + expect(harness.warn).toHaveBeenCalledWith( + '[agy] using the stream-json transport: agy 1.4.12 predates agy acp (1.5.0)' + ) + expect(state.events).toEqual([{ + type: 'message', + message: 'Antigravity runs without agy acp (agy 1.4.12 predates agy acp (1.5.0)); Steer is not available.' + }]) + }) + + it('falls back to stream-json when agy acp fails to start', async () => { + fakeAgy('echo 1.5.2') + harness.acpError = new AgyAcpStartError('Failed to start agy acp (requires Antigravity CLI 1.5.0 or newer): boom') + const { session, state } = fakeSession({}) + + await agyRemoteLauncher(session as never) + + expect(harness.acpLaunches).toBe(1) + expect(harness.streamJsonLaunches).toBe(1) + expect(state.events).toEqual([{ + type: 'message', + message: 'Antigravity runs without agy acp (agy acp failed to start: Failed to start agy acp (requires Antigravity CLI 1.5.0 or newer): boom); Steer is not available.' + }]) + }) + + it('does not fall back for errors after agy acp started', async () => { + fakeAgy('echo 1.5.2') + harness.acpError = new Error('connection lost') + const { session } = fakeSession({}) + + await expect(agyRemoteLauncher(session as never)).rejects.toThrow('connection lost') + expect(harness.streamJsonLaunches).toBe(0) + }) + + it('reads the version from stdout, not from notices on stderr', async () => { + fakeAgy('echo "update 1.5.3 available" >&2; echo 1.4.12') + const { session } = fakeSession({}) + + await agyRemoteLauncher(session as never) + + expect(harness.streamJsonLaunches).toBe(1) + expect(harness.acpLaunches).toBe(0) + }) + + it('falls back to stream-json and says why when the version check fails', async () => { + fakeAgy('echo "not signed in" >&2; exit 3') + const { session } = fakeSession({}) + + await agyRemoteLauncher(session as never) + + expect(harness.streamJsonLaunches).toBe(1) + expect(harness.acpLaunches).toBe(0) + expect(harness.warn).toHaveBeenCalledWith( + '[agy] using the stream-json transport: could not read the agy version (agy --version exited with code 3)' + ) + }) +}) + +describe('probeAgyVersion', () => { + let dir: string + beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'agy-probe-')) }) + afterEach(() => { rmSync(dir, { recursive: true, force: true }) }) + + function script(body: string): string { + const path = join(dir, 'agy') + writeFileSync(path, `#!/bin/sh\n${body}\n`) + chmodSync(path, 0o755) + return path + } + + it('reports a missing agy binary', async () => { + await expect(probeAgyVersion(join(dir, 'missing-agy'))).rejects.toMatchObject({ code: 'ENOENT' }) + expect(await needsStreamJson(() => probeAgyVersion(join(dir, 'missing-agy')))).toMatchObject({ streamJson: true }) + }) + + it('gives up on an agy that never answers', async () => { + const choice = await needsStreamJson(() => probeAgyVersion(script('sleep 5'), 200)) + expect(choice).toEqual({ streamJson: true, reason: 'could not read the agy version (agy --version did not answer within 200 ms)' }) + }) + + it('does not wait for a background child that keeps stdout open', async () => { + const started = Date.now() + const output = await probeAgyVersion(script('(sleep 3 &); echo 1.5.2'), 5000) + expect(output.trim()).toBe('1.5.2') + expect(Date.now() - started).toBeLessThan(2500) + }) +}) diff --git a/cli/src/agy/loop.ts b/cli/src/agy/loop.ts index 58ba0642..ccbbb938 100644 --- a/cli/src/agy/loop.ts +++ b/cli/src/agy/loop.ts @@ -2,7 +2,7 @@ import { MessageQueue2 } from '@/utils/MessageQueue2'; import { logger } from '@/ui/logger'; import { runLocalRemoteSession } from '@/agent/loopBase'; import { AgySession } from './session'; -import { agyHeadlessDriver } from './headless/agyHeadlessDriver'; +import { agyRemoteLauncher } from './agyRemoteLauncher'; import { ApiClient, ApiSessionClient } from '@/lib'; import type { AgyMode, PermissionMode } from './types'; import type { SessionEffort, SessionModel } from '@/api/types'; @@ -58,7 +58,7 @@ export async function agyLoop(opts: AgyLoopOptions): Promise { logger.debug('[agy-loop] Local mode not supported; switching to remote'); return 'switch'; }, - runRemote: agyHeadlessDriver, + runRemote: agyRemoteLauncher, onSessionReady: opts.onSessionReady }); } diff --git a/cli/src/agy/runAgy.test.ts b/cli/src/agy/runAgy.test.ts index 504293a4..1dfe5429 100644 --- a/cli/src/agy/runAgy.test.ts +++ b/cli/src/agy/runAgy.test.ts @@ -65,6 +65,7 @@ describe('runAgy model and effort config', () => { session: { onUserMessage: mocks.onUserMessage, onCancelQueuedMessage: vi.fn(), + onRetryQueuedMessage: vi.fn(), rpcHandlerManager: { registerHandler: mocks.registerHandler }, }, } @@ -127,6 +128,17 @@ describe('runAgy model and effort config', () => { expect(mocks.loop).toHaveBeenCalledWith(expect.objectContaining({ model: undefined, effort: 'high' })) }) + it('queues the first message with the permission mode the session was spawned with', async () => { + mocks.loop.mockImplementation(async ({ messageQueue }: { messageQueue: MessageQueue2 }) => { + const send = mocks.onUserMessage.mock.calls[0]![0] + send({ content: { text: 'plan this' } }, 'first') + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ permissionMode: 'plan' }) + }) + await runAgy({ permissionMode: 'plan', workingDirectory: '/tmp' }) + expect(mocks.loop).toHaveBeenCalledWith(expect.objectContaining({ permissionMode: 'plan' })) + }) + it('cleans up a bootstrapped session if catalog initialization rejects', async () => { mocks.listModels.mockRejectedValueOnce(new Error('catalog unavailable')) await runAgy({ model: 'gemini-4-argon-medium', workingDirectory: '/tmp' }) diff --git a/cli/src/agy/runAgy.ts b/cli/src/agy/runAgy.ts index 35c4f8e1..a81af553 100644 --- a/cli/src/agy/runAgy.ts +++ b/cli/src/agy/runAgy.ts @@ -114,17 +114,11 @@ export async function runAgy(opts: { }; session.onCancelQueuedMessage((localId) => { - // A batch held in the driver's retry backoff is outside MessageQueue2; - // the driver-owned cancel handles it (returns true when removed). - const retryRemoved = sessionWrapperRef.current?.cancelRetryDelivery?.(localId) ?? false; - if (retryRemoved) { - logger.debug(`[agy] cancelByLocalId(${localId}): removed from retry backoff`); - return true; - } const removed = messageQueue.cancelByLocalId(localId); logger.debug(`[agy] cancelByLocalId(${localId}): ${removed ? 'removed' : 'not found'}`); return removed; }); + session.onRetryQueuedMessage((localId) => messageQueue.releaseIndeterminateReservation(localId)); registerSessionConfigRpc({ rpcHandlerManager: session.rpcHandlerManager, diff --git a/cli/src/agy/session.ts b/cli/src/agy/session.ts index 26218097..8064ba70 100644 --- a/cli/src/agy/session.ts +++ b/cli/src/agy/session.ts @@ -11,16 +11,12 @@ type LocalLaunchFailure = { }; /** - * Headless agy session using a persistent stream-json stdin/stdout process. - * The driver reuses matching launch settings and resumes the conversation - * when the process restarts, mapping NDJSON onto the transcript-entry channel - * (sendAgySessionMessage), so hub/web rendering is unchanged. + * The remote launchers acknowledge a queued message once agy accepts it, so + * the queue does not acknowledge on dequeue. */ export class AgySession extends AgentSessionBase { readonly startedBy: 'runner' | 'terminal'; localLaunchFailure: LocalLaunchFailure | null = null; - /** Set by the headless driver; lets the CLI cancel a batch held in retry backoff. */ - cancelRetryDelivery: ((localId: string) => boolean) | null = null; constructor(opts: { api: ApiClient; diff --git a/cli/src/agy/utils/agyAcpBackend.ts b/cli/src/agy/utils/agyAcpBackend.ts new file mode 100644 index 00000000..07bcf7c3 --- /dev/null +++ b/cli/src/agy/utils/agyAcpBackend.ts @@ -0,0 +1,28 @@ +import { AcpSdkBackend } from '@/agent/backends/acp'; +import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'; + +/** + * GEMINI_FORCE_FILE_STORAGE reads the saved OAuth token instead of a flaky + * keyring. SSH session markers would switch agy to a degraded auth path, but + * the agent socket stays for tool subprocesses. + */ +export function buildAgyAcpEnv(source: NodeJS.ProcessEnv = process.env): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(source)) { + if (value !== undefined) env[key] = value; + } + env.GEMINI_FORCE_FILE_STORAGE = 'true'; + for (const key of ['SSH_CLIENT', 'SSH_CONNECTION', 'SSH_TTY']) { + delete env[key]; + } + return env; +} + +export function createAgyAcpBackend(): AcpSdkBackend { + return new AcpSdkBackend({ + command: getAgentLaunchCommand('agy'), + args: ['acp'], + env: buildAgyAcpEnv(), + flavor: 'agy' + }); +} diff --git a/cli/src/api/apiSession.test.ts b/cli/src/api/apiSession.test.ts index e99b9970..a2e8b2a1 100644 --- a/cli/src/api/apiSession.test.ts +++ b/cli/src/api/apiSession.test.ts @@ -666,40 +666,6 @@ describe('ApiSessionClient lazy materialization', () => { }) }) -describe('ApiSessionClient agy transcript messages', () => { - it('renders only the USER_REQUEST body, not the sections agy appends', () => { - socketHarness.sockets.length = 0 - const client = new ApiSessionClient('token', createSession({ namespace: 'default' })) - const socket = socketHarness.sockets[0] - if (!socket) throw new Error('expected socket') - - // The shape agy actually writes for every terminal-typed message. - client.sendAgySessionMessage({ - step_index: 0, - source: 'USER_EXPLICIT', - type: 'USER_INPUT', - status: 'DONE', - created_at: '2026-08-04T00:00:00Z', - content: [ - '', - 'hi', - '', - '', - 'The current local time is: 2026-08-04T09:00:00+09:00.', - '', - '', - 'The user changed setting `Model Selection` from None to Gemini 3.6 Flash (Low).', - '', - ].join('\n'), - } as never) - - const emitted = socket.emitted.find((entry) => entry.event === 'message') - expect(emitted).toBeDefined() - expect((emitted!.args[0] as any).message.content.text).toBe('hi') - client.close() - }) -}) - describe('ApiSessionClient incoming user messages', () => { it.each([true, false])('replays explicitly marked native queue input only for shared sessions (%s)', shared => { socketHarness.sockets.length = 0 diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index 9f2e8adb..fbb1a205 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -10,7 +10,6 @@ import { apiValidationError } from '@/utils/errorUtils' import { AsyncLock } from '@/utils/lock' import type { RawJSONLines } from '@/claude/types' import { configuration } from '@/configuration' -import { extractUserRequest } from '@/agy/utils/agyMessageText' import { AGENT_MESSAGE_PAYLOAD_TYPE } from "@hapi/protocol" import type { SessionEndReason } from '@hapi/protocol' import type { ClientToServerEvents, ServerToClientEvents, TerminalOutputPayload, Update } from '@hapi/protocol' @@ -1048,78 +1047,6 @@ export class ApiSessionClient extends EventEmitter { } } - sendAgySessionMessage( - entry: { type: string; content?: string; tool_calls?: { name: string; args: Record }[]; step_index?: number; model?: string }, - conversationId?: string, - // The tool CALL (name + args) that produced this action entry, paired by - // the launcher from the preceding PLANNER_RESPONSE. agy splits the - // invocation (name/args live on the planner step) from its result (the - // action entry's `content`), so without this the tool card has no input - // to show — just the raw result. Carrying it here lets the web render a - // command/path/args like the other flavors. - toolCall?: { name: string; args: Record } - ): void { - const isUser = entry.type === 'USER_INPUT' - // agy appends its own sections (, ) - // after the request block, so only the extracted request may be rendered. - const text = isUser ? (extractUserRequest(entry.content ?? '') ?? entry.content ?? '').trim() : undefined - - if (isUser && text) { - this.socket.emit('message', { - sid: this.sessionId, - message: { - role: 'user', - content: { type: 'text', text }, - meta: { sentFrom: 'cli' } - } - }) - return - } - - // agy's structured entry types map to distinct chat renderings: - // - PLANNER_RESPONSE → the agent's prose (agy_message). Its `tool_calls` - // are only the model's INTENT and are immediately followed by the real - // action entry below, so we intentionally don't render them separately - // (that produced a duplicate "view_file" + "View file" card). - // - every other type (VIEW_FILE, RUN_COMMAND, LIST_DIRECTORY, CODE_ACTION, - // …) is a tool ACTION whose `content` is its result. Render it as a - // collapsible tool card (agy_tool_action) instead of dumping the raw - // (often huge) result text as a chat bubble. - let data: Record - if (entry.type !== 'PLANNER_RESPONSE') { - // Key the tool card by conversationId:stepIdx — the SAME id the - // PreToolUse permission request uses — so a gated tool's approval card - // and its result merge into one card (no stuck "running" duplicate) - // while still showing the pending approval in real time. - const toolUseId = conversationId != null && entry.step_index != null - ? `${conversationId}:${entry.step_index}` - : undefined - data = { - type: 'agy_tool_action', - name: entry.type, - content: entry.content ?? '', - toolUseId, - // The invocation the web renders as the tool INPUT. `toolName` is - // agy's own tool id (run_command, view_file, …) which the web maps - // to a canonical presentation; `input` is the raw args. - toolName: toolCall?.name, - input: toolCall?.args - } - } else { - // Tag the agent response with the model that produced it (per-turn), - // enriched by the scanner from the conversation DB. - data = { type: 'agy_message', content: entry.content ?? '', model: entry.model } - } - this.socket.emit('message', { - sid: this.sessionId, - message: { - role: 'agent', - content: { type: 'output', data }, - meta: { sentFrom: 'cli' } - } - }) - } - sendUserMessage(text: string, meta?: MessageMeta, localId?: string): void { if (!text) { return diff --git a/cli/src/commands/agy.test.ts b/cli/src/commands/agy.test.ts index 20ca3744..823a1d8a 100644 --- a/cli/src/commands/agy.test.ts +++ b/cli/src/commands/agy.test.ts @@ -10,6 +10,10 @@ describe('parseAgyCommandOptions', () => { expect(parseAgyCommandOptions(['--hapi-starting-mode', 'remote']).startingMode).toBe('remote') }) + it.each(['request-review', 'acceptEdits', 'plan', 'always-proceed'])('takes the %s permission mode from the spawn', (mode) => { + expect(parseAgyCommandOptions(['--permission-mode', mode]).permissionMode).toBe(mode) + }) + it.each(['local', 'pty'])('rejects unsupported %s mode', (mode) => { expect(() => parseAgyCommandOptions(['--hapi-starting-mode', mode])).toThrow( 'Invalid --hapi-starting-mode' diff --git a/cli/src/commands/pingPeer.ts b/cli/src/commands/pingPeer.ts index c879a94a..1e4ffce4 100644 --- a/cli/src/commands/pingPeer.ts +++ b/cli/src/commands/pingPeer.ts @@ -51,7 +51,8 @@ ${chalk.bold('Notes:')} the peer needs to know now to adjust its current work, not after its current turn. State why the finding matters now and what the peer should adjust. Explicit steer requires an active turn in remote Claude, Pi, Codex, OpenCode, - or Cursor ACP; it neither resumes inactive targets nor sends to idle targets. + Antigravity (agy acp), or Cursor ACP; it neither resumes inactive targets nor + sends to idle targets. Steer uses the existing queued-message action. If it fails after send, inspect the target before retrying: the accepted message may still be queued or consumed. When a user cites [title](/sessions/) or Copy-reference diff --git a/cli/src/modules/common/permission/AcpPermissionHandler.test.ts b/cli/src/modules/common/permission/AcpPermissionHandler.test.ts new file mode 100644 index 00000000..215a2ec6 --- /dev/null +++ b/cli/src/modules/common/permission/AcpPermissionHandler.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentBackend, PermissionRequest } from '@/agent/types' +import type { ApiSessionClient } from '@/api/apiSession' +import type { PermissionMode } from '@hapi/protocol/types' +import { AcpPermissionHandler } from './AcpPermissionHandler' + +function setup(mode: PermissionMode, options?: ConstructorParameters[3]) { + let onRequest: ((request: PermissionRequest) => void) | null = null + const backend = { + onPermissionRequest: vi.fn((handler: (request: PermissionRequest) => void) => { onRequest = handler }), + respondToPermission: vi.fn(async () => {}), + cancelPrompt: vi.fn(async () => {}) + } + const client = { + updateAgentState: vi.fn(), + rpcHandlerManager: { registerHandler: vi.fn() } + } + new AcpPermissionHandler( + client as unknown as ApiSessionClient, + backend as unknown as AgentBackend, + () => mode, + options + ) + return { backend, client, request: (request: PermissionRequest) => onRequest!(request) } +} + +function setupWithHandler(mode: PermissionMode, options?: ConstructorParameters[3]) { + let onRequest: ((request: PermissionRequest) => void) | null = null + const backend = { + onPermissionRequest: vi.fn((h: (request: PermissionRequest) => void) => { onRequest = h }), + respondToPermission: vi.fn(async () => {}), + cancelPrompt: vi.fn(async () => {}) + } + const client = { + updateAgentState: vi.fn(), + rpcHandlerManager: { registerHandler: vi.fn() } + } + const handler = new AcpPermissionHandler( + client as unknown as ApiSessionClient, + backend as unknown as AgentBackend, + () => mode, + options + ) + return { backend, handler, request: (request: PermissionRequest) => onRequest!(request) } +} + +const commandRequest: PermissionRequest = { + id: 'perm-1', + sessionId: 'acp-1', + toolCallId: 'call_1', + // agy titles a run_command request with the command line itself. + title: 'grep -n think notes.md', + kind: 'execute', + rawInput: { CommandLine: 'grep -n think notes.md' }, + options: [ + { optionId: 'allow', name: 'Allow', kind: 'allow_once' }, + { optionId: 'deny', name: 'Deny', kind: 'reject_once' } + ] +} + +describe('AcpPermissionHandler auto-approval rules', () => { + it('auto-approves a tool name hint by default', async () => { + const { backend, request } = setup('default') + + request(commandRequest) + + await vi.waitFor(() => expect(backend.respondToPermission).toHaveBeenCalledWith( + 'acp-1', + commandRequest, + { outcome: 'selected', optionId: 'allow' } + )) + }) + + it('asks the user when the agent disables the name and id hints', () => { + const { backend, client, request } = setup('default', { autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] } }) + + request(commandRequest) + + expect(backend.respondToPermission).not.toHaveBeenCalled() + const update = client.updateAgentState.mock.calls[0]![0] as (state: object) => { requests: Record } + expect(update({}).requests['perm-1']).toMatchObject({ tool: 'grep -n think notes.md' }) + }) + + it('still approves everything in an always-approve mode without hints', async () => { + const { backend, request } = setup('always-proceed', { autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] } }) + + request(commandRequest) + + await vi.waitFor(() => expect(backend.respondToPermission).toHaveBeenCalledWith( + 'acp-1', + commandRequest, + { outcome: 'selected', optionId: 'allow' } + )) + }) + + const offersAlways: PermissionRequest = { + ...commandRequest, + options: [ + { optionId: 'always', name: 'Always allow', kind: 'allow_always' }, + { optionId: 'once', name: 'Allow', kind: 'allow_once' }, + { optionId: 'deny', name: 'Deny', kind: 'reject_once' } + ] + } + + it('grants an always-approve request for the session by default', async () => { + const { backend, request } = setup('always-proceed') + + request(offersAlways) + + await vi.waitFor(() => expect(backend.respondToPermission).toHaveBeenCalledWith( + 'acp-1', offersAlways, { outcome: 'selected', optionId: 'always' } + )) + }) + + it('answers automatic approvals once when the agent asks for it', async () => { + const { backend, request } = setup('always-proceed', { autoApproveOnce: true }) + + request(offersAlways) + + await vi.waitFor(() => expect(backend.respondToPermission).toHaveBeenCalledWith( + 'acp-1', offersAlways, { outcome: 'selected', optionId: 'once' } + )) + }) + + it('reports how long a request waited for the user, and only those', async () => { + const waits: string[] = [] + const { request, handler } = setupWithHandler('request-review', { + autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] }, + onUserWait: (req) => { + waits.push(`start ${req.id}`) + return () => waits.push(`end ${req.id}`) + } + }) + + request(commandRequest) + await handler.cancelAll('Prompt finished') + await handler.cancelAll('Prompt finished') + + expect(waits).toEqual(['start perm-1', 'end perm-1']) + + const auto = setupWithHandler('always-proceed', { onUserWait: () => { throw new Error('not a user wait') } }) + auto.request(commandRequest) + }) + + it('never auto-answers a request the agent marks as needing the user', () => { + const { backend, client, request } = setup('always-proceed', { requiresUser: () => true }) + + request(commandRequest) + + expect(backend.respondToPermission).not.toHaveBeenCalled() + const update = client.updateAgentState.mock.calls[0]![0] as (state: object) => { requests: Record } + expect(update({}).requests['perm-1']).toBeDefined() + }) +}) diff --git a/cli/src/modules/common/permission/AcpPermissionHandler.ts b/cli/src/modules/common/permission/AcpPermissionHandler.ts index 40d65725..ff1b9304 100644 --- a/cli/src/modules/common/permission/AcpPermissionHandler.ts +++ b/cli/src/modules/common/permission/AcpPermissionHandler.ts @@ -6,6 +6,7 @@ import { logger } from '@/ui/logger' import { BasePermissionHandler, type AutoApprovalDecision, + type AutoApprovalRuleSet, type PendingPermissionRequest, type PermissionCompletion } from './BasePermissionHandler' @@ -45,11 +46,25 @@ function mapDecisionToOutcome( /** Shared HAPI permission bridge for ACP agents with one-shot choices. */ export class AcpPermissionHandler extends BasePermissionHandler { private readonly pendingBackendRequests = new Map() + private readonly userWaitEnds = new Map void>() constructor( session: ApiSessionClient, private readonly backend: AgentBackend, - private readonly getPermissionMode: () => PermissionMode | undefined + private readonly getPermissionMode: () => PermissionMode | undefined, + private readonly options: { + // Agents that title requests with free text (agy: the command + // line) turn off the HAPI tool-name hints, which could match it. + autoApprovalRules?: AutoApprovalRuleSet + // A long-lived agent process outlives mode switches, so automatic + // approvals must not leave standing grants behind. + autoApproveOnce?: boolean + // Questions need the user's answer in every mode. + requiresUser?: (request: PermissionRequest) => boolean + // Called when a request starts waiting for the user; the returned + // callback runs once it is answered (agents timing their own work). + onUserWait?: (request: PermissionRequest) => () => void + } = {} ) { super(session) this.backend.onPermissionRequest((request) => this.handlePermissionRequest(request)) @@ -62,17 +77,25 @@ export class AcpPermissionHandler extends BasePermissionHandler {}, reject: () => {} @@ -118,6 +141,7 @@ export class AcpPermissionHandler extends BasePermissionHandler 0 + } + async cancelAll(reason: string): Promise { const pending = Array.from(this.pendingBackendRequests.values()) this.pendingBackendRequests.clear() for (const request of pending) { await this.backend.respondToPermission(request.sessionId, request, { outcome: 'cancelled' }) + this.endUserWait(request.id) } this.cancelPendingRequests({ completedReason: reason, diff --git a/cli/src/modules/pingPeer/pingPeer.ts b/cli/src/modules/pingPeer/pingPeer.ts index fa52fa2f..b2fa6c91 100644 --- a/cli/src/modules/pingPeer/pingPeer.ts +++ b/cli/src/modules/pingPeer/pingPeer.ts @@ -689,7 +689,7 @@ function getSteeringIneligibility(session: PingPeerSessionSummary): SteeringInel // Explicit steer refuses before sending, so these texts say no message was sent. const EXPLICIT_STEER_REFUSAL: Record = { inactive: 'Steering requires an active turn; target is inactive, no message sent. Use queue with wake to resume it', - unsupported: 'Steering is only supported for Claude, Pi, Codex, OpenCode, and Cursor ACP sessions; no message sent', + unsupported: 'Steering is only supported for Claude, Pi, Codex, OpenCode, Antigravity, and Cursor ACP sessions; no message sent', local: 'Steering is only available for remote sessions; no message sent', idle: 'Steering requires an active turn; target is idle, no message sent. Use queue to start a turn' } diff --git a/cli/src/runner/buildCliArgs.test.ts b/cli/src/runner/buildCliArgs.test.ts index bd319bd1..4fb7db97 100644 --- a/cli/src/runner/buildCliArgs.test.ts +++ b/cli/src/runner/buildCliArgs.test.ts @@ -16,6 +16,16 @@ describe('buildCliArgs', () => { expect(args).not.toContain('--yolo') }) + it('passes the Antigravity permission mode chosen at create time', () => { + const args = buildCliArgs('agy', { + directory: '/tmp', + permissionMode: 'plan', + }) + expect(args.slice(args.indexOf('--permission-mode'), args.indexOf('--permission-mode') + 2)) + .toEqual(['--permission-mode', 'plan']) + expect(args).not.toContain('--yolo') + }) + it('ignores invalid permission mode and falls back to --yolo', () => { const args = buildCliArgs('claude', { directory: '/tmp', diff --git a/docs/guide/agents.md b/docs/guide/agents.md index e2e1cbec..1285e018 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -20,7 +20,7 @@ agent's integration; their supported syntax varies by agent. | Kimi | `hapi kimi` | ACP (`kimi acp`) | ✓ | ✓ | `default` `read-only` `safe-yolo` `yolo` | ✓ | | OpenCode | `hapi opencode` | ACP (`opencode acp`) | ✓ | ✓ | `default` `plan` `yolo` | ✓ | | DeepSeek Harness | `hapi dsh` | ACP (`dsh --profile acp` or configured server) | — | ✓ | Managed by DSH ACP composition | ✓* | -| Antigravity (agy) | `hapi agy` | Persistent headless NDJSON over stdio | — | ✓ | `request-review` `always-proceed` | ✓ | +| Antigravity (agy) | `hapi agy` | ACP (`agy acp`, agy 1.5.0+); persistent stream-json for older agy | — | ✓ | `request-review` `acceptEdits` `plan` `always-proceed` | ✓ | | Pi | `hapi pi` | `pi --mode rpc` (JSON-line RPC over stdio) | — | ✓ | none (always auto-approve) | ✓ | | Gemini CLI | — | **Removed** — Google sunset the consumer Gemini CLI (2026-06-18) | — | — | — | — | @@ -30,7 +30,7 @@ Gemini is no longer launchable: `hapi gemini` is kept as a tombstone command tha ### ACP -Most remote integrations speak the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) over stdio through a shared HAPI backend. ACP gives remote sessions bidirectional permission approval, plan/todo updates, question UI, model catalogs, and session resume via `session/load`. Cursor, Grok, Copilot, Kimi, OpenCode, and DeepSeek Harness remote sessions all run over ACP. DSH's official ACP server is automation-focused and currently supports committed assistant output, cancellation, one-shot permissions, native session resume via `session/resume`, and per-turn model switching through `session/set_config_option`; it does not provide MCP injection or live tool/reasoning telemetry. Legacy or incompatible DSH ACP servers fall back to a fresh session when native resume is unavailable. +Most remote integrations speak the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) over stdio through a shared HAPI backend. ACP gives remote sessions bidirectional permission approval, plan/todo updates, question UI, model catalogs, and session resume via `session/load`. Cursor, Grok, Copilot, Kimi, OpenCode, Antigravity, and DeepSeek Harness remote sessions all run over ACP. DSH's official ACP server is automation-focused and currently supports committed assistant output, cancellation, one-shot permissions, native session resume via `session/resume`, and per-turn model switching through `session/set_config_option`; it does not provide MCP injection or live tool/reasoning telemetry. Legacy or incompatible DSH ACP servers fall back to a fresh session when native resume is unavailable. ### Permission modes @@ -315,28 +315,38 @@ the prompt is loaded by DSH through its own `skill` tool and catalog. - **GitHub Copilot** (`hapi copilot`) — Copilot CLI over ACP (`copilot --acp --stdio`). [GitHub Copilot](https://github.com/features/copilot) - **Kimi** (`hapi kimi`) — Moonshot AI's Kimi CLI over ACP (`kimi acp`). [MoonshotAI/kimi-cli](https://github.com/MoonshotAI/kimi-cli) - **OpenCode** (`hapi opencode`) — the open-source OpenCode agent over ACP (`opencode acp`). [opencode.ai](https://opencode.ai) -- **Antigravity** (`hapi agy`) — Google's Antigravity CLI (`agy`), driven through - `agy --input-format stream-json --output-format stream-json`. HAPI starts the - process on the first prompt and reuses it for subsequent turns with the same - model, effort, and permission settings. Each prompt is sent through stdin; - the next turn starts after HAPI finishes handling the current `result` and - chat output. - Changing settings restarts the process with `--conversation `. Stop - terminates the process and its tools; the next send resumes the conversation. - A process failure also causes the next turn to start a fresh process, without - automatically replaying a prompt the agent already accepted. +- **Antigravity** (`hapi agy`) — Google's Antigravity CLI (`agy`) over ACP + (`agy acp`, added in agy 1.5.0). HAPI checks `agy --version` when the + session starts; older agy releases, an agy whose version cannot be read, + and an `agy acp` that fails to start keep the previous persistent + stream-json integration (no approval prompts in + HAPI: tools without an allow-rule in agy's `settings.json` are auto-denied). - Requires an agy CLI with `--input-format stream-json` support. Native CLI - commands such as `/model` and `/usage` cannot run inside this stream; use - HAPI's model and effort controls to change settings. Remote-only — there is - no local terminal input path or PTY/TUI wrapper. + On ACP, one `agy acp` process serves the whole session. The agy conversation + id is the ACP session id, so a session continues the same conversation + through `session/resume` without replaying history, whichever integration + started it. If the agy process dies, the next message restarts it and + resumes the conversation; a prompt agy never started is restored to the + composer. Stop sends `session/cancel`, which also ends open tool calls; a + prompt stopped before agy answered anything also goes back to the composer. - Permission handling uses agy's `settings.json` allow/deny rules - (`request-review`) or `--dangerously-skip-permissions` (`always-proceed`), - without a hook-based approval bridge. Tools without an allow-rule are - auto-denied and shown as a chat hint. MCP servers are loaded natively from - `~/.gemini/config/mcp_config.json` or workspace `.agents/mcp_config.json`; - HAPI does not inject its own MCP server. [Google Antigravity](https://antigravity.google) + On ACP, **Steer** a queued message to add it to the running turn instead of + waiting for the turn to end. HAPI sends it as another `session/prompt`; agy + finishes any tool call already running, then continues the same turn with + the new message. The turn's usage includes the steered part. + + Permission modes map to agy's session modes: `request-review` is agy's + `default` mode, which follows agy's own permission settings and, on ACP, + shows its approval requests in HAPI; `acceptEdits` and `plan` are agy's + `accept-edits` and `plan` modes; `always-proceed` approves every request + automatically. On ACP, mode changes apply to the next message without + restarting agy. Conversation titles come from agy; on ACP each response's + details show the turn's token usage. + + Remote-only — there is no local terminal input path or PTY/TUI wrapper. MCP + servers are loaded natively from `~/.gemini/config/mcp_config.json` or + workspace `.agents/mcp_config.json`; HAPI does not inject its own MCP server. + [Google Antigravity](https://antigravity.google) In the web model picker, models with multiple effort variants appear once, with a separate effort selector showing the levels in the machine's catalog. diff --git a/hub/src/sync/steerQueuedMessage.test.ts b/hub/src/sync/steerQueuedMessage.test.ts index 48148841..429b2cd4 100644 --- a/hub/src/sync/steerQueuedMessage.test.ts +++ b/hub/src/sync/steerQueuedMessage.test.ts @@ -161,6 +161,32 @@ describe('SyncEngine.steerQueuedMessage', () => { } }) + it('tells an Antigravity session without agy acp that Steer is not available yet', async () => { + const { store, engine } = createEngine() + const steer = spyOn(RpcGateway.prototype, 'steerQueuedMessage').mockResolvedValue({ steered: true }) + try { + const session = engine.getOrCreateSession( + 'steer-agy-starting', + { path: '/tmp/project', host: 'localhost', flavor: 'agy' }, + { requests: {}, completedRequests: {} }, + 'default' + ) + const message = store.messages.addMessage(session.id, { text: 'hi' }, 'local-id') + + const result = await engine.steerQueuedMessage(session.id, message.id) + + expect(result).toEqual({ + status: 'failed', + error: 'Antigravity is not running on agy acp (yet); Steer is not available', + localId: null + }) + expect(steer).not.toHaveBeenCalled() + } finally { + steer.mockRestore() + engine.stop() + } + }) + it('rejects unsupported flavors without invoking the CLI', async () => { const { store, engine } = createEngine() try { @@ -176,7 +202,7 @@ describe('SyncEngine.steerQueuedMessage', () => { expect(result).toEqual({ status: 'failed', - error: 'Steering is only supported for Claude, Pi, Codex, OpenCode, and Cursor ACP sessions', + error: 'Steering is only supported for Claude, Pi, Codex, OpenCode, Antigravity, and Cursor ACP sessions', localId: null }) } finally { diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 0ca50ab8..bbd8c0e5 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -1318,8 +1318,8 @@ export class SyncEngine { /** * Ask the CLI to deliver one waiting-queue message into the active turn - * (native steer). Supported for Claude, Pi, Codex, OpenCode, and Cursor - * ACP sessions; the CLI's handler is registered per flavor. Legacy + * (native steer). Supported for Claude, Pi, Codex, OpenCode, Antigravity, + * and Cursor ACP sessions; the CLI's handler is registered per flavor. Legacy * stream-json Cursor sessions and other flavors are rejected by the * capability gate. */ @@ -1332,7 +1332,12 @@ export class SyncEngine { return { status: 'failed', error: 'Session not found', localId: null } } if (!isSteeringSupportedForSession(session.metadata)) { - return { status: 'failed', error: 'Steering is only supported for Claude, Pi, Codex, OpenCode, and Cursor ACP sessions', localId: null } + // An agy session gets its ACP marker only once its CLI has picked + // the transport, a few seconds after spawn. + const error = session.metadata?.flavor === 'agy' + ? 'Antigravity is not running on agy acp (yet); Steer is not available' + : 'Steering is only supported for Claude, Pi, Codex, OpenCode, Antigravity, and Cursor ACP sessions' + return { status: 'failed', error, localId: null } } if (session.agentState?.controlledByUser === true && !session.metadata?.capabilities?.concurrentClients) { return { status: 'failed', error: 'Steering is only available for remote sessions', localId: null } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift index 667c02a3..e69f0827 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift @@ -100,7 +100,7 @@ extension AgentFlavor { case .dsh: return [] case .agy: - return [.requestReview, .alwaysProceed] + return [.requestReview, .acceptEdits, .plan, .alwaysProceed] case .cursor: return [.default, .plan, .ask, .debug, .autoReview, .yolo] case .pi: diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift index 1e78e7bb..6fe781a1 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift @@ -94,7 +94,7 @@ struct CatalogTests { @Test func remainingFlavorsMatchTheirDeclaredSets() { #expect(permissionModes(forFlavor: "grok") == [.default, .auto, .plan, .bypassPermissions]) #expect(permissionModes(forFlavor: "opencode") == [.default, .plan, .yolo]) - #expect(permissionModes(forFlavor: "agy") == [.requestReview, .alwaysProceed]) + #expect(permissionModes(forFlavor: "agy") == [.requestReview, .acceptEdits, .plan, .alwaysProceed]) #expect(permissionModes(forFlavor: "cursor") == [.default, .plan, .ask, .debug, .autoReview, .yolo]) // Pi has no runtime permission switching (always auto-approve). #expect(permissionModes(forFlavor: "pi") == []) diff --git a/shared/fixtures/catalogs/modes.json b/shared/fixtures/catalogs/modes.json index 41cf0c37..6aff1b92 100644 --- a/shared/fixtures/catalogs/modes.json +++ b/shared/fixtures/catalogs/modes.json @@ -16,6 +16,16 @@ "mode": "request-review", "tone": "neutral" }, + { + "label": "Accept Edits", + "mode": "acceptEdits", + "tone": "warning" + }, + { + "label": "Plan Mode", + "mode": "plan", + "tone": "info" + }, { "label": "Always Proceed", "mode": "always-proceed", diff --git a/shared/src/modes.test.ts b/shared/src/modes.test.ts index a50c4d08..d0980176 100644 --- a/shared/src/modes.test.ts +++ b/shared/src/modes.test.ts @@ -42,6 +42,15 @@ describe('getPermissionModesForFlavor', () => { ]) }) + test('returns the agy ACP session modes plus HAPI auto-approval', () => { + expect(getPermissionModesForFlavor('agy')).toEqual([ + 'request-review', + 'acceptEdits', + 'plan', + 'always-proceed' + ]) + }) + test("returns no HAPI mode selector for DSH's server-owned permission policy", () => { expect(getPermissionModesForFlavor('dsh')).toEqual([]) }) @@ -147,7 +156,8 @@ describe('claude auto permission mode', () => { }) describe('isSteeringSupportedForFlavor', () => { - it('supports claude, codex, cursor, opencode and pi', () => { + it('supports agy, claude, codex, cursor, opencode and pi', () => { + expect(isSteeringSupportedForFlavor('agy')).toBe(true) expect(isSteeringSupportedForFlavor('codex')).toBe(true) expect(isSteeringSupportedForFlavor('cursor')).toBe(true) expect(isSteeringSupportedForFlavor('opencode')).toBe(true) @@ -160,7 +170,8 @@ describe('isSteeringSupportedForFlavor', () => { }) describe('isSteeringSupportedForSession', () => { - it('supports claude, codex, opencode and pi sessions', () => { + it('supports agy, claude, codex, opencode and pi sessions', () => { + expect(isSteeringSupportedForSession({ flavor: 'agy', agyProtocol: 'acp' })).toBe(true) expect(isSteeringSupportedForSession({ flavor: 'codex' })).toBe(true) expect(isSteeringSupportedForSession({ flavor: 'opencode' })).toBe(true) expect(isSteeringSupportedForSession({ flavor: 'pi' })).toBe(true) @@ -176,6 +187,12 @@ describe('isSteeringSupportedForSession', () => { expect(isSteeringSupportedForSession({ flavor: 'cursor' })).toBe(true) }) + it('steers agy sessions only while they run on agy acp', () => { + expect(isSteeringSupportedForSession({ flavor: 'agy', agyProtocol: 'acp' })).toBe(true) + expect(isSteeringSupportedForSession({ flavor: 'agy' })).toBe(false) + expect(isSteeringSupportedForSession({ flavor: 'agy', agyProtocol: null })).toBe(false) + }) + it('rejects legacy Cursor stream-json sessions', () => { expect(isSteeringSupportedForSession({ flavor: 'cursor', @@ -203,6 +220,13 @@ describe('hasActiveSteeringTurn', () => { expect(hasActiveSteeringTurn({ metadata: { flavor }, thinking: true })).toBe(false) }) + it('uses steeringActive for agy acp sessions and ignores stream-json ones', () => { + const acp = { flavor: 'agy', agyProtocol: 'acp' as const } + expect(hasActiveSteeringTurn({ metadata: acp, thinking: false, agentState: { steeringActive: true } })).toBe(true) + expect(hasActiveSteeringTurn({ metadata: acp, thinking: true, agentState: { steeringActive: false } })).toBe(false) + expect(hasActiveSteeringTurn({ metadata: { flavor: 'agy' }, thinking: true, agentState: { steeringActive: true } })).toBe(false) + }) + it('uses the Pi runtime thinking signal', () => { expect(hasActiveSteeringTurn({ metadata: { flavor: 'pi' }, thinking: true, agentState: { steeringActive: false } })).toBe(true) @@ -227,10 +251,11 @@ describe('hasActiveSteeringTurn', () => { describe('steering support table', () => { // The pre-table branching, kept as the reference the table must match. - type Metadata = { flavor?: string | null; cursorSessionId?: string | null; cursorSessionProtocol?: 'acp' | 'stream-json' | null } + type Metadata = { flavor?: string | null; cursorSessionId?: string | null; cursorSessionProtocol?: 'acp' | 'stream-json' | null; agyProtocol?: 'acp' | null } function referenceSupportsSession(metadata?: Metadata | null): boolean { if (metadata?.flavor === 'claude' || metadata?.flavor === 'codex' || metadata?.flavor === 'opencode' || metadata?.flavor === 'pi') return true + if (metadata?.flavor === 'agy') return metadata.agyProtocol === 'acp' if (metadata?.flavor !== 'cursor') return false if (metadata.cursorSessionProtocol === 'stream-json') return false if (!metadata.cursorSessionProtocol && metadata.cursorSessionId) return false @@ -241,7 +266,8 @@ describe('steering support table', () => { 'claude', 'codex', 'cursor', 'opencode', 'pi', 'gemini', 'agy', 'unknown', '', '__proto__', 'constructor', 'toString', null, undefined, ] - const cursorShapes: Array> = [ + const cursorShapes: Array> = [ + { agyProtocol: 'acp' }, { agyProtocol: null }, { cursorSessionProtocol: 'acp', agyProtocol: 'acp' }, {}, { cursorSessionId: 'id' }, { cursorSessionId: null }, { cursorSessionProtocol: 'acp' }, { cursorSessionProtocol: 'stream-json' }, { cursorSessionProtocol: null }, { cursorSessionId: 'id', cursorSessionProtocol: 'acp' }, diff --git a/shared/src/modes.ts b/shared/src/modes.ts index fccdf60f..494497bc 100644 --- a/shared/src/modes.ts +++ b/shared/src/modes.ts @@ -19,7 +19,7 @@ export const CREATABLE_AGENT_FLAVORS: readonly AgentFlavor[] = AGENT_FLAVORS.fil (flavor) => flavor !== 'gemini' ) -export const AGY_PERMISSION_MODES = ['request-review', 'always-proceed'] as const +export const AGY_PERMISSION_MODES = ['request-review', 'acceptEdits', 'plan', 'always-proceed'] as const export type AgyPermissionMode = typeof AGY_PERMISSION_MODES[number] export const CLAUDE_PERMISSION_MODES = ['default', 'acceptEdits', 'auto', 'bypassPermissions', 'plan'] as const @@ -188,6 +188,7 @@ type SteeringSessionMetadata = { flavor?: string | null cursorSessionId?: string | null cursorSessionProtocol?: 'acp' | 'stream-json' | null + agyProtocol?: 'acp' | null } type SteeringSessionState = { @@ -215,16 +216,23 @@ type SteeringCapability = { * {@link isSteeringSupportedForSession}. * - Claude: stream-json stdin write during the turn (TUI Ctrl+X Ctrl+S); * Claude folds it in at the next tool boundary. Remote mode only. + * - Antigravity: concurrent ACP `session/prompt` (`agy acp`); agy answers the + * interrupted request at once and folds the steer in after any running + * tool call finishes. Only sessions marked `agyProtocol: 'acp'` steer. * * Others: not supported — UI hides Steer. */ -export const STEERING_SUPPORTED_FLAVORS = ['claude', 'codex', 'cursor', 'opencode', 'pi'] as const +export const STEERING_SUPPORTED_FLAVORS = ['agy', 'claude', 'codex', 'cursor', 'opencode', 'pi'] as const type SteeringFlavor = typeof STEERING_SUPPORTED_FLAVORS[number] // Keep protocol restrictions and the runtime's active-turn signal together so // peer senders and the waiting queue do not need their own flavor branches. const STEERING_CAPABILITIES = { + agy: { + activeTurnState: 'steeringActive', + supportsSession: (metadata: SteeringSessionMetadata) => metadata.agyProtocol === 'acp' + }, claude: { activeTurnState: 'steeringActive' }, codex: { activeTurnState: 'steeringActive' }, cursor: { diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 9598762c..8532a789 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -87,6 +87,8 @@ export const MetadataSchema = z.object({ opencodeSessionId: z.string().optional(), grokSessionId: z.string().optional(), agySessionId: z.string().optional(), + /** Set while an agy session runs on `agy acp`; absent otherwise. */ + agyProtocol: z.literal('acp').optional(), cursorSessionId: z.string().optional(), cursorSessionProtocol: z.enum(['acp', 'stream-json']).optional(), // Drives the web `CursorMigrationBanner`: diff --git a/shared/src/sessionCitation.ts b/shared/src/sessionCitation.ts index ad4680b6..77968681 100644 --- a/shared/src/sessionCitation.ts +++ b/shared/src/sessionCitation.ts @@ -86,7 +86,7 @@ export const PEER_DELIVERY_MODE_DESCRIPTION = 'steer: use for important, time-sensitive findings the peer needs to know now, not after finishing its current turn ' + '(e.g. a correction that invalidates its assumptions, a blocker, or a result that changes its next action). ' + 'State why the finding matters now and what the peer should adjust. ' + - 'Steer requires insertion into an active Claude, Pi, Codex, OpenCode, or Cursor ACP turn; unsupported, idle, or inactive targets are rejected before sending. ' + + 'Steer requires insertion into an active Claude, Pi, Codex, OpenCode, Antigravity, or Cursor ACP turn; unsupported, idle, or inactive targets are rejected before sending. ' + 'Steering does not abort the current turn or guarantee an immediate response. ' + 'If send or steer is unconfirmed after submission, inspect the target before retrying; do not resend automatically.' diff --git a/web/scripts/fixtures/cases/agy.ts b/web/scripts/fixtures/cases/agy.ts index 317cb2bd..17e5f31e 100644 --- a/web/scripts/fixtures/cases/agy.ts +++ b/web/scripts/fixtures/cases/agy.ts @@ -6,7 +6,7 @@ import { T0, wireMessage } from './support' * Claude-style output envelope (content.type === 'output') with * data.type === 'agy_message' (planner prose) and 'agy_tool_action' (a DONE * tool action whose content is its result). See normalizeAgent.ts (agy - * branches) and cli/src/api/apiSession.ts sendAgySessionMessage. + * branches). */ export const agyCases: FixtureCase[] = [ { diff --git a/web/src/chat/normalizeAgent.roundSummary.test.ts b/web/src/chat/normalizeAgent.roundSummary.test.ts index a7c6420d..e6694c44 100644 --- a/web/src/chat/normalizeAgent.roundSummary.test.ts +++ b/web/src/chat/normalizeAgent.roundSummary.test.ts @@ -109,3 +109,52 @@ it('omits only the throughput pair for absent, partial or invalid optional gener expect(normalized?.content).not.toHaveProperty('summary.generationOutputTokens') } }) + +describe('agy round summary carrier', () => { + const normalizeCarrier = (summary: unknown) => normalizeDecryptedMessage({ + id: 'agy-round-summary', seq: 1, localId: null, createdAt: 1, + content: { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary } } } + }) + + it('keeps the agy usage breakdown, model and round time', () => { + expect(normalizeCarrier({ + provider: 'agy', + model: 'gemini-3-flash-low', + agy_usage: { input_tokens: 30458, output_tokens: 58, thinking_tokens: 0, cache_read_tokens: 0, total_tokens: 30516 }, + duration_ms: 9_500 + })).toMatchObject({ + role: 'event', + content: { + type: 'turn-summary', + summary: { + provider: 'agy', + modelUsage: { 'gemini-3-flash-low': {} }, + agyUsage: { input_tokens: 30458, output_tokens: 58, thinking_tokens: 0, cache_read_tokens: 0, total_tokens: 30516 }, + durationMs: 9_500 + } + } + }) + }) + + it('keeps agy generation time and tokens only when both are positive', () => { + const base = { provider: 'agy', agy_usage: { output_tokens: 70 }, duration_ms: 14_900 } + expect(normalizeCarrier({ ...base, generation_ms: 2_500, generation_output_tokens: 70 })?.content) + .toMatchObject({ summary: { generationMs: 2_500, generationOutputTokens: 70 } }) + for (const generation of [{}, { generation_ms: 0, generation_output_tokens: 70 }, { generation_ms: 2_500 }, { generation_ms: -1, generation_output_tokens: 70 }]) { + expect(normalizeCarrier({ ...base, ...generation })?.content).not.toHaveProperty('summary.generationMs') + } + }) + + it('drops invalid token counts and empty agy summaries', () => { + const normalized = normalizeCarrier({ + provider: 'agy', + agy_usage: { input_tokens: -1, output_tokens: 1.5, thinking_tokens: '3', cache_read_tokens: 2, total_tokens: Number.MAX_SAFE_INTEGER + 1 } + }) + expect(normalized?.content).toEqual({ + type: 'turn-summary', + summary: { provider: 'agy', modelUsage: {}, agyUsage: { cache_read_tokens: 2 } } + }) + expect(normalizeCarrier({ provider: 'agy', agy_usage: { input_tokens: -1 } })).toBeNull() + expect(normalizeCarrier({ provider: 'agy', agy_usage: [1, 2] })).toBeNull() + }) +}) diff --git a/web/src/chat/normalizeAgent.ts b/web/src/chat/normalizeAgent.ts index bdcb1279..7ecf5fc3 100644 --- a/web/src/chat/normalizeAgent.ts +++ b/web/src/chat/normalizeAgent.ts @@ -95,6 +95,30 @@ function normalizeRoundSummary(value: unknown): RoundSummary | undefined { } } +function normalizeAgyRoundSummary(value: Record): RoundSummary | undefined { + const raw = value.agy_usage + const agyUsage: NonNullable = {} + if (isObject(raw) && !Array.isArray(raw)) { + for (const key of ['input_tokens', 'output_tokens', 'thinking_tokens', 'cache_read_tokens', 'total_tokens'] as const) { + const token = nonNegativeSafeInteger(raw[key]) + if (token !== undefined) agyUsage[key] = token + } + } + const durationMs = nonNegativeNumber(value.duration_ms) + const model = asString(value.model) + const hasUsage = Object.keys(agyUsage).length > 0 + if (!hasUsage && durationMs === undefined) return undefined + const generationMs = nonNegativeSafeInteger(value.generation_ms) + const generationOutputTokens = nonNegativeSafeInteger(value.generation_output_tokens) + return { + provider: 'agy', + modelUsage: model ? { [model]: {} } : {}, + ...(hasUsage ? { agyUsage } : {}), + ...(durationMs !== undefined ? { durationMs } : {}), + ...(generationMs && generationOutputTokens ? { generationMs, generationOutputTokens } : {}) + } +} + function normalizeOpencodeRoundSummary(value: unknown): RoundSummary | undefined { if (!isObject(value) || Array.isArray(value)) return undefined const usage = normalizeResultUsage(value.usage) @@ -1084,7 +1108,9 @@ export function normalizeAgentRecord( } if (data.type === 'round-summary') { - const summary = normalizeOpencodeRoundSummary(data.summary) + const summary = isObject(data.summary) && data.summary.provider === 'agy' + ? normalizeAgyRoundSummary(data.summary) + : normalizeOpencodeRoundSummary(data.summary) if (!summary) return null return { id: messageId, diff --git a/web/src/chat/reconcile.roundSummary.test.ts b/web/src/chat/reconcile.roundSummary.test.ts index fea708e9..558ea2e7 100644 --- a/web/src/chat/reconcile.roundSummary.test.ts +++ b/web/src/chat/reconcile.roundSummary.test.ts @@ -29,3 +29,26 @@ describe('round throughput reconciliation', () => { expect(result.blocks[0]).toBe(previous) }) }) + +describe('agy round usage reconciliation', () => { + const agy: RoundSummary = { + provider: 'agy', modelUsage: {}, durationMs: 2_000, + agyUsage: { input_tokens: 10, output_tokens: 2, thinking_tokens: 1, cache_read_tokens: 4, total_tokens: 13 } + } + + it.each(['input_tokens', 'output_tokens', 'thinking_tokens', 'cache_read_tokens', 'total_tokens'] as const)( + 'updates the footer when only agy %s changes', + (key) => { + const previous = block(agy) + const next = block({ ...agy, agyUsage: { ...agy.agyUsage, [key]: 99 } }) + const result = reconcileChatBlocks([next], new Map([[previous.id, previous]])) + expect(result.blocks[0]).toBe(next) + } + ) + + it('retains stable references for unchanged agy usage', () => { + const previous = block(agy) + const result = reconcileChatBlocks([block({ ...agy, agyUsage: { ...agy.agyUsage } })], new Map([[previous.id, previous]])) + expect(result.blocks[0]).toBe(previous) + }) +}) diff --git a/web/src/chat/reconcile.ts b/web/src/chat/reconcile.ts index 4920fadc..394e12ed 100644 --- a/web/src/chat/reconcile.ts +++ b/web/src/chat/reconcile.ts @@ -53,7 +53,13 @@ function areRoundSummariesEqual(left?: RoundSummary, right?: RoundSummary): bool if (!left || !right) return false const leftModels = Object.keys(left.modelUsage) const rightModels = Object.keys(right.modelUsage) - return left.totalCostUsd === right.totalCostUsd + return left.provider === right.provider + && left.agyUsage?.input_tokens === right.agyUsage?.input_tokens + && left.agyUsage?.output_tokens === right.agyUsage?.output_tokens + && left.agyUsage?.thinking_tokens === right.agyUsage?.thinking_tokens + && left.agyUsage?.cache_read_tokens === right.agyUsage?.cache_read_tokens + && left.agyUsage?.total_tokens === right.agyUsage?.total_tokens + && left.totalCostUsd === right.totalCostUsd && left.numTurns === right.numTurns && left.durationMs === right.durationMs && left.generationMs === right.generationMs diff --git a/web/src/chat/types.ts b/web/src/chat/types.ts index 843625bf..053c92ee 100644 --- a/web/src/chat/types.ts +++ b/web/src/chat/types.ts @@ -21,8 +21,13 @@ export type RoundModelUsage = { cacheCreationInputTokens?: number } +export type AgyUsage = Partial> + export type RoundSummary = { - provider?: 'codex' + provider?: 'codex' | 'agy' + agyUsage?: AgyUsage turnId?: string usage?: UsageData modelUsage: Record diff --git a/web/src/components/AssistantChat/messages/MessageMetadata.test.ts b/web/src/components/AssistantChat/messages/MessageMetadata.test.ts index a9c314da..b333c4e1 100644 --- a/web/src/components/AssistantChat/messages/MessageMetadata.test.ts +++ b/web/src/components/AssistantChat/messages/MessageMetadata.test.ts @@ -287,4 +287,42 @@ describe('provider throughput metadata', () => { it.each([undefined, 0, -1, NaN, Infinity, 1.5])('hides invalid output %s', (generationOutputTokens) => { expect(buildMessageMetadataLabels({ roundSummary: { ...summary, generationOutputTokens } }).join(' ')).not.toContain('tok/s') }) + it('renders the agy usage breakdown, cache share and round time', () => { + const parts = buildMessageMetadataLabels({ + roundSummary: { + provider: 'agy', + modelUsage: { 'gemini-3-flash-low': {} }, + agyUsage: { input_tokens: 30_458, output_tokens: 58, thinking_tokens: 120, cache_read_tokens: 10_000, total_tokens: 30_636 }, + durationMs: 9_500 + } + }) + + expect(parts).toEqual([ + 'Model: gemini-3-flash-low', + 'Tokens: 30.6k (30.5k in · 58 out · 120 thinking)', + 'Cached input: 24.7%', + 'Round: 9.5s' + ]) + }) + + it('adds agy tok/s to the Round line when the summary carries generation time', () => { + const parts = buildMessageMetadataLabels({ + roundSummary: { + provider: 'agy', + modelUsage: {}, + agyUsage: { input_tokens: 4_422, output_tokens: 58, thinking_tokens: 12, total_tokens: 35_530 }, + durationMs: 14_900, + generationMs: 2_500, + generationOutputTokens: 70 + } + }) + expect(parts.at(-1)).toBe('Round: 14.9s · 28.0 tok/s') + }) + + it('omits the agy cache share without cache reads and shows partial usage as reported', () => { + expect(buildMessageMetadataLabels({ + model: 'fallback-model', + roundSummary: { provider: 'agy', modelUsage: {}, agyUsage: { input_tokens: 15_172, output_tokens: 44, cache_read_tokens: 0 } } + })).toEqual(['Model: fallback-model', 'Tokens: 15.2k in · 44 out']) + }) }) diff --git a/web/src/components/AssistantChat/messages/MessageMetadata.tsx b/web/src/components/AssistantChat/messages/MessageMetadata.tsx index ddf24472..ea9531f2 100644 --- a/web/src/components/AssistantChat/messages/MessageMetadata.tsx +++ b/web/src/components/AssistantChat/messages/MessageMetadata.tsx @@ -54,12 +54,49 @@ function getRoundUsage(summary: RoundSummary): UsageData | undefined { }), { input_tokens: 0, output_tokens: 0 }) } +function formatTokensPerSecond({ generationMs, generationOutputTokens }: RoundSummary): string | undefined { + if (generationMs === undefined || !Number.isSafeInteger(generationMs) || generationMs <= 0 + || generationOutputTokens === undefined || !Number.isSafeInteger(generationOutputTokens) || generationOutputTokens <= 0) { + return undefined + } + const tokensPerSecond = generationOutputTokens / (generationMs / 1_000) + return Number.isFinite(tokensPerSecond) ? `${tokensPerSecond.toFixed(1)} tok/s` : undefined +} + +function buildAgyRoundLabels(summary: RoundSummary): string[] { + const parts: string[] = [] + const usage = summary.agyUsage + if (usage) { + const breakdown = [ + usage.input_tokens !== undefined ? `${formatCompactTokenCount(usage.input_tokens)} in` : undefined, + usage.output_tokens !== undefined ? `${formatCompactTokenCount(usage.output_tokens)} out` : undefined, + usage.thinking_tokens !== undefined ? `${formatCompactTokenCount(usage.thinking_tokens)} thinking` : undefined + ].filter(Boolean).join(' · ') + const total = usage.total_tokens !== undefined ? formatCompactTokenCount(usage.total_tokens) : undefined + if (total || breakdown) parts.push(`Tokens: ${total ? total + (breakdown ? ` (${breakdown})` : '') : breakdown}`) + // agy's input excludes cache reads. + const input = usage.input_tokens + const cached = usage.cache_read_tokens + if (input !== undefined && cached !== undefined && cached > 0 && Number.isSafeInteger(input + cached)) { + parts.push(`Cached input: ${formatPercentage(cached / (input + cached) * 100)}%`) + } + } + const round: string[] = [] + if (summary.durationMs !== undefined) round.push(formatRoundDuration(summary.durationMs)) + const tokensPerSecond = formatTokensPerSecond(summary) + if (tokensPerSecond) round.push(tokensPerSecond) + if (round.length > 0) parts.push(`Round: ${round.join(' · ')}`) + return parts +} + function buildRoundSummaryLabels(summary: RoundSummary, fallbackModel?: string | null): string[] { const parts: string[] = [] const models = Object.keys(summary.modelUsage) const model = models.length > 0 ? models.join(', ') : fallbackModel if (model) parts.push(`${models.length > 1 ? 'Models' : 'Model'}: ${model}`) + if (summary.provider === 'agy') return [...parts, ...buildAgyRoundLabels(summary)] + const isCodex = summary.provider === 'codex' const usage = isCodex && summary.usage ? summary.usage : getRoundUsage(summary) if (usage && (!isCodex || (Number.isSafeInteger(usage.input_tokens) && usage.input_tokens >= 0 @@ -93,12 +130,8 @@ function buildRoundSummaryLabels(summary: RoundSummary, fallbackModel?: string | if (summary.numTurns !== undefined && summary.numTurns > 0) { round.push(`${summary.numTurns} turn${summary.numTurns === 1 ? '' : 's'}`) } - const { generationMs, generationOutputTokens } = summary - if (generationMs !== undefined && Number.isSafeInteger(generationMs) && generationMs > 0 - && generationOutputTokens !== undefined && Number.isSafeInteger(generationOutputTokens) && generationOutputTokens > 0) { - const tokensPerSecond = generationOutputTokens / (generationMs / 1_000) - if (Number.isFinite(tokensPerSecond)) round.push(`${tokensPerSecond.toFixed(1)} tok/s`) - } + const tokensPerSecond = formatTokensPerSecond(summary) + if (tokensPerSecond) round.push(tokensPerSecond) if (round.length > 0) parts.push(`Round: ${round.join(' · ')}`) return parts } diff --git a/web/src/components/NewSession/PermissionField.test.tsx b/web/src/components/NewSession/PermissionField.test.tsx index 0fe13653..ad014fb8 100644 --- a/web/src/components/NewSession/PermissionField.test.tsx +++ b/web/src/components/NewSession/PermissionField.test.tsx @@ -45,6 +45,16 @@ describe('PermissionField', () => { expect(screen.getByText(/did not enable Auto permissions/i)).toBeInTheDocument() }) + it('renders the Antigravity permission modes as a native select', () => { + const onChange = vi.fn() + renderField({ agent: 'agy', nativeValue: 'request-review', onNativeChange: onChange }) + expect(screen.queryByRole('switch')).toBeNull() + expect(screen.getAllByRole('option').map(option => (option as HTMLOptionElement).value)) + .toEqual(['request-review', 'acceptEdits', 'plan', 'always-proceed']) + fireEvent.change(screen.getByRole('combobox'), { target: { value: 'plan' } }) + expect(onChange).toHaveBeenCalledWith('plan') + }) + it('renders Claude permission modes as a native select', () => { const onChange = vi.fn() renderField({ agent: 'claude', nativeValue: 'default', onNativeChange: onChange }) @@ -64,10 +74,13 @@ describe('PermissionField', () => { expect(onChange).toHaveBeenCalledWith('plan') }) - it('renders the YOLO toggle with its native mapping for toggle flavors', () => { - renderField({ agent: 'agy' }) - expect(screen.getByRole('checkbox')).toBeTruthy() - expect(screen.getByText(/applies native Always Proceed mode/i)).toBeInTheDocument() + it('offers every built-in agent with a permission select its native modes, not the YOLO toggle', () => { + for (const agent of ['agy', 'claude', 'codex', 'copilot', 'cursor', 'gemini', 'grok', 'kimi', 'opencode'] as const) { + const { unmount } = renderField({ agent }) + expect(screen.getByRole('combobox')).toBeTruthy() + expect(screen.queryByRole('checkbox')).toBeNull() + unmount() + } }) it('reports Pi permission as managed instead of offering a silent YOLO toggle', () => { diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index 95be1393..2e0f6428 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -1887,18 +1887,38 @@ describe('NewSession launch preferences', () => { } ) - it('persists explicit YOLO toggle edits across remounts', async () => { + it('starts Antigravity on request-review and spawns it with the chosen mode', async () => { savePreferredAgent('agy') - const form = {}} /> - const view = renderWithQuery(form) - await waitFor(() => expect(screen.getByTestId('yolo-toggle')).toHaveTextContent('yolo-off')) - expect(localStorage.getItem('hapi:newSession:yolo')).toBeNull() + mocks.spawnSession.mockResolvedValue({ type: 'success', sessionId: 'agy-session' }) + renderWithQuery( {}} />) + await waitFor(() => expect(screen.getByTestId('permission-mode')).toHaveTextContent('request-review')) - fireEvent.click(screen.getByTestId('yolo-toggle')) - expect(localStorage.getItem('hapi:newSession:yolo')).toBe('true') - view.unmount() - renderWithQuery(form) - await waitFor(() => expect(screen.getByTestId('yolo-toggle')).toHaveTextContent('yolo-on')) + fireEvent.click(screen.getByTestId('permission-mode-plan')) + fireEvent.click(screen.getByTestId('create')) + + await waitFor(() => expect(mocks.onSuccess).toHaveBeenCalledWith('agy-session')) + expect(mocks.spawnSession).toHaveBeenCalledWith(expect.objectContaining({ + agent: 'agy', + permissionMode: 'plan', + yolo: undefined + })) + expect(loadPreferredLaunchSettings('machine-1', 'agy')).toMatchObject({ permissionMode: 'plan' }) + }) + + it.each([ + ['true', 'always-proceed'], + ['false', 'request-review'] + ] as const)('carries a stored YOLO toggle (%s) into the Antigravity mode %s', async (stored, expected) => { + savePreferredAgent('agy') + localStorage.setItem('hapi:newSession:yolo', stored) + mocks.spawnSession.mockResolvedValue({ type: 'success', sessionId: 'agy-session' }) + renderWithQuery( {}} />) + await waitFor(() => expect(screen.getByTestId('permission-mode')).toHaveTextContent(expected)) + fireEvent.click(screen.getByTestId('create')) + await waitFor(() => expect(mocks.spawnSession).toHaveBeenCalledWith(expect.objectContaining({ + agent: 'agy', + permissionMode: expected + }))) }) it('keeps Create disabled while getHubSettings is pending', async () => { diff --git a/web/src/components/NewSession/index.tsx b/web/src/components/NewSession/index.tsx index ff874cfa..c2787b75 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -240,7 +240,7 @@ export function NewSession(props: { setEffort('auto') setModelReasoningEffort('default') setGrokPermissionMode('default') - setNativePermissionMode('default') + setNativePermissionMode(resolvePermissionModeForFlavor('default', agent)) setServiceTier('standard') setCollaborationMode('default') setCopilotAgentMode('interactive') @@ -364,7 +364,7 @@ export function NewSession(props: { ) { const bridged = legacyYoloBridge.enabled ? resolveHapiYoloPermissionMode(targetAgent) - : 'default' + : resolvePermissionModeForFlavor('default', targetAgent) if (bridged) { setNativePermissionMode(bridged) } @@ -1123,7 +1123,7 @@ export function NewSession(props: { setModelReasoningEffort(preferred.modelReasoningEffort) setServiceTier(agent === 'codex' ? preferred.serviceTier ?? 'standard' : 'standard') if (usesSharedPermissionMode) { - setNativePermissionMode(preferred.permissionMode ?? 'default') + setNativePermissionMode(preferred.permissionMode ?? resolvePermissionModeForFlavor('default', agent)) } if (agent === 'grok' && !editedPermissionRef.current) { const hubMode = hubPermissionModeRef.current diff --git a/web/src/components/NewSession/newSessionFormDraft.test.ts b/web/src/components/NewSession/newSessionFormDraft.test.ts index 024c4cd5..fa86f840 100644 --- a/web/src/components/NewSession/newSessionFormDraft.test.ts +++ b/web/src/components/NewSession/newSessionFormDraft.test.ts @@ -18,6 +18,13 @@ describe('newSessionFormDraft', () => { clearNewSessionFormDraft() }) + it('restores an Antigravity draft from the YOLO-toggle era with a mode agy accepts', () => { + sessionStorage.setItem('hapi:new-session-form-draft', JSON.stringify({ agent: 'agy', model: 'auto', yoloMode: false })) + expect(loadNewSessionFormDraft()).toMatchObject({ nativePermissionMode: 'request-review' }) + sessionStorage.setItem('hapi:new-session-form-draft', JSON.stringify({ agent: 'agy', model: 'auto', yoloMode: true })) + expect(loadNewSessionFormDraft()).toMatchObject({ nativePermissionMode: 'always-proceed' }) + }) + it('round-trips cursor model fields through sessionStorage', () => { saveNewSessionFormDraft({ agent: 'cursor', diff --git a/web/src/components/NewSession/newSessionFormDraft.ts b/web/src/components/NewSession/newSessionFormDraft.ts index 07ab9cb6..f29114c3 100644 --- a/web/src/components/NewSession/newSessionFormDraft.ts +++ b/web/src/components/NewSession/newSessionFormDraft.ts @@ -10,6 +10,7 @@ import { type PermissionMode } from '@hapi/protocol' import type { AgentType, LaunchEffort, CodexReasoningEffort, NewSessionServiceTier, SessionType } from './types' +import { resolvePermissionModeForFlavor } from '@hapi/protocol/peerSpawnDefaults' import { LEGACY_YOLO_BRIDGE_AGENTS } from '@/lib/codexFamilyPermissionAgents' const DRAFT_STORAGE_KEY = 'hapi:new-session-form-draft' @@ -86,7 +87,7 @@ export function loadNewSessionFormDraft(): NewSessionFormDraft | null { if (agentPreserved && parsedMode === undefined && parsed.yoloMode && yoloBridgeMode && modes.includes(yoloBridgeMode)) { return yoloBridgeMode } - return 'default' + return resolvePermissionModeForFlavor('default', restoredAgent) })(), grokPermissionMode: agentPreserved && GROK_PERMISSION_MODES.includes(parsed.grokPermissionMode as GrokPermissionMode) diff --git a/web/src/components/NewSession/preferences.ts b/web/src/components/NewSession/preferences.ts index 644bfa27..65dc196d 100644 --- a/web/src/components/NewSession/preferences.ts +++ b/web/src/components/NewSession/preferences.ts @@ -231,7 +231,7 @@ export function resolvePreferredLaunchSettings( && LEGACY_YOLO_BRIDGE_AGENTS.includes(agent) ? (legacyYolo ? resolveHapiYoloPermissionMode(agent) - : 'default') + : resolvePermissionModeForFlavor('default', agent as AgentFlavor)) : null const hubMode = hubPermissionMode ? (() => { @@ -248,10 +248,10 @@ export function resolvePreferredLaunchSettings( : preferredPermissionMode !== undefined // Explicit saved mode that left the launch catalog → Default, // never hub yolo (would upgrade sandboxed → unrestricted). - ? 'default' + ? resolvePermissionModeForFlavor('default', agent as AgentFlavor) : legacyYoloBridgeMode && availablePermissionModes.includes(legacyYoloBridgeMode) ? legacyYoloBridgeMode - : hubMode ?? 'default' + : hubMode ?? resolvePermissionModeForFlavor('default', agent as AgentFlavor) : undefined return { diff --git a/web/src/lib/codexFamilyPermissionAgents.ts b/web/src/lib/codexFamilyPermissionAgents.ts index 288c0c85..260bcfda 100644 --- a/web/src/lib/codexFamilyPermissionAgents.ts +++ b/web/src/lib/codexFamilyPermissionAgents.ts @@ -23,13 +23,14 @@ export function usesCodexFamilyPermissionModes( * Ports: `NewSessionLogic.usesNativePermissionSelect` * (`ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift`, * `android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionForm.kt`). - * claude and grok do not share the codex-family mode set, but they render - * through the same native select. + * claude, grok, cursor and agy do not share the codex-family mode set, but + * they render through the same native select. */ export function usesNativePermissionSelect(flavor: string | null | undefined): boolean { return flavor === 'claude' || flavor === 'grok' || flavor === 'cursor' + || flavor === 'agy' || usesCodexFamilyPermissionModes(flavor) } @@ -50,4 +51,4 @@ export function usesSharedPermissionModeState(flavor: string | null | undefined) * once into the native mode it mapped to; flavors that moved earlier already * settled on 'default' and are intentionally left alone. */ -export const LEGACY_YOLO_BRIDGE_AGENTS: readonly AgentFlavor[] = ['codex', 'claude', 'cursor'] +export const LEGACY_YOLO_BRIDGE_AGENTS: readonly AgentFlavor[] = ['codex', 'claude', 'cursor', 'agy']