From 24348b37a9cafffe43d6ef5483e47f1954e2091c Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 17:55:29 -0800 Subject: [PATCH 1/4] docs(antigravity): plan native terminal support --- docs/plans/2026-11-27-native-agy-terminal.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 docs/plans/2026-11-27-native-agy-terminal.md diff --git a/docs/plans/2026-11-27-native-agy-terminal.md b/docs/plans/2026-11-27-native-agy-terminal.md new file mode 100644 index 000000000..e735d9052 --- /dev/null +++ b/docs/plans/2026-11-27-native-agy-terminal.md @@ -0,0 +1,9 @@ +# Antigravity native terminal + +## Outcome and evidence + +An Antigravity pane in Terminal mode should accept keyboard input in the installed agy terminal interface. In 0.1.9 the provider is marked structured-only and its only registered session starts agy acp on pipes. The installed CLI offers an interactive session and supports resuming a conversation by ID. + +## Change and verification + +Select a PTY-backed interactive agy session for Terminal and keep the existing ACP session for the rendered view. Carry the pane's selected runtime through creation, restoration and switching. Exercise input, resize, exit, runtime selection and the rendered path with focused tests. Smoke-test the installed CLI without submitting a model request. Releasing a new signed build is separate. From d350625ec8d87847f5de8e17d62aac0b8c8c3887 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 18:06:28 -0800 Subject: [PATCH 2/4] docs(antigravity): record native session boundaries and probe results --- docs/decomposition/antigravity-terminal.md | 42 ++++++++++++++++++++ docs/plans/2026-11-27-native-agy-terminal.md | 2 + 2 files changed, 44 insertions(+) create mode 100644 docs/decomposition/antigravity-terminal.md diff --git a/docs/decomposition/antigravity-terminal.md b/docs/decomposition/antigravity-terminal.md new file mode 100644 index 000000000..fb1734c26 --- /dev/null +++ b/docs/decomposition/antigravity-terminal.md @@ -0,0 +1,42 @@ +# Antigravity native terminal + +**Status** — Native prompt and both view transitions verified locally. The release containing this change is pending. +**Approval mode** — The owner requested native agy and authorized staged implementation. Revisit scope with the owner if a solution requires changing their agy settings, submitting a model turn, or modifying the provider's private conversation store. + +## Starting point and outcome + +Agent Code 0.1.9 could drive agy through ACP. That proved the rendered conversation worked. It exposed no interactive terminal for this provider. The owner wants the real prompt inside an Antigravity pane. Terminal should accept native keyboard input, resizing and local commands. Agent view must still render ACP. Opening or changing views must follow the chosen conversation when two panes share a directory. If a handoff fails, the original pane should remain usable. + +## Stage 0 results + +The opt-in [registry-to-prompt probe](../../testing/live/antigravity-terminal.test.ts) exercised the installed macOS CLI through the production provider registry. Two signed-in panes opened in the same directory with distinct IDs. One pane displayed a typed draft, cleared it, ran the native local command `/new` and acquired a third ID. The probe reopened that ID in ACP, then reopened the native prompt while ACP was still running. It submitted zero model prompts. These are observed cases, not a population estimate. + +| Hypothesis | Observation and verdict | +| --- | --- | +| H1. The CLI lacks a terminal interface. | Disproven. The installed CLI painted its own interactive prompt and accepted keyboard input. The restriction belonged to the host. | +| H2. A pane's directory identifies its conversation. | Disproven. The two panes shared a directory and had distinct IDs. | +| H3. An interactive process starting proves it resumed the requested conversation. | Disproven. With one nonexistent ID agy stayed alive and reported that it could not find the conversation. | +| H4. A pane can follow changes inside agy without reading its conversation content. | Observed on this CLI. The native `/new` action emitted a process-local active-conversation record naming the new ID. Other diagnostic records mention unrelated IDs. | + +## Verification stages + +| Boundary | Produces | Independently verified by | Why separate | Real evidence | +| --- | --- | --- | --- | --- | +| 1. CLI and PTY | AntigravityTerminalSession and its registered terminal factory | Read and write through the pseudoterminal, resize, close, and observe exit. Exercise signed-out and slow bootstrap paths separately. | An enabled menu can still launch the headless process. | Installed agy, live prompt, and a controlled child process for error paths. | +| 2. Conversation ownership | terminalIdentity and a per-pane ID | Drive native `/new`, ignore unrelated records and reject a missing explicit resume target. Check the actual provider acknowledgment for a requested resume. | A painted prompt can belong to a different conversation. | Agy's per-process diagnostics and the real missing-ID probe. | +| 3. App handoff | Runtime selection, view picker, restore metadata and guarded replacement | Exercise new panes, saved conversations, previous ACP panes, cancellation, failed successors and activity or identity changes during a switch. | Killing the source early can lose a running turn even if both launchers work. | Actual renderer entry points and the registry probe with overlapping successor and source lifetimes. | +| 4. Distribution boundary | Tested application build and PR | Type-check, build the main process and renderer, run the focused suites and run the opt-in live probe on the combined tree. | A local CLI probe does not verify the application wiring. | Application build and integration test results recorded on the PR. | + +## Ownership and fixtures + +Agy owns conversation IDs. Only the native runtime consumes its per-process diagnostic stream. The identity parser accepts active-conversation metadata, bounds partial lines, and discards unrelated bytes. No renderer or command handler reads those diagnostics or agy's SQLite contents. The registry selects the launcher. The workspace owns view preference, source revalidation and replacement. Automated workers continue to use ACP by default for their session-specific tools. + +The system tests use a contract-probe child for PTY operations and bootstrap failures. The identity examples use the observed agy diagnostic format with substitute IDs. Overlong lines, missing records and interleaved unrelated IDs are deliberate mutations. The live test uses agy's own prompt and local command in a trusted directory. Keep raw logs and user conversation contents out of fixtures. + +## Unknowns and discarded approaches + +1. A future CLI can change its diagnostic format. Keep the positive-resume probe as the compatibility check. A process ID or another pane's files cannot establish which conversation opened. +2. Native agy loads its configured MCP servers. The known mechanism for attaching Agent Code's per-pane tools is ACP. Native mode does not write global or workspace MCP configuration. +3. A signed public build needs its own release. The development evidence applies to this branch. + +The structured-only provider flag, selecting the most recent conversation in the directory, and treating a successful process spawn as a successful resume all failed the observations above. diff --git a/docs/plans/2026-11-27-native-agy-terminal.md b/docs/plans/2026-11-27-native-agy-terminal.md index e735d9052..5d18add47 100644 --- a/docs/plans/2026-11-27-native-agy-terminal.md +++ b/docs/plans/2026-11-27-native-agy-terminal.md @@ -7,3 +7,5 @@ An Antigravity pane in Terminal mode should accept keyboard input in the install ## Change and verification Select a PTY-backed interactive agy session for Terminal and keep the existing ACP session for the rendered view. Carry the pane's selected runtime through creation, restoration and switching. Exercise input, resize, exit, runtime selection and the rendered path with focused tests. Smoke-test the installed CLI without submitting a model request. Releasing a new signed build is separate. + +The staged contracts, evidence and remaining release boundary are recorded in the [native terminal decomposition](../decomposition/antigravity-terminal.md). The decomposition was added after the initial implementation when the owner requested this verification method. From f397242b38b4e577a573e61fc2fbbcbeadcbbc53 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 18:06:55 -0800 Subject: [PATCH 3/4] docs(antigravity): pin explicit resume to observed provider acknowledgment --- docs/decomposition/antigravity-terminal.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/decomposition/antigravity-terminal.md b/docs/decomposition/antigravity-terminal.md index fb1734c26..289c04c20 100644 --- a/docs/decomposition/antigravity-terminal.md +++ b/docs/decomposition/antigravity-terminal.md @@ -18,6 +18,12 @@ The opt-in [registry-to-prompt probe](../../testing/live/antigravity-terminal.te | H3. An interactive process starting proves it resumed the requested conversation. | Disproven. With one nonexistent ID agy stayed alive and reported that it could not find the conversation. | | H4. A pane can follow changes inside agy without reading its conversation content. | Observed on this CLI. The native `/new` action emitted a process-local active-conversation record naming the new ID. Other diagnostic records mention unrelated IDs. | +### Explicit resume probe + +Nine native launches received no user input. Three of three ACP-created empty conversations and three of three conversations selected by a previous native `/new` emitted `conversation_manager.go:] Streaming conversation ` within 380–514 ms. The matching redraw followed within 433–568 ms. Three of three nonexistent IDs emitted `Conversation not found, ignoring --conversation flag` within 260–324 ms. None emitted a matching active-stream record within three seconds. + +**Resume contract.** Only the matching active-stream record establishes a successful explicit handoff. The local store check catches an obviously missing target early. A wrong ID, a refusal, early exit or a timeout cannot retire the source pane. A fresh pane can open the CLI's own sign-in screen without a prior conversation. + ## Verification stages | Boundary | Produces | Independently verified by | Why separate | Real evidence | From e9fe6ec1953f9f6f2d5705bd37f1c9c1ac9b69da Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 18:09:16 -0800 Subject: [PATCH 4/4] fix(antigravity): run the native agy prompt in Terminal view --- ARCHITECTURE.md | 12 +- README.md | 5 +- docs/decomposition/antigravity-terminal.md | 6 + .../remote/RemoteServer.integration.test.ts | 7 +- src/main/remote/RemoteServer.ts | 12 +- src/preload/api/types.ts | 2 +- .../antigravity/runtime/antigravitySession.ts | 5 +- .../antigravityTerminalSession.system.test.ts | 188 +++++++++++++++++ .../runtime/antigravityTerminalSession.ts | 193 ++++++++++++++++++ .../antigravity/runtime/promptDelivery.ts | 2 +- .../antigravity/runtime/terminalIdentity.ts | 57 ++++++ src/providers/registry.main.ts | 4 +- src/remote-client/src/wire.ts | 3 +- .../features/settings/lib/settingsRegistry.ts | 2 +- ...AgentViewModePickerModal.renderer.test.tsx | 14 +- .../workspace/ui/AgentViewModePickerModal.tsx | 45 ++-- .../src/workspace/agentDisplayMode.test.ts | 8 +- .../src/workspace/agentDisplayMode.ts | 35 ++-- src/renderer/src/workspace/control/agents.ts | 2 +- .../src/workspace/control/lifecycle.ts | 2 +- .../control/preferences.renderer.test.tsx | 17 +- .../src/workspace/control/preferences.ts | 13 +- .../actions/mcpPreferences.renderer.test.tsx | 23 +++ .../src/workspace/hook/actions/pane.ts | 19 +- .../src/workspace/hook/actions/session.ts | 27 ++- .../src/workspace/hook/actions/undoClose.ts | 2 +- src/renderer/src/workspace/hook/index.ts | 78 +++++-- .../orchestrationRuntime.renderer.test.tsx | 69 +++++++ .../workspace/terminalOnlyProvider.test.ts | 4 +- .../tile-tree/TileLeaf/useComposerKeybinds.ts | 4 +- src/shared/runtime/terminalSession.ts | 6 +- src/shared/types/providerKind.ts | 26 +-- testing/live/antigravity-terminal.test.ts | 59 ++++++ 33 files changed, 815 insertions(+), 136 deletions(-) create mode 100644 src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts create mode 100644 src/providers/antigravity/runtime/antigravityTerminalSession.ts create mode 100644 src/providers/antigravity/runtime/terminalIdentity.ts create mode 100644 testing/live/antigravity-terminal.test.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f996d5c85..c9cae7888 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -266,16 +266,16 @@ Build aliases resolve most local packages directly from source. Workflow integra Provider selection is exhaustive at several boundaries: main factories and native operations, renderer mapping/rendering capabilities, and setup requirements. Adding a string to a UI picker is insufficient. The source owners are [main registry](src/providers/registry.main.ts), [setup registry](src/providers/registry.setup.ts), [renderer capability registry](src/providers/registry.renderer.capabilities.ts), and [feature capabilities](src/providers/shared/featureCapabilities.ts). -| Property | Claude | Codex | OpenCode structured | OpenCode terminal | Pi (terminal-only) | Hermes (remote chat) | Antigravity (structured, ACP) | +| Property | Claude | Codex | OpenCode structured | OpenCode terminal | Pi (terminal-only) | Hermes (remote chat) | Antigravity (ACP and native TUI) | | --- | --- | --- | --- | --- | --- | --- | --- | -| Native execution | CLI in PTY | CLI in PTY | `opencode serve` spawned by the package | TUI in PTY with its embedded server | `pi` TUI in PTY with Agent Code's bridge extension loaded by `-e` | `hermes serve` on the user's own server; Agent Code launches nothing | `agy acp` spawned by Agent Code; ACP over stdio, no PTY | +| Native execution | CLI in PTY | CLI in PTY | `opencode serve` spawned by the package | TUI in PTY with its embedded server | `pi` TUI in PTY with Agent Code's bridge extension loaded by `-e` | `hermes serve` on the user's own server; Agent Code launches nothing | `agy` in a PTY for Terminal, `agy acp` over stdio for Agent view | | Live observations | Terminal mirror, optional mitmproxy stream | Terminal mirror, rollout events, optional Responses proxy stream | Server SSE bus | TUI server SSE: turns, phases, requests; no streaming text | Bridge events over a private Unix socket: turns, phases, tools, dialogs, session switches; no streaming text | WebSocket JSON-RPC events with a per-session sequence and a replay ring | ACP `session/update` notifications: text, thinking and tool chunks, permission requests; assembled into the semantic vocabulary | | Committed observations | Exact JSONL tail | Attributed rollout tail | Messages assembled from bus part snapshots, plus HTTP history | Read-only SQLite event log | Session JSONL tree, active branch only | `session.history` rows, fetched after each settled turn | Rows cut per conversation segment with ordinal keys `ag::`, held in memory by the live session; agy's SQLite store is never read | | Native identity | UUID selected before launch/resume | Exact rollout/thread identity, proven before tailing | `ses_...` | Pre-created `ses_...` | UUID passed as `--session-id`; the pane follows `/new`, `/resume` and `/fork` inside the TUI | Hermes' stored session id, created by the server; the pane follows `/new` | agy assigns the id at `session/new`; resume is `session/load`, which replays the conversation as a history reset | | Prompt path | Readiness, absorption and durable acceptance transaction | Attested PTY delivery profile | HTTP `prompt_async`, text only | Keyboard to PTY; programmatic prompts through the TUI server with the session's agent, model and variant | Keyboard to PTY; programmatic prompts through the bridge (`sendUserMessage` as follow-up), acknowledged only by Pi's own evidence | `prompt.submit` over the socket; slash commands through `slash.exec` | ACP `session/prompt`, queued behind a running turn; text only; Esc sends `session/cancel` | | App saved-session listing | Supported | Supported | Not implemented | Not a separate listing capability | Supported (conversation catalog) | Not implemented; a pane resumes its own conversation | Supported (conversation catalog through `session/list`) | | Accepted upstream version | 2.1.263 | 0.149.1 | Not pinned by the package | 1.18.30 | 0.87.1 | v0.21.7 (desktop contract 8, minimum 7) | 1.5.15 (recorded live) | -| Native terminal view | Available | Available | Not a PTY | Required; the pane always shows the TUI | Required; Pi has no other surface | None; the pane is always a chat | None in Agent Code; the pane is always the rendered feed. `agy --conversation ` opens the same conversation in agy's TUI | +| Native terminal view | Available | Available | Not a PTY | Required; the pane always shows the TUI | Required; Pi has no other surface | None; the pane is always a chat | Available through the native agy terminal runtime | #### 5.3.1 Observing a process Agent Code does not control @@ -773,7 +773,7 @@ Sources: [Hermes runtime adapter](src/providers/hermes/runtime), [connections](s #### 5.3.8 antigravity-acp-headless -Antigravity (the `agy` CLI, `antigravity.google/cli`) is Google's replacement for Gemini CLI for personal accounts: Gemini CLI stopped serving them on 2026-06-18. agy has no PTY hook, no socket and no transcript file that a host could observe. Its conversations live in private SQLite (`~/.gemini/antigravity-cli/conversations/.db`) owned by a closed binary that updates itself. What it does ship is a supported integration surface, `agy acp`: the Agent Client Protocol, JSON-RPC over newline-delimited stdio. So Agent Code does not run the agy TUI in a PTY and watch it. It spawns `agy acp` and is the ACP client. `packages/antigravity-acp-headless` owns the protocol and the row assembly. Agent Code spawns the process; the package's session class never spawns or kills, and `stop()` only closes the protocol. +Antigravity (the `agy` CLI, `antigravity.google/cli`) is Google's replacement for Gemini CLI for personal accounts: Gemini CLI stopped serving them on 2026-06-18. agy has no PTY hook, no socket and no transcript file that a host could observe. Its conversations live in private SQLite (`~/.gemini/antigravity-cli/conversations/.db`) owned by a closed binary that updates itself. What it does ship is a supported integration surface, `agy acp`: the Agent Client Protocol, JSON-RPC over newline-delimited stdio. Terminal view runs the interactive agy TUI in a PTY. The rendered view spawns `agy acp` and acts as the ACP client. `packages/antigravity-acp-headless` owns the protocol and the row assembly. Agent Code spawns the process; the package's session class never spawns or kills, and `stop()` only closes the protocol. | Concern | Owner and rule | | --- | --- | @@ -786,7 +786,7 @@ Antigravity (the `agy` CLI, `antigravity.google/cli`) is Google's replacement fo | Built-in MCP | agy advertises no HTTP MCP capability, so Agent Code's per-session HTTP endpoint reaches agy as a stdio server: `mcpProxy.mjs`, started by agy through Electron in node mode. Endpoint URLs and header values travel in the server's `env` list (one variable per header), never in argv, and nothing is written to agy's own MCP config. With no servers configured the proxy is a valid server with zero tools | | History | A renderer reload or phone backfill adopts the running session and is served its in-memory rows back, so later live rows dedupe by key. A pane that is not live (the catalog preview, `read_agent` on a closed agent) replays the conversation through a short-lived `agy acp` and `session/load`, which makes no model call. Locator: `antigravity://session/` | | Catalog | `session/list`, following cursors up to 100 pages, in a short-lived `agy acp`. It also lists conversations made in agy's TUI, because ACP and the TUI share one store. agy reports the cwd of ACP-created sessions percent-encoded, so it is decoded only when the result is still an absolute path. A missing agy lists nothing rather than failing the catalog | -| Surface | `STRUCTURED_ONLY_PROVIDER_KINDS` pins the pane to the rendered feed, like structured OpenCode, but it is the coding feed, not Hermes' chat surface. `agy --conversation ` opens the same conversation in agy's own TUI, which is the verified external resume command | +| Surface | Terminal renders agy's own TUI. Agent view renders ACP events. `agy --conversation ` opens a known conversation in the native TUI | | Skills | Project skills are discovered from `.agents/skills` up to the git root. agy's personal skills folder is undocumented, so personal skills are declared unsupported rather than deployed to a place agy may not read | Rewind, duplicate and provider switching are off (`featureCapabilities.ts`). Each needs to write a conversation agy will resume, and the only place agy keeps one is the private SQLite schema. A command that no-ops or corrupts a conversation is worse than a missing command. The catalog, prompt history extraction and resume-in-app stay on, because they only read. @@ -2204,7 +2204,7 @@ class Shadow caution #### 8.3.1 Why the conversation must be reconstructed -Agent Code does not use a provider SDK or act as an API client for a user's subscription. Provider subscription OAuth is not available to a third-party application, and an SDK integration would also replace the native experience: slash commands, compaction, permission prompts, resume and authentication would become Agent Code reimplementations. Instead, the application runs the provider's own client and observes it. Claude Code and Codex run as CLIs inside a pseudo-terminal. Structured OpenCode runs as its native HTTP/SSE service, and OpenCode terminal mode runs its TUI in a PTY. Antigravity runs `agy acp` and speaks the Agent Client Protocol over stdio, with no PTY. +Agent Code does not use a provider SDK or act as an API client for a user's subscription. Provider subscription OAuth is not available to a third-party application, and an SDK integration would also replace the native experience: slash commands, compaction, permission prompts, resume and authentication would become Agent Code reimplementations. Instead, the application runs the provider's own client and observes it. Claude Code and Codex run as CLIs inside a pseudo-terminal. Structured OpenCode runs as its native HTTP/SSE service, and OpenCode terminal mode runs its TUI in a PTY. Antigravity runs its native TUI in a pseudo-terminal or uses `agy acp` over stdio for the rendered view. Observation has a price. The same assistant message can exist simultaneously as a live semantic stream, retained semantic history, one or more committed transcript records, and a provisional ghost. A user's prompt can exist as a local optimistic echo, a native queue record and a committed message. These copies arrive on different channels, at different times, with different clocks and incompatible identifiers. Codex proxy events use `resp_*` ids that never match rollout ids. Any channel can also stall or die permanently; the committed tail is sometimes the only one that does. diff --git a/README.md b/README.md index 79805564d..9487686bf 100644 --- a/README.md +++ b/README.md @@ -152,9 +152,8 @@ program from the outside — the terminal screen, the model stream, the transcri files on disk and the process — and expose it as an API. Agent Code reconciles those observations into one conversation and renders it in React, without replacing the agent loop underneath. -Antigravity is the exception to the PTY shape: Agent Code runs `agy acp` and -speaks the Agent Client Protocol with it through `antigravity-acp-headless`, so -there is no terminal to attach. +Antigravity’s Terminal view runs the interactive `agy` CLI in a PTY. Its Agent +view uses `agy acp` to render the conversation through the Agent Client Protocol. [`agent-transcript-parser`](https://github.com/Juliusolsson05/agent-transcript-parser) translates transcripts between harnesses, which is what makes switching, diff --git a/docs/decomposition/antigravity-terminal.md b/docs/decomposition/antigravity-terminal.md index 289c04c20..db4bdaf6d 100644 --- a/docs/decomposition/antigravity-terminal.md +++ b/docs/decomposition/antigravity-terminal.md @@ -46,3 +46,9 @@ The system tests use a contract-probe child for PTY operations and bootstrap fai 3. A signed public build needs its own release. The development evidence applies to this branch. The structured-only provider flag, selecting the most recent conversation in the directory, and treating a successful process spawn as a successful resume all failed the observations above. + +## Outcome and deviations + +The first native implementation already existed when the owner requested staged verification. The staged probe found a real handoff gap. Six regression cases failed when process startup alone counted as a successful resume. They passed after explicit resume started waiting for agy's matching ID. In a disposable copy, disabling three renderer guards also reproduced four failures: the new-pane runtime default, the preference command restarting a process, and failure to preserve a source whose conversation or turn changed. + +The combined live probe also reopens the rendered conversation in its native successor before the source exits. The native successor confirms its selection even before the new renderer can answer terminal queries. To repeat in an already trusted directory with a signed-in CLI, set `ANTIGRAVITY_TERMINAL_LIVE=1` and `ANTIGRAVITY_LIVE_CWD` and run `npx vitest run --config vitest.live.config.ts testing/live/antigravity-terminal.test.ts`. The probe creates empty conversations and submits only agy's local `/new` command. diff --git a/src/main/remote/RemoteServer.integration.test.ts b/src/main/remote/RemoteServer.integration.test.ts index f0066c07d..844d7457c 100644 --- a/src/main/remote/RemoteServer.integration.test.ts +++ b/src/main/remote/RemoteServer.integration.test.ts @@ -313,17 +313,18 @@ describe('v2 session summary overlays', () => { } } - it('overlays title, agent name, tab, pin and the OpenCode runtime onto summaries', async () => { + it('overlays title, agent name, tab, pin and the selected native runtime onto summaries', async () => { const workspace = fakeWorkspace([ ['s-oc', { title: 'Shell rewrite', agentName: 'Apollo', tabTitle: 'agent-code', pinned: true, tldrIdentity: 't1', cwd: '/dev/agent-code', kind: 'opencode' }], ['s-cl', { title: null, agentName: null, tabTitle: null, pinned: false, tldrIdentity: null, cwd: null, kind: 'claude' }], ]) ;(manager.getSpawnProviderRuntime as ReturnType).mockImplementation( - (sessionId: string) => (sessionId === 's-oc' ? 'terminal' : null), + (sessionId: string) => (sessionId === 's-oc' || sessionId === 's-ag' ? 'terminal' : null), ) await restartServer({ workspace: workspace.model }) try { manager.emit('started', { sessionId: 's-oc', kind: 'opencode', projectDir: '/dev/agent-code' }) + manager.emit('started', { sessionId: 's-ag', kind: 'antigravity', projectDir: '/dev/agent-code' }) manager.emit('started', { sessionId: 's-cl', kind: 'claude', projectDir: '/dev/x' }) const { ws, frames } = await openAuthed() await waitFor(frames, f => framesOfType(f, 'session-list').length > 0) @@ -338,7 +339,7 @@ describe('v2 session summary overlays', () => { pinned: true, providerRuntime: 'terminal', }) - // Runtime is stamped ONLY on the provider that has two runtimes. + expect(sessions.find(s => s.sessionId === 's-ag')).toMatchObject({ providerRuntime: 'terminal' }) expect(cl).toMatchObject({ title: null, agentName: null, pinned: false }) expect('providerRuntime' in (cl ?? {})).toBe(false) ws.close() diff --git a/src/main/remote/RemoteServer.ts b/src/main/remote/RemoteServer.ts index ea2545d26..41af687c2 100644 --- a/src/main/remote/RemoteServer.ts +++ b/src/main/remote/RemoteServer.ts @@ -15,7 +15,7 @@ import type { AppRunJournal } from '@main/incident/AppRunJournal.js' import type { ResolveConditionResult } from '@shared/sessionFeed/types.js' import type { ConditionCustomAction } from '@shared/conditions-core/contract.js' import type { SessionKind, AgentProviderRuntime } from '@shared/types/providerKind.js' -import { isAgentProviderKind, isTerminalOnlyProviderKind } from '@shared/types/providerKind.js' +import { isAgentProviderKind, providerOffersTerminalRuntime } from '@shared/types/providerKind.js' import type { PromptDeliveryResult } from '@shared/types/providerConfig.js' import type { SessionBackendSnapshot } from '@shared/types/session.js' import type { RemoteSessionIdentity } from './workspaceProjection.js' @@ -952,7 +952,7 @@ export class RemoteServer extends EventEmitter { } /** Session summaries with the v2 identity overlays: projection-provided - * title/agentName/tabTitle/pinned, plus the OpenCode runtime so the phone + * title/agentName/tabTitle/pinned, plus the selected runtime so the phone * can label the TUI runtime honestly. Every overlay is additive — a * missing projection or an old manager interface degrades field-by-field * to the v1 summary, never to an error. */ @@ -972,12 +972,8 @@ export class RemoteServer extends EventEmitter { pinned: identity.pinned, } : {}), - // Runtime only means something for a provider whose pane can be its - // native TUI: OpenCode (two runtimes) and the terminal-only ones (Pi, - // always 'terminal' — main normalizes it at spawn). Stamping - // 'terminal'-vs-null onto claude/codex rows would conflate the - // discriminator with the plain-shell session kind. - ...(summary.kind === 'opencode' || isTerminalOnlyProviderKind(summary.kind) ? { providerRuntime: runtime } : {}), + // Include the runtime only for providers which expose it as part of their launch contract. + ...(isAgentProviderKind(summary.kind) && providerOffersTerminalRuntime(summary.kind) ? { providerRuntime: runtime } : {}), ...(subAgentCount !== null ? { subAgentCount } : {}), } }) diff --git a/src/preload/api/types.ts b/src/preload/api/types.ts index cf38037bd..c257fdf20 100644 --- a/src/preload/api/types.ts +++ b/src/preload/api/types.ts @@ -191,7 +191,7 @@ export type { export type SessionSpawnOptions = { /** Which kind of session to spawn. Defaults to 'claude' in main. */ kind?: SessionKind - /** Alternate agent execution runtime. Currently supported by OpenCode only. */ + /** Alternate agent execution runtime when the provider offers a native terminal. */ providerRuntime?: AgentProviderRuntime cwd: string cols?: number diff --git a/src/providers/antigravity/runtime/antigravitySession.ts b/src/providers/antigravity/runtime/antigravitySession.ts index b9ed7a656..67b85a993 100644 --- a/src/providers/antigravity/runtime/antigravitySession.ts +++ b/src/providers/antigravity/runtime/antigravitySession.ts @@ -41,9 +41,8 @@ export interface AntigravitySession { /** * Google Antigravity (the `agy` CLI) as a structured provider: Agent Code * spawns `agy acp` and drives it over the Agent Client Protocol through - * antigravity-acp-headless. There is no PTY: the pane is the rendered feed - * (STRUCTURED_ONLY_PROVIDER_KINDS), and the same conversation opens in agy's - * own TUI with `agy --conversation ` because both share agy's store. + * antigravity-acp-headless. This runtime powers the rendered feed. The terminal + * runtime opens the same conversation in agy's interactive TUI with `agy --conversation ` because both share agy's store. * * Auth is agy's own: the user signs in once in agy (Google account, AI * Pro/Ultra plans included); Agent Code never sees a credential. diff --git a/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts b/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts new file mode 100644 index 000000000..9e6ff2bbb --- /dev/null +++ b/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts @@ -0,0 +1,188 @@ +import { once } from 'node:events' +import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +import { AntigravityTerminalSession } from './antigravityTerminalSession.js' + +// Exercise the two real process boundaries: a short-lived ACP stdio process allocates an +// identity, followed by an interactive child with a real PTY in the chosen working directory. +const requestedId = '11111111-1111-4111-8111-111111111111' +const agy = String.raw`#!/usr/bin/env node +const args = process.argv.slice(2) +if (args[0] === 'acp') { + require('node:readline').createInterface({input:process.stdin}).on('line', line => { + const req = JSON.parse(line) + if (process.env.AGY_TEST_AUTH === 'hang') return + const err = req.method === 'session/new' && process.env.AGY_TEST_AUTH === 'missing' + console.log(JSON.stringify({jsonrpc:'2.0', id:req.id, ...(err + ? {error:{code:-32000,message:'Authentication required'}} + : {result:req.method === 'initialize' ? {protocolVersion:1} : {sessionId:'allocated-in-this-pane'}})})) + }) +} else { + const log = args[1] + if (args[0] !== '--log-file' || !require('node:fs').statSync(log).isFIFO()) process.exit(3) + const fs = require('node:fs') + const id = args[3] + const record = (severity, text) => fs.appendFileSync(log, severity + '1127 18:00:58.732484 1235 ' + text + '\n') + const stream = id => record('I', 'conversation_manager.go:1282] Streaming conversation ' + id) + if (id) { + fs.writeFileSync('launch-pipe-path', log) + switch (process.env.AGY_TEST_ACK) { + case 'hold': { + // A listing mentioning the exact target also occurs for conversations merely browsed. + record('I', 'server.go:3530] GetConversationDetail: found conversation ' + id + ' (active=false)') + const timer = setInterval(() => { + if (!fs.existsSync('confirm-resume')) return + clearInterval(timer) + stream(id) + }, 10) + break + } + case 'other': stream('00000000-0000-0000-0000-000000000004'); break + case 'refused': record('W', 'projectresolve.go:74] Conversation ' + id + ' not found, ignoring --conversation flag'); break + case 'exit': process.exit(3); break + default: stream(id) + } + } + process.stdin.setRawMode(true) + process.stdout.write('TUI:' + JSON.stringify(args.slice(2)) + ':' + process.stdout.columns + 'x' + process.stdout.rows) + process.stdout.on('resize', () => process.stdout.write('SIZE:' + process.stdout.columns + 'x' + process.stdout.rows)) + process.stdin.on('data', d => { + if (d.toString() === 'q') return process.exit(0) + if (d.toString() === 'n') { + const prefix = 'I1127 18:00:58.732484 1235 ' + require('node:fs').appendFileSync(log, prefix + 'server.go:3530] GetConversationDetail: found conversation 00000000-0000-0000-0000-000000000001 (active=false)\n' + + 'x'.repeat(300) + prefix + 'conversation_manager.go:1282] Streaming conversation 00000000-0000-0000-0000-000000000002\n' + + prefix + 'conversation_manager.go:1282] Streaming conversation 00000000-0000-0000-0000-000000000003\n') + } + process.stdout.write('INPUT:' + d.toString()) + }) +}` + +let cwd: string +let binary: string +let session: AntigravityTerminalSession | undefined +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), 'agent-code-agy-terminal-')) + binary = join(cwd, 'fake agy') + await writeFile(binary, agy, { mode: 0o755 }) +}) +afterEach(async () => { + await session?.stop() + await rm(cwd, { recursive: true, force: true }) +}) + +it.each([ + { resume: undefined, auth: 'present', id: 'allocated-in-this-pane' }, + { resume: requestedId, auth: 'missing', id: requestedId }, + { resume: undefined, auth: 'missing', id: null }, + { resume: undefined, auth: 'hang', id: null }, +])('opens native agy with resume=$resume and auth=$auth', async ({ resume, auth, id }) => { + const conversations = join(cwd, '.gemini', 'antigravity-cli', 'conversations') + if (resume) { + await mkdir(conversations, { recursive: true }) + await writeFile(join(conversations, resume + '.db'), '') + } + session = new AntigravityTerminalSession({ binary, cwd, resumeSessionId: resume, env: { GEMINI_CLI_HOME: cwd, AGY_TEST_AUTH: auth } }, { prepareTimeoutMs: auth === 'hang' ? 300 : 5000 }) + const changes: string[] = [] + session.on('provider-session-changed', event => changes.push(event.providerSessionId)) + let output = '' + session.on('pty-data', chunk => { output += chunk }) + expect(session.write('x')).toBe(false) + session.resize(90, 30) + await session.start() + await vi.waitFor(() => expect(output).toContain('TUI:' + JSON.stringify(id ? ['--conversation', id] : []) + ':90x30')) + expect(session.getProviderSessionId()).toBe(id) + expect(session.getProcessPid()).toBeGreaterThan(0) + expect(session.write('x')).toBe(true) + await vi.waitFor(() => expect(output).toContain('INPUT:x')) + session.resize(101, 40) + await vi.waitFor(() => expect(output).toContain('SIZE:101x40')) + expect(changes).toEqual([]) + session.write('n') + await vi.waitFor(() => expect(changes).toEqual(['00000000-0000-0000-0000-000000000003'])) + expect(session.getProviderSessionId()).toBe(changes[0]) + const exit = once(session, 'exit') + session.write('q') + expect(await exit).toMatchObject([{ exitCode: 0 }]) + expect(session.isExited()).toBe(true) + expect(session.write('x')).toBe(false) +}) + +it('does not start a terminal when the pane closes during identity allocation', async () => { + let finish!: (id: string) => void + const allocate = vi.fn(() => new Promise(resolve => { finish = resolve })) + session = new AntigravityTerminalSession({ binary, cwd }, { allocate }) + const starting = session.start() + await session.stop() + finish('unused') + await starting + expect(session.getProcessPid()).toBeNull() + expect(session.isExited()).toBe(true) +}) + + +it('rejects a missing explicit conversation before creating its replacement terminal', async () => { + const started = vi.fn() + session = new AntigravityTerminalSession({ binary, cwd, resumeSessionId: 'removed', env: { GEMINI_CLI_HOME: cwd } }) + session.on('started', started) + await expect(session.start()).rejects.toThrow('conversation is unavailable') + expect(started).not.toHaveBeenCalled() + expect(session.getProcessPid()).toBeNull() + expect(session.getProviderSessionId()).toBeNull() +}) + + +async function prepareExplicit(ack: string, resumeTimeoutMs: number) { + const conversations = join(cwd, '.gemini', 'antigravity-cli', 'conversations') + await mkdir(conversations, { recursive: true }) + await writeFile(join(conversations, requestedId + '.db'), '') + session = new AntigravityTerminalSession({ + binary, cwd, resumeSessionId: requestedId, + env: { GEMINI_CLI_HOME: cwd, AGY_TEST_ACK: ack }, + }, { resumeTimeoutMs }) + return session +} + +it('waits for the exact native selection before publishing identity, readiness or started', async () => { + const candidate = await prepareExplicit('hold', 3000) + const start = vi.fn() + const ready = vi.fn() + candidate.on('started', start) + candidate.on('input-readiness', input => { if (input.ready) ready() }) + const painted = once(candidate, 'pty-data') + const completion = candidate.start() + await painted + expect(start).not.toHaveBeenCalled() + expect(ready).not.toHaveBeenCalled() + expect(candidate.getProviderSessionId()).toBeNull() + await writeFile(join(cwd, 'confirm-resume'), '') + await completion + expect(start).toHaveBeenCalledOnce() + expect(ready).toHaveBeenCalledOnce() + expect(candidate.getProviderSessionId()).toBe(requestedId) +}) + +it.each([ + ['other', 'different conversation'], + ['refused', 'unavailable'], + ['exit', 'exited'], + ['hold', 'timed out'], + ['cancel', 'cancelled'], +])('disposes only the unconfirmed candidate on %s', async (mode, expected) => { + const candidate = await prepareExplicit(mode === 'cancel' ? 'hold' : mode, mode === 'hold' ? 600 : 3000) + const started = vi.fn() + candidate.on('started', started) + const painted = mode === 'cancel' ? once(candidate, 'pty-data') : null + const outcome = candidate.start().then(() => 'started', error => (error as Error).message) + if (painted) { await painted; await candidate.stop() } + expect(await outcome).toContain(expected) + expect(started).not.toHaveBeenCalled() + expect(candidate.getProviderSessionId()).toBeNull() + expect(candidate.getProcessPid()).toBeNull() + const fifo = await readFile(join(cwd, 'launch-pipe-path'), 'utf8') + await expect(access(fifo)).rejects.toMatchObject({ code: 'ENOENT' }) +}) diff --git a/src/providers/antigravity/runtime/antigravityTerminalSession.ts b/src/providers/antigravity/runtime/antigravityTerminalSession.ts new file mode 100644 index 000000000..79133f3ec --- /dev/null +++ b/src/providers/antigravity/runtime/antigravityTerminalSession.ts @@ -0,0 +1,193 @@ +import { spawn } from 'node:child_process' +import { EventEmitter } from 'node:events' +import { AntigravityAcpSession, antigravityConversationExists } from 'antigravity-acp-headless' + +import { TerminalSession } from '@shared/runtime/terminalSession.js' +import type { AgentSession, SessionOptions } from '@shared/types/session.js' +import { openAntigravityIdentityPipe } from './terminalIdentity.js' +import { antigravityTranscriptLocator } from './antigravityHistory.js' + +/** Allocate an exact conversation before launching the TUI so reopening two panes in one directory + * cannot attach either pane to the other's most recent conversation. No prompt is submitted. */ +async function allocateConversation(binary: string, options: SessionOptions, signal: AbortSignal): Promise { + const env = { ...process.env, ...options.env } + const child = spawn(binary, ['acp'], { + cwd: options.cwd, env, stdio: ['pipe', 'pipe', 'ignore'], signal, + }) + const failed = new Promise((_, reject) => child.once('error', reject)) + const closed = new Promise(resolve => child.once('close', () => resolve())) + const acp = new AntigravityAcpSession({ input: child.stdout, output: child.stdin, cwd: options.cwd }) + try { + return (await Promise.race([acp.start(), failed])).sessionId + } finally { + await acp.stop() + child.stdin.end() + child.kill() + // Release the temporary ACP writer before agy opens the same store in its interactive mode. + const timer = setTimeout(() => child.kill('SIGKILL'), 1000) + try { await closed } finally { clearTimeout(timer) } + } +} + +type TerminalDeps = { + allocate?: typeof allocateConversation + prepareTimeoutMs?: number + resumeTimeoutMs?: number +} + +export class AntigravityTerminalSession extends EventEmitter implements AgentSession { + private readonly startup = new AbortController() + private terminal: TerminalSession | null = null + private observer: ReturnType | null = null + private started = false + private exited = false + private providerSessionId: string | null = null + private cols: number + private rows: number + + constructor(private readonly options: SessionOptions, private readonly deps: TerminalDeps = {}) { + super() + this.cols = options.cols ?? 120 + this.rows = options.rows ?? 40 + } + + async start(): Promise { + if (this.started) throw new Error('AntigravityTerminalSession already started') + this.started = true + this.emit('input-readiness', { ready: false, reason: 'starting' }) + const binary = this.options.binary ?? 'agy' + const requested = this.options.resumeSessionId + if (requested) { + // agy silently ignores an unknown --conversation and opens a blank prompt. During a mode + // switch that would falsely claim success, retiring the pane the user was trying to keep. + const env = { ...process.env, ...this.options.env } + if (!antigravityConversationExists(requested, env, env.HOME)) throw new Error('The Antigravity conversation is unavailable. Open a new pane to start a fresh conversation.') + } else { + const deadline = AbortSignal.timeout(this.deps.prepareTimeoutMs ?? 5000) + try { + const id = await (this.deps.allocate ?? allocateConversation)(binary, this.options, AbortSignal.any([this.startup.signal, deadline])) + if (this.startup.signal.aborted) return + this.providerSessionId = id + } catch { + if (this.startup.signal.aborted) return + // Authentication, a stuck ACP startup or an incompatible ACP version should never hide + // agy's working interactive prompt. Its own identity stream will bind the conversation. + this.emit('transcript-diagnostic', { kind: 'antigravity-native-preallocation-unavailable' }) + } + } + if (this.startup.signal.aborted) return + const id = requested ?? this.providerSessionId + // A live PTY can paint a perfectly usable *different* prompt after agy ignores an invalid + // selection. Only agy's own positive selection may complete an explicit handoff. + let awaitingResume = Boolean(requested) + let confirm!: () => void + let reject!: (error: Error) => void + const selection = awaitingResume ? new Promise((ok, fail) => { confirm = ok; reject = fail }) : undefined + const failResume = (message: string) => { + if (awaitingResume) reject(new Error(message)) + } + this.observer = openAntigravityIdentityPipe({ + active: next => { + if (this.startup.signal.aborted || this.exited) return + if (awaitingResume) { + if (next === requested) confirm() + else failResume('Antigravity opened a different conversation.') + return + } + if (this.providerSessionId === next) return + this.providerSessionId = next + const transcriptFile = antigravityTranscriptLocator(next) + this.emit('provider-session-changed', { providerSessionId: next, transcriptFile, reason: 'antigravity-native-conversation' }) + this.emit('jsonl-entry', { type: 'antigravity-identity', sessionId: next }, transcriptFile) + }, + missing: missing => { + if (missing === requested) failResume('The requested Antigravity conversation is unavailable.') + }, + error: () => { + failResume('Could not verify the requested Antigravity conversation.') + this.emit('transcript-diagnostic', { kind: 'antigravity-native-identity-unavailable' }) + }, + }) + const args = ['--log-file', this.observer.path] + if (id) args.push('--conversation', id) + const options = { + shell: binary, args, cwd: this.options.cwd, + cols: this.cols, rows: this.rows, env: this.options.env, + } + const terminal = new TerminalSession(options) + this.terminal = terminal + terminal.on('data', data => this.emit('pty-data', data)) + // The terminal can accept human input, including sign-in and trust choices, as soon as the + // PTY is running. Automated prompt delivery is a separate ACP-only capability. + let painted = false + terminal.once('data', () => { + painted = true + if (!awaitingResume && !this.startup.signal.aborted && !this.exited) this.emit('input-readiness', { ready: true, reason: 'ready' }) + }) + terminal.on('exit', exit => { + this.exited = true + failResume('Antigravity exited before confirming the requested conversation.') + this.emit('input-readiness', { ready: false, reason: 'provider-not-ready' }) + this.closeObserver() + this.emit('exit', exit) + }) + const cancel = () => failResume('Antigravity conversation resume was cancelled.') + const timer = selection && setTimeout(() => failResume('Antigravity timed out confirming the requested conversation.'), this.deps.resumeTimeoutMs ?? 10_000) + this.startup.signal.addEventListener('abort', cancel, { once: true }) + try { + await Promise.all([terminal.start(), selection]) + if (requested) { + if (this.startup.signal.aborted) throw new Error('Antigravity conversation resume was cancelled.') + if (this.exited) throw new Error('Antigravity exited during conversation resume.') + this.providerSessionId = requested + if (painted) this.emit('input-readiness', { ready: true, reason: 'ready' }) + } + } catch (error) { + this.exited = true + await terminal.stop() + this.closeObserver() + throw error + } finally { + awaitingResume = false + this.startup.signal.removeEventListener('abort', cancel) + clearTimeout(timer) + } + if (this.startup.signal.aborted || this.exited) return + if (id) { + const transcriptFile = antigravityTranscriptLocator(id) + this.emit('jsonl-entry', { type: 'antigravity-identity', sessionId: id }, transcriptFile) + } + this.emit('started', {}) + } + + write(data: string): boolean { + if (!this.terminal || this.exited || this.startup.signal.aborted) return false + this.terminal.write(data) + return true + } + + resize(cols: number, rows: number): void { + if (cols < 1 || rows < 1) return + this.cols = cols + this.rows = rows + this.terminal?.resize(cols, rows) + } + + async stop(): Promise { + this.startup.abort() + await this.terminal?.stop() + this.closeObserver() + } + + private closeObserver(): void { + this.observer?.close() + this.observer = null + } + + getProcessPid(): number | null { return this.terminal?.getProcessPid() ?? null } + isExited(): boolean { return this.exited || this.startup.signal.aborted } + getProviderSessionId(): string | null { return this.providerSessionId } + getTranscriptFile(): string | null { + return this.providerSessionId ? antigravityTranscriptLocator(this.providerSessionId) : null + } +} diff --git a/src/providers/antigravity/runtime/promptDelivery.ts b/src/providers/antigravity/runtime/promptDelivery.ts index ebb7d8f49..6fa16ce28 100644 --- a/src/providers/antigravity/runtime/promptDelivery.ts +++ b/src/providers/antigravity/runtime/promptDelivery.ts @@ -17,7 +17,7 @@ export async function deliverAntigravityPrompt(io: PromptDeliveryIo): Promise void + missing: (id: string) => void + error: () => void +}) { + const dir = mkdtempSync(join(tmpdir(), 'agent-code-agy-')) + const path = join(dir, 'session.fifo') + let fd: number | undefined + let stream: Socket + try { + execFileSync('/usr/bin/mkfifo', ['-m', '600', path], { timeout: 2000, stdio: 'ignore' }) + fd = openSync(path, constants.O_RDWR | constants.O_NONBLOCK) + stream = new Socket({ fd, readable: true, writable: false }) + } catch (error) { + if (fd !== undefined) closeSync(fd) + rmSync(dir, { recursive: true, force: true }) + throw error + } + // Unrelated log lines can be arbitrarily long. Keep at most the length of a short metadata + // record across chunks, discarding the remainder (including partial suffixes) until newline. + let partial: string | null = '' + stream.setEncoding('utf8') + stream.on('data', (chunk: string) => { + const parts = chunk.split('\n') + for (const [index, part] of parts.entries()) { + partial = partial !== null && partial.length + part.length <= 256 ? partial + part : null + if (index < parts.length - 1) { + const id = partial && activeStream.exec(partial)?.[1] + if (id) listeners.active(id) + else { + const missing = partial && missingTarget.exec(partial)?.[1] + if (missing) listeners.missing(missing) + } + partial = '' + } + } + }) + stream.on('error', listeners.error) + return { path, close() { + stream.destroy() + rmSync(dir, { recursive: true, force: true }) + } } +} diff --git a/src/providers/registry.main.ts b/src/providers/registry.main.ts index 561d11843..9bd5d1b27 100644 --- a/src/providers/registry.main.ts +++ b/src/providers/registry.main.ts @@ -23,6 +23,7 @@ import { resolvePiBridgeScript } from '@providers/pi/runtime/bridgeScript.js' import { loadPiHistoryChunk } from '@providers/pi/runtime/piHistory.js' import { resolvePiSessionFile } from 'pi-terminal-headless' import { getToolPath } from '@main/setup/toolchain.js' +import { AntigravityTerminalSession } from '@providers/antigravity/runtime/antigravityTerminalSession.js' import { AntigravitySession } from '@providers/antigravity/runtime/antigravitySession.js' import { deliverAntigravityPrompt } from '@providers/antigravity/runtime/promptDelivery.js' import { discoverAntigravitySkillRoots } from '@providers/antigravity/runtime/skillDiscovery.js' @@ -254,9 +255,8 @@ const antigravityMain: MainProviderConfig = { supported: false, reason: 'Antigravity reads project skills from .agents/skills; its personal skill folder is not documented, so Agent Code does not deploy personal skills to it.', }, - // One runtime: `agy acp` (ACP over stdio), structured, no PTY - // (STRUCTURED_ONLY_PROVIDER_KINDS pins the pane to the rendered feed). createSession: (opts) => new AntigravitySession(opts), + createTerminalSession: (opts) => new AntigravityTerminalSession(opts), getProjectDir: async (cwd) => cwd, // No transcript FILE Agent Code reads: agy's store is private SQLite. // History comes from the live session's rows, else from an agy replay diff --git a/src/remote-client/src/wire.ts b/src/remote-client/src/wire.ts index f97e22c60..a973e0629 100644 --- a/src/remote-client/src/wire.ts +++ b/src/remote-client/src/wire.ts @@ -28,8 +28,7 @@ export type RemoteSessionSummary = { agentName?: string | null tabTitle?: string | null pinned?: boolean - /** OpenCode execution runtime ('terminal' = the TUI runtime). Absent = - * the structured runtime, and always absent for other providers. */ + /** Selected execution runtime for providers offering a native TUI. */ providerRuntime?: 'terminal' | null subAgentCount?: number } diff --git a/src/renderer/src/features/settings/lib/settingsRegistry.ts b/src/renderer/src/features/settings/lib/settingsRegistry.ts index 8c97fc1fe..d4cced2a7 100644 --- a/src/renderer/src/features/settings/lib/settingsRegistry.ts +++ b/src/renderer/src/features/settings/lib/settingsRegistry.ts @@ -570,7 +570,7 @@ export function getSettingsRegistry( category: 'workspace', title: 'Agent View Mode', description: - 'Choose whether PTY-backed agent panes (Claude, Codex, Grok) show the provider terminal, Agent Code rendering, or terminal-first Hybrid mode that renders only while a feature needs the feed. Terminal-only providers (OpenCode Terminal, Pi) always use their native terminal; structured-only providers (OpenCode, Hermes, Antigravity) always use Agent Code rendering.', + 'Choose whether PTY-backed agent panes (Claude, Codex, Grok) show the provider terminal, Agent Code rendering, or terminal-first Hybrid mode that renders only while a feature needs the feed. New Antigravity sessions open the agy prompt in Terminal mode and the rendered conversation in Agent or Hybrid mode. OpenCode Terminal and Pi use their native terminals. OpenCode and Hermes use Agent Code rendering.', keywords: ['agent', 'view', 'mode', 'terminal', 'raw', 'hybrid', 'renderer', 'feed', 'tui'], control: { type: 'select', diff --git a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx index 46f891140..d41c11eaa 100644 --- a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx +++ b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx @@ -43,7 +43,19 @@ describe('Agent View Mode picker', () => { expect(setSessionAgentViewModeOverride).toHaveBeenCalledWith('agent', 'agent') }) - it('uses provider-specific copy rather than OpenCode-only copy for Antigravity and Hermes panes', () => { + it.each([undefined, 'terminal'] as const)('offers both agy views for runtime %s', providerRuntime => { + const setter = vi.fn(async () => 'replacement') + const workspace = { + state: { sessions: { agent: { cwd: '/repo', kind: 'antigravity', providerRuntime } } }, + setSessionAgentViewModeOverride: setter, + } as unknown as Workspace + render( {}} />) + const next = providerRuntime ? 'Agent' : 'Terminal' + fireEvent.click(screen.getByRole('option', { name: new RegExp('^' + next + ' ') })) + expect(setter).toHaveBeenCalledWith('agent', next.toLowerCase()) + }) + + it('explains the Hermes chat surface', () => { const workspace = { state: { sessions: { agent: { cwd: '/repo', kind: 'hermes', projectId: 'tab', joinedAt: 0 } } }, setSessionAgentViewModeOverride: vi.fn(() => true), diff --git a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx index 4024350a1..182760518 100644 --- a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx +++ b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx @@ -15,7 +15,7 @@ import type { Workspace } from '@renderer/workspace/workspaceStore' import type { AgentViewModeOverride, SessionId } from '@renderer/workspace/types' import { DEFAULT_PROVIDER, effectiveProviderRuntime, isAgentProviderKind } from '@shared/types/providerKind' import { getRendererProviderCapabilities } from '@providers/registry.renderer.capabilities' -import { providerHasNoNativeTerminal } from '@renderer/workspace/agentDisplayMode' +import { antigravityRuntimeForView, providerHasNoNativeTerminal } from '@renderer/workspace/agentDisplayMode' type PickerValue = AgentViewModeOverride | 'default' @@ -43,6 +43,7 @@ export function AgentViewModePickerModal({ }: Props) { // The LISTBOX is the focus owner (focus-owner invariant, useListNavigation). const listRef = useRef(null) + const applying = useRef(false) const meta = sessionId ? workspace.state.sessions[sessionId] : null const kind = meta?.kind ?? DEFAULT_PROVIDER const isAgent = isAgentProviderKind(kind) @@ -51,9 +52,12 @@ export function AgentViewModePickerModal({ // even when its metadata carries no runtime. const terminalRuntime = effectiveProviderRuntime(kind, meta?.providerRuntime) === 'terminal' const nativeUnavailable = providerHasNoNativeTerminal(kind, meta?.providerRuntime) - const currentValue: PickerValue = terminalRuntime - ? 'terminal' - : meta?.agentViewModeOverride ?? 'default' + const switchesRuntime = kind === 'antigravity' + // A restored ACP pane can predate native support or a later global mode + // change. Show what it is actually running until the user opts to reopen it. + const currentValue: PickerValue = switchesRuntime + ? meta?.agentViewModeOverride ?? (meta?.providerRuntime === antigravityRuntimeForView(globalMode) ? 'default' : terminalRuntime ? 'terminal' : 'agent') + : terminalRuntime ? 'terminal' : meta?.agentViewModeOverride ?? 'default' const options = useMemo( () => [ @@ -61,37 +65,44 @@ export function AgentViewModePickerModal({ value: 'default', label: `Follow Global (${labelForGlobalMode(globalMode)})`, description: 'Use the app-wide Agent View Mode setting.', - disabled: terminalRuntime, + disabled: terminalRuntime && !switchesRuntime, }, { value: 'agent', label: 'Agent', - description: 'Always show Agent Code rendering for this session.', - disabled: terminalRuntime, + description: switchesRuntime ? 'Reopen this conversation in the Agent Code view.' : 'Always show Agent Code rendering for this session.', + disabled: terminalRuntime && !switchesRuntime, }, { value: 'terminal', label: 'Terminal', - description: nativeUnavailable + description: switchesRuntime + ? 'Reopen this conversation in the native agy terminal.' + : nativeUnavailable ? kind === 'opencode' ? 'Choose OpenCode Terminal when creating an agent; this structured session has no PTY.' : `${provider.name} has no native terminal; it always uses Agent Code rendering.` : 'Always show the provider native terminal for this session.', - disabled: nativeUnavailable, + disabled: nativeUnavailable && !switchesRuntime, }, ], - [globalMode, kind, nativeUnavailable, provider.name, terminalRuntime], + [globalMode, kind, nativeUnavailable, provider.name, switchesRuntime, terminalRuntime], ) - const pick = (value: PickerValue) => { - if (!sessionId || !isAgent) return + const pick = async (value: PickerValue) => { + if (!sessionId || !isAgent || applying.current) return const option = options.find(item => item.value === value) if (option?.disabled) return - const ok = workspace.setSessionAgentViewModeOverride( - sessionId, - value === 'default' ? null : value, - ) - if (ok) onClose() + applying.current = true + try { + const ok = await workspace.setSessionAgentViewModeOverride( + sessionId, + value === 'default' ? null : value, + ) + if (ok) onClose() + } finally { + applying.current = false + } } // Movement, disabled-row skipping, Enter and hover go through the shared // list hook (plan K5); this dialog only says what Enter means. The diff --git a/src/renderer/src/workspace/agentDisplayMode.test.ts b/src/renderer/src/workspace/agentDisplayMode.test.ts index 95d6ca8ab..15c4d5562 100644 --- a/src/renderer/src/workspace/agentDisplayMode.test.ts +++ b/src/renderer/src/workspace/agentDisplayMode.test.ts @@ -104,7 +104,7 @@ describe('agent display mode policy', () => { ).toBe('terminal') }) - it('keeps Antigravity (STRUCTURED_ONLY) on the rendered feed even under default Terminal mode', () => { + it('keeps an existing Antigravity ACP session rendered under default Terminal mode', () => { expect( getEffectiveAgentSurfaceForSession({ kind: 'antigravity', @@ -123,6 +123,12 @@ describe('agent display mode policy', () => { ).toBe(true) }) + it('keeps the native agy prompt attached to its PTY under all display preferences', () => { + for (const mode of ['agent', 'hybrid', 'terminal'] as const) { + expect(getEffectiveAgentSurface({ kind: 'antigravity', providerRuntime: 'terminal', mode, runtime: emptyRuntime() })).toBe('terminal') + } + }) + it('falls back to Terminal mode when an unrecognized mode reaches the selector (#1548)', () => { expect( getEffectiveAgentSurface({ diff --git a/src/renderer/src/workspace/agentDisplayMode.ts b/src/renderer/src/workspace/agentDisplayMode.ts index 3db6a0c5c..2725ae582 100644 --- a/src/renderer/src/workspace/agentDisplayMode.ts +++ b/src/renderer/src/workspace/agentDisplayMode.ts @@ -1,6 +1,6 @@ import type { AgentViewMode } from '@renderer/app-state/settings/types' import type { AgentViewModeOverride, SessionKind } from '@renderer/workspace/types' -import { effectiveProviderRuntime, isAgentProviderKind, isAgentSessionKind, isChatSurfaceProviderKind, isStructuredOnlyProviderKind } from '@shared/types/providerKind' +import { effectiveProviderRuntime, isAgentProviderKind, isAgentSessionKind, isChatSurfaceProviderKind } from '@shared/types/providerKind' import type { AgentProviderKind, AgentProviderRuntime } from '@shared/types/providerKind' import type { RenderedViewLeaseFeature, @@ -75,24 +75,21 @@ export function providerHasNoNativeTerminal( providerRuntime: AgentProviderRuntime | null | undefined, ): boolean { if (isChatSurfaceProviderKind(kind)) return true - // Antigravity (agy over ACP) has no PTY at all; see STRUCTURED_ONLY_PROVIDER_KINDS. - if (isStructuredOnlyProviderKind(kind)) return true - return kind === 'opencode' && effectiveProviderRuntime(kind, providerRuntime) !== 'terminal' + return (kind === 'opencode' || kind === 'antigravity') && effectiveProviderRuntime(kind, providerRuntime) !== 'terminal' } -function normalizeAgentViewModeForKind( - kind: AgentProviderKind, - mode: AgentViewMode, -): AgentViewMode { - if (kind !== 'opencode' && !isChatSurfaceProviderKind(kind) && !isStructuredOnlyProviderKind(kind)) return mode - // WHY ordinary OpenCode is pinned to Agent mode: - // Claude/Codex "Terminal" means "attach xterm to the real provider PTY." - // The ordinary OpenCode choice is still HTTP/SSE and has no PTY, so mounting - // AgentTerminalLeaf would paint an empty terminal. OpenCode Terminal is a - // separately selected process runtime and is forced to terminal before this - // normalizer runs; keeping this pin prevents the two choices from collapsing - // back into one misleading view toggle. - return 'agent' +// agy's interactive CLI and ACP server are different processes. Hybrid uses ACP +// so features that need the feed can render it. Record the choice at creation; +// preferences must never reinterpret an existing process after app restart. +export function antigravityRuntimeForView(mode: AgentViewMode): AgentProviderRuntime | undefined { + return mode === 'terminal' ? 'terminal' : undefined +} + +export function runtimeForNewPane( + kind: SessionKind, requestedRuntime: AgentProviderRuntime | null | undefined, continuing: boolean, mode: AgentViewMode, +): AgentProviderRuntime | undefined { + if (kind === 'antigravity' && requestedRuntime === undefined && !continuing) return antigravityRuntimeForView(mode) + return requestedRuntime ?? undefined } export function getEffectiveAgentSurface(args: { @@ -117,7 +114,7 @@ export function getEffectiveAgentSurface(args: { // terminal-only provider (Pi) is pinned whatever its metadata stored — // many spawn paths pass only a kind (providerKind.ts TERMINAL_ONLY_…). if (effectiveProviderRuntime(kind, args.providerRuntime) === 'terminal') return 'terminal' - const mode = normalizeAgentViewModeForKind(kind, requestedMode) + const mode = providerHasNoNativeTerminal(kind, args.providerRuntime) ? 'agent' : requestedMode // WHY this selector ignores leases in hard Terminal mode: // Terminal mode is the user's "never mount Agent Code's renderer for this @@ -204,7 +201,7 @@ export function commandAllowedByRenderedViewPolicy(args: { args.mode === 'terminal' || args.mode === 'hybrid' || args.mode === 'agent' ? args.mode : 'terminal' - const mode = normalizeAgentViewModeForKind(args.kind, requestedMode) + const mode = providerHasNoNativeTerminal(args.kind, args.providerRuntime) ? 'agent' : requestedMode // Commands that open/promote the rendered surface are exactly what Hybrid // exists for: show them in Agent and Hybrid, but hide them in hard Terminal diff --git a/src/renderer/src/workspace/control/agents.ts b/src/renderer/src/workspace/control/agents.ts index cf79d0981..b40628eac 100644 --- a/src/renderer/src/workspace/control/agents.ts +++ b/src/renderer/src/workspace/control/agents.ts @@ -221,7 +221,7 @@ export function agentControlCapabilities(getWorkspace: () => Workspace) { output: sessionReference.extend({ readiness: z.object({ inputReady: z.boolean().nullable(), sessionRunId: z.string().nullable() }) }), handler: async ({ tabId, anchorSessionId, provider: kind, providerRuntime, title, selectCreated }) => { requireUi(); requireSession(anchorSessionId) - if (providerRuntime && !providerOffersTerminalRuntime(kind)) throw new ControlError('invalid_input', 'Only OpenCode and terminal-only providers (Pi) support the terminal runtime') + if (providerRuntime && !providerOffersTerminalRuntime(kind)) throw new ControlError('invalid_input', 'This provider does not offer a separate terminal runtime') if (!resolveTabSessions(useAppStore.getState().workspaceState, tabId).includes(anchorSessionId)) { throw new ControlError('unavailable', 'Anchor does not belong to that project') } diff --git a/src/renderer/src/workspace/control/lifecycle.ts b/src/renderer/src/workspace/control/lifecycle.ts index 9a1a93ada..fef72a982 100644 --- a/src/renderer/src/workspace/control/lifecycle.ts +++ b/src/renderer/src/workspace/control/lifecycle.ts @@ -71,7 +71,7 @@ export function lifecycleControlCapabilities(getWorkspace: () => Workspace) { const check = () => { if (getWorkspace().restoreStatus === 'pending' || hasAppInteractionOwner()) throw new ControlError('unavailable', 'Wait for restoration or finish the input-owning surface') if (!resolveTabSessions(useAppStore.getState().workspaceState, input.tabId).includes(input.anchorSessionId)) throw new ControlError('unavailable', 'Anchor is not in the target project') - if (input.runtime && !providerOffersTerminalRuntime(input.provider)) throw new ControlError('invalid_input', 'Only OpenCode and terminal-only providers (Pi) support the terminal runtime') + if (input.runtime && !providerOffersTerminalRuntime(input.provider)) throw new ControlError('invalid_input', 'This provider does not offer a separate terminal runtime') } check() return startControlTask(context, async () => { diff --git a/src/renderer/src/workspace/control/preferences.renderer.test.tsx b/src/renderer/src/workspace/control/preferences.renderer.test.tsx index cb2fd362b..5ea97e8bc 100644 --- a/src/renderer/src/workspace/control/preferences.renderer.test.tsx +++ b/src/renderer/src/workspace/control/preferences.renderer.test.tsx @@ -1,5 +1,5 @@ import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import { useAppStore } from '@renderer/app-state/store' import { emptyRuntime } from '@renderer/session-runtime/state' import { useWorkspaceHelpers } from '@renderer/workspace/hook/helpers' @@ -56,3 +56,18 @@ it('reports working follow dynamically and invalidates stale preference revision expect(await invoke('views.tailAllSet', { expected: false, enabled: true })).toMatchObject({ ok: true }) expect(await invoke('views.preferencesRead', { sessionId: 'first' })).toMatchObject({ ok: true, value: { tailAll: true, tailWorking: false, followEnabled: true } }) }) + + +it('allows Antigravity view preferences without replacing a running process through control', async () => { + useAppStore.setState({ workspaceState: { ...original.workspaceState, sessions: { agy: { kind: 'antigravity', cwd: '/trial' } } } }) + const setMode = vi.fn(async () => 'agy') + const caps = preferenceControlCapabilities(() => ({ restoreStatus: 'fresh', setSessionAgentViewModeOverride: setMode }) as unknown as Workspace) + const invoke = (id: string, input: unknown) => caps.find(cap => cap.descriptor.id === id)!.execute(input, context) + const current = await invoke('views.preferencesRead', { sessionId: 'agy' }) + if (!current.ok) throw new Error('Missing Antigravity preferences') + const target = { sessionId: 'agy', revision: (current.value as { revision: string }).revision } + expect(await invoke('views.modeSet', { ...target, mode: 'terminal' })).toMatchObject({ ok: false, error: { code: 'unavailable' } }) + expect(setMode).not.toHaveBeenCalled() + expect(await invoke('views.modeSet', { ...target, mode: 'agent' })).toMatchObject({ ok: true }) + expect(setMode).toHaveBeenCalledWith('agy', 'agent') +}) diff --git a/src/renderer/src/workspace/control/preferences.ts b/src/renderer/src/workspace/control/preferences.ts index c526ef29c..cb7dc7b42 100644 --- a/src/renderer/src/workspace/control/preferences.ts +++ b/src/renderer/src/workspace/control/preferences.ts @@ -3,7 +3,7 @@ import { ControlError, defineCapability, paginate } from '@control-sdk' import { useAppStore } from '@renderer/app-state/store' import { hasAppInteractionOwner } from '@renderer/lib/interaction-ownership' import { emptyRuntime } from '@renderer/session-runtime/state' -import { getEffectiveAgentSurfaceForSession, isAgentKind } from '@renderer/workspace/agentDisplayMode' +import { antigravityRuntimeForView, getEffectiveAgentSurfaceForSession, isAgentKind } from '@renderer/workspace/agentDisplayMode' import type { Workspace } from '@renderer/workspace/hook' import { agentFollowEnabled } from '@renderer/workspace/agentFollow' @@ -35,7 +35,16 @@ export function preferenceControlCapabilities(getWorkspace: () => Workspace) { defineCapability({ id: 'views.modeSet', title: 'Set an agent display mode', execution: 'window', effect: 'mutation', target: { kind: 'session', field: 'sessionId' }, description: 'Set an exact agent’s durable Agent/Terminal override, or null to inherit global Agent/Terminal/Hybrid mode. Requires views.preferencesRead revision. Uses the normal provider policy: structured OpenCode cannot become a native terminal, and OpenCode Terminal cannot become a rendered agent. Does not focus, reload or rearrange panes.', input: target.extend({ revision: z.string(), mode: z.enum(['agent', 'terminal']).nullable() }), output, - handler: input => { guard(input); if (!getWorkspace().setSessionAgentViewModeOverride(input.sessionId, input.mode)) throw new ControlError('unavailable', 'Provider rejected this view mode'); return read(input.sessionId) } }), + handler: async input => { + const current = guard(input) + const meta = useAppStore.getState().workspaceState.sessions[input.sessionId] + if (meta?.kind === 'antigravity' && meta.providerRuntime !== antigravityRuntimeForView(input.mode ?? current.globalMode)) { + throw new ControlError('unavailable', 'Use the Agent View Mode picker to reopen this Antigravity conversation in another runtime') + } + const sessionId = await getWorkspace().setSessionAgentViewModeOverride(input.sessionId, input.mode) + if (!sessionId) throw new ControlError('unavailable', 'Provider rejected this view mode') + return read(sessionId) + } }), defineCapability({ id: 'views.followSet', title: 'Set an agent auto-follow preference', execution: 'window', effect: 'mutation', target: { kind: 'session', field: 'sessionId' }, description: 'Set the exact agent’s auto-follow preference for its rendered feed or raw terminal viewport using a fresh views.preferencesRead revision. Idempotent desired state; leaves other agents and pane layout untouched. Bulk follow modes can keep followEnabled true when this preference is false; inspect tailAll/tailWorking for the current window-wide policy.', input: target.extend({ revision: z.string(), enabled: z.boolean() }), output, diff --git a/src/renderer/src/workspace/hook/actions/mcpPreferences.renderer.test.tsx b/src/renderer/src/workspace/hook/actions/mcpPreferences.renderer.test.tsx index 12a4756c3..94220cc8d 100644 --- a/src/renderer/src/workspace/hook/actions/mcpPreferences.renderer.test.tsx +++ b/src/renderer/src/workspace/hook/actions/mcpPreferences.renderer.test.tsx @@ -59,6 +59,29 @@ async function perform(operation: () => Promise) { await act(async () => { await operation(); await vi.runAllTimersAsync() }) } +describe('Antigravity runtime selection', () => { + it('stores the default Terminal runtime on a new pane and preserves ACP on a legacy reload', async () => { + const h = setup({ kind: 'antigravity' }) + await perform(() => h.hook.result.current.sessions.spawn('/project', { kind: 'antigravity' })) + expect(h.spawnSession.mock.calls.at(-1)![0].providerRuntime).toBe('terminal') + expect(h.writer.getState().sessions['new-1']?.providerRuntime).toBe('terminal') + + await perform(() => h.hook.result.current.provider.reloadSessionAgent('original')) + expect(h.spawnSession.mock.calls.at(-1)![0]).toMatchObject({ resumeSessionId: 'native-original', providerRuntime: undefined }) + }) + + it('replaces an Antigravity pane in either direction with the same conversation', async () => { + const h = setup({ kind: 'antigravity' }) + for (const runtime of ['terminal', null] as const) { + await perform(() => h.hook.result.current.sessions.replaceSession('/project', { + kind: 'antigravity', providerRuntime: runtime, targetSessionId: h.focused(), resumeSessionId: 'native-original', + })) + expect(h.spawnSession.mock.calls.at(-1)![0]).toMatchObject({ resumeSessionId: 'native-original', providerRuntime: runtime ?? undefined }) + expect(h.writer.getState().sessions[h.focused()]?.providerRuntime).toBe(runtime ?? undefined) + } + }) +}) + describe('global MCP preferences at actual provider replacement', () => { // Not MCP, but this is the file that drives the REAL reloadSessionAgent → // replaceSession → spawn path. Review a #3: Reload Agent re-resolved the diff --git a/src/renderer/src/workspace/hook/actions/pane.ts b/src/renderer/src/workspace/hook/actions/pane.ts index a936c0efd..655164647 100644 --- a/src/renderer/src/workspace/hook/actions/pane.ts +++ b/src/renderer/src/workspace/hook/actions/pane.ts @@ -1,3 +1,5 @@ +import { runtimeForNewPane } from '@renderer/workspace/agentDisplayMode' +import { useAppStore } from '@renderer/app-state/store' import { DEFAULT_PROVIDER, effectiveProviderRuntime, isRemoteProviderKind } from '@shared/types/providerKind' import { isSidekickSession } from '@renderer/workspace/sessionOwnership' import { SESSION_START_FAILED_MESSAGE } from '@shared/types/session' @@ -868,7 +870,6 @@ export function usePaneActions( ) => { const resumeSessionId = continuation?.resumeSessionId const builtInMcpOverrides = continuation?.builtInMcpOverrides - const providerRuntime = continuation?.providerRuntime const dispatchSnapshot = refs.stateRef.current // #1102 central guard (review finding #2): the DEFAULT kind bypassed // every per-command enablement gate because per-kind commands are @@ -898,6 +899,9 @@ export function usePaneActions( ? kind : [...AGENT_PROVIDER_KINDS].find(candidate => enabledAgentKinds.has(candidate))! })() + // Capture the selected runtime before starting: cleanup must name the same + // runtime even if the project closes or settings change while agy boots. + const providerRuntime = runtimeForNewPane(effectiveKind, continuation?.providerRuntime, !!resumeSessionId, useAppStore.getState().settings.agentViewMode) // ONE Dispatch creation flow for every session kind. // // WHY terminals no longer take a separate path: they used to be inserted @@ -985,7 +989,7 @@ export function usePaneActions( // the code it describes. sessionId = await sessionActions.spawn(cwd, { kind: effectiveKind, - ...(providerRuntime ? { providerRuntime } : {}), + ...(effectiveKind === 'antigravity' || providerRuntime ? { providerRuntime: providerRuntime ?? null } : {}), resumeSessionId, builtInMcpOverrides, ...(options?.hermesLane ? { hermesLane: options.hermesLane } : {}), @@ -1096,7 +1100,8 @@ export function usePaneActions( continuation?: SplitFocusedContinuation, placement?: { selectCreated: boolean }, ) => { - const { kind, providerRuntime } = selection + const { kind } = selection + const providerRuntime = runtimeForNewPane(kind, selection.providerRuntime, !!continuation?.resumeSessionId, useAppStore.getState().settings.agentViewMode) const snapshot = refs.stateRef.current // Resolve the target project ONCE so cwd and projectTab agree. In Tiled // Dispatch this follows the focused lane, not the stale active tab — @@ -1157,7 +1162,7 @@ export function usePaneActions( let sessionId: SessionId try { - sessionId = await sessionActions.spawn(cwd, { kind, providerRuntime, resumeSessionId: continuation?.resumeSessionId, builtInMcpOverrides: continuation?.builtInMcpOverrides }) + sessionId = await sessionActions.spawn(cwd, { kind, providerRuntime: kind === 'antigravity' ? providerRuntime ?? null : providerRuntime, resumeSessionId: continuation?.resumeSessionId, builtInMcpOverrides: continuation?.builtInMcpOverrides }) } catch (err) { showToast(spawnFailureToast(kind === 'terminal' ? 'terminal' : 'agent', err, cwd)) return null @@ -1332,7 +1337,7 @@ export function usePaneActions( // main would have normalized it (Astra review, finding 3). OpenCode is // untouched: its absent runtime still means the structured one. const providerRuntime = effectiveProviderRuntime(params.kind, params.providerRuntime) - if (!enabledAgentProviderChoices().some(choice => choice.kind === params.kind && choice.providerRuntime === providerRuntime)) { + if (!enabledAgentProviderChoices().some(choice => choice.kind === params.kind && (choice.providerRuntime === providerRuntime || params.kind === 'antigravity'))) { throw new Error(`${params.kind} does not support the requested ${providerRuntime ?? 'structured'} runtime`) } const snapshot = refs.stateRef.current @@ -1392,7 +1397,9 @@ export function usePaneActions( const sessionId = await sessionActions.spawn(cwd, { kind: params.kind, - ...(providerRuntime ? { providerRuntime } : {}), + // An orchestrated agy worker needs the per-pane MCP endpoint supplied + // by ACP. Only a caller explicitly asking for the terminal opts out. + providerRuntime: params.kind === 'antigravity' ? providerRuntime ?? null : providerRuntime, resumeSessionId, builtInMcpDomains: params.builtInMcpDomains, }) diff --git a/src/renderer/src/workspace/hook/actions/session.ts b/src/renderer/src/workspace/hook/actions/session.ts index e246e21cc..2e9e4fcab 100644 --- a/src/renderer/src/workspace/hook/actions/session.ts +++ b/src/renderer/src/workspace/hook/actions/session.ts @@ -15,7 +15,7 @@ import { SESSION_START_FAILED_MESSAGE, type SessionRecoverFailureCode } from '@s import { useCallback, useRef } from 'react' import { useAppStore } from '@renderer/app-state/store' -import { shouldUseProxyForSession } from '@renderer/workspace/agentDisplayMode' +import { runtimeForNewPane, shouldUseProxyForSession } from '@renderer/workspace/agentDisplayMode' import { emptyRuntime } from '@renderer/session-runtime/state' import type { SessionRuntime } from '@renderer/session-runtime/state' @@ -86,7 +86,7 @@ export type SessionActions = { opts?: { resumeSessionId?: string kind?: SessionKind - providerRuntime?: AgentProviderRuntime + providerRuntime?: AgentProviderRuntime | null dangerousMode?: boolean recoverTmuxName?: string tldrIdentity?: string @@ -109,7 +109,7 @@ export type SessionActions = { opts?: { resumeSessionId?: string kind?: SessionKind - providerRuntime?: AgentProviderRuntime + providerRuntime?: AgentProviderRuntime | null /** Per-domain MCP choices to ADOPT; omit to continue the pane's own. */ builtInMcpOverrides?: BuiltInMcpOverrides preserveTldr?: boolean @@ -414,7 +414,7 @@ export function useSessionActions( predecessorSessionId?: SessionId predecessorKillCaller?: KillCaller kind?: SessionKind - providerRuntime?: AgentProviderRuntime + providerRuntime?: AgentProviderRuntime | null dangerousMode?: boolean recoverTmuxName?: string tldrIdentity?: string @@ -433,6 +433,10 @@ export function useSessionActions( }, ): Promise => { const kind: SessionKind = opts?.kind ?? DEFAULT_PROVIDER + // Only a fresh request follows today's workspace preference. Old agy panes + // stored no runtime because their only process was the ACP server. + const providerRuntime = runtimeForNewPane(kind, opts?.providerRuntime, + !!opts?.predecessorSessionId, useAppStore.getState().settings.agentViewMode) // Only remote kinds wait for the connection list. An unconditional // await here deferred EVERY spawn's IPC by a microtask, which broke // replaceSession's ordering against edits made while a replacement is @@ -492,7 +496,7 @@ export function useSessionActions( const result = await window.api.spawnSession({ tldrIdentity, kind, - providerRuntime: opts?.providerRuntime, + providerRuntime, cwd, resumeSessionId: opts?.resumeSessionId, ...(opts?.predecessorSessionId @@ -575,7 +579,7 @@ export function useSessionActions( kind, // Write the field even when absent so a pathological reused id cannot // inherit an alternate runtime from stale metadata. - providerRuntime: opts?.providerRuntime, + providerRuntime, ...(tmuxName ? { tmuxName } : {}), ...(kind !== 'terminal' && requestedProviderSessionId ? { @@ -1241,7 +1245,7 @@ export function useSessionActions( opts?: { resumeSessionId?: string kind?: SessionKind - providerRuntime?: AgentProviderRuntime + providerRuntime?: AgentProviderRuntime | null /** Per-domain choices this replacement should ADOPT. Omit to continue * the pane's existing choices; replacement never takes the previous * process's effective capability list as intent. */ @@ -1319,7 +1323,7 @@ export function useSessionActions( // Reload/resume of the same provider preserves its execution surface; // switching providers drops it because runtime capabilities are owned by // the target provider, not transferable pane decoration. - const providerRuntime = spawnOpts.providerRuntime ?? ( + const providerRuntime = spawnOpts.providerRuntime !== undefined ? spawnOpts.providerRuntime ?? undefined : ( nextKind === (oldMeta.kind ?? DEFAULT_PROVIDER) ? oldMeta.providerRuntime : undefined @@ -1349,8 +1353,15 @@ export function useSessionActions( defaultDomains: refs.defaultBuiltInMcpDomainsRef.current, }) : undefined + const switchingAgyView = nextKind === 'antigravity' && oldMeta.kind === nextKind && + oldMeta.providerRuntime !== providerRuntime && !spawnOpts.newConversation const canCommit = (state: WorkspaceState) => { const current = state.sessions[oldId] + // Starting the successor can take seconds. Keep the original pane if + // it changed conversations or received a new ACP turn during that wait. + if (switchingAgyView && (!spawnOpts.resumeSessionId || + resumableProviderSessionId(current) !== spawnOpts.resumeSessionId || + (oldMeta.providerRuntime !== 'terminal' && refs.latestRuntimesRef.current[oldId]?.processActive))) return false return Boolean(current && current.cwd === oldMeta.cwd && current.kind === oldMeta.kind && current.providerRuntime === oldMeta.providerRuntime // Still owned: its project still exists. (A `buried` check sat here diff --git a/src/renderer/src/workspace/hook/actions/undoClose.ts b/src/renderer/src/workspace/hook/actions/undoClose.ts index df0e1e541..49d20d0c8 100644 --- a/src/renderer/src/workspace/hook/actions/undoClose.ts +++ b/src/renderer/src/workspace/hook/actions/undoClose.ts @@ -204,7 +204,7 @@ export function useUndoCloseAction( try { const sessionId = await sessionActions.spawn(meta.cwd, { kind, - ...(meta.providerRuntime ? { providerRuntime: meta.providerRuntime } : {}), + ...(kind === 'antigravity' || meta.providerRuntime ? { providerRuntime: meta.providerRuntime ?? null } : {}), // - an agent with a durable transcript resumes it; // - a terminal with tmuxName re-attaches the same tmux session, // preserving scrollback and any running process. Without this, diff --git a/src/renderer/src/workspace/hook/index.ts b/src/renderer/src/workspace/hook/index.ts index 548234e8b..93cafbfec 100644 --- a/src/renderer/src/workspace/hook/index.ts +++ b/src/renderer/src/workspace/hook/index.ts @@ -71,7 +71,9 @@ import { closeCompletedGoalAgents as runCompletedGoalClose } from '@renderer/wor import type { TldrRecord } from '@shared/types/tldr' import { withTerminalLastUsed, withTerminalLastUsedFloor } from '@renderer/workspace/terminalLastUsed' import type { AgentActivitySelection } from '@renderer/workspace/agentActivityClose' -import { providerHasNoNativeTerminal } from '@renderer/workspace/agentDisplayMode' +import { requestConfirm } from '@renderer/components/ui/confirm-dialog' +import { resumableProviderSessionId } from '@renderer/workspace/providerSessionIdentity' +import { antigravityRuntimeForView, providerHasNoNativeTerminal } from '@renderer/workspace/agentDisplayMode' // ----------------------------------------------------------------------------- // useWorkspace — the composer. @@ -159,16 +161,56 @@ export function useWorkspace( // The last save error while saves keep failing, null once one succeeds // (#1244). Shown by RestoreBanner; see useAutoSave for the threshold. const [saveFailure, setSaveFailure] = useState(null) - const setSessionAgentViewModeOverride = useCallback(( + // Session lifecycle + derivatives that depend on it + const sessionActions = useSessionActions(state, setState, setRuntimes, refs) + const { spawn, ensureSessionLive, killSession, replaceSession, reloadAgentSessions, softReloadAgentView } = + sessionActions + + const setSessionAgentViewModeOverride = useCallback(async ( sessionId: SessionId, override: AgentViewModeOverride | null, - ): boolean => { + ): Promise => { const snapshot = refs.stateRef.current const meta = snapshot.sessions[sessionId] - if (!meta) return false + if (!meta) return null const kind = meta.kind ?? DEFAULT_PROVIDER - if (!isAgentProviderKind(kind)) return false - if ( + if (!isAgentProviderKind(kind)) return null + let successorId = sessionId + if (kind === 'antigravity') { + const desiredRuntime = antigravityRuntimeForView(override ?? useAppStore.getState().settings.agentViewMode) + if (meta.providerRuntime !== desiredRuntime) { + const resumeSessionId = resumableProviderSessionId(meta) + if (!resumeSessionId) { + showToast('This pane needs a saved Antigravity conversation before it can switch views') + return null + } + // Native agy does not publish turn activity over its PTY. Typing in or + // running a turn in its terminal cannot be distinguished from idle. + if (meta.providerRuntime === 'terminal' && !await requestConfirm({ + title: 'Switch Antigravity to Agent view?', + description: 'This closes the native agy prompt and reopens the same conversation. Finish any running turn and submit or copy your draft first.', + confirmLabel: 'Switch view', + })) return null + const current = refs.stateRef.current.sessions[sessionId] + if (!current || resumableProviderSessionId(current) !== resumeSessionId || current.providerRuntime !== meta.providerRuntime) return null + if (meta.providerRuntime !== 'terminal' && refs.latestRuntimesRef.current[sessionId]?.processActive) { + showToast('Wait for Antigravity to finish responding before switching views') + return null + } + // The raw prompt and the feed are different agy processes. A view change + // must resume the exact conversation and retain the pane through replacement. + try { + const successor = await replaceSession(meta.cwd, { + kind, targetSessionId: sessionId, resumeSessionId, providerRuntime: desiredRuntime ?? null, + }) + if (!successor) return null + successorId = successor + } catch (error) { + showToast(error instanceof Error ? error.message : 'Could not switch Antigravity views') + return null + } + } + } else if ( providerHasNoNativeTerminal(kind, meta.providerRuntime) && override === 'terminal' ) { @@ -184,24 +226,24 @@ export function useWorkspace( ? 'Choose OpenCode Terminal when creating the agent to use the native TUI' : `${providerChoiceLabel(kind)} has no native terminal; it always uses Agent Code rendering.`, ) - return false + return null } - if (effectiveProviderRuntime(kind, meta.providerRuntime) === 'terminal' && override === 'agent') { + if (kind !== 'antigravity' && effectiveProviderRuntime(kind, meta.providerRuntime) === 'terminal' && override === 'agent') { // Effective runtime: Pi panes are terminal-only whatever their metadata // stored, and the toast names the pane's own provider. showToast(`${providerChoiceLabel(kind, 'terminal')} sessions always use the native TUI`) - return false + return null } setState(prev => { - const current = prev.sessions[sessionId] + const current = prev.sessions[successorId] if (!current) return prev const sessions = { ...prev.sessions } if (override === null) { const { agentViewModeOverride: _removed, ...rest } = current - sessions[sessionId] = rest + sessions[successorId] = rest } else { - sessions[sessionId] = { + sessions[successorId] = { ...current, agentViewModeOverride: override, } @@ -213,7 +255,7 @@ export function useWorkspace( }) if (override === 'terminal') { setRuntimes(prev => { - const current = prev[sessionId] + const current = prev[successorId] if (!current) return prev if ( !current.assistantPicker && @@ -224,7 +266,7 @@ export function useWorkspace( } return { ...prev, - [sessionId]: { + [successorId]: { ...current, assistantPicker: null, codeBlockPicker: null, @@ -233,8 +275,8 @@ export function useWorkspace( } }) } - return true - }, [refs.stateRef, setRuntimes, setState, showToast]) + return successorId + }, [refs.stateRef, refs.latestRuntimesRef, replaceSession, setRuntimes, setState, showToast]) const setAgentTitle = useCallback((sessionId: SessionId, title: string): boolean => { // Any existing session can carry a title (#865); only a vanished one is refused. @@ -304,10 +346,6 @@ export function useWorkspace( // unified layout (#992): Tile Tabs and split resizing both died with the // tile tree. Lane/row sizing lives in useDispatchActions. - // Session lifecycle + derivatives that depend on it - const sessionActions = useSessionActions(state, setState, setRuntimes, refs) - const { spawn, ensureSessionLive, killSession, replaceSession, reloadAgentSessions, softReloadAgentView } = - sessionActions const ensureSessionLiveRef = useRef(ensureSessionLive) ensureSessionLiveRef.current = ensureSessionLive diff --git a/src/renderer/src/workspace/hook/orchestrationRuntime.renderer.test.tsx b/src/renderer/src/workspace/hook/orchestrationRuntime.renderer.test.tsx index 12c8e2b5f..1af6fa71c 100644 --- a/src/renderer/src/workspace/hook/orchestrationRuntime.renderer.test.tsx +++ b/src/renderer/src/workspace/hook/orchestrationRuntime.renderer.test.tsx @@ -1,5 +1,6 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { requestConfirm } from '@renderer/components/ui/confirm-dialog' import { useAppStore } from '@renderer/app-state/hooks' import { emptyRuntime } from '@renderer/session-runtime/state' import type { OrchestrationRendererRequest, OrchestrationRendererResponse } from '@mcp/shared/orchestrationTypes' @@ -11,6 +12,8 @@ import { oneLaneStage } from '@renderer/workspace/testing/stageFixtures' // suppress them so this deterministic create test cannot discover processes // or read personal configuration. window.api.spawnSession is the main-process // boundary, whose existing runtime factory selection is not reimplemented. +vi.mock('./actions/initialHistory', () => ({ loadInitialHistoryForSession: vi.fn(async () => undefined) })) +vi.mock('@renderer/components/ui/confirm-dialog', () => ({ requestConfirm: vi.fn(async () => false) })) vi.mock('./ipc/useIpcSubscriptions', () => ({ useIpcSubscriptions: () => undefined })) vi.mock('./ipc/useWorkspaceAdoption', () => ({ useWorkspaceAdoption: () => undefined })) vi.mock('./persistence/useBootstrap', () => ({ useBootstrap: () => undefined })) @@ -44,6 +47,7 @@ beforeEach(() => { resolveOrchestrationRequest: resolved, spawnSession, reportSessionLifecycle: vi.fn(), + killOwnedSession: vi.fn(async () => true), appendFeedDebugLog: async () => undefined, } }) }) @@ -64,6 +68,63 @@ async function dispatch(request: OrchestrationRendererRequest): Promise { await act(async () => { await vi.runOnlyPendingTimersAsync() }) } +describe('changing the view of an existing Antigravity pane', () => { + it('resumes a saved conversation opened in a new tab in the preferred view', async () => { + const hook = renderHook(() => useWorkspace()) + await act(async () => { await hook.result.current.newTab('/repo', 'agy-history', 'antigravity') }) + expect(spawnSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + kind: 'antigravity', providerRuntime: 'terminal', resumeSessionId: 'agy-history', + })) + expect(useAppStore.getState().workspaceState.sessions.child?.providerRuntime).toBe('terminal') + }) + + + it.each(['another conversation', 'a new turn'])('keeps the original process if the source starts %s while agy launches', async change => { + const id = 'agy-source-changing' + useAppStore.setState(state => ({ workspaceState: { ...state.workspaceState, stage: oneLaneStage(id), sessions: { + ...state.workspaceState.sessions, [id]: { ...state.workspaceState.sessions.root!, kind: 'antigravity', providerSessionId: 'agy-before' }, + } } })) + const hook = renderHook(() => useWorkspace()) + let started!: () => void + spawnSession.mockImplementationOnce(() => new Promise(resolve => { started = () => resolve({ sessionId: 'unused-agy' }) })) + let opening!: Promise + await act(async () => { opening = hook.result.current.setSessionAgentViewModeOverride(id, 'terminal'); await Promise.resolve() }) + expect(spawnSession).toHaveBeenCalled() + await act(async () => { + if (change === 'a new turn') { + useAppStore.setState(state => ({ workspaceRuntimes: { ...state.workspaceRuntimes, [id]: { ...emptyRuntime(), processActive: true } } })) + } else { + useAppStore.setState(state => ({ workspaceState: { ...state.workspaceState, sessions: { + ...state.workspaceState.sessions, [id]: { ...state.workspaceState.sessions[id]!, providerSessionId: 'agy-after' }, + } } })) + } + started() + expect(await opening).toBeNull() + }) + expect(window.api.killOwnedSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sessionId: 'unused-agy', caller: 'replace.orphaned-successor' })) + expect(useAppStore.getState().workspaceState.sessions[id]).toBeDefined() + expect(useAppStore.getState().workspaceState.sessions['unused-agy']).toBeUndefined() + }) + + it('opens the same conversation in agy and preserves the native process when switching back is cancelled', async () => { + useAppStore.setState(state => ({ workspaceState: { ...state.workspaceState, stage: oneLaneStage('agy-source'), sessions: { + ...state.workspaceState.sessions, 'agy-source': { ...state.workspaceState.sessions.root!, kind: 'antigravity', providerSessionId: 'agy-conversation' }, + } } })) + const hook = renderHook(() => useWorkspace()) + let successor: string | null = null + await act(async () => { successor = await hook.result.current.setSessionAgentViewModeOverride('agy-source', 'terminal') }) + expect(successor).toBe('child') + expect(spawnSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + kind: 'antigravity', providerRuntime: 'terminal', resumeSessionId: 'agy-conversation', + })) + expect(useAppStore.getState().workspaceState.sessions.child).toMatchObject({ providerRuntime: 'terminal', agentViewModeOverride: 'terminal' }) + + await act(async () => { expect(await hook.result.current.setSessionAgentViewModeOverride('child', 'agent')).toBeNull() }) + expect(requestConfirm).toHaveBeenCalledWith(expect.objectContaining({ confirmLabel: 'Switch view' })) + expect(spawnSession).toHaveBeenCalledTimes(1) + }) +}) + describe('renderer orchestration runtime creation', () => { it.each([true, false])('carries the selected runtime and ownership through real spawn; terminal=%s', async terminal => { renderHook(() => useWorkspace()) @@ -99,6 +160,14 @@ describe('renderer orchestration runtime creation', () => { expect(resolved).toHaveBeenLastCalledWith(expect.objectContaining({ requestId: 'read', ok: true, output: expect.objectContaining({ agent: expect.objectContaining({ sessionId: 'child', ...ownership }) }) })) }) + it.each([undefined, 'terminal'] as const)('creates an Antigravity worker with runtime %s', async providerRuntime => { + renderHook(() => useWorkspace()) + await dispatch({ requestId: 'agy', type: 'create-agent', parentSessionId: 'parent', kind: 'antigravity', providerRuntime }) + expect(resolved).toHaveBeenCalledWith(expect.objectContaining({ requestId: 'agy', ok: true })) + expect(spawnSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ kind: 'antigravity', providerRuntime })) + expect(useAppStore.getState().workspaceState.sessions.child?.providerRuntime).toBe(providerRuntime) + }) + // Astra review finding 3: MCP create_agent may name only the kind. Pi has // one runtime, so `{ kind: 'pi' }` must create a terminal Pi child instead // of being refused because the raw request carried no runtime. diff --git a/src/renderer/src/workspace/terminalOnlyProvider.test.ts b/src/renderer/src/workspace/terminalOnlyProvider.test.ts index 4c3e595bb..3623b53b6 100644 --- a/src/renderer/src/workspace/terminalOnlyProvider.test.ts +++ b/src/renderer/src/workspace/terminalOnlyProvider.test.ts @@ -58,8 +58,8 @@ describe('terminal-only providers (Pi)', () => { ]) }) - it('may request the terminal runtime for Pi and OpenCode only', () => { - expect(AGENT_PROVIDER_KINDS.filter(providerOffersTerminalRuntime)).toEqual(['opencode', 'pi']) + it('may request the terminal runtime for providers with a native terminal factory', () => { + expect(AGENT_PROVIDER_KINDS.filter(providerOffersTerminalRuntime)).toEqual(['opencode', 'pi', 'antigravity']) }) // Regression guards: the helper must not change anything for providers diff --git a/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts b/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts index e87eeb6fe..0ebf66866 100644 --- a/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts +++ b/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts @@ -1,4 +1,4 @@ -import { isChatSurfaceProviderKind, isStructuredOnlyProviderKind, type AgentProviderKind } from '@shared/types/providerKind' +import { isChatSurfaceProviderKind, type AgentProviderKind } from '@shared/types/providerKind' import { useRef, useState } from 'react' import type { SessionId } from '@renderer/workspace/types' @@ -117,7 +117,7 @@ export function useComposerKeybinds({ // as prompt text in session/prompt, where agy expands them. PTY slash mode // would send each key to a write() that refuses it, and Enter would then // clear the line without sending anything (review finding). - const noPtySlashMode = chatSurface || isStructuredOnlyProviderKind(provider) + const noPtySlashMode = chatSurface || provider === 'antigravity' const isLocalUsageCommand = () => !chatSurface && input.trim().toLowerCase() === '/usage' const openLocalUsageCommand = async (clearProviderLine: boolean) => { // WHY this local slash command is intercepted LATE instead of blocking diff --git a/src/shared/runtime/terminalSession.ts b/src/shared/runtime/terminalSession.ts index 157723818..58b73f48b 100644 --- a/src/shared/runtime/terminalSession.ts +++ b/src/shared/runtime/terminalSession.ts @@ -43,6 +43,8 @@ export type TerminalSessionOptions = { * about Windows — if/when Agent Code runs there we'll add a branch. */ shell?: string + /** Direct executable arguments, e.g. an agent CLI resuming its own conversation. */ + args?: string[] /** Extra environment overrides for the spawned shell. */ env?: Record /** @@ -104,6 +106,7 @@ export class TerminalSession extends EventEmitter { private readonly cols: number private readonly rows: number private readonly shell: string + private readonly args: string[] private readonly extraEnv: Record private readonly runtime: 'direct' | 'tmux' private readonly tmuxSessionName: string | null @@ -122,6 +125,7 @@ export class TerminalSession extends EventEmitter { // in a way that read like a crash. An explicit options.shell still // bypasses the probe — see pickShell for why. this.shell = pickShell(options.shell) + this.args = options.args ?? [] this.extraEnv = options.env ?? {} this.runtime = options.runtime ?? 'direct' this.tmuxSessionName = options.tmuxSessionName ?? null @@ -198,7 +202,7 @@ export class TerminalSession extends EventEmitter { }, ) } else { - this.pty = ptySpawn(this.shell, [], { + this.pty = ptySpawn(this.shell, this.args, { name: 'xterm-256color', cols: this.cols, rows: this.rows, diff --git a/src/shared/types/providerKind.ts b/src/shared/types/providerKind.ts index b2540ea9d..eaecf5e24 100644 --- a/src/shared/types/providerKind.ts +++ b/src/shared/types/providerKind.ts @@ -172,35 +172,15 @@ export function isChatSurfaceProviderKind(value: unknown): boolean { return typeof value === 'string' && (CHAT_SURFACE_PROVIDER_KINDS as readonly string[]).includes(value) } -/** - * Providers whose ONLY runtime is structured (no PTY) but whose pane is the - * coding feed, not a chat. - * - * Antigravity runs as `agy acp` (Agent Client Protocol over stdio): there is - * no native terminal to attach, exactly like OpenCode's structured runtime, - * yet the pane is the ordinary rendered coding feed (tool rows, thinking, - * permissions), unlike Hermes' chat surface. WHY a provider property resolved - * at read time, like the sets above: every gate that would otherwise mount - * AgentTerminalLeaf (agentDisplayMode, the view-mode picker, the durable - * override guard) sees only a kind, and a spawn path that forgot a per-pane - * flag would paint an empty terminal. - */ -export const STRUCTURED_ONLY_PROVIDER_KINDS = ['antigravity'] as const satisfies readonly AgentProviderKind[] - -export function isStructuredOnlyProviderKind(value: unknown): boolean { - return typeof value === 'string' && (STRUCTURED_ONLY_PROVIDER_KINDS as readonly string[]).includes(value) -} - /** * May a caller REQUEST the terminal runtime for this provider (the control API, - * MCP create_agent)? OpenCode, whose native TUI is a second, separately - * selectable runtime, and every terminal-only provider, whose only runtime it - * is. Grok's main registry also names a terminal factory, but that is the same + * MCP create_agent)? OpenCode and Antigravity each offer a separate native + * TUI runtime. Pi runs only as a terminal. Grok's main registry also names a terminal factory, but that is the same * single runtime and the renderer never offered it as a choice; keeping it out * preserves that behaviour. */ export function providerOffersTerminalRuntime(kind: SessionKind | undefined): boolean { - return kind === 'opencode' || isTerminalOnlyProviderKind(kind) + return kind === 'opencode' || kind === 'antigravity' || isTerminalOnlyProviderKind(kind) } /** diff --git a/testing/live/antigravity-terminal.test.ts b/testing/live/antigravity-terminal.test.ts new file mode 100644 index 000000000..c1b1362ac --- /dev/null +++ b/testing/live/antigravity-terminal.test.ts @@ -0,0 +1,59 @@ +import { Terminal } from '@xterm/headless' +import { expect, it } from 'vitest' +import { getMainProvider } from '@providers/registry.main' + +// Each fresh TUI allocates an empty conversation in the signed-in agy account. Keep this +// opt-in and never submit the marker: typing it is enough to prove interactive input. +it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('opens two native agy prompts and resumes the chosen conversation', async () => { + const provider = getMainProvider('antigravity') + const create = provider.createTerminalSession! + const options = { cwd: process.env.ANTIGRAVITY_LIVE_CWD ?? process.cwd(), binary: process.env.AGY_BINARY ?? 'agy', cols: 100, rows: 30 } + const first = create(options) + const second = create(options) + const screen = new Terminal({ cols: 100, rows: 30, allowProposedApi: true }) + const visible = () => Array.from({ length: screen.rows }, (_, i) => + screen.buffer.active.getLine(screen.buffer.active.viewportY + i)?.translateToString(true) ?? '').join('\n') + first.on('pty-data', data => screen.write(data)) + screen.onData(reply => first.write(reply)) + let rendered: ReturnType | undefined + let resumed: ReturnType | undefined + try { + await first.start() + await second.start() + const firstId = first.getProviderSessionId?.() + expect(firstId).toBeTruthy() + expect(second.getProviderSessionId?.()).toBeTruthy() + expect(second.getProviderSessionId?.()).not.toBe(firstId) + await expect.poll(() => visible().includes('for shortcuts'), { timeout: 30000 }).toBe(true) + screen.resize(90, 25) + first.resize(90, 25) + first.write('native-terminal-check') + await expect.poll(() => visible().includes('native-terminal-check'), { timeout: 5000 }).toBe(true) + first.write('\x15') + await expect.poll(() => visible().includes('native-terminal-check')).toBe(false) + first.write('/new') + await expect.poll(() => visible().includes('/new')).toBe(true) + first.write('\r') + await expect.poll(() => first.getProviderSessionId?.(), { timeout: 15000 }).not.toBe(firstId) + const newId = first.getProviderSessionId?.() + expect(newId).toBeTruthy() + expect(newId).not.toBe(second.getProviderSessionId?.()) + // The view picker starts its successor before it retires the source pane. + rendered = provider.createSession({ ...options, resumeSessionId: newId! }) + await rendered.start() + expect(rendered.getProviderSessionId?.()).toBe(newId) + await first.stop() + resumed = create({ ...options, resumeSessionId: newId! }) + screen.reset() + resumed.on('pty-data', data => screen.write(data)) + // The successor pane has no renderer yet during a view switch. Its own resume + // acknowledgment must arrive without keyboard input or terminal query replies. + await resumed.start() + screen.onData(reply => resumed?.write(reply)) + await expect.poll(() => visible().includes('for shortcuts'), { timeout: 15000 }).toBe(true) + expect(resumed.getProviderSessionId?.()).toBe(newId) + } finally { + await Promise.all([first.stop(), second.stop(), resumed?.stop(), rendered?.stop()]) + screen.dispose() + } +}, 60000)