diff --git a/README.md b/README.md index 9487686bf..d789e3b95 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,16 @@ those observations into one conversation and renders it in React, without replacing the agent loop underneath. Antigravity’s Terminal view runs the interactive `agy` CLI in a PTY. Its Agent view uses `agy acp` to render the conversation through the Agent Client Protocol. +Both views receive the Agent Code tools enabled for that pane. Open `/mcp` inside the +native prompt to inspect its servers. To attach your own stdio or Streamable HTTP server, +enable its Antigravity column in **Settings → MCP** and reload the pane. Agent Code keeps +these grants local to the pane. Running `agy mcp list` in an ordinary shell lists your +separately configured CLI servers. + +Agent view accepts pasted images through the composer. In Terminal view, Agent Code can +deliver a text prompt when the CLI is showing an empty editor in the confirmed conversation. +An existing draft or dialog holds delivery. Both views discover Agent Code's personal skills +in `~/.gemini/config/skills` and the current project's skills in `.agents/skills`. [`agent-transcript-parser`](https://github.com/Juliusolsson05/agent-transcript-parser) translates transcripts between harnesses, which is what makes switching, diff --git a/docs/decomposition/antigravity-agent-code-compatibility.md b/docs/decomposition/antigravity-agent-code-compatibility.md new file mode 100644 index 000000000..559b183f4 --- /dev/null +++ b/docs/decomposition/antigravity-agent-code-compatibility.md @@ -0,0 +1,35 @@ +# Antigravity compatibility in Agent Code + +## Outcome + +Opening an Antigravity pane should preserve the Agent Code capabilities granted to that pane. A user can choose the native prompt or the rendered Agent view without silently losing tools. Preserve the provider's conversation identity and the user's CLI configuration. + +## Evidence + +- The released Terminal launcher forwards terminal I/O and conversation selection. It drops the already registered MCP servers. +- Agent view passes the built-in bridge to session/new or session/load. User-configured MCP servers are a separate path to verify. +- Native prompt delivery, project and personal skill discovery, management, and provider-specific conversation actions each have their own capability gates. Making a tool appear does not establish its behavior. +- The installed agy 1.5.18 lists zero configured servers on the reported setup. A disposable profile accepts an MCP server through its MCP config and rejects mcpServers as an unknown --settings key. + +## Stages + +1. Prove the installed CLI's supported configuration boundaries. Verify discovery using an isolated workspace and a harmless MCP server. Keep the application token scoped to the intended pane. +2. Reuse the existing session registration and implement native and rendered tool provisioning for supported transports, preferences and lifecycle paths. Preserve existing CLI settings and test concurrent panes. +3. Wire programmatic prompt delivery to the correct runtime, retaining native drafts and safe retry semantics. Verify readiness, permissions and session control. +4. Reconcile skill deployment and provider capability declarations against the CLI, including managed and personal skills, conversation operations and composer inputs. Expose only functions with verified behavior. +5. Exercise the normal application paths and record evidence for each feature plus any provider limitations. Run targeted tests, typecheck and review the combined changes. + +## Verification + +Use the real installed CLI with disposable settings and identifiable local MCP servers. Verify list, tool execution and isolation independently. Check failure and teardown with deterministic tests. Keep credentials, conversations and model responses out of fixtures. + +## Observations on agy 1.5.18 + +- Two concurrent native panes in one real checkout listed distinct grants from the application MCP host. Resuming the first pane restored its original tool. Opening agy separately left its configured servers intact. +- Native prompt dispatch preserved a human draft and submitted the local /new command from an empty confirmed editor. Rendered Agent view accepts image content over ACP. CLI permissions remain under the user's control. +- The CLI recognized personal skills from its current and two legacy directories. Agent Code uses the current directory for managed installs. +- Reading a confirmed native conversation uses ACP replay through the running pane's identity. Closing the pane revokes this access. Rendered panes retain their in-memory history. +- Google's documented hooks are configured in a temporary per-pane workspace. PreInvocation starts a reporting turn, PostToolUse marks work, and a fully idle Stop can request a TLDR or complete the turn. The adapter strips prompts, tool input and output before contacting the reporting host. See https://antigravity.google/docs/hooks. +- The installed ACP server returned method-not-found for fork, rewind and import. The CLI provides interactive /fork and /rewind; the application cannot use them as an exact durable conversation-editing API. Cross-provider history transfer and native subagent visualization remain outside verified support. +- A real SDK tools/call over the native relay wrote a TLDR into the intended pane's reporting store. The live CLI probe exercised discovery. External OAuth consent and model interpretation of an image were not exercised. Native agy handles OAuth directly for headerless HTTPS servers at an origin or /mcp. A server that relies on browser OAuth at a custom path can be configured in agy itself. +- The CLI can retain a globally started MCP server when an additional workspace declares the same name. Managed launches check global, project, and plugin configuration for an enabled external operator server before spawning agy. A real CLI disable sets the entry's disabled field to true. Reopen the pane after changing these settings so the check runs again. diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 3b9d71d93..89621cf90 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -171,6 +171,10 @@ function copyMainRuntimeResourcesPlugin(): Plugin { from: resolve(__dirname, 'packages/antigravity-acp-headless/src/mcpProxy.mjs'), to: resolve(__dirname, 'out/main/runtime/antigravity/mcpProxy.mjs'), }, + { + from: resolve(__dirname, 'src/providers/antigravity/runtime/nativeMcpRelay.cjs'), + to: resolve(__dirname, 'out/main/runtime/antigravity/nativeMcpRelay.cjs'), + }, ] const copyResources = async () => { diff --git a/packages/antigravity-acp-headless/src/AntigravityAcpSession.ts b/packages/antigravity-acp-headless/src/AntigravityAcpSession.ts index 1c0a2a5ef..40c44f87c 100644 --- a/packages/antigravity-acp-headless/src/AntigravityAcpSession.ts +++ b/packages/antigravity-acp-headless/src/AntigravityAcpSession.ts @@ -105,6 +105,9 @@ export class AntigravityAcpSession extends EventEmitter { private started = false private closed = false private turnActive = false + private promptImages = false + + get acceptsImages(): boolean { return this.promptImages } private readonly rows: AntigravityRow[] = [] private readonly permissions = new Map() private activity: AntigravityActivity = { active: false, status: 'starting' } @@ -161,6 +164,9 @@ export class AntigravityAcpSession extends EventEmitter { throw new AcpError('protocol', 'agy acp answered initialize with an unsupported protocol version') } + const caps = init.agentCapabilities + this.promptImages = isRecord(caps) && isRecord(caps.promptCapabilities) && caps.promptCapabilities.image === true + const mcpServers = [...(this.options.mcpServers ?? [])] const resumeId = this.options.resumeSessionId ?? null let result: unknown @@ -230,7 +236,11 @@ export class AntigravityAcpSession extends EventEmitter { * session/prompt at a time per session; a prompt typed during a turn should * run after it, as it would in agy's own TUI queue. */ - prompt(text: string): { accepted: Promise; finished: Promise } { + prompt(text: string, images: readonly { type: 'image'; mimeType: string; data: string }[] = []): { accepted: Promise; finished: Promise } { + if (images.length && !this.promptImages) { + const error = new AntigravityPromptError('rejected', 'agy does not advertise image prompts') + return { accepted: Promise.reject(error), finished: Promise.reject(error) } + } if (this.closed || !this.sessionId) { const error = new AntigravityPromptError(this.closed ? 'closed' : 'not-ready', this.closed ? 'agy has stopped' : 'agy is not ready yet') return { accepted: Promise.reject(error), finished: Promise.reject(error) } @@ -248,9 +258,9 @@ export class AntigravityAcpSession extends EventEmitter { throw error } this.turnActive = true - this.assembler.beginTurn(text) + this.assembler.beginTurn(images.length && !text.trim() ? '[Image attached]' : text) this.setActivity({ active: true, status: 'working' }) - const request = this.connection.request('session/prompt', { sessionId: this.sessionId, prompt: [{ type: 'text', text }] }, null) + const request = this.connection.request('session/prompt', { sessionId: this.sessionId, prompt: [...(text ? [{ type: 'text', text }] : []), ...images] }, null) accept() // Settled early only when agy ignores a cancel (see cancel()). const abandoned = new Promise((_, reject) => { diff --git a/packages/antigravity-acp-headless/src/catalog.ts b/packages/antigravity-acp-headless/src/catalog.ts index 62a8b81aa..4d12beedd 100644 --- a/packages/antigravity-acp-headless/src/catalog.ts +++ b/packages/antigravity-acp-headless/src/catalog.ts @@ -23,11 +23,11 @@ function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value) } -async function withConnection(input: Readable, output: Writable, run: (connection: AcpConnection, updates: (handler: ((update: Record) => void) | null) => void) => Promise): Promise { +async function withConnection(input: Readable, output: Writable, run: (connection: AcpConnection, updates: (handler: ((update: Record) => void) | null) => void) => Promise, sessionId?: string): Promise { let onUpdate: ((update: Record) => void) | null = null const connection = new AcpConnection(input, output, { onNotification: (method, params) => { - if (method === 'session/update' && isRecord(params) && isRecord(params.update)) onUpdate?.(params.update) + if (method === 'session/update' && isRecord(params) && params.sessionId === sessionId && isRecord(params.update)) onUpdate?.(params.update) }, // A read-only query never grants anything: refuse every agent request. onRequest: request => connection.respondError(request.id, -32601, 'read-only catalog client'), @@ -81,5 +81,5 @@ export async function readAntigravityConversation(input: Readable, output: Writa await connection.request('session/load', { sessionId: options.sessionId, cwd: options.cwd, mcpServers: [] }, 120_000) assembler.flush() return rows.sort((a, b) => a.ordinal - b.ordinal) - }) + }, options.sessionId) } diff --git a/packages/antigravity-acp-headless/src/transcript/assembler.ts b/packages/antigravity-acp-headless/src/transcript/assembler.ts index 87e22941f..e98ba8723 100644 --- a/packages/antigravity-acp-headless/src/transcript/assembler.ts +++ b/packages/antigravity-acp-headless/src/transcript/assembler.ts @@ -57,7 +57,7 @@ export type AntigravityRow = { export type AntigravitySemanticEvent = Record & { type: string; source: 'antigravity-acp'; ts: number } -type OpenSegment = { kind: 'user' | 'assistant' | 'thought'; ordinal: number; text: string; blockId: string; blockIndex: number; openedAt: number } +type OpenSegment = { includesImage?: boolean; kind: 'user' | 'assistant' | 'thought'; ordinal: number; text: string; blockId: string; blockIndex: number; openedAt: number } type OpenTool = AntigravityToolSnapshot & { ordinal: number; blockIndex: number; committed: boolean; openedAt: number } const TERMINAL_TOOL_STATUSES = new Set(['completed', 'failed', 'cancelled', 'canceled', 'error']) @@ -235,7 +235,7 @@ export class TurnAssembler { apply(update: Record): void { switch (update.sessionUpdate) { case 'user_message_chunk': - return this.appendText('user', contentText(update.content)) + return this.appendText('user', contentText(update.content), isRecord(update.content) && update.content.type === 'image') case 'agent_message_chunk': return this.appendText('assistant', contentText(update.content)) case 'agent_thought_chunk': @@ -251,8 +251,8 @@ export class TurnAssembler { } } - private appendText(kind: OpenSegment['kind'], text: string): void { - if (text.length === 0) return + private appendText(kind: OpenSegment['kind'], text: string, isImage = false): void { + if (text.length === 0 && !isImage) return if (this.segment?.kind !== kind) { this.closeSegment() const blockIndex = this.blockCounter++ @@ -264,6 +264,7 @@ export class TurnAssembler { } } const segment = this.segment! + if (isImage) segment.includesImage = true segment.text += text if (!this.live || !this.turnId || kind === 'user') return if (kind === 'assistant') { @@ -281,6 +282,9 @@ export class TurnAssembler { if (this.live && this.turnId && segment.kind !== 'user') { this.emit({ type: 'block_completed', turnId: this.turnId, blockId: segment.blockId, blockIndex: segment.blockIndex, kind: segment.kind === 'thought' ? 'reasoning' : 'text' }) } + // Images may be the entire user prompt. Preserve its turn and ordinal on reload + // without copying base64 into the UI journal or altering mixed prompts' typed text. + if (segment.includesImage && !segment.text.trim()) segment.text = '[Image attached]' if (segment.text.trim().length === 0) return this.sink.row({ type: 'antigravity-row', diff --git a/scripts/copy-packaged-resources.mjs b/scripts/copy-packaged-resources.mjs index 2e39ee233..35911eebc 100644 --- a/scripts/copy-packaged-resources.mjs +++ b/scripts/copy-packaged-resources.mjs @@ -36,6 +36,10 @@ const staticResources = [ from: 'packages/antigravity-acp-headless/src/mcpProxy.mjs', to: 'out/main/runtime/antigravity/mcpProxy.mjs', }, + { + from: 'src/providers/antigravity/runtime/nativeMcpRelay.cjs', + to: 'out/main/runtime/antigravity/nativeMcpRelay.cjs', + }, ] // WHY fileURLToPath and not `new URL(import.meta.url).pathname`: diff --git a/scripts/verify-build-output.mjs b/scripts/verify-build-output.mjs index 1bec0c65e..bd7de67f2 100644 --- a/scripts/verify-build-output.mjs +++ b/scripts/verify-build-output.mjs @@ -19,6 +19,7 @@ const requiredOutputs = [ // without it they start with no Agent Code tools, which only a live run // would notice. 'out/main/runtime/antigravity/mcpProxy.mjs', + 'out/main/runtime/antigravity/nativeMcpRelay.cjs', ] const missing = [] diff --git a/src/main/agentCodeConventions/targets.test.ts b/src/main/agentCodeConventions/targets.test.ts index 43dd4548b..b93f6c6a4 100644 --- a/src/main/agentCodeConventions/targets.test.ts +++ b/src/main/agentCodeConventions/targets.test.ts @@ -16,10 +16,12 @@ describe('Agent Code conventions provider targets', () => { // agent skills unsupported; targets resolution must tolerate it — grok // simply never contributes a target row. Hermes (#1482) is the second: // its skills live on the user's own server, not in a local root. - // Antigravity: its personal skill folder is undocumented (project - // .agents/skills is discovered instead). - expect(result.unsupportedProviders).toEqual(['antigravity', 'grok', 'hermes']) - expect(result.targets).toHaveLength(2) + expect(result.unsupportedProviders).toEqual(['grok', 'hermes']) + expect(result.targets).toHaveLength(3) + expect(result.targets.find(target => target.id === 'antigravity-personal-skills')).toMatchObject({ + providers: ['antigravity'], + skillsDirectory: join(homeDirectory, '.gemini', 'config', 'skills'), + }) expect(result.targets.find(target => target.id === 'claude-personal-skills')).toMatchObject({ providers: ['claude', 'opencode'], skillsDirectory: join(claudeConfig, 'skills'), diff --git a/src/main/agentSkills/inventory.system.test.ts b/src/main/agentSkills/inventory.system.test.ts index d1ff4c679..55d5c21ff 100644 --- a/src/main/agentSkills/inventory.system.test.ts +++ b/src/main/agentSkills/inventory.system.test.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path' import { execFileSync } from 'node:child_process' import { afterEach, describe, expect, it } from 'vitest' import type { AgentSkillRoot, AgentSkillsSnapshot } from '@shared/types/agentSkills.js' +import { discoverAntigravitySkillRoots } from '@providers/antigravity/runtime/skillDiscovery.js' import { collectInstalledAgentSkills } from './inventory.js' const temporary: string[] = [] @@ -26,6 +27,28 @@ afterEach(async () => { }) describe('installed skill inventory', () => { + it('lists Antigravity managed, legacy and workspace skills and respects the repository root', async () => { + const homeDirectory = await temp() + const project = join(homeDirectory, 'repo') + const cwd = join(project, 'sub') + await mkdir(join(project, '.git'), { recursive: true }) + const managed = join(homeDirectory, '.gemini/config/skills/agent-code-goal/SKILL.md') + await write(managed, skill('agent-code-goal')) + for (const [folder, name] of [ + [join(homeDirectory, '.gemini/antigravity-cli/skills'), 'cli-legacy'], + [join(homeDirectory, '.gemini/skills'), 'gemini-legacy'], + [join(cwd, '.agents/skills'), 'child-skill'], + [join(project, '.agents/skills'), 'project-skill'], + [join(homeDirectory, '.agents/skills'), 'outside-project'], + ] as const) await write(join(folder, name, 'SKILL.md'), skill(name)) + const discovery = await discoverAntigravitySkillRoots({ cwd, homeDirectory, environment: {} }) + const result = await collectInstalledAgentSkills(discovery, { paths: [managed], notices: [] }) + expect(result.skills.map(({ source, name }) => [source, name])).toEqual([ + ['agent-code', 'agent-code-goal'], ['project', 'child-skill'], ['personal', 'cli-legacy'], + ['personal', 'gemini-legacy'], ['project', 'project-skill'], + ]) + }) + it('labels managed deployments and returns metadata only, without modifying files', async () => { const base = await temp() const managedPath = join(base, 'personal', 'conventions', 'SKILL.md') diff --git a/src/main/agentTranscripts/AgentTranscriptReader.ts b/src/main/agentTranscripts/AgentTranscriptReader.ts index 1d146d375..d30a5915d 100644 --- a/src/main/agentTranscripts/AgentTranscriptReader.ts +++ b/src/main/agentTranscripts/AgentTranscriptReader.ts @@ -3,7 +3,7 @@ import { constants } from 'node:fs' import { parseOpencodeTranscriptFile, type OpencodeStore } from 'opencode-terminal-headless' import { readPiBranch } from 'pi-terminal-headless' -import { liveAntigravityRows, parseAntigravityTranscriptLocator } from '@providers/antigravity/runtime/antigravityHistory.js' +import { readOpenAntigravityRows, parseAntigravityTranscriptLocator } from '@providers/antigravity/runtime/antigravityHistory.js' import { streamJsonl } from '@shared/runtime/streamJsonl.js' import { codexExecScriptCalls, decodeDoubleQuotedLiteral, parseExecCommandArgument } from '@shared/codex/execScript.js' @@ -84,8 +84,8 @@ type TranscriptSource = | { kind: 'pi'; path: string } // An Antigravity conversation has no file Agent Code reads (agy's store is // private SQLite); its locator `antigravity://session/` names the rows - // the LIVE pane holds (antigravityHistory.ts). - | { kind: 'antigravity'; path: string; sessionId: string } + // from its live runtime or a confirmed native pane’s ACP replay. + | { kind: 'antigravity'; path: string; rows: readonly import('antigravity-acp-headless').AntigravityRow[] } type PreparedTranscript = { ok: true @@ -280,10 +280,13 @@ async function prepareTranscript( if (requestedProvider !== 'auto' && requestedProvider !== 'antigravity') { return { ok: false, error: 'unsupported_provider', message: `${path} is an Antigravity conversation, not a ${requestedProvider} transcript.` } } - if (!liveAntigravityRows(antigravitySessionId)) { - return { ok: false, error: 'file_not_readable', message: 'This Antigravity conversation is not open in Agent Code; open or resume the agent to read it.' } + try { + const rows = await readOpenAntigravityRows(antigravitySessionId) + if (!rows) return { ok: false, error: 'file_not_readable', message: 'This Antigravity conversation is not open in Agent Code; open or resume the agent to read it.' } + return { ok: true, source: { kind: 'antigravity', path, rows }, provider: 'antigravity' } + } catch { + return { ok: false, error: 'file_not_readable', message: 'Antigravity could not replay this open conversation.' } } - return { ok: true, source: { kind: 'antigravity', path, sessionId: antigravitySessionId }, provider: 'antigravity' } } try { @@ -338,7 +341,7 @@ async function* transcriptRecords(source: TranscriptSource): AsyncGenerator(source.path) return case 'antigravity': { - for (const row of liveAntigravityRows(source.sessionId) ?? []) yield row as unknown as JsonRecord + for (const row of source.rows) yield row as unknown as JsonRecord return } case 'pi': { diff --git a/src/main/conversations/sources/antigravity.ts b/src/main/conversations/sources/antigravity.ts index 44e587bea..3ef073c79 100644 --- a/src/main/conversations/sources/antigravity.ts +++ b/src/main/conversations/sources/antigravity.ts @@ -1,3 +1,4 @@ +import { assertAntigravityExternalControlExcluded } from '@providers/antigravity/runtime/externalControl.js' import { spawn } from 'node:child_process' import { listAntigravityConversations } from 'antigravity-acp-headless' @@ -48,6 +49,7 @@ export class AntigravityConversationSource implements ConversationSource { } let listings try { + await assertAntigravityExternalControlExcluded(process.cwd()) const child = spawn(this.binary(), ['acp'], { stdio: ['pipe', 'pipe', 'pipe'] }) child.stderr.on('data', () => {}) const failed = new Promise((_, reject) => child.once('error', reject)) diff --git a/src/main/goalLoop/GoalLoopService.test.ts b/src/main/goalLoop/GoalLoopService.test.ts index 59c6c47c5..34779577e 100644 --- a/src/main/goalLoop/GoalLoopService.test.ts +++ b/src/main/goalLoop/GoalLoopService.test.ts @@ -79,6 +79,16 @@ describe('GoalLoopService drain (#1341)', () => { } } + it('pauses a running loop when the provider interrupts its turn without a successful Stop', async () => { + const { svc, manager, deliver } = await service() + await svc.startLoop('s1', { goal: 'Finish the task', loopPrompt: 'Continue' }) + svc.observeProviderHook('s1', 'user-prompt-submit') + manager.emit('process-state', { sessionId: 's1', active: false, turnInterrupted: true }) + await svc.whenSettled() + expect(svc.snapshot().s1).toMatchObject({ phase: 'paused', pauseReason: 'interrupted' }) + expect(deliver).not.toHaveBeenCalled() + }) + it('dispose waits for an in-flight persist, then starts nothing new', async () => { const directory = await mkdtemp(join(tmpdir(), 'agent-code-goal-loop-')) directories.push(directory) diff --git a/src/main/goalLoop/GoalLoopService.ts b/src/main/goalLoop/GoalLoopService.ts index 8f2565e4a..368046968 100644 --- a/src/main/goalLoop/GoalLoopService.ts +++ b/src/main/goalLoop/GoalLoopService.ts @@ -345,7 +345,8 @@ export class GoalLoopService extends EventEmitter { // out the poll. It is an OPTIMISATION, never the mechanism: the poll re- // reads the level, so a provider that stops emitting edges (or never emits // this one) still resolves its hold. - const onProcessState = ({ sessionId, active }: { sessionId: string; active: boolean }) => { + const onProcessState = ({ sessionId, active, turnInterrupted }: { sessionId: string; active: boolean; turnInterrupted?: true }) => { + if (turnInterrupted) { this.interrupt(sessionId); return } if (active || !this.heldSince.has(sessionId)) return this.requestContinue(sessionId) } diff --git a/src/main/ipc/session.ts b/src/main/ipc/session.ts index eefd917a6..8bbfa300a 100644 --- a/src/main/ipc/session.ts +++ b/src/main/ipc/session.ts @@ -573,7 +573,10 @@ export function registerSessionIpc( } : undefined const result = await manager.deliverPromptToAgent(sessionId, prompt, imagePaths, record, deliveryId, - options?.requireEmptyNativeComposer === true ? { requireEmptyNativeComposer: true } : undefined) + options ? { + ...(options.requireEmptyNativeComposer === true ? { requireEmptyNativeComposer: true } : {}), + ...(options.inlineImages !== undefined ? { inlineImages: options.inlineImages } : {}), + } : undefined) // ORDER BARRIER (#1181): send the committed rows before the answer. // Claude's acceptance IS main seeing the prompt's JSONL line, and that // line is buffered in the session feed tap's JSONL burst and sent on the next diff --git a/src/main/sessionManager.ts b/src/main/sessionManager.ts index a9291a2ce..366743c60 100644 --- a/src/main/sessionManager.ts +++ b/src/main/sessionManager.ts @@ -117,7 +117,8 @@ import type { SessionSpawnOptions, SessionSpawnResult, } from '@preload/api/types.js' -import type { PromptDeliveryResult } from '@shared/types/providerConfig.js' +import type { InlinePromptImage, PromptDeliveryResult } from '@shared/types/providerConfig.js' +import { validInlinePromptImages } from '@shared/lib/inlinePromptImages.js' import { CodexReplacementLedger, type CodexReplacementReclaim, @@ -5123,6 +5124,7 @@ export class SessionManager extends EventEmitter { * else, and the brief still has to arrive. */ supersedesPendingPrompt?: boolean + inlineImages?: InlinePromptImage[] /** Stricter provider-owned admission for generated tasks such as browser * recovery. Never infer native draft safety in the renderer or overwrite * a draft to make this request fit. */ @@ -5200,6 +5202,15 @@ export class SessionManager extends EventEmitter { message: `Cannot deliver prompt: ${sessionId} is not a live agent session`, } } + if (options?.inlineImages !== undefined && (!entry.session.deliverPromptWithImages || !validInlinePromptImages(options.inlineImages))) { + return { + ok: false, stage: 'before-write', code: 'missing-capability', promptWritten: false, enterWritten: false, + retrySafe: true, disposition: 'retry-after-resolve', + message: entry.session.deliverPromptWithImages + ? 'Attach up to four PNG, JPEG, GIF, or WebP images of at most 5 MB each.' + : 'This session cannot receive embedded images from the composer.', + } + } this.promptDeliveriesInFlight.add(sessionId) record?.('reserved') let promptWritten = false @@ -5213,6 +5224,7 @@ export class SessionManager extends EventEmitter { this.monitorResponses.begin(sessionId, operationId, false) try { const delivery = await getMainProvider(entry.kind).deliverPrompt({ + ...(options?.inlineImages ? { inlineImages: options.inlineImages } : {}), session: entry.session, // WHY identity-check every delayed write: provider protocols await // absorption/readiness. A same-ID wake must never receive Enter from a diff --git a/src/main/userMcp/nativeServers.ts b/src/main/userMcp/nativeServers.ts index 4d02555ae..8de115341 100644 --- a/src/main/userMcp/nativeServers.ts +++ b/src/main/userMcp/nativeServers.ts @@ -1,3 +1,4 @@ +import { readAntigravityConfig } from '@providers/antigravity/runtime/externalControl.js' import { access, readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' @@ -69,8 +70,8 @@ export async function claudeManagedMcpPolicyPresent(paths = defaultNativeMcpPath } export async function readNativeMcpServers(paths = defaultNativeMcpPaths()): Promise { - const [claude, codex] = await Promise.all([readClaudeNative(paths), readCodexNative(paths)]) - return [...claude, ...codex] + const [claude, codex, antigravity] = await Promise.all([readClaudeNative(paths), readCodexNative(paths), readAntigravityNative(join(paths.home, '.gemini', 'config', 'mcp_config.json'), paths)]) + return [...claude, ...codex, ...antigravity] } /** @@ -163,6 +164,35 @@ async function readClaudeNative(paths: NativeMcpPaths): Promise { + let config: unknown + try { + config = await readAntigravityConfig(file) + } catch { return [] } + if (!isPlainObject(config) || !isPlainObject(config.mcpServers)) return [] + return Object.entries(config.mcpServers).map(([name, value]) => { + // Copy In moves a definition across providers. An OAuth client secret must never + // enter the plain settings document, and provider-only filters must not disappear. + const allowed = isPlainObject(value) && typeof value.command === 'string' + ? ['command', 'args', 'env', 'type'] : ['serverUrl', 'url', 'headers', 'type'] + const entry = isPlainObject(value) && Object.keys(value).every(key => allowed.includes(key)) ? { ...value } : null + if (entry && typeof entry.serverUrl === 'string') { + entry.type = 'http' + entry.url = entry.serverUrl + delete entry.serverUrl + } + return nativeServer('antigravity', name, displayPath(file, paths.home), entry) + }) +} + +export async function antigravityNativeServerNames(cwd: string, paths = defaultNativeMcpPaths()): Promise> { + const layers = await Promise.all([ + readAntigravityNative(join(paths.home, '.gemini', 'config', 'mcp_config.json'), paths), + readAntigravityNative(join(cwd, '.agents', 'mcp_config.json'), paths), + ]) + return new Set(layers.flat().map(server => server.name)) +} + async function readCodexNative(paths: NativeMcpPaths): Promise { const file = join(codexHome(paths), 'config.toml') const table = await readCodexMcpTable(file) @@ -215,7 +245,7 @@ function codexToMcpServersShape(raw: Record): Record | null, diff --git a/src/main/userMcp/service.test.ts b/src/main/userMcp/service.test.ts index 4f352f709..bef404069 100644 --- a/src/main/userMcp/service.test.ts +++ b/src/main/userMcp/service.test.ts @@ -70,6 +70,32 @@ afterEach(async () => { }) describe('UserMcpService storage', () => { + it('requires an Antigravity selection for legacy servers and reports unsupported transports', async () => { + const svc = service() + const saved = await svc.save(beeper()) + if (!saved.ok) throw new Error(saved.error) + const resolve = (overrides = {}) => svc.resolveForLaunch({ provider: 'antigravity', cwd: dir, overrides }) + expect((await resolve()).attachedIds).toEqual([]) + expect((await resolve({ [saved.id!]: true })).attachedIds).toEqual([saved.id]) + await svc.setProvider(saved.id!, 'antigravity', true) + expect((await resolve()).servers[0]?.secrets['beeper-authorization']).toBe(TOKEN) + await svc.save(beeper({ id: saved.id, entry: { type: 'sse', url: 'https://calendar.example/sse' }, secrets: {}, inputs: [] })) + expect((await resolve()).dropped[0]?.reason).toMatch(/Streamable HTTP/) + }) + + it('keeps agy-only auth and tool restrictions out of Copy In', async () => { + const configDir = join(dir, '.gemini', 'config') + await mkdir(configDir, { recursive: true }) + await writeFile(join(configDir, 'mcp_config.json'), '// locally configured servers\n' + JSON.stringify({ mcpServers: { + simple: { serverUrl: 'https://tracker.example/mcp' }, + restricted: { command: 'example', disabledTools: ['write'], oauth: { clientSecret: TOKEN } }, + } })) + const entries = await readNativeMcpServers({ home: dir, platform: 'darwin' }) + expect(entries.find(entry => entry.name === 'simple')).toMatchObject({ copyable: true, transport: 'http' }) + expect(entries.find(entry => entry.name === 'restricted')).toMatchObject({ copyable: false, entry: null }) + expect(JSON.stringify(entries)).not.toContain(TOKEN) + }) + it('persists the server without its secret, and the snapshot shows only a hint', async () => { const result = await service().save(beeper()) expect(result.ok).toBe(true) @@ -116,7 +142,7 @@ describe('UserMcpService storage', () => { const result = await service().copyNative('codex', 'sentry') if (!result.ok) throw new Error(result.error) const copy = result.snapshot.servers[0]! - expect(copy.providers).toEqual({ claude: true, codex: false }) + expect(copy.providers).toEqual({ claude: true, codex: false, antigravity: false }) expect(copy.secrets['sentry-authorization']).toEqual({ set: false }) }) }) diff --git a/src/main/userMcp/service.ts b/src/main/userMcp/service.ts index 811004c09..5027c63d3 100644 --- a/src/main/userMcp/service.ts +++ b/src/main/userMcp/service.ts @@ -40,6 +40,7 @@ import { import { claudeManagedMcpPolicyPresent, codexNativeServerNames, + antigravityNativeServerNames, codexShellPolicyStyle, readNativeMcpServers, } from './nativeServers.js' @@ -62,6 +63,7 @@ export type UserMcpServiceDeps = { /** Injectable for tests; production reads the real CLI config files. */ native?: { list(): Promise + antigravityNames?(cwd: string): Promise> codexNames(cwd: string): Promise> claudeManagedPolicy(): Promise codexShellPolicy?(cwd: string): Promise @@ -117,6 +119,7 @@ export class UserMcpService { this.secrets = new UserMcpSecretStore(join(deps.stateDir, 'mcp-secrets'), deps.codec) this.native = deps.native ?? { list: () => readNativeMcpServers(), + antigravityNames: cwd => antigravityNativeServerNames(cwd), codexNames: cwd => codexNativeServerNames(cwd), claudeManagedPolicy: () => claudeManagedMcpPolicyPresent(), codexShellPolicy: cwd => codexShellPolicyStyle(cwd), @@ -200,7 +203,7 @@ export class UserMcpService { id: existing?.id ?? randomUUID(), name: input.name.trim(), enabled, - providers: { claude: input.providers.claude === true, codex: input.providers.codex === true }, + providers: { claude: input.providers.claude === true, codex: input.providers.codex === true, antigravity: input.providers.antigravity === undefined ? existing?.providers.antigravity === true : input.providers.antigravity === true }, entry, inputs: coerceInputs(input.inputs), ...(pendingReview ? { pendingReview: true as const } : {}), @@ -485,7 +488,7 @@ export class UserMcpService { id: randomUUID(), name: native.name, enabled: true, - providers: { claude: provider !== 'claude', codex: provider !== 'codex' }, + providers: { claude: provider !== 'claude', codex: provider !== 'codex', antigravity: false }, entry: normalizeEntry(native.entry), inputs: native.inputs, } @@ -543,6 +546,7 @@ export class UserMcpService { const dropped: UserMcpDroppedServer[] = [] const candidates: ResolvedUserMcpServer[] = [] const claudeManaged = provider === 'claude' && await this.native.claudeManagedPolicy().catch(() => false) + const agyNames = provider === 'antigravity' ? await this.native.antigravityNames?.(params.cwd) : undefined const codexNames = provider === 'codex' ? await this.native.codexNames(params.cwd).catch(() => new Set()) : new Set() @@ -566,6 +570,10 @@ export class UserMcpService { dropped.push({ name: server.name, reason: 'Waiting for your review in Settings → MCP' }) continue } + if (agyNames?.has(server.name)) { + dropped.push({ name: server.name, reason: 'A server with this name is already configured in Antigravity' }) + continue + } if (codexNames.has(server.name)) { dropped.push({ name: server.name, reason: 'A server with this name is already in your Codex config.toml' }) continue @@ -597,7 +605,7 @@ export class UserMcpService { ? await (this.native.codexShellPolicy?.(params.cwd) ?? Promise.resolve({ style: 'filters' } as const)) .catch(() => ({ style: 'filters' } as const)) : undefined - const translatorDrops = provider === 'claude' + const translatorDrops = provider !== 'codex' ? claudeUserMcpEntries(candidates).dropped // The dry run sees the same inherited environment the Codex process will // (Codex inherits main's), so its "your environment already sets X" diff --git a/src/mcp/runtime/userMcpTools.test.ts b/src/mcp/runtime/userMcpTools.test.ts index cf6c6257c..ba460db7c 100644 --- a/src/mcp/runtime/userMcpTools.test.ts +++ b/src/mcp/runtime/userMcpTools.test.ts @@ -119,7 +119,7 @@ describe('mcp_servers built-in domain', () => { expect((await service.snapshot()).servers[0]!.secrets['beeper-access_token']!.set).toBe(true) await call('mcp_servers_update', { id, codex: false }) - expect((await service.snapshot()).servers[0]!.providers).toEqual({ claude: true, codex: false }) + expect((await service.snapshot()).servers[0]!.providers).toEqual({ claude: true, codex: false, antigravity: true }) await call('mcp_servers_remove', { id }) expect((await service.snapshot()).servers).toEqual([]) diff --git a/src/mcp/runtime/userMcpTools.ts b/src/mcp/runtime/userMcpTools.ts index 1b95d15d9..003a04a7f 100644 --- a/src/mcp/runtime/userMcpTools.ts +++ b/src/mcp/runtime/userMcpTools.ts @@ -33,7 +33,7 @@ export type UserMcpToolDependencies = { onUserMcpChangedByAgent?: (event: { sessionId: string; message: string }) => void } -export const MCP_SERVERS_INSTRUCTIONS = `MCP Servers lets you manage the user's own MCP servers in Agent Code (the servers Agent Code attaches to new Claude and Codex agents). Only add, change or remove servers when the user's current request asks for it; never add a server on your own initiative, and prefer the exact config the server's official documentation publishes. Add servers with mcp_servers_add using that config (a {"mcpServers": {...}} block, a VS Code {"servers": ...} block, or one entry). Every env and header value in it becomes an encrypted secret automatically; README placeholders such as YOUR_TOKEN_HERE stay unset. A server you add, or point at a different URL, command, arguments or environment, is saved switched OFF and waits for the user's review: tell the user to review it and turn it on in Settings → MCP. You cannot turn a server on. Set a secret with mcp_servers_set_secret only when the user has given you the value in this conversation; otherwise tell the user to set it in Settings → MCP. Never repeat a secret value back. Changes apply to new agents and to existing agents when they reload — including you: you will not get a server's tools until the user reloads you. OAuth servers sign in through the CLIs (codex mcp login, or /mcp in Claude); say so instead of looking for a token. Report exactly what you changed.` +export const MCP_SERVERS_INSTRUCTIONS = `MCP Servers lets you manage the user's own MCP servers in Agent Code (the servers Agent Code attaches to new Claude, Codex and Antigravity agents). Only add, change or remove servers when the user's current request asks for it; never add a server on your own initiative, and prefer the exact config the server's official documentation publishes. Add servers with mcp_servers_add using that config (a {"mcpServers": {...}} block, a VS Code {"servers": ...} block, or one entry). Every env and header value in it becomes an encrypted secret automatically; README placeholders such as YOUR_TOKEN_HERE stay unset. A server you add, or point at a different URL, command, arguments or environment, is saved switched OFF and waits for the user's review: tell the user to review it and turn it on in Settings → MCP. You cannot turn a server on. Set a secret with mcp_servers_set_secret only when the user has given you the value in this conversation; otherwise tell the user to set it in Settings → MCP. Never repeat a secret value back. Changes apply to new agents and to existing agents when they reload — including you: you will not get a server's tools until the user reloads you. OAuth servers sign in through the CLIs (codex mcp login, or /mcp in Claude or Antigravity); say so instead of looking for a token. Report exactly what you changed.` export function registerUserMcpTools( server: McpServer, @@ -73,10 +73,11 @@ export function registerUserMcpTools( config: z.string().min(2).max(64 * 1024).describe('The JSON config snippet.'), name: z.string().min(1).max(64).optional().describe('Server name, used only when config is a single bare entry.'), claude: z.boolean().optional().describe('Attach to new Claude agents. Defaults to true when supported.'), + antigravity: z.boolean().optional(), codex: z.boolean().optional().describe('Attach to new Codex agents. Defaults to true when supported (not for SSE).'), }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, - }, async ({ config, name, claude, codex }) => { + }, async ({ config, name, claude, codex, antigravity }) => { try { const imported = service().importConfig(config, name) if (!imported.ok) return { ...toolText({ ok: false, message: imported.error }), isError: true } @@ -94,6 +95,7 @@ export function registerUserMcpTools( providers: { claude: support.claude.ok && (claude ?? true), codex: support.codex.ok && (codex ?? true), + antigravity: support.antigravity.ok && (antigravity ?? true), }, entry: candidate.entry, inputs: candidate.inputs, @@ -129,10 +131,11 @@ export function registerUserMcpTools( entry: z.record(z.string(), z.unknown()).optional(), enabled: z.literal(false).optional().describe('Pass false to switch the server off. Only the user can switch it on.'), claude: z.boolean().optional(), + antigravity: z.boolean().optional(), codex: z.boolean().optional(), }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, - }, async ({ id, name, entry, enabled, claude, codex }) => { + }, async ({ id, name, entry, enabled, claude, codex, antigravity }) => { try { const current = (await service().snapshot()).servers.find(candidate => candidate.id === id) if (!current) return { ...toolText({ ok: false, message: `No MCP server with id ${id}.` }), isError: true } @@ -144,7 +147,7 @@ export function registerUserMcpTools( id, name: name ?? current.name, enabled: enabled ?? current.enabled, - providers: { claude: claude ?? current.providers.claude, codex: codex ?? current.providers.codex }, + providers: { claude: claude ?? current.providers.claude, codex: codex ?? current.providers.codex, antigravity: antigravity ?? current.providers.antigravity }, entry: nextEntry, inputs: referenced.map(inputId => current.inputs.find(input => input.id === inputId) ?? { id: inputId, description: 'Secret' }), }, 'agent') diff --git a/src/providers/antigravity/renderer/composerSubmit.ts b/src/providers/antigravity/renderer/composerSubmit.ts index 17514c739..920cb3ec7 100644 --- a/src/providers/antigravity/renderer/composerSubmit.ts +++ b/src/providers/antigravity/renderer/composerSubmit.ts @@ -12,7 +12,9 @@ import type { ComposerSubmitIo } from '@providers/registry.renderer.capabilities import type { PromptAcceptance, PromptDeliveryResult } from '@shared/types/providerConfig' export async function antigravityComposerSubmit(io: ComposerSubmitIo): Promise { - const result = await io.deliverPrompt(io.input) + const result = io.draftImages.length + ? await io.deliverPrompt(io.input, undefined, { inlineImages: io.draftImages.map(({ mediaType, base64Data }) => ({ mediaType, base64Data })) }) + : await io.deliverPrompt(io.input) if (!result.ok) { const error = new Error(result.message) as Error & { promptDeliveryResult: PromptDeliveryResult } error.promptDeliveryResult = result diff --git a/src/providers/antigravity/runtime/antigravityHistory.ts b/src/providers/antigravity/runtime/antigravityHistory.ts index 93d7e5006..0bea830d3 100644 --- a/src/providers/antigravity/runtime/antigravityHistory.ts +++ b/src/providers/antigravity/runtime/antigravityHistory.ts @@ -1,3 +1,4 @@ +import { assertAntigravityExternalControlExcluded } from './externalControl.js' // Antigravity history pages, and the `antigravity://session/` locator. // // WHY the live session's rows first: a renderer reload (and the phone's @@ -19,32 +20,55 @@ import { readAntigravityConversation, type AntigravityRow } from 'antigravity-ac import type { ProviderHistoryChunk, ProviderHistoryRequest } from '@shared/types/providerConfig.js' -export type AntigravityHistorySource = { - rows: () => ReadonlyArray -} +export type AntigravityHistorySource = + | { rows: () => ReadonlyArray } + | { replay: () => Promise> } -const live = new Map() +// Native and rendered panes (and old and new processes during handoff) can +// temporarily own the same conversation. Removing one must preserve the others. +const live = new Map>() export function registerAntigravityHistory(sessionId: string, source: AntigravityHistorySource): () => void { - live.set(sessionId, source) + const sources = live.get(sessionId) ?? new Set() + sources.add(source) + live.set(sessionId, sources) return () => { - if (live.get(sessionId) === source) live.delete(sessionId) + sources.delete(source) + if (!sources.size && live.get(sessionId) === sources) live.delete(sessionId) } } export function liveAntigravityRows(sessionId: string): ReadonlyArray | null { - return live.get(sessionId)?.rows() ?? null + for (const source of [...(live.get(sessionId) ?? [])].reverse()) { + if ('rows' in source) return source.rows() + } + return null +} + +/** A transcript locator is not permission to spawn a process in an arbitrary + * directory. Only the registered runtime supplies a native replay. Require its + * registration to survive the read, including a native /new during replay. */ +export async function readOpenAntigravityRows(sessionId: string): Promise | null> { + const rows = liveAntigravityRows(sessionId) + if (rows) return rows + const source = [...(live.get(sessionId) ?? [])].pop() + if (!source || !('replay' in source)) return null + const replay = await source.replay() + return live.get(sessionId)?.has(source) ? replay : null } export type AntigravityReplayDeps = { binary?: string - spawn?: (binary: string, args: string[], options: { cwd: string }) => ChildProcessWithoutNullStreams + env?: NodeJS.ProcessEnv + signal?: AbortSignal + spawn?: (binary: string, args: string[], options: { cwd: string; env?: NodeJS.ProcessEnv; signal?: AbortSignal }) => ChildProcessWithoutNullStreams } /** Replay a conversation through a short-lived `agy acp` (no model call). */ export async function replayAntigravityConversation(sessionId: string, cwd: string, deps: AntigravityReplayDeps = {}): Promise { + await assertAntigravityExternalControlExcluded(cwd, deps.env) const binary = deps.binary ?? 'agy' - const child = (deps.spawn ?? ((bin, args, options) => spawn(bin, args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] })))(binary, ['acp'], { cwd }) + const child = (deps.spawn ?? ((bin, args, options) => spawn(bin, args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] })))(binary, ['acp'], { cwd, ...(deps.env ? { env: deps.env } : {}), ...(deps.signal ? { signal: deps.signal } : {}) }) child.stderr.on('data', () => {}) // WHY an 'error' listener: Node reports a spawn failure (agy not installed, // a stale tool path, EACCES) as an 'error' EVENT on the child, and never @@ -68,14 +92,13 @@ export async function replayAntigravityConversation(sessionId: string, cwd: stri } export async function loadAntigravityHistoryChunk(request: ProviderHistoryRequest, deps: AntigravityReplayDeps = {}): Promise { - let rows = liveAntigravityRows(request.providerSessionId) - if (!rows) { - try { - rows = await replayAntigravityConversation(request.providerSessionId, request.cwd, deps) - } catch (error) { - // Electron keeps Error.message, not custom properties: the category rides in the message. - throw Object.assign(new Error(`unreadable: Antigravity history unavailable: ${(error as Error).message}`), { code: 'unreadable' }) - } + let rows: readonly AntigravityRow[] + try { + rows = await readOpenAntigravityRows(request.providerSessionId) + ?? await replayAntigravityConversation(request.providerSessionId, request.cwd, deps) + } catch (error) { + // Electron keeps Error.message, not custom properties: the category rides in the message. + throw Object.assign(new Error(`unreadable: Antigravity history unavailable: ${(error as Error).message}`), { code: 'unreadable' }) } // Paging by the mapper's marker (= the row key): everything strictly older. const end = request.beforeMarker ? rows.findIndex(row => row.key === request.beforeMarker) : rows.length diff --git a/src/providers/antigravity/runtime/antigravitySession.system.test.ts b/src/providers/antigravity/runtime/antigravitySession.system.test.ts index 003ac683f..1c464e9f8 100644 --- a/src/providers/antigravity/runtime/antigravitySession.system.test.ts +++ b/src/providers/antigravity/runtime/antigravitySession.system.test.ts @@ -148,6 +148,38 @@ const semanticTypes = (events: Event[]) => named(events, 'semantic-event').map(e const lastConditions = (events: Event[]) => named(events, 'conditions').at(-1)?.args[0] as { conditions: Record } | undefined const waitFor = (check: () => T) => vi.waitFor(check, { timeout: 2000, interval: 5 }) +// agy 1.5.18's initialize response advertises promptCapabilities.image. Exercise +// the composer delivery boundary through the real ACP writer and its live rows. +it.each(['', 'Describe this'])('sends embedded clipboard bytes to agy with caption %j', async caption => { + const { session, agy, events } = await launch((frame, child) => { + if (frame.method === 'initialize') return child.reply(frame, { ...INIT, agentCapabilities: { promptCapabilities: { image: true } } }) + if (frame.method === 'session/prompt') return child.reply(frame, { stopReason: 'end_turn' }) + return agyScript()(frame, child) + }) + const result = await deliverAntigravityPrompt({ + session, sessionId: 'pane', prompt: caption, write: () => false, + inlineImages: [{ base64Data: 'iVBORw0KGgo=', mediaType: 'image/png' }], + }) + expect(result.ok).toBe(true) + expect(agy().sent.find(f => f.method === 'session/prompt')?.params.prompt).toEqual([ + ...(caption ? [{ type: 'text', text: caption }] : []), + { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }, + ]) + expect(events.find(e => e.name === 'jsonl-entry' && (e.args[0] as { role?: string }).role === 'user')?.args[0]).toMatchObject({ + text: caption || '[Image attached]', + }) +}) + +it('restores image-only and captioned image prompts without retaining image bytes in rows', async () => { + const image = { sessionUpdate: 'user_message_chunk', content: { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' } } + const { events } = await launch(agyScript({ replays: { 'conv-images': [ + image, text('agent_message_chunk', 'one'), image, text('user_message_chunk', 'caption'), + ] } }), { resumeSessionId: 'conv-images' }, ['conv-images']) + const prompts = events.filter(e => e.name === 'jsonl-entry' && (e.args[0] as { role?: string }).role === 'user').map(e => e.args[0] as { text: string }) + expect(prompts.map(row => row.text)).toEqual(['[Image attached]', 'caption']) + expect(JSON.stringify(prompts)).not.toContain('iVBORw0KGgo=') +}) + describe('AntigravitySession start', () => { it('a fresh start spawns `agy acp`, creates a session, and binds identity before reporting ready', async () => { const { session, events, spawned, conversationExists, agy } = await launch(agyScript(), { @@ -255,6 +287,7 @@ describe('AntigravitySession start', () => { it('a spawn failure is reported as spawn-failed and fails start', async () => { const { session, events, agy } = create(() => {}) const starting = session.start() + await vi.waitFor(() => expect(agy()).toBeDefined()) agy().emit('error', Object.assign(new Error('spawn agy ENOENT'), { code: 'ENOENT' })) await expect(starting).rejects.toThrow(/agy acp did not start/) const [first] = named(events, 'jsonl-error') @@ -265,6 +298,22 @@ describe('AntigravitySession start', () => { }) describe('AntigravitySession built-in MCP servers', () => { + it.each([false, true])('attaches managed HTTP and stdio servers over the ACP pipe on resume=%s', async resume => { + const { agy, spawned } = await launch(agyScript(), { + resumeSessionId: resume ? 'saved' : undefined, + userMcpServers: [ + { id: 'a', name: 'tracker', entry: { type: 'http', url: 'https://tracker.example/mcp', headers: { Authorization: 'Bearer ${input:key}' } }, secrets: { key: 'test-secret' } }, + { id: 'b', name: 'calendar', entry: { command: '/bin/example', args: ['serve'], env: { ACCOUNT: '${input:id}' } }, secrets: { id: 'test-account' } }, + ], + }, ['saved']) + const request = agy().sent.find(frame => frame.method === (resume ? 'session/load' : 'session/new')) + expect(request!.params.mcpServers).toEqual([ + { type: 'http', name: 'tracker', url: 'https://tracker.example/mcp', headers: [{ name: 'Authorization', value: 'Bearer test-secret' }] }, + { type: 'stdio', name: 'calendar', command: '/bin/example', args: ['serve'], env: [{ name: 'ACCOUNT', value: 'test-account' }] }, + ]) + expect(JSON.stringify(spawned)).not.toContain('test-secret') + }) + it('become ONE stdio proxy server agy starts, with headers in its env and the bearer never in argv', async () => { const bearer = 'bearer-secret-7f3a' const { agy, spawned } = await launch(agyScript(), { diff --git a/src/providers/antigravity/runtime/antigravitySession.ts b/src/providers/antigravity/runtime/antigravitySession.ts index 67b85a993..c47f9082a 100644 --- a/src/providers/antigravity/runtime/antigravitySession.ts +++ b/src/providers/antigravity/runtime/antigravitySession.ts @@ -1,3 +1,6 @@ +import { assertAntigravityExternalControlExcluded } from './externalControl.js' +import { resolveAntigravityUserMcpEntries } from './userMcpEntries.js' +import { openAgyTurnHooks } from './turnHooks.js' import { EventEmitter } from 'node:events' import { constants as osConstants } from 'node:os' import { spawn as spawnProcess, type ChildProcessWithoutNullStreams } from 'node:child_process' @@ -8,6 +11,7 @@ import { } from 'antigravity-acp-headless' import type { AgentSession, AgentSessionEvents, SessionOptions } from '@shared/types/session.js' +import type { InlinePromptImage } from '@shared/types/providerConfig.js' import type { ConditionCustomAction } from '@shared/types/providerConditions.js' import { asRecord } from '@shared/lib/asRecord.js' import { registerAntigravityHistory, antigravityTranscriptLocator } from '@providers/antigravity/runtime/antigravityHistory.js' @@ -53,16 +57,16 @@ export interface AntigravitySession { * conversation agy no longer holds (deleted) starts a NEW conversation and * says so through provider-session-changed rather than failing the pane. * - * dangerousMode → session mode... is NOT mapped: ACP has no auto-approve - * switch in agy 1.5.15's session/new, and silently approving every permission - * request client-side would hide from the user exactly what dangerous mode - * is meant to skip — the Allow/Deny cards stay, each one click. + * The app's Dangerous Mode preference promises automatic approval for Claude + * and Codex. Antigravity keeps its own approval policy and ACP permission cards. */ export class AntigravitySession extends EventEmitter implements AgentSession { private child: ChildProcessWithoutNullStreams | null = null + private starting = false private acp: AntigravityAcpSession | null = null private exited = false private stopping = false + private turnHooks: Awaited> = null private providerSessionId: string | null = null private unregisterHistory: (() => void) | null = null private historyGeneration = 0 @@ -84,6 +88,7 @@ export class AntigravitySession extends EventEmitter implements AgentSession { private readonly extraEnv: Record private readonly resumeSessionId: string | null private readonly builtInMcpServers: NonNullable + private readonly userMcpServers: NonNullable private readonly deps: Required constructor(options: SessionOptions, deps: AntigravitySessionDeps = {}) { @@ -93,6 +98,7 @@ export class AntigravitySession extends EventEmitter implements AgentSession { this.extraEnv = options.env ?? {} this.resumeSessionId = options.resumeSessionId ?? null this.builtInMcpServers = options.builtInMcpServers ?? [] + this.userMcpServers = options.userMcpServers ?? [] this.deps = { spawn: deps.spawn ?? ((binary, args, spawnOptions) => spawnProcess(binary, args, { ...spawnOptions, stdio: ['pipe', 'pipe', 'pipe'] })), mcpProxyScript: deps.mcpProxyScript ?? resolveAntigravityMcpProxyScript(), @@ -102,7 +108,12 @@ export class AntigravitySession extends EventEmitter implements AgentSession { } async start(): Promise { - if (this.child) throw new Error('AntigravitySession already started') + if (this.child || this.starting) throw new Error('AntigravitySession already started') + this.starting = true + try { await this.startSession() } finally { this.starting = false } + } + + private async startSession(): Promise { this.exited = false this.emit('input-readiness', { ready: false, reason: 'starting' }) @@ -113,7 +124,22 @@ export class AntigravitySession extends EventEmitter implements AgentSession { else env[key] = value } - const child = this.deps.spawn(this.binary, ['acp'], { cwd: this.cwd, env }) + await assertAntigravityExternalControlExcluded(this.cwd, env, [...this.builtInMcpServers, ...this.userMcpServers]) + if (this.builtInMcpServers.some(server => server.tldrHooks)) { + this.turnHooks = await openAgyTurnHooks(this.builtInMcpServers, () => this.providerSessionId, (active, turnInterrupted) => { + // ACP normally owns process state. A reporting interruption also needs to + // pause the loop, even if the local HTTP reporting service just went away. + if (turnInterrupted) this.emit('process-state', { active, turnInterrupted }) + }) + } + if (this.stopping) { await this.closeTurnHooks(); return } + let child: ChildProcessWithoutNullStreams + try { + child = this.deps.spawn(this.binary, this.turnHooks ? ['acp', '--add-dir', this.turnHooks.workspace] : ['acp'], { cwd: this.cwd, env }) + } catch (error) { + await this.closeTurnHooks() + throw error + } this.child = child // agy logs to stderr; drained so a chatty run can never fill the pipe and // stall the agent. @@ -170,7 +196,15 @@ export class AntigravitySession extends EventEmitter implements AgentSession { * server's env list, never in argv. */ private mcpServers(): AntigravityMcpServer[] { - if (this.builtInMcpServers.length === 0) return [] + // agy 1.5.18 initializes and lists tools on HTTP ACP entries even though its + // initialize response omits mcpCapabilities.http. Preserve the legacy built-in + // bridge for older installations; user servers keep their own names and transport. + const pairs = (values: Record) => Object.entries(values).map(([name, value]) => ({ name, value })) + const managed = resolveAntigravityUserMcpEntries(this.userMcpServers).map(({ name, config }): AntigravityMcpServer => + 'serverUrl' in config + ? { type: 'http', name, url: config.serverUrl, headers: pairs(config.headers) } + : { type: 'stdio', name, command: config.command, args: config.args, env: pairs(config.env) }) + if (this.builtInMcpServers.length === 0) return managed const env: Array<{ name: string; value: string }> = [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }] const specs = this.builtInMcpServers.map((server, serverIndex) => { const headers = { ...server.headers, ...(server.bearerToken === undefined ? {} : { Authorization: `Bearer ${server.bearerToken}` }) } @@ -183,7 +217,7 @@ export class AntigravitySession extends EventEmitter implements AgentSession { return { name: server.name, url: server.url, headerEnv } }) env.push({ name: 'AGENT_CODE_ACP_MCP_SERVERS', value: JSON.stringify(specs) }) - return [{ type: 'stdio', name: this.builtInMcpServers[0]!.name, command: this.deps.scriptRunner, args: [this.deps.mcpProxyScript], env }] + return [{ type: 'stdio', name: this.builtInMcpServers[0]!.name, command: this.deps.scriptRunner, args: [this.deps.mcpProxyScript], env }, ...managed] } private bindIdentity(sessionId: string, changedReason: string | null): void { @@ -254,11 +288,16 @@ export class AntigravitySession extends EventEmitter implements AgentSession { * is pending, so every other delivery to the pane would fail with * delivery-in-flight in the meantime. */ - async deliverPromptText(text: string): Promise<{ turnStarted: boolean }> { + async deliverPromptWithImages(text: string, images: readonly InlinePromptImage[]): Promise<{ turnStarted: boolean }> { + if (!this.acp?.acceptsImages) throw new AntigravityNotReadyError('The installed agy session does not accept image input.') + return this.deliverPromptText(text, images) + } + + async deliverPromptText(text: string, images: readonly InlinePromptImage[] = []): Promise<{ turnStarted: boolean }> { const acp = this.acp if (!acp || this.exited || !this.providerSessionId) throw new AntigravityNotReadyError('agy is not running') const queued = acp.isTurnActive() - const { accepted, finished } = acp.prompt(text) + const { accepted, finished } = acp.prompt(text, images.map(({ mediaType, base64Data }) => ({ type: 'image', mimeType: mediaType, data: base64Data }))) // The turn's outcome arrives as semantic events. A QUEUED prompt that never // ran because agy stopped first is said once, so it is not lost silently. finished.catch(error => { @@ -308,6 +347,7 @@ export class AntigravitySession extends EventEmitter implements AgentSession { private onExit(code: number | null, signal: NodeJS.Signals | null): void { if (this.exited) return this.exited = true + void this.closeTurnHooks() // An exited pane no longer owns the conversation: the user may continue // it in agy's own TUI (`agy --conversation`), and history / catalog reads // must then replay it fresh instead of serving these stale rows. @@ -324,8 +364,15 @@ export class AntigravitySession extends EventEmitter implements AgentSession { this.emit('exit', { exitCode: code ?? 1, ...(signalNumber !== undefined ? { signal: signalNumber } : {}) }) } + private async closeTurnHooks(): Promise { + const hooks = this.turnHooks + this.turnHooks = null + await hooks?.close() + } + async stop(): Promise { this.stopping = true + await this.closeTurnHooks() this.unregisterHistory?.() this.unregisterHistory = null const acp = this.acp diff --git a/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts b/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts index 9e6ff2bbb..6533a53d1 100644 --- a/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts +++ b/src/providers/antigravity/runtime/antigravityTerminalSession.system.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { inspectAgentTranscriptFile, readAgentTranscriptFile, searchAgentTranscriptFile } from '@main/agentTranscripts/AgentTranscriptReader.js' import { AntigravityTerminalSession } from './antigravityTerminalSession.js' // Exercise the two real process boundaries: a short-lived ACP stdio process allocates an @@ -16,6 +17,12 @@ if (args[0] === 'acp') { require('node:readline').createInterface({input:process.stdin}).on('line', line => { const req = JSON.parse(line) if (process.env.AGY_TEST_AUTH === 'hang') return + if (req.method === 'session/load') { + if (req.params.cwd !== process.env.GEMINI_CLI_HOME || require('node:fs').realpathSync(req.params.cwd) !== require('node:fs').realpathSync(process.cwd())) process.exit(5) + for (const [id, text] of [['foreign-id', 'unrelated'], [req.params.sessionId, 'verified native transcript']]) { + console.log(JSON.stringify({jsonrpc:'2.0', method:'session/update', params:{sessionId:id, update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text}}}})) + } + } const err = req.method === 'session/new' && process.env.AGY_TEST_AUTH === 'missing' console.log(JSON.stringify({jsonrpc:'2.0', id:req.id, ...(err ? {error:{code:-32000,message:'Authentication required'}} @@ -49,6 +56,10 @@ if (args[0] === 'acp') { } process.stdin.setRawMode(true) process.stdout.write('TUI:' + JSON.stringify(args.slice(2)) + ':' + process.stdout.columns + 'x' + process.stdout.rows) + // Reconstruct the empty prompt and footer observed on agy 1.5.18. A banner + // alone is not evidence that automated input can target a conversation. + const rule = '─'.repeat(process.stdout.columns) + process.stdout.write('\r\n\x1b[?2004h' + rule + '\r\n>\r\n' + rule + '\r\n? for shortcuts\x1b[2A\r\x1b[2C') process.stdout.on('resize', () => process.stdout.write('SIZE:' + process.stdout.columns + 'x' + process.stdout.rows)) process.stdin.on('data', d => { if (d.toString() === 'q') return process.exit(0) @@ -117,6 +128,7 @@ it('does not start a terminal when the pane closes during identity allocation', const allocate = vi.fn(() => new Promise(resolve => { finish = resolve })) session = new AntigravityTerminalSession({ binary, cwd }, { allocate }) const starting = session.start() + await vi.waitFor(() => expect(allocate).toHaveBeenCalledOnce()) await session.stop() finish('unused') await starting @@ -162,7 +174,7 @@ it('waits for the exact native selection before publishing identity, readiness o await writeFile(join(cwd, 'confirm-resume'), '') await completion expect(start).toHaveBeenCalledOnce() - expect(ready).toHaveBeenCalledOnce() + await vi.waitFor(() => expect(ready).toHaveBeenCalledOnce()) expect(candidate.getProviderSessionId()).toBe(requestedId) }) @@ -186,3 +198,23 @@ it.each([ const fifo = await readFile(join(cwd, 'launch-pipe-path'), 'utf8') await expect(access(fifo)).rejects.toMatchObject({ code: 'ENOENT' }) }) + +it('allows MCP read, search and inspect through this native pane’s confirmed identity and revokes access on stop', async () => { + const candidate = await prepareExplicit('hold', 3000) + const path = 'antigravity://session/' + requestedId + const starting = candidate.start() + await expect.poll(() => access(join(cwd, 'launch-pipe-path')).then(() => true, () => false)).toBe(true) + expect(await inspectAgentTranscriptFile({ path })).toMatchObject({ ok: false, error: 'file_not_readable' }) + await writeFile(join(cwd, 'confirm-resume'), '') + await starting + const [read, search, stats] = await Promise.all([ + readAgentTranscriptFile({ path, projection: 'timeline' }), + searchAgentTranscriptFile({ path, query: 'verified native' }), + inspectAgentTranscriptFile({ path }), + ]) + expect(read, JSON.stringify(read)).toMatchObject({ ok: true, items: [expect.objectContaining({ text: 'verified native transcript' })] }) + expect(search).toMatchObject({ ok: true, matches: [expect.anything()] }) + expect(stats).toMatchObject({ ok: true, provider: 'antigravity' }) + await candidate.stop() + expect(await inspectAgentTranscriptFile({ path })).toMatchObject({ ok: false, error: 'file_not_readable' }) +}) diff --git a/src/providers/antigravity/runtime/antigravityTerminalSession.ts b/src/providers/antigravity/runtime/antigravityTerminalSession.ts index 79133f3ec..47cb61069 100644 --- a/src/providers/antigravity/runtime/antigravityTerminalSession.ts +++ b/src/providers/antigravity/runtime/antigravityTerminalSession.ts @@ -1,11 +1,15 @@ +import { assertAntigravityExternalControlExcluded } from './externalControl.js' import { spawn } from 'node:child_process' +import { openAgyTurnHooks } from './turnHooks.js' import { EventEmitter } from 'node:events' import { AntigravityAcpSession, antigravityConversationExists } from 'antigravity-acp-headless' import { TerminalSession } from '@shared/runtime/terminalSession.js' -import type { AgentSession, SessionOptions } from '@shared/types/session.js' +import type { AgentInputReadiness, AgentSession, PromptReadinessOutcome, SessionOptions } from '@shared/types/session.js' +import { openAntigravityNativeMcp } from './nativeMcp.js' import { openAntigravityIdentityPipe } from './terminalIdentity.js' -import { antigravityTranscriptLocator } from './antigravityHistory.js' +import { AntigravityTerminalComposer } from './terminalComposer.js' +import { antigravityTranscriptLocator, registerAntigravityHistory, replayAntigravityConversation } from './antigravityHistory.js' /** Allocate an exact conversation before launching the TUI so reopening two panes in one directory * cannot attach either pane to the other's most recent conversation. No prompt is submitted. */ @@ -38,10 +42,17 @@ type TerminalDeps = { export class AntigravityTerminalSession extends EventEmitter implements AgentSession { private readonly startup = new AbortController() private terminal: TerminalSession | null = null + private nativeMcp?: Awaited> private observer: ReturnType | null = null private started = false private exited = false + private turnHooks: Awaited> = null private providerSessionId: string | null = null + readonly nativeComposer: AntigravityTerminalComposer + private activeConversation: string | null = null + private history: { id: string; unregister: () => void } | undefined + private attached = false + private lastReadiness: AgentInputReadiness['reason'] = 'starting' private cols: number private rows: number @@ -49,6 +60,7 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes super() this.cols = options.cols ?? 120 this.rows = options.rows ?? 40 + this.nativeComposer = new AntigravityTerminalComposer(this.cols, this.rows, () => this.publishReadiness()) } async start(): Promise { @@ -56,6 +68,12 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes this.started = true this.emit('input-readiness', { ready: false, reason: 'starting' }) const binary = this.options.binary ?? 'agy' + const policyEnv = { ...process.env, ...this.options.env } + const paneServers = [...this.options.builtInMcpServers ?? [], ...this.options.userMcpServers ?? []] + // Preallocation starts its own agy before the native PTY. In particular, + // its recoverable sign-in fallback must never swallow a policy conflict. + await assertAntigravityExternalControlExcluded(this.options.cwd, policyEnv, paneServers) + if (this.startup.signal.aborted) return const requested = this.options.resumeSessionId if (requested) { // agy silently ignores an unknown --conversation and opens a blank prompt. During a mode @@ -86,48 +104,61 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes const failResume = (message: string) => { if (awaitingResume) reject(new Error(message)) } - this.observer = openAntigravityIdentityPipe({ - active: next => { - if (this.startup.signal.aborted || this.exited) return - if (awaitingResume) { - if (next === requested) confirm() - else failResume('Antigravity opened a different conversation.') - return - } - if (this.providerSessionId === next) return - this.providerSessionId = next - const transcriptFile = antigravityTranscriptLocator(next) - this.emit('provider-session-changed', { providerSessionId: next, transcriptFile, reason: 'antigravity-native-conversation' }) - this.emit('jsonl-entry', { type: 'antigravity-identity', sessionId: next }, transcriptFile) - }, - missing: missing => { - if (missing === requested) failResume('The requested Antigravity conversation is unavailable.') - }, - error: () => { - failResume('Could not verify the requested Antigravity conversation.') - this.emit('transcript-diagnostic', { kind: 'antigravity-native-identity-unavailable' }) - }, - }) + await assertAntigravityExternalControlExcluded(this.options.cwd, policyEnv, paneServers) + if (this.startup.signal.aborted) return + this.nativeMcp = await openAntigravityNativeMcp(this.options) + if (this.startup.signal.aborted) { this.closeObserver(); return } + try { + this.turnHooks = await openAgyTurnHooks(this.options.builtInMcpServers ?? [], () => this.activeConversation, + (active, turnInterrupted) => this.emit('process-state', { active, turnInterrupted })) + if (this.startup.signal.aborted) { this.closeObserver(); return } + this.observer = openAntigravityIdentityPipe({ + active: next => { + if (this.startup.signal.aborted || this.exited) return + this.activeConversation = next + if (awaitingResume) { + if (next === requested) confirm() + else failResume('Antigravity opened a different conversation.') + return + } + if (this.providerSessionId === next) { this.publishReadiness(); return } + this.providerSessionId = next + this.publishReadiness() + const transcriptFile = antigravityTranscriptLocator(next) + this.emit('provider-session-changed', { providerSessionId: next, transcriptFile, reason: 'antigravity-native-conversation' }) + this.emit('jsonl-entry', { type: 'antigravity-identity', sessionId: next }, transcriptFile) + }, + missing: missing => { + if (missing === requested) failResume('The requested Antigravity conversation is unavailable.') + }, + error: () => { + failResume('Could not verify the requested Antigravity conversation.') + this.emit('transcript-diagnostic', { kind: 'antigravity-native-identity-unavailable' }) + }, + }) + } catch (error) { + this.closeObserver() + throw error + } const args = ['--log-file', this.observer.path] if (id) args.push('--conversation', id) + if (this.nativeMcp) args.push('--add-dir', this.nativeMcp.directory) + if (this.turnHooks) args.push('--add-dir', this.turnHooks.workspace) const options = { shell: binary, args, cwd: this.options.cwd, cols: this.cols, rows: this.rows, env: this.options.env, } const terminal = new TerminalSession(options) this.terminal = terminal - terminal.on('data', data => this.emit('pty-data', data)) - // The terminal can accept human input, including sign-in and trust choices, as soon as the - // PTY is running. Automated prompt delivery is a separate ACP-only capability. - let painted = false - terminal.once('data', () => { - painted = true - if (!awaitingResume && !this.startup.signal.aborted && !this.exited) this.emit('input-readiness', { ready: true, reason: 'ready' }) + terminal.on('data', data => { + void this.nativeComposer.output(data) + this.emit('pty-data', data) }) terminal.on('exit', exit => { this.exited = true failResume('Antigravity exited before confirming the requested conversation.') this.emit('input-readiness', { ready: false, reason: 'provider-not-ready' }) + this.nativeComposer.dispose() this.closeObserver() this.emit('exit', exit) }) @@ -135,16 +166,16 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes const timer = selection && setTimeout(() => failResume('Antigravity timed out confirming the requested conversation.'), this.deps.resumeTimeoutMs ?? 10_000) this.startup.signal.addEventListener('abort', cancel, { once: true }) try { - await Promise.all([terminal.start(), selection]) + await Promise.all([terminal.start().then(() => this.nativeMcp?.setOwner(terminal.getProcessPid())), selection]) if (requested) { if (this.startup.signal.aborted) throw new Error('Antigravity conversation resume was cancelled.') if (this.exited) throw new Error('Antigravity exited during conversation resume.') this.providerSessionId = requested - if (painted) this.emit('input-readiness', { ready: true, reason: 'ready' }) } } catch (error) { this.exited = true await terminal.stop() + this.nativeComposer.dispose() this.closeObserver() throw error } finally { @@ -157,11 +188,73 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes const transcriptFile = antigravityTranscriptLocator(id) this.emit('jsonl-entry', { type: 'antigravity-identity', sessionId: id }, transcriptFile) } + this.attached = true + this.publishReadiness() this.emit('started', {}) } + confirmedConversation(): string | null { + return this.attached && !this.isExited() && this.activeConversation === this.providerSessionId + ? this.activeConversation : null + } + + private publishReadiness(): void { + const id = this.confirmedConversation() + if ((this.history?.id ?? null) !== id) { + this.history?.unregister() + this.history = undefined + if (id) { + // Never infer replay configuration from a transcript-reader request. agy + // authenticated this conversation; reuse its trusted cwd, binary and profile. + // Share overlapping reads, then discard the result so a new turn is visible. + const lifetime = new AbortController() + let pending: ReturnType | undefined + const replay = () => pending ??= replayAntigravityConversation(id, this.options.cwd, { + binary: this.options.binary, env: { ...process.env, ...this.options.env }, signal: lifetime.signal, + }).finally(() => { pending = undefined }) + const release = registerAntigravityHistory(id, { replay }) + this.history = { id, unregister: () => { release(); lifetime.abort() } } + } + } + const ready = Boolean(id) && this.nativeComposer.ready() + const reason = ready ? 'ready' : this.nativeComposer.occupied() ? 'composer-occupied' : 'provider-not-ready' + if (reason !== this.lastReadiness) { + this.lastReadiness = reason + this.emit('input-readiness', { ready, reason }) + } + } + + async awaitReadyForPrompt(options: { deadlineAt?: number; timeoutMs?: number } = {}): Promise { + // The manager can now hold one follow-up for a booting pane, released by + // a real paint, without reserving the keyboard during sign-in or trust. + const start = Date.now() + const deadline = options.deadlineAt ?? start + (options.timeoutMs ?? 2000) + return new Promise(resolve => { + const settle = (expired = false) => { + let state: PromptReadinessOutcome + if (this.isExited()) state = { kind: 'terminal', reason: 'exited' } + else if (this.confirmedConversation() && this.nativeComposer.ready()) state = { kind: 'ready', waitedMs: Date.now() - start } + else if (this.nativeComposer.occupied()) state = { kind: 'occupied', reason: 'human-draft' } + else if (expired) state = { kind: 'timeout', waitedMs: Date.now() - start, lastState: { kind: 'warming', reason: 'composer-unpainted' } } + else return + clearTimeout(timer) + this.off('input-readiness', onState) + this.off('exit', onState) + this.startup.signal.removeEventListener('abort', onState) + resolve(state) + } + const onState = () => settle() + const timer = setTimeout(() => settle(true), Math.max(0, deadline - start)) + this.on('input-readiness', onState) + this.on('exit', onState) + this.startup.signal.addEventListener('abort', onState, { once: true }) + settle() + }) + } + write(data: string): boolean { if (!this.terminal || this.exited || this.startup.signal.aborted) return false + this.nativeComposer.input(data) this.terminal.write(data) return true } @@ -170,18 +263,26 @@ export class AntigravityTerminalSession extends EventEmitter implements AgentSes if (cols < 1 || rows < 1) return this.cols = cols this.rows = rows + this.nativeComposer.resize(cols, rows) this.terminal?.resize(cols, rows) } async stop(): Promise { this.startup.abort() await this.terminal?.stop() + this.nativeComposer.dispose() this.closeObserver() } private closeObserver(): void { + void this.turnHooks?.close() + this.turnHooks = null + this.history?.unregister() + this.history = undefined this.observer?.close() this.observer = null + this.nativeMcp?.close() + this.nativeMcp = undefined } getProcessPid(): number | null { return this.terminal?.getProcessPid() ?? null } diff --git a/src/providers/antigravity/runtime/externalControl.system.test.ts b/src/providers/antigravity/runtime/externalControl.system.test.ts new file mode 100644 index 000000000..8107d1df6 --- /dev/null +++ b/src/providers/antigravity/runtime/externalControl.system.test.ts @@ -0,0 +1,50 @@ +import { mkdtemp, mkdir, 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 { AntigravitySession } from './antigravitySession.js' +import { AntigravityTerminalSession } from './antigravityTerminalSession.js' +import { replayAntigravityConversation } from './antigravityHistory.js' +import { resolveFamily } from '@main/conversations/family.js' +import { AntigravityConversationSource } from '@main/conversations/sources/antigravity.js' + +let home: string, globalConfig: string +beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'agy-launch-policy-')) + const configDir = join(home, '.gemini/config') + await mkdir(configDir, { recursive: true }) + globalConfig = join(configDir, 'mcp_config.json') + vi.stubEnv('HOME', home) +}) +afterEach(async () => { vi.unstubAllEnvs(); await rm(home, { recursive: true, force: true }) }) +const writeConflict = () => writeFile(globalConfig, '{"mcpServers":{"agent-code-control":{"command":"/usr/bin/true"}}}') + +it('blocks native preallocation, rendered launch, history replay and catalog before starting a subprocess', async () => { + await writeConflict() + const allocate = vi.fn() + const spawn = vi.fn() + const acp = new AntigravitySession({ cwd: home }, { spawn, mcpProxyScript: 'unused', scriptRunner: 'unused' }) + const terminal = new AntigravityTerminalSession({ cwd: home }, { allocate }) + const source = new AntigravityConversationSource({ binary: spawn }) + try { + await expect(acp.start()).rejects.toThrow(/agent-code-control/) + await expect(terminal.start()).rejects.toThrow(/agent-code-control/) + await expect(replayAntigravityConversation('unused', home, { spawn })).rejects.toThrow(/agent-code-control/) + const family = await resolveFamily(home, 'everywhere', { listWorktrees: async () => [] }) + expect(await source.discover({ scope: 'everywhere', family })).toEqual([]) + expect(spawn).not.toHaveBeenCalled() + expect(allocate).not.toHaveBeenCalled() + expect(terminal.getProcessPid()).toBeNull() + } finally { await Promise.all([acp.stop(), terminal.stop()]) } +}) + +it('rechecks the native launch when the config changes during preallocation', async () => { + const allocate = vi.fn(async () => { await writeConflict(); return 'unused' }) + const terminal = new AntigravityTerminalSession({ cwd: home }, { allocate }) + try { + await expect(terminal.start()).rejects.toThrow(/agent-code-control/) + expect(allocate).toHaveBeenCalledOnce() + expect(terminal.getProcessPid()).toBeNull() + } finally { await terminal.stop() } +}) diff --git a/src/providers/antigravity/runtime/externalControl.test.ts b/src/providers/antigravity/runtime/externalControl.test.ts new file mode 100644 index 000000000..7ae599a69 --- /dev/null +++ b/src/providers/antigravity/runtime/externalControl.test.ts @@ -0,0 +1,45 @@ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { assertAntigravityExternalControlExcluded } from './externalControl.js' + +let root: string, home: string, work: string, global: string, local: string +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'agy-policy-')) + home = join(root, 'home') + work = join(root, 'project') + global = join(home, '.gemini/config') + local = join(work, '.agents') + await Promise.all([mkdir(global, { recursive: true }), mkdir(local, { recursive: true })]) +}) +afterEach(() => rm(root, { recursive: true, force: true })) +const inspect = () => assertAntigravityExternalControlExcluded(work, { HOME: home }) +const reserved = (disabled: boolean) => JSON.stringify({ mcpServers: { 'agent-code-control': { command: '/usr/bin/true', disabled } } }) + +it('refuses an enabled global operator even if a workspace disables the same name and no pane MCP servers were granted', async () => { + const file = join(global, 'mcp_config.json') + await writeFile(file, '') + await expect(inspect()).resolves.toBeUndefined() + await writeFile(file, '// harmless fixture\n' + reserved(false)) + await writeFile(join(local, 'mcp_config.json'), reserved(true)) + await expect(Promise.all([inspect(), inspect()])).rejects.toThrow(/agent-code-control/) + expect(await readFile(file, 'utf8')).toBe('// harmless fixture\n' + reserved(false)) + await writeFile(file, reserved(true)) + await expect(inspect()).resolves.toBeUndefined() +}) + +it('checks project and plugin MCP configurations without exposing configuration values', async () => { + const plugin = join(global, 'plugins', 'test-plugin') + await mkdir(plugin, { recursive: true }) + await writeFile(join(plugin, 'plugin.json'), '{"name":"test-plugin"}') + await writeFile(join(plugin, 'mcp_config.json'), reserved(false)) + await expect(inspect()).rejects.toThrow(/agent-code-control/) + await writeFile(join(global, 'config.json'), '{"plugins":{"test-plugin":{"enabled":false}}}') + await expect(inspect()).resolves.toBeUndefined() + await writeFile(join(local, 'mcp_config.json'), '{"mcpServers":{"other":{"command":"/usr/bin/true","serverUrl":"https://example.test"}}}') + await expect(inspect()).resolves.toBeUndefined() + await writeFile(join(local, 'mcp_config.json'), '{"mcpServers":{"bad":"sensitive malformed value') + await expect(inspect()).rejects.toThrow(/could not verify/i) + await expect(inspect()).rejects.not.toThrow(/sensitive/) +}) diff --git a/src/providers/antigravity/runtime/externalControl.ts b/src/providers/antigravity/runtime/externalControl.ts new file mode 100644 index 000000000..f857f57ec --- /dev/null +++ b/src/providers/antigravity/runtime/externalControl.ts @@ -0,0 +1,83 @@ +import { constants } from 'node:fs' +import { open, readdir } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' + +import { EXTERNAL_OPERATOR_SERVER_NAME } from '@providers/shared/runtime/externalControlExclusion.js' +import { asRecord } from '@shared/lib/asRecord.js' + +const missing = (error: unknown) => ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '') + +function verificationError(path: string) { + // JSON.parse errors and several filesystem errors include the malformed + // source, which could contain credentials. Only the path reaches the UI. + return new Error(`Could not verify Antigravity configuration at ${path}. Review this file before opening a managed Antigravity session.`) +} + +export async function readAntigravityConfig(path: string): Promise | null> { + let file + try { + file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK) + if (!(await file.stat()).isFile()) throw verificationError(path) + const text = await file.readFile('utf8') + // agy accepts // comments. Preserve slashes and escaped quotes inside + // JSON strings, including user-supplied server URLs and arguments. + const json = text.replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*/g, token => token.startsWith('//') ? '' : token) + // A fresh agy install can create a zero-byte file. The CLI reports + // 'No MCP servers configured' for that state. + if (!json.trim()) return {} + const value = asRecord(JSON.parse(json)) + if (!value) throw verificationError(path) + return value + } catch (error) { + if (missing(error)) return null + throw verificationError(path) + } finally { await file?.close() } +} + +function reserved(name: string): boolean { + return name.toLowerCase().replace(/_/g, '-') === EXTERNAL_OPERATOR_SERVER_NAME +} + +function conflict(path: string) { + return new Error(`Antigravity enables the external operator MCP server "${EXTERNAL_OPERATOR_SERVER_NAME}" in ${path}. Disable that entry for this profile before opening an Agent Code pane. Your configuration was left unchanged.`) +} + +async function enabledOperator(path: string): Promise { + const config = await readAntigravityConfig(path) + const servers = asRecord(config?.mcpServers) + return Object.entries(servers ?? {}).some(([name, entry]) => reserved(name) && asRecord(entry)?.disabled !== true) +} + +/** agy's additional workspace cannot shadow a running global MCP server. + * A session permissions deny applies to TOOL USE; it still starts the server. + * Refuse a conflicting launch before any agy code runs. This check is read-only, + * independent of per-pane grants, and needs no shared or temporary override. + * https://antigravity.google/docs/cli-settings */ +export async function assertAntigravityExternalControlExcluded( + cwd: string, + env: NodeJS.ProcessEnv = process.env, + paneServers: readonly { name: string }[] = [], +): Promise { + if (paneServers.some(entry => reserved(entry.name))) throw conflict('the pane configuration') + const global = join(env.HOME || env.USERPROFILE || homedir(), '.gemini', 'config') + for (const root of [global, join(cwd, '.agents')]) { + const mcpPath = join(root, 'mcp_config.json') + if (await enabledOperator(mcpPath)) throw conflict(mcpPath) + + const pluginsDir = join(root, 'plugins') + let plugins + try { plugins = await readdir(pluginsDir, { withFileTypes: true }) } + catch (error) { if (missing(error)) continue; throw verificationError(pluginsDir) } + for (const plugin of plugins) { + if (!plugin.isDirectory() && !plugin.isSymbolicLink()) continue + const path = join(pluginsDir, plugin.name, 'mcp_config.json') + if (!await enabledOperator(path)) continue + // agy 1.5.18's plugin disable writes plugins[folder].enabled=false + // in the global config. The CLI keys it by folder, independent of the + // display name inside plugin.json. Only skip a verified global disable. + const config = root === global ? await readAntigravityConfig(join(global, 'config.json')) : null + if (asRecord(asRecord(config?.plugins)?.[plugin.name])?.enabled !== false) throw conflict(path) + } + } +} diff --git a/src/providers/antigravity/runtime/nativeMcp.system.test.ts b/src/providers/antigravity/runtime/nativeMcp.system.test.ts new file mode 100644 index 000000000..e66709af7 --- /dev/null +++ b/src/providers/antigravity/runtime/nativeMcp.system.test.ts @@ -0,0 +1,202 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { createServer } from 'node:http' +import { join } from 'node:path' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' +import { expect, it, vi } from 'vitest' +import { BuiltInMcpHttpHost } from '@mcp/runtime/BuiltInMcpHttpHost.js' +import { TldrStore } from '@main/tldr/TldrStore.js' +import { openAntigravityNativeMcp } from './nativeMcp.js' + +vi.mock('@main/performance/PerformanceService.js', () => ({ performanceService: { record: vi.fn() } })) + +// A real upstream and the very executable/config that agy consumes. Checking a generated +// JSON shape alone missed both the absent native wiring and leaked environment credentials. +it('keeps two concurrent panes and their upstream credentials separate through real discovery and calls', async () => { + const calls: Array<[string, string | undefined]> = [] + const host = createServer(async (req, res) => { + let body = '' + for await (const chunk of req) body += chunk + const method = req.method === 'POST' && JSON.parse(body).method + if (!method || method === 'notifications/initialized') { res.writeHead(method ? 202 : 405).end(); return } + const { id } = JSON.parse(body) + calls.push([method, req.headers.authorization]) + const result = method === 'initialize' + ? { protocolVersion: '2025-06-18', serverInfo: { name: 'fixture', version: '1' }, capabilities: { tools: {} } } + : method === 'tools/list' + ? { tools: [{ name: 'echo', inputSchema: { type: 'object' } }] } + : { content: [{ type: 'text', text: 'received by ' + req.headers.authorization }] } + res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id, result })) + }) + await new Promise(ok => host.listen(0, '127.0.0.1', ok)) + const address = host.address() + if (!address || typeof address === 'string') throw Error('fixture failed to listen') + const url = 'http://127.0.0.1:' + address.port + const resources: Array>>> = [] + const clients: Client[] = [] + try { + for (const bearerToken of ['first-only', 'second-only']) { + const pane = await openAntigravityNativeMcp({ cwd: process.cwd(), builtInMcpServers: [{ name: 'agent_code', url, bearerToken, headers: {} }] }) + if (!pane) throw Error('missing registration') + resources.push(pane) + pane.setOwner(process.pid) + const configText = await readFile(join(pane.directory, '.agents/mcp_config.json'), 'utf8') + const config = JSON.parse(configText).mcpServers.agent_code + expect(configText).not.toContain(bearerToken) + const client = new Client({ name: 'test', version: '1' }) + clients.push(client) + await client.connect(new StdioClientTransport({ ...config, env: config.env })) + expect((await client.listTools()).tools.map(t => t.name)).toEqual(['echo']) + expect(await client.callTool({ name: 'echo' })).toMatchObject({ content: [{ text: 'received by Bearer ' + bearerToken }] }) + } + const wrong = new Client({ name: 'wrong-pane', version: '1' }) + clients.push(wrong) + const firstConfig = JSON.parse(await readFile(join(resources[0]!.directory, '.agents/mcp_config.json'), 'utf8')).mcpServers.agent_code + resources[0]!.setOwner(process.pid + 1) + await expect(wrong.connect(new StdioClientTransport(firstConfig))).rejects.toThrow() + resources[0]!.close() + await expect(readFile(join(resources[0]!.directory, '.agents/mcp_config.json'))).rejects.toMatchObject({ code: 'ENOENT' }) + expect(await clients[1]!.callTool({ name: 'echo' })).toMatchObject({ content: [{ text: 'received by Bearer second-only' }] }) + expect(calls.filter(([m]) => m === 'tools/call')).toEqual([ + ['tools/call', 'Bearer first-only'], ['tools/call', 'Bearer second-only'], ['tools/call', 'Bearer second-only'], + ]) + } finally { + for (const pane of resources) pane.close() + await Promise.all(clients.map(client => client.close())) + host.closeAllConnections() + await new Promise(ok => host.close(() => ok())) + } +}) + +it('does not create a workspace or listener for a pane without grants', async () => { + expect(await openAntigravityNativeMcp({ cwd: process.cwd() })).toBeUndefined() +}) + +it('passes managed stdio secrets only to their own server and keeps relay grants outside the attached workspace', async () => { + const fixture = String.raw` + require('node:readline').createInterface({ input: process.stdin }).on('line', line => { + const { id, method } = JSON.parse(line) + if (id === undefined) return + const result = method === 'initialize' + ? { protocolVersion: '2025-06-18', serverInfo: { name: 'env', version: '1' }, capabilities: { tools: {} } } + : { content: [{ type: 'text', text: JSON.stringify({ + own: process.env.MCP_FIXTURE_SECRET, + inheritedBootstrap: Boolean(process.env.AGENT_CODE_AGY_RELAY_BOOTSTRAP), + cwd: process.cwd() + }) }] } + console.log(JSON.stringify({ jsonrpc: '2.0', id, result })) + })` + const pane = await openAntigravityNativeMcp({ cwd: process.cwd(), userMcpServers: [ + { name: 'server_a', id: '1', entry: { command: process.execPath, args: ['-e', fixture], env: { MCP_FIXTURE_SECRET: '${input:key}' } }, secrets: { key: 'isolated-stdio-value' } }, + ] }) + if (!pane) throw Error('missing managed registration') + const client = new Client({ name: 'native', version: '1' }) + try { + pane.setOwner(process.pid) + const disk = await readFile(join(pane.directory, '.agents/mcp_config.json'), 'utf8') + expect(disk).not.toContain('isolated-stdio-value') + const entry = JSON.parse(disk).mcpServers.server_a + const bootstrap: string = entry.env.AGENT_CODE_AGY_RELAY_BOOTSTRAP + expect(bootstrap.startsWith(pane.directory + '/')).toBe(false) + expect((await readFile(bootstrap)).length).toBe(32) + await client.connect(new StdioClientTransport(entry)) + expect(await client.callTool({ name: 'check' })).toMatchObject({ + content: [{ text: JSON.stringify({ own: 'isolated-stdio-value', inheritedBootstrap: false, cwd: process.cwd() }) }], + }) + pane.close() + await expect(readFile(bootstrap)).rejects.toMatchObject({ code: 'ENOENT' }) + } finally { + pane.close() + await client.close() + } +}) + +it('writes a real TLDR record through the native bridge with the scope of its registered pane', async () => { + const directory = await mkdtemp(join(tmpdir(), 'agy-mcp-tldr-')) + const store = new TldrStore(join(directory, 'tldr.json')) + const host = new BuiltInMcpHttpHost() + const client = new Client({ name: 'native', version: '1' }) + let pane: Awaited> + try { + host.setDependencies({ tldrStore: store }) + await host.start() + const cwd = process.cwd() + const builtInMcpServers = host.registerSession({ sessionId: 'native-test', tldrIdentity: 'this-pane', providerKind: 'antigravity', cwd, domains: ['tldr'] }) + pane = await openAntigravityNativeMcp({ cwd, builtInMcpServers }) + if (!pane) throw Error('missing built-in registration') + pane.setOwner(process.pid) + const entry = JSON.parse(await readFile(join(pane.directory, '.agents/mcp_config.json'), 'utf8')).mcpServers.agent_code + await client.connect(new StdioClientTransport(entry)) + expect((await client.listTools()).tools.map(tool => tool.name)).toEqual(['tldr_update']) + expect((await client.callTool({ name: 'tldr_update', arguments: { text: 'Verified native tools.' } })).isError).not.toBe(true) + expect(await store.read(['this-pane', 'other-pane'])).toMatchObject({ 'this-pane': { text: 'Verified native tools.' } }) + expect(await store.read(['other-pane'])).toEqual({}) + } finally { + await client.close() + pane?.close() + await host.stop() + await rm(directory, { recursive: true, force: true }) + } +}) + +it('gives agy native HTTP endpoints for OAuth and keeps credential-bearing endpoint shapes off disk', async () => { + const examples = [ + ['oauth', 'https://example.com/mcp'], ['root', 'https://oauth.example.com'], + ['with_path', 'https://example.com/private-value'], ['query', 'https://example.com/mcp?key=private-value'], + ['fragment', 'https://example.com/mcp#private-value'], ['userinfo', 'https://user:private-value@example.com/mcp'], + ['normalized', 'https://example.com/private-value/../mcp'], ['insecure', 'http://example.com/mcp'], + ] as const + const pane = await openAntigravityNativeMcp({ + cwd: process.cwd(), + userMcpServers: [ + ...examples.map(([name, url]) => ({ id: name, name, entry: { type: 'http' as const, url }, secrets: {} })), + { id: 'headers', name: 'headers', entry: { type: 'http', url: 'https://example.com/mcp', headers: { 'X-Api-Key': 'private-value' } }, secrets: {} }, + ], + builtInMcpServers: [{ name: 'agent_code', url: 'https://example.com/mcp', headers: {} }], + }) + if (!pane) throw Error('missing workspace') + try { + const raw = await readFile(join(pane.directory, '.agents/mcp_config.json'), 'utf8') + const entries = JSON.parse(raw).mcpServers + expect(entries.oauth).toEqual({ serverUrl: 'https://example.com/mcp' }) + expect(entries.root).toEqual({ serverUrl: 'https://oauth.example.com' }) + expect(raw).not.toContain('private-value') + for (const name of ['with_path', 'query', 'fragment', 'userinfo', 'normalized', 'insecure', 'headers', 'agent_code']) { + // The settings layer may also reject an invalid URL before launch. + if (name === 'userinfo' && !entries[name]) continue + expect(entries[name]).toHaveProperty('command') + } + } finally { pane.close() } +}) + +it('closes a failed upstream launch and can reconnect the pane after the executable appears', async () => { + const directory = await mkdtemp(join(tmpdir(), 'agy-missing-mcp-')) + const command = join(directory, 'server') + const pane = await openAntigravityNativeMcp({ + cwd: directory, + userMcpServers: [{ id: 'recover', name: 'recover', entry: { command }, secrets: {} }], + }) + if (!pane) throw Error('missing registration') + const failed = new Client({ name: 'first', version: '1' }) + const recovered = new Client({ name: 'second', version: '1' }) + try { + pane.setOwner(process.pid) + const entry = JSON.parse(await readFile(join(pane.directory, '.agents/mcp_config.json'), 'utf8')).mcpServers.recover + await expect(failed.connect(new StdioClientTransport(entry))).rejects.toThrow() + await writeFile(command, `#!/usr/bin/env node +require('node:readline').createInterface({input: process.stdin}).on('line', line => { + const { id, method } = JSON.parse(line) + if (id === undefined) return + const result = method === 'initialize' ? { protocolVersion: '2025-06-18', capabilities: {tools:{}}, serverInfo:{name:'recovered',version:'1'} } : {tools:[]} + console.log(JSON.stringify({ jsonrpc: '2.0', id, result })) +}) +`, { mode: 0o700 }) + await recovered.connect(new StdioClientTransport(entry)) + expect(await recovered.listTools()).toMatchObject({ tools: [] }) + } finally { + await Promise.all([failed.close(), recovered.close()]) + pane.close() + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/src/providers/antigravity/runtime/nativeMcp.ts b/src/providers/antigravity/runtime/nativeMcp.ts new file mode 100644 index 000000000..c6f4b72ec --- /dev/null +++ b/src/providers/antigravity/runtime/nativeMcp.ts @@ -0,0 +1,156 @@ +import { randomBytes } from 'node:crypto' +import { mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { createServer, type Socket } from 'node:net' +import { join } from 'node:path' +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' + +import { createPrivateMcpDirectory } from '@providers/shared/runtime/builtInMcpLaunch.js' +import type { SessionOptions } from '@shared/types/session.js' +import { resolveAntigravityNativeMcpRelay, resolveAntigravityScriptRunner } from './runtimeScripts.js' +import { type AntigravityUserMcpConfig, resolveAntigravityUserMcpEntries } from './userMcpEntries.js' + +/** Only a public service address can go in an agent-readable workspace. Let native agy + * receive its HTTP 401 and perform OAuth. A query, userinfo, fragment or custom path may + * contain a credential. Match the original spelling too: URL normalization discards + * dot segments, so testing pathname alone would write the original secret onto disk. */ +function nativeOAuthUrl(entry: AntigravityUserMcpConfig): string | undefined { + if (!('serverUrl' in entry) || Object.keys(entry.headers).length || !URL.canParse(entry.serverUrl)) return + const url = new URL(entry.serverUrl) + if (url.protocol !== 'https:' || !['/', '/mcp', '/mcp/'].includes(url.pathname)) return + if (entry.serverUrl === url.origin || entry.serverUrl === url.origin + url.pathname) return entry.serverUrl +} + +/** Native agy reads an additional workspace's .agents/mcp_config.json at launch, including + * explicit resumes. It does not expand environment variables there, and an agy shell or + * unrelated MCP process inherits agy's environment. Keep the original credentials in main. + * A stolen relay grant can speak only MCP to that one registered server until this pane + * closes; the relay has no API to retrieve the server config, headers or environment. */ +export async function openAntigravityNativeMcp(options: SessionOptions) { + const publicEntries: Array<[string, { serverUrl: string }]> = [] + const entries: Array<{ name: string; config: AntigravityUserMcpConfig }> = [] + for (const server of resolveAntigravityUserMcpEntries(options.userMcpServers ?? [])) { + const serverUrl = nativeOAuthUrl(server.config) + if (serverUrl) publicEntries.push([server.name, { serverUrl }]) + else entries.push(server) + } + for (const server of options.builtInMcpServers ?? []) { + const headers = { ...server.headers, ...(server.bearerToken === undefined ? {} : { Authorization: 'Bearer ' + server.bearerToken }) } + entries.push({ name: server.name, config: { serverUrl: server.url, headers } }) + } + if (!entries.length && !publicEntries.length) return undefined + + const directory = await createPrivateMcpDirectory() + const workspace = join(directory, 'workspace') + const bootstraps = join(directory, 'private') + const grants = new Map() + let ownerPid: number | null = null + const sockets = new Set() + const server = createServer(socket => { + sockets.add(socket) + socket.once('close', () => sockets.delete(socket)) + socket.on('error', () => socket.destroy()) + socket.setTimeout(3000, () => socket.destroy()) + const authenticate = () => { + // Use a fixed-size handshake: a split TCP packet must not turn half a token + // into an authentication failure, or swallow MCP bytes following the token. + const frame: Buffer | null = socket.read(36) + if (!frame) return + socket.removeListener('readable', authenticate) + const entry = grants.get(frame.subarray(0, 32).toString('hex')) + if (!entry || frame.readUInt32BE(32) !== ownerPid) return socket.destroy() + socket.setTimeout(0) + void connectNativeMcp(socket, entry, options).catch(() => socket.destroy()) + } + socket.on('readable', authenticate) + }) + const close = () => { + grants.clear() + if (server.listening) server.close() + for (const socket of sockets) socket.destroy() + rmSync(directory, { recursive: true, force: true }) + } + try { + let port: number | undefined + if (entries.length) { + await new Promise((ok, fail) => { + server.once('error', fail) + server.listen(0, '127.0.0.1', () => { server.removeListener('error', fail); ok() }) + }) + const address = server.address() + if (!address || typeof address === 'string') throw new Error('Could not open the Antigravity MCP relay.') + port = address.port + mkdirSync(bootstraps, { mode: 0o700 }) + } + const relayEntries = entries.map(({ name, config }) => { + // agy passes the parent environment to every MCP child and shell. Its per-entry + // env contains only this private bootstrap path. The grant itself stays outside + // the model's additional workspace and expires with this pane's listener. + const bootstrap = join(bootstraps, randomBytes(12).toString('hex')) + const grant = randomBytes(32) + writeFileSync(bootstrap, grant, { mode: 0o600 }) + grants.set(grant.toString('hex'), config) + return [name, { + command: resolveAntigravityScriptRunner(), + args: [resolveAntigravityNativeMcpRelay(), String(port)], + env: { ELECTRON_RUN_AS_NODE: '1', AGENT_CODE_AGY_RELAY_BOOTSTRAP: bootstrap }, + }] as const + }) + const mcpServers = Object.fromEntries([...publicEntries, ...relayEntries]) + const configDir = join(workspace, '.agents') + mkdirSync(configDir, { mode: 0o700, recursive: true }) + writeFileSync(join(configDir, 'mcp_config.json'), JSON.stringify({ mcpServers }), { mode: 0o600 }) + return { directory: workspace, setOwner(pid: number | null) { ownerPid = pid }, close } + } catch (error) { + close() + throw error + } +} + +/** Transport-level forwarding preserves resource/prompt methods, cancellation, server + * instructions, paginated results and tool errors without translating any tool schemas. + * HTTP redirects are disabled so arbitrary API-key headers cannot reach a different origin. */ +async function connectNativeMcp(socket: Socket, entry: AntigravityUserMcpConfig, options: SessionOptions) { + const downstream = new StdioServerTransport(socket, socket) + const upstream: Transport = 'command' in entry + ? new StdioClientTransport({ ...entry, cwd: options.cwd, stderr: 'ignore', env: { + ...(options.env?.PATH ? { PATH: options.env.PATH } : {}), ...entry.env, + } }) + : new StreamableHTTPClientTransport(new URL(entry.serverUrl), { + requestInit: { headers: entry.headers, redirect: 'error' }, + }) + socket.once('close', () => { + void downstream.close() + void upstream.close().catch(() => {}) + }) + let initializeId: string | number | undefined + upstream.onclose = () => socket.destroy() + downstream.onerror = () => socket.destroy() + upstream.onmessage = message => { + if (upstream instanceof StreamableHTTPClientTransport && 'result' in message && message.id === initializeId && typeof message.result.protocolVersion === 'string') { + upstream.setProtocolVersion(message.result.protocolVersion) + } + void downstream.send(message).catch(() => socket.destroy()) + } + downstream.onmessage = message => { + // agy extends stdio with an optional discover probe before MCP initialize. + // Streamable HTTP servers can reject any pre-initialize request at the HTTP + // layer. Answer the optional extension locally; agy then negotiates MCP. + if ('method' in message && message.method === 'server/discover' && 'id' in message && upstream instanceof StreamableHTTPClientTransport) { + void downstream.send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }).catch(() => socket.destroy()) + return + } + if ('method' in message && message.method === 'initialize' && 'id' in message) initializeId = message.id + void upstream.send(message).catch(() => { + if ('method' in message && 'id' in message) { + // An upstream CLI or server can include credentials in its error text. + void downstream.send({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: 'MCP upstream request failed' } }).catch(() => socket.destroy()) + } else socket.destroy() + }) + } + await upstream.start() + if (socket.destroyed) { await upstream.close(); return } + await downstream.start() +} diff --git a/src/providers/antigravity/runtime/nativeMcpRelay.cjs b/src/providers/antigravity/runtime/nativeMcpRelay.cjs new file mode 100644 index 000000000..f2172ef12 --- /dev/null +++ b/src/providers/antigravity/runtime/nativeMcpRelay.cjs @@ -0,0 +1,24 @@ +// agy starts this helper as a native stdio MCP server. Only protocol bytes +// cross this socket: real HTTP credentials and stdio server secrets stay in +// the owning Agent Code process. The main process also binds the bootstrap +// to the agy process it launched, so a resumed pane cannot reuse a stale entry. +const { connect } = require('node:net') +const { readFileSync } = require('node:fs') +const [, , port] = process.argv +const bootstrap = process.env.AGENT_CODE_AGY_RELAY_BOOTSTRAP +if (!bootstrap) process.exit(1) +const grant = readFileSync(bootstrap) +if (grant.length !== 32) process.exit(1) +const frame = Buffer.alloc(36) +grant.copy(frame) +frame.writeUInt32BE(process.ppid, 32) + +const socket = connect(Number(port), '127.0.0.1') +socket.on('error', () => process.exit(1)) +process.stdout.on('error', () => socket.destroy()) +socket.on('close', () => process.exit(0)) +socket.on('connect', () => { + socket.write(frame) + socket.pipe(process.stdout) + process.stdin.pipe(socket) +}) diff --git a/src/providers/antigravity/runtime/nativePromptDelivery.test.ts b/src/providers/antigravity/runtime/nativePromptDelivery.test.ts new file mode 100644 index 000000000..e93658779 --- /dev/null +++ b/src/providers/antigravity/runtime/nativePromptDelivery.test.ts @@ -0,0 +1,43 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { PromptDeliveryIo } from '@shared/types/providerConfig.js' +import { AntigravityTerminalSession } from './antigravityTerminalSession.js' +import { deliverAntigravityPrompt } from './promptDelivery.js' + +let session: AntigravityTerminalSession +afterEach(() => session.stop()) + +async function setup() { + session = new AntigravityTerminalSession({ cwd: '/project', cols: 40, rows: 20 }) + const conversation = vi.spyOn(session, 'confirmedConversation').mockReturnValue('pane-conversation') + const rule = '─'.repeat(40) + await session.nativeComposer.output('\x1b[?2004h' + rule + '\r\n>\r\n' + rule + '\r\n? for shortcuts\x1b[2A\r\x1b[2C') + const write = vi.fn<(data: string) => boolean>().mockReturnValue(true) + const deliver = (prompt: string) => deliverAntigravityPrompt({ session, sessionId: 'pane', write, prompt } satisfies PromptDeliveryIo) + return { write, deliver, conversation } +} + +it('refuses unsupported terminal control bytes before writing any of a generated prompt', async () => { + const { deliver, write } = await setup() + expect(await deliver('test\x1b[201~\rnext')).toMatchObject({ ok: false, promptWritten: false, enterWritten: false }) + expect(write).not.toHaveBeenCalled() +}) + +it('never retries or sends Enter when the pasted text belongs to a previous conversation', async () => { + const { deliver, write, conversation } = await setup() + write.mockImplementation(() => { conversation.mockReturnValue('different-conversation'); return true }) + expect(await deliver('first\r\nsecond')).toMatchObject({ ok: false, stage: 'absorption', promptWritten: true, enterWritten: false, retrySafe: false }) + expect(write.mock.calls).toEqual([['\x1b[200~first\nsecond\x1b[201~']]) +}) + +it('reports a lost process before paste as safe to retry', async () => { + const { deliver, write } = await setup() + write.mockReturnValue(false) + expect(await deliver('one')).toMatchObject({ ok: false, code: 'write-failed', promptWritten: false, enterWritten: false, retrySafe: true }) +}) + +it('keeps a native prompt with an app attachment intact for delivery through Agent view', async () => { + const { write } = await setup() + const result = await deliverAntigravityPrompt({ session, sessionId: 'pane', write, prompt: 'inspect the image', imagePaths: ['/screenshot.png'] }) + expect(result).toMatchObject({ ok: false, code: 'missing-capability', enterWritten: false, promptWritten: false }) + expect(write).not.toHaveBeenCalled() +}) diff --git a/src/providers/antigravity/runtime/nativePromptDelivery.ts b/src/providers/antigravity/runtime/nativePromptDelivery.ts new file mode 100644 index 000000000..772fba634 --- /dev/null +++ b/src/providers/antigravity/runtime/nativePromptDelivery.ts @@ -0,0 +1,69 @@ +import { setTimeout as delay } from 'node:timers/promises' + +import type { PromptDeliveryIo, PromptDeliveryResult } from '@shared/types/providerConfig.js' +import type { AntigravityTerminalSession } from './antigravityTerminalSession.js' + +/** SessionManager reserves this process's input for the duration and verifies + * backend identity on each write. Inspect the actual editor between paste and + * Enter: a draft or modal that raced the first paint must never get submitted. */ +export async function deliverNativeAntigravityPrompt( + io: PromptDeliveryIo, + session: AntigravityTerminalSession, +): Promise { + if (io.inlineImages?.length || io.imagePaths?.length) { + return { + ok: false, stage: 'before-write', code: 'missing-capability', retrySafe: true, + disposition: 'session-unusable', promptWritten: false, enterWritten: false, + message: 'Antigravity accepts Agent Code image attachments in Agent view.', + } + } + const id = session.confirmedConversation() + const text = io.prompt.replace(/\r\n/g, '\n') + // ESC can terminate a bracketed paste early. Reject terminal control bytes + // even for trusted automation since prompts routinely quote arbitrary data. + if (!text.trim() || /[\x00-\x08\x0b-\x1f\x7f-\x9f]/u.test(text)) { + return { + ok: false, stage: 'before-write', code: 'missing-capability', retrySafe: true, + disposition: 'session-unusable', promptWritten: false, enterWritten: false, + message: 'Antigravity native prompts must contain text and cannot include terminal control characters.', + } + } + if (!id || !session.nativeComposer.ready()) { + const occupied = session.nativeComposer.occupied() + return { + ok: false, stage: 'before-write', code: 'not-ready', retrySafe: true, + disposition: occupied ? 'retry-after-resolve' : 'retry-same-session', promptWritten: false, enterWritten: false, + message: occupied ? 'Antigravity has an existing native draft.' + : 'Antigravity has not confirmed an empty prompt in the selected conversation.', + } + } + if (!io.write('\x1b[200~' + text + '\x1b[201~')) { + return { + ok: false, stage: 'before-write', code: 'write-failed', retrySafe: true, + disposition: 'session-unusable', promptWritten: false, enterWritten: false, + message: 'The Antigravity terminal closed before the prompt was written.', + } + } + + const deadline = Date.now() + 3000 + while (session.confirmedConversation() === id && Date.now() < deadline) { + if (session.nativeComposer.containsPaste(text)) { + if (!io.write('\r')) { + return { + ok: false, stage: 'session-exit', code: 'session-exited', retrySafe: false, + disposition: 'do-not-retry', promptWritten: true, enterWritten: false, + message: 'The target Antigravity process disappeared after the paste. Enter was never written.', + } + } + return { ok: true, acceptance: { kind: 'transport', acceptedAt: Date.now() } } + } + await delay(20) + } + // The paste may still be editable. Never clear it or send Enter after the + // reservation expires; either could change a human's subsequent keystrokes. + return { + ok: false, stage: 'absorption', code: 'absorption-timeout', retrySafe: false, + disposition: 'do-not-retry', promptWritten: true, enterWritten: false, + message: 'Antigravity could not confirm the pasted text in the same native conversation. Check the terminal draft before submitting.', + } +} diff --git a/src/providers/antigravity/runtime/promptDelivery.ts b/src/providers/antigravity/runtime/promptDelivery.ts index 6fa16ce28..9f00f9e11 100644 --- a/src/providers/antigravity/runtime/promptDelivery.ts +++ b/src/providers/antigravity/runtime/promptDelivery.ts @@ -11,13 +11,24 @@ import type { PromptDeliveryIo, PromptDeliveryResult } from '@shared/types/providerConfig.js' +import { AntigravityTerminalSession } from './antigravityTerminalSession.js' +import { deliverNativeAntigravityPrompt } from './nativePromptDelivery.js' + export async function deliverAntigravityPrompt(io: PromptDeliveryIo): Promise { + if (io.session instanceof AntigravityTerminalSession) return deliverNativeAntigravityPrompt(io, io.session) + if (io.imagePaths?.length || (io.inlineImages?.length && !io.session.deliverPromptWithImages)) { + return { + ok: false, stage: 'before-write', code: 'missing-capability', + message: 'This session accepts pasted images through the Antigravity Agent composer.', + promptWritten: false, enterWritten: false, retrySafe: true, disposition: 'retry-after-resolve', + } + } if (typeof io.session.deliverPromptText !== 'function') { return { ok: false, stage: 'before-write', code: 'missing-capability', - message: `Antigravity session ${io.sessionId} has no structured prompt transport. Type in its native terminal, or use the rendered Agent view for automated prompts.`, + message: `Antigravity session ${io.sessionId} has no prompt delivery transport.`, retrySafe: true, disposition: 'session-unusable', promptWritten: false, @@ -25,7 +36,9 @@ export async function deliverAntigravityPrompt(io: PromptDeliveryIo): Promise/SKILL.md`, and a - * `SKILL.md` without frontmatter or `name` is dropped. agy follows the - * `.agents` convention up the workspace, so the cwd and its ancestors up to - * the git root are listed, like Pi's `.agents` walk. - * - * NOT listed: a personal (global) skills folder. agy's is undocumented, and - * the Skills UI must not show a location agy may not read; registry.main.ts - * declares personal agent skills unsupported for the same reason. - */ +/** Google documents these as personal CLI roots. Write managed skills only to the + * canonical shared config root; also installing them in legacy roots would leave + * duplicate slash commands and stale copies when the user disables a skill. */ +export function antigravityPersonalSkills({ homeDirectory }: Pick): string { + return join(homeDirectory, '.gemini', 'config', 'skills') +} + export async function discoverAntigravitySkillRoots(context: AgentSkillDiscoveryContext): Promise { const { cwd } = context const children = { layout: 'children', includeHidden: false } as const @@ -24,8 +18,10 @@ export async function discoverAntigravitySkillRoots(context: AgentSkillDiscovery for (const directory of ancestorsThrough(cwd, gitRoot)) { roots.push({ path: join(directory, '.agents', 'skills'), source: 'project', ...children }) } - return { - roots, - notices: ['Antigravity reads project skills from .agents/skills; its personal skill folder is not documented, so none is listed.'], - } + for (const path of [ + antigravityPersonalSkills(context), + join(context.homeDirectory, '.gemini', 'antigravity-cli', 'skills'), + join(context.homeDirectory, '.gemini', 'skills'), + ]) roots.push({ path, source: 'personal', ...children }) + return { roots, notices: [] } } diff --git a/src/providers/antigravity/runtime/terminalComposer.test.ts b/src/providers/antigravity/runtime/terminalComposer.test.ts new file mode 100644 index 000000000..e9b226c96 --- /dev/null +++ b/src/providers/antigravity/runtime/terminalComposer.test.ts @@ -0,0 +1,62 @@ +import { afterEach, expect, it } from 'vitest' +import { AntigravityTerminalComposer } from './terminalComposer.js' + +// Reconstruct the cursor, borders and text observed on agy 1.5.18 with its real +// native prompt. Only the paint mechanics are synthesized. Human typing, even +// whitespace, removes the shortcut hint; moving to column two leaves it removed. +const cols = 80 +const rule = '─'.repeat(cols) +let composer: AntigravityTerminalComposer | undefined +afterEach(() => composer?.dispose()) +function open() { + return composer = new AntigravityTerminalComposer(cols, 20, () => {}) +} +const paint = (lines: string[], x: number, y: number) => + '\x1b[?2004h\x1b[H\x1b[2J' + lines.join('\r\n') + '\x1b[' + y + ';' + x + 'H' +const ready = paint([rule, '> ', rule, '? for shortcuts'], 3, 2) +const draft = paint([rule, '> human draft', rule], 3, 2) + +it('recognizes only a settled empty native prompt, including when typing is awaiting its echo', async () => { + const c = open() + expect(c.ready()).toBe(false) + await c.output(ready) + expect(c.ready()).toBe(true) + c.input('\x7f') + expect(c.ready()).toBe(true) + c.input('\x08') + expect(c.ready()).toBe(true) + c.input('h') + c.input('\x7f') + expect(c.ready()).toBe(false) + await c.output(ready) + expect(c.ready()).toBe(false) + await c.output(draft) + expect(c.ready()).toBe(false) + expect(c.occupied()).toBe(true) + await c.output(ready) + expect(c.ready()).toBe(true) + for (const screen of [ + draft, paint([rule, '> ', rule], 3, 2), + paint([rule, '>', rule, '? for shortcuts', 'Allow this command?'], 3, 5), + paint([rule, '>', rule, '? for shortcuts'], 1, 4), + paint(['Sign in', '> ', '? for shortcuts'], 3, 2), + ]) { + await c.output(screen) + expect(c.ready()).toBe(false) + } +}) + +it('checks the complete editable content before Enter, including multiline and collapsed pastes', async () => { + const c = open() + await c.output(paint([rule, '> first', ' second', rule], 9, 3)) + expect(c.containsPaste('first\nsecond')).toBe(true) + expect(c.containsPaste('second')).toBe(false) + await c.output(paint([rule, '> [Pasted text #1 +100 lines]', rule], 30, 2)) + expect(c.containsPaste(Array(100).fill('long').join('\n'))).toBe(true) + expect(c.containsPaste(Array(99).fill('long').join('\n'))).toBe(false) + await c.output(paint([rule, '> [Pasted text #1 2600 chars]', rule], 30, 2)) + expect(c.containsPaste('🧪é'.repeat(1300))).toBe(true) + expect(c.containsPaste('🧪é'.repeat(1299))).toBe(false) + await c.output(paint([rule, '> our prompt and a human draft', rule], 13, 2)) + expect(c.containsPaste('our prompt')).toBe(false) +}) diff --git a/src/providers/antigravity/runtime/terminalComposer.ts b/src/providers/antigravity/runtime/terminalComposer.ts new file mode 100644 index 000000000..2d65186d6 --- /dev/null +++ b/src/providers/antigravity/runtime/terminalComposer.ts @@ -0,0 +1,127 @@ +import { Terminal } from '@xterm/headless' + +/** Read only the current editable region. A chat message can contain a fake + * prompt; agy's native cursor, two full-width rules and empty-only hint bind + * the decision to the editor that would actually receive Enter. The mirror + * never answers terminal queries (the visible terminal owns those replies). */ +export class AntigravityTerminalComposer { + private readonly screen: Terminal + private pending = 0 + private inputRevision = 0 + private awaitingEdit = false + private disposed = false + + constructor(cols: number, rows: number, private readonly changed: () => void) { + this.screen = new Terminal({ cols, rows, scrollback: 0, allowProposedApi: true }) + } + + output(data: string): Promise { + if (this.disposed) return Promise.resolve() + this.pending++ + const beforeInput = this.inputRevision + return new Promise(resolve => this.screen.write(data, () => { + this.pending-- + if (!this.disposed && !this.pending) { + if (beforeInput === this.inputRevision && !this.emptyScreen()) this.awaitingEdit = false + this.changed() + } + resolve() + })) + } + + input(data: string): void { + // xterm answers device-status and attribute queries through the same write + // API as typing. Those replies never edit agy's composer. + if (/^(?:\x1b\[\??[\d;]*R|\x1b\[[?>][\d;]*c)$/.test(data)) return + // Backspace on a settled empty agy 1.5.18 prompt is a no-op with + // no ensuing edit to observe. Never clear an already outstanding key: + // its draft may still be waiting for the CLI's first echo. + if ((data === '\x7f' || data === '\x08') && this.ready()) return + this.inputRevision++ + if (this.emptyScreen()) this.awaitingEdit = true + this.changed() + } + + resize(cols: number, rows: number): void { + if (this.disposed) return + this.screen.resize(cols, rows) + this.changed() + } + + dispose(): void { + if (!this.disposed) this.screen.dispose() + this.disposed = true + } + + ready(): boolean { + return !this.disposed && this.pending === 0 && !this.awaitingEdit && this.emptyScreen() + } + + occupied(): boolean { + if (this.disposed || this.pending || !this.screen.modes.bracketedPasteMode) return false + const y = this.screen.buffer.active.cursorY + const rule = '─'.repeat(this.screen.cols) + if (this.line(y + 1) !== rule || this.emptyScreen()) return false + for (let row = y; row > 0; row--) { + const line = this.line(row) + if (/^>(?: |$)/.test(line) && this.line(row - 1) === rule) return true + if (line && !line.startsWith(' ')) break + } + return false + } + + private line(row: number): string { + if (row < 0 || row >= this.screen.rows) return '' + const buffer = this.screen.buffer.active + return buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? '' + } + + private emptyScreen(): boolean { + if (this.disposed || !this.screen.modes.bracketedPasteMode) return false + const buffer = this.screen.buffer.active + const y = buffer.cursorY + const rule = '─'.repeat(this.screen.cols) + return buffer.cursorX === 2 && /^> ?$/.test(this.line(y)) && + this.line(y - 1) === rule && this.line(y + 1) === rule && + /^\? for shortcuts(?:\s{2,}.*)?$/.test(this.line(y + 2)) + } + + containsPaste(text: string): boolean { + if (this.disposed || this.pending || !this.screen.modes.bracketedPasteMode) return false + const y = this.screen.buffer.active.cursorY + const rule = '─'.repeat(this.screen.cols) + if (this.line(y + 1) !== rule) return false + const rows: string[] = [] + for (let row = y; row >= 0; row--) { + const content = this.line(row) + if (content.startsWith('> ') && this.line(row - 1) === rule) { + rows.unshift(content.slice(2)) + // agy collapses larger pastes immediately into a chip with the + // number of lines. A bare chip is sufficient only after we owned + // an empty composer and its one reserved paste. + const displayed = rows.join('\n') + const lineChip = /^\[Pasted text #\d+ \+(\d+) lines?\]$/.exec(displayed) + if (lineChip && Number(lineChip[1]) === text.split('\n').length) return true + // A long single line gets a character count instead. The real CLI + // counted 🧪é × 1300 as 2600 Unicode code points (3900 UTF-16 units). + const charChip = /^\[Pasted text #\d+ (\d+) chars?\]$/.exec(displayed) + if (charChip && Number(charChip[1]) === Array.from(text).length) return true + // Rendering wraps at the pane width and strips trailing spaces from + // padded cells. Walk the expected text so hard and soft wrapping + // don't disguise an extra prefix or suffix from an unrelated draft. + let remaining = text + for (const [i, line] of rows.entries()) { + if (i) { + while (!remaining.startsWith(line) && /^\s/u.test(remaining)) remaining = remaining.slice(1) + } + if (!remaining.startsWith(line)) return false + remaining = remaining.slice(line.length) + } + return remaining.trim().length === 0 + } + if (content && !content.startsWith(' ')) return false + rows.unshift(content.slice(2)) + } + return false + } +} diff --git a/src/providers/antigravity/runtime/turnHooks.test.ts b/src/providers/antigravity/runtime/turnHooks.test.ts new file mode 100644 index 000000000..6d1c09d99 --- /dev/null +++ b/src/providers/antigravity/runtime/turnHooks.test.ts @@ -0,0 +1,77 @@ +import { once } from 'node:events' +import { spawn } from 'node:child_process' +import { join } from 'node:path' +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { expect, it, vi } from 'vitest' +import { agyTurnObserver, openAgyTurnHooks } from './turnHooks.js' + +it('reports one parent turn across invocations and waits for an allowed, fully idle stop', async () => { + const send = vi.fn[1]>(async (event) => event === 'user-prompt-submit' + ? { hookSpecificOutput: { additionalContext: 'Set your goal.' } } : {}) + const activity = vi.fn() + const observe = agyTurnObserver(() => 'parent', send, activity) + const parent = { conversationId: 'parent' } + expect(await observe('/pre', { conversationId: 'child' })).toEqual({}) + expect(await observe('/pre', parent)).toEqual({ injectSteps: [{ systemMessage: { systemMessage: 'Set your goal.' } }] }) + await observe('/pre', parent) + await observe('/tool', parent) + const stop = { ...parent, terminationReason: 'model_stop', fullyIdle: true } + await observe('/stop', { ...stop, fullyIdle: false }) + expect(send.mock.calls.flat()).toEqual(['user-prompt-submit', 'post-tool-use']) + send.mockImplementationOnce(async () => ({ decision: 'block', reason: 'Update your TLDR.' })) + expect(await observe('/stop', stop)).toEqual({ decision: 'continue', reason: 'Update your TLDR.' }) + expect(activity.mock.calls.flat()).toEqual([true]) + await observe('/pre', parent) + await observe('/stop', stop) + await observe('/stop', stop) + expect(send.mock.calls.flat()).toEqual(['user-prompt-submit', 'post-tool-use', 'stop', 'stop']) + expect(activity.mock.calls.flat()).toEqual([true, false]) +}) + +it('sends only the boundary to the pane host when the generated CLI command runs', async () => { + const seen: unknown[] = [] + const host = createServer(async (req, res) => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + seen.push([req.url, req.headers.authorization, Buffer.concat(chunks).toString()]) + res.end(JSON.stringify({ hookSpecificOutput: { additionalContext: 'Report your goal.' } })) + }) + host.listen(0, '127.0.0.1') + await once(host, 'listening') + const address = host.address() + if (!address || typeof address === 'string') throw new Error('Missing loopback port') + const url = 'http://127.0.0.1:' + address.port + const hooks = await openAgyTurnHooks([{ name: 'agent_code', url, headers: {}, bearerToken: 'local-test-token', tldrHooks: { baseUrl: url } }], () => 'local-pane') + try { + const raw = await readFile(join(hooks!.workspace, '.agents', 'hooks.json'), 'utf8') + expect(raw).not.toContain('local-test-token') + const command = JSON.parse(raw)['agent-code-reporting'].PreInvocation[0].command + const child = spawn('/bin/sh', ['-c', command]) + const exited = once(child, 'close') + child.stdin.end(JSON.stringify({ conversationId: 'local-pane', lastUserInput: 'private-example' })) + const chunks = [] + for await (const chunk of child.stdout) chunks.push(chunk) + expect((await exited)[0]).toBe(0) + expect(JSON.parse(Buffer.concat(chunks).toString())).toEqual({ injectSteps: [{ systemMessage: { systemMessage: 'Report your goal.' } }] }) + expect(seen).toEqual([['/user-prompt-submit', 'Bearer local-test-token', '{}']]) + } finally { + await hooks?.close() + host.closeAllConnections() + host.close() + } +}) + +it('pauses on an interrupted turn or failed stop and accepts the next turn', async () => { + const send = vi.fn[1]>(async () => ({})) + const activity = vi.fn() + const observe = agyTurnObserver(() => 'pane', send, activity) + const input = { conversationId: 'pane', fullyIdle: true } + await observe('/pre', input) + await observe('/stop', { ...input, terminationReason: 'error' }) + await observe('/pre', input) + send.mockRejectedValueOnce(new Error('Host closed')) + await expect(observe('/stop', { ...input, terminationReason: 'model_stop' })).rejects.toThrow('Host closed') + await observe('/pre', input) + expect(activity.mock.calls).toEqual([[true], [false, true], [true], [false, true], [true]]) +}) diff --git a/src/providers/antigravity/runtime/turnHooks.ts b/src/providers/antigravity/runtime/turnHooks.ts new file mode 100644 index 000000000..e5ded2345 --- /dev/null +++ b/src/providers/antigravity/runtime/turnHooks.ts @@ -0,0 +1,130 @@ +import { createServer, type IncomingMessage } from 'node:http' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tldrHookServer } from '@providers/shared/runtime/tldrHooks.js' +import type { BuiltInMcpServerConfig } from '@mcp/shared/types.js' + +type HookResult = { decision?: string; reason?: string; hookSpecificOutput?: { additionalContext?: string } } +type TurnActivity = (active: boolean, interrupted?: true) => void +type HookEvent = 'user-prompt-submit' | 'post-tool-use' | 'stop' + +async function readHookInput(request: IncomingMessage): Promise> { + const chunks: Buffer[] = [] + let size = 0 + for await (const chunk of request) { + size += chunk.length + if (size > 1024 * 1024) throw new Error('Hook input too large') + chunks.push(chunk) + } + return JSON.parse(Buffer.concat(chunks).toString('utf8')) +} + +/** Translate the CLI's execution loop into Agent Code's reporting boundaries. A model + * can make several invocations per user turn. Child conversations inherit workspace hooks. */ +export function agyTurnObserver(getId: () => string | null, send: (event: HookEvent) => Promise, activity: TurnActivity) { + let open: string | null = null + return async (path: string, input: Record) => { + const id = getId() + if (!id || input?.conversationId !== id) return {} + if (path === '/pre' && open !== id) { + open = id + activity(true) + let result: HookResult + try { + result = await send('user-prompt-submit') + } catch (error) { + open = null + activity(false, true) + throw error + } + const message = result.hookSpecificOutput?.additionalContext + return message ? { injectSteps: [{ systemMessage: { systemMessage: message } }] } : {} + } + if (path === '/tool') { + await send('post-tool-use') + } else if (path === '/stop' && open === id && input.fullyIdle === true) { + // An interruption is not a successful completion and must not schedule another + // model turn. Clear local busy state so the user can type again. + let continuing = false + let interrupted = true + try { + if (input.terminationReason === 'model_stop') { + const result = await send('stop') + interrupted = false + if (result.decision === 'block') { + continuing = true + return { decision: 'continue', reason: result.reason } + } + } + } finally { + if (!continuing) { + open = null + if (interrupted) activity(false, true) + else activity(false) + } + } + } + return {} + } +} + +export async function openAgyTurnHooks(servers: readonly BuiltInMcpServerConfig[], getId: () => string | null, activity: TurnActivity = () => {}) { + const host = tldrHookServer(servers) + if (!host) return null + // macOS AF_UNIX paths have a 104-byte limit; the per-user TMPDIR can use nearly + // all of it. mkdtemp makes a private directory underneath the short system path. + const root = await mkdtemp('/tmp/agent-code-agy-hooks-') + const socketPath = join(root, 'hooks.sock') + const workspace = join(root, 'workspace') + const observe = agyTurnObserver(getId, async event => { + const response = await fetch(`${host.tldrHooks.baseUrl}/${event}`, { + method: 'POST', headers: { Authorization: `Bearer ${host.bearerToken}`, 'content-type': 'application/json' }, + // Keep the provider's prompt, transcript path, tool arguments, and outputs inside + // its own hook process. The host only needs to know which boundary fired. + body: '{}', redirect: 'error', signal: AbortSignal.timeout(4000), + }) + if (!response.ok) throw new Error('Reporting hook unavailable') + return await response.json() as HookResult + }, activity) + let pending = Promise.resolve() + const listener = createServer(async (request, response) => { + let result = {} + try { + if (request.method === 'POST') { + const input = await readHookInput(request) + // Serialize the state transition as well as the HTTP request. Two simultaneous + // stop notifications must not schedule two continuations of one turn. + const handled = pending.then(() => observe(request.url ?? '', input)) + pending = handled.then(() => {}, () => {}) + result = await handled + } + } catch { /* Reporting is best effort; an unavailable hook must never strand a turn. */ } + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify(result)) + }) + const close = async () => { + listener.close() + listener.closeAllConnections() + await rm(root, { recursive: true, force: true, maxRetries: 2 }).catch(() => {}) + } + try { + await new Promise((resolve, reject) => { + listener.once('error', reject) + listener.listen(socketPath, resolve) + }) + const handler = (path: string) => ({ + type: 'command', timeout: 6, + command: `/usr/bin/curl --silent --max-time 5 --unix-socket '${socketPath}' --data-binary @- http://localhost/${path}`, + }) + await mkdir(join(workspace, '.agents'), { recursive: true }) + await writeFile(join(workspace, '.agents', 'hooks.json'), JSON.stringify({ + 'agent-code-reporting': { + PreInvocation: [handler('pre')], PostToolUse: [{ matcher: '*', hooks: [handler('tool')] }], Stop: [handler('stop')], + }, + }), { mode: 0o600 }) + return { workspace, close } + } catch (error) { + await close() + throw error + } +} diff --git a/src/providers/antigravity/runtime/userMcpEntries.ts b/src/providers/antigravity/runtime/userMcpEntries.ts new file mode 100644 index 000000000..11598211e --- /dev/null +++ b/src/providers/antigravity/runtime/userMcpEntries.ts @@ -0,0 +1,22 @@ +import { claudeUserMcpEntries } from '@providers/shared/runtime/userMcpLaunch.js' +import type { ResolvedUserMcpServer } from '@shared/userMcp/types.js' +import { isStringArray, isStringRecord, providerSupportForEntry } from '@shared/userMcp/validate.js' + +export type AntigravityUserMcpConfig = + | { command: string; args: string[]; env: Record } + | { serverUrl: string; headers: Record } + +export function resolveAntigravityUserMcpEntries(servers: readonly ResolvedUserMcpServer[]): Array<{ name: string; config: AntigravityUserMcpConfig }> { + // Both launchers receive the same already-approved entry. Reuse substitution so + // missing secrets never turn into empty headers, and keep values on their own server. + const { entries } = claudeUserMcpEntries(servers.filter(server => providerSupportForEntry(server.entry).antigravity.ok)) + const result: Array<{ name: string; config: AntigravityUserMcpConfig }> = [] + for (const [name, entry] of Object.entries(entries)) { + if (typeof entry.command === 'string') { + result.push({ name, config: { command: entry.command, args: isStringArray(entry.args) ? entry.args : [], env: isStringRecord(entry.env) ? entry.env : {} } }) + } else if (typeof entry.url === 'string') { + result.push({ name, config: { serverUrl: entry.url, headers: isStringRecord(entry.headers) ? entry.headers : {} } }) + } + } + return result +} diff --git a/src/providers/registry.main.ts b/src/providers/registry.main.ts index 9bd5d1b27..1f8830380 100644 --- a/src/providers/registry.main.ts +++ b/src/providers/registry.main.ts @@ -26,7 +26,7 @@ import { getToolPath } from '@main/setup/toolchain.js' import { AntigravityTerminalSession } from '@providers/antigravity/runtime/antigravityTerminalSession.js' import { AntigravitySession } from '@providers/antigravity/runtime/antigravitySession.js' import { deliverAntigravityPrompt } from '@providers/antigravity/runtime/promptDelivery.js' -import { discoverAntigravitySkillRoots } from '@providers/antigravity/runtime/skillDiscovery.js' +import { antigravityPersonalSkills, discoverAntigravitySkillRoots } from '@providers/antigravity/runtime/skillDiscovery.js' import { antigravityTranscriptLocator, loadAntigravityHistoryChunk, @@ -249,11 +249,9 @@ const antigravityMain: MainProviderConfig = { id: 'antigravity', name: 'Antigravity', discoverSkillRoots: discoverAntigravitySkillRoots, - // agy's personal skill folder is undocumented (skillDiscovery.ts); claiming - // a location agy may not read would show deployed skills that never load. personalAgentSkills: { - supported: false, - reason: 'Antigravity reads project skills from .agents/skills; its personal skill folder is not documented, so Agent Code does not deploy personal skills to it.', + supported: true, + locations: [{ id: 'antigravity-personal-skills', resolveDirectory: antigravityPersonalSkills }], }, createSession: (opts) => new AntigravitySession(opts), createTerminalSession: (opts) => new AntigravityTerminalSession(opts), diff --git a/src/providers/registry.renderer.capabilities.ts b/src/providers/registry.renderer.capabilities.ts index 745b4d226..87278880a 100644 --- a/src/providers/registry.renderer.capabilities.ts +++ b/src/providers/registry.renderer.capabilities.ts @@ -346,7 +346,7 @@ export type ComposerSubmitIo = { input: string draftImages: Array<{ base64Data: string; mediaType: string; filename?: string }> send: (data: string, pasteId?: string) => Promise - deliverPrompt: (prompt: string, imagePaths?: string[]) => Promise + deliverPrompt: (prompt: string, imagePaths?: string[], options?: import('@shared/types/providerConfig').PromptDeliveryOptions) => Promise pasteId: string } @@ -482,9 +482,8 @@ const antigravityCapabilities: RendererProviderCapabilities = { isTypedUserPrompt: isAntigravityTypedUserPrompt, typedUserPromptText: text => text, composerSubmit: antigravityComposerSubmit, - // ACP prompts carry images (agy advertises promptCapabilities.image), but - // the composer→main path for images is Claude-specific today; text first. - supportsImageAttachments: false, + // The ACP launch also checks the installed CLI’s advertised image capability. + supportsImageAttachments: true, // The user row is committed when the session cuts it at prompt time, right // after acceptance; the echo bridges the IPC gap and reconciles by text. usesOptimisticUserEcho: true, diff --git a/src/providers/shared/featureCapabilities.ts b/src/providers/shared/featureCapabilities.ts index c3b8f8328..641cb3804 100644 --- a/src/providers/shared/featureCapabilities.ts +++ b/src/providers/shared/featureCapabilities.ts @@ -193,11 +193,10 @@ const FEATURES_BY_KIND: Record = // SAME conversation in agy's own TUI: ACP and the TUI share one store // (session/list returns sessions created by either). // - // Rewind, Duplicate and switching are OFF: each needs to WRITE a - // conversation agy will resume, and agy stores conversations in a private, - // undocumented SQLite schema (~/.gemini/antigravity-cli/conversations/) that - // a closed, self-updating binary owns. Offering them would hand the user - // commands that no-op or corrupt. + // The interactive TUI offers /fork and /rewind. agy 1.5.18 ACP returns + // JSON-RPC -32601 for session/fork, session/rewind and session/import. The + // app's durable conversation actions require named targets and a verified + // outcome, even when the pane is parked. A TUI picker cannot supply that contract. antigravity: { transcriptRewind: false, transcriptDuplicate: false, diff --git a/src/providers/shared/runtime/builtInMcpLaunch.ts b/src/providers/shared/runtime/builtInMcpLaunch.ts index 4aeb470ed..bc7a68561 100644 --- a/src/providers/shared/runtime/builtInMcpLaunch.ts +++ b/src/providers/shared/runtime/builtInMcpLaunch.ts @@ -181,7 +181,7 @@ export async function createPrivateClaudeMcpConfig( if (servers.length === 0 && Object.keys(userEntries).length === 0) return null // The pid in the prefix lets sweepStalePrivateMcpConfigs tell a crashed // run's leftovers from a live instance's files. - const directory = await mkdtemp(join(tmpdir(), `${PRIVATE_MCP_CONFIG_PREFIX}${process.pid}-`)) + const directory = await createPrivateMcpDirectory() const path = join(directory, 'mcp.json') const document = { mcpServers: Object.fromEntries([ @@ -219,6 +219,12 @@ export async function createPrivateClaudeMcpConfig( const PRIVATE_MCP_CONFIG_PREFIX = 'agent-code-mcp-' +/** Both file-configured providers participate in the same process-owned crash sweep. */ +export function createPrivateMcpDirectory(): Promise { + return mkdtemp(join(tmpdir(), `${PRIVATE_MCP_CONFIG_PREFIX}${process.pid}-`)) +} + + /** * Remove private MCP config directories left behind by a run that crashed. * diff --git a/src/remote-client/src/WebSocketSessionFeed.ts b/src/remote-client/src/WebSocketSessionFeed.ts index 2d048135b..c93cb4185 100644 --- a/src/remote-client/src/WebSocketSessionFeed.ts +++ b/src/remote-client/src/WebSocketSessionFeed.ts @@ -345,11 +345,12 @@ export class WebSocketSessionFeed implements SessionFeed { prompt: string, imagePaths?: string[], _deliveryId?: string, + options?: import('@shared/types/providerConfig.js').PromptDeliveryOptions, ): Promise { - if (imagePaths && imagePaths.length > 0) { + if (imagePaths?.length || options?.inlineImages?.length) { return { ok: false, stage: 'before-write', code: 'missing-capability', - message: 'Remote image-path delivery is not supported', retrySafe: true, + message: 'Remote image delivery is not supported', retrySafe: true, disposition: 'retry-after-resolve', promptWritten: false, enterWritten: false, } diff --git a/src/renderer/src/features/mcp/controlReference.ts b/src/renderer/src/features/mcp/controlReference.ts index 4c6afe64b..1deddeda1 100644 --- a/src/renderer/src/features/mcp/controlReference.ts +++ b/src/renderer/src/features/mcp/controlReference.ts @@ -17,7 +17,7 @@ export const controlReference = [ ], outcome: 'New agents, and existing agents on their next reload, launch with the chosen servers. Agent Code never writes the CLIs\' own config files.', cautions: - 'User servers reach Claude and Codex only; OpenCode and Grok get built-in servers only. Codex cannot use SSE servers, and a user server whose name is already in the user\'s Codex config.toml is skipped for Codex. A server that cannot attach (missing secret, invalid config, enterprise Claude MCP policy) is left out of that launch with a notice; the agent still starts. Secrets are passed to the MCP server through the agent process environment, so the agent\'s own tools can read them. Changes need an agent reload. OAuth servers sign in through each CLI (codex mcp login, Claude /mcp).', + 'User servers can attach to Claude, Codex and Antigravity. Antigravity accepts stdio and Streamable HTTP in both views. Codex cannot use SSE servers, and a user server whose name is already in the user\'s Codex config.toml is skipped for Codex. A server that cannot attach (missing secret, invalid config, enterprise Claude MCP policy) is left out of that launch with a notice; the agent still starts. Each provider receives its own launch configuration. Changes need an agent reload. OAuth servers sign in through each CLI (codex mcp login, Claude or Antigravity /mcp).', commandIds: ['mcp-servers', 'add-mcp-server', 'agent-mcp-servers'], }, ] satisfies FeatureReference[] diff --git a/src/renderer/src/features/mcp/ui/AgentMcpServersModal.renderer.test.tsx b/src/renderer/src/features/mcp/ui/AgentMcpServersModal.renderer.test.tsx index 228f73135..8376a8690 100644 --- a/src/renderer/src/features/mcp/ui/AgentMcpServersModal.renderer.test.tsx +++ b/src/renderer/src/features/mcp/ui/AgentMcpServersModal.renderer.test.tsx @@ -23,14 +23,14 @@ const beeper: UserMcpServerView = { id: 'srv-beeper', name: 'beeper', enabled: true, - providers: { claude: false, codex: true }, + providers: { claude: false, codex: true, antigravity: false }, entry: { type: 'http', url: 'http://localhost:23373/v0/mcp' }, inputs: [], transport: 'http', summary: 'localhost:23373/v0/mcp', secrets: {}, problems: [], - support: { claude: { ok: true }, codex: { ok: true } }, + support: { antigravity: { ok: true }, claude: { ok: true }, codex: { ok: true } }, } function snapshot(servers: UserMcpServerView[]): UserMcpSnapshot { diff --git a/src/renderer/src/features/mcp/ui/McpServerDialog.tsx b/src/renderer/src/features/mcp/ui/McpServerDialog.tsx index ce8b3657a..24c621369 100644 --- a/src/renderer/src/features/mcp/ui/McpServerDialog.tsx +++ b/src/renderer/src/features/mcp/ui/McpServerDialog.tsx @@ -25,7 +25,7 @@ import type { import { USER_MCP_PROVIDERS, type UserMcpSecretState } from '@shared/userMcp/types' import { providerSupportForEntry, transportOf, userMcpDestination } from '@shared/userMcp/validate' -const PROVIDER_LABEL: Record = { claude: 'Claude', codex: 'Codex' } +const PROVIDER_LABEL: Record = { claude: 'Claude', codex: 'Codex', antigravity: 'Antigravity' } /** * Add / Edit MCP server (#1143). Paste-first on purpose: "any MCP server" @@ -163,7 +163,7 @@ function AddServer({ onDone, onCancel, onDirty, onSaving }: { onDone: () => void const fresh: Draft = { include: true, name: candidate.name, - providers: { claude: support.claude.ok, codex: support.codex.ok }, + providers: { claude: support.claude.ok, codex: support.codex.ok, antigravity: support.antigravity.ok }, secrets: { ...candidate.pendingSecrets }, } const index = before.candidates.findIndex(old => old.name === candidate.name) @@ -176,6 +176,7 @@ function AddServer({ onDone, onCancel, onDirty, onSaving }: { onDone: () => void providers: { claude: old.providers.claude && support.claude.ok, codex: old.providers.codex && support.codex.ok, + antigravity: old.providers.antigravity && support.antigravity.ok, }, // Values typed or lifted earlier survive for every secret the new // parse still references; a value pasted literally again wins. @@ -425,6 +426,7 @@ function EditServer({ server, onDone, onCancel, onDirty, onSaving }: { server: U providers: { claude: providers.claude && support.claude.ok, codex: providers.codex && support.codex.ok, + antigravity: providers.antigravity && support.antigravity.ok, }, entry: parsed.entry, inputs, diff --git a/src/renderer/src/features/mcp/ui/McpServersRow.renderer.test.tsx b/src/renderer/src/features/mcp/ui/McpServersRow.renderer.test.tsx index c97387044..119ade976 100644 --- a/src/renderer/src/features/mcp/ui/McpServersRow.renderer.test.tsx +++ b/src/renderer/src/features/mcp/ui/McpServersRow.renderer.test.tsx @@ -24,14 +24,14 @@ function server(overrides: Partial = {}): UserMcpServerView { id: 'srv-beeper', name: 'beeper', enabled: true, - providers: { claude: true, codex: false }, + providers: { claude: true, codex: false, antigravity: false }, entry: { type: 'http', url: 'http://localhost:23373/v0/mcp', headers: { Authorization: 'Bearer ${input:beeper-authorization}' } }, inputs: [{ id: 'beeper-authorization', description: 'Header Authorization' }], transport: 'http', summary: 'localhost:23373/v0/mcp', secrets: { 'beeper-authorization': { set: true, hint: '1c7d' } }, problems: [], - support: { claude: { ok: true }, codex: { ok: true } }, + support: { antigravity: { ok: true }, claude: { ok: true }, codex: { ok: true } }, ...overrides, } } @@ -92,7 +92,7 @@ describe('Settings → MCP grid', () => { it('shows an SSE server as Claude-only, with the reason, instead of a Codex checkbox', () => { useUserMcpStore.setState({ snapshot: { - servers: [server({ name: 'linear', transport: 'sse', support: { claude: { ok: true }, codex: { ok: false, reason: 'Codex does not support SSE servers' } } })], + servers: [server({ name: 'linear', transport: 'sse', support: { antigravity: { ok: true }, claude: { ok: true }, codex: { ok: false, reason: 'Codex does not support SSE servers' } } })], native: [], claudeManagedPolicy: false, }, @@ -193,7 +193,7 @@ describe('MCP server dialog', () => { useAppStore.setState({ mcpServerDialog: { mode: 'edit', serverId: 'srv-beeper' } }) render() act(() => { - useUserMcpStore.setState({ snapshot: { servers: [server({ providers: { claude: true, codex: true } })], native: [], claudeManagedPolicy: false } }) + useUserMcpStore.setState({ snapshot: { servers: [server({ providers: { claude: true, codex: true, antigravity: false } })], native: [], claudeManagedPolicy: false } }) }) expect(screen.getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true) expect(screen.getByText(/changed in another window or by an agent/)).toBeTruthy() @@ -280,7 +280,7 @@ describe('MCP server dialog', () => { await vi.waitFor(() => expect(api.userMcpSave).toHaveBeenCalledTimes(1)) expect(api.userMcpSave.mock.calls[0]![0]).toMatchObject({ name: 'beeper', - providers: { claude: true, codex: true }, + providers: { claude: true, codex: true, antigravity: true }, secrets: { 'beeper-authorization': TOKEN }, }) // Closing is the store's job; Radix animates the DOM out asynchronously. diff --git a/src/renderer/src/features/mcp/ui/McpServersRow.tsx b/src/renderer/src/features/mcp/ui/McpServersRow.tsx index c2a6a1a72..5c9c39623 100644 --- a/src/renderer/src/features/mcp/ui/McpServersRow.tsx +++ b/src/renderer/src/features/mcp/ui/McpServersRow.tsx @@ -10,7 +10,7 @@ import { BUILT_IN_MCP_SERVERS } from '@renderer/features/mcp/lib/builtInServers' import { applyUserMcpResult, useUserMcpSnapshot } from '@renderer/features/mcp/store' import { useEnabledAgentProviderKinds } from '@renderer/features/providers/store' import { AGENT_PROVIDER_KINDS, isRemoteProviderKind, type AgentProviderKind } from '@shared/types/providerKind' -import { isUserMcpProvider, USER_MCP_PROVIDERS, type NativeMcpServer, type UserMcpServerView } from '@shared/userMcp/types' +import { isUserMcpProvider, USER_MCP_PROVIDERS, type NativeMcpServer, type UserMcpProvider, type UserMcpServerView } from '@shared/userMcp/types' type Props = { settings: Settings @@ -171,7 +171,7 @@ function UserServerRow({ providers: AgentProviderKind[] columns: string onToggleEnabled: () => void - onToggleProvider: (kind: 'claude' | 'codex', on: boolean) => void + onToggleProvider: (kind: UserMcpProvider, on: boolean) => void onEdit: () => void }) { const unsetSecrets = Object.values(server.secrets).filter(secret => !secret.set).length diff --git a/src/renderer/src/features/sessionFeed/IpcSessionFeed.ts b/src/renderer/src/features/sessionFeed/IpcSessionFeed.ts index 94516fd9e..7089dd46c 100644 --- a/src/renderer/src/features/sessionFeed/IpcSessionFeed.ts +++ b/src/renderer/src/features/sessionFeed/IpcSessionFeed.ts @@ -40,8 +40,8 @@ export const ipcSessionFeed: SessionFeed = { onSessionSubAgents: cb => window.api.onSessionSubAgents(cb), onSessionExit: cb => window.api.onSessionExit(cb), sendInput: (sessionId, data, pasteId) => window.api.sendInput(sessionId, data, pasteId), - deliverPrompt: (sessionId, prompt, imagePaths, deliveryId) => - window.api.deliverPrompt(sessionId, prompt, imagePaths, deliveryId), + deliverPrompt: (sessionId, prompt, imagePaths, deliveryId, options) => + window.api.deliverPrompt(sessionId, prompt, imagePaths, deliveryId, ...(options ? [options] as const : [])), resolveCondition: (sessionId, action) => window.api.resolveCondition(sessionId, action), // The one place this object does more than rename: the contract has one // history call and the preload bridge has two, keyed by whether a cursor diff --git a/src/renderer/src/features/skills/ui/Skills.renderer.test.tsx b/src/renderer/src/features/skills/ui/Skills.renderer.test.tsx index 7a7277342..33c75624f 100644 --- a/src/renderer/src/features/skills/ui/Skills.renderer.test.tsx +++ b/src/renderer/src/features/skills/ui/Skills.renderer.test.tsx @@ -57,8 +57,7 @@ function installedSkill(overrides: Partial = {}): Agent // What main reports today (targets.ts: every provider whose // personalAgentSkills is unsupported, sorted): Grok, and Hermes, whose skills // live on the user's own server. -// What main reports (agentCodeConventions targets): Antigravity, Grok and Hermes declare personal skills unsupported. -const UNSUPPORTED: AgentCodeInstalledSkillsSnapshot['unsupportedProviders'] = ['antigravity', 'grok', 'hermes'] +const UNSUPPORTED: AgentCodeInstalledSkillsSnapshot['unsupportedProviders'] = ['grok', 'hermes'] const installed: AgentCodeInstalledSkillsSnapshot = { revision: 7, skills: [installedSkill()], @@ -115,7 +114,7 @@ beforeEach(() => { vi.clearAllMocks() Object.assign(window, { api: { ...window.api, ...api } }) useProviderEnablementStore.getState().setSnapshot({ - entries: ['claude', 'codex', 'opencode', 'grok', 'pi'].map(kind => ({ kind, enabled: kind !== 'pi', installed: true, because: 'detected' })), + entries: ['claude', 'codex', 'opencode', 'grok', 'pi', 'antigravity'].map(kind => ({ kind, enabled: kind !== 'pi', installed: true, because: 'detected' })), } as unknown as ProviderEnablementSnapshot) useSkillsStore.setState({ installed, custom, external, updates: {}, loadError: null }) }) @@ -156,6 +155,7 @@ describe('Settings → Skills grid (#1161)', () => { it('shows columns for enabled providers that support skills, never Grok', async () => { render() await waitFor(() => expect(api.auditAgentCodeInstalledSkills).toHaveBeenCalled()) + expect(screen.getByRole('checkbox', { name: 'pdf for Antigravity agents' })).toBeTruthy() expect(screen.getByRole('checkbox', { name: 'pdf for Claude agents' })).toBeTruthy() expect(screen.getByRole('checkbox', { name: 'pdf for Codex agents' })).toBeTruthy() expect(screen.queryByRole('checkbox', { name: /for Grok agents/ })).toBeNull() @@ -171,7 +171,7 @@ describe('Settings → Skills grid (#1161)', () => { skillId: 'skill-pdf', // Pi stays chosen even though its column is hidden: hiding a provider // must never silently drop it from a skill. - providers: ['codex', 'opencode', 'pi'], + providers: ['codex', 'opencode', 'pi', 'antigravity'], })) }) diff --git a/src/renderer/src/workspace/hook/actions/pane.ts b/src/renderer/src/workspace/hook/actions/pane.ts index 655164647..8482d9d02 100644 --- a/src/renderer/src/workspace/hook/actions/pane.ts +++ b/src/renderer/src/workspace/hook/actions/pane.ts @@ -1397,8 +1397,8 @@ export function usePaneActions( const sessionId = await sessionActions.spawn(cwd, { kind: params.kind, - // An orchestrated agy worker needs the per-pane MCP endpoint supplied - // by ACP. Only a caller explicitly asking for the terminal opts out. + // Automated workers default to ACP for structured prompt acknowledgments. + // A caller requesting the native prompt keeps the same pane tool grants. providerRuntime: params.kind === 'antigravity' ? providerRuntime ?? null : providerRuntime, resumeSessionId, builtInMcpDomains: params.builtInMcpDomains, diff --git a/src/renderer/src/workspace/tile-tree/TileLeaf/useClaudeImagePaste.renderer.test.tsx b/src/renderer/src/workspace/tile-tree/TileLeaf/useClaudeImagePaste.renderer.test.tsx index 47507da93..7d286e4d6 100644 --- a/src/renderer/src/workspace/tile-tree/TileLeaf/useClaudeImagePaste.renderer.test.tsx +++ b/src/renderer/src/workspace/tile-tree/TileLeaf/useClaudeImagePaste.renderer.test.tsx @@ -38,7 +38,7 @@ function paste(options: { image?: boolean; text?: string; html?: string; items?: } } -function hook(provider: 'codex' | 'opencode' | 'grok' | 'pi' | 'claude') { +function hook(provider: 'codex' | 'opencode' | 'grok' | 'pi' | 'claude' | 'antigravity') { const showToast = vi.fn() const setDraftImages = vi.fn() const { result } = renderHook(() => useClaudeImagePaste({ provider, sessionId: 's1' as never, setDraftImages, showToast })) @@ -93,8 +93,8 @@ describe('pasting an image into a composer that cannot take one', () => { expect(showToast).not.toHaveBeenCalled() }) - it('does not say it for Claude, which takes the image', async () => { - const { handlePaste, showToast, setDraftImages } = hook('claude') + it.each(['claude', 'antigravity'] as const)('accepts the pasted image in the %s composer', async provider => { + const { handlePaste, showToast, setDraftImages } = hook(provider) let answer: unknown await act(async () => { answer = await handlePaste(paste({ image: true })) }) expect(showToast).not.toHaveBeenCalledWith(expect.stringContaining("can't be sent")) diff --git a/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts b/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts index 0ebf66866..f74e75293 100644 --- a/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts +++ b/src/renderer/src/workspace/tile-tree/TileLeaf/useComposerKeybinds.ts @@ -382,9 +382,9 @@ export function useComposerKeybinds({ // protocol). On main's before-write "not a live agent session" reject // the wrapper wakes the SAME SessionId and retries once; every other // failure shape flows through untouched. - deliverPrompt: (prompt, imagePaths) => + deliverPrompt: (prompt, imagePaths, options) => deliverWithWake( - () => feed.deliverPrompt(sessionId, prompt, imagePaths, pasteId), + () => feed.deliverPrompt(sessionId, prompt, imagePaths, pasteId, ...(options ? [options] as const : [])), () => workspace.ensureSessionLive(sessionId, 'tile-leaf.deliver-retry'), ), pasteId, diff --git a/src/shared/lib/inlinePromptImages.test.ts b/src/shared/lib/inlinePromptImages.test.ts new file mode 100644 index 000000000..03eb7ee55 --- /dev/null +++ b/src/shared/lib/inlinePromptImages.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest' +import { validInlinePromptImages } from './inlinePromptImages.js' + +describe('inline image delivery from the composer', () => { + it('bounds bytes and rejects malformed, sparse, external and unsupported content', () => { + const image = { mediaType: 'image/png', base64Data: 'AQ==' } + expect(validInlinePromptImages([image])).toBe(true) + for (const invalid of [ + [], Array(1), [null], Array(5).fill(image), + [{ ...image, mediaType: 'image/svg+xml' }], + [{ ...image, base64Data: '%%%%' }], [{ ...image, base64Data: 'file:///tmp/picture' }], + [{ ...image, base64Data: Buffer.alloc(5 * 1024 * 1024 + 1).toString('base64') }], + ]) expect(validInlinePromptImages(invalid)).toBe(false) + }) +}) diff --git a/src/shared/lib/inlinePromptImages.ts b/src/shared/lib/inlinePromptImages.ts new file mode 100644 index 000000000..b9c78501e --- /dev/null +++ b/src/shared/lib/inlinePromptImages.ts @@ -0,0 +1,14 @@ +import type { InlinePromptImage } from '@shared/types/providerConfig.js' + +/** Recheck the desktop IPC payload in main. Base64 padding can change the decoded + * size by two bytes; checking the encoded length alone accepts oversized images. */ +export function validInlinePromptImages(value: unknown): value is InlinePromptImage[] { + return Array.isArray(value) && value.length > 0 && value.length <= 4 && Array.from(value).every(image => { + if (!image || !['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(image.mediaType)) return false + const data = image.base64Data + const limit = 5 * 1024 * 1024 + if (typeof data !== 'string' || !data.length || data.length % 4 || data.length > 4 * Math.ceil(limit / 3)) return false + const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0 + return data.length * 3 / 4 - padding <= limit && /^[A-Za-z0-9+/]+={0,2}$/.test(data) + }) +} diff --git a/src/shared/sessionFeed/SessionFeed.ts b/src/shared/sessionFeed/SessionFeed.ts index 936d2632a..18448ecd5 100644 --- a/src/shared/sessionFeed/SessionFeed.ts +++ b/src/shared/sessionFeed/SessionFeed.ts @@ -112,6 +112,7 @@ export interface SessionFeed { prompt: string, imagePaths?: string[], deliveryId?: string, + options?: import('@shared/types/providerConfig.js').PromptDeliveryOptions, ): Promise /** Resolve a live provider condition (permission prompt, trust dialog, diff --git a/src/shared/types/providerConfig.ts b/src/shared/types/providerConfig.ts index fcab435e5..758499475 100644 --- a/src/shared/types/providerConfig.ts +++ b/src/shared/types/providerConfig.ts @@ -415,7 +415,12 @@ export type MainProviderConfig = { deliverPrompt: (io: PromptDeliveryIo) => Promise } +export type InlinePromptImage = { mediaType: string; base64Data: string } + export type PromptDeliveryOptions = { + /** Clipboard data for structured prompt protocols. Never resolve renderer-supplied paths + * into bytes in main: choosing pixels must not grant a generic filesystem read. */ + inlineImages?: InlinePromptImage[] /** App-generated tasks must not submit an unrelated native terminal draft. * Providers must refuse when their transport cannot preserve it or establish * that the active composer is empty. This is stricter than legacy delivery. */ diff --git a/src/shared/types/session.ts b/src/shared/types/session.ts index d3ee6b879..91cac6a90 100644 --- a/src/shared/types/session.ts +++ b/src/shared/types/session.ts @@ -428,6 +428,8 @@ export type AgentTranscriptObservationMetadata = { * actively working, plus an optional human-readable status verb. */ export type AgentProcessState = { active: boolean + /** The provider explicitly cancelled the turn or lost its reporting boundary. */ + turnInterrupted?: true status?: string } @@ -768,6 +770,7 @@ export interface AgentSession extends AgentSessionEmitter { * for a Telegram turn, or a slash command main answered itself). The * delivery adapter reports that as a `queue` acceptance so the composer * settles its optimistic "submitting" phase. */ + deliverPromptWithImages?(text: string, images: readonly import('./providerConfig.js').InlinePromptImage[]): Promise<{ turnStarted: boolean }> deliverPromptText?(text: string): Promise } diff --git a/src/shared/userMcp/types.ts b/src/shared/userMcp/types.ts index 24bf0620d..db5733a94 100644 --- a/src/shared/userMcp/types.ts +++ b/src/shared/userMcp/types.ts @@ -5,14 +5,13 @@ /** * Providers that can receive a user MCP server today. * - * WHY only Claude and Codex (not every AgentProviderKind): these are the two - * launchers whose MCP injection semantics were verified against their source + * Keep this list closed to launchers whose MCP injection semantics were verified against their source * and installed binaries. OpenCode and Grok also carry built-in MCP, but a user * server there needs its own translator and evidence. Keeping this list closed * means a new provider shows an honest "not supported yet" instead of silently * receiving a config shape nobody checked. */ -export const USER_MCP_PROVIDERS = ['claude', 'codex'] as const +export const USER_MCP_PROVIDERS = ['claude', 'codex', 'antigravity'] as const export type UserMcpProvider = (typeof USER_MCP_PROVIDERS)[number] export function isUserMcpProvider(value: unknown): value is UserMcpProvider { @@ -170,7 +169,8 @@ export type UserMcpSaveInput = { id?: string name: string enabled: boolean - providers: Record + // Older saved forms and clients predate the Antigravity column. + providers: Record<'claude' | 'codex', boolean> & { antigravity?: boolean } entry: UserMcpServerEntry inputs: UserMcpInput[] /** Secret values to set with this save (inputId → value). Values for inputs diff --git a/src/shared/userMcp/userMcp.test.ts b/src/shared/userMcp/userMcp.test.ts index 9d76e394b..5efa97892 100644 --- a/src/shared/userMcp/userMcp.test.ts +++ b/src/shared/userMcp/userMcp.test.ts @@ -141,7 +141,7 @@ describe('coerceUserMcpDocument', () => { }) expect(doc.servers.map(server => server.id)).toEqual(['a1', 'b2']) expect(doc.servers[0]!.entry).toMatchObject({ oauth: { clientId: 'c' } }) - expect(doc.servers[0]!.providers).toEqual({ claude: true, codex: false }) + expect(doc.servers[0]!.providers).toEqual({ claude: true, codex: false, antigravity: false }) expect(doc.servers[1]!.entry).toEqual({}) }) diff --git a/src/shared/userMcp/validate.ts b/src/shared/userMcp/validate.ts index 321b01857..0c09604e6 100644 --- a/src/shared/userMcp/validate.ts +++ b/src/shared/userMcp/validate.ts @@ -212,6 +212,13 @@ export const USER_MCP_HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+^_`|~-]+$/ * transport. Every UI surface and launch uses this one. */ export function providerSupportForEntry(entry: unknown): Record { const support = providerSupport(transportOf(entry)) + if (support.antigravity.ok && isPlainObject(entry)) { + // An ignored cwd, tool allowlist, or auth setting would attach a different server + // than the one the user reviewed. Report unsupported fields before resolving secrets. + const fields = transportOf(entry) === 'stdio' ? ['type', 'command', 'args', 'env'] : ['type', 'url', 'headers'] + const unsupported = Object.keys(entry).find(key => !fields.includes(key)) + if (unsupported) support.antigravity = { ok: false, reason: `Antigravity cannot apply the MCP setting "${unsupported}"` } + } if (support.codex.ok && isPlainObject(entry) && isStringRecord(entry.env)) { const protectedKey = Object.entries(entry.env) .find(([key, value]) => hasInputReference(value) && CODEX_PROTECTED_ENV.test(key))?.[0] @@ -280,6 +287,9 @@ export function providerSupport( ): Record { return { claude: { ok: true }, + antigravity: transport === 'stdio' || transport === 'http' + ? { ok: true } + : { ok: false, reason: 'Antigravity supports stdio and Streamable HTTP servers' }, // Codex speaks stdio and Streamable HTTP only (codex-rs mcp_types.rs has // no SSE transport). Claude still accepts SSE, so an SSE server is // Claude-only rather than invalid. diff --git a/testing/live/antigravity-native-mcp.test.ts b/testing/live/antigravity-native-mcp.test.ts new file mode 100644 index 000000000..16bd3fb7d --- /dev/null +++ b/testing/live/antigravity-native-mcp.test.ts @@ -0,0 +1,71 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { BuiltInMcpHttpHost } from '@mcp/runtime/BuiltInMcpHttpHost' +import { TldrStore } from '@main/tldr/TldrStore' +import { Terminal } from '@xterm/headless' +import { expect, it, vi } from 'vitest' +import { getMainProvider } from '@providers/registry.main' + +// The CLI and both MCP endpoints are real; only Electron's performance recorder +// is unavailable in this Node-run live probe. +vi.mock('@main/performance/PerformanceService.js', () => ({ performanceService: { record: vi.fn() } })) + +// Interactive discovery happens on agy's /mcp screen. The SDK transport test separately +// exercises tool calls without spending model credits or submitting a prompt to an account. +it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('lists only this pane’s tools in native agy, including after resume', async () => { + const directory = await mkdtemp(join(tmpdir(), 'agy-live-reporting-')) + const host = new BuiltInMcpHttpHost() + const cwd = process.env.ANTIGRAVITY_LIVE_CWD ?? process.cwd() + host.setDependencies({ + tldrStore: new TldrStore(join(directory, 'tldr.json')), + goalStore: new TldrStore(join(directory, 'goal.json')), + }) + await host.start() + const open = (pane: 'goal' | 'tldr', resumeSessionId?: string) => { + const builtInMcpServers = host.registerSession({ + sessionId: pane + (resumeSessionId ? '-resumed' : ''), tldrIdentity: pane, + providerKind: 'antigravity', cwd, domains: [pane], + }) + const session = getMainProvider('antigravity').createTerminalSession!({ + cwd, binary: process.env.AGY_BINARY ?? 'agy', + resumeSessionId, cols: 110, rows: 32, + builtInMcpServers, + }) + const screen = new Terminal({ cols: 110, rows: 32, allowProposedApi: true }) + session.on('pty-data', data => screen.write(data)) + screen.onData(reply => session.write(reply)) + return { + session, screen, + visible: () => Array.from({ length: screen.rows }, (_, i) => + screen.buffer.active.getLine(screen.buffer.active.viewportY + i)?.translateToString(true) ?? '').join('\n'), + } + } + const panes: Array> = [] + async function check(which: 'goal' | 'tldr', resume?: string) { + const pane = open(which, resume) + panes.push(pane) + await pane.session.start() + await expect.poll(pane.visible, { timeout: 15000 }).toContain('for shortcuts') + pane.session.write('/mcp') + await expect.poll(pane.visible).toContain('/mcp') + pane.session.write('\r') + await expect.poll(pane.visible, { timeout: 15000 }).toContain(which === 'goal' ? 'goal_set' : 'tldr_update') + expect(pane.visible()).not.toContain(which === 'goal' ? 'tldr_update' : 'goal_set') + return pane + } + try { + const [first, second] = await Promise.all([check('goal'), check('tldr')]) + const id = first.session.getProviderSessionId?.() + expect(id).toBeTruthy() + expect(second.session.getProviderSessionId?.()).not.toBe(id) + await first.session.stop() + const resumed = await check('goal', id!) + expect(resumed.session.getProviderSessionId?.()).toBe(id) + } finally { + await Promise.all(panes.map(p => p.session.stop())) + for (const pane of panes) pane.screen.dispose() + await host.stop() + await rm(directory, { recursive: true, force: true }) + } +}, 60_000) diff --git a/testing/live/antigravity-reporting.test.ts b/testing/live/antigravity-reporting.test.ts new file mode 100644 index 000000000..65a89bb9f --- /dev/null +++ b/testing/live/antigravity-reporting.test.ts @@ -0,0 +1,33 @@ +import { Terminal } from '@xterm/headless' +import { expect, it } from 'vitest' +import { BuiltInMcpHttpHost } from '@mcp/runtime/BuiltInMcpHttpHost' +import { getMainProvider } from '@providers/registry.main' + +it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('loads pane reporting hooks and its real MCP host in the native CLI', async () => { + const host = new BuiltInMcpHttpHost() + await host.start() + const cwd = process.env.ANTIGRAVITY_LIVE_CWD ?? process.cwd() + const grants = host.registerSession({ sessionId: 'reporting-probe', providerKind: 'antigravity', cwd, domains: ['goal', 'tldr'] }) + const terminal = getMainProvider('antigravity').createTerminalSession!({ + binary: process.env.AGY_BINARY ?? 'agy', cwd, cols: 110, rows: 35, builtInMcpServers: grants, + }) + const screen = new Terminal({ cols: 110, rows: 35, allowProposedApi: true }) + const text = () => Array.from({ length: screen.rows }, (_, i) => screen.buffer.active.getLine(screen.buffer.active.viewportY + i)?.translateToString(true)).join('\n') + terminal.on('pty-data', data => screen.write(data)) + screen.onData(data => terminal.write(data)) + try { + await terminal.start() + await expect.poll(text, { timeout: 12000 }).toContain('for shortcuts') + terminal.write('/hooks') + await expect.poll(text).toContain('/hooks') + terminal.write('\r') + // The /hooks landing page groups entries by event. It does not show their names. + for (const event of ['PostToolUse', 'PreInvocation', 'Stop']) { + await expect.poll(() => new RegExp(event + '[^\\n]+[1-9][0-9]* hooks?').test(text()), { timeout: 10000 }).toBe(true) + } + } finally { + await terminal.stop() + await host.stop() + screen.dispose() + } +}, 30000) diff --git a/testing/live/antigravity-terminal.test.ts b/testing/live/antigravity-terminal.test.ts index c1b1362ac..8688dcded 100644 --- a/testing/live/antigravity-terminal.test.ts +++ b/testing/live/antigravity-terminal.test.ts @@ -1,5 +1,6 @@ import { Terminal } from '@xterm/headless' import { expect, it } from 'vitest' +import { inspectAgentTranscriptFile } from '@main/agentTranscripts/AgentTranscriptReader' import { getMainProvider } from '@providers/registry.main' // Each fresh TUI allocates an empty conversation in the signed-in agy account. Keep this @@ -31,9 +32,18 @@ it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('opens two native agy p await expect.poll(() => visible().includes('native-terminal-check'), { timeout: 5000 }).toBe(true) first.write('\x15') await expect.poll(() => visible().includes('native-terminal-check')).toBe(false) - first.write('/new') - await expect.poll(() => visible().includes('/new')).toBe(true) - first.write('\r') + const deliver = (prompt: string) => provider.deliverPrompt({ session: first, sessionId: 'native-test', prompt, write: data => first.write(data) !== false }) + first.write('human draft') + expect(await deliver('/new')).toMatchObject({ ok: false, promptWritten: false, enterWritten: false }) + await expect.poll(() => visible().includes('human draft')).toBe(true) + expect(await first.awaitReadyForPrompt?.()).toMatchObject({ kind: 'occupied' }) + first.write('\x15') + await expect.poll(() => visible().includes('? for shortcuts')).toBe(true) + // Local-only command. Its new conversation id proves the real TUI + // accepted Enter after inspecting the pasted command. No model turn. + expect(await first.awaitReadyForPrompt?.()).toMatchObject({ kind: 'ready' }) + const submission = await deliver('/new') + expect(submission).toMatchObject({ ok: true }) await expect.poll(() => first.getProviderSessionId?.(), { timeout: 15000 }).not.toBe(firstId) const newId = first.getProviderSessionId?.() expect(newId).toBeTruthy() @@ -57,3 +67,26 @@ it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('opens two native agy p screen.dispose() } }, 60000) + +it.skipIf(process.env.ANTIGRAVITY_TERMINAL_LIVE !== '1')('reads a newly created native conversation through Agent Code transcript inspection', async () => { + const provider = getMainProvider('antigravity') + const options = { cwd: process.env.ANTIGRAVITY_LIVE_CWD ?? process.cwd(), binary: process.env.AGY_BINARY ?? 'agy' } + const fresh = provider.createSession(options) + let native: ReturnType | undefined + try { + await fresh.start() + const id = fresh.getProviderSessionId?.() + if (!id) throw new Error('agy created no conversation') + await fresh.stop() + native = provider.createTerminalSession!({ ...options, resumeSessionId: id }) + await native.start() + const path = native.getTranscriptFile?.() + if (!path) throw new Error('native agy published no transcript locator') + expect(await inspectAgentTranscriptFile({ path })).toMatchObject({ ok: true, provider: 'antigravity' }) + await native.stop() + expect(await inspectAgentTranscriptFile({ path })).toMatchObject({ ok: false, error: 'file_not_readable' }) + } finally { + await native?.stop() + await fresh.stop() + } +}, 60000)