diff --git a/config/scripts/build-native-for-platform.mjs b/config/scripts/build-native-for-platform.mjs index c8817ab864bd..07d958aa5c21 100755 --- a/config/scripts/build-native-for-platform.mjs +++ b/config/scripts/build-native-for-platform.mjs @@ -122,6 +122,10 @@ function runPnpmScript(scriptName) { // A descendant that inherited the pipes must not hold the launcher open forever. const armReap = () => { clearTimeout(closeTimer) + // A late drain can resume a stream after its child has relinquished group ownership. + if (!children.has(child)) { + return + } // A backpressure pause also delays 'close'; only count time spent actually draining. if (child.stdout.isPaused() || child.stderr.isPaused()) { return diff --git a/config/scripts/build-native-for-platform.test.mjs b/config/scripts/build-native-for-platform.test.mjs index ce15aa54dc67..af8fc3013b9c 100644 --- a/config/scripts/build-native-for-platform.test.mjs +++ b/config/scripts/build-native-for-platform.test.mjs @@ -39,7 +39,7 @@ function startBuild(mode, options = {}) { writeFileSync( cli, ` - import { appendFileSync, existsSync } from 'node:fs' + import { appendFileSync, existsSync, writeSync } from 'node:fs' import { spawn } from 'node:child_process' const name = process.argv.at(-1) const delay = name.includes('computer') ? 0 : name.includes('keyboard') ? 200 : 400 @@ -54,6 +54,7 @@ function startBuild(mode, options = {}) { spawn(process.execPath, ['-e', ${JSON.stringify("process.on('SIGTERM', () => {}); console.log('descendant ' + process.pid); setInterval(() => {}, 1000)")}], { stdio: 'inherit' }) } let flooding = false + let exiting = false setInterval(() => { if (!existsSync(process.env.NATIVE_BUILD_GATE)) return if (process.env.NATIVE_BUILD_MODE.startsWith('output-closed-')) { @@ -71,11 +72,24 @@ function startBuild(mode, options = {}) { } if (['success', 'descendant-success'].includes(process.env.NATIVE_BUILD_MODE)) { record('completed'); process.exit(0) } if (process.env.NATIVE_BUILD_MODE === 'stalled-consumer') { - if (!name.includes('computer') || existsSync(process.env.NATIVE_BUILD_GATE + '-exit')) { record('completed'); process.exit(0) } + if (!name.includes('computer')) { record('completed'); process.exit(0) } + if (existsSync(process.env.NATIVE_BUILD_GATE + '-exit')) { + if (!exiting) { exiting = true; setTimeout(() => { record('completed'); process.exit(0) }, Number(process.env.NATIVE_BUILD_COMPLETION_DELAY)) } + return + } if (flooding) return flooding = true - // Each callback means the kernel pipe accepted the line, so it survives our exit. - const pump = (line) => process.stdout.write('line ' + line + ' ' + 'x'.repeat(190) + '\\n', () => { record('accepted', { line }); pump(line + 1) }) + // Synchronous byte counts remain authoritative when exit preempts writable callbacks. + const pump = (line, offset = 0) => { + const text = 'line ' + line + ' ' + 'x'.repeat(190) + '\\n' + let bytes + try { bytes = offset + writeSync(1, text.slice(offset)) } + catch (error) { if (error.code !== 'EAGAIN') throw error; setTimeout(() => pump(line, offset), 1); return } + record('accepted', { line, bytes }) + const next = () => bytes === text.length ? pump(line + 1) : pump(line, bytes) + if (Number(process.env.NATIVE_BUILD_COMPLETION_DELAY) > 0) setTimeout(next, 1) + else setImmediate(next) + } pump(1) return } @@ -102,6 +116,12 @@ function startBuild(mode, options = {}) { `data:text/javascript,${encodeURIComponent(`import { appendFileSync } from 'node:fs'; setInterval(() => appendFileSync(process.env.NATIVE_BUILD_JOURNAL, JSON.stringify({ name: 'launcher', event: 'buffered', bytes: process.stdout.writableLength }) + '\\n'), 50).unref()`)}` ] : []), + ...(options.lateResume + ? [ + '--import', + `data:text/javascript,${encodeURIComponent(`import childProcess from 'node:child_process'; import { syncBuiltinESMExports } from 'node:module'; const spawn = childProcess.spawn; childProcess.spawn = (...args) => { const child = spawn(...args); child.once('close', () => { child.stdout.pause(); setImmediate(() => child.stdout.resume()) }); return child }; syncBuiltinESMExports()`)}` + ] + : []), ...(options.lateOutputError ? [ '--import', @@ -117,7 +137,8 @@ function startBuild(mode, options = {}) { npm_execpath: options.missingCli ? join(directory, 'missing-pnpm') : cli, NATIVE_BUILD_JOURNAL: journal, NATIVE_BUILD_GATE: join(directory, 'release'), - NATIVE_BUILD_MODE: mode + NATIVE_BUILD_MODE: mode, + NATIVE_BUILD_COMPLETION_DELAY: String(options.completionDelay ?? 0) }, stdio: ['ignore', 'pipe', 'pipe'] }) @@ -277,6 +298,16 @@ describe.skipIf(process.platform !== 'darwin')('parallel native builds', () => { } ) + it('does not rearm descendant reaping when a closed compiler stream resumes', async () => { + const build = startBuild('success', { lateResume: true }) + await build.ready + build.release() + const result = await build.closed + expect(result).toMatchObject({ code: 0, signal: null }) + expect(result.stderr).not.toContain('reaping') + expect(build.events().filter(({ event }) => event === 'completed')).toHaveLength(3) + }) + it('reports a missing build command without waiting forever', async () => { const build = startBuild('success', { missingCli: true }) expect(await build.closed).toMatchObject({ code: 1, signal: null }) @@ -317,35 +348,59 @@ describe.skipIf(process.platform !== 'darwin')('parallel native builds', () => { expect(Math.max(...buffered)).toBeLessThan(1_000_000) }) - it('delivers every compiler line when its own stdout consumer stalls past the reap timeout', async () => { - const build = startBuild('stalled-consumer', { reportBuffered: true }) - await build.ready - build.child.stdout.pause() - build.release() - // Launcher stops reading once its stdout hits the high-water mark; then let the compiler fill its pipe. - await waitFor(() => - build.events().some(({ event, bytes }) => event === 'buffered' && bytes >= 16_384) - ) - await sleep(300) - build.releaseExit() - await waitFor(() => build.events().some(({ event }) => event === 'completed')) - const accepted = Math.max( - ...build + it.each([0, 200])( + 'delivers every accepted compiler byte after a stalled consumer and %ims completion delay', + async (completionDelay) => { + const build = startBuild('stalled-consumer', { reportBuffered: true, completionDelay }) + await build.ready + build.child.stdout.pause() + build.release() + await waitFor(() => + build.events().some(({ event, bytes }) => event === 'buffered' && bytes >= 16_384) + ) + await sleep(300) + build.releaseExit() + // Quiet siblings finish first; only the output producer freezes the expected byte count. + await waitFor(() => + build.events().some(({ name, event }) => name.includes('computer') && event === 'completed') + ) + const compiler = build .events() - .filter(({ event }) => event === 'accepted') - .map(({ line }) => line) - ) - expect(accepted).toBeGreaterThan(0) - await sleep(3_000) - build.child.stdout.resume() + .find(({ name, event }) => name.includes('computer') && event === 'started') + await waitFor(() => { + try { + process.kill(compiler.pid, 0) + return false + } catch (error) { + if (error.code === 'ESRCH') { + return true + } + throw error + } + }) + const accepted = build.events().findLast(({ event }) => event === 'accepted') + expect(accepted.line).toBeGreaterThan(0) + await sleep(3_000) + build.child.stdout.resume() - const result = await build.closed - expect(result).toMatchObject({ code: 0, signal: null }) - const delivered = [...result.output.matchAll(/^\[computer\] line (\d+) /gm)].map((match) => - Number(match[1]) - ) - expect(delivered).toEqual(Array.from({ length: accepted }, (_, index) => index + 1)) - }) + const result = await build.closed + expect(result).toMatchObject({ code: 0, signal: null }) + expect(build.events().filter(({ event }) => event === 'completed')).toHaveLength(3) + const lineText = (line) => `line ${line} ${'x'.repeat(190)}\n` + const expected = [ + `[computer] ready ${compiler.pid}`, + ...Array.from( + { length: accepted.line - 1 }, + (_, index) => `[computer] ${lineText(index + 1).trimEnd()}` + ), + `[computer] ${lineText(accepted.line).slice(0, accepted.bytes).replace(/\n$/, '')}` + ] + expect(result.output.split('\n').filter((line) => line.startsWith('[computer] '))).toEqual( + expected + ) + expect(result.stderr).not.toContain('reaping') + } + ) it.each(['linux', 'win32'])('keeps the %s entry point out of macOS builds', async (platform) => { const build = startBuild('success', { platform }) diff --git a/docs/reference/antigravity-native-chat.md b/docs/reference/antigravity-native-chat.md new file mode 100644 index 000000000000..171e7ce52861 --- /dev/null +++ b/docs/reference/antigravity-native-chat.md @@ -0,0 +1,110 @@ +# Antigravity terminal-backed Chat UI + +Antigravity uses the existing experimental Chat UI over its terminal and saved +transcript. It is not a structured-session provider. The opt-in default-chat +setting applies when a real provider session is associated. New unassociated +Antigravity sessions start in Terminal and apply that preference when the execution +host supplies their CLI conversation ID. Resuming a known CLI conversation applies +the preference at launch. An explicit view choice or an unconfirmed restored row +is preserved; an IDE reference ID is not a CLI conversation ID. + +## Transcript contract + +The execution host reads +`.gemini/antigravity-cli/brain//.system_generated/logs/transcript.jsonl`. +A hook-reported transcript path takes precedence. Existing WSL exact-path and +host-isolation rules apply; id-only WSL reads derive the distro from the owning +hook server's canonical provider-session row and inspect only that guest. +Ambiguous or unavailable namespaces fail before reading a local file, including +provenance checks for SSH- or paired-owned IDs on the client. A missing guest transcript must not +fall back to a native host's same-named conversation. Direct SSH panes stay in the terminal: +that connection has no native-chat transcript transport, and its absolute file +path must never be opened on the client. Paired runtimes remain eligible because +their own host reads the transcript. Direct SSH chat support remains unfinished. + +The sanitized fixture in `src/main/native-chat/__fixtures__/antigravity/` records +these observed shapes: + +- User input is `USER_EXPLICIT/USER_INPUT` with a `USER_REQUEST` wrapper. +- Planner responses carry text, thinking, or tool calls. Tool arguments are in `args`. +- Tool output is a `MODEL` record with a tool-specific type such as `RUN_COMMAND` + or `VIEW_FILE`. It is not a `TOOL_RESULT` record. +- A planner step marked `DONE` can precede more tool work in the same user turn. + The decoder therefore emits no turn-completion verdict. The existing host-owned + hook/status system remains authoritative. + +Full reads, incremental tails, and legacy journal imports reuse the same decoder. +Unknown record types are skipped. Tool failures retain a nonzero exit code or +`ERROR` status as an error result. + +## Mixed versions + +New hosts advertise `native-chat.antigravity.v1`. A new client's chat transport +checks the owning host before reading or subscribing to Antigravity. An older +host gets the existing update-runtime error; a failed capability probe gets the +existing read error. Neither becomes a perpetual first-transcript wait. +No stream opcode or message-block type was added. + +## Approvals and terminal ownership + +Captured command menus publish an Allow/Deny card through the hook server's +canonical row. Allow sends the recorded one-time `1` key; Deny sends Escape to +the same terminal through the existing input transport. The publisher refuses +stale revisions, replaced terminal generations, unconfirmed restored rows, +unreadable screens, and lost execution-host contact. A WSL relay row must match +an explicitly known PTY distro; an unknown/default distro is not proof of a match. + +The current trusted-grid checks and 1.2.14 agent-state rules remain in force. +Only the captured working layout or an idle composer can clear this producer's +card; the idle composer must remain quiet for three seconds. Pending timers +recheck the live row and screen before publication and are cancelled on PTY exit. +Output during a screen read replaces the pending quiet timer; callbacks and reads +from a forgotten PTY incarnation cannot reschedule or publish for its replacement. +No removed readiness module or reader-side status store was restored. + +## Verification limits on the current port (2026-10-02) + +The native CLI observations below are the original author's evidence preserved +from `09169edd23e2a56ee66f4d3d7b07403f0b04c478`, including its attached proof. The +subsequent review repair replays those committed captures and checks the rebuilt +hidden UI with private CLI/status/transcript fixtures. That fixture proof is not +a new authenticated native run or a new verification of hook delivery or model +generation. + +The focused suites cover decoder/full-read/tail parity, unknown records, durable +journal imports, WSL path isolation and stalled reads, captured Windows approvals, +canonical-row revision/incarnation fences, current 1.2.14 readiness/quiescence, +capability refusal and transient probe failure, stream cancellation/reconnect, +Terminal/Chat eligibility and default view. Mobile also checks capabilities before +subscription and history reads. No new wire opcode or structured provider was added. + +In a hidden macOS app built from this worktree, with a brand-new profile and +`agentStatusHooksEnabled=false` verified through the live store, a real Chat +composer send reached installed agy 1.2.14 in the same terminal and its saved +transcript. The provider returned “Individual quota reached” on Gemini 3.8 Flash +with a reset about 120 hours away. To inspect the real transcript in Chat without +installing hooks, the actual session ID/path was manually bound after matching the +submitted marker in that file. This is real read/send/toggle evidence, not proof +of automatic hook delivery, successful generation, or live Allow/Deny actions. + +A subsequent isolated, authenticated Claude Sonnet turn reached an actual +`cat proof.txt` command approval on macOS agy 1.2.14. Its sanitized authoritative +159×69 main-buffer grid is recorded with a provenance sidecar and passes the +existing hold rule. The canonical hook-server snapshot remained empty on that +main build, so automatic Chat association and live Chat Allow/Deny remain +unverified pending the separately owned POSIX hook transport fix. This turn +proves real generation and the current permission layout, not completed tool +execution or a Chat approval card. + +The committed Windows approval recordings came from the scoped predecessor and +remain historical 1.2.7 evidence. Current Windows/WSL/Linux/paired execution and +mobile device UI were not available here. These limits must accompany a successor +PR; keep #20157 open while its Cursor portion is absent. Accounts and IDE history +continuation are separate follow-ups. + +## Adoption + +Scoped recovery of #21660 and #21776 credits the original #15773 work by +@haoliangli. WSL transcript and relay-approval support recovers #24141 by +@sojiro-o. No old development branch was merged wholesale, and predecessors must +remain open until the successor lands. diff --git a/docs/reference/antigravity-readiness-evidence.md b/docs/reference/antigravity-readiness-evidence.md index 18317d7e5cec..98971416ed7d 100644 --- a/docs/reference/antigravity-readiness-evidence.md +++ b/docs/reference/antigravity-readiness-evidence.md @@ -330,3 +330,45 @@ The honest summary is that this is a screen-shaped problem being solved with lin rule over the derived tail can be made much better than what ships today, but the durable fix is to ask the terminal emulator what the bottom row of the screen actually is, rather than inferring it from a byte stream that was written with cursor addressing. Attempt seven does that. + +## Native Windows command approval — 1.2.7 (2026-09-20) + +`antigravity-windows-command-approval.txt` records an actual authenticated tool +turn, stopped while the four-choice “Run this command?” dialog owns the screen. +`antigravity-windows-command-cancelled.txt` records another harmless command turn +and Escape dismissing that dialog back to the empty composer. Both used the +repository PTY recorder on native Windows at 120×40, with account information +hidden. The command executable's OS username is replaced with a same-length +placeholder in the transcript and sidecar. Both pass the transcript secret scan. + +The approval screen ends with the navigation hint and `esc to cancel`; its four +choices distinguish it from ordinary working output. The runtime regression +previously timed out without a blocked reason. The approval publisher recognizes that captured menu; the current agent-state +rules hold readiness while it owns the screen. The cancelled capture reads as +an idle composer, held to the current three-second quiescence gate. + +These are historical Windows recordings, not live proof of the current port. +Current macOS/Windows/WSL Allow/Deny flows and narrower widths still need live +verification. Do not infer permission from `PreToolUse`: agy can +execute an already-allowed tool without waiting for a user decision. + +`antigravity-windows-command-allow-key.txt` additionally records the pending menu, +sending the single key `1` (no Enter), successful harmless command execution and +return to the empty composer. This verifies the existing Chat approval card's +one-time acceptance key on native Windows 1.2.7. The recorder metadata confirms +completion; the capture was transferred as raw UTF-8 bytes without newline +normalization and its username was replaced with a same-length placeholder. + +## Native macOS command approval — 1.2.14 (2026-10-02) + +`antigravity-macos-1-2-14-command-approval.txt` captures an actual authenticated +Claude Sonnet turn requesting `cat proof.txt` in a disposable folder. It is the +authoritative restored main PTY grid at 159×69, with ANSI retained and identifying +username, hostname and task-profile suffix scrubbed; the sidecar distinguishes +this grid snapshot from raw PTY event bytes. Existing replay tests recognize the +four-choice menu and return `hold`. No predicate was changed for this capture. + +The owning hook-server row was absent during this run. This proves the current +CLI permission screen, not automatic Chat association, an actionable Chat card, +or successful Allow/Deny delivery. Those require live verification after the +separately owned POSIX hook transport successor lands. diff --git a/mobile/src/session/mobile-antigravity-chat-capability.test.ts b/mobile/src/session/mobile-antigravity-chat-capability.test.ts new file mode 100644 index 000000000000..d0daf4add72d --- /dev/null +++ b/mobile/src/session/mobile-antigravity-chat-capability.test.ts @@ -0,0 +1,62 @@ +import { expect, it, vi } from 'vitest' +import { + requireMobileAntigravityChatCapability, + startMobileNativeChatAfterCapability +} from './mobile-antigravity-chat-capability' + +const response = (capabilities: string[]) => ({ + ok: true as const, + id: 'status', + result: { capabilities }, + _meta: { runtimeId: 'host' } +}) + +it('refuses old hosts and keeps transient probe failures as read errors', async () => { + await expect( + requireMobileAntigravityChatCapability( + { sendRequest: vi.fn(async () => response([])) }, + 'antigravity' + ) + ).rejects.toThrow('Update the connected') + await expect( + requireMobileAntigravityChatCapability( + { + sendRequest: vi.fn(async () => { + throw new Error('timeout') + }) + }, + 'antigravity' + ) + ).rejects.toThrow('Unable to read') +}) + +it('does not open a cancelled subscription after a capability probe settles', async () => { + const pending = Promise.withResolvers>() + const start = vi.fn(() => () => {}) + const onError = vi.fn() + const cancel = startMobileNativeChatAfterCapability( + { sendRequest: () => pending.promise }, + 'antigravity', + start, + onError + ) + cancel() + pending.resolve(response(['native-chat.antigravity.v1'])) + await vi.waitFor(() => expect(pending.promise).resolves.toBeDefined()) + expect(start).not.toHaveBeenCalled() + expect(onError).not.toHaveBeenCalled() +}) + +it('opens capable hosts and tears down their stream', async () => { + const stop = vi.fn() + const start = vi.fn(() => stop) + const cancel = startMobileNativeChatAfterCapability( + { sendRequest: vi.fn(async () => response(['native-chat.antigravity.v1'])) }, + 'antigravity', + start, + vi.fn() + ) + await vi.waitFor(() => expect(start).toHaveBeenCalledOnce()) + cancel() + expect(stop).toHaveBeenCalledOnce() +}) diff --git a/mobile/src/session/mobile-antigravity-chat-capability.ts b/mobile/src/session/mobile-antigravity-chat-capability.ts new file mode 100644 index 000000000000..a8568a95f013 --- /dev/null +++ b/mobile/src/session/mobile-antigravity-chat-capability.ts @@ -0,0 +1,58 @@ +import { ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import { hostStatusProbe } from '../transport/host-status-probe-operations' + +const READ_ERROR = 'Unable to read Antigravity Chat from the connected host.' +const OLD_HOST = 'Update the connected Orca runtime to use Antigravity Chat.' + +type Client = Parameters[0] + +export async function requireMobileAntigravityChatCapability( + client: Client, + agent: string +): Promise { + if (agent !== 'antigravity') { + return + } + let supports: boolean + try { + const reply = hostStatusProbe.interpret(await hostStatusProbe.request(client)) + if (!reply.accepted || !reply.value) { + throw new Error(READ_ERROR) + } + supports = + reply.value.capabilities?.includes(ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY) === true + } catch { + throw new Error(READ_ERROR) + } + if (!supports) { + throw new Error(OLD_HOST) + } +} + +export function startMobileNativeChatAfterCapability( + client: Client, + agent: string, + start: () => () => void, + onError: (message: string) => void +): () => void { + if (agent !== 'antigravity') { + return start() + } + let cancelled = false + let unsubscribe: (() => void) | undefined + void requireMobileAntigravityChatCapability(client, agent) + .then(() => { + if (!cancelled) { + unsubscribe = start() + } + }) + .catch((error: unknown) => { + if (!cancelled) { + onError(error instanceof Error ? error.message : READ_ERROR) + } + }) + return () => { + cancelled = true + unsubscribe?.() + } +} diff --git a/mobile/src/session/use-mobile-native-chat-session.ts b/mobile/src/session/use-mobile-native-chat-session.ts index 1f8bdae2d481..aadbfbbda40e 100644 --- a/mobile/src/session/use-mobile-native-chat-session.ts +++ b/mobile/src/session/use-mobile-native-chat-session.ts @@ -13,6 +13,10 @@ import { type MobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' import { structuredSessionRandomUuid } from './structured-session-operation-id' +import { + requireMobileAntigravityChatCapability, + startMobileNativeChatAfterCapability +} from './mobile-antigravity-chat-capability' export type MobileNativeChatStatus = | 'idle' @@ -149,75 +153,84 @@ export function useMobileNativeChatSession(args: { return } - const unsubscribe = client.subscribe( - 'nativeChat.subscribe', - { - agent, - sessionId, - limit: limitRef.current, - // Why: a token of its own, so another screen on this chat never evicts this feed on the host. - subscriptionId: buildNativeChatSubscriptionId( - agent, - sessionId, - structuredSessionRandomUuid() + const unsubscribe = startMobileNativeChatAfterCapability( + client, + agent, + () => + client.subscribe( + 'nativeChat.subscribe', + { + agent, + sessionId, + limit: limitRef.current, + // Why: a token of its own, so another screen on this chat never evicts this feed on the host. + subscriptionId: buildNativeChatSubscriptionId( + agent, + sessionId, + structuredSessionRandomUuid() + ), + capabilities: { transcriptPending: 1 }, + ...(transcriptPath ? { transcriptPath } : {}) + }, + (raw) => { + if (cancelled) { + return + } + const frame = raw as MobileNativeChatStreamFrame + const applied = applyMobileNativeChatStreamFrame({ + merger: mergerRef.current, + frame, + limit: limitRef.current, + replaceSnapshot: !snapshotSeenRef.current + }) + if (applied.kind === 'ignored') { + return + } + if (applied.kind === 'error') { + setRead({ client, identity, status: 'error' }) + setError(applied.error) + return + } + if (frame.type === 'snapshot' && !applied.pending) { + // A pending window has no transcript behind it, so the snapshot that + // follows is still this subscription's base, not a reconnect replay. + snapshotSeenRef.current = true + } + if (applied.windowReplaced || frame.type === 'snapshot') { + // Why: any authoritative window (and any replay merge) invalidates an + // in-flight older-page request; stale results must not land on it. + streamGenerationRef.current += 1 + loadingEarlierRef.current = false + setLoadingEarlier(false) + } + if (applied.windowReplaced) { + // Only a genuinely fresh window resets the grown read window — an + // overlapping reconnect replay keeps the paged-in history and limit. + limitRef.current = INITIAL_LIMIT + beforeOffsetRef.current = applied.beforeOffset ?? null + setHasMore(applied.hasMore ?? applied.messages.length >= INITIAL_LIMIT) + } + setMessages(applied.messages) + if (!applied.windowReplaced && applied.hasMore != null) { + setHasMore(applied.hasMore) + } + if (!applied.windowReplaced && applied.beforeOffset != null) { + beforeOffsetRef.current = applied.beforeOffset + } + if (applied.cursorInvalidated) { + // Fall back to a growing-tail read so history trimmed by live appends + // cannot leave a gap between the retained window and the old cursor. + streamGenerationRef.current += 1 + loadingEarlierRef.current = false + setLoadingEarlier(false) + beforeOffsetRef.current = null + } + setRead({ client, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + } ), - capabilities: { transcriptPending: 1 }, - ...(transcriptPath ? { transcriptPath } : {}) - }, - (raw) => { - if (cancelled) { - return - } - const frame = raw as MobileNativeChatStreamFrame - const applied = applyMobileNativeChatStreamFrame({ - merger: mergerRef.current, - frame, - limit: limitRef.current, - replaceSnapshot: !snapshotSeenRef.current - }) - if (applied.kind === 'ignored') { - return - } - if (applied.kind === 'error') { - setRead({ client, identity, status: 'error' }) - setError(applied.error) - return - } - if (frame.type === 'snapshot' && !applied.pending) { - // A pending window has no transcript behind it, so the snapshot that - // follows is still this subscription's base, not a reconnect replay. - snapshotSeenRef.current = true - } - if (applied.windowReplaced || frame.type === 'snapshot') { - // Why: any authoritative window (and any replay merge) invalidates an - // in-flight older-page request; stale results must not land on it. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) - } - if (applied.windowReplaced) { - // Only a genuinely fresh window resets the grown read window — an - // overlapping reconnect replay keeps the paged-in history and limit. - limitRef.current = INITIAL_LIMIT - beforeOffsetRef.current = applied.beforeOffset ?? null - setHasMore(applied.hasMore ?? applied.messages.length >= INITIAL_LIMIT) - } - setMessages(applied.messages) - if (!applied.windowReplaced && applied.hasMore != null) { - setHasMore(applied.hasMore) - } - if (!applied.windowReplaced && applied.beforeOffset != null) { - beforeOffsetRef.current = applied.beforeOffset - } - if (applied.cursorInvalidated) { - // Fall back to a growing-tail read so history trimmed by live appends - // cannot leave a gap between the retained window and the old cursor. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) - beforeOffsetRef.current = null - } - setRead({ client, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + (message) => { + setRead({ client, identity, status: 'error' }) + setError(message) } ) @@ -246,6 +259,9 @@ export function useMobileNativeChatSession(args: { setLoadingEarlier(true) void (async () => { try { + if (agent === 'antigravity') { + await requireMobileAntigravityChatCapability(client, agent) + } const response = await nativeChatSessionPageRead.request(client, { agent, sessionId, diff --git a/src/main/agent-hooks/server-ingest-antigravity-screen.test.ts b/src/main/agent-hooks/server-ingest-antigravity-screen.test.ts new file mode 100644 index 000000000000..09dbdc8bb69a --- /dev/null +++ b/src/main/agent-hooks/server-ingest-antigravity-screen.test.ts @@ -0,0 +1,163 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { AgentHookServer, _internals } from './server' +import { PANE } from './server.test-fixtures' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) + +beforeEach(() => _internals.resetCachesForTests()) + +function workingPane( + agentType = 'antigravity', + connectionId: string | null = null +): AgentHookServer { + const server = new AgentHookServer() + server.ingestTerminalStatus({ + paneKey: PANE, + terminalHandle: 'term-screen', + connectionId, + payload: { state: 'working', agentType, prompt: 'print marker', toolName: 'run_command' } + }) + return server +} + +function baseline(server: AgentHookServer) { + const row = server.getStatusSnapshot()[0] + if (!row) { + throw new Error('Missing test status row') + } + return row +} + +describe('host-owned Antigravity screen permission', () => { + it('publishes permission through the canonical store and clears only its own prompt', () => { + const server = workingPane() + const listener = vi.fn() + server.setListener(listener) + listener.mockClear() + expect( + server.ingestAntigravityScreenPermission({ baseline: baseline(server), command: 'echo OK' }) + ).toBe(true) + expect(baseline(server)).toMatchObject({ + state: 'waiting', + toolName: 'run_command', + observation: { origin: 'process' } + }) + expect(JSON.parse(baseline(server).interactivePrompt ?? '')).toEqual({ + approval: { source: 'antigravity-screen', tool: 'run_command', summary: 'echo OK' } + }) + expect(listener).toHaveBeenCalledTimes(1) + expect( + server.ingestAntigravityScreenPermission({ + baseline: baseline(server), + command: null, + clearedState: 'done' + }) + ).toBe(true) + expect(baseline(server)).toMatchObject({ state: 'done', prompt: 'print marker' }) + expect(baseline(server).interactivePrompt).toBeUndefined() + expect(baseline(server).toolName).toBeUndefined() + expect(listener).toHaveBeenCalledTimes(2) + }) + + it('does not overwrite a newer provider state with a late snapshot', () => { + const server = workingPane() + const old = baseline(server) + server.ingestTerminalStatus({ + paneKey: PANE, + terminalHandle: 'term-screen', + payload: { state: 'done', agentType: 'antigravity', prompt: 'print marker' } + }) + expect(server.ingestAntigravityScreenPermission({ baseline: old, command: 'echo OK' })).toBe( + false + ) + expect(baseline(server).state).toBe('done') + }) + + it('rejects another terminal incarnation and missing observation proof', () => { + const server = workingPane() + const row = baseline(server) + expect( + server.ingestAntigravityScreenPermission({ + baseline: { ...row, terminalHandle: 'replaced' }, + command: 'echo OK' + }) + ).toBe(false) + expect( + server.ingestAntigravityScreenPermission({ + baseline: { ...row, observation: undefined }, + command: 'echo OK' + }) + ).toBe(false) + }) + + it.each([ + ['claude', null], + ['antigravity', 'ssh-connection'] + ] as const)('does not infer permission for %s on %s', (agent, connection) => { + const server = workingPane(agent, connection) + expect( + server.ingestAntigravityScreenPermission({ baseline: baseline(server), command: 'echo OK' }) + ).toBe(false) + }) + + it('publishes permission for a WSL relay row, whose pty this host owns', () => { + const server = workingPane('antigravity', 'wsl:Ubuntu-26.04') + expect( + server.ingestAntigravityScreenPermission({ baseline: baseline(server), command: 'echo OK' }) + ).toBe(true) + expect(baseline(server)).toMatchObject({ state: 'waiting', connectionId: 'wsl:Ubuntu-26.04' }) + }) + + it('does not clear a permission prompt from another producer', () => { + const server = workingPane() + server.ingestTerminalStatus({ + paneKey: PANE, + terminalHandle: 'term-screen', + payload: { + state: 'waiting', + agentType: 'antigravity', + prompt: 'print marker', + interactivePrompt: '{"questions":[]}' + } + }) + expect( + server.ingestAntigravityScreenPermission({ + baseline: baseline(server), + command: null, + clearedState: 'done' + }) + ).toBe(false) + expect(baseline(server).state).toBe('waiting') + }) + + it('coalesces an unchanged permission observation without refreshing its revision', () => { + const server = workingPane() + server.ingestAntigravityScreenPermission({ baseline: baseline(server), command: 'echo OK' }) + const waiting = baseline(server) + expect( + server.ingestAntigravityScreenPermission({ baseline: waiting, command: 'echo OK' }) + ).toBe(true) + expect(baseline(server).observation).toEqual(waiting.observation) + }) +}) + +it('accepts the runtime-attested binding absent from a native hook row', () => { + const server = new AgentHookServer() + server.ingestTerminalStatus({ + paneKey: PANE, + payload: { state: 'working', agentType: 'antigravity', prompt: 'print marker' } + }) + const row = baseline(server) + expect(row.terminalHandle).toBeUndefined() + expect(server.ingestAntigravityScreenPermission({ baseline: row, command: 'echo OK' })).toBe( + false + ) + expect( + server.ingestAntigravityScreenPermission({ + baseline: { ...row, terminalHandle: 'term-runtime' }, + command: 'echo OK' + }) + ).toBe(true) + expect(baseline(server)).toMatchObject({ state: 'waiting', terminalHandle: 'term-runtime' }) +}) diff --git a/src/main/agent-hooks/server/server-ingest-antigravity-screen.ts b/src/main/agent-hooks/server/server-ingest-antigravity-screen.ts new file mode 100644 index 000000000000..2897a1ad726d --- /dev/null +++ b/src/main/agent-hooks/server/server-ingest-antigravity-screen.ts @@ -0,0 +1,81 @@ +import type { AgentStatusIpcPayload } from '../../../shared/agent-status-types' +import type { EnrichedAgentHookEventPayload } from './server-types' +import { AgentHookServerIngestNormalization } from './server-ingest-normalization' +import { isWslHookRelayConnectionId } from '../../../shared/wsl-hook-relay-contract' + +export type AntigravityScreenPermissionObservation = { + baseline: Pick +} & ({ command: string } | { command: null; clearedState: 'working' | 'done' }) + +const SCREEN_APPROVAL_PREFIX = '{"approval":{"source":"antigravity-screen",' + +export abstract class AgentHookServerIngestAntigravityScreen extends AgentHookServerIngestNormalization { + ingestAntigravityScreenPermission(request: AntigravityScreenPermissionObservation): boolean { + const { baseline, command } = request + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This server's canonical row writer stores enriched events in the shared listener map. + const previous = this.state.lastStatusByPaneKey.get(baseline.paneKey) as + | EnrichedAgentHookEventPayload + | undefined + const expected = baseline.observation + const current = previous?.observation + if ( + !previous || + previous.restoredUnconfirmed || + // Why: SSH mirrors stay on their execution host; a WSL relay row is this host's own pty. + (previous.connectionId && !isWslHookRelayConnectionId(previous.connectionId)) || + previous.payload.agentType !== 'antigravity' || + !baseline.terminalHandle || + (previous.terminalHandle !== undefined && + previous.terminalHandle !== baseline.terminalHandle) || + !expected || + !current || + current.authorityId !== expected.authorityId || + current.incarnation !== expected.incarnation || + current.revision !== expected.revision || + this.getAgentStatusDisposition(baseline.paneKey) !== 'accept' + ) { + return false + } + const ownsPrompt = + current.origin === 'process' && + previous.payload.state === 'waiting' && + previous.payload.interactivePrompt?.startsWith(SCREEN_APPROVAL_PREFIX) === true + if (command === null ? !ownsPrompt : previous.payload.state !== 'working' && !ownsPrompt) { + return false + } + const interactivePrompt = + command === null + ? undefined + : JSON.stringify({ + approval: { + source: 'antigravity-screen', + tool: previous.payload.toolName ?? 'run_command', + summary: command + } + }) + if (interactivePrompt === previous.payload.interactivePrompt) { + return true + } + // Only a positively identified working or idle screen can clear our approval. + return ( + this.applyNormalizedStatus( + { + paneKey: previous.paneKey, + tabId: previous.tabId, + worktreeId: previous.worktreeId, + connectionId: previous.connectionId, + terminalHandle: baseline.terminalHandle, + providerSession: previous.providerSession, + payload: { + ...previous.payload, + state: request.command === null ? request.clearedState : 'waiting', + ...(command === null ? { toolName: undefined, toolInput: undefined } : {}), + interactivePrompt + } + }, + undefined, + 'process' + ) !== undefined + ) + } +} diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 63355e3592b2..e1074b963375 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -5,9 +5,9 @@ import { terminalStatusPayloadMatchesHook } from '../../../shared/agent-terminal import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' import { isAgentStatusHeldOpenByChildWork } from '../../../shared/agent-lead-status-fold' -import { AgentHookServerIngestNormalization } from './server-ingest-normalization' +import { AgentHookServerIngestAntigravityScreen } from './server-ingest-antigravity-screen' -export abstract class AgentHookServerIngestTerminal extends AgentHookServerIngestNormalization { +export abstract class AgentHookServerIngestTerminal extends AgentHookServerIngestAntigravityScreen { ingestTerminalStatus(event: { ptyId?: string paneKey: string diff --git a/src/main/ai-vault/session-scanner-antigravity-parser.ts b/src/main/ai-vault/session-scanner-antigravity-parser.ts index c391f01bba73..d6ed8c8efea5 100644 --- a/src/main/ai-vault/session-scanner-antigravity-parser.ts +++ b/src/main/ai-vault/session-scanner-antigravity-parser.ts @@ -131,7 +131,7 @@ function consumeAntigravityRecordLine(accumulator: SessionAccumulator, line: str } } -function extractAntigravityUserRequest(content: string): string | null { +export function extractAntigravityUserRequest(content: string): string | null { const opener = '' const startIndex = content.indexOf(opener) if (startIndex === -1) { diff --git a/src/main/ai-vault/session-scanner-antigravity-paths.ts b/src/main/ai-vault/session-scanner-antigravity-paths.ts index 1930d78270b4..7455b6e3e575 100644 --- a/src/main/ai-vault/session-scanner-antigravity-paths.ts +++ b/src/main/ai-vault/session-scanner-antigravity-paths.ts @@ -4,6 +4,13 @@ const ANTIGRAVITY_TRANSCRIPT_FILE = 'transcript.jsonl' const ANTIGRAVITY_SYSTEM_DIR = '.system_generated' const ANTIGRAVITY_LOGS_DIR = 'logs' +export const ANTIGRAVITY_BRAIN_HOME_SEGMENTS = ['.gemini', 'antigravity-cli', 'brain'] as const + +/** Segments from a brain root to one conversation's transcript. */ +export function antigravityTranscriptSegmentsInBrain(conversationId: string): string[] { + return [conversationId, ANTIGRAVITY_SYSTEM_DIR, ANTIGRAVITY_LOGS_DIR, ANTIGRAVITY_TRANSCRIPT_FILE] +} + export function antigravityConversationIdFromTranscriptPath(filePath: string): string | null { const segments = pathSegments(filePath) const transcriptIndex = segments.length - 1 diff --git a/src/main/claude/claude-child-work-evidence-retention.test.ts b/src/main/claude/claude-child-work-evidence-retention.test.ts index 613c2694ac74..d98344289490 100644 --- a/src/main/claude/claude-child-work-evidence-retention.test.ts +++ b/src/main/claude/claude-child-work-evidence-retention.test.ts @@ -7,8 +7,8 @@ import type { import { deriveToolInputPreview } from '../../shared/agent-hook-listener/tool-input-preview' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { ClaudeChildWorkDecoder } from './claude-child-work-decoder' -import { claudeChildOperation, drainClaudeChildWork } from './claude-child-work-evidence' import { ClaudePromptRegistry } from './claude-prompt-registry' +import { claudeChildOperation, drainClaudeChildWork } from './claude-child-work-evidence' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' import { claudeToolResults, diff --git a/src/main/daemon/serialize-grid-transcript-replay.test.ts b/src/main/daemon/serialize-grid-transcript-replay.test.ts index 9a28f0a243aa..deaed374baa0 100644 --- a/src/main/daemon/serialize-grid-transcript-replay.test.ts +++ b/src/main/daemon/serialize-grid-transcript-replay.test.ts @@ -43,6 +43,8 @@ const KNOWN_PREEXISTING_I2_FAILURES: Record = { // Shrink leaves the cursor one column short; also present in the pre-Qoder serializer. 'qoder-no-account': 2, 'qoder-ready': 2, + // Prior efbf651c7bb2 also clamps the restored right-margin cursor (120→119); I1/I3 hold. + 'antigravity-windows-command-approval': 4, // Codex 0.157 header border restores with an extra attribute bit (STA-8628 fixtures). 'codex-0157-config-override-embedded-warning': 22, 'codex-0157-effort-override-embedded-warning': 4, @@ -247,6 +249,14 @@ describe('serialize round trip over captured PTY transcripts', () => { console.log(`${transcript.name} ${JSON.stringify(counts)}`) } expect(blocking).toEqual([]) + if (SEEDS === 2 && transcript.name === 'antigravity-windows-command-approval') { + expect(failureSignatures).toEqual([ + 'shrink-grow/false/1/30:ee4f2be236723b8d30e4c58413e1e2200e8c209cfc2b32c35b7caf0f6569c5bd', + 'shrink-grow/false/2/35:ee4f2be236723b8d30e4c58413e1e2200e8c209cfc2b32c35b7caf0f6569c5bd', + 'shrink-grow/true/1/30:ee4f2be236723b8d30e4c58413e1e2200e8c209cfc2b32c35b7caf0f6569c5bd', + 'shrink-grow/true/2/35:ee4f2be236723b8d30e4c58413e1e2200e8c209cfc2b32c35b7caf0f6569c5bd' + ]) + } if (SEEDS === 2 && transcript.name === 'hermes-tui-ready') { expect(failureSignatures).toEqual([ 'jitter/false/2/34:0db2561506ff28d2e83276b07bc8684541957f61e488b6f8081627e8cad80c63', diff --git a/src/main/native-chat/__fixtures__/antigravity/README.md b/src/main/native-chat/__fixtures__/antigravity/README.md new file mode 100644 index 000000000000..78cb7da8a208 --- /dev/null +++ b/src/main/native-chat/__fixtures__/antigravity/README.md @@ -0,0 +1,16 @@ +This fixture preserves the record and nested tool-call shapes observed in local +Antigravity CLI transcripts on 2026-09-19. Conversation text, tool arguments, +timestamps, and step numbers are replaced with harmless synthetic values. + +A planner step with `status: DONE` can precede a tool step and another planner +response without a new user prompt. It does not prove completion of the user turn. +Tool results use `source: MODEL` and their tool-specific step type; planner tool +calls carry arguments in `args`. + +`live-timestamp-tie.jsonl` preserves two actual macOS agy 1.2.14 records from +2026-10-02, produced by an authenticated Claude Sonnet Chat-composer turn in a +disposable folder. User step 9 and assistant step 10 have the same second-level +`created_at`. Their IDs and timestamps are retained to reproduce reply-before-user +lexical sorting; the optional provider step order fixes it without changing either. +Account identifiers, native username and task-profile suffix are scrubbed if present. +No synthesized model output is used in this capture. diff --git a/src/main/native-chat/__fixtures__/antigravity/live-timestamp-tie.jsonl b/src/main/native-chat/__fixtures__/antigravity/live-timestamp-tie.jsonl new file mode 100644 index 000000000000..fa81be09d0a4 --- /dev/null +++ b/src/main/native-chat/__fixtures__/antigravity/live-timestamp-tie.jsonl @@ -0,0 +1,2 @@ +{"step_index":9,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-10-02T09:54:18Z","content":"\nDo not use tools. Reply exactly ORCA_NATIVE_CHAT_DONE.\n\n\nThe current local time is: 2026-10-02T02:54:18-07:00.\n"} +{"step_index":10,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-10-02T09:54:18Z","content":"ORCA_NATIVE_CHAT_DONE","thinking":"The user wants me to reply exactly ORCA_NATIVE_CHAT_DONE without using any tools."} diff --git a/src/main/native-chat/__fixtures__/antigravity/tool-turn.jsonl b/src/main/native-chat/__fixtures__/antigravity/tool-turn.jsonl new file mode 100644 index 000000000000..255ef51ccd5b --- /dev/null +++ b/src/main/native-chat/__fixtures__/antigravity/tool-turn.jsonl @@ -0,0 +1,5 @@ +{"step_index":0,"source":"USER_EXPLICIT","type":"USER_INPUT","status":"DONE","created_at":"2026-09-19T10:00:00Z","content":"Inspect the sample file."} +{"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-09-19T10:00:01Z","thinking":"I will inspect the sample.","tool_calls":[{"name":"run_command","args":{"CommandLine":"printf sample","Cwd":"/workspace","WaitMsBeforeAsync":1000,"toolAction":"Inspect","toolSummary":"Read sample"}}]} +{"step_index":2,"source":"MODEL","type":"RUN_COMMAND","status":"DONE","exit_code":0,"created_at":"2026-09-19T10:00:02Z","content":"sample"} +{"step_index":3,"source":"SYSTEM","type":"CHECKPOINT","status":"DONE","created_at":"2026-09-19T10:00:03Z"} +{"step_index":4,"source":"MODEL","type":"PLANNER_RESPONSE","status":"DONE","created_at":"2026-09-19T10:00:04Z","content":"The sample file contains sample."} diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import-antigravity.test.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import-antigravity.test.ts new file mode 100644 index 000000000000..1ed8897753ed --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import-antigravity.test.ts @@ -0,0 +1,52 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { importLegacyTranscriptIntoJournal } from './journal-legacy-import' +import { openAgentSessionJournal } from './journal-store-factory' +import { + closeTestJournalHostDatabase, + openTestJournalHostDatabase +} from './journal-host-database-test-support' + +it('imports the Antigravity decoder into the durable journal without inventing turn completion', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-agy-journal-')) + const journal = await openAgentSessionJournal({ + identity: { + sessionId: 'conversation', + workspaceId: 'folder:workspace', + hostId: 'host', + agent: 'antigravity', + providerHandle: { kind: 'opaque', agent: 'antigravity', value: 'conversation' } + }, + database: openTestJournalHostDatabase(root) + }) + try { + const filePath = join(__dirname, '../__fixtures__/antigravity/tool-turn.jsonl') + const input = { + journal, + agent: 'antigravity' as const, + sessionId: 'conversation', + fence: 1, + options: { filePath } + } + expect((await importLegacyTranscriptIntoJournal(input)).ok).toBe(true) + const first = journal.snapshot().items + expect(first.some((item) => item.body.kind === 'tool-call')).toBe(true) + expect( + first.some((item) => item.body.kind === 'tool-call' && item.body.name === 'tool-result') + ).toBe(true) + expect(first.some((item) => item.body.kind === 'turn')).toBe(false) + expect(first.some((item) => item.body.kind === 'message' && item.body.role === 'user')).toBe( + true + ) + expect((await importLegacyTranscriptIntoJournal(input)).ok).toBe(true) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( + first.map((item) => item.itemId) + ) + } finally { + await journal.close() + closeTestJournalHostDatabase(root) + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index ba6a918cc6e4..2b9beb9edc11 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -22,6 +22,7 @@ import type { NativeChatBlock, NativeChatMessage } from '../../../shared/native- import { resolveNativeChatTranscriptAgent } from '../../../shared/native-chat-agent-support' import { resolveSessionFilePath, type ResolveSessionFileOptions } from '../session-file-resolver' import { + decodeAntigravityTranscriptLine, decodeClaudeTranscriptLine, decodeCodexTranscriptLine, decodeGrokTranscriptLine, @@ -148,6 +149,7 @@ export async function prepareLegacyTranscriptImport(input: { const TRANSCRIPT_DECODERS = { claude: decodeClaudeTranscriptLine, codex: decodeCodexTranscriptLine, + antigravity: decodeAntigravityTranscriptLine, grok: decodeGrokTranscriptLine, omp: decodeOmpTranscriptLine } as const diff --git a/src/main/native-chat/antigravity-execution-namespace-refusal.test.ts b/src/main/native-chat/antigravity-execution-namespace-refusal.test.ts new file mode 100644 index 000000000000..01c55de41021 --- /dev/null +++ b/src/main/native-chat/antigravity-execution-namespace-refusal.test.ts @@ -0,0 +1,219 @@ +import { mkdir, mkdtemp, 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 type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import type { RuntimeMobileSessionTerminalClientTab } from '../../shared/runtime-types' +import { + configureNativeChatExecutionNamespace, + antigravitySessionWslDistro +} from './native-chat-execution-namespace' +import { resolveSessionFilePath } from './session-file-resolver' +import { readNativeChatTranscript } from './transcript-reader' +import { readNativeChatTranscriptTail } from './transcript-tail-reader' +import { nativeChatTranscriptIncludesPath } from './native-chat-file-provenance' +import * as transcriptFs from './wsl-transcript-fs-access' + +const ID = 'repair-native-remote-collision' +let fixtureHome: string +let sentinel: string +let citedPath: string +let rows: AgentStatusIpcPayload[] = [] + +function owner(connectionId: string | null): AgentStatusIpcPayload { + return { + paneKey: 'tab:leaf', + agentType: 'antigravity', + state: 'working', + prompt: '', + receivedAt: 1, + stateStartedAt: 1, + connectionId, + providerSession: { key: 'conversation_id', id: ID } + } +} + +beforeEach(async () => { + rows = [] + configureNativeChatExecutionNamespace(() => rows) + fixtureHome = await mkdtemp(join(tmpdir(), 'namespace-sentinel-')) + vi.stubEnv('HOME', fixtureHome) + vi.stubEnv('USERPROFILE', fixtureHome) + const logs = join( + fixtureHome, + '.gemini', + 'antigravity-cli', + 'brain', + ID, + '.system_generated', + 'logs' + ) + sentinel = join(logs, 'transcript.jsonl') + citedPath = join(fixtureHome, 'local-only-evidence.txt') + await mkdir(logs, { recursive: true }) + await writeFile( + sentinel, + `${JSON.stringify({ + step_index: 0, + source: 'MODEL', + type: 'PLANNER_RESPONSE', + status: 'DONE', + content: `Open ${citedPath}` + })}\n` + ) + vi.spyOn(transcriptFs, 'wslGatedOpen') + vi.spyOn(transcriptFs, 'openTranscriptReadStream') +}) +afterEach(async () => { + configureNativeChatExecutionNamespace(() => []) + vi.restoreAllMocks() + vi.unstubAllEnvs() + await rm(fixtureHome, { recursive: true, force: true }) +}) + +it.each([ + 'ssh-only', + 'runtime:paired-only', + 'runtime-paired-only', + 'runtime-ssh-paired-host', + 'unknown-host', + ' ' +])('refuses %s before opening the same-named native transcript', async (connectionId) => { + rows = [owner(connectionId)] + await expect(resolveSessionFilePath('antigravity', ID)).rejects.toThrow(/namespace.*unavailable/) + await expect(readNativeChatTranscript('antigravity', ID)).rejects.toThrow( + /namespace.*unavailable/ + ) + await expect( + readNativeChatTranscriptTail({ agent: 'antigravity', sessionId: ID, limit: 10 }) + ).rejects.toThrow(/namespace.*unavailable/) + expect(transcriptFs.wslGatedOpen).not.toHaveBeenCalled() + expect(transcriptFs.openTranscriptReadStream).not.toHaveBeenCalled() +}) + +it.each([null, 'wsl:Ubuntu'])( + 'refuses remote ownership even beside a same-ID %s owner', + async (connectionId) => { + rows = [owner(connectionId), owner('ssh-unverifiable')] + await expect(resolveSessionFilePath('antigravity', ID)).rejects.toThrow( + /namespace.*unavailable/ + ) + expect(transcriptFs.wslGatedOpen).not.toHaveBeenCalled() + } +) + +it.each([ + [null, 'wsl:Ubuntu'], + ['wsl:Ubuntu', 'wsl:Debian'] +] as const)( + 'rejects ambiguous native/guest or different-guest owners (%s, %s)', + async (left, right) => { + rows = [owner(left), owner(right)] + await expect(resolveSessionFilePath('antigravity', ID)).rejects.toThrow(/namespace.*ambiguous/) + } +) + +it('deduplicates the same WSL distro and refuses a mismatched requested distro', async () => { + rows = [owner('wsl:Ubuntu'), owner('wsl:Ubuntu')] + expect(antigravitySessionWslDistro(ID)).toBe('Ubuntu') + await expect(resolveSessionFilePath('antigravity', ID, { wslDistro: 'Debian' })).rejects.toThrow( + /namespace.*match/ + ) +}) + +it.each(['historical', 'native'])('preserves %s transcripts', async (kind) => { + rows = kind === 'native' ? [owner(null)] : [] + expect(await resolveSessionFilePath('antigravity', ID)).toBe(sentinel) + const full = await readNativeChatTranscript('antigravity', ID) + expect(full).toMatchObject({ + messages: [{ blocks: [{ type: 'text', text: `Open ${citedPath}` }] }] + }) + const tail = await readNativeChatTranscriptTail({ + agent: 'antigravity', + sessionId: ID, + limit: 10 + }) + expect(tail).toHaveProperty('messages') + expect(transcriptFs.wslGatedOpen).toHaveBeenCalled() +}) + +function clientTab(connectionId: string | null | undefined): RuntimeMobileSessionTerminalClientTab { + return { + type: 'terminal', + id: 'tab', + title: 'Antigravity', + parentTabId: 'tab', + leafId: 'leaf', + launchAgent: 'antigravity', + isActive: true, + status: 'ready', + terminal: 'term', + agentStatus: { + paneKey: 'tab:leaf', + agentType: 'antigravity', + state: 'working', + prompt: '', + updatedAt: 1, + stateStartedAt: 1, + stateHistory: [], + connectionId, + providerSession: { key: 'conversation_id', id: ID } + } + } +} + +it.each([ + ['ssh-unverifiable', true], + ['runtime-ssh-paired-host', true], + ['ssh-unverifiable', false], + ['runtime-ssh-paired-host', false], + ['unknown-host', false], + ['wsl:Ubuntu', false], + ['wsl:', false] +] as const)( + 'the ungated provenance path refuses the native collision for %s (canonical owner present: %s)', + async (connectionId, ownerPresent) => { + rows = ownerPresent ? [owner(connectionId)] : [] + expect( + await nativeChatTranscriptIncludesPath({ + tabs: [clientTab(connectionId)], + context: { tabId: 'tab', sessionId: ID }, + pathText: citedPath, + absolutePath: citedPath + }) + ).toBe(false) + expect(transcriptFs.wslGatedOpen).not.toHaveBeenCalled() + } +) + +it.each([null, undefined])( + 'preserves native and historical provenance (%s connection)', + async (connectionId) => { + expect( + await nativeChatTranscriptIncludesPath({ + tabs: [clientTab(connectionId)], + context: { tabId: 'tab', sessionId: ID }, + pathText: citedPath, + absolutePath: citedPath + }) + ).toBe(true) + expect(transcriptFs.wslGatedOpen).toHaveBeenCalled() + } +) + +it.each([null, 'wsl:Debian'])( + 'refuses a WSL tab constraint that disagrees with its %s canonical owner', + async (connectionId) => { + rows = [owner(connectionId)] + expect(() => antigravitySessionWslDistro(ID, 'wsl:Ubuntu')).toThrow('ambiguous') + expect( + await nativeChatTranscriptIncludesPath({ + tabs: [clientTab('wsl:Ubuntu')], + context: { tabId: 'tab', sessionId: ID }, + pathText: citedPath, + absolutePath: citedPath + }) + ).toBe(false) + expect(transcriptFs.wslGatedOpen).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/antigravity-session-file-resolution.ts b/src/main/native-chat/antigravity-session-file-resolution.ts new file mode 100644 index 000000000000..a415cfc56385 --- /dev/null +++ b/src/main/native-chat/antigravity-session-file-resolution.ts @@ -0,0 +1,61 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import { + ANTIGRAVITY_BRAIN_HOME_SEGMENTS, + antigravityTranscriptSegmentsInBrain +} from '../ai-vault/session-scanner-antigravity-paths' +import { + createWslTranscriptResolutionSnapshot, + toHostReadableTranscriptPath, + wslAntigravityTranscriptPaths +} from './host-readable-transcript-path' +import { wslTranscriptFsRefusal, type WslTranscriptFsError } from './wsl-transcript-fs-gate' + +export async function resolveAntigravitySessionFile( + conversationId: string, + brainDirOverride: string | undefined, + signal?: AbortSignal, + wslDistro?: string +): Promise { + // A conversation id is one directory segment, never a caller-supplied path. + if (!/^[a-zA-Z0-9_-]+$/.test(conversationId)) { + return null + } + const hostHit = wslDistro + ? null + : await toHostReadableTranscriptPath( + join( + brainDirOverride ?? join(homedir(), ...ANTIGRAVITY_BRAIN_HOME_SEGMENTS), + ...antigravityTranscriptSegmentsInBrain(conversationId) + ), + { signal } + ) + signal?.throwIfAborted() + if (!wslDistro) { + return hostHit + } + if (process.platform !== 'win32') { + return null + } + // Only inspect the attested guest; equal session ids do not establish ownership. + signal?.throwIfAborted() + const wslSnapshot = await createWslTranscriptResolutionSnapshot({ includeHomes: false }) + wslSnapshot.runningDistros = wslSnapshot.runningDistros.filter((distro) => distro === wslDistro) + signal?.throwIfAborted() + let unavailable: WslTranscriptFsError | undefined + for (const candidate of await wslAntigravityTranscriptPaths(conversationId, { wslSnapshot })) { + try { + const hit = await toHostReadableTranscriptPath(candidate, { signal, wslSnapshot, wslDistro }) + if (hit) { + return hit + } + } catch (error) { + signal?.throwIfAborted() + unavailable = wslTranscriptFsRefusal(error) + } + } + if (unavailable) { + throw unavailable + } + return null +} diff --git a/src/main/native-chat/host-readable-transcript-path.ts b/src/main/native-chat/host-readable-transcript-path.ts index bb29955c3838..e9c9d441acfa 100644 --- a/src/main/native-chat/host-readable-transcript-path.ts +++ b/src/main/native-chat/host-readable-transcript-path.ts @@ -2,6 +2,10 @@ import { existsSync } from 'node:fs' import { isAbsolute } from 'node:path' import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' import { WSL_CODEX_RUNTIME_HOME_SEGMENTS } from '../pty/codex-home-wsl-env' +import { + ANTIGRAVITY_BRAIN_HOME_SEGMENTS, + antigravityTranscriptSegmentsInBrain +} from '../ai-vault/session-scanner-antigravity-paths' import { getWslHomeAsync, listRunningWslDistrosAsync, listRunningWslHomeDirsAsync } from '../wsl' import { filterPathsToRunningWslDistrosAsync, @@ -292,6 +296,28 @@ export async function wslCodexSessionsDirs( return dirs.filter((dir, index) => dirs.indexOf(dir) === index) } +/** agy launched in a WSL pane writes under the guest home, like AI Vault's WSL brain roots. */ +export async function wslAntigravityTranscriptPaths( + conversationId: string, + deps: Pick = {} +): Promise { + const platform = deps.platform ?? process.platform + if (platform !== 'win32') { + return [] + } + const homeDirs = deps.wslSnapshot + ? await snapshotHomeDirs(deps.wslSnapshot) + : await resolveWslHomeDirs(deps.listWslHomeDirs) + const paths = homeDirs.map((home) => + joinUnderWslHome( + home, + ...ANTIGRAVITY_BRAIN_HOME_SEGMENTS, + ...antigravityTranscriptSegmentsInBrain(conversationId) + ) + ) + return paths.filter((path, index) => paths.indexOf(path) === index) +} + // Why: node:path.join is posix-flavoured off Windows and would mangle the // `\\wsl.localhost\` share prefix these roots must keep. function joinUnderWslHome(home: string, ...segments: string[]): string { diff --git a/src/main/native-chat/native-chat-execution-namespace.test.ts b/src/main/native-chat/native-chat-execution-namespace.test.ts new file mode 100644 index 000000000000..38913c60aaee --- /dev/null +++ b/src/main/native-chat/native-chat-execution-namespace.test.ts @@ -0,0 +1,47 @@ +import { afterEach, expect, it } from 'vitest' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import { + antigravitySessionWslDistro, + configureNativeChatExecutionNamespace +} from './native-chat-execution-namespace' + +function row(connectionId: string | null, sessionId = 'conversation'): AgentStatusIpcPayload { + return { + paneKey: 'tab:leaf', + state: 'working', + prompt: '', + receivedAt: 1, + stateStartedAt: 1, + agentType: 'antigravity', + connectionId, + providerSession: { key: 'conversation_id', id: sessionId } + } +} + +afterEach(() => configureNativeChatExecutionNamespace(() => [])) + +it('reads the current owning-host store on every lookup without caching scope', () => { + let rows = [row('wsl:Debian'), row('wsl:Ubuntu', 'other')] + configureNativeChatExecutionNamespace(() => rows) + expect(antigravitySessionWslDistro('conversation')).toBe('Debian') + rows = [row('wsl:Ubuntu')] + expect(antigravitySessionWslDistro('conversation')).toBe('Ubuntu') +}) + +it.each([ + [row('wsl:Debian'), row('wsl:Ubuntu')], + [row(null), row('wsl:Debian')] +])('refuses a same-ID ambiguity across execution namespaces', (...rows) => { + configureNativeChatExecutionNamespace(() => rows) + expect(() => antigravitySessionWslDistro('conversation')).toThrow('ambiguous') +}) + +it('does not import direct SSH mirror identity into the local namespace', () => { + configureNativeChatExecutionNamespace(() => [row('ssh-host'), row('wsl:Debian')]) + expect(() => antigravitySessionWslDistro('conversation')).toThrow('unavailable') +}) + +it('refuses an unverified WSL relay distro', () => { + configureNativeChatExecutionNamespace(() => [row('wsl:')]) + expect(() => antigravitySessionWslDistro('conversation')).toThrow('unavailable') +}) diff --git a/src/main/native-chat/native-chat-execution-namespace.ts b/src/main/native-chat/native-chat-execution-namespace.ts new file mode 100644 index 000000000000..f2321d0c4f1f --- /dev/null +++ b/src/main/native-chat/native-chat-execution-namespace.ts @@ -0,0 +1,45 @@ +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import { + isWslHookRelayConnectionId, + WSL_HOOK_RELAY_CONNECTION_PREFIX +} from '../../shared/wsl-hook-relay-contract' + +let readProviderSessions: () => readonly AgentStatusIpcPayload[] = () => [] + +export function configureNativeChatExecutionNamespace( + read: () => readonly AgentStatusIpcPayload[] +): void { + readProviderSessions = read +} + +function antigravityConnectionNamespace(connectionId: string | null | undefined): string { + if (isWslHookRelayConnectionId(connectionId)) { + const distro = connectionId?.slice(WSL_HOOK_RELAY_CONNECTION_PREFIX.length).trim() + if (distro) { + return distro + } + } else if (!connectionId) { + return '' + } + throw new Error('Antigravity transcript execution namespace is unavailable') +} + +export function antigravitySessionWslDistro( + sessionId: string, + expectedConnectionId?: string | null +): string | undefined { + const namespaces = new Set() + if (expectedConnectionId !== undefined) { + namespaces.add(antigravityConnectionNamespace(expectedConnectionId)) + } + for (const row of readProviderSessions()) { + if (row.agentType !== 'antigravity' || row.providerSession?.id !== sessionId) { + continue + } + namespaces.add(antigravityConnectionNamespace(row.connectionId)) + } + if (namespaces.size > 1) { + throw new Error('Antigravity transcript execution namespace is ambiguous') + } + return namespaces.values().next().value || undefined +} diff --git a/src/main/native-chat/native-chat-file-provenance.ts b/src/main/native-chat/native-chat-file-provenance.ts index 07b0b47082e4..9d42801cfbab 100644 --- a/src/main/native-chat/native-chat-file-provenance.ts +++ b/src/main/native-chat/native-chat-file-provenance.ts @@ -7,6 +7,7 @@ import type { } from '../../shared/runtime-types' import { recentTerminalOutputIncludesPath } from '../runtime/terminal-output-path-candidates' import { readNativeChatTranscriptTail } from './transcript-tail-reader' +import { antigravitySessionWslDistro } from './native-chat-execution-namespace' // Match the largest transcript window mobile can render so any visible citation remains provable. const NATIVE_CHAT_FILE_PROVENANCE_WINDOW = 2000 @@ -15,6 +16,7 @@ type TranscriptRead = (args: { agent: AgentType sessionId: string transcriptPath?: string + wslDistro?: string limit: number }) => Promise<{ messages: NativeChatMessage[] } | { error: string }> @@ -50,10 +52,15 @@ export async function nativeChatTranscriptIncludesPath(args: { } try { + const wslDistro = + agent === 'antigravity' + ? antigravitySessionWslDistro(providerSession.id, tab.agentStatus?.connectionId) + : undefined const result = await (args.readTranscript ?? readNativeChatTranscriptTail)({ agent, sessionId: providerSession.id, ...(providerSession.transcriptPath ? { transcriptPath: providerSession.transcriptPath } : {}), + ...(wslDistro ? { wslDistro } : {}), limit: NATIVE_CHAT_FILE_PROVENANCE_WINDOW }) if (!('messages' in result)) { diff --git a/src/main/native-chat/session-file-resolver-antigravity-wsl.test.ts b/src/main/native-chat/session-file-resolver-antigravity-wsl.test.ts new file mode 100644 index 000000000000..af971b642d07 --- /dev/null +++ b/src/main/native-chat/session-file-resolver-antigravity-wsl.test.ts @@ -0,0 +1,240 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsModule from 'node:fs' +import type * as NodeOsModule from 'node:os' +import type * as WslTranscriptFsAccessModule from './wsl-transcript-fs-access' + +const CONVERSATION_ID = '4c45c752-d568-475a-9a04-973901abee4c' +const TRANSCRIPT_TAIL = `.gemini\\antigravity-cli\\brain\\${CONVERSATION_ID}\\.system_generated\\logs\\transcript.jsonl` +const UBUNTU_TRANSCRIPT = `\\\\wsl.localhost\\Ubuntu\\home\\ada\\${TRANSCRIPT_TAIL}` +const DEBIAN_TRANSCRIPT = `\\\\wsl.localhost\\Debian\\home\\ada\\${TRANSCRIPT_TAIL}` + +const mocks = vi.hoisted(() => ({ + hostExisting: new Set(), + // UNC path → true (readable), or 'stall' for a gate refusal. Absent means missing. + wslFiles: new Map(), + existsSync: vi.fn(), + wslGatedAccess: vi.fn() +})) + +vi.mock('node:os', async (importOriginal) => ({ + ...(await importOriginal()), + homedir: () => 'C:\\Users\\ada' +})) +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + mocks.existsSync.mockImplementation((path: string) => + [...mocks.hostExisting].some((hostPath) => path === hostPath) + ) + return { ...actual, existsSync: mocks.existsSync } +}) +vi.mock('./wsl-transcript-fs-access', async (importOriginal) => { + const { wslTranscriptFsTimeoutError } = await import('./wsl-transcript-fs-error') + mocks.wslGatedAccess.mockImplementation(async (path: string) => { + const entry = mocks.wslFiles.get(path) + if (entry === 'stall') { + throw wslTranscriptFsTimeoutError() + } + return entry === true + }) + return { + ...(await importOriginal()), + wslGatedAccess: mocks.wslGatedAccess + } +}) +vi.mock('../wsl', () => ({ + listRunningWslDistrosAsync: vi.fn(async () => ['Ubuntu', 'Debian']), + listRunningWslHomeDirsAsync: vi.fn(async () => [ + '\\\\wsl.localhost\\Ubuntu\\home\\ada', + '\\\\wsl.localhost\\Debian\\home\\ada' + ]), + getWslHomeAsync: vi.fn(async (distro: string) => `\\\\wsl.localhost\\${distro}\\home\\ada`) +})) + +import { join } from 'node:path' +import { resolveSessionFilePath } from './session-file-resolver' +import { resetHostReadableTranscriptPathCacheForTests } from './host-readable-transcript-path' +import { WslTranscriptFsError } from './wsl-transcript-fs-error' +import { listRunningWslDistrosAsync, listRunningWslHomeDirsAsync } from '../wsl' +import { configureNativeChatExecutionNamespace } from './native-chat-execution-namespace' + +const HOST_TRANSCRIPT = join( + 'C:\\Users\\ada', + '.gemini', + 'antigravity-cli', + 'brain', + CONVERSATION_ID, + '.system_generated', + 'logs', + 'transcript.jsonl' +) + +const realPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) +} + +beforeEach(() => { + resetHostReadableTranscriptPathCacheForTests() + configureNativeChatExecutionNamespace(() => []) + mocks.hostExisting.clear() + mocks.wslFiles.clear() + mocks.existsSync.mockClear() + mocks.wslGatedAccess.mockClear() + vi.mocked(listRunningWslDistrosAsync).mockClear() + vi.mocked(listRunningWslHomeDirsAsync).mockClear() + setPlatform('win32') +}) + +afterEach(() => { + setPlatform(realPlatform) + configureNativeChatExecutionNamespace(() => []) +}) + +describe('Antigravity id-based resolve on a Windows host with WSL', () => { + it('does not guess an unassociated conversation across WSL guests', async () => { + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + await expect(resolveSessionFilePath('antigravity', CONVERSATION_ID)).resolves.toBeNull() + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + }) + + it('derives id-only namespace from the owning host canonical session row', async () => { + configureNativeChatExecutionNamespace(() => [ + { + paneKey: 'tab:leaf', + state: 'working', + prompt: '', + receivedAt: 1, + stateStartedAt: 1, + agentType: 'antigravity', + connectionId: 'wsl:Debian', + providerSession: { key: 'conversation_id', id: CONVERSATION_ID } + } + ]) + mocks.hostExisting.add(HOST_TRANSCRIPT) + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + mocks.wslFiles.set(DEBIAN_TRANSCRIPT, true) + await expect(resolveSessionFilePath('antigravity', CONVERSATION_ID)).resolves.toBe( + DEBIAN_TRANSCRIPT + ) + expect(mocks.existsSync).not.toHaveBeenCalledWith(HOST_TRANSCRIPT) + expect(mocks.wslGatedAccess).not.toHaveBeenCalledWith( + UBUNTU_TRANSCRIPT, + expect.anything(), + expect.anything() + ) + }) + + it('reads only the attested guest even when a native duplicate exists', async () => { + mocks.hostExisting.add(HOST_TRANSCRIPT) + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { wslDistro: 'Ubuntu' }) + ).resolves.toBe(UBUNTU_TRANSCRIPT) + expect(mocks.existsSync).not.toHaveBeenCalledWith(HOST_TRANSCRIPT) + }) + + it('keeps the host transcript first and never enumerates WSL homes on a host hit', async () => { + mocks.hostExisting.add(HOST_TRANSCRIPT) + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + + await expect(resolveSessionFilePath('antigravity', CONVERSATION_ID)).resolves.toBe( + HOST_TRANSCRIPT + ) + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + }) + + it('treats an explicit brain root as exact and skips the WSL fallback', async () => { + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { + antigravityBrainDir: 'C:\\isolated\\brain' + }) + ).resolves.toBeNull() + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + }) + + it('probes running distros once per attempt, not once per candidate', async () => { + mocks.wslFiles.set(DEBIAN_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { wslDistro: 'Debian' }) + ).resolves.toBe(DEBIAN_TRANSCRIPT) + expect(listRunningWslDistrosAsync).toHaveBeenCalledTimes(1) + }) + + it('does not start WSL discovery for a cancelled lookup', async () => { + const controller = new AbortController() + mocks.existsSync.mockImplementationOnce(() => { + controller.abort() + return false + }) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, {}, controller.signal) + ).rejects.toThrow() + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + expect(listRunningWslHomeDirsAsync).not.toHaveBeenCalled() + }) + + it('does not replace a stalled owning distro with a responsive duplicate', async () => { + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, 'stall') + mocks.wslFiles.set(DEBIAN_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { wslDistro: 'Ubuntu' }) + ).rejects.toBeInstanceOf(WslTranscriptFsError) + }) + + it('reports a stalled distro as unavailable instead of missing', async () => { + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, 'stall') + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { wslDistro: 'Ubuntu' }) + ).rejects.toBeInstanceOf(WslTranscriptFsError) + }) + + it('rejects a path-shaped conversation id before touching any filesystem', async () => { + await expect(resolveSessionFilePath('antigravity', '..\\..\\secrets')).resolves.toBeNull() + expect(mocks.existsSync).not.toHaveBeenCalled() + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + }) + + it('does not replace an attested distro miss with an id match in another guest', async () => { + mocks.wslFiles.set(DEBIAN_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { wslDistro: 'Ubuntu' }) + ).resolves.toBeNull() + expect(mocks.wslGatedAccess).not.toHaveBeenCalledWith( + DEBIAN_TRANSCRIPT, + expect.anything(), + expect.anything() + ) + }) + + it('does not replace a missing guest hook path with an id match', async () => { + mocks.wslFiles.set(DEBIAN_TRANSCRIPT, true) + + await expect( + resolveSessionFilePath('antigravity', CONVERSATION_ID, { + transcriptPath: `/home/ada/.gemini/antigravity-cli/brain/other/.system_generated/logs/transcript.jsonl` + }) + ).resolves.toBeNull() + expect(mocks.wslGatedAccess).not.toHaveBeenCalledWith( + DEBIAN_TRANSCRIPT, + expect.anything(), + expect.anything() + ) + }) + + it('never enumerates WSL homes off Windows', async () => { + setPlatform('linux') + mocks.wslFiles.set(UBUNTU_TRANSCRIPT, true) + + await expect(resolveSessionFilePath('antigravity', CONVERSATION_ID)).resolves.toBeNull() + expect(listRunningWslDistrosAsync).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 08de49763b45..6edff4fddef5 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -9,7 +9,9 @@ import { isWslUncPath } from '../../shared/wsl-paths' import { walkSessionFiles } from '../ai-vault/session-scanner-discovery' import { OMP_SESSION_ARTIFACT_DIR_PATTERN } from '../ai-vault/session-scanner-omp-subagent-transcripts' import { resolveOmpSessionsDir } from '../ai-vault/omp-session-root' +import { resolveAntigravitySessionFile } from './antigravity-session-file-resolution' import { resolveOrcaManagedCodexHomePath } from '../codex/codex-home-paths' +import { antigravitySessionWslDistro } from './native-chat-execution-namespace' import { findGrokChatHistoryBySessionId, resolveGrokSessionsDir @@ -74,6 +76,8 @@ export type ResolveSessionFileOptions = { grokSessionsDir?: string /** Override the omp sessions root (`~/.omp/agent/sessions`). */ ompSessionsDir?: string + /** Antigravity CLI brain root on the execution host. */ + antigravityBrainDir?: string /** Authoritative transcript path reported by the agent hook * (`providerSession.transcriptPath`). When set and the file exists, it is used * directly — recent Claude Code names the transcript with a UUID that differs @@ -104,12 +108,29 @@ export async function resolveSessionFilePath( if (!transcriptAgent || transcriptAgent === 'opencode') { return null } + if (transcriptAgent === 'antigravity') { + const canonicalDistro = antigravitySessionWslDistro(sessionId) + if (canonicalDistro && options.wslDistro && canonicalDistro !== options.wslDistro) { + throw new Error('Antigravity transcript execution namespace does not match') + } + if (canonicalDistro) { + options = { ...options, wslDistro: canonicalDistro } + } + } // Why: the hook's transcript_path is the exact file the agent is writing, so it // beats reconstructing a path from the session id. Route it through the host // readability check so a WSL guest path becomes an openable UNC on Windows; // stale/missing paths fall through to the id-based search. let unavailable: WslTranscriptFsError | undefined const hookPath = options.transcriptPath?.trim() + if ( + transcriptAgent === 'antigravity' && + options.wslDistro && + hookPath && + !needsWslHostResolution(hookPath) + ) { + throw new Error('Antigravity guest transcript path does not match its execution namespace') + } if (hookPath && extname(hookPath) === '.jsonl') { try { const hostReadable = await toHostReadableTranscriptPath(hookPath, { @@ -144,7 +165,14 @@ export async function resolveSessionFilePath( if (unavailable) { throw unavailable } - return null + return transcriptAgent === 'antigravity' && !hookPath + ? resolveAntigravitySessionFile( + sessionId, + options.antigravityBrainDir, + signal, + options.wslDistro + ) + : null } const resolved = await resolveSessionFileById(transcriptAgent, sessionId, options, signal) @@ -188,6 +216,9 @@ async function resolveSessionFileById( signal ) } + if (transcriptAgent === 'antigravity') { + return resolveAntigravitySessionFile(trimmedId, options.antigravityBrainDir, signal) + } if (transcriptAgent === 'grok') { return resolveGrokSessionFile(trimmedId, options.grokSessionsDir ?? grokSessionsDir(), signal) } diff --git a/src/main/native-chat/transcript-line-decoders-antigravity.ts b/src/main/native-chat/transcript-line-decoders-antigravity.ts new file mode 100644 index 000000000000..1d2aed636c86 --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders-antigravity.ts @@ -0,0 +1,147 @@ +// Antigravity (AGY) JSONL line → NativeChatMessage decoder. + +import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types' +import { + asRecord, + extractString, + parseJsonObject, + timestampMs +} from '../ai-vault/session-scanner-values' +import { extractAntigravityUserRequest } from '../ai-vault/session-scanner-antigravity-parser' + +const TOOL_STEP_TYPES = new Set([ + 'RUN_COMMAND', + 'LIST_DIRECTORY', + 'GENERIC', + 'INVOKE_SUBAGENT', + 'VIEW_FILE', + 'CODE_ACTION', + 'GREP_SEARCH', + 'SEARCH_WEB' +]) + +export function decodeAntigravityTranscriptLine( + line: string, + fallbackId: string +): NativeChatMessage | null { + const record = parseJsonObject(line) + if (!record) { + return null + } + + const timestamp = parseTimestamp(record.created_at ?? record.timestamp) + // Antigravity's created_at clock is second-granular; a fallback timestamp has no such contract. + const coarseTimestamp = + (typeof record.created_at === 'string' || + (typeof record.created_at === 'number' && record.created_at <= 1_000_000_000_000)) && + timestamp !== null && + timestamp % 1000 === 0 + const stepIndex = + typeof record.step_index === 'number' + ? String(record.step_index) + : (extractString(record.step_index) ?? extractString(record.id)) + const id = stepIndex ?? fallbackId + const ordinal = stepIndex && /^\d+$/.test(stepIndex) ? Number(stepIndex) : undefined + const transcriptPosition = + ordinal !== undefined && Number.isSafeInteger(ordinal) ? ordinal : undefined + const source = extractString(record.source) + const type = extractString(record.type) + + if ( + (source === 'USER_EXPLICIT' || source === 'USER') && + (type === 'USER_INPUT' || type === 'REQUEST') + ) { + const rawContent = extractString(record.content) ?? '' + const text = extractAntigravityUserRequest(rawContent) || rawContent + if (!text.trim()) { + return null + } + return { + id, + role: 'user', + blocks: [{ type: 'text', text }], + timestamp, + ...(coarseTimestamp ? { timestampPrecision: 'second' as const } : {}), + ...(transcriptPosition === undefined ? {} : { transcriptPosition }), + source: 'transcript' + } + } + + if (source === 'MODEL' && type === 'PLANNER_RESPONSE') { + const blocks: NativeChatBlock[] = [] + + const thinking = extractString(record.thinking) + if (thinking && thinking.trim()) { + blocks.push({ type: 'text', text: `> *Thinking:*\n${thinking}` }) + } + + const content = extractString(record.content) + if (content && content.trim()) { + blocks.push({ type: 'text', text: content }) + } + + blocks.push(...toolCallBlocks(record.tool_calls)) + + if (blocks.length === 0) { + return null + } + + return { + id, + role: 'assistant', + blocks, + timestamp, + ...(coarseTimestamp ? { timestampPrecision: 'second' as const } : {}), + ...(transcriptPosition === undefined ? {} : { transcriptPosition }), + source: 'transcript' + } + } + + // Recorded tool steps are MODEL records, not TOOL_RESULT messages. + if (source === 'MODEL' && type && TOOL_STEP_TYPES.has(type)) { + const output = extractString(record.content) + const blocks = toolCallBlocks(record.tool_calls) + const isError = + record.status === 'ERROR' || (typeof record.exit_code === 'number' && record.exit_code !== 0) + if (output) { + blocks.push({ type: 'tool-result', output, ...(isError ? { isError: true } : {}) }) + } + if (blocks.length === 0) { + return null + } + return { + id, + role: 'tool', + blocks, + timestamp, + ...(coarseTimestamp ? { timestampPrecision: 'second' as const } : {}), + ...(transcriptPosition === undefined ? {} : { transcriptPosition }), + source: 'transcript' + } + } + + return null +} + +function parseTimestamp(value: unknown): number | null { + const parsed = timestampMs(value) + return Number.isFinite(parsed) ? parsed : null +} + +function toolCallBlocks(value: unknown): NativeChatBlock[] { + if (!Array.isArray(value)) { + return [] + } + return value.flatMap((call) => { + const tool = asRecord(call) + return tool + ? [ + { + type: 'tool-call' as const, + name: extractString(tool.name) ?? 'tool', + input: tool.args ?? tool.arguments ?? tool.input ?? null + } + ] + : [] + }) +} diff --git a/src/main/native-chat/transcript-line-decoders.antigravity.test.ts b/src/main/native-chat/transcript-line-decoders.antigravity.test.ts new file mode 100644 index 000000000000..133b7da10779 --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders.antigravity.test.ts @@ -0,0 +1,126 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { projectNativeChatTranscriptMessages } from '../../shared/native-chat-transcript-projection' +import { decodeAntigravityTranscriptLine } from './transcript-line-decoders-antigravity' + +const lines = readFileSync( + new URL('./__fixtures__/antigravity/tool-turn.jsonl', import.meta.url), + 'utf8' +) + .trim() + .split('\n') + +function decode(record: unknown) { + return decodeAntigravityTranscriptLine(JSON.stringify(record), 'line-1') +} + +describe('Antigravity transcript records', () => { + it('preserves the recorded prompt, tool arguments, output, and subsequent response', () => { + const messages = lines.map((line, index) => + decodeAntigravityTranscriptLine(line, `line-${index}`) + ) + expect(messages[0]).toMatchObject({ + role: 'user', + blocks: [{ type: 'text', text: 'Inspect the sample file.' }] + }) + expect(messages[1]?.blocks).toContainEqual({ + type: 'tool-call', + name: 'run_command', + input: { + CommandLine: 'printf sample', + Cwd: '/workspace', + WaitMsBeforeAsync: 1000, + toolAction: 'Inspect', + toolSummary: 'Read sample' + } + }) + expect(messages[2]).toMatchObject({ + role: 'tool', + blocks: [{ type: 'tool-result', output: 'sample' }] + }) + expect(messages[3]).toBeNull() + expect(messages[4]).toMatchObject({ + role: 'assistant', + blocks: [{ type: 'text', text: 'The sample file contains sample.' }] + }) + }) + + it.each([ + 'RUN_COMMAND', + 'VIEW_FILE', + 'LIST_DIRECTORY', + 'GREP_SEARCH', + 'CODE_ACTION', + 'GENERIC', + 'INVOKE_SUBAGENT' + ])('keeps recorded %s output without treating step completion as turn completion', (type) => { + expect(decode({ source: 'MODEL', type, status: 'DONE', content: 'output' })).toMatchObject({ + role: 'tool', + blocks: [{ type: 'tool-result', output: 'output' }] + }) + }) + + it.each([{ status: 'ERROR' }, { status: 'DONE', exit_code: 1 }])( + 'marks failed tool results', + (fields) => { + expect( + decode({ source: 'MODEL', type: 'RUN_COMMAND', content: 'failed', ...fields })?.blocks + ).toEqual([{ type: 'tool-result', output: 'failed', isError: true }]) + } + ) + + it('ignores malformed, empty, and system bookkeeping records', () => { + expect(decodeAntigravityTranscriptLine('{', 'line')).toBeNull() + expect(decode({ source: 'MODEL', type: 'PLANNER_RESPONSE' })).toBeNull() + expect(decode({ source: 'SYSTEM', type: 'CHECKPOINT', content: 'private context' })).toBeNull() + }) +}) + +it('keeps tool arguments on the observed MODEL/GENERIC shape, including outputless calls', () => { + const tool_calls = [{ name: 'view_file', args: { path: '/workspace/sample.txt' } }] + const record = { source: 'MODEL', type: 'GENERIC', tool_calls } + const expected = { + type: 'tool-call', + name: 'view_file', + input: { path: '/workspace/sample.txt' } + } + expect(decode(record)?.blocks).toEqual([expected]) + expect(decode({ ...record, content: 'sample' })?.blocks).toEqual([ + expected, + { type: 'tool-result', output: 'sample' } + ]) +}) + +it('preserves user-before-response step order across a decimal boundary at the same second', () => { + const [userLine, replyLine] = readFileSync( + new URL('./__fixtures__/antigravity/live-timestamp-tie.jsonl', import.meta.url), + 'utf8' + ) + .trim() + .split('\n') + if (!userLine || !replyLine) { + throw new Error('Expected captured user and reply records') + } + const user = decodeAntigravityTranscriptLine(userLine, 'user-fallback') + const reply = decodeAntigravityTranscriptLine(replyLine, 'reply-fallback') + if (!user || !reply) { + throw new Error('Expected captured message shapes to decode') + } + expect(user.id).toBe('9') + expect(reply.id).toBe('10') + expect(user.timestamp).toBe(reply.timestamp) + expect(projectNativeChatTranscriptMessages([reply, user]).map((message) => message.id)).toEqual([ + '9', + '10' + ]) +}) + +it.each([-1, 1.5, Number.MAX_SAFE_INTEGER + 1, 'opaque-id'])( + 'does not invent transcript order for invalid step %s', + (step_index) => { + expect( + decode({ source: 'USER_EXPLICIT', type: 'USER_INPUT', step_index, content: 'hello' }) + ?.transcriptPosition + ).toBeUndefined() + } +) diff --git a/src/main/native-chat/transcript-line-decoders.ts b/src/main/native-chat/transcript-line-decoders.ts index 2d84d1a55866..ccf05aaa672b 100644 --- a/src/main/native-chat/transcript-line-decoders.ts +++ b/src/main/native-chat/transcript-line-decoders.ts @@ -13,3 +13,5 @@ export { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' export { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' export { decodeGrokTranscriptLine } from './transcript-line-decoders-grok' export { decodeOmpTranscriptLine } from './transcript-line-decoders-omp' + +export { decodeAntigravityTranscriptLine } from './transcript-line-decoders-antigravity' diff --git a/src/main/native-chat/transcript-reader-antigravity.test.ts b/src/main/native-chat/transcript-reader-antigravity.test.ts new file mode 100644 index 000000000000..e1d3a0d61993 --- /dev/null +++ b/src/main/native-chat/transcript-reader-antigravity.test.ts @@ -0,0 +1,67 @@ +import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { resolveSessionFilePath } from './session-file-resolver' +import { readNativeChatTranscript } from './transcript-reader' +import { + nativeChatLineDecoderForAgent, + readNativeChatTranscriptTailFile +} from './transcript-tail-reader' +import { nativeChatTurnLifecycleDecoderForAgent } from './transcript-turn-lifecycle' + +let root: string | undefined + +afterEach(async () => { + if (root) { + await rm(root, { recursive: true, force: true }) + } + root = undefined +}) + +async function fixture() { + root = await mkdtemp(join(tmpdir(), 'orca-agy-chat-')) + const dir = join(root, 'conversation', '.system_generated', 'logs') + await mkdir(dir, { recursive: true }) + const path = join(dir, 'transcript.jsonl') + await copyFile(new URL('./__fixtures__/antigravity/tool-turn.jsonl', import.meta.url), path) + return { path, options: { antigravityBrainDir: root } } +} + +describe('Antigravity native transcript reading', () => { + it('resolves its CLI conversation and preserves full-reader / tail-reader parity', async () => { + const { path, options } = await fixture() + expect(await resolveSessionFilePath('antigravity', 'conversation', options)).toBe(path) + const full = await readNativeChatTranscript('antigravity', 'conversation', options) + const decode = nativeChatLineDecoderForAgent('antigravity') + expect(decode).not.toBeNull() + if (!decode || !('messages' in full)) { + throw new Error('transcript reader unavailable') + } + const tail = await readNativeChatTranscriptTailFile(path, 20, decode) + expect(tail.messages).toEqual(full.messages) + expect(full.messages.map((message) => message.role)).toEqual([ + 'user', + 'assistant', + 'tool', + 'assistant' + ]) + expect(nativeChatTurnLifecycleDecoderForAgent('antigravity')).toBeNull() + expect(full.lifecycle).toBeUndefined() + expect(tail.lifecycle).toBeUndefined() + }) + + it('rejects path-shaped ids and does not substitute a native file for a WSL session', async () => { + const { options } = await fixture() + for (const id of ['../conversation', '..\\conversation', '/conversation', 'C:conversation']) { + expect(await resolveSessionFilePath('antigravity', id, options)).toBeNull() + } + expect( + await resolveSessionFilePath('antigravity', 'conversation', { + ...options, + wslDistro: 'Ubuntu' + }) + ).toBeNull() + expect(await resolveSessionFilePath('antigravity', 'missing', options)).toBeNull() + }) +}) diff --git a/src/main/native-chat/transcript-reader.ts b/src/main/native-chat/transcript-reader.ts index 97ab76802d00..88c22306d215 100644 --- a/src/main/native-chat/transcript-reader.ts +++ b/src/main/native-chat/transcript-reader.ts @@ -10,6 +10,7 @@ import { resolveSessionFilePath, type ResolveSessionFileOptions } from './sessio import { openTranscriptReadStream } from './wsl-transcript-fs-access' import { wslTranscriptFsRefusal } from './wsl-transcript-fs-gate' import { + decodeAntigravityTranscriptLine, decodeClaudeTranscriptLine, decodeCodexTranscriptLine, decodeGrokTranscriptLine, @@ -59,6 +60,9 @@ export async function readNativeChatTranscript( } try { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) + if (transcriptAgent === 'antigravity') { + return { messages: await readTranscript(filePath, decodeAntigravityTranscriptLine) } + } if (transcriptAgent === 'claude') { return { messages: await readTranscript(filePath, decodeClaudeTranscriptLine) } } diff --git a/src/main/native-chat/transcript-tail-reader.ts b/src/main/native-chat/transcript-tail-reader.ts index 7afef93571f1..4e458f130c80 100644 --- a/src/main/native-chat/transcript-tail-reader.ts +++ b/src/main/native-chat/transcript-tail-reader.ts @@ -7,6 +7,7 @@ import type { import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat-agent-support' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' import { + decodeAntigravityTranscriptLine, decodeClaudeTranscriptLine, decodeCodexTranscriptLine, decodeGrokTranscriptLine, @@ -36,6 +37,9 @@ export type NativeChatLineDecoder = (line: string, fallbackId: string) => Native export function nativeChatLineDecoderForAgent(agent: AgentType): NativeChatLineDecoder | null { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) + if (transcriptAgent === 'antigravity') { + return decodeAntigravityTranscriptLine + } if (transcriptAgent === 'claude') { return decodeClaudeTranscriptLine } diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index ad9f51e7ad63..5f1317cd7359 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -227,6 +227,7 @@ async function startOrcadRuntime( // PTY agent on this host, and the store is the only place `worktree.ps` and the mobile // projection read from — unwired, orcad lists no PTY agents at all. onTerminalAgentStatus: (event) => agentHookServer.ingestTerminalStatus(event), + onTerminalScreenPermission: (event) => agentHookServer.ingestAntigravityScreenPermission(event), // Why here too and not only on the desktop: orcad serves `worktree.ps` and `agentSession.*`, // so without these a headless host publishes its structured chats nowhere and lists no agents. getAgentStatusSnapshot: () => diff --git a/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.meta.json b/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.meta.json new file mode 100644 index 000000000000..b1c6d570aa12 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-10-02T09:43:00Z", + "platform": "darwin", + "command": ["agy", "--model", "claude-sonnet-4-6"], + "cols": 159, + "rows": 69, + "captureKind": "authoritative-main-buffer-snapshot", + "note": "Installed authenticated agy 1.2.14; actual Claude turn paused at cat proof.txt approval in disposable folder. ANSI restored main PTY grid, not a synthetic fixture. Username/hostname/task profile suffix scrubbed; no hook row or UI approval proof claimed." +} diff --git a/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.txt b/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.txt new file mode 100644 index 000000000000..99a968ac355c --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-macos-1-2-14-command-approval.txt @@ -0,0 +1,34 @@ +[?2004hREDACTED_USER@REDACTED_HOST antigravity-chat-live-workspace $ env HOME=/var/folders/td/0d_w3jrs3654mtmk1gd6kpq00000gn/T/orca-agy-chat-isolated-REDACTED/home USERPROFILE=/var/folders/td/0d_w3jrs3654mtmk1gd6kpq00000gn/T/orca-agy-chat-isolated-REDACTED/home SSH_CONNECTION=task-private AGY_CLI_HIDE_ACCOUNT_INFO=1 /Users/REDACTED_USER/.local/bin/agy '--model' 'claude-sonnet-4-6' + +▄▀▀▄ Antigravity CLI 1.2.14 +▀▀▀▀▀▀ Claude Sonnet 4.6 (Thinking) +▀▀▀▀▀▀▀▀ /tmp/orca-integration-reports-20261002/antigravity-chat-live-workspace + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────── +> Use the run_command tool to run cat proof.txt first, then cat deny.txt separately. Ask for permission for each command and wait for my decision. Do not use + other tools or read any other files. If the second command is denied, respect that decision and finish by replying exactly ORCA_NATIVE_CHAT_DONE. + +▸ Thought for 1s + The user wants me to run two commands sequentially, asking for permission before each one. Let me start with the first command. + I'dliketo run thefollowingcommand. Doyou givepermission? + + Command:cat proof.txt + +● Bash(cat proof.txt) (ctrl+o to expand) + +Command +─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +Requesting permission for: + cat proof.txt + +Run this command? +> 1. Yes, run command + 2. Yes, and always allow in this conversation for commands that start with 'cat' + 3. Yes, and always allow for commands that start with 'cat' (Persist to settings.json) + 4. No, cancel + + ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command +esc to cancelClaude Sonnet 4.6 (Thinking)[?2004h[?25l[?6l7[?6l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.meta.json b/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.meta.json new file mode 100644 index 000000000000..e12cc9bf8ddc --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-20T10:03:18.668Z", + "platform": "win32", + "command": ["C:\\Users\\user\\AppData\\Local\\agy\\bin\\agy.exe"], + "cols": 120, + "rows": 40, + "note": "Native Windows agy 1.2.7; approved 20-second command still running; key 1 at 45 seconds; 120x40.", + "exitCode": 1 +} diff --git a/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.txt b/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.txt new file mode 100644 index 000000000000..bdd12fd1c07f --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-approved-command-running.txt @@ -0,0 +1,194 @@ +[?9001h[?1004h[?25l[>4m]0;C:\Users\user\AppData\Local\agy\bin\agy.exe[?25h[?1049h[?2004h[>4;2m[>1u[?u + ▄▀▀▄ + ▀▀▀▀▀▀ + ▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome to the Antigravity CLI. You are currently not signed in. + + No authentication methods available. + + Press ctrl+c or ctrl+d twice to exit. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25l[>4m[<1u[?1049l[>4;2m[>1u[?u[0 q + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25l + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25lUsG[?25he the terminal toolto run Start-Sleep-Seconds 20; Write-OutputORCA_BUSY_CAPTURE_OK.Donotmodifyfiles.[?25l[?25h[?25l? for shortcuts[?25h[?25l +> Use the terminal tool to run Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK. Do not modify files. +⣾ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⣷ [?25h[?25l⣯ Gene[?25h[?25l⣟ Genera[?25h[?25l⡿ Generat[?25h[?25l⢿ Generati[?25h[?25l⣻ Generatin[?25h[?25l⣽ Generating.[?25h[?25l⣾ Generating..[?25h[?25l⣷ Generating...[?25h[?25l⣯ Generatin[?25h[?25l⣟ Generating[?25h[?25l..[?25h[?25l⡿ Generating..[?25h[?25l⢿ Generating...[?25h[?25l⣻ [?25h[?25l⣽ [?25h[?25l⣾ [?25h[?25l⣷ [?25h[?25l⣯ [?25h[?25l⣟ G[?25h[?25l⡿ Gen[?25h[?25l⢿ Gene[?25h[?25l⣻ Gener[?25h[?25l⣽ Genera[?25h[?25l⣾ Generati[?25h[?25l⣷ Generatin[?25h[?25l⣯ Generating[?25h[?25l⣟ Generating.[?25h[?25l I'm now setting up the execution. I've formulated the exact command I need to use, which involves a sleep function... +└ Tip: You can switch conversations with /resume. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⡿[?25h[?25letting[?25h[?25lsettin[?25h[?25l⢿ I'm now setti[?25h[?25lw sett[?25h[?25low set[?25h[?25l⣻[?25h[?25lnow se[?25h[?25l now s[?25h[?25l⣽[?25h[?25lm now [?25h[?25l'm now[?25h[?25l⣾ I'm no[?25h[?25ln[?25h[?25l [?25h[?25l⣷[?25h[?25lm[?25h[?25l'[?25h[?25l I[?25h[?25l⣯[?25h[?25l +▸ Thought for 3s, 186 tokens + I'm now setting up the execution. I've formulated the exact command I need to use, which involves a sleep function...  + +○ Bash(Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK) (ctrl+o to expand) +⣯ Running command... +└ Tip: You can switch conversations with /resume. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[0 q[?25l●  + +Command +Requesting permission for: + Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK + +Run this command? +> 1. Yes, run command + 2. Yes, and always allow in this conversation for commands that start with 'Start-Sleep -Seconds 20; Write-Output +ORCA_BUSY_CAPTURE_OK' + 3. Yes, and always allow for commands that start with 'Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK' +(Persist to settings.json) + 4. No, cancel + + ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command +esc to cancel Gemini 3.1 Pro · low[0 q⣟ Running command... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + +[?25h[?25l⡿ [?25h[?25l⢿ Running[?25h[?25l⣻ Running c[?25h[?25l⣽ Running co[?25h[?25l⣾ Running com[?25h[?25lg comm[?25h[?25l⣷  ● [03:02:48] Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low · 1 task(s) · /tasks[?25h[?25l⣯ Running comman[?25h[?25l⣟ Running command[?25h[?25l⡿ Running command.[?25h[?25l⢿ Running command..[?25h[?25l⣻ Running command...[?25h[?25l⣽ Running command[?25h[?25l⣾ Running command.[?25h[?25l⣷ Running command..[?25h[?25l⣯ Running command...[?25h[?25l⣟ [?25h[?25l⡿ [?25h[?25l⢿ [?25h[?25l⣻ [?25h[?25l⣽ R[?25h[?25lun[?25h[?25l⣾ [?25h[?25l⣷ Run[?25h[?25l⣯ Runni[?25h[?25l⣟ Runnin[?25h[?25l⡿ Running[?25h[?25l⢿ Running [?25h[?25l⣻ Running co[?25h[?25l⣽ Running com[?25h[?25l⣾ Running comm[?25h[?25l⣷ Running comma[?25h[?25l⣯ Running command[?25h[?25l⣟ Running command.[?25h[?25l⡿ Running command..[?25h[?25l⢿ Running command...[?25h[?25l⣻ Running command[?25h[?25l⣽ Running command.[?25h[?25l⣾ Running command..[?25h[?25l⣷ Running command...[?25h[?25l⣯ [?25h[?25l⣟ [?25h[?25l⡿ [?25h[?25l + I've started the backgro +⡿ Running command...> ● [03:02:48] Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low · 1 task(s) · /tasks[?25h[?25lund task to +⢿ [?25h[?25lrun the comm[?25h[?25land Start-S[?25h[?25lleep -Second[?25h[?25ls [?25h[?25l Ru[?25h[?25l⣻ [?25h[?25l20; Write-Ou[?25h[?25ltput ORCA_BUSY_CAPTURE_OK. The + system will notify us when it completes. +⣻ Running command... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [03:02:48] Start-Sleep -Seconds 20; Write-Output ORCA_BUSY_CAPTURE_OK running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low · 1 task(s) · /tasks[?25h[?25l⣽ Ru[?25h[?25l? for shortcuts[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.meta.json b/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.meta.json new file mode 100644 index 000000000000..d4a019e16738 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-20T09:26:40.702Z", + "platform": "win32", + "command": ["C:\\Users\\user\\AppData\\Local\\agy\\bin\\agy.exe"], + "cols": 120, + "rows": 40, + "note": "Native Windows agy 1.2.7; test one-time approval key 1; 120x40.", + "exitCode": 1 +} diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.txt b/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.txt new file mode 100644 index 000000000000..48996981f235 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-allow-key.txt @@ -0,0 +1,209 @@ +[?9001h[?1004h[?25l[>4m]0;C:\Users\user\AppData\Local\agy\bin\agy.exe[?25h[?1049h[?2004h[>4;2m[>1u[?u + ▄▀▀▄ + ▀▀▀▀▀▀ + ▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome to the Antigravity CLI. You are currently not signed in. + + No authentication methods available. + + Press ctrl+c or ctrl+d twice to exit. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25l[>4m[<1u[?1049l[>4;2m[>1u[?u[0 q + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25l + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25lUsG[?25he the terminal tool to printORCA_PERMISSION_ALLOW_OK.Donot modify files.[?25l[?25h[?25l? for shortcuts[?25h[?25l +> Use the terminal tool to print ORCA_PERMISSION_ALLOW_OK. Do not modify files. +⣾ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⣷ [?25h[?25l⣯ Gene[?25h[?25l⣟ Genera[?25h[?25l⡿ Generat[?25h[?25l⢿ Generati[?25h[?25l⣻ Generating[?25h[?25l⣽ Generating.[?25h[?25l⣾ Generating..[?25h[?25l⣷ Generating...[?25h[?25l⣯ Generating[?25h[?25l⣟ Generating.[?25h[?25l⡿ Generating..[?25h[?25l⢿ Generating...[?25h[?25l⣻ [?25h[?25l⣽ [?25h[?25l⣾ [?25h[?25l⣷ [?25h[?25l⣯ [?25h[?25l⣟ Ge[?25h[?25l⡿ Gen[?25h[?25ler[?25h[?25l⢿ [?25h[?25l⣻ Gener[?25h[?25l⣽ Generat[?25h[?25l⣾ Generati[?25h[?25l⣷ Generatin[?25h[?25l⣯ Generating[?25h[?25l⣟ Generating..[?25h[?25l⡿ Generating...[?25h[?25l⢿ Generatin[?25h[?25l I'm focusing intently on tool selection, always opting for the most specialized option available. I'm actively avo... +└ Tip: Use /skills to browse and manage agent skills. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⣻ I'm focusing intently on tool selection, always opting for the most specialized option avail[?25h[?25ln avai[?25h[?25l⣽ I'm focusing intently on tool selection, always opting for the most specialized option ava[?25h[?25lion av[?25h[?25ltion a[?25h[?25l⣾ I'm focusing intently on tool selection, always opting for the most specialized option [?25h[?25loption[?25h[?25l optio[?25h[?25l⣷[?25h[?25ld opti[?25h[?25led opt[?25h[?25l⣯ I'm focusing intently on tool selection, always opting for the most specialized op[?25h[?25lized o[?25h[?25l⣟ I'm focusing intently on tool selection, always opting for the most specialized [?25h[?25lalized[?25h[?25lialize[?25h[?25lcializ[?25h[?25l⡿[?25h[?25leciali[?25h[?25lpecial[?25h[?25l⢿[?25h[?25lspecia[?25h[?25l speci[?25h[?25l⣻ I'm focusing intently on tool selection, always opting for the most spec[?25h[?25lst spe[?25h[?25l +▸ Thought for 3s, 246 tokens + I'm focusing intently on tool selection, always opting for the most specialized option available. I'm actively avo...  + +● Bash(Write-Host "ORCA_PERMISSION_ALLOW_OK") (ctrl+o to expand) +⣻ Running command... +└ Tip: Use /skills to browse and manage agent skills. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[0 q[?25l +Command +Requesting permission for: + Write-Host "ORCA_PERMISSION_ALLOW_OK" + +Run this command? +> 1. Yes, run command + 2. Yes, and always allow in this conversation for commands that start with 'Write-Host "ORCA_PERMISSION_ALLOW_OK"' + 3. Yes, and always allow for commands that start with 'Write-Host "ORCA_PERMISSION_ALLOW_OK"' (Persist to +settings.json) + 4. No, cancel + + ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command +esc to cancel Gemini 3.1 Pro · low[0 q○  +⣽ Running command... +└ Tip: Use /diff to view uncommitted changes in your workspace.> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + +[?25h[?25l⣾ [?25h[?25l⣷ Running command[?25h[?25l⣯ Running command.[?25h[?25l● ..[?25h[?25l● [?25h[?25l⣟ Running command...[?25h[?25l⡿ [?25h[?25l⢿ [?25h[?25l⣻ [?25h[?25l⣽ [?25h[?25l⣾ [?25h[?25l⣷ R[?25h[?25lun[?25h[?25l⣯ [?25h[?25l⣟ Run[?25h[?25l⡿ Runni[?25h[?25l⢿ Runnin[?25h[?25l⣻ Running[?25h[?25l⣽ Running c[?25h[?25l⣾ Running co[?25h[?25l⣷ Running com[?25h[?25l⣯ Running comm[?25h[?25l⣟ Running comman[?25h[?25lommand[?25h[?25l⡿ [?25h[?25l⢿ Running command.[?25h[?25l⣻ Running command..[?25h[?25l⣽ Running command...[?25h[?25l⣾ Running command[?25h[?25l⣷ Running command.[?25h[?25l⣯ Running command...[?25h[?25l⣟ [?25h[?25l⡿ [?25h[?25l⢿ [?25h[?25l + I have executed the comm +⢿ Running command... +└ Tip: Use /diff to view uncommitted changes in your workspace.> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25land in the t[?25h[?25lerminal,[?25h[?25l⣻ [?25h[?25land it successfully printed ORCA_PERMISSION_ALLOW_OK. Let me know if + you need anything else! +⣻ Running command... +└ Tip: Use /diff to view uncommitted changes in your workspace. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⣽ [?25h[?25l +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + +[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-approval.meta.json b/src/main/runtime/__fixtures__/antigravity-windows-command-approval.meta.json new file mode 100644 index 000000000000..9cf6c09e06e3 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-approval.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-20T09:20:25.623Z", + "platform": "win32", + "command": ["C:\\Users\\user\\AppData\\Local\\agy\\bin\\agy.exe"], + "cols": 120, + "rows": 40, + "note": "Native Windows agy 1.2.7; authenticated profile; harmless command approval; 120x40.", + "exitCode": 1 +} diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-approval.txt b/src/main/runtime/__fixtures__/antigravity-windows-command-approval.txt new file mode 100644 index 000000000000..7b701d36ccc8 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-approval.txt @@ -0,0 +1,148 @@ +[?9001h[?1004h[?25l[>4m]0;C:\Users\user\AppData\Local\agy\bin\agy.exe[?25h[?1049h[?2004h[>4;2m[>1u[?u + ▄▀▀▄ + ▀▀▀▀▀▀ + ▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome to the Antigravity CLI. You are currently not signed in. + + No authentication methods available. + + Press ctrl+c or ctrl+d twice to exit. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25l[>4m[<1u[?1049l[>4;2m[>1u[?u[0 q + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25l + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25lUseG[?25h theterminal tool to print ORCA_PERMISSION_CAPTURE_OK.Do not modify files.[?25l[?25h[?25l? for shortcuts[?25h[?25l +> Use the terminal tool to print ORCA_PERMISSION_CAPTURE_OK. Do not modify files. + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low[?25h[?25l⣾ Generating...esc to cancel [?25h[?25l⣷ [?25h[?25l⣯ [?25h[?25l⣟ [?25h[?25l⡿ [?25h[?25l⢿ [?25h[?25l⣻ Ge[?25h[?25l⣽ Gen[?25h[?25l⣾ Gene[?25h[?25l⣷ Gener[?25h[?25l⣯ Generat[?25h[?25l⣟ Generati[?25h[?25l⡿ Generatin[?25h[?25l⢿ Generating[?25h[?25l⣻ Generating.[?25h[?25l⣽ Generating...[?25h[?25l⣾ Generatin[?25h[?25l⣷ Generating[?25h[?25l⣯ Generating.[?25h[?25l⣟ Generating...[?25h[?25l⡿ [?25h[?25l⢿ [?25h[?25l⣻ [?25h[?25l⣽ [?25h[?25l⣾ [?25h[?25l⣷ G[?25h[?25l⣯ Ge[?25h[?25l⣟ Gene[?25h[?25l⡿ Gener[?25h[?25l⢿ Genera[?25h[?25l⣻ Generat[?25h[?25lneratin[?25h[?25l⣽ [?25h[?25l I've zeroed in on the `run_command` tool. My goal is to use it to print `ORCA_PERMISSION_CAPTURE_OK` without alter...[?25h[?25l⣾ I've zeroed in on the `run_command` tool. My goal is to use it to[?25h[?25le it t[?25h[?25lse it [?25h[?25l⣷[?25h[?25luse it[?25h[?25l use i[?25h[?25lo use [?25h[?25l⣯[?25h[?25lto use[?25h[?25l to us[?25h[?25l⣟[?25h[?25ls to u[?25h[?25lis to [?25h[?25l⡿ I've zeroed in on the `run_command` tool. My goal is to[?25h[?25ll is t[?25h[?25lal is [?25h[?25l⢿[?25h[?25loal is[?25h[?25lgoal i[?25h[?25l goal [?25h[?25l⣻[?25h[?25ly goal[?25h[?25lMy goa[?25h[?25l⣽ I've zeroed in on the `run_command` tool. My go[?25h[?25l. My g[?25h[?25l⣾ I've zeroed in on the `run_command` tool. My [?25h[?25lol. My[?25h[?25lool. M[?25h[?25l⣷[?25h[?25ltool. [?25h[?25l tool.[?25h[?25l⣯ I've zeroed in on the `run_command` tool[?25h[?25ld` too[?25h[?25lnd` to[?25h[?25l⣟[?25h[?25land` t[?25h[?25lmand` [?25h[?25l⡿[?25h[?25lmmand`[?25h[?25lommand[?25h[?25l⢿ I've zeroed in on the `run_comman[?25h[?25l_comma[?25h[?25ln_comm[?25h[?25l⣻[?25h[?25lun_com[?25h[?25lrun_co[?25h[?25l`run_c[?25h[?25l⣽[?25h[?25l `run_[?25h[?25le `run[?25h[?25lhe `ru[?25h[?25l +▸ Thought for 4s, 310 tokens + I've zeroed in on the `run_command` tool. My goal is to use it to print `ORCA_PERMISSION_CAPTURE_OK` without alter... + +○ Bash(echo "ORCA_PERMISSION_CAPTURE_OK") (ctrl+o to expand) +⣾ Running command... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[0 q[?25l●  + +Command +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +Requesting permission for: + echo "ORCA_PERMISSION_CAPTURE_OK" + +Run this command? +> 1. Yes, run command + 2. Yes, and always allow in this conversation for commands that start with 'echo "ORCA_PERMISSION_CAPTURE_OK"' + 3. Yes, and always allow for commands that start with 'echo "ORCA_PERMISSION_CAPTURE_OK"' (Persist to settings.json) + 4. No, cancel + + ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command +esc to cancel Gemini 3.1 Pro · low \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.meta.json b/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.meta.json new file mode 100644 index 000000000000..ce03cc4c86fb --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-20T09:23:21.869Z", + "platform": "win32", + "command": ["C:\\Users\\user\\AppData\\Local\\agy\\bin\\agy.exe"], + "cols": 120, + "rows": 40, + "note": "Native Windows agy 1.2.7; command approval dismissed with Escape; 120x40.", + "exitCode": 1 +} diff --git a/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.txt b/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.txt new file mode 100644 index 000000000000..55aa2d5a343f --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-windows-command-cancelled.txt @@ -0,0 +1,173 @@ +[?9001h[?1004h[?25l[>4m]0;C:\Users\user\AppData\Local\agy\bin\agy.exe[?25h[?1049h[?2004h[>4;2m[>1u[?u + ▄▀▀▄ + ▀▀▀▀▀▀ + ▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome to the Antigravity CLI. You are currently not signed in. + + No authentication methods available. + + Press ctrl+c or ctrl+d twice to exit. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25l[>4m[<1u[?1049l[>4;2m[>1u[?u[0 q + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25h[?25l + ▄▀▀▄ Antigravity CLI 1.2.7 + ▀▀▀▀▀▀ Gemini 3.1 Pro (Low) + ▀▀▀▀▀▀▀▀ C:/orca-agy-verify-0920 + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[?25hUs[?25leG[?25htheterminal tool toprint ORCA_PERMISSION_CANCEL_OK. Do not modify files.[?25l? for shortcuts[?25h[?25l +> Use the terminal tool to print ORCA_PERMISSION_CANCEL_OK. Do not modify files. +⣾ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25l⣷ [?25h[?25l⣯ Generating[?25h[?25l⣟ Generating..[?25h[?25l⡿ Generating...[?25h[?25l⢿ [?25h[?25l⣻ [?25h[?25l⣽ [?25h[?25l⣾ [?25h[?25l⣷ [?25h[?25l⣯ G[?25h[?25l⣟ Ge[?25h[?25lne[?25h[?25l⡿ Gene[?25h[?25l⢿ Gener[?25h[?25l⣻ Genera[?25h[?25l⣽ Generat[?25h[?25l⣾ Generatin[?25h[?25l⣷ Generating[?25h[?25l⣯ Generating.[?25h[?25l⣟ Generating..[?25h[?25l⡿ Generating...[?25h[?25l⢿ Generating[?25h[?25l⣻ Generating.[?25h[?25l⣽ Generating..[?25h[?25l⣾ Generating...[?25h[?25l⣷ [?25h[?25l⣯ [?25h[?25l⣟ [?25h[?25l⡿ [?25h[?25l⢿ G[?25h[?25l⣻ Ge[?25h[?25lne[?25h[?25l⣽ I'm focusing intently on tool specificity. I've been refining my approach to avoid unnecessary use of `cat` within... +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[?25lng int[?25h[?25l⣾ I'm focusing inte[?25h[?25l inten[?25h[?25lintent[?25h[?25l⣷[?25h[?25lntentl[?25h[?25ltently[?25h[?25lently [?25h[?25l⣯[?25h[?25lntly o[?25h[?25ltly on[?25h[?25l⣟ I'm focusing intently on [?25h[?25ly on t[?25h[?25l⡿ I'm focusing intently on to[?25h[?25lon too[?25h[?25ln tool[?25h[?25l⢿ I'm focusing intently on tool [?25h[?25ltool s[?25h[?25lool sp[?25h[?25l⣻[?25h[?25lol spe[?25h[?25ll spec[?25h[?25l⣽ I'm focusing intently on tool speci[?25h[?25lspecif[?25h[?25lpecifi[?25h[?25l⣾[?25h[?25lecific[?25h[?25lcifici[?25h[?25l⣷[?25h[?25lificit[?25h[?25lficity[?25h[?25licity.[?25h[?25l⣯[?25h[?25lcity. [?25h[?25lity. I[?25h[?25l⣟ I'm focusing intently on tool specificity. I'[?25h[?25ly. I'v[?25h[?25l⡿ I'm focusing intently on tool specificity. I've[?25h[?25l I've [?25h[?25lI've b[?25h[?25l⢿ I'm focusing intently on tool specificity. I've be[?25h[?25lve bee[?25h[?25l +▸ Thought for 4s, 365 tokens + I'm focusing intently on tool specificity. I've been refining my approach to avoid unnecessary use of `cat` within...  + +● Bash(echo ORCA_PERMISSION_CANCEL_OK) (ctrl+o to expand) +⢿ Running command... +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancel Gemini 3.1 Pro · low[?25h[0 q[?25l +Command +Requesting permission for: + echo ORCA_PERMISSION_CANCEL_OK + +Run this command? +> 1. Yes, run command + 2. Yes, and always allow in this conversation for commands that start with 'echo ORCA_PERMISSION_CANCEL_OK' + 3. Yes, and always allow for commands that start with 'echo ORCA_PERMISSION_CANCEL_OK' (Persist to settings.json) + 4. No, cancel + + ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command +esc to cancel Gemini 3.1 Pro · low[0 q●  ⎿ Interrupted · What should Antigravity CLI do instead?> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts Gemini 3.1 Pro · low + + + + + + + + + + + + + + + + + + + +[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@agent.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@agent.json new file mode 100644 index 000000000000..1e4bdd33c0b6 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@agent.json @@ -0,0 +1,7 @@ +{ + "description": "antigravity recording at 159x69 replayed on the agent pane, one entry per chunk", + "observations": { + "clocked": ["0-46: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending"], + "clockless": ["0-46: verdict=pending:closed wait=pending"] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@unknown.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@unknown.json new file mode 100644 index 000000000000..61267b60ccc4 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-macos-1-2-14-command-approval@unknown.json @@ -0,0 +1,7 @@ +{ + "description": "antigravity recording at 159x69 replayed on the unknown pane, one entry per chunk", + "observations": { + "clocked": ["0-46: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll"], + "clockless": ["0-46: verdict=pending:open wait=ready@poll"] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@agent.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@agent.json new file mode 100644 index 000000000000..a4c059b197f8 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@agent.json @@ -0,0 +1,19 @@ +{ + "description": "antigravity recording at 120x40 replayed on the agent pane, one entry per chunk", + "observations": { + "clocked": [ + "0-45: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "46-77: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "78-80: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "81: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "82-231: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending" + ], + "clockless": [ + "0-45: verdict=pending:closed wait=pending", + "46-77: verdict=ready-strong wait=ready@start", + "78-80: verdict=pending:closed wait=pending", + "81: verdict=ready-strong wait=ready@start", + "82-231: verdict=pending:closed wait=pending" + ] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@unknown.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@unknown.json new file mode 100644 index 000000000000..e212f2aa296a --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-approved-command-running@unknown.json @@ -0,0 +1,15 @@ +{ + "description": "antigravity recording at 120x40 replayed on the unknown pane, one entry per chunk", + "observations": { + "clocked": [ + "0-158: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll", + "159: now=ready-strong edge=ready-strong quiet=ready-strong wait=ready@start", + "160-231: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll" + ], + "clockless": [ + "0-158: verdict=pending:open wait=ready@poll", + "159: verdict=ready-strong wait=ready@start", + "160-231: verdict=pending:open wait=ready@poll" + ] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@agent.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@agent.json new file mode 100644 index 000000000000..62327b767c36 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@agent.json @@ -0,0 +1,21 @@ +{ + "description": "antigravity recording at 120x40 replayed on the agent pane, one entry per chunk", + "observations": { + "clocked": [ + "0-45: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "46-77: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "78-79: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "80: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "81-227: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "228-231: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start" + ], + "clockless": [ + "0-45: verdict=pending:closed wait=pending", + "46-77: verdict=ready-strong wait=ready@start", + "78-79: verdict=pending:closed wait=pending", + "80: verdict=ready-strong wait=ready@start", + "81-227: verdict=pending:closed wait=pending", + "228-231: verdict=ready-strong wait=ready@start" + ] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@unknown.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@unknown.json new file mode 100644 index 000000000000..f0907c0dcb37 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-allow-key@unknown.json @@ -0,0 +1,7 @@ +{ + "description": "antigravity recording at 120x40 replayed on the unknown pane, one entry per chunk", + "observations": { + "clocked": ["0-231: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll"], + "clockless": ["0-231: verdict=pending:open wait=ready@poll"] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@agent.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@agent.json new file mode 100644 index 000000000000..00987e89dd00 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@agent.json @@ -0,0 +1,23 @@ +{ + "description": "antigravity recording at 120x40 replayed on the agent pane, one entry per chunk", + "observations": { + "clocked": [ + "0-45: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "46-77: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "78-79: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "80: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "81-86: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "87-89: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "90-175: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending" + ], + "clockless": [ + "0-45: verdict=pending:closed wait=pending", + "46-77: verdict=ready-strong wait=ready@start", + "78-79: verdict=pending:closed wait=pending", + "80: verdict=ready-strong wait=ready@start", + "81-86: verdict=pending:closed wait=pending", + "87-89: verdict=ready-strong wait=ready@start", + "90-175: verdict=pending:closed wait=pending" + ] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@unknown.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@unknown.json new file mode 100644 index 000000000000..11fd24a82001 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-approval@unknown.json @@ -0,0 +1,7 @@ +{ + "description": "antigravity recording at 120x40 replayed on the unknown pane, one entry per chunk", + "observations": { + "clocked": ["0-175: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll"], + "clockless": ["0-175: verdict=pending:open wait=ready@poll"] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@agent.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@agent.json new file mode 100644 index 000000000000..837838077670 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@agent.json @@ -0,0 +1,21 @@ +{ + "description": "antigravity recording at 120x40 replayed on the agent pane, one entry per chunk", + "observations": { + "clocked": [ + "0-45: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "46-76: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "77-79: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "80: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start", + "81-182: now=pending:closed edge=pending:closed quiet=pending:closed wait=pending", + "183-184: now=pending:closed edge=pending:closed quiet=ready-strong wait=ready@start" + ], + "clockless": [ + "0-45: verdict=pending:closed wait=pending", + "46-76: verdict=ready-strong wait=ready@start", + "77-79: verdict=pending:closed wait=pending", + "80: verdict=ready-strong wait=ready@start", + "81-182: verdict=pending:closed wait=pending", + "183-184: verdict=ready-strong wait=ready@start" + ] + } +} diff --git a/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@unknown.json b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@unknown.json new file mode 100644 index 000000000000..969b7d0d4828 --- /dev/null +++ b/src/main/runtime/__fixtures__/readiness-census/transcript--antigravity-windows-command-cancelled@unknown.json @@ -0,0 +1,7 @@ +{ + "description": "antigravity recording at 120x40 replayed on the unknown pane, one entry per chunk", + "observations": { + "clocked": ["0-184: now=pending:open edge=pending:open quiet=pending:open wait=ready@poll"], + "clockless": ["0-184: verdict=pending:open wait=ready@poll"] + } +} diff --git a/src/main/runtime/agent-status-store-wiring.test-fixture.ts b/src/main/runtime/agent-status-store-wiring.test-fixture.ts index 1f399e0464f0..bd45c4bf3ef3 100644 --- a/src/main/runtime/agent-status-store-wiring.test-fixture.ts +++ b/src/main/runtime/agent-status-store-wiring.test-fixture.ts @@ -20,6 +20,9 @@ export function makeAgentStatusStoreWiring(): { statusStore: AgentHookServer deps: { onTerminalAgentStatus: (event: Parameters[0]) => void + onTerminalScreenPermission: ( + event: Parameters[0] + ) => boolean getAgentStatusSnapshot: () => ReturnType getAgentProviderSessionSnapshot: () => ReturnType getAgentProviderSessionRowsForPane: ( @@ -37,6 +40,7 @@ export function makeAgentStatusStoreWiring(): { statusStore, deps: { onTerminalAgentStatus: (event) => statusStore.ingestTerminalStatus(event), + onTerminalScreenPermission: (event) => statusStore.ingestAntigravityScreenPermission(event), getAgentStatusSnapshot: () => statusStore.getStatusSnapshot().filter((entry) => entry.providerSessionOnly !== true), getAgentProviderSessionSnapshot: () => statusStore.getStatusSnapshot(), diff --git a/src/main/runtime/antigravity-approval-screen-liveness.test.ts b/src/main/runtime/antigravity-approval-screen-liveness.test.ts new file mode 100644 index 000000000000..ef42c0873bdb --- /dev/null +++ b/src/main/runtime/antigravity-approval-screen-liveness.test.ts @@ -0,0 +1,141 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + app: { getPath: () => process.env.TMPDIR } +})) + +class ScreenProbe extends OrcaRuntimeService { + model() { + return this.getOrCreateHeadlessTerminal('pty') + } + readScreen() { + return this.readHeadlessVisibleTerminalState('pty') + } + replaceModel() { + this.headlessTerminals.set( + 'pty', + this.createPtyHeadlessTerminalState('pty', { cols: 120, rows: 40 }) + ) + } + replaceGeneration() { + this.advancePtyLifecycleGeneration('pty') + } + isCurrent(screen: RuntimeVisibleTerminalState): boolean { + const publisher: unknown = this.antigravityScreenPermissions + const deps: unknown = + publisher && typeof publisher === 'object' && 'deps' in publisher ? publisher.deps : null + if ( + !deps || + typeof deps !== 'object' || + !('isCurrent' in deps) || + typeof deps.isCurrent !== 'function' + ) { + throw new Error('Production screen validator missing') + } + return deps.isCurrent('pty', screen) + } + disposeModels() { + this.antigravityScreenPermissions.forget('pty') + for (const state of this.headlessTerminals.values()) { + state.emulator.dispose() + } + this.headlessTerminals.clear() + } +} +const probes: ScreenProbe[] = [] +afterEach(() => { + for (const runtime of probes.splice(0)) { + runtime.disposeModels() + } +}) + +async function probe() { + const runtime = new ScreenProbe(null) + probes.push(runtime) + runtime.registerPty('pty', 'folder-workspace', null) + runtime.onPtyData('pty', 'captured frame\r\n', Date.now()) + await runtime.readScreen() + return runtime +} + +it('does not claim a headless identity field absent from production reader results', () => { + const source = readFileSync(join(__dirname, 'orca-runtime-visible-snapshot-preview.ts'), 'utf8') + expect(source.includes('screen.headlessWriteChain')).toBe(false) +}) + +it('returns the actual generation and output sequence without an invented identity property', async () => { + const runtime = await probe() + const screen = await runtime.readScreen() + expect(screen).toMatchObject({ sequence: runtime.getPtyOutputSequence('pty') }) + expect(screen).not.toHaveProperty('headlessWriteChain') + expect(screen?.lines.join('\n')).toContain('captured frame') + if (!screen) { + throw new Error('Real screen missing') + } + expect(runtime.isCurrent(screen)).toBe(true) +}) + +it.each(['model', 'generation'] as const)( + 'rejects a replaced %s while its real write chain is pending', + async (replacement) => { + const runtime = await probe() + const previous = runtime.model() + const drain = Promise.withResolvers() + previous.writeChain = drain.promise + const reading = runtime.readScreen() + if (replacement === 'model') { + runtime.replaceModel() + } else { + runtime.replaceGeneration() + } + drain.resolve() + expect(await reading).toBeNull() + if (replacement === 'model') { + previous.emulator.dispose() + } + } +) + +it('rejects a real frame overtaken by output or a newer generation', async () => { + const runtime = await probe() + const screen = await runtime.readScreen() + if (!screen) { + throw new Error('Real screen missing') + } + runtime.onPtyData('pty', 'new output\r\n', Date.now()) + expect(runtime.isCurrent(screen)).toBe(false) + const next = await runtime.readScreen() + if (!next) { + throw new Error('New screen missing') + } + expect(runtime.isCurrent(next)).toBe(true) + runtime.replaceGeneration() + expect(runtime.isCurrent(next)).toBe(false) +}) + +it('rejects a real frame after the PTY disconnects', async () => { + const runtime = await probe() + const screen = await runtime.readScreen() + if (!screen) { + throw new Error('Real screen missing') + } + runtime.onPtyExit('pty', 0) + expect(runtime.isCurrent(screen)).toBe(false) +}) + +it('rejects a real frame while its execution host is unverifiable', async () => { + const runtime = await probe() + const screen = await runtime.readScreen() + if (!screen) { + throw new Error('Real screen missing') + } + runtime.markPtyLivenessUnverifiable('pty', 'SSH provider contact lost') + expect(runtime.isCurrent(screen)).toBe(false) +}) diff --git a/src/main/runtime/antigravity-command-approval-screen.ts b/src/main/runtime/antigravity-command-approval-screen.ts new file mode 100644 index 000000000000..f300b10f7229 --- /dev/null +++ b/src/main/runtime/antigravity-command-approval-screen.ts @@ -0,0 +1,41 @@ +/** Matches the captured agy command dialog only while it owns the bottom of the screen. */ +export function isAntigravityCommandApprovalScreen(rows: readonly string[]): boolean { + const lines = rows.map((row) => row.trim()).filter(Boolean) + const footer = lines.at(-1) ?? '' + const navigation = lines.at(-2) ?? '' + if ( + !footer.startsWith('esc to cancel') || + navigation !== '↑/↓ Navigate · tab Amend · ctrl+g edit/expand command' + ) { + return false + } + const question = lines.lastIndexOf('Run this command?') + if (question === -1) { + return false + } + const choices = lines.slice(question + 1, -2).map((line) => line.replace(/^>\s*/, '')) + return ( + choices[0] === '1. Yes, run command' && + choices.some((line) => line.startsWith('2. Yes, and always allow in this conversation')) && + choices.some((line) => line.startsWith('3. Yes, and always allow for commands')) && + choices.at(-1) === '4. No, cancel' + ) +} + +/** Captured foreground generation and Windows background-task layouts. */ +export function isAntigravityWorkingTerminalScreen(tail: readonly string[]): boolean { + const rows = tail.map((row) => row.trim()).filter(Boolean) + const footer = rows.at(-1) ?? '' + const composerAt = (offset: number): boolean => + /^─{8,}$/.test(rows.at(offset) ?? '') && + /^(?:>|>\s+[a-z][a-z-]*\s+mode:\s.*)$/i.test(rows.at(offset - 1) ?? '') && + /^─{8,}$/.test(rows.at(offset - 2) ?? '') + return ( + (footer.startsWith('esc to cancel') && composerAt(-2)) || + (footer.startsWith('? for shortcuts') && + /· [1-9]\d* task\(s\) · \/tasks$/.test(footer) && + /^─{8,}$/.test(rows.at(-2) ?? '') && + /^● \[\d{2}:\d{2}:\d{2}\] .+ running$/.test(rows.at(-3) ?? '') && + composerAt(-4)) + ) +} diff --git a/src/main/runtime/antigravity-command-approval-transcript.test.ts b/src/main/runtime/antigravity-command-approval-transcript.test.ts new file mode 100644 index 000000000000..e2d51cf4f1b7 --- /dev/null +++ b/src/main/runtime/antigravity-command-approval-transcript.test.ts @@ -0,0 +1,97 @@ +import { makeAgentStatusStoreWiring } from './agent-status-store-wiring.test-fixture' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { createTranscriptPane, TRANSCRIPT_PANE_PTY_ID } from './agent-transcript-pane-test-harness' +import { finalReplayFrame } from './agent-transcript-replay-test-harness' +import { evaluateAgentStateRules } from './agent-state-rules/agent-state-rules-engine' +import { isAntigravityCommandApprovalScreen } from './antigravity-command-approval-screen' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + app: { getPath: vi.fn(() => '/tmp') } +})) + +describe('captured native Windows Antigravity command approval', () => { + it.each(['approval', 'cancelled', 'allow-key'] as const)( + 'reads the recorded %s screen through the current rules', + async (name) => { + const { ruledScreenLines } = await finalReplayFrame( + `antigravity-windows-command-${name}`, + 120, + 40 + ) + expect(isAntigravityCommandApprovalScreen(ruledScreenLines)).toBe(name === 'approval') + expect( + evaluateAgentStateRules('antigravity', { readScreenLines: () => ruledScreenLines }) + ).toMatchObject( + name === 'approval' ? { state: 'hold' } : { state: 'idle', requiresQuiet: true } + ) + } + ) +}) + +it.each([ + ['antigravity-windows-command-cancelled', 'done'], + ['antigravity-busy-mid-turn', 'working'], + ['antigravity-windows-approved-command-running', 'working'] +] as const)('publishes permission then the captured %s state', async (capture, state) => { + const wiring = makeAgentStatusStoreWiring() + const { runtime, handle } = await createTranscriptPane( + { + paneTitle: 'agy', + foregroundProcess: 'agy', + size: { cols: 120, rows: 40 }, + data: '' + }, + wiring.deps + ) + const paneKey = runtime.getTerminalPaneKey(handle) + if (!paneKey) { + throw new Error('Missing test pane key') + } + wiring.statusStore.ingestTerminalStatus({ + paneKey, + payload: { + state: 'working', + agentType: 'antigravity', + prompt: 'print marker', + toolName: 'run_command' + } + }) + const approval = readFileSync( + join(__dirname, '__fixtures__/antigravity-windows-command-approval.txt'), + 'utf8' + ) + runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, approval, Date.now()) + await vi.waitFor(() => + expect(wiring.statusStore.getStatusSnapshot()[0]).toMatchObject({ + state: 'waiting', + observation: { origin: 'process' } + }) + ) + expect(wiring.statusStore.getStatusSnapshot()[0].interactivePrompt).toContain( + 'ORCA_PERMISSION_CAPTURE_OK' + ) + const cancelled = readFileSync(join(__dirname, `__fixtures__/${capture}.txt`), 'utf8') + runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, cancelled, Date.now()) + await vi.waitFor( + () => expect(wiring.statusStore.getStatusSnapshot()[0]).toMatchObject({ state }), + { timeout: 5000 } + ) + expect(wiring.statusStore.getStatusSnapshot()[0].interactivePrompt).toBeUndefined() +}) + +it('recognizes the actual macOS 1.2.14 Claude command permission grid', async () => { + const { ruledScreenLines } = await finalReplayFrame( + 'antigravity-macos-1-2-14-command-approval', + 159, + 69 + ) + expect(isAntigravityCommandApprovalScreen(ruledScreenLines)).toBe(true) + expect( + evaluateAgentStateRules('antigravity', { readScreenLines: () => ruledScreenLines }) + ).toMatchObject({ state: 'hold' }) +}) diff --git a/src/main/runtime/antigravity-ruled-screen-publication.test.ts b/src/main/runtime/antigravity-ruled-screen-publication.test.ts new file mode 100644 index 000000000000..1d183e4da794 --- /dev/null +++ b/src/main/runtime/antigravity-ruled-screen-publication.test.ts @@ -0,0 +1,150 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { createTranscriptPane, TRANSCRIPT_PANE_PTY_ID } from './agent-transcript-pane-test-harness' +import { finalReplayFrame, readRuntimeFixture } from './agent-transcript-replay-test-harness' +import { makeAgentStatusStoreWiring } from './agent-status-store-wiring.test-fixture' +import type { OrcaRuntimeService } from './orca-runtime' +import { TUI_IDLE_QUIESCENCE_MS } from './orca-runtime-postlude' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + app: { getPath: () => process.env.TMPDIR } +})) + +const runtimes: OrcaRuntimeService[] = [] +afterEach(() => { + for (const runtime of runtimes.splice(0)) { + runtime.onPtyExit(TRANSCRIPT_PANE_PTY_ID, 0) + } + vi.useRealTimers() +}) + +function productionScreenReader(runtime: OrcaRuntimeService) { + const source: unknown = runtime + if (!source || typeof source !== 'object' || !('antigravityScreenPermissions' in source)) { + throw new Error('Production Antigravity screen publisher missing') + } + const publisher = source.antigravityScreenPermissions + const deps: unknown = + publisher && typeof publisher === 'object' && 'deps' in publisher ? publisher.deps : null + if ( + !deps || + typeof deps !== 'object' || + !('readScreen' in deps) || + typeof deps.readScreen !== 'function' + ) { + throw new Error('Production Antigravity screen reader missing') + } + const readScreen = deps.readScreen + return () => readScreen(TRANSCRIPT_PANE_PTY_ID) +} + +async function pane(capture: string, cols = 120, rows = 40) { + const size = { cols, rows } + const result = await createTranscriptPane({ + paneTitle: 'agy', + foregroundProcess: 'agy', + data: readRuntimeFixture(capture), + size + }) + runtimes.push(result.runtime) + return { ...result, size, read: productionScreenReader(result.runtime) } +} + +it.each([ + ['antigravity-windows-command-approval', 120, 40], + ['antigravity-macos-1-2-14-command-approval', 159, 69], + ['antigravity-1-2-14-ready', 120, 40] +] as const)( + 'reads captured %s through the real runtime publication closure', + async (capture, cols, rows) => { + const { runtime, read } = await pane(capture, cols, rows) + const expected = await finalReplayFrame(capture, cols, rows) + await expect(read()).resolves.toMatchObject({ + lines: expected.ruledScreenLines, + sequence: runtime.getPtyOutputSequence(TRANSCRIPT_PANE_PTY_ID) + }) + } +) + +it('refuses a captured approval painted for a different PTY grid', async () => { + const { read, size } = await pane('antigravity-windows-command-approval') + await read() + size.cols = 100 + size.rows = 30 + await expect(read()).resolves.toBeNull() +}) + +it('refuses the captured grid after reflow without a TUI repaint', async () => { + const { runtime, read, size } = await pane('antigravity-windows-command-approval') + await read() + size.cols = 100 + size.rows = 30 + runtime.reflowHeadlessTerminalToPtyGrid(TRANSCRIPT_PANE_PTY_ID, size.cols, size.rows) + await expect(read()).resolves.toBeNull() +}) + +it('returns null when the PTY has no screen model', async () => { + const { runtime } = await createTranscriptPane({ + paneTitle: 'agy', + foregroundProcess: 'agy', + data: '' + }) + runtimes.push(runtime) + await expect(productionScreenReader(runtime)()).resolves.toBeNull() +}) + +it('publishes captured permission and quiet ready state into the canonical host store', async () => { + const wiring = makeAgentStatusStoreWiring() + const { runtime, handle } = await createTranscriptPane( + { + paneTitle: 'agy', + foregroundProcess: 'agy', + data: '', + size: { cols: 120, rows: 40 } + }, + wiring.deps + ) + runtimes.push(runtime) + const paneKey = runtime.getTerminalPaneKey(handle) + if (!paneKey) { + throw new Error('Runtime pane binding missing') + } + wiring.statusStore.ingestTerminalStatus({ + paneKey, + payload: { + state: 'working', + agentType: 'antigravity', + prompt: 'print marker', + toolName: 'run_command' + } + }) + runtime.onPtyData( + TRANSCRIPT_PANE_PTY_ID, + readRuntimeFixture('antigravity-windows-command-approval'), + Date.now() + ) + await expect(productionScreenReader(runtime)()).resolves.not.toBeNull() + await vi.waitFor(() => + expect(wiring.statusStore.getStatusSnapshot()[0]).toMatchObject({ + state: 'waiting', + observation: { origin: 'process' } + }) + ) + expect(wiring.statusStore.getStatusSnapshot()[0].interactivePrompt).toContain( + 'ORCA_PERMISSION_CAPTURE_OK' + ) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + runtime.onPtyData( + TRANSCRIPT_PANE_PTY_ID, + readRuntimeFixture('antigravity-1-2-14-ready'), + Date.now() + ) + await productionScreenReader(runtime)() + await vi.advanceTimersByTimeAsync(TUI_IDLE_QUIESCENCE_MS - 1) + expect(wiring.statusStore.getStatusSnapshot()[0].state).toBe('waiting') + await vi.advanceTimersByTimeAsync(1) + expect(wiring.statusStore.getStatusSnapshot()[0]).toMatchObject({ state: 'done' }) + expect(wiring.statusStore.getStatusSnapshot()[0].interactivePrompt).toBeUndefined() +}) diff --git a/src/main/runtime/antigravity-screen-permission-lifecycle.test.ts b/src/main/runtime/antigravity-screen-permission-lifecycle.test.ts new file mode 100644 index 000000000000..281ced07f6aa --- /dev/null +++ b/src/main/runtime/antigravity-screen-permission-lifecycle.test.ts @@ -0,0 +1,133 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { Terminal } from '@xterm/headless' +import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' +import { AntigravityScreenPermissionPublisher } from './antigravity-screen-permission-publisher' + +let ready: RuntimeVisibleTerminalState +const baseline: AgentStatusIpcPayload = { + paneKey: 'tab:leaf', + agentType: 'antigravity', + state: 'waiting', + prompt: '', + connectionId: null, + receivedAt: 1, + stateStartedAt: 1 +} +beforeAll(async () => { + const terminal = new Terminal({ cols: 120, rows: 40, allowProposedApi: true }) + try { + await new Promise((resolve) => + terminal.write( + readFileSync(join(__dirname, '__fixtures__/antigravity-1-2-14-ready.txt'), 'utf8'), + resolve + ) + ) + const buffer = terminal.buffer.active + ready = { + lines: Array.from( + { length: 40 }, + (_, row) => buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? '' + ).filter((line) => line.trim()), + generation: 1, + sequence: 1, + isAlternateScreen: true + } + } finally { + terminal.dispose() + } +}) +beforeEach(() => vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })) +afterEach(() => vi.useRealTimers()) + +async function flushReads(): Promise { + for (let index = 0; index < 10; index += 1) { + await Promise.resolve() + } +} + +function deferredPublisher() { + const first = Promise.withResolvers() + const second = Promise.withResolvers() + const readScreen = vi + .fn() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockResolvedValue(ready) + const publish = vi.fn(() => true) + let remaining = 3000 + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => baseline, + readScreen, + isCurrent: () => true, + quietRemainingMs: () => remaining, + publish + }) + return { + first, + second, + readScreen, + publish, + publisher, + setRemaining: (value: number) => { + remaining = value + } + } +} + +it('keeps one quiet timer when output dirties a pending screen read', async () => { + const fixture = deferredPublisher() + fixture.publisher.schedule('pty') + fixture.publisher.schedule('pty') + fixture.first.resolve(ready) + await flushReads() + expect(fixture.readScreen).toHaveBeenCalledTimes(2) + expect(vi.getTimerCount()).toBe(1) + fixture.setRemaining(5000) + fixture.second.resolve(ready) + await flushReads() + expect(vi.getTimerCount()).toBe(1) + fixture.publisher.forget('pty') + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(6000) + expect(fixture.readScreen).toHaveBeenCalledTimes(2) + expect(fixture.publish).not.toHaveBeenCalled() +}) + +it('a forgotten pending read cannot publish or arm a timer', async () => { + const fixture = deferredPublisher() + fixture.publisher.schedule('pty') + fixture.publisher.forget('pty') + fixture.first.resolve(ready) + await flushReads() + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(6000) + expect(fixture.readScreen).toHaveBeenCalledTimes(1) + expect(fixture.publish).not.toHaveBeenCalled() +}) + +it('old read cleanup cannot consume a replacement PTY pending read or timer', async () => { + const fixture = deferredPublisher() + fixture.publisher.schedule('pty') + fixture.publisher.forget('pty') + fixture.publisher.schedule('pty') + expect(fixture.readScreen).toHaveBeenCalledTimes(2) + fixture.second.resolve(ready) + await flushReads() + expect(vi.getTimerCount()).toBe(1) + fixture.first.resolve(ready) + await flushReads() + expect(vi.getTimerCount()).toBe(1) + fixture.setRemaining(0) + await vi.advanceTimersByTimeAsync(3000) + expect(fixture.readScreen).toHaveBeenCalledTimes(3) + expect(fixture.publish).toHaveBeenCalledExactlyOnceWith({ + baseline, + command: null, + clearedState: 'done' + }) + fixture.publisher.forget('pty') + expect(vi.getTimerCount()).toBe(0) +}) diff --git a/src/main/runtime/antigravity-screen-permission-publisher.test.ts b/src/main/runtime/antigravity-screen-permission-publisher.test.ts new file mode 100644 index 000000000000..806dbd52303a --- /dev/null +++ b/src/main/runtime/antigravity-screen-permission-publisher.test.ts @@ -0,0 +1,219 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { Terminal } from '@xterm/headless' +import { beforeAll, describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' +import { + AntigravityScreenPermissionPublisher, + antigravityHookRowMatchesPty +} from './antigravity-screen-permission-publisher' + +const baseline: AgentStatusIpcPayload = { + paneKey: 'pane', + terminalHandle: 'term-1', + connectionId: null, + agentType: 'antigravity', + state: 'working', + prompt: 'print marker', + receivedAt: 1, + stateStartedAt: 1 +} +let approval: RuntimeVisibleTerminalState + +beforeAll(async () => { + const terminal = new Terminal({ cols: 120, rows: 40, allowProposedApi: true }) + try { + const raw = readFileSync( + join(__dirname, '__fixtures__/antigravity-windows-command-approval.txt'), + 'utf8' + ) + await new Promise((resolve) => terminal.write(raw, resolve)) + const buffer = terminal.buffer.active + approval = { + lines: Array.from( + { length: 40 }, + (_, row) => buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? '' + ), + generation: 1, + sequence: 1, + isAlternateScreen: true + } + } finally { + terminal.dispose() + } +}) + +describe('Antigravity screen publication scheduling', () => { + it('coalesces output during a read and retries the newest frame', async () => { + const frame = Promise.withResolvers() + const readScreen = vi.fn().mockReturnValueOnce(frame.promise).mockResolvedValue(approval) + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => baseline, + readScreen, + isCurrent: () => true, + publish + }) + publisher.schedule('pty') + for (let index = 0; index < 100; index += 1) { + publisher.schedule('pty') + } + expect(readScreen).toHaveBeenCalledTimes(1) + frame.resolve(null) + await vi.waitFor(() => expect(publish).toHaveBeenCalledTimes(1)) + expect(readScreen).toHaveBeenCalledTimes(2) + expect(publish).toHaveBeenCalledWith({ baseline, command: 'echo "ORCA_PERMISSION_CAPTURE_OK"' }) + }) + + it('does not publish a frame rejected by generation, sequence or liveness validation', async () => { + const isCurrent = vi.fn(() => false) + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => baseline, + readScreen: async () => approval, + isCurrent, + publish + }) + publisher.schedule('pty') + await vi.waitFor(() => expect(isCurrent).toHaveBeenCalled()) + expect(publish).not.toHaveBeenCalled() + }) + + it.each([ + null, + { + lines: ['tool output without a recognized composer'], + generation: 1, + sequence: 1, + isAlternateScreen: false + } + ])('does not clear permission from a missing or unrecognized screen: %s', async (screen) => { + const readScreen = vi.fn(async () => screen) + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => ({ ...baseline, state: 'waiting' }), + readScreen, + isCurrent: () => true, + publish + }) + publisher.schedule('pty') + await vi.waitFor(() => expect(readScreen).toHaveBeenCalled()) + expect(publish).not.toHaveBeenCalled() + }) + + it('does not interpret another provider or a direct SSH mirror', async () => { + const readScreen = vi.fn(async () => approval) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: (id) => + id === 'ssh' + ? { ...baseline, connectionId: 'remote' } + : { ...baseline, agentType: 'claude' }, + readScreen, + isCurrent: () => true, + publish: () => true + }) + publisher.schedule('ssh') + publisher.schedule('claude') + await Promise.resolve() + expect(readScreen).not.toHaveBeenCalled() + }) + + it('reads a WSL relay row, whose pty this host owns', async () => { + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => ({ ...baseline, connectionId: 'wsl:Ubuntu-26.04' }), + readScreen: async () => approval, + isCurrent: () => true, + publish + }) + publisher.schedule('wsl') + await vi.waitFor(() => expect(publish).toHaveBeenCalledTimes(1)) + expect(publish).toHaveBeenCalledWith( + expect.objectContaining({ command: expect.stringContaining('echo') }) + ) + }) + + it('does not lose output queued between a synchronous empty read and its cleanup', async () => { + const readBaseline = vi.fn().mockReturnValueOnce(null).mockReturnValue(baseline) + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: readBaseline, + readScreen: async () => approval, + isCurrent: () => true, + publish + }) + publisher.schedule('pty') + publisher.schedule('pty') + await vi.waitFor(() => expect(publish).toHaveBeenCalledTimes(1)) + }) +}) + +describe('antigravityHookRowMatchesPty', () => { + const wslPty = { isWsl: true, wslDistro: 'Ubuntu-26.04' } + const nativePty = { isWsl: false, wslDistro: null } + + it.each([ + ['a native hook row', null, nativePty, true], + ['a WSL relay row on its own distro', 'wsl:Ubuntu-26.04', wslPty, true], + [ + 'a WSL relay row when the pty distro is the default', + 'wsl:Ubuntu-26.04', + { isWsl: true, wslDistro: null }, + false + ], + ['a WSL relay row on another distro', 'wsl:Debian', wslPty, false], + ['a WSL relay row on a native pty', 'wsl:Ubuntu-26.04', nativePty, false], + ['an SSH mirror row', 'ssh-connection', wslPty, false] + ] as const)('%s → %s', (_label, connectionId, pty, expected) => { + expect(antigravityHookRowMatchesPty(connectionId, pty)).toBe(expected) + }) +}) + +it('holds a cleared approval to quiescence and rechecks ownership after the timer', async () => { + const terminal = new Terminal({ cols: 120, rows: 40, allowProposedApi: true }) + await new Promise((resolve) => + terminal.write( + readFileSync(join(__dirname, '__fixtures__/antigravity-1-2-14-ready.txt'), 'utf8'), + resolve + ) + ) + const buffer = terminal.buffer.active + const ready = { + ...approval, + lines: Array.from( + { length: 40 }, + (_, row) => buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? '' + ).filter((line) => line.trim()) + } + terminal.dispose() + let remaining = 3000 + let current = true + const publish = vi.fn(() => true) + const publisher = new AntigravityScreenPermissionPublisher({ + baseline: () => ({ ...baseline, state: 'waiting' }), + readScreen: async () => ready, + isCurrent: () => current, + quietRemainingMs: () => remaining, + publish + }) + vi.useFakeTimers() + try { + publisher.schedule('pty') + await vi.advanceTimersByTimeAsync(2999) + expect(publish).not.toHaveBeenCalled() + remaining = 0 + current = false + await vi.advanceTimersByTimeAsync(1) + expect(publish).not.toHaveBeenCalled() + current = true + publisher.schedule('pty') + await vi.advanceTimersByTimeAsync(0) + expect(publish).toHaveBeenCalledWith( + expect.objectContaining({ command: null, clearedState: 'done' }) + ) + publisher.forget('pty') + } finally { + vi.useRealTimers() + } +}) diff --git a/src/main/runtime/antigravity-screen-permission-publisher.ts b/src/main/runtime/antigravity-screen-permission-publisher.ts new file mode 100644 index 000000000000..7f3c4fbaa47c --- /dev/null +++ b/src/main/runtime/antigravity-screen-permission-publisher.ts @@ -0,0 +1,131 @@ +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import { + isWslHookRelayConnectionId, + wslHookRelayConnectionId +} from '../../shared/wsl-hook-relay-contract' +import type { AntigravityScreenPermissionObservation } from '../agent-hooks/server/server-ingest-antigravity-screen' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' +import { + isAntigravityCommandApprovalScreen, + isAntigravityWorkingTerminalScreen +} from './antigravity-command-approval-screen' +import { evaluateAgentStateRules } from './agent-state-rules/agent-state-rules-engine' + +type Dependencies = { + baseline(ptyId: string): AgentStatusIpcPayload | null + readScreen(ptyId: string): Promise + isCurrent(ptyId: string, screen: RuntimeVisibleTerminalState): boolean + quietRemainingMs?(ptyId: string): number + publish(observation: AntigravityScreenPermissionObservation): boolean +} + +/** A WSL relay row is local screen evidence, but only for a WSL pty in that same distro. */ +export function antigravityHookRowMatchesPty( + rowConnectionId: string | null | undefined, + pty: { isWsl: boolean | null; wslDistro: string | null } +): boolean { + if (!rowConnectionId) { + return true + } + return ( + isWslHookRelayConnectionId(rowConnectionId) && + pty.isWsl === true && + Boolean(pty.wslDistro) && + rowConnectionId === wslHookRelayConnectionId(pty.wslDistro ?? '') + ) +} + +export class AntigravityScreenPermissionPublisher { + private readonly pending = new Map() + + private readonly quietTimers = new Map>() + + constructor(private readonly deps: Dependencies) {} + + forget(ptyId: string): void { + this.cancelQuietTimer(ptyId) + this.pending.delete(ptyId) + } + + private cancelQuietTimer(ptyId: string): void { + clearTimeout(this.quietTimers.get(ptyId)) + this.quietTimers.delete(ptyId) + } + + schedule(ptyId: string): void { + this.cancelQuietTimer(ptyId) + const existing = this.pending.get(ptyId) + if (existing) { + existing.dirty = true + return + } + const pending = { dirty: true } + this.pending.set(ptyId, pending) + void this.drain(ptyId, pending).finally(() => { + if (this.pending.get(ptyId) !== pending) { + return + } + this.pending.delete(ptyId) + if (pending.dirty) { + this.schedule(ptyId) + } + }) + } + + private async drain(ptyId: string, pending: { dirty: boolean }): Promise { + while (pending.dirty && this.pending.get(ptyId) === pending) { + pending.dirty = false + const baseline = this.deps.baseline(ptyId) + if ( + !baseline || + baseline.agentType !== 'antigravity' || + (baseline.connectionId && !isWslHookRelayConnectionId(baseline.connectionId)) + ) { + continue + } + try { + const screen = await this.deps.readScreen(ptyId) + if (this.pending.get(ptyId) !== pending || !screen || !this.deps.isCurrent(ptyId, screen)) { + continue + } + if (isAntigravityCommandApprovalScreen(screen.lines)) { + const lines = screen.lines.map((line) => line.trim()) + const start = lines.lastIndexOf('Requesting permission for:') + const end = lines.lastIndexOf('Run this command?') + if (start !== -1 && end > start) { + const command = lines + .slice(start + 1, end) + .filter(Boolean) + .join('\n') + if (command) { + this.deps.publish({ baseline, command }) + } + } + } else if (isAntigravityWorkingTerminalScreen(screen.lines)) { + this.deps.publish({ baseline, command: null, clearedState: 'working' }) + } else if ( + !screen.draft?.trim() && + evaluateAgentStateRules('antigravity', { readScreenLines: () => screen.lines })?.state === + 'idle' + ) { + const remaining = this.deps.quietRemainingMs?.(ptyId) ?? 0 + if (remaining > 0 && baseline.state === 'waiting') { + this.cancelQuietTimer(ptyId) + const timer = setTimeout(() => { + if (this.quietTimers.get(ptyId) !== timer) { + return + } + this.quietTimers.delete(ptyId) + this.schedule(ptyId) + }, remaining) + this.quietTimers.set(ptyId, timer) + } else if (remaining === 0) { + this.deps.publish({ baseline, command: null, clearedState: 'done' }) + } + } + } catch { + // An unreadable screen is not evidence that a permission prompt disappeared. + } + } + } +} diff --git a/src/main/runtime/orca-runtime-on-pty-data.ts b/src/main/runtime/orca-runtime-on-pty-data.ts index c3dfd7b2cac3..1b7db6bb5a13 100644 --- a/src/main/runtime/orca-runtime-on-pty-data.ts +++ b/src/main/runtime/orca-runtime-on-pty-data.ts @@ -72,6 +72,9 @@ export class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePtyExecution forwardQueryReplies ) captureModelReceipt?.(modelCompletion) + if (this.onTerminalScreenPermission) { + this.antigravityScreenPermissions.schedule(ptyId) + } const pty = this.getOrCreatePtyWorktreeRecord(ptyId) const ptyTailBefore = pty diff --git a/src/main/runtime/orca-runtime-on-pty-exit.ts b/src/main/runtime/orca-runtime-on-pty-exit.ts index abcf2fcf57f4..f3eb0f5c819a 100644 --- a/src/main/runtime/orca-runtime-on-pty-exit.ts +++ b/src/main/runtime/orca-runtime-on-pty-exit.ts @@ -198,6 +198,7 @@ export class OrcaRuntimeWithOnPtyExit extends OrcaRuntimeWithOnClientDisconnecte // stale `mobile{X}` to any caller that hasn't yet seen the exit IPC. this.terminalDrivers.clear(ptyId) this.remoteDesktopFloor.clearPty(ptyId) + this.antigravityScreenPermissions.forget(ptyId) this.disposeHeadlessTerminal(ptyId) if (processDeathCertified) { // The bounded verdict register also fences late graphs after the PTY record was pruned. diff --git a/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts b/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts index 37f8121f99ae..c98463aaa0f5 100644 --- a/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts +++ b/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts @@ -1,4 +1,5 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import type { AntigravityScreenPermissionObservation } from '../agent-hooks/server/server-ingest-antigravity-screen' import { OrcaRuntimeWithTerminalDrivers } from './orca-runtime-terminal-drivers' import { RuntimePreservedBranchCleanup } from './runtime-preserved-branch-cleanup' import type { IPtyProvider } from '../providers/types' @@ -55,6 +56,10 @@ export class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeWithTermin protected readonly onPtyStopped: ((ptyId: string) => void) | null + protected readonly onTerminalScreenPermission: + | ((event: AntigravityScreenPermissionObservation) => boolean) + | null + protected readonly onTerminalAgentStatus: | ((event: RuntimeTerminalAgentStatusEvent) => void) | null diff --git a/src/main/runtime/orca-runtime-state-fields.ts b/src/main/runtime/orca-runtime-state-fields.ts index ede9c6edce59..b216a40385bc 100644 --- a/src/main/runtime/orca-runtime-state-fields.ts +++ b/src/main/runtime/orca-runtime-state-fields.ts @@ -1,4 +1,5 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import type { AntigravityScreenPermissionObservation } from '../agent-hooks/server/server-ingest-antigravity-screen' import { OrcaRuntimeWithLinearCommands } from './orca-runtime-linear-commands' import type { RuntimeStore } from './runtime-store-contract' import type { StatsCollector } from '../stats/collector' @@ -37,6 +38,7 @@ import { RuntimeAutomationController } from './runtime-automation-controller' import { RuntimeOrchestrationFederation } from './runtime-orchestration-federation' import { configureAiVaultSessionSources } from '../ai-vault/cached-session-list' import { configureHostReadableTranscriptPathSources } from '../native-chat/host-readable-transcript-path' +import { configureNativeChatExecutionNamespace } from '../native-chat/native-chat-execution-namespace' import { createEphemeralAgentSessionClaimSigner } from './agent-session-claim-identity' import { registerConptyDa1OverrideInstaller } from './terminal-model-query-authority' import { registerTerminalViewAttributesApplier } from './terminal-view-attribute-store' @@ -57,6 +59,7 @@ export class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCommands { getSshProvider?: (connectionId: string) => IPtyProvider | undefined prepareClaudeAuth?: PrepareClaudeAuth onPtyStopped?: (ptyId: string) => void + onTerminalScreenPermission?: (event: AntigravityScreenPermissionObservation) => boolean onTerminalAgentStatus?: (event: RuntimeTerminalAgentStatusEvent) => void onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void // Why: agent status mostly arrives via hooks (agent-hooks/server), not OSC @@ -223,6 +226,7 @@ export class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCommands { deps?.readObservedAgentStatusPaneIdentity ?? (() => ({ kind: 'unobserved' })) this.getAgentProviderSessionSnapshotFn = deps?.getAgentProviderSessionSnapshot ?? deps?.getAgentStatusSnapshot ?? null + configureNativeChatExecutionNamespace(() => this.getAgentProviderSessionSnapshotFn?.() ?? []) this.getAgentProviderSessionRowsForPaneFn = deps?.getAgentProviderSessionRowsForPane ?? null this.attestAgentHookCompatibilityAuthorityFn = deps?.attestAgentHookCompatibilityAuthority ?? null @@ -252,6 +256,7 @@ export class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCommands { this.getLocalProviderFn = deps?.getLocalProvider ?? null this.getSshProviderFn = deps?.getSshProvider ?? null this.onPtyStopped = deps?.onPtyStopped ?? null + this.onTerminalScreenPermission = deps?.onTerminalScreenPermission ?? null this.onTerminalAgentStatus = deps?.onTerminalAgentStatus ?? null this.buildAgentHookPtyEnv = deps?.buildAgentHookPtyEnv ?? null this.getDesktopWindowStatusFn = deps?.getDesktopWindowStatus ?? (() => 'openable') diff --git a/src/main/runtime/orca-runtime-visible-snapshot-preview.ts b/src/main/runtime/orca-runtime-visible-snapshot-preview.ts index fd53d34f9a33..3697a533db99 100644 --- a/src/main/runtime/orca-runtime-visible-snapshot-preview.ts +++ b/src/main/runtime/orca-runtime-visible-snapshot-preview.ts @@ -1,4 +1,8 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import { + AntigravityScreenPermissionPublisher, + antigravityHookRowMatchesPty +} from './antigravity-screen-permission-publisher' import { OrcaRuntimeWithCaptureProviderTerminalBuffer } from './orca-runtime-capture-provider-terminal-buffer' import type { RuntimeTerminalProjection } from './orca-runtime-core' import { buildPreview } from './terminal-tail-state' @@ -7,6 +11,7 @@ import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' import { + TUI_IDLE_QUIESCENCE_MS, VISIBLE_TERMINAL_SNAPSHOT_RETRY_MS, VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from './orca-runtime-postlude' @@ -17,6 +22,41 @@ import { HeadlessEmulator } from '../daemon/headless-emulator' import { withTimeout } from './runtime-async-boundaries' export class OrcaRuntimeWithVisibleSnapshotPreview extends OrcaRuntimeWithCaptureProviderTerminalBuffer { + protected readonly antigravityScreenPermissions = new AntigravityScreenPermissionPublisher({ + baseline: (ptyId) => { + const pty = this.ptysById.get(ptyId) + if (!pty?.connected || pty.connectionId || !pty.paneKey) { + return null + } + const terminalHandle = this.getAgentStatusTerminalHandleForPaneKey(pty.paneKey) + const row = this.getAgentProviderSessionRowsForPaneFn?.(pty.paneKey)?.find( + (candidate) => + candidate.providerSessionOnly !== true && candidate.agentType === 'antigravity' + ) + // Native hooks identify the pane; the runtime owns its live terminal binding. + return row && terminalHandle && antigravityHookRowMatchesPty(row.connectionId, pty) + ? { ...row, terminalHandle } + : null + }, + readScreen: async (ptyId) => { + const screen = await this.readVisibleTerminalState(ptyId) + const ruledScreen = this.readRuledScreen(ptyId) + return screen && ruledScreen ? { ...screen, lines: ruledScreen.lines } : null + }, + quietRemainingMs: (ptyId) => { + const lastOutputAt = this.ptysById.get(ptyId)?.lastOutputAt + return lastOutputAt == null + ? 0 + : Math.max(0, TUI_IDLE_QUIESCENCE_MS - (Date.now() - lastOutputAt)) + }, + isCurrent: (ptyId, screen) => + this.ptysById.get(ptyId)?.connected === true && + this.getPtyLivenessVerdict(ptyId)?.status !== 'unverifiable' && + screen.generation === this.getPtyLifecycleGeneration(ptyId) && + screen.sequence >= this.getPtyOutputSequence(ptyId), + publish: (event) => this.onTerminalScreenPermission?.(event) ?? false + }) + protected async visibleSnapshotPreview(ptyId: string, preview: string): Promise { const knownAlternateScreen = this.isTerminalAlternateScreen(ptyId) const providerModeUnknown = diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 9da3d7212ef2..45b1bb5b72dd 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -87,6 +87,7 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { getSshProvider: (connectionId) => getSshPtyProvider(connectionId), onPtyStopped: clearProviderPtyState, onTerminalAgentStatus: (event) => agentHookServer.ingestTerminalStatus(event), + onTerminalScreenPermission: (event) => agentHookServer.ingestAntigravityScreenPermission(event), // Why: serve can be promoted in place, so wire the listener from startup; runtime enables desktop-only scanners only for a ready renderer. onTerminalSideEffects: (batch: TerminalSideEffectBatch) => { if (state.mainWindow && !state.mainWindow.isDestroyed()) { diff --git a/src/renderer/src/components/native-chat/native-chat-antigravity-capability.test.ts b/src/renderer/src/components/native-chat/native-chat-antigravity-capability.test.ts new file mode 100644 index 000000000000..37421ddecc18 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-antigravity-capability.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it, vi } from 'vitest' +import { guardAntigravityChatTransport } from './native-chat-antigravity-capability' +import { + RUNTIME_NATIVE_CHAT_READ_ERROR, + RUNTIME_NATIVE_CHAT_TOO_OLD +} from './native-chat-runtime-contract' + +const args = { + agent: 'antigravity' as const, + sessionId: 'conversation', + subscriptionId: 'subscription' +} + +function setup(supports: () => Promise) { + const stop = vi.fn() + const transport = { + readSession: vi.fn(async () => ({ messages: [] })), + subscribe: vi.fn(() => stop) + } + return { transport, stop, guarded: guardAntigravityChatTransport(transport, supports) } +} + +describe('Antigravity chat host capability', () => { + it('rejects old hosts before read or subscribe without claiming the transcript is pending', async () => { + const { guarded, transport } = setup(async () => false) + expect(await guarded.readSession('antigravity', 'conversation')).toEqual({ + error: RUNTIME_NATIVE_CHAT_TOO_OLD + }) + const onFrame = vi.fn() + const close = await guarded.subscribe(args, onFrame) + await vi.waitFor(() => + expect(onFrame).toHaveBeenCalledWith({ + type: 'snapshot', + messages: [], + hasMore: false, + error: RUNTIME_NATIVE_CHAT_TOO_OLD + }) + ) + expect(transport.readSession).not.toHaveBeenCalled() + expect(transport.subscribe).not.toHaveBeenCalled() + close() + }) + + it('keeps host-contact failure separate from unsupported versions', async () => { + const { guarded } = setup(async () => { + throw new Error('offline') + }) + expect(await guarded.readSession('antigravity', 'conversation')).toEqual({ + error: RUNTIME_NATIVE_CHAT_READ_ERROR + }) + }) + + it('does not open a subscription after teardown while the probe was pending', async () => { + let resolve: ((supported: boolean) => void) | undefined + const { guarded, transport } = setup( + () => + new Promise((done) => { + resolve = done + }) + ) + const close = await guarded.subscribe(args, vi.fn()) + close() + resolve?.(true) + await Promise.resolve() + await Promise.resolve() + expect(transport.subscribe).not.toHaveBeenCalled() + }) + + it('uses supported hosts and closes their subscription once', async () => { + const { guarded, transport, stop } = setup(async () => true) + await guarded.readSession('antigravity', 'conversation') + expect(transport.readSession).toHaveBeenCalledWith('antigravity', 'conversation') + const close = await guarded.subscribe(args, vi.fn()) + await vi.waitFor(() => expect(transport.subscribe).toHaveBeenCalledOnce()) + close() + expect(stop).toHaveBeenCalledOnce() + }) + + it('leaves existing agents on their existing transport', async () => { + const supports = vi.fn(async () => false) + const { guarded, transport } = setup(supports) + await guarded.readSession('claude', 'conversation') + await guarded.subscribe({ ...args, agent: 'claude' }, vi.fn()) + expect(transport.readSession).toHaveBeenCalledOnce() + expect(transport.subscribe).toHaveBeenCalledOnce() + expect(supports).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-antigravity-capability.ts b/src/renderer/src/components/native-chat/native-chat-antigravity-capability.ts new file mode 100644 index 000000000000..21b60da3f5fa --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-antigravity-capability.ts @@ -0,0 +1,70 @@ +import type { NativeChatApi } from '../../../../preload/api-types' +import { + RUNTIME_NATIVE_CHAT_READ_ERROR, + RUNTIME_NATIVE_CHAT_TOO_OLD +} from './native-chat-runtime-contract' + +type Transport = Pick + +/** An older host cannot decode agy; distinguish that from a transcript awaiting its first write. */ +export function guardAntigravityChatTransport( + transport: Transport, + supports: () => Promise +): Transport { + const errorForHost = async (): Promise => { + try { + return (await supports()) ? null : RUNTIME_NATIVE_CHAT_TOO_OLD + } catch { + return RUNTIME_NATIVE_CHAT_READ_ERROR + } + } + return { + readSession: async (agent, ...args) => { + const error = agent === 'antigravity' ? await errorForHost() : null + return error ? { error } : transport.readSession(agent, ...args) + }, + subscribe: (args, onFrame) => { + if (args.agent !== 'antigravity') { + return transport.subscribe(args, onFrame) + } + let cancelled = false + let unsubscribe: (() => void) | undefined + void errorForHost() + .then(async (error) => { + if (cancelled) { + return + } + if (error) { + onFrame({ type: 'snapshot', messages: [], hasMore: false, error }) + return + } + const stop = await Promise.resolve( + transport.subscribe(args, (frame) => { + if (!cancelled) { + onFrame(frame) + } + }) + ) + if (cancelled) { + stop() + } else { + unsubscribe = stop + } + }) + .catch(() => { + if (!cancelled) { + onFrame({ + type: 'snapshot', + messages: [], + hasMore: false, + error: RUNTIME_NATIVE_CHAT_READ_ERROR + }) + } + }) + return () => { + cancelled = true + unsubscribe?.() + } + } + } +} diff --git a/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.test.ts b/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.test.ts new file mode 100644 index 000000000000..86b3c1b11da7 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.test.ts @@ -0,0 +1,159 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { createNativeChatAntigravityInterrupt } from './native-chat-antigravity-interrupt' + +const paneKey = 'tab:11111111-1111-4111-8111-111111111111' + +function working(): AgentStatusEntry { + return { + paneKey, + state: 'working', + agentType: 'antigravity', + prompt: 'bounded task', + updatedAt: Date.now(), + stateStartedAt: Date.now(), + stateHistory: [], + observation: { + origin: 'hook', + authorityId: 'host', + incarnation: 1, + revision: 2, + observedAt: Date.now() + } + } +} + +function harness() { + let current = working() + const delivery = Promise.withResolvers() + const inferInterrupt = vi.fn(async () => true) + const interrupt = createNativeChatAntigravityInterrupt({ + paneKey, + getStatusEntry: () => current, + writeAccepted: () => delivery.promise, + inferInterrupt + }) + return { + interrupt, + delivery, + inferInterrupt, + replace: (row: AgentStatusEntry) => (current = row) + } +} + +beforeEach(() => vi.useFakeTimers()) +afterEach(() => vi.useRealTimers()) + +describe('acknowledged Antigravity Chat interruption', () => { + it('reuses the captured canonical turn only after accepted delivery and the existing settle delay', async () => { + const { interrupt, delivery, inferInterrupt } = harness() + const cancelling = interrupt.cancel() + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + delivery.resolve(true) + await cancelling + await vi.advanceTimersByTimeAsync(499) + expect(inferInterrupt).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(inferInterrupt).toHaveBeenCalledExactlyOnceWith({ + paneKey, + baselineAgentType: 'antigravity', + baselinePrompt: 'bounded task', + baselineUpdatedAt: expect.any(Number), + baselineStateStartedAt: expect.any(Number), + intent: 'plain-escape' + }) + interrupt.dispose() + }) + + it('never treats refused delivery as success', async () => { + const { interrupt, delivery, inferInterrupt } = harness() + const cancelling = interrupt.cancel() + delivery.resolve(false) + await cancelling + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + }) + + it('propagates unavailable delivery without inferring a stopped agent', async () => { + const { interrupt, delivery, inferInterrupt } = harness() + const cancelling = interrupt.cancel() + delivery.reject(new Error('transport unavailable')) + await expect(cancelling).rejects.toThrow('transport unavailable') + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + }) + + it.each(['before acknowledgement', 'after acknowledgement'])( + 'rejects target rebinding/unmount %s', + async (when) => { + const { interrupt, delivery, inferInterrupt } = harness() + const cancelling = interrupt.cancel() + if (when === 'before acknowledgement') { + interrupt.dispose() + } + delivery.resolve(true) + await cancelling + interrupt.dispose() + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + } + ) + + it.each(['authorityId', 'incarnation', 'revision'] as const)( + 'rejects a changed canonical %s even when turn timestamps match', + async (field) => { + const { interrupt, delivery, inferInterrupt, replace } = harness() + const row = working() + replace(row) + const cancelling = interrupt.cancel() + delivery.resolve(true) + await cancelling + if (!row.observation) { + throw new Error('Missing observation') + } + row.observation = { + ...row.observation, + [field]: field === 'authorityId' ? 'other-host' : 3 + } + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + } + ) + + it.each(['waiting', 'done'] as const)('does not cancel a %s baseline', async (state) => { + const { interrupt, delivery, inferInterrupt, replace } = harness() + replace({ ...working(), state }) + const cancelling = interrupt.cancel() + delivery.resolve(true) + await cancelling + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + }) + + it('refuses old rows without canonical observation identity', async () => { + const { interrupt, delivery, inferInterrupt, replace } = harness() + replace({ ...working(), observation: undefined }) + const cancelling = interrupt.cancel() + delivery.resolve(true) + await cancelling + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + }) + + it('does not mint a replacement turn baseline when delivery acknowledges late', async () => { + const { interrupt, delivery, inferInterrupt, replace } = harness() + const cancelling = interrupt.cancel() + replace({ ...working(), prompt: 'replacement turn' }) + delivery.resolve(true) + await cancelling + await vi.advanceTimersByTimeAsync(1000) + expect(inferInterrupt).not.toHaveBeenCalled() + interrupt.dispose() + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.ts b/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.ts new file mode 100644 index 000000000000..5a8f4ccec609 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-antigravity-interrupt.ts @@ -0,0 +1,63 @@ +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { AgentInterruptInferenceRequest } from '../../../../shared/agent-interrupt-intent' +import { createAgentInterruptInference } from '../terminal-pane/agent-interrupt-inference' + +type Dependencies = { + paneKey: string + getStatusEntry: () => AgentStatusEntry | undefined + writeAccepted: () => Promise + inferInterrupt: (request: AgentInterruptInferenceRequest) => Promise +} + +/** Chat writes bypass xterm's acknowledged-input observer; reuse its guarded inference. */ +export function createNativeChatAntigravityInterrupt(deps: Dependencies): { + cancel(): Promise + dispose(): void +} { + let disposed = false + let sequence = 0 + let pending: ReturnType | null = null + return { + async cancel() { + const baseline = deps.getStatusEntry() + const captured = baseline?.observation ? { ...baseline.observation } : undefined + const capturedSequence = ++sequence + pending?.dispose() + pending = null + if (!(await deps.writeAccepted()) || disposed || capturedSequence !== sequence) { + return + } + if (baseline?.agentType !== 'antigravity' || !captured) { + return + } + const inference = createAgentInterruptInference({ + paneKey: deps.paneKey, + getStatusEntry: deps.getStatusEntry, + inferInterrupt: (request) => { + const current = deps.getStatusEntry() + const observed = current?.observation + if ( + disposed || + capturedSequence !== sequence || + !captured || + !observed || + captured.authorityId !== observed.authorityId || + captured.incarnation !== observed.incarnation || + captured.revision !== observed.revision + ) { + return false + } + return deps.inferInterrupt(request) + } + }) + pending = inference + inference.observeInputIntent('plain-escape', baseline) + }, + dispose() { + disposed = true + sequence += 1 + pending?.dispose() + pending = null + } + } +} diff --git a/src/renderer/src/components/native-chat/native-chat-availability.test.ts b/src/renderer/src/components/native-chat/native-chat-availability.test.ts index 737d7d4a0774..e80a696e6d7f 100644 --- a/src/renderer/src/components/native-chat/native-chat-availability.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-availability.test.ts @@ -90,20 +90,22 @@ describe('canToggleNativeChat', () => { ).toBe(false) }) - // Why: omp discloses no hook transcript path either, so its session file is - // only reachable when this process can read the agent's disk. - it('rejects Model-A SSH omp but accepts it local and runtime-owned', () => { - const forConnection = (connectionId: string | null): boolean => - canToggleNativeChat({ - experimentalNativeChatEnabled: true, - contentType: 'terminal', - launchAgent: 'omp', - nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(connectionId) - }) - expect(forConnection('ssh-target-1')).toBe(false) - expect(forConnection(null)).toBe(true) - expect(forConnection('runtime-ssh-env-1')).toBe(true) - }) + // Direct SSH has no transcript transport, even when a hook names the remote file. + it.each(['omp', 'antigravity'] as const)( + 'rejects Model-A SSH %s but accepts it local and runtime-owned', + (agent) => { + const forConnection = (connectionId: string | null): boolean => + canToggleNativeChat({ + experimentalNativeChatEnabled: true, + contentType: 'terminal', + launchAgent: agent, + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(connectionId) + }) + expect(forConnection('ssh-target-1')).toBe(false) + expect(forConnection(null)).toBe(true) + expect(forConnection('runtime-ssh-env-1')).toBe(true) + } + ) it('lets an existing Model-A SSH Grok chat toggle back to terminal', () => { expect( diff --git a/src/renderer/src/components/native-chat/native-chat-launch-session-options.ts b/src/renderer/src/components/native-chat/native-chat-launch-session-options.ts index 2271d4bd1d8b..76041b295b10 100644 --- a/src/renderer/src/components/native-chat/native-chat-launch-session-options.ts +++ b/src/renderer/src/components/native-chat/native-chat-launch-session-options.ts @@ -17,6 +17,7 @@ export type InitialNativeChatSessionOptionsArgs = { promptDelivery?: NativeChatLaunchPromptDelivery launchDraftText?: string nativeChatTranscriptIsLocalReadable?: boolean + providerSessionId?: string | null } export function resolveInitialNativeChatSessionOptions( diff --git a/src/renderer/src/components/native-chat/native-chat-live-status.test.ts b/src/renderer/src/components/native-chat/native-chat-live-status.test.ts index 9dcd683dcd90..787e3f7da302 100644 --- a/src/renderer/src/components/native-chat/native-chat-live-status.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-live-status.test.ts @@ -22,6 +22,34 @@ function user(id: string, text: string): NativeChatMessage { } describe('mergeNativeChatLiveSession', () => { + it('keeps Antigravity working after an intermediate planner response', () => { + const planner: NativeChatMessage = { + ...assistant('planner', '> *Thinking:*\nI will run the command.'), + blocks: [ + { type: 'text', text: '> *Thinking:*\nI will run the command.' }, + { type: 'tool-call', name: 'run_command', input: { command: 'cat proof.txt' } } + ] + } + expect( + mergeNativeChatLiveSession({ + messages: [user('request', 'read the proof'), planner], + sessionId: 'conversation', + agent: 'antigravity', + hookState: 'working', + stateStartedAt: 1 + }).status + ).toBe('working') + expect( + mergeNativeChatLiveSession({ + messages: [user('request', 'read the proof'), planner], + sessionId: 'conversation', + agent: 'antigravity', + hookState: 'done', + stateStartedAt: 3 + }).status + ).toBe('ready') + }) + it("surfaces live 'working' before the assistant turn lands in the transcript", () => { const session = mergeNativeChatLiveSession({ messages: [user('u-1', 'do a thing')], diff --git a/src/renderer/src/components/native-chat/native-chat-live-status.ts b/src/renderer/src/components/native-chat/native-chat-live-status.ts index f3d2bb58be94..d777a8a179cc 100644 --- a/src/renderer/src/components/native-chat/native-chat-live-status.ts +++ b/src/renderer/src/components/native-chat/native-chat-live-status.ts @@ -110,7 +110,7 @@ export const LIFECYCLE_CLOCK_SKEW_SLACK_MS = 2_000 * is never a dropped Stop, so a trailing assistant row (a tool call mid-run) cannot end it. */ function hookDeliversTurnEnd(agent: AgentType): boolean { - return agent === 'omp' + return agent === 'omp' || agent === 'antigravity' } function liveStatusOverride( diff --git a/src/renderer/src/components/native-chat/native-chat-pending.ts b/src/renderer/src/components/native-chat/native-chat-pending.ts index 680ca687e77b..bb7a24b00601 100644 --- a/src/renderer/src/components/native-chat/native-chat-pending.ts +++ b/src/renderer/src/components/native-chat/native-chat-pending.ts @@ -130,9 +130,19 @@ function messageIsAfterPendingTimestamp( const boundary = nativeChatPendingMatchingAfter(pending) // A transcript-clock boundary describes an existing message, so exclude ties. // Local send time has no existing record and remains inclusive. - return pending.afterMessageTimestamp == null - ? message.timestamp >= boundary - : message.timestamp > boundary + if (pending.afterMessageTimestamp != null) { + return message.timestamp > boundary + } + return messageIsAtOrAfterSendTimestamp(message, boundary) +} + +function messageIsAtOrAfterSendTimestamp(message: NativeChatMessage, sentAt: number): boolean { + // Only a producer-declared coarse clock may precede the local send within its second. + return ( + message.timestamp === null || + message.timestamp >= + (message.timestampPrecision === 'second' ? Math.floor(sentAt / 1000) * 1000 : sentAt) + ) } /** @@ -288,9 +298,7 @@ export function launchPromptAsMessage( // Why: a launch prompt seeds a brand-new session, so a matching user turn // with no timestamp (e.g. Grok transcripts) can only be its own delivery. const represented = matchingNativeChatUserContentCounts( - existingMessages.filter( - (message) => message.timestamp === null || message.timestamp >= entry.createdAt - ) + existingMessages.filter((message) => messageIsAtOrAfterSendTimestamp(message, entry.createdAt)) ) if ((represented.get(nativeChatPendingContentKey(entry)) ?? 0) > 0) { return null @@ -311,8 +319,8 @@ export function shouldPruneLaunchPrompt( entry: NativeChatLaunchPrompt, messages: NativeChatMessage[] ): boolean { - const relevant = messages.filter( - (message) => message.timestamp === null || message.timestamp >= entry.createdAt + const relevant = messages.filter((message) => + messageIsAtOrAfterSendTimestamp(message, entry.createdAt) ) return ( (advancedNativeChatUserContentCounts(relevant).get(nativeChatPendingContentKey(entry)) ?? 0) > 0 diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-contract.ts b/src/renderer/src/components/native-chat/native-chat-runtime-contract.ts index 329c93f852ff..d67c269f9ea4 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-contract.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-contract.ts @@ -4,6 +4,9 @@ import type { } from '../../../../preload/api-types' import type { NativeChatTurnLifecycle } from '../../../../shared/native-chat-types' +export const RUNTIME_NATIVE_CHAT_TOO_OLD = + 'This remote runtime is too old to show agent chat history. Update the remote runtime to view it.' + export const RUNTIME_NATIVE_CHAT_READ_ERROR = "Couldn't read agent chat from the remote runtime." export function parseRuntimeNativeChatTurnLifecycle( diff --git a/src/renderer/src/components/native-chat/native-chat-session-transport.ts b/src/renderer/src/components/native-chat/native-chat-session-transport.ts index 112e7cdc3e0a..222b6dab0717 100644 --- a/src/renderer/src/components/native-chat/native-chat-session-transport.ts +++ b/src/renderer/src/components/native-chat/native-chat-session-transport.ts @@ -1,7 +1,11 @@ +import { ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { ensureLocalRuntimeCapabilities } from '@/runtime/local-runtime-capabilities' +import { guardAntigravityChatTransport } from './native-chat-antigravity-capability' import type { NativeChatApi, NativeChatAppendedMessages } from '../../../../preload/api-types' import { isWebClientLocation } from '@/lib/web-client-location' import { callRuntimeRpc, + runtimeEnvironmentSupportsCapability, RuntimeRpcCallError, type RuntimeClientTarget } from '@/runtime/runtime-rpc-client' @@ -9,7 +13,8 @@ import { isRuntimeCompatBlockError } from '@/runtime/runtime-protocol-compat' import { parseRuntimeNativeChatReadSessionResult, parseRuntimeNativeChatTurnLifecycle, - RUNTIME_NATIVE_CHAT_READ_ERROR + RUNTIME_NATIVE_CHAT_READ_ERROR, + RUNTIME_NATIVE_CHAT_TOO_OLD } from './native-chat-runtime-contract' /** The read/subscribe surface the live-session hook needs, decoupled from where @@ -17,9 +22,6 @@ import { * hook and everything downstream (merge, assembler, pagination) are unchanged. */ export type NativeChatSessionTransport = Pick -const RUNTIME_TOO_OLD = - 'This remote runtime is too old to show agent chat history. Update the remote runtime to view it.' - /** Backoff before re-opening a dropped runtime chat stream. Exported for tests. */ export const RUNTIME_NATIVE_CHAT_RECONNECT_MS = 2_000 @@ -30,10 +32,10 @@ export const RUNTIME_NATIVE_CHAT_RECONNECT_MS = 2_000 * never mislabeled as a version problem (KTD-4, not catch-all). */ export function toRuntimeNativeChatErrorMessage(err: unknown): string { if (err instanceof RuntimeRpcCallError && err.code === 'method_not_found') { - return RUNTIME_TOO_OLD + return RUNTIME_NATIVE_CHAT_TOO_OLD } if (isRuntimeCompatBlockError(err)) { - return RUNTIME_TOO_OLD + return RUNTIME_NATIVE_CHAT_TOO_OLD } return RUNTIME_NATIVE_CHAT_READ_ERROR } @@ -268,8 +270,22 @@ function createRuntimeNativeChatTransport(environmentId: string): NativeChatSess export function getNativeChatSessionTransport( runtimeEnvironmentId: string | null ): NativeChatSessionTransport { - if (runtimeEnvironmentId && !isWebClientLocation()) { - return createRuntimeNativeChatTransport(runtimeEnvironmentId) - } - return localNativeChatTransport + const webClient = isWebClientLocation() + const remote = runtimeEnvironmentId && !webClient ? runtimeEnvironmentId : null + const transport = remote ? createRuntimeNativeChatTransport(remote) : localNativeChatTransport + return guardAntigravityChatTransport(transport, async () => { + if (remote) { + return runtimeEnvironmentSupportsCapability( + remote, + ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY + ) + } + const capabilities = webClient + ? (await window.api.runtime.getStatus()).capabilities + : await ensureLocalRuntimeCapabilities() + if (!capabilities) { + throw new Error('Runtime capabilities unavailable') + } + return capabilities.includes(ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY) + }) } diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts index d0930253ab26..1b0ef168ed97 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts @@ -1,6 +1,6 @@ import { useCallback, useLayoutEffect, useRef } from 'react' import { useAppStore } from '../../store' -import { sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection' +import { isRemoteRuntimePtyId, sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection' import { getSettingsForAgentTabRuntimeOwner } from '@/lib/agent-paste-draft' import type { AgentType } from '../../../../shared/native-chat-types' import { @@ -21,6 +21,9 @@ import { type NativeChatSendHandle } from './native-chat-runtime-send' import { inferQuestionAnsweredFromCurrentStatus } from '../terminal-pane/agent-question-answered-inference' +import { createNativeChatAntigravityInterrupt } from './native-chat-antigravity-interrupt' +import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' // ESC is the agent-TUI interrupt/cancel key over the PTY (matches how the // composer forwards Escape). Used to cancel a question or deny an approval. @@ -62,16 +65,34 @@ export function useNativeChatInteractiveSend( // unmount so a detached setTimeout chain can't keep writing PTY bytes after // the view is gone / the user switched away. const inFlightRef = useRef(null) + const interruptRef = useRef | null>(null) const cancelInFlight = useCallback(() => { inFlightRef.current?.cancel() inFlightRef.current = null }, []) // Why: a split can be rebound without unmounting this view. Cancel during // commit so no delayed answer write can race the replacement PTY. - useLayoutEffect( - () => cancelInFlight, - [agent, cancelInFlight, paneKey, targetPtyId, terminalTabId] - ) + useLayoutEffect(() => { + const interrupt = createNativeChatAntigravityInterrupt({ + paneKey, + getStatusEntry: () => useAppStore.getState().agentStatusByPaneKey[paneKey], + writeAccepted: () => + targetPtyId + ? window.api.pty.writeAccepted(targetPtyId, ESC, 'driving') + : Promise.resolve(false), + inferInterrupt: (request) => + window.api.agentStatus.inferInterrupt(request).catch((error) => { + console.warn('[agent-interrupt] native Chat inference failed:', error) + return false + }) + }) + interruptRef.current = interrupt + return () => { + cancelInFlight() + interrupt.dispose() + interruptRef.current = null + } + }, [agent, cancelInFlight, paneKey, targetPtyId, terminalTabId]) const sendRaw = useCallback( (raw: string) => { @@ -159,8 +180,21 @@ export function useNativeChatInteractiveSend( const cancelAsk = useCallback(() => { cancelInFlight() - sendRaw(ESC) - }, [cancelInFlight, sendRaw]) + const settings = getSettingsForAgentTabRuntimeOwner(terminalTabId) + if ( + agent === 'antigravity' && + targetPtyId && + !isRemoteRuntimePtyId(targetPtyId) && + !parseAppSshPtyId(targetPtyId) && + getActiveRuntimeTarget(settings).kind === 'local' + ) { + void interruptRef.current?.cancel().catch((error) => { + console.warn('[agent-interrupt] native Chat cancellation failed:', error) + }) + } else { + sendRaw(ESC) + } + }, [agent, cancelInFlight, sendRaw, targetPtyId, terminalTabId]) const cancel = useCallback(() => { cancelInFlight() diff --git a/src/renderer/src/components/settings/NativeChatSupportedAgents.test.tsx b/src/renderer/src/components/settings/NativeChatSupportedAgents.test.tsx index 18c4ab37182d..cebc2531b2b4 100644 --- a/src/renderer/src/components/settings/NativeChatSupportedAgents.test.tsx +++ b/src/renderer/src/components/settings/NativeChatSupportedAgents.test.tsx @@ -19,7 +19,8 @@ const EXPECTED_SUPPORTED_AGENTS = [ 'grok', 'omp', 'opencode', - 'opencode2' + 'opencode2', + 'antigravity' ] as const satisfies readonly TuiAgent[] const SUPPORTED_AGENTS_LABEL_KEY = 'auto.components.settings.NativeChatSupportedAgents.label' diff --git a/src/renderer/src/lib/antigravity-session-launch-view.test.ts b/src/renderer/src/lib/antigravity-session-launch-view.test.ts new file mode 100644 index 000000000000..a5121c5f22eb --- /dev/null +++ b/src/renderer/src/lib/antigravity-session-launch-view.test.ts @@ -0,0 +1,214 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { createGlobalSettingsFixture } from '../../../shared/global-settings-test-fixture' +import { makePaneKey } from '../../../shared/stable-pane-id' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' +import { makeWorktree, TEST_REPO } from '@/store/slices/store-test-helpers' +import { launchAgentInNewTab } from './launch-agent-in-new-tab' +import { launchAiVaultSessionInNewTab } from './launch-ai-vault-session' +import { launchSleepingAgentSession } from './sleeping-agent-session-launch' +import * as draftDelivery from './agent-paste-draft' + +const initialState = useAppStore.getState() +const WORKTREE = 'wt-1' +const CLI_ID = 'actual-native-cli-conversation' +const LEAF = '11111111-1111-4111-8111-111111111111' + +beforeEach(() => { + vi.stubGlobal('window', { api: { ui: { set: vi.fn(async () => {}) } } }) + useAppStore.setState({ + settings: { + ...createGlobalSettingsFixture(), + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + agentStatusHooksEnabled: false, + agentWorkspaceTrustEnabled: false + }, + repos: [{ ...TEST_REPO, connectionId: null, executionHostId: 'local' }], + worktreesByRepo: { [TEST_REPO.id]: [makeWorktree({ id: WORKTREE, repoId: TEST_REPO.id })] }, + tabsByWorktree: {}, + unifiedTabsByWorktree: {}, + terminalLayoutsByTabId: {}, + pendingStartupByTabId: {}, + tabBarOrderByWorktree: {}, + activeWorktreeId: WORKTREE, + activeTabType: 'terminal' + }) +}) + +afterEach(() => { + useAppStore.setState(initialState, true) + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +function viewMode(tabId: string, worktreeId = WORKTREE) { + return useAppStore + .getState() + .unifiedTabsByWorktree[worktreeId]?.find((tab) => tab.entityId === tabId)?.viewMode +} + +function associate(tabId: string, worktreeId = WORKTREE) { + useAppStore + .getState() + .setAgentStatus( + makePaneKey(tabId, LEAF), + { agentType: 'antigravity', state: 'waiting', prompt: '' }, + 'Antigravity', + { updatedAt: 20, stateStartedAt: 20 }, + { tabId, worktreeId, connectionId: null }, + { providerSession: { key: 'conversation_id', id: CLI_ID } } + ) +} + +it('launches without a fabricated conversation and applies the preference after host association', () => { + const result = launchAgentInNewTab({ agent: 'antigravity', worktreeId: WORKTREE }) + if (result?.surface.kind !== 'local-terminal') { + throw new Error('Expected terminal launch') + } + const tabId = result.surface.tabId + const startup = useAppStore.getState().pendingStartupByTabId[tabId] + expect(viewMode(tabId)).toBeUndefined() + expect(startup?.resumeProviderSession).toBeUndefined() + expect(startup?.launchAgent).toBe('antigravity') + associate(tabId) + expect(viewMode(tabId)).toBe('chat') +}) + +it('keeps an explicit Terminal choice made between launch and association', () => { + const result = launchAgentInNewTab({ agent: 'antigravity', worktreeId: WORKTREE }) + if (result?.surface.kind !== 'local-terminal') { + throw new Error('Expected terminal launch') + } + useAppStore.getState().setTabViewMode(result.surface.tabId, 'terminal') + associate(result.surface.tabId) + expect(viewMode(result.surface.tabId)).toBe('terminal') +}) + +it('retains an unsent draft that the Chat composer cannot mirror in Terminal after association', () => { + const paste = vi.spyOn(draftDelivery, 'pasteDraftWhenAgentReady').mockResolvedValue(true) + const result = launchAgentInNewTab({ + agent: 'antigravity', + worktreeId: WORKTREE, + prompt: 'first\u2028second', + promptDelivery: 'draft' + }) + if (result?.surface.kind !== 'local-terminal') { + throw new Error('Expected draft terminal launch') + } + expect(viewMode(result.surface.tabId)).toBe('terminal') + associate(result.surface.tabId) + expect(viewMode(result.surface.tabId)).toBe('terminal') + expect(paste).toHaveBeenCalledWith( + expect.objectContaining({ content: 'first\u2028second', submit: false }) + ) +}) + +it('uses the actual native CLI identity supplied by the AI Vault resume caller', () => { + const providerSession = { key: 'conversation_id', id: CLI_ID } as const + const result = launchAiVaultSessionInNewTab({ + agent: 'antigravity', + worktreeId: WORKTREE, + command: `antigravity --resume ${CLI_ID}`, + providerSession + }) + if (result.tabId === null) { + throw new Error('Expected local resume') + } + expect(viewMode(result.tabId)).toBe('chat') + expect(useAppStore.getState().pendingStartupByTabId[result.tabId]?.resumeProviderSession).toEqual( + providerSession + ) +}) + +it.each([undefined, { key: 'session_id', id: 'ide-reference' } as const])( + 'keeps an AI Vault launch without a CLI conversation in Terminal', + (providerSession) => { + const result = launchAiVaultSessionInNewTab({ + agent: 'antigravity', + worktreeId: WORKTREE, + command: 'antigravity', + providerSession + }) + if (result.tabId === null) { + throw new Error('Expected local launch') + } + expect(viewMode(result.tabId)).toBeUndefined() + } +) + +it('uses the sleeping CLI session identity while retaining background resume and claim behavior', () => { + const record: SleepingAgentSessionRecord = { + paneKey: makePaneKey('old-tab', LEAF), + tabId: 'old-tab', + worktreeId: WORKTREE, + agent: 'antigravity', + providerSession: { key: 'conversation_id', id: CLI_ID }, + prompt: '', + state: 'waiting', + origin: 'quit', + capturedAt: 1, + updatedAt: 1 + } + useAppStore.setState({ sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } }) + expect(launchSleepingAgentSession(record, { suppressNavigation: true })).toBe(true) + const tab = useAppStore.getState().tabsByWorktree[WORKTREE]?.[0] + if (!tab) { + throw new Error('Missing resume tab') + } + expect(viewMode(tab.id)).toBe('chat') + expect(useAppStore.getState().pendingStartupByTabId[tab.id]?.resumeProviderSession).toEqual( + record.providerSession + ) + expect(useAppStore.getState().pendingStartupByTabId[tab.id]?.showSessionRestoredBanner).toBe(true) + expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[record.paneKey]).toBeUndefined() + expect(useAppStore.getState().activeTabId).toBe(initialState.activeTabId) +}) + +it('keeps a direct SSH resume in Terminal even with a known conversation', () => { + useAppStore.setState({ repos: [{ ...TEST_REPO, connectionId: 'ssh-offline' }] }) + const result = launchAiVaultSessionInNewTab({ + agent: 'antigravity', + worktreeId: WORKTREE, + command: `antigravity --resume ${CLI_ID}`, + providerSession: { key: 'conversation_id', id: CLI_ID } + }) + if (result.tabId === null) { + throw new Error('Expected direct SSH terminal') + } + expect(viewMode(result.tabId)).toBeUndefined() +}) + +it('applies delayed CLI association in a folder workspace without a git worktree', () => { + const worktreeId = 'folder:fixture-folder' + useAppStore.setState({ + repos: [], + worktreesByRepo: {}, + folderWorkspaces: [ + { + id: 'fixture-folder', + projectGroupId: 'folder-group', + name: 'Folder fixture', + folderPath: '/private/fixture-folder', + connectionId: null, + executionHostId: 'local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + ] + }) + const result = launchAgentInNewTab({ agent: 'antigravity', worktreeId }) + if (result?.surface.kind !== 'local-terminal') { + throw new Error('Expected folder terminal launch') + } + expect(viewMode(result.surface.tabId, worktreeId)).toBeUndefined() + associate(result.surface.tabId, worktreeId) + expect(viewMode(result.surface.tabId, worktreeId)).toBe('chat') +}) diff --git a/src/renderer/src/lib/launch-ai-vault-session.ts b/src/renderer/src/lib/launch-ai-vault-session.ts index 4cf4ceaef5fa..1ac367a0f08c 100644 --- a/src/renderer/src/lib/launch-ai-vault-session.ts +++ b/src/renderer/src/lib/launch-ai-vault-session.ts @@ -13,6 +13,9 @@ import type { } from '../../../shared/agent-session-resume' import type { TabSplitDirection } from '@/store/slices/tabs' import type { WebRuntimeTerminalCreateOutcome } from '@/runtime/web-runtime-session' +import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode' +import { getConnectionIdFromState } from '@/lib/connection-context' +import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' export type LaunchAiVaultSessionInNewTabResult = | { tabId: string; groupId?: string } @@ -31,6 +34,17 @@ export function launchAiVaultSessionInNewTab(args: { splitDirection?: TabSplitDirection }): LaunchAiVaultSessionInNewTabResult { const store = useAppStore.getState() + const antigravityViewModeProps = + args.agent === 'antigravity' + ? initialAgentTabViewModeProps(store.settings, { + agent: 'antigravity', + providerSessionId: + args.providerSession?.key === 'conversation_id' ? args.providerSession.id : undefined, + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable( + getConnectionIdFromState(store, args.worktreeId) + ) + }) + : {} let targetGroupId = args.targetGroupId const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(store, args.worktreeId) if (isWebRuntimeSessionActive(runtimeEnvironmentId)) { @@ -46,6 +60,9 @@ export function launchAiVaultSessionInNewTab(args: { ...(args.envToDelete ? { envToDelete: args.envToDelete } : {}), ...(args.launchConfig ? { launchConfig: args.launchConfig } : {}), ...(args.providerSession ? { providerSession: args.providerSession } : {}), + ...(args.agent === 'antigravity' + ? { viewMode: antigravityViewModeProps.viewMode ?? 'terminal' } + : {}), ...(args.launchConfig ? { agentArgs: args.launchConfig.agentArgs } : {}), activate: true }) @@ -68,9 +85,15 @@ export function launchAiVaultSessionInNewTab(args: { targetGroupId } - const tab = args.cwd - ? store.createTab(args.worktreeId, targetGroupId, undefined, { startupCwd: args.cwd }) - : store.createTab(args.worktreeId, targetGroupId) + const tab = + args.cwd || args.agent === 'antigravity' + ? store.createTab(args.worktreeId, targetGroupId, undefined, { + ...(args.cwd ? { startupCwd: args.cwd } : {}), + ...(args.agent === 'antigravity' + ? { launchAgent: 'antigravity', ...antigravityViewModeProps } + : {}) + }) + : store.createTab(args.worktreeId, targetGroupId) store.queueTabStartupCommand(tab.id, { command: args.command, ...(args.env ? { env: args.env } : {}), diff --git a/src/renderer/src/lib/native-chat-initial-view-mode.test.ts b/src/renderer/src/lib/native-chat-initial-view-mode.test.ts index 52385894c034..ce143f171e42 100644 --- a/src/renderer/src/lib/native-chat-initial-view-mode.test.ts +++ b/src/renderer/src/lib/native-chat-initial-view-mode.test.ts @@ -7,15 +7,35 @@ import { import { isNativeChatTranscriptLocalReadable } from './native-chat-transcript-readability' describe('decideInitialAgentTabViewMode', () => { - it("returns 'chat' when native chat and the opt-in default setting are on", () => { - expect( - decideInitialAgentTabViewMode({ - experimentalNativeChat: true, - openAgentTabsInChatByDefault: true, - agent: 'codex' - }) - ).toBe('chat') - }) + it.each(['codex', 'antigravity'] as const)( + 'opens %s in chat when native chat and the opt-in default setting are on', + (agent) => { + expect( + decideInitialAgentTabViewMode({ + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + agent, + providerSessionId: agent === 'antigravity' ? 'known-conversation' : undefined, + nativeChatTranscriptIsLocalReadable: true + }) + ).toBe('chat') + } + ) + + it.each([undefined, null, '', ' '])( + 'keeps Antigravity in Terminal until its provider session is associated (%s)', + (providerSessionId) => { + expect( + decideInitialAgentTabViewMode({ + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + agent: 'antigravity', + providerSessionId, + nativeChatTranscriptIsLocalReadable: true + }) + ).toBeUndefined() + } + ) it('returns undefined when native chat is disabled', () => { expect( @@ -71,17 +91,21 @@ describe('decideInitialAgentTabViewMode', () => { ).toBe('chat') }) - it('keeps Model-A SSH omp in the terminal view but opens it locally', () => { - const forConnection = (connectionId: string | null): Tab['viewMode'] => - decideInitialAgentTabViewMode({ - experimentalNativeChat: true, - openAgentTabsInChatByDefault: true, - agent: 'omp', - nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(connectionId) - }) - expect(forConnection('ssh-target-1')).toBeUndefined() - expect(forConnection(null)).toBe('chat') - }) + it.each(['omp', 'antigravity'] as const)( + 'keeps Model-A SSH %s in the terminal view but opens it locally', + (agent) => { + const forConnection = (connectionId: string | null): Tab['viewMode'] => + decideInitialAgentTabViewMode({ + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + agent, + providerSessionId: agent === 'antigravity' ? 'known-conversation' : undefined, + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(connectionId) + }) + expect(forConnection('ssh-target-1')).toBeUndefined() + expect(forConnection(null)).toBe('chat') + } + ) it('keeps Model-A SSH Grok in the terminal view', () => { expect( diff --git a/src/renderer/src/lib/native-chat-initial-view-mode.ts b/src/renderer/src/lib/native-chat-initial-view-mode.ts index 8f89ecee0381..449525b7220b 100644 --- a/src/renderer/src/lib/native-chat-initial-view-mode.ts +++ b/src/renderer/src/lib/native-chat-initial-view-mode.ts @@ -27,6 +27,7 @@ export function decideInitialAgentTabViewMode(args: { /** The unsent launch context, when `promptDelivery` is `'draft'`. */ launchDraftText?: string nativeChatTranscriptIsLocalReadable?: boolean + providerSessionId?: string | null }): Tab['viewMode'] { if (!agentTabsDefaultToNativeChat(args)) { return undefined @@ -34,6 +35,9 @@ export function decideInitialAgentTabViewMode(args: { if (!isNativeChatSupportedAgent(args.agent)) { return undefined } + if (args.agent === 'antigravity' && !args.providerSessionId?.trim()) { + return undefined + } if ( nativeChatRequiresLocalTranscript(args.agent) && args.nativeChatTranscriptIsLocalReadable !== true @@ -59,6 +63,7 @@ export function initialAgentTabViewModeProps( promptDelivery?: NativeChatLaunchPromptDelivery launchDraftText?: string nativeChatTranscriptIsLocalReadable?: boolean + providerSessionId?: string | null } = {} ): { viewMode?: Tab['viewMode'] } { const viewMode = decideInitialAgentTabViewMode({ @@ -67,7 +72,13 @@ export function initialAgentTabViewModeProps( agent: options.agent, promptDelivery: options.promptDelivery, launchDraftText: options.launchDraftText, - nativeChatTranscriptIsLocalReadable: options.nativeChatTranscriptIsLocalReadable + nativeChatTranscriptIsLocalReadable: options.nativeChatTranscriptIsLocalReadable, + providerSessionId: options.providerSessionId }) - return viewMode ? { viewMode } : {} + // A draft the composer cannot mirror must keep its terminal surface after session association. + const keepAntigravityDraftInTerminal = + options.agent === 'antigravity' && + options.promptDelivery === 'draft' && + !canMirrorLaunchDraftToNativeChat(options.launchDraftText ?? '') + return viewMode ? { viewMode } : keepAntigravityDraftInTerminal ? { viewMode: 'terminal' } : {} } diff --git a/src/renderer/src/lib/sleeping-agent-session-launch.ts b/src/renderer/src/lib/sleeping-agent-session-launch.ts index 5b6e192ec4b3..5b55b032f1f3 100644 --- a/src/renderer/src/lib/sleeping-agent-session-launch.ts +++ b/src/renderer/src/lib/sleeping-agent-session-launch.ts @@ -15,6 +15,9 @@ import { } from '../../../shared/tui-agent-launch-defaults' import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-resume' import { translate } from '@/i18n/i18n' +import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode' +import { getConnectionIdFromState } from '@/lib/connection-context' +import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' export type ResumeSleepingAgentSessionsOptions = { suppressNavigation?: boolean @@ -100,6 +103,18 @@ export function launchSleepingAgentSession( const tab = state.createTab(record.worktreeId, undefined, undefined, { launchAgent: record.agent, + ...(record.agent === 'antigravity' + ? initialAgentTabViewModeProps(state.settings, { + agent: 'antigravity', + providerSessionId: + record.providerSession.key === 'conversation_id' + ? record.providerSession.id + : undefined, + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable( + getConnectionIdFromState(state, record.worktreeId) + ) + }) + : {}), pendingStartup: { command: startupPlan.launchCommand, ...(startupPlan.env ? { env: startupPlan.env } : {}), diff --git a/src/renderer/src/store/slices/agent-status-live-reducer.ts b/src/renderer/src/store/slices/agent-status-live-reducer.ts index 1ce8de5f7200..ec718ed2a1b6 100644 --- a/src/renderer/src/store/slices/agent-status-live-reducer.ts +++ b/src/renderer/src/store/slices/agent-status-live-reducer.ts @@ -10,6 +10,7 @@ import { removePaneKeys } from './agent-status-pane-keyed-records' import { recoveryRecordMatches } from './agent-status-recovery-equivalence' import type { AgentStatusLiveEntryBuild } from './agent-status-live-entry-builder' import { agentProviderSessionsEqual } from '../../../../shared/agent-session-resume' +import { antigravityInitialChatViewPatch } from './antigravity-initial-chat-view' export type AgentStatusLiveUpdateReduction = { patch: Partial @@ -110,6 +111,7 @@ export function reduceAgentStatusLiveUpdate( nextLaunchConfigs = removePaneKeys(nextLaunchConfigs, evicted) } const patch: Partial = { + ...antigravityInitialChatViewPatch(state, entry), agentStatusByPaneKey: nextLive, retainedAgentsByPaneKey: nextRetainedAgents, sleepingAgentSessionsByPaneKey: nextSleepingAgentSessions, diff --git a/src/renderer/src/store/slices/antigravity-initial-chat-association.test.ts b/src/renderer/src/store/slices/antigravity-initial-chat-association.test.ts new file mode 100644 index 000000000000..9c11e31ad3c7 --- /dev/null +++ b/src/renderer/src/store/slices/antigravity-initial-chat-association.test.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture' +import { createTestStore, makeTab, makeUnifiedTab } from './store-test-helpers' +import { makePaneKey } from '../../../../shared/stable-pane-id' + +const WORKSPACE = 'folder-workspace' +const TAB = 'agy-tab' +const LEAF = '11111111-1111-4111-8111-111111111111' +const PANE = makePaneKey(TAB, LEAF) +let store: ReturnType + +beforeEach(() => { + vi.stubGlobal('window', { api: { ui: { set: vi.fn(async () => {}) } } }) + store = createTestStore() + store.setState({ + settings: { + ...createGlobalSettingsFixture(), + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + agentStatusHooksEnabled: false, + agentWorkspaceTrustEnabled: false + }, + tabsByWorktree: { + [WORKSPACE]: [makeTab({ id: TAB, worktreeId: WORKSPACE, launchAgent: 'antigravity' })] + }, + unifiedTabsByWorktree: { + [WORKSPACE]: [makeUnifiedTab({ id: TAB, worktreeId: WORKSPACE, groupId: 'group' })] + }, + terminalLayoutsByTabId: { + [TAB]: { root: { type: 'leaf', leafId: LEAF }, activeLeafId: LEAF, expandedLeafId: null } + } + }) +}) +afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +function associate( + args: { + id?: string + key?: 'conversation_id' | 'session_id' + restored?: boolean + connectionId?: string | null + at?: number + } = {} +) { + store.getState().setAgentStatus( + PANE, + { + agentType: 'antigravity', + state: 'working', + prompt: '', + ...(args.restored ? { restoredUnconfirmed: true } : {}) + }, + 'Antigravity', + { updatedAt: args.at ?? 10, stateStartedAt: 10 }, + { tabId: TAB, worktreeId: WORKSPACE, connectionId: args.connectionId ?? null }, + args.id ? { providerSession: { key: args.key ?? 'conversation_id', id: args.id } } : undefined + ) +} +function mode() { + return store.getState().unifiedTabsByWorktree[WORKSPACE][0].viewMode +} + +it('keeps a fresh launch in Terminal until a real CLI association reaches the production status path', () => { + associate() + expect(mode()).toBeUndefined() + associate({ id: 'actual-cli-conversation', at: 20 }) + expect(mode()).toBe('chat') + expect(store.getState().tabsByWorktree[WORKSPACE][0].viewMode).toBe('chat') +}) + +it.each(['terminal', 'chat'] as const)( + 'keeps the explicit %s choice during delayed identity and restore', + (choice) => { + store.getState().setTabViewMode(TAB, choice) + associate({ id: 'restored-cli', restored: true }) + associate({ id: 'actual-cli-conversation', at: 20 }) + expect(mode()).toBe(choice) + } +) + +it('does not treat restored identity or an IDE/reference session key as a fresh CLI association', () => { + associate({ id: 'restored-cli', restored: true }) + expect(mode()).toBeUndefined() + associate({ id: 'ide-reference-id', key: 'session_id', at: 20 }) + expect(mode()).toBeUndefined() +}) + +it('does not apply a stale association after a newer unassociated turn', () => { + associate({ at: 30 }) + associate({ id: 'old-cli-conversation', at: 20 }) + expect(mode()).toBeUndefined() +}) + +it('keeps a direct SSH association in Terminal', () => { + associate({ id: 'remote-cli', connectionId: 'ssh-unverifiable' }) + expect(mode()).toBeUndefined() +}) + +it.each(['wsl:Debian', 'runtime-ssh-fixture-host'])( + 'retains the existing transcript transport for %s associations', + (connectionId) => { + associate({ id: 'host-owned-cli', connectionId }) + expect(mode()).toBe('chat') + } +) + +it('does not apply the preference to an arbitrary terminal that merely runs Antigravity', () => { + store.setState({ tabsByWorktree: { [WORKSPACE]: [makeTab({ id: TAB, worktreeId: WORKSPACE })] } }) + associate({ id: 'typed-cli' }) + expect(mode()).toBeUndefined() +}) + +it('keeps the preference disabled when the setting is off', () => { + const settings = store.getState().settings + if (!settings) { + throw new Error('Settings missing') + } + store.setState({ settings: { ...settings, openAgentTabsInChatByDefault: false } }) + associate({ id: 'actual-cli-conversation' }) + expect(mode()).toBeUndefined() +}) diff --git a/src/renderer/src/store/slices/antigravity-initial-chat-view.ts b/src/renderer/src/store/slices/antigravity-initial-chat-view.ts new file mode 100644 index 000000000000..5cbc7db67469 --- /dev/null +++ b/src/renderer/src/store/slices/antigravity-initial-chat-view.ts @@ -0,0 +1,69 @@ +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { isWslHookRelayConnectionId } from '../../../../shared/wsl-hook-relay-contract' +import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode' +import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' +import { collectLeafIdsInOrder } from '@/components/terminal-pane/layout-serialization' +import type { AppState } from '../types' +import { patchTab } from './tab-group-state' +import { patchTerminalTabRow } from './tabs/tabs-host-mirroring' + +/** Apply the launch preference when the execution host first supplies the CLI identity. */ +export function antigravityInitialChatViewPatch( + state: AppState, + entry: AgentStatusEntry +): Partial { + const pane = parsePaneKey(entry.paneKey) + const worktreeId = entry.worktreeId + if ( + !pane || + !worktreeId || + entry.agentType !== 'antigravity' || + entry.restoredUnconfirmed === true || + entry.providerSession?.key !== 'conversation_id' + ) { + return {} + } + const terminal = state.tabsByWorktree[worktreeId]?.find((tab) => tab.id === pane.tabId) + const tab = state.unifiedTabsByWorktree[worktreeId]?.find( + (candidate) => candidate.contentType === 'terminal' && candidate.entityId === pane.tabId + ) + if ( + !terminal || + !tab || + terminal.launchAgent !== 'antigravity' || + terminal.viewMode !== undefined || + tab.viewMode !== undefined + ) { + return {} + } + const layout = state.terminalLayoutsByTabId[pane.tabId] + const leaves = layout ? collectLeafIdsInOrder(layout.root) : [] + if (leaves.length > 0 && (leaves.length !== 1 || leaves[0] !== pane.leafId)) { + return {} + } + const draft = state.nativeChatLaunchDraftByTabId[pane.tabId] + const { viewMode } = initialAgentTabViewModeProps(state.settings, { + agent: 'antigravity', + providerSessionId: entry.providerSession.id, + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable( + isWslHookRelayConnectionId(entry.connectionId) ? null : entry.connectionId + ), + ...(draft ? { promptDelivery: 'draft', launchDraftText: draft.text } : {}) + }) + if (viewMode !== 'chat') { + return {} + } + return { + ...patchTab(state.unifiedTabsByWorktree, tab.id, { viewMode }), + ...patchTerminalTabRow(state.tabsByWorktree, terminal.id, { viewMode }), + ...(layout + ? { + terminalLayoutsByTabId: { + ...state.terminalLayoutsByTabId, + [pane.tabId]: { ...layout, chatLeafId: pane.leafId } + } + } + : {}) + } +} diff --git a/src/shared/agent-session-resume.test.ts b/src/shared/agent-session-resume.test.ts index 0fd5ce5ebd58..a33effd2c4ba 100644 --- a/src/shared/agent-session-resume.test.ts +++ b/src/shared/agent-session-resume.test.ts @@ -8,6 +8,19 @@ import { } from './agent-session-resume' describe('agent session resume metadata', () => { + it('preserves the Antigravity hook transcript path for host-owned chat reads', () => { + expect( + extractAgentProviderSession('antigravity', { + conversationId: 'agy-conversation', + transcriptPath: '/workspace/brain/transcript.jsonl' + }) + ).toEqual({ + key: 'conversation_id', + id: 'agy-conversation', + transcriptPath: '/workspace/brain/transcript.jsonl' + }) + }) + it('treats devin as a resumable TUI agent', () => { expect(isResumableTuiAgent('devin')).toBe(true) }) diff --git a/src/shared/agent-session-resume.ts b/src/shared/agent-session-resume.ts index ba1f5574ab1f..87e91997564d 100644 --- a/src/shared/agent-session-resume.ts +++ b/src/shared/agent-session-resume.ts @@ -235,7 +235,7 @@ export function extractAgentProviderSession( } case 'antigravity': { const id = readSessionId(payload, ['conversationId']) - return id ? { key: 'conversation_id', id } : null + return id ? withTranscriptPath({ key: 'conversation_id', id }, payload) : null } case 'opencode': case 'opencode2': diff --git a/src/shared/native-chat-agent-support.test.ts b/src/shared/native-chat-agent-support.test.ts index 23749bb0dfbf..8eafacfab534 100644 --- a/src/shared/native-chat-agent-support.test.ts +++ b/src/shared/native-chat-agent-support.test.ts @@ -38,13 +38,14 @@ describe('isNativeChatSupportedAgent', () => { }) describe('nativeChatRequiresLocalTranscript', () => { - it('covers the agents whose hook discloses no transcript path', () => { + it('covers agents requiring a runtime-owned transcript filesystem', () => { // Claude/Codex report `transcript_path`; Grok and omp report only an id, so // native chat has to find their file on a disk this process can read. expect(nativeChatRequiresLocalTranscript('opencode')).toBe(true) expect(nativeChatRequiresLocalTranscript('opencode2')).toBe(true) expect(nativeChatRequiresLocalTranscript('grok')).toBe(true) expect(nativeChatRequiresLocalTranscript('omp')).toBe(true) + expect(nativeChatRequiresLocalTranscript('antigravity')).toBe(true) expect(nativeChatRequiresLocalTranscript('claude')).toBe(false) expect(nativeChatRequiresLocalTranscript('openclaude')).toBe(false) expect(nativeChatRequiresLocalTranscript('codex')).toBe(false) diff --git a/src/shared/native-chat-agent-support.ts b/src/shared/native-chat-agent-support.ts index e2bb9c40cacc..021b1dbe5ff7 100644 --- a/src/shared/native-chat-agent-support.ts +++ b/src/shared/native-chat-agent-support.ts @@ -1,6 +1,12 @@ import type { TuiAgent } from './tui-agent' -export type NativeChatTranscriptAgent = 'claude' | 'codex' | 'grok' | 'omp' | 'opencode' +export type NativeChatTranscriptAgent = + | 'claude' + | 'codex' + | 'grok' + | 'omp' + | 'opencode' + | 'antigravity' /** Agents whose transcripts the native chat view can parse and render, in the * order the settings pane advertises them. */ @@ -11,7 +17,8 @@ export const NATIVE_CHAT_SUPPORTED_AGENT_LIST: readonly TuiAgent[] = [ 'grok', 'omp', 'opencode', - 'opencode2' + 'opencode2', + 'antigravity' ] export const NATIVE_CHAT_SUPPORTED_AGENTS: ReadonlySet = new Set( @@ -22,11 +29,16 @@ export function isNativeChatSupportedAgent(agent: string | null | undefined): bo return agent != null && NATIVE_CHAT_SUPPORTED_AGENTS.has(agent) } -/** Agents whose Model-A SSH transcript reader is not supported. A hook path alone - * does not establish owning-host reads, so OMP remains gated even with metadata. */ +/** Agents whose chat reads require a filesystem owned by the selected runtime. + * Direct SSH has no transcript transport; a hook path alone is not a local file. */ export function nativeChatRequiresLocalTranscript(agent: string | null | undefined): boolean { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) - return transcriptAgent === 'grok' || transcriptAgent === 'omp' || transcriptAgent === 'opencode' + return ( + transcriptAgent === 'grok' || + transcriptAgent === 'omp' || + transcriptAgent === 'opencode' || + transcriptAgent === 'antigravity' + ) } /** Selector TUIs require key steps rather than pasted option labels. */ @@ -48,7 +60,7 @@ export function resolveNativeChatTranscriptAgent( if (agent === 'opencode' || agent === 'opencode2') { return 'opencode' } - if (agent === 'codex' || agent === 'grok' || agent === 'omp') { + if (agent === 'codex' || agent === 'grok' || agent === 'omp' || agent === 'antigravity') { return agent } return null diff --git a/src/shared/native-chat-reasoning-order.test.ts b/src/shared/native-chat-reasoning-order.test.ts index ea3fd56305b4..a5865cc20215 100644 --- a/src/shared/native-chat-reasoning-order.test.ts +++ b/src/shared/native-chat-reasoning-order.test.ts @@ -44,3 +44,21 @@ it('keeps timestamp and journal authority ahead of a derived reasoning key', () laterReasoning.timestamp = 0 expect(compareNativeChatTranscriptMessages(answer, laterReasoning)).toBeLessThan(0) }) + +it('keeps provider step order and reasoning pairs together at a timestamp tie', () => { + const user = { ...row('9', 'user'), transcriptPosition: 9, timestampPrecision: 'second' as const } + const answer = { ...row('10', 'assistant'), transcriptPosition: 10 } + const reasoning = { ...row('10:reasoning', 'reasoning'), transcriptPosition: 10 } + const messages = [answer, reasoning, user] + const sorted = [...messages].sort(compareNativeChatTranscriptMessages) + expect(sorted).toEqual([user, reasoning, answer]) + expect(projectNativeChatTranscriptMessages(messages)).toEqual(sorted) + expect(sorted[0]).toBe(user) + expect(sorted[0].timestampPrecision).toBe('second') + for (let first = 0; first < sorted.length; first++) { + for (let second = first + 1; second < sorted.length; second++) { + expect(compareNativeChatTranscriptMessages(sorted[first], sorted[second])).toBeLessThan(0) + expect(compareNativeChatTranscriptMessages(sorted[second], sorted[first])).toBeGreaterThan(0) + } + } +}) diff --git a/src/shared/native-chat-transcript-projection.test.ts b/src/shared/native-chat-transcript-projection.test.ts index a6cce5e9d16f..3b91d592a8d1 100644 --- a/src/shared/native-chat-transcript-projection.test.ts +++ b/src/shared/native-chat-transcript-projection.test.ts @@ -177,3 +177,25 @@ describe("a subagent's rows are not the conversation's", () => { ]) }) }) + +it('keeps journal order ahead of a provider transcript position', () => { + const first = row('first', say('first'), { + transcriptPosition: 10, + journalPosition: { sequence: 1, index: 0 } + }) + const second = row('second', say('second'), { + transcriptPosition: 9, + journalPosition: { sequence: 2, index: 0 } + }) + expect(projectNativeChatTranscriptMessages([second, first]).map((message) => message.id)).toEqual( + ['first', 'second'] + ) +}) + +it('retains lexical ties for transcripts without provider order', () => { + const first = row('9', say('first'), { journalPosition: undefined }) + const second = row('10', say('second'), { journalPosition: undefined }) + expect(projectNativeChatTranscriptMessages([first, second]).map((message) => message.id)).toEqual( + ['10', '9'] + ) +}) diff --git a/src/shared/native-chat-transcript-projection.ts b/src/shared/native-chat-transcript-projection.ts index 3ab78007edb0..6c3d73a611fa 100644 --- a/src/shared/native-chat-transcript-projection.ts +++ b/src/shared/native-chat-transcript-projection.ts @@ -25,6 +25,12 @@ export function compareNativeChatMessagesByTime( if (at !== bt) { return at - bt } + if (a.transcriptPosition !== undefined && b.transcriptPosition !== undefined) { + const order = a.transcriptPosition - b.transcriptPosition + if (order !== 0) { + return order + } + } // Split reasoning shares its provider row's key, before that row's answer. const aId = nativeChatSemanticRowId(a) const bId = nativeChatSemanticRowId(b) diff --git a/src/shared/native-chat-types.ts b/src/shared/native-chat-types.ts index 127a9837910b..a1d483697f7f 100644 --- a/src/shared/native-chat-types.ts +++ b/src/shared/native-chat-types.ts @@ -204,6 +204,10 @@ export type NativeChatMessage = AgentJournalProducerLinkage & { /** Epoch ms when the message was produced, or null when the source could not * supply one (e.g. some scrape segments). Null sorts before any timestamp. */ timestamp: number | null + /** Producer-declared clock precision; absent means exact milliseconds. */ + timestampPrecision?: 'second' | 'millisecond' + /** Provider step order breaks ties when its transcript clock has coarse precision. */ + transcriptPosition?: number source: NativeChatSource /** Optional provider row cursor; split projections share it for whole-row paging. */ transcriptOffset?: number diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index 47deda80d81d..b48a1be13ac5 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -334,12 +334,15 @@ export const NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES = [ export const ANTIGRAVITY_CONFIGURED_MODEL_RUNTIME_CAPABILITY = 'git.antigravity-configured-model.v1' as const +export const ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY = 'native-chat.antigravity.v1' as const + // Why: `agentSession.create` is a strict object, so an older host refuses a payload carrying the // reserved `tabId` rather than ignoring it. A client sends the field only to a host advertising this. export const AGENT_SESSION_CREATE_TAB_ID_RUNTIME_CAPABILITY = 'agentSession.create.tab-id.v1' as const export const RUNTIME_CAPABILITIES = [ + ANTIGRAVITY_NATIVE_CHAT_RUNTIME_CAPABILITY, ...AGENT_SESSION_STOP_RUNTIME_CAPABILITIES, AGENT_SESSION_CREATE_TAB_ID_RUNTIME_CAPABILITY, ANTIGRAVITY_CONFIGURED_MODEL_RUNTIME_CAPABILITY, diff --git a/tests/e2e/native-chat-antigravity-first-send.unit.test.ts b/tests/e2e/native-chat-antigravity-first-send.unit.test.ts new file mode 100644 index 000000000000..42ae7e39f046 --- /dev/null +++ b/tests/e2e/native-chat-antigravity-first-send.unit.test.ts @@ -0,0 +1,180 @@ +// @vitest-environment happy-dom +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { NativeChatMessage } from '../../src/shared/native-chat-types' +import { decodeAntigravityTranscriptLine } from '../../src/main/native-chat/transcript-line-decoders-antigravity' +import { decodeClaudeTranscriptLine } from '../../src/main/native-chat/transcript-line-decoders-claude' +import { decodeCodexTranscriptLine } from '../../src/main/native-chat/transcript-line-decoders-codex' +import { assembleNativeChatSession } from '../../src/renderer/src/components/native-chat/native-chat-session-assembler' +import { parseRuntimeNativeChatReadSessionResult } from '../../src/renderer/src/components/native-chat/native-chat-runtime-contract' +import { prepareNativeChatLiveMessages } from '../../src/renderer/src/components/native-chat/native-chat-live-message-preparation' +import { + appendPendingSendCache, + clearPendingSendCacheForTests, + launchPromptAsMessage, + shouldPruneLaunchPrompt, + pendingSendsAsMessages, + prunePendingSends +} from '../../src/renderer/src/components/native-chat/native-chat-pending' +import { useNativeChatPendingDelivery } from '../../src/renderer/src/components/native-chat/use-native-chat-pending-delivery' + +const captured = readFileSync( + resolve('src/main/native-chat/__fixtures__/antigravity/live-timestamp-tie.jsonl'), + 'utf8' +) + .trim() + .split('\n') + .map((line, index) => { + const message = decodeAntigravityTranscriptLine(line, `line-${index}`) + if (!message) { + throw new Error('Expected captured Antigravity row') + } + return message + }) +const user = captured[0]! +const reply = captured[1]! +const second = user.timestamp! +const text = user.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join(' ') +const firstSend = { id: 'first', text, sentAt: second + 300, afterMessageId: null } + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(firstSend.sentAt) + clearPendingSendCacheForTests() +}) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +it('hides the first echo at user-only flush, retains it over an empty read, then retires on reply', () => { + const initialMessages: NativeChatMessage[] = [] + const { result, rerender } = renderHook( + ({ messages }: { messages: NativeChatMessage[] }) => + useNativeChatPendingDelivery({ paneKey: 'agy-pane', agent: 'antigravity', messages }), + { initialProps: { messages: initialMessages } } + ) + act(() => result.current.record(text)) + expect(pendingSendsAsMessages(result.current.pending, [])).toHaveLength(1) + const visibleUser = prepareNativeChatLiveMessages([user], 'antigravity') + rerender({ messages: visibleUser }) + expect(pendingSendsAsMessages(result.current.pending, visibleUser)).toEqual([]) + expect(result.current.pending).toHaveLength(1) + rerender({ messages: [] }) + expect(pendingSendsAsMessages(result.current.pending, [])).toHaveLength(1) + rerender({ + messages: assembleNativeChatSession({ + sources: { transcript: [reply, user] }, + agent: 'antigravity', + sessionId: 'captured' + }).messages + }) + expect(result.current.pending).toEqual([]) +}) + +it('excludes earlier seconds and preserves strict transcript boundaries after paging', () => { + const old = captured.map((message) => ({ ...message, timestamp: second - 1000 })) + expect(prunePendingSends([firstSend], old)).toEqual([firstSend]) + const paged = { ...firstSend, afterMessageId: 'paged-out', afterMessageTimestamp: second } + expect(prunePendingSends([paged], captured)).toEqual([paged]) + expect(pendingSendsAsMessages([paged], captured)).toHaveLength(1) +}) + +it('does not let one coarse transcript occurrence consume two identical sends', () => { + const scope = { paneKey: 'agy-pane', agent: 'antigravity' } + appendPendingSendCache(scope, firstSend) + const pending = appendPendingSendCache(scope, { + ...firstSend, + id: 'second', + sentAt: second + 700 + }) + const remaining = prunePendingSends(pending, captured) + expect(remaining.map((entry) => entry.id)).toEqual(['second']) + expect(pendingSendsAsMessages(remaining, captured).map((message) => message.id)).toEqual([ + 'pending:second' + ]) +}) + +it.each(['claude', 'codex'] as const)( + 'keeps exact .000 %s history from claiming a later send', + (agent) => { + const timestamp = new Date(second).toISOString() + const record = + agent === 'claude' + ? { type: 'user', uuid: 'old', timestamp, message: { role: 'user', content: text } } + : { + type: 'response_item', + timestamp, + payload: { type: 'message', role: 'user', content: [{ type: 'text', text }] } + } + const decode = agent === 'claude' ? decodeClaudeTranscriptLine : decodeCodexTranscriptLine + const precise = decode(JSON.stringify(record), 'old') + if (!precise) { + throw new Error('Expected precise provider row') + } + const history = [precise, { ...reply, id: 'old-answer' }] + expect(precise.timestamp).toBe(second) + expect(prunePendingSends([firstSend], history)).toEqual([firstSend]) + expect(pendingSendsAsMessages([firstSend], history)).toHaveLength(1) + } +) + +it('also reconciles the seeded launch prompt against the captured first turn', () => { + const launch = { + tabId: 'agy-launch', + agent: 'antigravity' as const, + text, + createdAt: firstSend.sentAt + } + expect(launchPromptAsMessage(launch, [user])).toBeNull() + expect(shouldPruneLaunchPrompt(launch, [user])).toBe(false) + expect(shouldPruneLaunchPrompt(launch, captured)).toBe(true) +}) + +it('keeps an exact fallback timestamp at .000 from claiming a later Antigravity send', () => { + const row = decodeAntigravityTranscriptLine( + JSON.stringify({ + source: 'USER_EXPLICIT', + type: 'USER_INPUT', + content: text, + timestamp: new Date(second).toISOString() + }), + 'precise-fallback' + ) + if (!row) { + throw new Error('Expected fallback timestamp row') + } + expect(row.timestampPrecision).toBeUndefined() + expect(pendingSendsAsMessages([firstSend], [row])).toHaveLength(1) +}) + +it('preserves explicitly millisecond numeric Antigravity created_at even at .000', () => { + const row = decodeAntigravityTranscriptLine( + JSON.stringify({ + source: 'USER_EXPLICIT', + type: 'USER_INPUT', + content: text, + created_at: second + }), + 'precise-numeric' + ) + if (!row) { + throw new Error('Expected numeric timestamp row') + } + expect(row.timestampPrecision).toBeUndefined() + expect(pendingSendsAsMessages([firstSend], [row])).toHaveLength(1) +}) + +it('carries coarse precision across JSON reads and remains conservative when an older host omits it', () => { + const read = parseRuntimeNativeChatReadSessionResult( + JSON.parse(JSON.stringify({ messages: captured })) + ) + if (!('messages' in read)) { + throw new Error('Expected transported transcript') + } + expect(prunePendingSends([firstSend], read.messages)).toEqual([]) + const legacy = read.messages.map((message) => ({ ...message, timestampPrecision: undefined })) + expect(prunePendingSends([firstSend], legacy)).toEqual([firstSend]) +})