diff --git a/Cargo.lock b/Cargo.lock index 02cf906267..55446da142 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -459,6 +459,7 @@ dependencies = [ "bibcode-server", "block2", "cairo-rs", + "dirs", "futures-util", "gtk", "if-addrs", diff --git a/README.md b/README.md index 7a92599886..26d24e23b2 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ ## What it is -BiBCode is a desktop app, a browser UI, and a headless server for coding agents. It runs Codex, Claude Code, Cursor (Early Access), and OpenCode side by side, each in its own Git worktree, with the terminals, Git client, pull requests, and CI pipelines for the same project one click away. It runs on macOS, Windows, and Linux, on Apple Silicon, Intel, and ARM64, and it can run on another machine and connect back to your desktop. +BiBCode is a desktop app, a browser UI, and a headless server for coding agents. It runs Codex, Claude Code, Cursor (Early Access), Antigravity (Preview), and OpenCode side by side, each in its own Git worktree, with the terminals, Git client, pull requests, and CI pipelines for the same project one click away. It runs on macOS, Windows, and Linux, on Apple Silicon, Intel, and ARM64, and it can run on another machine and connect back to your desktop. All screenshots below use demo data. @@ -139,6 +139,7 @@ The same release has standalone `bibcode` server archives for each platform, plu > - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login` > - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login` > - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login` +> - Antigravity (Preview, off by default): install the Antigravity CLI and run `agy` to sign in > - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login` Then open BiBCode, add a project, and start a chat. [Getting started](docs/getting-started/quick-start.md) walks through the first launch, and [Workspace UI](docs/user/workspace-ui.md) covers every panel. diff --git a/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts b/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts new file mode 100644 index 0000000000..40d22414e5 --- /dev/null +++ b/apps/desktop/e2e/specs/files-undo-shortcuts.e2e.ts @@ -0,0 +1,1785 @@ +// @effect-diagnostics nodeBuiltinImport:off - Packaged UI tests write fixture files, record evidence and send native input. +// @effect-diagnostics globalTimers:off - The spec waits out the editors' history grouping delay. +// @effect-diagnostics globalDate:off - Preview waits run on timers while WebDriver cannot see the window. +// @effect-diagnostics globalFetch:off - The page reports the preview to the spec while WebDriver cannot. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeHttp from "node:http"; +import type * as NodeNet from "node:net"; +import * as NodePath from "node:path"; + +import { desktopUiPlatform } from "../support/app-lifecycle.ts"; +import { refreshDesktopUiDocument } from "../support/document-navigation.ts"; +import { openCenterTerminal } from "../support/terminal-input.ts"; +import { desktopUiFixture } from "../support/test-project.ts"; +import { + ensureMainSidebarOpen, + mockDesktopUiFolderPicker, + setDesktopUiWindowSize, +} from "../support/ui-state.ts"; + +const projectPath = process.env.BIBCODE_E2E_PROJECT_PATH; +const artifactDirectory = process.env.BIBCODE_E2E_ARTIFACT_DIR; +if (!projectPath || !artifactDirectory) { + throw new Error("The packaged desktop Files undo fixture environment was not prepared."); +} +const preparedProjectPath: string = projectPath; +const evidencePath = NodePath.join(artifactDirectory, "files-undo-matrix.jsonl"); +const platform = desktopUiPlatform(); +// Native input types into whatever session is in front, so only a lab run turns it on. +const nativeInput = process.env.BIBCODE_E2E_NATIVE_INPUT === "1"; +const bundleIdentifier = "com.bibcode.desktop.e2e"; + +const fileViewSelector = "[data-preview-panel-mode]"; +const richEditorSelector = `${fileViewSelector} .rich-markdown-editor [contenteditable="true"]`; +const sourceHostSelector = `${fileViewSelector} diffs-container`; +const composerSelector = '[data-testid="composer-editor"]'; + +type View = "source" | "rendered"; +type Direction = "undo" | "redo"; +type InputPath = "driver" | "keystroke" | "menu"; +type Chord = "primary+z" | "primary+shift+z" | "ctrl+y"; + +interface ProbeEvent { + readonly type: string; + readonly key: string | null; + readonly modifiers: string; + readonly inputType: string | null; + readonly cancelable: boolean; + readonly isTrusted: boolean; + readonly defaultPrevented: boolean; + readonly target: string; +} + +interface EditorState { + readonly text: string; + readonly canUndo: boolean; + readonly canRedo: boolean; +} + +declare global { + interface Window { + __bibcodeUndoProbe?: ProbeEvent[]; + } +} + +function recordEvidence(entry: Record): void { + NodeFS.appendFileSync(evidencePath, `${JSON.stringify({ platform, ...entry })}\n`); +} + +async function openFixtureWorkspace(): Promise { + await ensureMainSidebarOpen(); + const project = browser.$( + `//button[.//span[normalize-space()="${desktopUiFixture.projectName}"]]`, + ); + if (!(await project.isDisplayed())) { + const projectDataLoading = browser.$("//*[normalize-space()='Project data is still loading']"); + if (await projectDataLoading.isExisting()) { + await projectDataLoading.waitForDisplayed({ reverse: true }); + } + const addProject = browser.$('[data-testid="sidebar-add-project-trigger"]'); + await addProject.waitForDisplayed(); + await addProject.click(); + const browseFolder = browser.$( + "//button[@data-add-project-action='true'][.//span[normalize-space()='Browse folder']]", + ); + await browseFolder.waitForDisplayed(); + await mockDesktopUiFolderPicker(preparedProjectPath); + await browseFolder.click(); + } + await project.waitForDisplayed(); + const primaryWorkspace = browser.$( + '//*[@data-thread-item="true"][.//span[normalize-space()="main"]]', + ); + if ((await project.getAttribute("aria-expanded")) !== "true") { + await project.click(); + } + await primaryWorkspace.waitForDisplayed(); + await primaryWorkspace.click(); +} + +async function openFilesSurface(): Promise { + const rightPanel = browser.$("[data-right-panel-tabbar]"); + if (!(await rightPanel.isDisplayed())) { + const toggle = browser.$('button[aria-label^="Toggle right panel"]'); + await toggle.waitForDisplayed(); + await toggle.click(); + await rightPanel.waitForDisplayed(); + } + const existingTab = browser.$( + '//*[@data-right-panel-tab-list]//button[normalize-space()="Files"]', + ); + if (await existingTab.isDisplayed()) { + await existingTab.click(); + return; + } + const emptyStateAction = browser.$( + '//button[.//span[normalize-space()="Files"] and not(@aria-disabled="true")]', + ); + if (await emptyStateAction.isDisplayed()) { + await emptyStateAction.click(); + return; + } + const addSurface = browser.$('button[aria-label="Add panel surface"]'); + await addSurface.waitForDisplayed(); + await addSurface.click(); + const menuItem = browser.$('//*[@role="menuitem" and normalize-space()="Files"]'); + await menuItem.waitForDisplayed(); + await menuItem.click(); +} + +/** Writes a fresh file for one case and opens it editable in `view`. */ +async function openFreshFile( + view: View, + name: string, + own?: { readonly extension: string; readonly content: string }, +): Promise { + const fileName = own + ? `${name}.${own.extension}` + : view === "source" + ? `${name}.txt` + : `${name}.md`; + NodeFS.writeFileSync( + NodePath.join(preparedProjectPath, fileName), + own?.content ?? "Hello world\n", + ); + await setDesktopUiWindowSize(1_200, 720); + await openFixtureWorkspace(); + await openFilesSurface(); + const itemSelector = `[role="treeitem"][data-item-path="${fileName}"]`; + await browser.waitUntil( + () => + browser.execute( + (hostQuery: string, targetQuery: string) => { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + const target = host?.shadowRoot?.querySelector(targetQuery); + if (!target) return false; + target.click(); + return true; + }, + `${fileViewSelector} file-tree-container`, + itemSelector, + ), + { timeoutMsg: `The Files tree did not list ${fileName}.` }, + ); + await browser.waitUntil(async () => (await readState(view, fileName)).text.includes("Hello"), { + // The first file of a session waits for the editor bundle to load. + timeout: 30_000, + timeoutMsg: `${fileName} did not open editable in the ${view} view.`, + }); + return fileName; +} + +/** The focused element, looking through shadow roots, as `tag[role]`. */ +async function focusedElement(): Promise { + return browser.execute(() => { + let active = document.activeElement; + while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; + if (!active) return "none"; + const role = active.getAttribute("role"); + return `${active.tagName.toLowerCase()}${role ? `[role=${role}]` : ""}`; + }); +} + +async function readState(view: View, fileName: string): Promise { + return browser.execute( + (sourceView: boolean, hostQuery: string, richQuery: string, label: string) => { + let text = ""; + if (sourceView) { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + text = + host?.shadowRoot?.querySelector(`[role="textbox"][aria-label="${label}"]`)?.textContent ?? + ""; + } else { + text = document.querySelector(richQuery)?.textContent ?? ""; + } + const enabled = (name: string) => { + const button = document.querySelector( + `[data-file-editor-toolbar] button[aria-label="${name}"]`, + ); + return ( + button !== null && !button.disabled && button.getAttribute("aria-disabled") !== "true" + ); + }; + return { text, canUndo: enabled("Undo"), canRedo: enabled("Redo") }; + }, + view === "source", + sourceHostSelector, + richEditorSelector, + fileName, + ); +} + +/** Focuses the editing host and puts the caret at the end, or the start, of its text. */ +async function placeCaretAtEnd(view: View, fileName: string, atStart = false): Promise { + const placed = await browser.execute( + (sourceView: boolean, hostQuery: string, richQuery: string, label: string, start: boolean) => { + let editor: HTMLElement | null = null; + if (sourceView) { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + editor = + host?.shadowRoot?.querySelector(`[role="textbox"][aria-label="${label}"]`) ?? + null; + } else { + editor = document.querySelector(richQuery); + } + if (!editor) return false; + editor.focus(); + const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT); + let first: Text | null = null; + let last: Text | null = null; + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if ((node.textContent ?? "").trim().length > 0) { + first ??= node as Text; + last = node as Text; + } + } + if (!first || !last) return false; + if (start) window.getSelection()?.setBaseAndExtent(first, 0, first, 0); + else window.getSelection()?.setBaseAndExtent(last, last.length, last, last.length); + return true; + }, + view === "source", + sourceHostSelector, + richEditorSelector, + fileName, + atStart, + ); + if (!placed) throw new Error(`Could not place the caret in the ${view} view of ${fileName}.`); + // Pierre reads the caret on the next selectionchange. + await new Promise((resolve) => setTimeout(resolve, 200)); +} + +/** Types `marker` through the page: a `beforeinput` the source editor handles, or WebDriver text. */ +async function seedThroughPage(view: View, fileName: string, marker: string): Promise { + await placeCaretAtEnd(view, fileName); + if (view === "rendered") { + await browser.$(richEditorSelector).addValue(marker); + return; + } + await browser.execute( + (hostQuery: string, label: string, data: string) => { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + const editor = host?.shadowRoot?.querySelector( + `[role="textbox"][aria-label="${label}"]`, + ); + editor?.dispatchEvent( + new InputEvent("beforeinput", { + inputType: "insertText", + data, + bubbles: true, + cancelable: true, + composed: true, + }), + ); + }, + sourceHostSelector, + fileName, + marker, + ); +} + +function runNative(command: string, args: readonly string[]): string { + return NodeChildProcess.execFileSync(command, args, { encoding: "utf8" }).trim(); +} + +function macSystemEvents(lines: readonly string[]): string { + return runNative("osascript", [ + "-e", + [ + `tell application id "${bundleIdentifier}" to activate`, + 'tell application "System Events"', + ...lines.map((line) => ` ${line}`), + "end tell", + ].join("\n"), + ]); +} + +function powershell(script: string): string { + return runNative("powershell", ["-NoProfile", "-NonInteractive", "-Command", script]); +} + +/** Types plain letters as real operating-system key events. */ +function typeNative(letters: string): void { + if (platform === "mac") macSystemEvents([`keystroke "${letters}"`]); + else if (platform === "win") { + powershell( + `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('${letters}')`, + ); + } else runNative("xdotool", ["type", "--delay", "40", letters]); +} + +/** Presses Return as a real operating-system key event. */ +function typeNativeReturn(): void { + if (platform === "mac") macSystemEvents(["keystroke return"]); + else if (platform === "win") { + powershell( + "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('{ENTER}')", + ); + } else runNative("xdotool", ["key", "--clearmodifiers", "Return"]); +} + +function sendNativeChord(chord: Chord): void { + if (platform === "mac") { + const using = + chord === "primary+z" + ? "{command down}" + : chord === "primary+shift+z" + ? "{command down, shift down}" + : "{control down}"; + macSystemEvents([`keystroke "${chord === "ctrl+y" ? "y" : "z"}" using ${using}`]); + } else if (platform === "win") { + const keys = chord === "primary+z" ? "^z" : chord === "primary+shift+z" ? "^+z" : "^y"; + powershell( + `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('${keys}')`, + ); + } else { + const keys = + chord === "primary+z" ? "ctrl+z" : chord === "primary+shift+z" ? "ctrl+shift+z" : "ctrl+y"; + runNative("xdotool", ["key", "--clearmodifiers", keys]); + } +} + +/** Chooses Edit > Undo or Redo in the native menu bar. Returns whether the item existed and was enabled. */ +function chooseNativeEditItem(item: "Undo" | "Redo"): { + exists: boolean; + enabled: boolean; + reply?: string; +} { + if (platform === "mac") { + const reply = macSystemEvents([ + `tell (first application process whose bundle identifier is "${bundleIdentifier}")`, + " set frontmost to true", + ` set target to menu item "${item}" of menu 1 of menu bar item "Edit" of menu bar 1`, + " set isEnabled to enabled of target", + " if isEnabled then click target", + " return isEnabled as text", + " end tell", + ]); + return { exists: true, enabled: reply === "true" }; + } + if (platform === "win") { + const reply = powershell( + [ + "Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes", + "$A = [System.Windows.Automation.AutomationElement]", + "$S = [System.Windows.Automation.TreeScope]::Descendants", + // The packaged app is the one process of that executable with a main window. + `$window = $A::FromHandle((Get-Process -Name "${NodePath.parse(process.env.BIBCODE_E2E_APP_PATH ?? "bibcode-desktop").name}" | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1).MainWindowHandle)`, + '$named = { param($root, $name) $root.FindAll($S, [System.Windows.Automation.Condition]::TrueCondition) | Where-Object { $_.Current.Name -like "$name*" -and $_.Current.ControlType -eq [System.Windows.Automation.ControlType]::MenuItem } | Select-Object -First 1 }', + "$edit = & $named $window 'Edit'", + // The window's own Win32 menu bar, read through user32, decides whether the item exists. + 'Add-Type -Namespace LabWin -Name User32 -MemberDefinition \'[DllImport("user32.dll")] public static extern System.IntPtr GetMenu(System.IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetMenuItemCount(System.IntPtr hMenu);\'', + `$hwnd = (Get-Process -Name "${NodePath.parse(process.env.BIBCODE_E2E_APP_PATH ?? "bibcode-desktop").name}" | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1).MainWindowHandle`, + "$menuCount = [LabWin.User32]::GetMenuItemCount([LabWin.User32]::GetMenu($hwnd))", + // Without a UI Automation item, open Edit from the keyboard as a person can: F10, Right, Down. + `if (-not $edit) { Add-Type -AssemblyName System.Windows.Forms; if ($menuCount -le 0) { "missing-menu count=$menuCount"; exit }; [System.Windows.Forms.SendKeys]::SendWait("{F10}"); Start-Sleep -Milliseconds 300; [System.Windows.Forms.SendKeys]::SendWait("{RIGHT}{DOWN}"); Start-Sleep -Milliseconds 300; [System.Windows.Forms.SendKeys]::SendWait("${item === "Redo" ? "{DOWN}" : ""}{ENTER}"); "keyboard count=$menuCount"; exit }`, + "$edit.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern).Expand()", + "Start-Sleep -Milliseconds 400", + `$entry = & $named $A::RootElement '${item}'`, + "if (-not $entry) { 'missing-item'; exit }", + "if (-not $entry.Current.IsEnabled) { 'disabled'; exit }", + "$entry.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()", + "'invoked'", + ].join("; "), + ); + return { + exists: !reply.startsWith("missing"), + enabled: reply === "invoked" || reply.startsWith("keyboard"), + reply, + }; + } + // The pinned menu library creates no predefined Undo or Redo item on GTK. + return { exists: false, enabled: false }; +} + +async function startProbe(): Promise { + await browser.execute(() => { + const events: ProbeEvent[] = []; + window.__bibcodeUndoProbe = events; + const label = (event: Event) => { + const target = event.composedPath()[0]; + return target instanceof Element + ? `${target.tagName.toLowerCase()}${target.getAttribute("role") ? `[role=${target.getAttribute("role")}]` : ""}` + : String(target); + }; + // The focused element inside a shadow root also listens, in case an event does not cross it. + let focused = document.activeElement; + while (focused?.shadowRoot?.activeElement) focused = focused.shadowRoot.activeElement; + const listeners: [EventTarget, string, boolean, string][] = []; + for (const [type, capture] of [ + ["keydown", true], + ["keydown", false], + ["beforeinput", true], + ["beforeinput", false], + ["input", false], + ] as const) { + listeners.push([window, type, capture, capture ? `${type}:capture` : type]); + } + if (focused && focused.getRootNode() !== document) { + for (const type of ["keydown", "beforeinput"]) { + listeners.push([focused, type, true, `${type}:focused-in-shadow`]); + } + } + for (const [listenerTarget, type, capture, name] of listeners) { + listenerTarget.addEventListener( + type, + (event) => { + events.push({ + type: name, + key: event instanceof KeyboardEvent ? `${event.key} keyCode=${event.keyCode}` : null, + modifiers: + event instanceof KeyboardEvent + ? `${event.metaKey ? "meta+" : ""}${event.ctrlKey ? "ctrl+" : ""}${event.shiftKey ? "shift+" : ""}${event.altKey ? "alt+" : ""}` + : "", + inputType: event instanceof InputEvent ? event.inputType : null, + cancelable: event.cancelable, + isTrusted: event.isTrusted, + defaultPrevented: event.defaultPrevented, + target: label(event), + }); + }, + capture, + ); + } + }); +} + +async function readProbe(): Promise { + return browser.execute(() => window.__bibcodeUndoProbe ?? []); +} + +async function sendChord(path: InputPath, chord: Chord, direction: Direction) { + if (path === "keystroke") { + sendNativeChord(chord); + return { menu: null }; + } + if (path === "menu") { + return { menu: chooseNativeEditItem(direction === "undo" ? "Undo" : "Redo") }; + } + await dispatchPageChord(chord); + return { menu: null }; +} + +/** + * Dispatches the chord as a page `keydown` at the focused element, as a browser delivers it. The + * embedded driver's own keys land on the shadow host and carry the character code as `keyCode` + * (122 for "z"), so neither editor reads them as the chord. + */ +async function dispatchPageChord(chord: Chord | "primary+s"): Promise { + const primaryIsMeta = platform === "mac"; + await browser.execute( + (name: string, macPrimary: boolean) => { + let target = document.activeElement; + while (target?.shadowRoot?.activeElement) target = target.shadowRoot.activeElement; + const letter = name.endsWith("y") ? "y" : name.endsWith("s") ? "s" : "z"; + const primary = name.startsWith("primary"); + const shift = name.includes("shift"); + (target ?? document.body).dispatchEvent( + new KeyboardEvent("keydown", { + key: shift ? letter.toUpperCase() : letter, + code: `Key${letter.toUpperCase()}`, + keyCode: letter.toUpperCase().charCodeAt(0), + metaKey: primary && macPrimary, + ctrlKey: (primary && !macPrimary) || name === "ctrl+y", + shiftKey: shift, + bubbles: true, + cancelable: true, + composed: true, + }), + ); + }, + chord, + primaryIsMeta, + ); +} + +async function renderedHtml(): Promise { + return browser.execute( + (query: string) => document.querySelector(query)?.innerHTML ?? "", + richEditorSelector, + ); +} + +async function clickToolbar(label: "Undo" | "Redo" | "Heading 2" | "Link"): Promise { + const button = await browser.$(`[data-file-editor-toolbar] button[aria-label="${label}"]`); + await button.waitForEnabled(); + await button.click(); +} + +interface Cell { + readonly view: View; + readonly direction: Direction; + readonly path: InputPath; + readonly chord: Chord; + /** How the redo case's step was undone first: by the same path, or by the toolbar button. */ + readonly redoAfter?: "path" | "toolbar"; + /** The seeded step: typed text, or a toolbar formatting change (rendered view only). */ + readonly edit?: "typing" | "format"; +} + +function cellName({ view, direction, path, chord, redoAfter, edit }: Cell): string { + return [ + view, + direction, + path, + chord.replaceAll("+", "-"), + redoAfter ? `after-${redoAfter}-undo` : null, + edit === "format" ? "format" : null, + ] + .filter(Boolean) + .join("-"); +} + +/** + * Seeds one fresh edit, sends the chord or menu item, and checks that the history moved one step: + * the marker leaves on undo and returns on redo, and the toolbar agrees. + */ +async function measureCell(cell: Cell): Promise { + const name = `undo-${cellName(cell)}`; + const fileName = await openFreshFile(cell.view, name); + if (cell.path !== "driver") await giveNativeFocus(editorQuery(cell.view)); + const unseededText = (await readState(cell.view, fileName)).text; + // A formatting step shows in the text as the heading's own block, so it is read from the HTML. + const marker = cell.edit === "format" ? " + cell.edit === "format" + ? (await renderedHtml()).includes(marker) + : (await readState(cell.view, fileName)).text.includes(marker); + if (cell.edit === "format") { + await placeCaretAtEnd(cell.view, fileName); + await clickToolbar("Heading 2"); + await placeCaretAtEnd(cell.view, fileName); + } else if (cell.path === "driver") await seedThroughPage(cell.view, fileName, marker); + else { + await placeCaretAtEnd(cell.view, fileName); + typeNative(marker); + } + await browser.waitUntil(holdsStep, { + timeoutMsg: `The seeded ${cell.edit ?? "typing"} step never reached ${fileName}.`, + }); + // Past both editors' history grouping delay, so the edit is one closed step. + await new Promise((resolve) => setTimeout(resolve, 800)); + const seededText = (await readState(cell.view, fileName)).text; + // A native redo gets two pending redo entries, so a redo that runs twice shows: the second + // step is typed away from the first, which keeps the two steps apart in both editors. + const secondMarker = "wv"; + const twoRedoEntries = + cell.direction === "redo" && cell.path !== "driver" && cell.edit !== "format"; + if (twoRedoEntries) { + await placeCaretAtEnd(cell.view, fileName, true); + typeNative(secondMarker); + await browser.waitUntil( + async () => (await readState(cell.view, fileName)).text.includes(secondMarker), + { timeoutMsg: `The second seeded step never reached ${fileName}.` }, + ); + await new Promise((resolve) => setTimeout(resolve, 800)); + } + const holdsSecond = async () => + (await readState(cell.view, fileName)).text.includes(secondMarker); + if (cell.direction === "redo") { + if (cell.redoAfter === "path") { + if (twoRedoEntries) { + await sendChord(cell.path, "primary+z", "undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + } + await sendChord(cell.path, "primary+z", "undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + if ((await holdsStep()) || (twoRedoEntries && (await holdsSecond()))) { + recordEvidence({ + cell: cellName(cell), + ...cell, + passed: false, + note: "this path did not undo", + }); + throw new Error("This path cannot undo, so its redo is not measured."); + } + } else { + if (twoRedoEntries) { + await clickToolbar("Undo"); + await browser.waitUntil(async () => !(await holdsSecond()), { + timeoutMsg: "The toolbar Undo did not remove the second seeded step.", + }); + } + await clickToolbar("Undo"); + await browser.waitUntil(async () => !(await holdsStep()), { + timeoutMsg: "The toolbar Undo did not remove the seeded edit.", + }); + // The click moved focus to the toolbar; a person clicks back into the text before redoing. + await placeCaretAtEnd(cell.view, fileName); + } + } + const before = await readState(cell.view, fileName); + const focus = await focusedElement(); + await startProbe(); + const sent = await sendChord(cell.path, cell.chord, cell.direction); + await new Promise((resolve) => setTimeout(resolve, 800)); + const after = await readState(cell.view, fileName); + const events = await readProbe(); + const expectMarker = cell.direction === "redo"; + const stepPresent = await holdsStep(); + // After one redo of two, the second step is still undone and Redo stays enabled. + const secondPresent = twoRedoEntries && (await holdsSecond()); + const expectRedo = twoRedoEntries || !expectMarker; + const passed = + stepPresent === expectMarker && + !secondPresent && + after.canUndo === expectMarker && + after.canRedo === expectRedo && + after.text === (expectMarker ? seededText : unseededText); + recordEvidence({ + cell: cellName(cell), + ...cell, + passed, + chordKeydownReachedPage: chordKeydownReachedPage(events), + focus, + before, + after, + sent, + events, + }); + expect({ + text: stepPresent, + second: secondPresent, + exactText: after.text === (expectMarker ? seededText : unseededText), + canUndo: after.canUndo, + canRedo: after.canRedo, + }).toEqual({ + text: expectMarker, + second: false, + exactText: true, + canUndo: expectMarker, + canRedo: expectRedo, + }); +} + +/** + * Two typed steps, then one undo: exactly the second step leaves and the first stays. Catches a + * menu item that both runs its action and lets the chord's own `keydown` reach the editor. + */ +async function measureTwoSteps(view: View, path: InputPath): Promise { + const fileName = await openFreshFile(view, `undo-two-steps-${view}-${path}`); + await giveNativeFocus(editorQuery(view)); + await placeCaretAtEnd(view, fileName); + typeNative("kq"); + await browser.waitUntil(async () => (await readState(view, fileName)).text.includes("kq")); + // The source editor joins adjacent typing into one step whatever the pause, so the second step + // is typed at the start of the text; a new line would add a step a double undo hides behind. + await new Promise((resolve) => setTimeout(resolve, 1_200)); + await placeCaretAtEnd(view, fileName, true); + const firstStep = await readState(view, fileName); + typeNative("wv"); + await browser.waitUntil(async () => (await readState(view, fileName)).text.includes("wv")); + await new Promise((resolve) => setTimeout(resolve, 1_200)); + await startProbe(); + const sent = await sendChord(path, "primary+z", "undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + const after = await readState(view, fileName); + const events = await readProbe(); + const passed = after.text === firstStep.text && after.canUndo && after.canRedo; + recordEvidence({ + cell: `${view}-two-steps-undo-${path}`, + passed, + chordKeydownReachedPage: chordKeydownReachedPage(events), + after, + sent, + events, + }); + expect(after).toEqual({ text: firstStep.text, canUndo: true, canRedo: true }); +} + +/** + * Independent edits in the source view and in its inline comment field: undo with the comment + * field focused undoes the comment text and leaves the file's history where it was. + */ +async function measureCommentIndependence(path: InputPath, direction: Direction): Promise { + const fileName = await openFreshFile("source", `undo-comment-${path}-${direction}`); + await giveNativeFocus(sourceHostSelector); + await placeCaretAtEnd("source", fileName); + typeNative("kq"); + await browser.waitUntil(async () => (await readState("source", fileName)).text.includes("kq")); + await new Promise((resolve) => setTimeout(resolve, 800)); + // A click on the first line number opens a comment form with its textarea focused. + await browser.execute((hostQuery: string) => { + const host = [...document.querySelectorAll(hostQuery)].find( + (candidate) => candidate.getBoundingClientRect().height > 0, + ); + const gutter = host?.shadowRoot?.querySelector( + "[data-gutter] [data-column-number]", + ); + if (!gutter) throw new Error("The source view shows no line number."); + const rect = gutter.getBoundingClientRect(); + const pointer = (type: string, buttons: number) => + gutter.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + button: 0, + buttons, + clientX: Math.round(rect.left + rect.width / 2), + clientY: Math.round(rect.top + rect.height / 2), + composed: true, + isPrimary: true, + pointerId: 74, + pointerType: "mouse", + }), + ); + pointer("pointermove", 0); + pointer("pointerdown", 1); + pointer("pointerup", 0); + gutter.click(); + }, sourceHostSelector); + const comment = browser.$('textarea[aria-label^="Comment on lines"]'); + await comment.waitForDisplayed({ timeoutMsg: "The line number did not open a comment form." }); + await browser.execute(() => + document.querySelector('textarea[aria-label^="Comment on lines"]')?.focus(), + ); + // Capitalized, so macOS has no capitalization step of its own to add before the undo. + typeNative("Cmtq"); + await browser.waitUntil(async () => (await comment.getValue()).toLowerCase().includes("cmtq"), { + timeoutMsg: "The typed text never reached the comment field.", + }); + await new Promise((resolve) => setTimeout(resolve, 800)); + // Read before any undo, so a setup undo that also moved the file's history is caught. + const filesBefore = await readState("source", fileName); + expect(filesBefore.text.includes("kq") && filesBefore.canUndo).toBe(true); + if (direction === "redo") { + await sendChord(path, "primary+z", "undo"); + await browser.waitUntil( + async () => !(await comment.getValue()).toLowerCase().includes("cmtq"), + { + timeoutMsg: `Undo by ${path} did not empty the comment field, so its redo is not measured.`, + }, + ); + } + await startProbe(); + const sent = await sendChord( + path, + direction === "undo" ? "primary+z" : "primary+shift+z", + direction, + ); + await new Promise((resolve) => setTimeout(resolve, 800)); + const commentHoldsText = (await comment.getValue()).toLowerCase().includes("cmtq"); + const filesAfter = await readState("source", fileName); + const events = await readProbe(); + recordEvidence({ + cell: `comment-${direction}-${path}`, + passed: + commentHoldsText === (direction === "redo") && + filesAfter.text === filesBefore.text && + filesAfter.canUndo === filesBefore.canUndo, + filesBefore, + filesAfter, + commentHoldsText, + sent, + events, + }); + expect(commentHoldsText).toBe(direction === "redo"); + expect(filesAfter).toEqual(filesBefore); +} + +const views: readonly View[] = ["source", "rendered"]; +const redoChords: readonly Chord[] = + platform === "mac" ? ["primary+shift+z"] : ["primary+shift+z", "ctrl+y"]; + +const probeTextareaId = "undo-probe-textarea"; + +/** Whether any recorded `keydown` was the Z or Y of a chord, that is, whether the chord reached the page. */ +function chordKeydownReachedPage(events: readonly ProbeEvent[]): boolean { + return events.some( + (event) => event.type.startsWith("keydown") && /^[zy] /i.test(event.key ?? ""), + ); +} + +async function fieldText(kind: "composer" | "textarea"): Promise { + if (kind === "composer") return browser.$(composerSelector).getText(); + return browser.execute( + (id: string) => (document.getElementById(id) as HTMLTextAreaElement | null)?.value ?? "", + probeTextareaId, + ); +} + +/** + * Undo outside Files: the chat composer (Lexical) or a plain `textarea` added to the page. One + * typed step, then the chord or Edit > Undo, and the typed text must be gone. + */ +async function measureTextField( + kind: "composer" | "textarea", + path: InputPath, + direction: Direction = "undo", +): Promise { + await openFixtureWorkspace(); + if (kind === "composer") { + const composer = browser.$(composerSelector); + await composer.waitForDisplayed(); + await composer.click(); + } else { + await browser.execute((id: string) => { + const area = document.createElement("textarea"); + area.id = id; + area.setAttribute("aria-label", "Undo probe"); + area.style.cssText = + "position:fixed;top:8px;left:8px;z-index:2147483647;width:240px;height:48px"; + document.body.append(area); + area.focus(); + }, probeTextareaId); + } + if (path !== "driver") { + await giveNativeFocus(kind === "composer" ? composerSelector : `#${probeTextareaId}`); + } + if (path === "driver") { + if (kind === "composer") await browser.$(composerSelector).addValue("cmpq"); + else await browser.$(`#${probeTextareaId}`).addValue("cmpq"); + } else typeNative("Cmpq"); + await browser.waitUntil(async () => (await fieldText(kind)).toLowerCase().includes("cmpq"), { + timeoutMsg: `The typed text never reached the ${kind}.`, + }); + await new Promise((resolve) => setTimeout(resolve, 800)); + if (direction === "redo") { + await sendChord(path, "primary+z", "undo"); + await browser.waitUntil(async () => !(await fieldText(kind)).toLowerCase().includes("cmpq"), { + timeoutMsg: `Undo by ${path} did not empty the ${kind}, so its redo is not measured.`, + }); + } + await startProbe(); + const sent = await sendChord( + path, + direction === "undo" ? "primary+z" : "primary+shift+z", + direction, + ); + await new Promise((resolve) => setTimeout(resolve, 600)); + const text = await fieldText(kind); + const events = await readProbe(); + // macOS may capitalize the typed word as a replacement step, which is not an undo. + const holdsText = text.toLowerCase().includes("cmpq"); + recordEvidence({ + cell: `${kind}-${direction}-${path}`, + passed: holdsText === (direction === "redo"), + chordKeydownReachedPage: chordKeydownReachedPage(events), + text, + sent, + events, + }); + if (kind === "textarea") { + await browser.execute((id: string) => document.getElementById(id)?.remove(), probeTextareaId); + } + expect(holdsText).toBe(direction === "redo"); +} + +/** + * A real undo chord in a focused terminal. On Windows and Linux, Ctrl+Z is the shell's suspend + * key, which the terminal must keep, so the page must not run an undo of its own. + */ +async function recordTerminalChord(sent: Chord = "primary+z"): Promise { + await openFixtureWorkspace(); + await openCenterTerminal(); + const input = await browser.$(".xterm-helper-textarea"); + await input.waitForExist(); + await giveNativeFocus(".xterm"); + await browser.execute(() => + document.querySelector(".xterm-helper-textarea")?.focus(), + ); + await startProbe(); + // Counts the page's native undo and redo, and reads whether the chord was cancelled once its + // dispatch ended: xterm cancels the keys it sends to the shell. + await browser.execute(() => { + const probe = window as unknown as { __terminalChord?: { exec: number; cancelled: boolean } }; + const state = { exec: 0, cancelled: false }; + probe.__terminalChord = state; + const exec = document.execCommand.bind(document); + document.execCommand = (command: string, ...rest: unknown[]) => { + if (command === "undo" || command === "redo") state.exec += 1; + return exec(command, ...(rest as [boolean?, string?])); + }; + window.addEventListener( + "keydown", + (event) => { + if (/^[zy]$/i.test(event.key)) { + setTimeout(() => { + state.cancelled = event.defaultPrevented; + }); + } + }, + true, + ); + }); + sendNativeChord(sent); + await new Promise((resolve) => setTimeout(resolve, 600)); + const events = await readProbe(); + const chord = await browser.execute( + () => + (window as unknown as { __terminalChord: { exec: number; cancelled: boolean } }) + .__terminalChord, + ); + const reached = chordKeydownReachedPage(events); + recordEvidence({ + cell: `terminal-${sent.replaceAll("+", "-")}-keystroke`, + chordKeydownReachedPage: reached, + focus: await focusedElement(), + chord, + events, + }); + // On Windows and Linux the shell gets Ctrl+Z (xterm cancels the keydown it sends) and the page + // runs no undo. On macOS Cmd+Z never reaches the page; the Edit menu takes it and, the terminal + // being no Files editor, runs the native undo once, as the predefined item did. + if (platform === "mac") + expect({ reached, exec: chord.exec }).toEqual({ reached: false, exec: 1 }); + else { + // xterm sends Ctrl+Z to the shell and cancels it; it leaves Shift+Ctrl+Z to the page, + // which must still run no undo of its own. + expect({ + reached, + cancelled: chord.cancelled || sent === "primary+shift+z", + exec: chord.exec, + }).toEqual({ + reached: true, + cancelled: true, + exec: 0, + }); + } +} + +/** The screen point under page coordinates `point` of the main window. */ +async function screenPointOf(point: { + x: number; + y: number; +}): Promise<{ x: number; y: number; scale: number }> { + // The window's content origin on screen: the frame's position plus its title bar and borders. + return browser.execute( + (x: number, y: number) => { + const border = Math.max(0, (window.outerWidth - window.innerWidth) / 2); + return { + x: window.screenX + border + x, + y: window.screenY + window.outerHeight - window.innerHeight - border + y, + scale: window.devicePixelRatio, + }; + }, + point.x, + point.y, + ); +} + +/** Clicks a screen point from `screenPointOf`, as a person does. */ +function nativeClickAtScreen(screen: { x: number; y: number; scale: number }): void { + const x = Math.round(screen.x); + const y = Math.round(screen.y); + if (platform === "mac") { + // A window-server click: System Events' accessibility click never reaches the preview's + // child webview, so its page never saw a mouse-down and its field never took focus. + runNative("osascript", ["-e", `tell application id "${bundleIdentifier}" to activate`]); + runNative("osascript", [ + "-l", + "JavaScript", + "-e", + [ + 'ObjC.import("CoreGraphics");', + `const point = $.CGPointMake(${x}, ${y});`, + "for (const type of [$.kCGEventLeftMouseDown, $.kCGEventLeftMouseUp]) {", + " $.CGEventPost($.kCGHIDEventTap, $.CGEventCreateMouseEvent(null, type, point, $.kCGMouseButtonLeft));", + " delay(0.05);", + "}", + ].join("\n"), + ]); + } else if (platform === "win") { + powershell( + [ + 'Add-Type -Namespace LabWin -Name Mouse -MemberDefinition \'[DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] public static extern void mouse_event(int f, int x, int y, int d, int e);\'', + "[LabWin.Mouse]::SetProcessDPIAware() | Out-Null", + `[LabWin.Mouse]::SetCursorPos(${Math.round(x * screen.scale)}, ${Math.round(y * screen.scale)}) | Out-Null`, + "[LabWin.Mouse]::mouse_event(2, 0, 0, 0, 0); Start-Sleep -Milliseconds 50; [LabWin.Mouse]::mouse_event(4, 0, 0, 0, 0)", + ].join("; "), + ); + } else runNative("xdotool", ["mousemove", String(x), String(y), "click", "1"]); +} + +/** + * The Link URL field, a plain input the rendered view's Link button opens: undo empties what was + * typed there natively and leaves the document's history where it was. + */ +async function measureLinkField(path: InputPath): Promise { + const fileName = await openFreshFile("rendered", `undo-link-${path}`); + await giveNativeFocus(richEditorSelector); + await placeCaretAtEnd("rendered", fileName); + typeNative("kqv"); + await browser.waitUntil(async () => (await readState("rendered", fileName)).text.includes("kqv")); + await new Promise((resolve) => setTimeout(resolve, 800)); + const filesBefore = await readState("rendered", fileName); + expect(filesBefore.canUndo).toBe(true); + // A plain click: the driver's pointer sequence closes the popover again as an outside press. + await browser.execute(() => + document + .querySelector('[data-file-editor-toolbar] button[aria-label="Link"]') + ?.click(), + ); + const field = browser.$('input[aria-label="Link URL"]'); + await field.waitForDisplayed({ timeoutMsg: "The Link button did not open the Link URL field." }); + await browser.execute(() => + document.querySelector('input[aria-label="Link URL"]')?.focus(), + ); + typeNative("Lnkq"); + await browser.waitUntil(async () => (await field.getValue()).toLowerCase().includes("lnkq"), { + timeoutMsg: "The typed text never reached the Link URL field.", + }); + await new Promise((resolve) => setTimeout(resolve, 800)); + await startProbe(); + const sent = await sendChord(path, "primary+z", "undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + const fieldValue = await field.getValue(); + const events = await readProbe(); + await browser.keys("Escape"); + await field.waitForDisplayed({ reverse: true }); + const filesAfter = await readState("rendered", fileName); + const fieldUndone = fieldValue === ""; + recordEvidence({ + cell: `link-url-undo-${path}`, + passed: fieldUndone && JSON.stringify(filesAfter) === JSON.stringify(filesBefore), + fieldValue, + filesBefore, + filesAfter, + sent, + events, + }); + expect({ fieldUndone, files: filesAfter }).toEqual({ fieldUndone: true, files: filesBefore }); +} + +// The probe page's field colour, which its native screenshot must show. +const previewPaint = [255, 0, 170] as const; + +// A page for the preview webview: it remembers the longest value its field held, and Return +// sends the field's value and that peak to `reportUrl` as an `echo` report. It reports rather than +// navigates: the server serves it as an opaque-origin sandbox, where `location.href =` throws. +const previewProbePage = (reportUrl = "") => ` +Preview probe + + + + + +`; + +interface TauriTestGlobal { + readonly core: { invoke: (command: string, args: Record) => Promise }; + readonly event: { + listen: ( + name: string, + listener: (event: { + payload: { tabId: string; state: { navStatus: { kind: string; url?: string } } }; + }) => void, + ) => Promise<() => void>; + }; +} + +/** What the main page reports about the preview while WebDriver cannot see the window. */ +interface PreviewReport { + readonly kind: "painted" | "echo" | "closed"; + readonly url?: string; + /** The native screenshot of the loaded page. */ + readonly path?: string; + readonly error?: string; +} + +/** + * A local endpoint for the main page's preview reports. While the preview's child webview shares + * the main window, the embedded WebDriver finds no window (Tauri's `webview_windows` leaves out a + * window with two webviews), so nothing may call WebDriver until the page closed that webview. + */ +async function startPreviewReports() { + const reports: PreviewReport[] = []; + let closeRequested = false; + const server = NodeHttp.createServer((request, response) => { + const query = new URL(request.url ?? "/", "http://127.0.0.1").searchParams; + const report = query.get("report"); + if (report) reports.push(JSON.parse(report) as PreviewReport); + response.writeHead(200, { "access-control-allow-origin": "*" }); + response.end(query.has("poll") && closeRequested ? "close" : ""); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as NodeNet.AddressInfo; + return { + url: `http://127.0.0.1:${port}/`, + /** The latest report of `kind` so far. */ + last: (kind: PreviewReport["kind"]) => reports.findLast((report) => report.kind === kind), + /** The first report of `kind`, waiting with timers only: WebDriver may be blind. */ + async next(kind: PreviewReport["kind"], timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const found = reports.find((report) => report.kind === kind); + if (found) return found; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + return undefined; + }, + /** Asks a page armed in `hold` mode to close the preview now. */ + requestClose: () => { + closeRequested = true; + }, + close: () => server.close(), + }; +} + +/** + * Arms the main page before "Open file in preview browser": once `fileName` loads it takes the + * preview's native screenshot, then closes the preview's native webview at once (`paint`) or when + * the spec asks (`hold`), reporting each step to `reportUrl`. It gives up after 60 s. + */ +async function armPreviewObserver( + fileName: string, + reportUrl: string, + mode: "paint" | "hold", +): Promise { + await browser.execute( + async (name: string, url: string, until: string) => { + const tauri = (window as unknown as { __TAURI__: TauriTestGlobal }).__TAURI__; + const report = (value: PreviewReport) => + void fetch(`${url}?report=${encodeURIComponent(JSON.stringify(value))}`, { + mode: "no-cors", + }).catch(() => undefined); + let tabId: string | null = null; + let painted = false; + let closed = false; + let unlisten = () => {}; + const close = (reason: string) => { + if (closed) return; + closed = true; + unlisten(); + if (tabId === null) { + report({ kind: "closed", error: `${reason}: no preview opened` }); + return; + } + tauri.core.invoke("desktop_preview_close_tab", { tabId }).then( + () => report(reason === "done" ? { kind: "closed" } : { kind: "closed", error: reason }), + (error) => report({ kind: "closed", error: `${reason}: ${String(error)}` }), + ); + }; + unlisten = await tauri.event.listen("preview://state", ({ payload }) => { + if (closed) return; + const nav = payload.state.navStatus; + const page = decodeURIComponent(nav.url ?? ""); + tabId = payload.tabId; + if (!painted && nav.kind === "Success" && page.includes(name)) { + painted = true; + tauri.core.invoke("desktop_preview_capture_screenshot", { tabId }).then( + (shot) => { + report({ kind: "painted", url: page, path: (shot as { path: string }).path }); + if (until === "paint") { + // The first capture can predate the webview's slot size, so take a later one. + setTimeout(() => { + tauri.core + .invoke("desktop_preview_capture_screenshot", { tabId }) + .then( + (later) => + report({ + kind: "painted", + url: page, + path: (later as { path: string }).path, + }), + () => undefined, + ) + .finally(() => close("done")); + }, 1_500); + } + if (until === "hold") { + const poll = () => + void fetch(`${url}?poll=1`) + .then((answer) => answer.text()) + .then((answer) => (answer === "close" ? close("done") : undefined)) + .catch(() => undefined) + .finally(() => { + if (!closed) setTimeout(poll, 300); + }); + poll(); + } + }, + (error) => { + report({ kind: "painted", error: String(error) }); + close("no screenshot"); + }, + ); + } + }); + setTimeout(() => close("timeout"), 60_000); + }, + fileName, + reportUrl, + mode, + ); +} + +/** Waits for the page to close the preview, then until WebDriver sees the window again. */ +async function awaitPreviewClosed( + reports: Awaited>, +): Promise { + const closed = await reports.next("closed", 70_000); + const deadline = Date.now() + 15_000; + for (;;) { + try { + await browser.execute(() => true); + return closed; + } catch (error) { + if (Date.now() > deadline) throw error; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + } +} + +/** Closes a preview a failed step left open, so the next test finds the main window again. */ +async function closePreviewLeftOpen( + reports: Awaited>, + open: boolean, +): Promise { + if (!open) return; + reports.requestClose(); + await awaitPreviewClosed(reports).catch(() => undefined); +} + +interface PreviewPaint { + /** The share of the capture in the probe page's colour. */ + readonly share: number; + readonly width: number; + readonly height: number; +} + +/** + * Reads a preview screenshot: only a painted page shows the probe page's colour, so a webview that + * never loaded or stayed blank scores near zero. + */ +async function readPreviewPaint(path: string | undefined): Promise { + if (!path || !NodeFS.existsSync(path)) return { share: 0, width: 0, height: 0 }; + const png = NodeFS.readFileSync(path).toString("base64"); + return browser.execute( + async (data: string, [red, green, blue]: readonly number[]) => { + const image = new Image(); + image.src = `data:image/png;base64,${data}`; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + const empty = { share: 0, width: canvas.width, height: canvas.height }; + if (!context || canvas.width === 0 || canvas.height === 0) return empty; + context.drawImage(image, 0, 0); + const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data; + let sampled = 0; + let painted = 0; + // Colour management can shift the capture a little, so the match is loose. + for (let index = 0; index < pixels.length; index += 4 * 16) { + sampled += 1; + if ( + Math.abs(pixels[index]! - red!) < 40 && + Math.abs(pixels[index + 1]! - green!) < 40 && + Math.abs(pixels[index + 2]! - blue!) < 40 + ) { + painted += 1; + } + } + return { share: painted / sampled, width: canvas.width, height: canvas.height }; + }, + png, + [...previewPaint], + ); +} + +/** The visible preview's page area, where the native webview sits, in page coordinates. */ +async function previewSlotRect(): Promise<{ width: number; height: number } | null> { + return browser.execute(() => { + const visible = [ + ...document.querySelectorAll("[data-thread-key] > div.relative.flex-1"), + ].find((candidate) => candidate.getBoundingClientRect().height > 40); + const box = visible?.getBoundingClientRect(); + return box ? { width: box.width, height: box.height } : null; + }); +} + +/** + * Whether the screenshot shows the page painted over the preview's whole slot: a webview never + * sized captures a pixel or two. The slot is measured after the close, which keeps the panel. + */ +async function checkPreviewPaint( + fileName: string, + painted: PreviewReport | undefined, +): Promise<{ painted: boolean; sized: boolean }> { + const paint = await readPreviewPaint(painted?.path); + const slot = await previewSlotRect(); + recordEvidence({ cell: "preview-paint", fileName, report: painted, paint, slot }); + return { + painted: paint.share > 0.5, + sized: slot !== null && paint.width >= slot.width * 0.9 && paint.height >= slot.height * 0.9, + }; +} + +/** + * Leaves the preview for Files and reloads the page, whose preview bridge still holds the native + * webview the observer closed behind its back. + */ +async function leaveClosedPreview(): Promise { + await openFilesSurface(); + await refreshDesktopUiDocument(); +} + +async function measurePreviewPaint(): Promise { + const fileName = await openFreshFile("source", "preview-paint", { + extension: "html", + content: previewProbePage(), + }); + const reports = await startPreviewReports(); + try { + const focusedBefore = await browser.execute(() => document.hasFocus()); + await armPreviewObserver(fileName, reports.url, "paint"); + await browser.$('button[aria-label="Open file in preview browser"]').click(); + const closed = await awaitPreviewClosed(reports); + // The preview took keyboard focus when it opened; closing it must hand focus back. + const focusedAfter = await browser + .waitUntil(() => browser.execute(() => document.hasFocus()), { timeout: 3_000 }) + .then( + () => true, + () => false, + ); + recordEvidence({ cell: "preview-close-returns-focus", focusedBefore, focusedAfter }); + const result = await checkPreviewPaint( + fileName, + await new Promise((resolve) => + setTimeout(() => resolve(reports.last("painted")), 1_000), + ), + ); + await leaveClosedPreview(); + expect({ ...result, closed: closed?.error ?? "closed" }).toEqual({ + painted: true, + sized: true, + closed: "closed", + }); + // Asserted where it was found; on macOS the evidence shows whether the bug exists there. + if (platform !== "mac") expect(focusedAfter).toBe(true); + } finally { + reports.close(); + } +} + +/** The right panel tab of the open file `fileName`, beside the Files tree's own tab. */ +function fileTabXPath(fileName: string): string { + return `//*[@data-right-panel-tab-list]//*[self::button or @role="tab"][contains(normalize-space(), "${fileName}")]`; +} + +/** The source view's state once Files shows the file again, after the preview had its place. */ +async function readFilesAfterPreview(fileName: string): Promise { + await browser.$(fileTabXPath(fileName)).click(); + // The remounted editor shows its text before the toolbar learns its history, so both callers' + // history (an undo or redo step) is waited for; a history really lost stays empty and fails. + await browser + .waitUntil( + async () => { + const state = await readState("source", fileName); + return state.text.length > 0 && (state.canUndo || state.canRedo); + }, + { timeout: 10_000 }, + ) + .catch(() => undefined); + return readState("source", fileName); +} + +/** + * How far a native click at `screenPointOf(point)` lands from `point`, measured with one click + * there, which must be harmless: the window's frame on screen is not what the page reports. + */ +async function measureNativeClickOffset(point: { + x: number; + y: number; +}): Promise<{ x: number; y: number }> { + await browser.execute(() => { + const target = window as unknown as { __bibcodeClickProbe?: { x: number; y: number } | null }; + target.__bibcodeClickProbe = null; + addEventListener( + "mousedown", + (event) => { + target.__bibcodeClickProbe = { x: event.clientX, y: event.clientY }; + }, + { capture: true, once: true }, + ); + }); + nativeClickAtScreen(await screenPointOf(point)); + let landed: { x: number; y: number } | null = null; + await browser.waitUntil( + async () => { + landed = await browser.execute( + () => + (window as unknown as { __bibcodeClickProbe?: { x: number; y: number } | null }) + .__bibcodeClickProbe ?? null, + ); + return landed !== null; + }, + { timeout: 5_000, timeoutMsg: "The calibration click never reached the page." }, + ); + const { x, y } = landed!; + return { x: point.x - x, y: point.y - y }; +} + +/** Clicks a macOS menu bar item of the app. */ +function clickMacMenuItem(menu: string, item: string): void { + macSystemEvents([ + `tell (first application process whose bundle identifier is "${bundleIdentifier}")`, + " set frontmost to true", + ` click menu item "${item}" of menu 1 of menu bar item "${menu}" of menu bar 1`, + " end tell", + ]); +} + +/** The centre of the first visible element `query` (CSS, or XPath from `//`) finds. */ +async function centreOf(query: string): Promise<{ x: number; y: number }> { + const centre = await browser.execute((selector: string) => { + const nodes = selector.startsWith("//") + ? (() => { + const found = document.evaluate( + selector, + document, + null, + XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, + null, + ); + return Array.from({ length: found.snapshotLength }, (_, index) => + found.snapshotItem(index), + ) as Element[]; + })() + : [...document.querySelectorAll(selector)]; + const rect = nodes + .find((node) => node.getBoundingClientRect().height > 0) + ?.getBoundingClientRect(); + return rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : null; + }, query); + if (!centre) throw new Error(`Nothing visible matched ${query}.`); + return centre; +} + +/** The editing host of the `view` view, for a native click into it. */ +function editorQuery(view: View): string { + return view === "source" ? sourceHostSelector : richEditorSelector; +} + +/** + * Clicks the centre of `query` natively, as a person does before typing. GTK and Win32 keyboard + * focus move only with a real click: a WebDriver click or `element.focus()` leaves it where it + * was, such as in a preview webview an earlier cell opened, and native keys then reach nothing. + * Callers still place focus and the caret through the page afterwards, since the click moves the + * caret. + */ +async function giveNativeFocus(query: string): Promise { + // shortcut: Linux and Windows, where native focus was found lost; add macOS if it shows there. + if (platform === "mac") return; + const centre = await centreOf(query); + // The calibration click is the focusing click; a second one lands it on target if it was off. + const offset = await measureNativeClickOffset(centre); + if (Math.hypot(offset.x, offset.y) > 4) { + nativeClickAtScreen(await screenPointOf({ x: centre.x + offset.x, y: centre.y + offset.y })); + } + await browser.waitUntil(() => browser.execute(() => document.hasFocus()), { + timeout: 3_000, + timeoutMsg: `The native click on ${query} did not give the main webview keyboard focus.`, + }); +} + +/** + * With a preview webview open in the main window (#418): Edit > Undo still undoes one step of the + * Files editor, and closing the window with that unsaved edit still asks first. + */ +async function measureMainWindowAfterPreview(): Promise { + const fileName = await openFreshFile("source", "undo-after-preview", { + extension: "html", + content: previewProbePage(), + }); + const editorCentre = await centreOf(sourceHostSelector); + const offset = await measureNativeClickOffset(editorCentre); + const onScreen = async (point: { x: number; y: number }) => + screenPointOf({ x: point.x + offset.x, y: point.y + offset.y }); + await placeCaretAtEnd("source", fileName); + typeNative("kq"); + await browser.waitUntil(async () => (await readState("source", fileName)).text.includes("kq")); + // Past the editor's history grouping, so the next letters are a step of their own. + await new Promise((resolve) => setTimeout(resolve, 1_200)); + // A second step, which the one undo removes (the editor may group it with the first). + typeNative("vx"); + await browser.waitUntil(async () => (await readState("source", fileName)).text.includes("kqvx")); + await new Promise((resolve) => setTimeout(resolve, 1_200)); + const filesBefore = await readState("source", fileName); + expect(filesBefore.canUndo).toBe(true); + // Measured now: WebDriver is blind while the preview's webview is open. + const fileTab = await onScreen(await centreOf(fileTabXPath(fileName))); + const editor = await onScreen(editorCentre); + const reports = await startPreviewReports(); + let previewOpen = false; + try { + await armPreviewObserver(fileName, reports.url, "hold"); + await browser.$('button[aria-label="Open file in preview browser"]').click(); + previewOpen = true; + const painted = await reports.next("painted", 30_000); + let menu: ReturnType | null = null; + if (painted?.path) { + // Back to the file: the preview's webview stays in the window, hidden. + nativeClickAtScreen(fileTab); + await new Promise((resolve) => setTimeout(resolve, 800)); + nativeClickAtScreen(editor); + await new Promise((resolve) => setTimeout(resolve, 400)); + menu = chooseNativeEditItem("Undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + // Command-W closes the active surface; the window closes from Window > Close Window. + clickMacMenuItem("Window", "Close Window"); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + } + reports.requestClose(); + await awaitPreviewClosed(reports); + previewOpen = false; + const asked = await browser + .$( + '//*[@role="alertdialog"][.//*[starts-with(normalize-space(), "Save your changes before")]]', + ) + .waitForDisplayed({ timeout: 3_000 }) + .then( + () => true, + () => false, + ); + if (asked) { + await browser.$('//*[@role="alertdialog"]//button[normalize-space()="Cancel"]').click(); + } + const filesAfter = await readFilesAfterPreview(fileName); + recordEvidence({ + cell: "main-window-after-preview", + painted, + menu, + filesBefore, + filesAfter, + asked, + }); + expect({ + painted: painted?.path !== undefined, + undone: !filesAfter.text.includes("vx") && filesAfter.canRedo, + asked, + }).toEqual({ painted: true, undone: true, asked: true }); + } finally { + await closePreviewLeftOpen(reports, previewOpen); + reports.close(); + } +} + +/** + * Undo in the preview webview, the browser opened by "Open file in preview browser": the host's + * focus check sends it to the native responder, so the page's own field undoes and the Files + * history behind it stays where it was. + */ +async function measurePreviewFallback(path: InputPath): Promise { + const reports = await startPreviewReports(); + const fileName = await openFreshFile("source", `undo-preview-${path}`, { + extension: "html", + content: previewProbePage(reports.url), + }); + await giveNativeFocus(sourceHostSelector); + await placeCaretAtEnd("source", fileName); + typeNative("kq"); + await browser.waitUntil(async () => (await readState("source", fileName)).text.includes("kq")); + await new Promise((resolve) => setTimeout(resolve, 800)); + const filesBefore = await readState("source", fileName); + expect(filesBefore.canUndo).toBe(true); + // The preview takes the Files surface's place; its field fills the page, so the surface's + // centre is in it. Measured now: WebDriver is blind while the preview is open. + const centre = await browser.execute((query: string) => { + const rect = [...document.querySelectorAll(query)] + .find((candidate) => candidate.getBoundingClientRect().height > 0) + ?.getBoundingClientRect(); + return rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : null; + }, fileViewSelector); + if (!centre) throw new Error("The Files surface was not found."); + const click = await screenPointOf(centre); + let previewOpen = false; + try { + await armPreviewObserver(fileName, reports.url, "hold"); + await browser.$('button[aria-label="Open file in preview browser"]').click(); + previewOpen = true; + // No WebDriver from here until the observer closed the preview. + const painted = await reports.next("painted", 30_000); + let sent: Awaited> | null = null; + if (painted?.path) { + await new Promise((resolve) => setTimeout(resolve, 500)); + nativeClickAtScreen(click); + await new Promise((resolve) => setTimeout(resolve, 400)); + typeNative("Undq"); + await new Promise((resolve) => setTimeout(resolve, 800)); + sent = await sendChord(path, "primary+z", "undo"); + await new Promise((resolve) => setTimeout(resolve, 800)); + typeNativeReturn(); + } + const title = (await reports.next("echo", 10_000))?.url ?? ""; + reports.requestClose(); + const closed = await awaitPreviewClosed(reports); + previewOpen = false; + const paint = await checkPreviewPaint(fileName, painted); + const filesAfter = await readFilesAfterPreview(fileName); + await refreshDesktopUiDocument(); + const typed = title.toLowerCase().includes("-peak-undq"); + const undone = title.toLowerCase().includes("echo--peak-"); + recordEvidence({ + cell: `preview-undo-${path}`, + passed: + paint.painted && + typed && + undone && + JSON.stringify(filesAfter) === JSON.stringify(filesBefore), + title, + closed, + filesBefore, + filesAfter, + sent, + }); + expect({ ...paint, typed, undone, files: filesAfter }).toEqual({ + painted: true, + sized: true, + typed: true, + undone: true, + files: filesBefore, + }); + } finally { + await closePreviewLeftOpen(reports, previewOpen); + reports.close(); + } +} + +describe("packaged Files undo and redo (#398)", () => { + for (const view of views) { + it(`driver: the undo chord undoes one step in the ${view} view`, async () => { + await measureCell({ view, direction: "undo", path: "driver", chord: "primary+z" }); + }); + for (const chord of redoChords) { + it(`driver: ${chord} redoes one step in the ${view} view`, async () => { + await measureCell({ view, direction: "redo", path: "driver", chord, redoAfter: "path" }); + }); + } + } + + it("driver: the undo chord undoes a formatting step in the rendered view", async () => { + await measureCell({ + view: "rendered", + direction: "undo", + path: "driver", + chord: "primary+z", + edit: "format", + }); + }); + + it("driver: the save chord still saves the source view", async () => { + const fileName = await openFreshFile("source", "undo-save-chord"); + await seedThroughPage("source", fileName, "kq"); + await dispatchPageChord("primary+s"); + await browser.waitUntil( + () => + NodeFS.readFileSync(NodePath.join(preparedProjectPath, fileName), "utf8").includes("kq"), + { timeoutMsg: "The save chord never wrote the edit to disk." }, + ); + }); + + it("driver: the undo chord still undoes in the chat composer", async () => { + await measureTextField("composer", "driver"); + }); + + it("driver: the preview browser paints a local HTML page (#417)", async () => { + await measurePreviewPaint(); + }); + + describe("native input (BIBCODE_E2E_NATIVE_INPUT=1)", function () { + before(function () { + if (!nativeInput) this.skip(); + }); + + for (const path of ["keystroke", "menu"] as const) { + for (const view of views) { + it(`${path}: one undo after two steps removes only the second in the ${view} view`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureTwoSteps(view, path); + }); + } + } + + for (const path of ["keystroke", "menu"] as const) { + const skipMenu = (context: Mocha.Context) => { + // The pinned menu library creates no predefined Undo or Redo item on GTK. + if (path === "menu" && platform === "linux") context.skip(); + }; + for (const view of views) { + it(`${path}: undo moves the ${view} view one step`, async function () { + skipMenu(this); + await measureCell({ view, direction: "undo", path, chord: "primary+z" }); + }); + const chords: readonly Chord[] = path === "menu" ? ["primary+shift+z"] : redoChords; + for (const chord of chords) { + for (const redoAfter of ["path", "toolbar"] as const) { + it(`${path}: ${path === "menu" ? "Redo" : chord} redoes the ${view} view after a ${redoAfter} undo`, async function () { + skipMenu(this); + await measureCell({ view, direction: "redo", path, chord, redoAfter }); + }); + } + } + } + it(`${path}: undo removes a formatting step in the rendered view`, async function () { + skipMenu(this); + await measureCell({ + view: "rendered", + direction: "undo", + path, + chord: "primary+z", + edit: "format", + }); + }); + } + + for (const kind of ["composer", "textarea"] as const) { + for (const path of ["keystroke", "menu"] as const) { + for (const direction of ["undo", "redo"] as const) { + it(`${path}: ${direction} still works in a ${kind === "composer" ? "chat composer" : "plain textarea"}`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureTextField(kind, path, direction); + }); + } + } + } + + for (const path of ["keystroke", "menu"] as const) { + for (const direction of ["undo", "redo"] as const) { + it(`${path}: ${direction} in the inline comment field leaves the file history alone`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureCommentIndependence(path, direction); + }); + } + } + + it("keystroke: the terminal keeps the undo chord", async () => { + await recordTerminalChord(); + }); + + for (const chord of ["primary+shift+z", "ctrl+y"] as const) { + it(`keystroke: the terminal keeps ${chord} off macOS`, async function () { + if (platform === "mac") this.skip(); + await recordTerminalChord(chord); + }); + } + + for (const path of ["keystroke", "menu"] as const) { + it(`${path}: undo in the Link URL field stays in the field`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measureLinkField(path); + }); + it(`${path}: undo in the preview browser stays in its page`, async function () { + if (path === "menu" && platform === "linux") this.skip(); + await measurePreviewFallback(path); + }); + } + + // Runs last: if the close guard broke, the window closes and ends the session. + it("menu: after a preview opened, Undo reaches Files and closing still asks (#418)", async function () { + if (platform !== "mac") this.skip(); + await measureMainWindowAfterPreview(); + }); + }); +}); diff --git a/apps/desktop/e2e/support/linux-text-field-undo.test.ts b/apps/desktop/e2e/support/linux-text-field-undo.test.ts new file mode 100644 index 0000000000..f08c2abeff --- /dev/null +++ b/apps/desktop/e2e/support/linux-text-field-undo.test.ts @@ -0,0 +1,93 @@ +// @vitest-environment happy-dom +// @effect-diagnostics nodeBuiltinImport:off - The test loads the injected preview script from disk. +// @effect-diagnostics globalTimers:off - The test waits for the script's own timer, as the page does. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +const source = NodeFS.readFileSync( + NodePath.join(import.meta.dirname, "../../src-tauri/src/preview/linux_text_field_undo.js"), + "utf8", +); +const execCommand = vi.fn(); + +// happy-dom marks no event trusted; WebKitGTK does for real input. +function trusted(event: T): T { + Object.defineProperty(event, "isTrusted", { value: true }); + return event; +} + +function typeInto(element: HTMLElement): void { + element.dispatchEvent(trusted(new InputEvent("input", { bubbles: true, composed: true }))); +} + +function ctrlZ(element: HTMLElement, isTrusted = true): KeyboardEvent { + const event = new KeyboardEvent("keydown", { + key: "z", + ctrlKey: true, + bubbles: true, + cancelable: true, + composed: true, + }); + element.focus(); + element.dispatchEvent(isTrusted ? trusted(event) : event); + return event; +} + +async function afterDispatch(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +beforeAll(() => { + document.execCommand = execCommand; + // oxlint-disable-next-line no-new-func -- evaluates the classic script the webview injects. + new Function(source)(); +}); + +beforeEach(() => { + document.body.replaceChildren(); + execCommand.mockClear(); +}); + +describe("Linux preview text field undo", () => { + it("undoes the user's edit in the focused textarea without cancelling the chord", async () => { + const textarea = document.body.appendChild(document.createElement("textarea")); + typeInto(textarea); + const event = ctrlZ(textarea); + expect(event.defaultPrevented).toBe(false); + await afterDispatch(); + expect(execCommand).toHaveBeenCalledExactlyOnceWith("undo"); + }); + + it("leaves another editor's edit alone when an untouched input has focus", async () => { + const editor = document.body.appendChild(document.createElement("div")); + editor.contentEditable = "true"; + const input = document.body.appendChild(document.createElement("input")); + typeInto(editor); + ctrlZ(input); + await afterDispatch(); + expect(execCommand).not.toHaveBeenCalled(); + }); + + it("leaves a chord the page's own later window listener cancelled", async () => { + const textarea = document.body.appendChild(document.createElement("textarea")); + const siteUndo = (event: Event) => event.preventDefault(); + window.addEventListener("keydown", siteUndo); + try { + typeInto(textarea); + ctrlZ(textarea); + await afterDispatch(); + } finally { + window.removeEventListener("keydown", siteUndo); + } + expect(execCommand).not.toHaveBeenCalled(); + }); + + it("ignores a synthetic chord the page dispatches", async () => { + const textarea = document.body.appendChild(document.createElement("textarea")); + typeInto(textarea); + ctrlZ(textarea, false); + await afterDispatch(); + expect(execCommand).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/e2e/support/test-project.test.ts b/apps/desktop/e2e/support/test-project.test.ts index 7b5d1fd339..9fe41fac14 100644 --- a/apps/desktop/e2e/support/test-project.test.ts +++ b/apps/desktop/e2e/support/test-project.test.ts @@ -17,6 +17,7 @@ import { composerProviderProfiles, completeDesktopUiSlowTurn, deferDesktopUiTestContextCleanupUntilExit, + fixtureToolProbeProblem, prepareDesktopUiTestContext, type DesktopUiDirectoryRemover, type DesktopUiExitRegistrar, @@ -147,6 +148,44 @@ describe.each([ expect(environment.BIBCODE_E2E_SHIM_DIRECTORY).toBe(context.shimDirectory); }); + it("pins the disabled Antigravity instance to an absent absolute executable", () => { + const environment: NodeJS.ProcessEnv = { BIBCODE_E2E_PLATFORM: platform }; + const context = prepareDesktopUiTestContext(environment); + contexts.push(context); + const settings = JSON.parse( + NodeFS.readFileSync(NodePath.join(context.stateRoot, "userdata", "settings.json"), "utf8"), + ) as { + readonly providers: Record< + string, + { readonly enabled: boolean; readonly binaryPath: string } + >; + }; + const antigravity = settings.providers.antigravity; + + expect(antigravity?.enabled).toBe(false); + expect(NodePath.isAbsolute(antigravity?.binaryPath ?? "")).toBe(true); + expect(NodeFS.existsSync(antigravity?.binaryPath ?? "")).toBe(false); + }); + + it("isolates maintained tools: a fixture codegraph first on PATH and no latest-version lookups", () => { + const environment: NodeJS.ProcessEnv = { BIBCODE_E2E_PLATFORM: platform }; + const context = prepareDesktopUiTestContext(environment); + contexts.push(context); + const settings = JSON.parse( + NodeFS.readFileSync(NodePath.join(context.stateRoot, "userdata", "settings.json"), "utf8"), + ) as { readonly enableProviderUpdateChecks?: boolean }; + + expect(settings.enableProviderUpdateChecks).toBe(false); + expect( + NodeFS.existsSync(NodePath.join(context.shimDirectory, `codegraph${executableSuffix}`)), + ).toBe(true); + expect(environment.BIBCODE_E2E_TOOL_PROBE_LOG).toBe(context.toolProbeLogPath); + expect(NodeFS.readFileSync(context.toolProbeLogPath, "utf8")).toBe(""); + expect(fixtureToolProbeProblem(context.toolProbeLogPath)).toMatch(/real codegraph/); + NodeFS.writeFileSync(context.toolProbeLogPath, "codegraph --version\n"); + expect(fixtureToolProbeProblem(context.toolProbeLogPath)).toBeNull(); + }); + it("seeds the Profiler only when BIBCODE_E2E_PROFILER is 1", () => { const read = (environment: NodeJS.ProcessEnv): { readonly enableProfiler?: boolean } => { const context = prepareDesktopUiTestContext(environment); @@ -274,6 +313,92 @@ describe.each([ }); }); +it.runIf(!isNativeWindowsHost)( + "logs every fixture codegraph start and answers its version probe", + () => { + const environment: NodeJS.ProcessEnv = { BIBCODE_E2E_PLATFORM: "linux" }; + const context = prepareDesktopUiTestContext(environment); + contexts.push(context); + const probe = NodeChildProcess.spawnSync( + NodePath.join(context.shimDirectory, "codegraph"), + ["--version"], + { env: { ...process.env, ...environment }, encoding: "utf8" }, + ); + + expect(probe.status, probe.stderr).toBe(0); + expect(probe.stdout.trim()).toBe("0.0.0"); + expect(NodeFS.readFileSync(context.toolProbeLogPath, "utf8")).toBe("codegraph --version\n"); + }, +); + +it("keeps the startup probe evidence when a worker prepares the same run again", () => { + const environment: NodeJS.ProcessEnv = { BIBCODE_E2E_PLATFORM: "linux" }; + const context = prepareDesktopUiTestContext(environment); + contexts.push(context); + NodeFS.writeFileSync(context.toolProbeLogPath, "codegraph --version\n"); + + // The WDIO worker loads the config again with the launcher's run root and artifact directory. + prepareDesktopUiTestContext(environment); + + expect(fixtureToolProbeProblem(context.toolProbeLogPath)).toBeNull(); +}); + +it("starts a new run's probe log empty even in a reused artifact directory", () => { + const first = prepareDesktopUiTestContext({ BIBCODE_E2E_PLATFORM: "linux" }); + contexts.push(first); + NodeFS.writeFileSync(first.toolProbeLogPath, "codegraph --version\n"); + + // A new launcher run pointed at the same artifact directory, as a lab script does. + const next = prepareDesktopUiTestContext({ + BIBCODE_E2E_PLATFORM: "linux", + BIBCODE_E2E_ARTIFACT_DIR: first.artifactDirectory, + }); + contexts.push(next); + + expect(fixtureToolProbeProblem(next.toolProbeLogPath)).toMatch(/real codegraph/); +}); + +// The packaged app puts its login shell's PATH first (`shell_environment::hydrate_posix_path`), +// and a profile such as macOS `path_helper` moves system directories ahead of inherited ones. +for (const shell of ["/bin/zsh", "/bin/bash"]) { + it.runIf(!isNativeWindowsHost && NodeFS.existsSync(shell))( + `keeps the fixture shims first in the PATH a ${NodePath.basename(shell)} login shell reports`, + () => { + const hostProfiles = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "host-profiles-")); + hostTemporaryDirectories.push(hostProfiles); + for (const profile of [".zshrc", ".zshenv", ".profile"]) { + NodeFS.writeFileSync( + NodePath.join(hostProfiles, profile), + 'PATH="/opt/host-tools:$PATH"\n', + ); + } + const environment: NodeJS.ProcessEnv = { + ...process.env, + BIBCODE_E2E_PLATFORM: "linux", + BIBCODE_E2E_RUN_ROOT: undefined, + BIBCODE_E2E_ARTIFACT_DIR: undefined, + BIBCODE_E2E_REAL_PROVIDERS: undefined, + PATH: "/usr/bin:/bin", + // A host's own shell start-up directories, whose profiles put a real tool first. + ZDOTDIR: hostProfiles, + XDG_CONFIG_HOME: hostProfiles, + ENV: NodePath.join(hostProfiles, ".profile"), + BASH_ENV: NodePath.join(hostProfiles, ".profile"), + }; + const context = prepareDesktopUiTestContext(environment); + contexts.push(context); + const probe = NodeChildProcess.spawnSync( + shell, + ["-ilc", "printf '%s' __PATH_START__; printf '%s' \"$PATH\"; printf '%s' __PATH_END__"], + { env: { ...environment, SHELL: shell }, encoding: "utf8", timeout: 20_000 }, + ); + const reported = /__PATH_START__(.*)__PATH_END__/s.exec(probe.stdout)?.[1] ?? ""; + + expect(reported.split(":")[0], probe.stderr).toBe(context.shimDirectory); + }, + ); +} + it.runIf(isNativeWindowsHost)( "executes the Cursor action shim through the native Windows command processor", () => { @@ -910,6 +1035,7 @@ describe("archiveAndCleanupDesktopUiTestContext", () => { fixtureUserHomePath: NodePath.join(runRoot, "fixture-user-home"), nativeActionLogPath: NodePath.join(artifactDirectory, "native-actions.jsonl"), providerInputLogPath: NodePath.join(runRoot, "provider-input.jsonl"), + toolProbeLogPath: NodePath.join(artifactDirectory, "tool-probes.log"), }; let removalOptions: Parameters[1] | undefined; const removeDirectory: DesktopUiDirectoryRemover = (path, options) => { diff --git a/apps/desktop/e2e/support/test-project.ts b/apps/desktop/e2e/support/test-project.ts index 69171ead07..353b7af091 100644 --- a/apps/desktop/e2e/support/test-project.ts +++ b/apps/desktop/e2e/support/test-project.ts @@ -119,6 +119,8 @@ export interface DesktopUiTestContext { readonly fixtureUserHomePath: string; readonly nativeActionLogPath: string; readonly providerInputLogPath: string; + /** Every start of a fixture tool, one line each, so a run can prove no real tool was reached. */ + readonly toolProbeLogPath: string; } export type DesktopUiDirectoryRemover = (path: string, options: NodeFS.RmDirOptions) => void; @@ -1249,6 +1251,31 @@ function createProviderShims(shimDirectory: string, isWindows: boolean): void { NodeFS.writeFileSync(NodePath.join(shimDirectory, `${provider}-fixture.mjs`), source); } + // The maintained tool BiBCode probes on PATH: it logs each start and reports a fixture version. + if (isWindows) { + NodeFS.writeFileSync( + NodePath.join(shimDirectory, "codegraph.cmd"), + [ + '@echo codegraph %*>>"%BIBCODE_E2E_TOOL_PROBE_LOG%"', + '@if "%~1"=="--version" (echo 0.0.0& exit /b 0)', + "@exit /b 1", + "", + ].join("\r\n"), + ); + } else { + writeExecutable( + NodePath.join(shimDirectory, "codegraph"), + [ + "#!/bin/sh", + 'printf "%s\\n" "codegraph $*" >> "$BIBCODE_E2E_TOOL_PROBE_LOG"', + 'if [ "$1" = "--version" ]; then printf "%s\\n" "0.0.0"; exit 0; fi', + "exit 1", + "", + ].join("\n"), + false, + ); + } + if (isWindows) { NodeFS.writeFileSync( NodePath.join(shimDirectory, "cursor.cmd"), @@ -1338,12 +1365,19 @@ function writeProviderSettings( ...(options.realProviders ? { enableTerminalAgentActivity: true, terminal: { webglEnabled: false } } : { + // No latest-version lookups: the fixture tool and providers are not real releases. + enableProviderUpdateChecks: false, providers: { codex: { enabled: true, binaryPath: executablePath("codex") }, claudeAgent: { enabled: true, binaryPath: executablePath("claude") }, cursor: { enabled: true, binaryPath: executablePath("cursor-agent") }, grok: { enabled: true, binaryPath: executablePath("grok") }, opencode: { enabled: true, binaryPath: executablePath("opencode") }, + // Disabled, and pinned to an absent path so no agy on PATH is ever probed. + antigravity: { + enabled: false, + binaryPath: NodePath.join(shimDirectory, "absent", isWindows ? "agy.cmd" : "agy"), + }, }, providerInstances: { cursor: { @@ -1482,6 +1516,7 @@ export function prepareDesktopUiTestContext( ); const nativeActionLogPath = NodePath.join(artifactDirectory, "native-actions.jsonl"); const providerInputLogPath = NodePath.join(runRoot, "provider-input.jsonl"); + const toolProbeLogPath = NodePath.join(artifactDirectory, "tool-probes.log"); NodeFS.mkdirSync(stateRoot, { recursive: true }); NodeFS.mkdirSync(shimDirectory, { recursive: true }); @@ -1495,6 +1530,11 @@ export function prepareDesktopUiTestContext( NodeFS.writeFileSync(nativeActionLogPath, ""); } NodeFS.writeFileSync(providerInputLogPath, ""); + // A WDIO worker prepares the run again after the app's startup probe; keep what it logged. + // A new run, even in a reused artifact directory, starts from an empty log. + if (environment.BIBCODE_E2E_TOOL_PROBE_LOG !== toolProbeLogPath) { + NodeFS.writeFileSync(toolProbeLogPath, ""); + } initializeGitProject(projectPath); writeFixtureFiles(fixtureUserHomePath, cursorInventoryFiles); createProviderShims(shimDirectory, isWindows); @@ -1515,6 +1555,7 @@ export function prepareDesktopUiTestContext( environment.BIBCODE_E2E_USER_HOME = fixtureUserHomePath; environment.BIBCODE_E2E_NATIVE_ACTION_LOG = nativeActionLogPath; environment.BIBCODE_E2E_PROVIDER_INPUT_LOG = providerInputLogPath; + environment.BIBCODE_E2E_TOOL_PROBE_LOG = toolProbeLogPath; environment.BIBCODE_HOME = stateRoot; if (realProviders) { // Keep HOME and PATH: the provider CLIs find their own sign-ins there. @@ -1529,6 +1570,14 @@ export function prepareDesktopUiTestContext( } if (!realProviders) { environment.PATH = `${shimDirectory}${NodePath.delimiter}${environment.PATH ?? ""}`; + if (!isWindows) { + // Every shell start-up directory points into the fixture HOME, so no host profile runs. + environment.ZDOTDIR = fixtureUserHomePath; + environment.XDG_CONFIG_HOME = NodePath.join(fixtureUserHomePath, ".config"); + Reflect.deleteProperty(environment, "ENV"); + Reflect.deleteProperty(environment, "BASH_ENV"); + pinShimsInLoginShellPath(fixtureUserHomePath, shimDirectory); + } } environment.RUST_LOG ??= "bibcode=debug"; environment.BIBCODE_LOG = `${environment.BIBCODE_LOG ?? environment.RUST_LOG},bibcode::desktop_e2e=info`; @@ -1542,6 +1591,7 @@ export function prepareDesktopUiTestContext( fixtureUserHomePath, nativeActionLogPath, providerInputLogPath, + toolProbeLogPath, }; } @@ -1578,6 +1628,35 @@ export function deferDesktopUiTestContextCleanupUntilExit( }); } +/** + * The packaged app puts its login shell's PATH ahead of the one it inherited, and a system profile + * (macOS `path_helper`, a Linux `/etc/profile`) can move real tool directories ahead of the shims. + * The fixture HOME's own profiles run last, so they put the shims back in front. + */ +function pinShimsInLoginShellPath(home: string, shimDirectory: string): void { + const quoted = `'${shimDirectory.replaceAll("'", "'\\''")}'`; + const posix = `PATH=${quoted}:"$PATH"; export PATH\n`; + for (const profile of [".zshrc", ".bash_profile", ".profile"]) { + NodeFS.writeFileSync(NodePath.join(home, profile), posix); + } + const fish = NodePath.join(home, ".config", "fish"); + NodeFS.mkdirSync(fish, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(fish, "config.fish"), `set -gx PATH ${quoted} $PATH\n`); +} + +/** + * Why the run reached no fixture tool, or null. The app probes codegraph at startup; a log + * without the fixture's version probe means a real codegraph on PATH answered it instead. + */ +export function fixtureToolProbeProblem(toolProbeLogPath: string): string | null { + const log = NodeFS.existsSync(toolProbeLogPath) + ? NodeFS.readFileSync(toolProbeLogPath, "utf8") + : ""; + return log.split(/\r?\n/).includes("codegraph --version") + ? null + : `The packaged app never started the fixture codegraph, so a real codegraph on PATH or none answered its probe (${toolProbeLogPath}).`; +} + export const desktopUiFixture = { projectName: FIXTURE_PROJECT_NAME, streamedResponse: STREAMED_RESPONSE, diff --git a/apps/desktop/e2e/wdio.conf.ts b/apps/desktop/e2e/wdio.conf.ts index c1ecda2ab5..5af4f2e4c0 100644 --- a/apps/desktop/e2e/wdio.conf.ts +++ b/apps/desktop/e2e/wdio.conf.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off - WDIO configuration manages host test artifacts. // @effect-diagnostics globalConsole:off - WDIO configuration reports the retained artifact path. +// @effect-diagnostics globalTimers:off - WDIO waits for the packaged app's startup tool probe. import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; @@ -20,6 +21,7 @@ import { } from "./support/app-lifecycle.ts"; import { deferDesktopUiTestContextCleanupUntilExit, + fixtureToolProbeProblem, prepareDesktopUiTestContext, } from "./support/test-project.ts"; import { normalizeWebDriverRequest } from "./support/webdriver-request.ts"; @@ -69,6 +71,7 @@ const desktopUiSpecFiles = "./specs/mermaid-diagrams.e2e.ts", "./specs/files-binary-preview.e2e.ts", "./specs/files-rich-markdown.e2e.ts", + "./specs/files-undo-shortcuts.e2e.ts", "./specs/appearance-themes.e2e.ts", "./specs/source-control-review.e2e.ts", "./specs/host-dashboard.e2e.ts", @@ -233,6 +236,16 @@ export const config = { if (!pluginReady) { throw new Error("The packaged Tauri WebDriver plugin did not initialize."); } + // The app probes its tools at startup; a real one on PATH must never answer in a test run. + if (process.env.BIBCODE_E2E_REAL_PROVIDERS !== "1") { + // Up to 30 s for the startup probe to finish. + for (let wait = 0; wait < 120; wait += 1) { + if (fixtureToolProbeProblem(testContext.toolProbeLogPath) === null) break; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + const problem = fixtureToolProbeProblem(testContext.toolProbeLogPath); + if (problem !== null) throw new Error(problem); + } }, beforeTest: async () => { await ensureLiveDesktopUiWebview(); @@ -285,5 +298,11 @@ export const config = { // until process exit so the Tauri service has released Windows filesystem handles first. deferDesktopUiTestContextCleanupUntilExit(testContext, process); console.log(`Desktop UI artifacts: ${testContext.artifactDirectory}`); + // A `before` hook error is only logged, so the run fails here when a real tool answered. + const probeProblem = + process.env.BIBCODE_E2E_REAL_PROVIDERS === "1" + ? null + : fixtureToolProbeProblem(testContext.toolProbeLogPath); + if (probeProblem !== null) throw new Error(probeProblem); }, }; diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 9332cb2097..facc8df1ad 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -19,6 +19,7 @@ tauri-build.workspace = true [dependencies] base64.workspace = true +dirs.workspace = true futures-util.workspace = true if-addrs.workspace = true libc.workspace = true @@ -77,6 +78,8 @@ windows = { workspace = true, features = [ "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Memory", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_WindowsAndMessaging", ] } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/apps/desktop/src-tauri/permissions/desktop-bridge.toml b/apps/desktop/src-tauri/permissions/desktop-bridge.toml index d63d61aeae..78bf92e81e 100644 --- a/apps/desktop/src-tauri/permissions/desktop-bridge.toml +++ b/apps/desktop/src-tauri/permissions/desktop-bridge.toml @@ -37,6 +37,8 @@ commands.allow = [ "desktop_bridge_set_wsl_backend_enabled", "desktop_bridge_set_wsl_distro", "desktop_bridge_set_wsl_only", + "desktop_bridge_get_linux_software_rendering", + "desktop_bridge_set_linux_software_rendering", "desktop_bridge_set_theme", "desktop_bridge_show_context_menu", "desktop_bridge_get_update_state", diff --git a/apps/desktop/src-tauri/src/appdir_working_directory.rs b/apps/desktop/src-tauri/src/appdir_working_directory.rs new file mode 100644 index 0000000000..dc1d986b54 --- /dev/null +++ b/apps/desktop/src-tauri/src/appdir_working_directory.rs @@ -0,0 +1,504 @@ +//! Linux AppDir: start the same way whatever the caller's working folder (#412). +//! The AppImage bundler rewrites the bundled WebKitGTK's helper paths to +//! `././/lib/...`, so WebKit finds `WebKitNetworkProcess` and its injected +//! bundle relative to the working folder, and its release build ignores +//! `WEBKIT_EXEC_PATH`. `AppRun` changes to `/usr` and sets up the bundled +//! GTK environment; the generated `bibcode://` handler of an extracted AppDir starts +//! the binary directly and skips both, and in a Hyprland VM its page then stayed +//! blank. So `main` hands such a launch to this bundle's `AppRun` once, and if that +//! fails, at least changes to `usr` itself. See +//! `docs/plans/2026-11-21-linux-software-rendering-design.md`. +// Also compiled for tests on other Unix hosts; only Linux applies it. +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::OnceLock; + +/// Set only on the handoff to `AppRun` and removed by the process it starts, so a launcher +/// that comes straight back to the binary ends in one handoff, not a loop. +pub(crate) const HANDOFF_GUARD: &str = "BIBCODE_APPRUN_HANDOFF"; + +/// `` of an executable at `/usr/bin/` whose `/AppRun` passes +/// `launcher_ok`. Mirrors `extracted_appdir` in `apps/server/src/process/appimage.rs` +/// (private to that crate), including its refusal of `/` as a root, so a system install +/// at `/usr/bin` never qualifies. +pub(crate) fn bundle_root(exe: &Path, launcher_ok: impl Fn(&Path) -> bool) -> Option { + let bin = exe.parent()?; + let usr = bin.parent()?; + let root = usr.parent()?; + (bin.ends_with("bin") && usr.ends_with("usr") && root.parent().is_some() && launcher_ok(root)) + .then(|| root.to_path_buf()) +} + +/// Whether `/AppRun` looks like this bundle's launcher: a regular executable file, or a +/// symlink that resolves to a file inside the bundle. +#[cfg(unix)] +pub(crate) fn launcher_belongs_to(root: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + let launcher = root.join("AppRun"); + let Ok(metadata) = std::fs::symlink_metadata(&launcher) else { + return false; + }; + if metadata.file_type().is_symlink() { + return match ( + std::fs::canonicalize(&launcher), + std::fs::canonicalize(root), + ) { + (Ok(target), Ok(root)) => target.starts_with(&root) && target.is_file(), + _ => false, + }; + } + metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 +} + +/// The AppImage runtime's markers besides `APPDIR`. Only this bundle's own mount may keep +/// them: inherited from another AppImage application, `APPIMAGE` would make a restart start +/// that application (Tauri restarts `APPIMAGE` when it is set). +pub(crate) const APPIMAGE_MARKERS: [&str; 3] = ["APPIMAGE", "ARGV0", "OWD"]; + +/// Whether `APPDIR` names this very bundle: its own `AppRun`, or its mounted AppImage, started +/// this process. An empty `APPDIR` or another application's AppDir (a link clicked inside +/// another AppImage) does not count. +pub(crate) fn launched_by_this_bundle( + root: &Path, + appdir: Option<&OsStr>, + canonical: impl Fn(&Path) -> Option, +) -> bool { + match ( + appdir + .filter(|value| !value.is_empty()) + .and_then(|value| canonical(Path::new(value))), + canonical(root), + ) { + (Some(appdir), Some(root)) => appdir == root, + _ => false, + } +} + +/// Whether to hand this launch to the bundle's `AppRun`: never after a handoff, and +/// otherwise unless this bundle launched it. +pub(crate) fn needs_handoff( + root: &Path, + appdir: Option<&OsStr>, + guard: bool, + canonical: impl Fn(&Path) -> Option, +) -> bool { + !guard && !launched_by_this_bundle(root, appdir, canonical) +} + +/// The overrides that strip another AppImage bundle, named by an inherited `APPDIR`, from +/// `environment`. The handoff drops that `APPDIR`, and with it the only marker the server's +/// child filter finds the other bundle's library and path entries by, so they go here +/// instead (#413). The same validation as that filter: an absolute `APPDIR` other than `/` +/// with an `AppRun`, and not this bundle, whose own entries the desktop needs. +#[cfg(target_os = "linux")] +pub(crate) fn foreign_bundle_overrides( + environment: &std::collections::BTreeMap, + root: &Path, + canonical: impl Fn(&Path) -> Option, +) -> Vec<(OsString, Option)> { + let Some(appdir) = environment.get(OsStr::new("APPDIR")) else { + return Vec::new(); + }; + let appdir = Path::new(appdir); + if !(appdir.is_absolute() + && appdir.parent().is_some() + && !launched_by_this_bundle(root, Some(appdir.as_os_str()), &canonical) + && appdir.join("AppRun").exists()) + { + return Vec::new(); + } + // Entries may name the AppDir by its inherited spelling or, behind a symlink, its target. + let roots: Vec<_> = std::iter::once(appdir.to_path_buf()) + .chain(canonical(appdir).filter(|resolved| resolved != appdir)) + .collect(); + bibcode_server::process::appimage_bundle_overrides(environment, &roots) +} + +/// The handoff: this bundle's `AppRun` with the same arguments (the `bibcode://` URL among +/// them), the guard set, `overrides` applied, and the inherited `APPDIR` and AppImage markers +/// removed: they belong to whatever launched this process, so `AppRun`'s GTK hook uses this +/// bundle's paths and a restart starts this bundle. +pub(crate) fn handoff_command( + root: &Path, + args: impl IntoIterator, + overrides: impl IntoIterator)>, +) -> Command { + let mut command = Command::new(root.join("AppRun")); + for (name, value) in overrides { + match value { + Some(value) => command.env(name, value), + None => command.env_remove(name), + }; + } + command + .args(args) + .env(HANDOFF_GUARD, "1") + .env_remove("APPDIR"); + for marker in APPIMAGE_MARKERS { + command.env_remove(marker); + } + command +} + +struct Startup { + /// `Ok(true)` when `main` changed the working folder, or the reason it could not. + moved: Result, + handoff_error: Option, +} + +static STARTUP: OnceLock = OnceLock::new(); + +/// Hands an AppDir launch that skipped this bundle's `AppRun` to it once, so every route gets +/// the same working folder and environment; if that fails, moves into `/usr`. +/// +/// # Safety +/// +/// It removes the handoff guard from the process environment, so no other thread may exist +/// yet: `main` calls it before Tauri, Tokio, GTK or WebKit start. +#[cfg(target_os = "linux")] +pub unsafe fn enter_appdir_usr() { + use std::os::unix::process::CommandExt; + let guard = std::env::var_os(HANDOFF_GUARD).is_some(); + if guard { + // SAFETY: the caller guarantees the process is still single-threaded. Removed so + // terminals, providers and a later restart never inherit it. + unsafe { std::env::remove_var(HANDOFF_GUARD) }; + } + let Some(root) = std::env::current_exe() + .ok() + .and_then(|exe| bundle_root(&exe, launcher_belongs_to)) + else { + return; + }; + let appdir = std::env::var_os("APPDIR"); + let canonical = |path: &Path| std::fs::canonicalize(path).ok(); + let handoff_error = needs_handoff(&root, appdir.as_deref(), guard, canonical) + // `exec` returns only when it failed. + .then(|| { + let environment = std::env::vars_os().collect(); + let overrides = foreign_bundle_overrides(&environment, &root, canonical); + handoff_command(&root, std::env::args_os().skip(1), overrides) + .exec() + .to_string() + }); + // Still here without this bundle's launch: another AppImage's markers would make Tauri's + // restart (and the AppImage checks) target that application. + if !launched_by_this_bundle(&root, appdir.as_deref(), canonical) { + for marker in APPIMAGE_MARKERS { + // SAFETY: the caller guarantees the process is still single-threaded. + unsafe { std::env::remove_var(marker) }; + } + } + let usr = root.join("usr"); + let moved = if std::env::current_dir().ok().as_deref() == Some(usr.as_path()) { + Ok(false) + } else { + std::env::set_current_dir(&usr) + .map(|()| true) + .map_err(|error| error.to_string()) + }; + let _ = STARTUP.set(Startup { + moved, + handoff_error, + }); +} + +/// Logs what `enter_appdir_usr` did, once the log sink exists. +pub(crate) fn record_startup() { + let Some(startup) = STARTUP.get() else { + return; + }; + if let Some(error) = &startup.handoff_error { + tracing::warn!(%error, "could not restart through the AppDir's AppRun"); + } + match &startup.moved { + Ok(true) => tracing::info!( + "started outside AppRun; working folder moved to the AppDir's usr folder for WebKit" + ), + Err(error) => tracing::warn!( + %error, + "could not move to the AppDir's usr folder; WebKit may not find its helper processes" + ), + Ok(false) => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::{PermissionsExt, symlink}; + + #[test] + fn appdir_working_directory_finds_the_bundle_root() { + let exe = Path::new("/opt/squashfs-root/usr/bin/bibcode-desktop"); + assert_eq!( + bundle_root(exe, |root| root == Path::new("/opt/squashfs-root")).as_deref(), + Some(Path::new("/opt/squashfs-root")) + ); + assert_eq!(bundle_root(exe, |_| false), None); + } + + #[test] + fn appdir_working_directory_refuses_a_system_install_beside_a_stray_apprun() { + // `/usr/bin/bibcode-desktop` with a `/AppRun`: the root would be `/`. + assert_eq!( + bundle_root(Path::new("/usr/bin/bibcode-desktop"), |_| true), + None + ); + for exe in [ + "/opt/app/bin/bibcode-desktop", + "/opt/app/usr/libexec/bibcode-desktop", + "bibcode-desktop", + ] { + assert_eq!(bundle_root(Path::new(exe), |_| true), None, "{exe}"); + } + } + + #[test] + fn appdir_working_directory_accepts_only_the_bundles_own_launcher() { + let directory = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(directory.path()).unwrap(); + std::fs::create_dir_all(root.join("usr/bin")).unwrap(); + let binary = root.join("usr/bin/bibcode-desktop"); + std::fs::write(&binary, "").unwrap(); + let launcher = root.join("AppRun"); + let set_mode = |path: &Path, mode| { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap() + }; + assert!(!launcher_belongs_to(&root), "missing"); + + std::fs::create_dir(&launcher).unwrap(); + assert!(!launcher_belongs_to(&root), "a directory"); + std::fs::remove_dir(&launcher).unwrap(); + + std::fs::write(&launcher, "#!/bin/sh\n").unwrap(); + set_mode(&launcher, 0o644); + assert!(!launcher_belongs_to(&root), "not executable"); + set_mode(&launcher, 0o755); + assert!(launcher_belongs_to(&root), "an executable file"); + std::fs::remove_file(&launcher).unwrap(); + + symlink("/bin/sh", &launcher).unwrap(); + assert!(!launcher_belongs_to(&root), "a symlink out of the bundle"); + std::fs::remove_file(&launcher).unwrap(); + + symlink("usr/bin/bibcode-desktop", &launcher).unwrap(); + assert!(launcher_belongs_to(&root), "a symlink inside the bundle"); + } + + #[test] + fn appdir_working_directory_hands_off_unless_this_bundles_launcher_ran() { + let root = Path::new("/opt/BiBCode.AppDir"); + let canonical = |path: &Path| Some(path.to_path_buf()); + let handoff = |appdir: Option<&str>, guard| { + needs_handoff(root, appdir.map(OsStr::new), guard, canonical) + }; + assert!(handoff(None, false), "no APPDIR"); + assert!(handoff(Some(""), false), "empty APPDIR"); + assert!( + handoff(Some("/tmp/.mount_OtherApp"), false), + "another app's APPDIR" + ); + assert!( + !handoff(Some("/opt/BiBCode.AppDir"), false), + "this bundle's AppRun ran" + ); + // After one handoff the guard wins, whatever APPDIR says. + assert!(!handoff(None, true)); + assert!(!handoff(Some("/tmp/.mount_OtherApp"), true)); + } + + #[test] + fn appdir_working_directory_keeps_appimage_markers_only_for_this_bundles_launch() { + let canonical = |path: &Path| Some(path.to_path_buf()); + // A mounted BiBCode AppImage: its runtime set APPDIR to the mount the binary runs from. + let mount = Path::new("/tmp/.mount_BiBCodeX1"); + assert!(launched_by_this_bundle( + mount, + Some(OsStr::new("/tmp/.mount_BiBCodeX1")), + canonical + )); + // An extracted AppDir started from inside another AppImage application. + let extracted = Path::new("/opt/squashfs-root"); + for appdir in [Some("/tmp/.mount_OtherApp"), Some(""), None] { + assert!( + !launched_by_this_bundle(extracted, appdir.map(OsStr::new), canonical), + "{appdir:?}" + ); + } + } + + #[test] + fn appdir_working_directory_handoff_forwards_the_link_and_sets_the_guard() { + let command = handoff_command( + Path::new("/opt/BiBCode.AppDir"), + [OsString::from("bibcode://open?x=1")], + [], + ); + assert_eq!(command.get_program(), "/opt/BiBCode.AppDir/AppRun"); + assert_eq!( + command.get_args().collect::>(), + vec![OsStr::new("bibcode://open?x=1")] + ); + let envs: Vec<_> = command.get_envs().collect(); + assert!(envs.contains(&(OsStr::new(HANDOFF_GUARD), Some(OsStr::new("1"))))); + assert!(envs.contains(&(OsStr::new("APPDIR"), None))); + // Another AppImage's markers do not reach the handoff, so its restart starts BiBCode. + for marker in APPIMAGE_MARKERS { + assert!(envs.contains(&(OsStr::new(marker), None)), "{marker}"); + } + // The process the handoff starts sees the guard and does not hand off again. + assert!(!needs_handoff( + Path::new("/opt/BiBCode.AppDir"), + None, + envs.iter().any(|(name, _)| *name == HANDOFF_GUARD), + |path| Some(path.to_path_buf()) + )); + } + + /// The environment the handoff gives `AppRun`, with every inherited variable that the + /// command neither overrides nor removes. + #[cfg(target_os = "linux")] + fn handoff_environment( + environment: &std::collections::BTreeMap, + root: &Path, + ) -> std::collections::BTreeMap { + let canonical = |path: &Path| Some(path.to_path_buf()); + let overrides = foreign_bundle_overrides(environment, root, canonical); + let command = handoff_command(root, [], overrides); + let mut result = environment.clone(); + for (name, value) in command.get_envs() { + match value { + Some(value) => result.insert(name.to_owned(), value.to_owned()), + None => result.remove(name), + }; + } + result + } + + #[cfg(target_os = "linux")] + #[test] + fn appdir_working_directory_handoff_strips_another_bundles_entries() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("BiBCode.AppDir"); + // Another application's extracted AppDir, and another AppImage's mount. + for other in ["Other.AppDir", ".mount_OtherAB12"] { + let other = directory.path().join(other); + for bundle in [&root, &other] { + std::fs::create_dir_all(bundle).unwrap(); + std::fs::write(bundle.join("AppRun"), "launcher").unwrap(); + } + let (o, r) = (other.display(), root.display()); + let environment = std::collections::BTreeMap::from([ + ("APPDIR".into(), other.clone().into_os_string()), + ("APPIMAGE".into(), "/opt/Other.AppImage".into()), + ( + "LD_LIBRARY_PATH".into(), + format!("{o}/usr/lib:{r}/usr/lib:/host/lib").into(), + ), + ("PATH".into(), format!("{o}/usr/bin:/usr/bin").into()), + ( + "XDG_DATA_DIRS".into(), + format!("{o}/usr/share:/usr/share").into(), + ), + ( + "GIO_MODULE_DIR".into(), + format!("{o}/usr/lib/gio/modules").into(), + ), + ("GTK_DATA_PREFIX".into(), format!("{o}/usr").into()), + ("HOME".into(), "/home/test-user".into()), + ]); + let handed = handoff_environment(&environment, &root); + let value = |name: &str| handed.get(OsStr::new(name)).cloned(); + // This bundle's own entries stay: the desktop and WebKit need them. + assert_eq!( + value("LD_LIBRARY_PATH"), + Some(format!("{r}/usr/lib:/host/lib").into()), + "{o}" + ); + assert_eq!(value("PATH"), Some("/usr/bin".into()), "{o}"); + assert_eq!(value("XDG_DATA_DIRS"), Some("/usr/share".into()), "{o}"); + for gone in ["GIO_MODULE_DIR", "GTK_DATA_PREFIX", "APPDIR", "APPIMAGE"] { + assert_eq!(value(gone), None, "{gone} from {o}"); + } + assert_eq!(value("HOME"), Some("/home/test-user".into())); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn appdir_working_directory_handoff_strips_a_symlinked_bundle_by_both_spellings() { + let directory = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(directory.path()).unwrap(); + let root = base.join("BiBCode.AppDir"); + let other = base.join("Other.AppDir"); + for bundle in [&root, &other] { + std::fs::create_dir_all(bundle).unwrap(); + std::fs::write(bundle.join("AppRun"), "launcher").unwrap(); + } + let link = base.join("other-link"); + symlink(&other, &link).unwrap(); + let environment = std::collections::BTreeMap::from([ + ("APPDIR".into(), link.clone().into_os_string()), + ( + "LD_LIBRARY_PATH".into(), + format!( + "{}/usr/lib:{}/usr/lib:/host/lib", + other.display(), + link.display() + ) + .into(), + ), + ]); + let overrides = + foreign_bundle_overrides(&environment, &root, |path| std::fs::canonicalize(path).ok()); + assert!( + overrides.contains(&("LD_LIBRARY_PATH".into(), Some("/host/lib".into()))), + "{overrides:?}" + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn appdir_working_directory_handoff_keeps_entries_without_another_bundle() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("BiBCode.AppDir"); + let not_appdir = directory.path().join("NotAnAppDir"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(¬_appdir).unwrap(); + std::fs::write(root.join("AppRun"), "launcher").unwrap(); + let library_path: OsString = format!( + "{}/usr/lib:{}/usr/lib:/usr/lib:/host/lib", + root.display(), + not_appdir.display() + ) + .into(); + // No APPDIR (a launcher started the binary), an empty one, this bundle's own (a + // genuine AppImage or AppRun start), or one that is no AppDir: nothing is stripped. + for appdir in [ + None, + Some(OsString::new()), + Some(root.clone().into_os_string()), + Some(not_appdir.clone().into_os_string()), + Some("/usr".into()), + Some("/".into()), + Some("relative/AppDir".into()), + ] { + let mut environment = std::collections::BTreeMap::from([ + ("LD_LIBRARY_PATH".into(), library_path.clone()), + ("GTK_THEME".into(), "Adwaita:dark".into()), + ]); + if let Some(appdir) = &appdir { + environment.insert("APPDIR".into(), appdir.clone()); + } + assert!( + foreign_bundle_overrides(&environment, &root, |path| Some(path.to_path_buf())) + .is_empty(), + "{appdir:?}" + ); + } + } +} diff --git a/apps/desktop/src-tauri/src/backend.rs b/apps/desktop/src-tauri/src/backend.rs index 0589a319e5..3057014278 100644 --- a/apps/desktop/src-tauri/src/backend.rs +++ b/apps/desktop/src-tauri/src/backend.rs @@ -4093,7 +4093,8 @@ exit /b 9 ) .expect("isolated desktop test settings should decode"); assert_eq!(settings["enableProviderUpdateChecks"], false); - for provider in ["codex", "claudeAgent", "cursor", "grok", "opencode"] { + // Every built-in driver, so a driver added later cannot escape its pin. + for provider in crate::test_support::hermetic_providers::BUILTIN_PROVIDER_DRIVERS { assert_eq!( settings["providers"][provider]["enabled"], false, "{provider} must not probe the developer host during desktop tests" diff --git a/apps/desktop/src-tauri/src/backend/ui_process_observer/macos.rs b/apps/desktop/src-tauri/src/backend/ui_process_observer/macos.rs index b87ae649f9..303e59b924 100644 --- a/apps/desktop/src-tauri/src/backend/ui_process_observer/macos.rs +++ b/apps/desktop/src-tauri/src/backend/ui_process_observer/macos.rs @@ -204,10 +204,10 @@ async fn collect_webview_pids(app: &AppHandle) -> WebKitPidCollec for webview in webviews.into_values() { let sender = sender.clone(); let dispatch = webview.with_webview(move |platform| { - // SAFETY: on macOS Tauri provides its live WKWebView and executes this - // closure on the main/UI thread. - let wk: &WKWebView = unsafe { &*platform.inner().cast() }; - let _ = sender.send(read_webview_pids(wk)); + // Tauri runs this on the main thread; a missing webview just drops its sender. + if let Some(wk) = crate::macos_webview::take_platform_webview(platform) { + let _ = sender.send(read_webview_pids(&wk)); + } }); if dispatch.is_ok() { expected_callbacks += 1; diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs index 35ef462c30..a177e2604c 100644 --- a/apps/desktop/src-tauri/src/bridge.rs +++ b/apps/desktop/src-tauri/src/bridge.rs @@ -64,7 +64,7 @@ const AUTH_ENVIRONMENT_BOOTSTRAP_TOKEN_TYPE: &str = const AUTH_TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange"; const CLIENT_SETTINGS_FILE_NAME: &str = "client-settings.json"; const CONNECTION_CATALOG_FILE_NAME: &str = "connection-catalog.tauri.json"; -const DESKTOP_SETTINGS_FILE_NAME: &str = "desktop-settings.json"; +pub(crate) const DESKTOP_SETTINGS_FILE_NAME: &str = "desktop-settings.json"; /// Tailscale Serve's default HTTPS port. BiBCode only probes it; it never configures Serve. const TAILSCALE_SERVE_HTTPS_PORT: u16 = 443; const PRIMARY_LOCAL_ENVIRONMENT_ID: &str = "primary"; @@ -78,6 +78,8 @@ struct DesktopSettings { wsl_backend_enabled: bool, wsl_distro: Option, wsl_only: bool, + #[cfg(target_os = "linux")] + linux_software_rendering: bool, } /// Keys an earlier version wrote, such as `tailscaleServeEnabled`, are ignored on read and @@ -262,6 +264,8 @@ fn default_desktop_settings() -> DesktopSettings { wsl_backend_enabled: false, wsl_distro: None, wsl_only: false, + #[cfg(target_os = "linux")] + linux_software_rendering: false, } } @@ -310,16 +314,24 @@ fn normalize_desktop_settings_document(document: DesktopSettingsDocument) -> Des wsl_backend_enabled, wsl_distro: normalize_wsl_distro(document.wsl_distro), wsl_only, + #[cfg(target_os = "linux")] + linux_software_rendering: false, } } fn desktop_settings_to_value(settings: &DesktopSettings) -> Value { - json!({ + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut value = json!({ "serverExposureMode": &settings.server_exposure_mode, "wslBackendEnabled": settings.wsl_backend_enabled, "wslDistro": &settings.wsl_distro, "wslOnly": settings.wsl_only, - }) + }); + #[cfg(target_os = "linux")] + { + value[crate::software_rendering::SETTING_KEY] = json!(settings.linux_software_rendering); + } + value } fn normalize_client_settings_document(value: Value) -> Value { @@ -404,8 +416,22 @@ fn read_desktop_settings(app: &AppHandle) -> Result DesktopSettings { + #[cfg(target_os = "linux")] + let linux_software_rendering = crate::software_rendering::setting_from_document(&value); let document = serde_json::from_value::(value).unwrap_or_default(); - Ok(normalize_desktop_settings_document(document)) + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut settings = normalize_desktop_settings_document(document); + #[cfg(target_os = "linux")] + { + settings.linux_software_rendering = linux_software_rendering; + } + settings } fn write_desktop_settings( @@ -1097,6 +1123,9 @@ pub fn desktop_bridge_restart_app( )?; // If requesting exit fails, Tauri restarts without RunEvent::Exit. crate::relaunch::prepare_descriptors_for_relaunch(); + // The exit callback then relaunches through the systemd scope handoff when needed, and + // without the software rendering variables BiBCode set itself. + crate::relaunch::note_relaunch_requested(); app.request_restart(); Ok(()) } @@ -1523,6 +1552,91 @@ pub async fn desktop_bridge_set_wsl_only( .await } +/// The Linux setting that disables GPU compositing (#411), with this launch's state. +#[cfg(target_os = "linux")] +fn linux_software_rendering_state(enabled: bool) -> Value { + use crate::software_rendering::{ + Override, gpu_compositing_disabled, restart_applies, startup_decision, user_variables, + }; + let decision = startup_decision(); + let user_variables: Vec = user_variables(&decision.set, |name| std::env::var_os(name)) + .into_iter() + .map(|(name, value)| json!({ "name": name, "value": value.to_string_lossy() })) + .collect(); + json!({ + "enabled": enabled, + "override": decision.override_value.map(Override::as_str), + "userVariables": user_variables, + "gpuCompositingDisabled": gpu_compositing_disabled(|name| std::env::var_os(name)), + "restartApplies": restart_applies(enabled, &decision, |name| { + std::env::var_os(name).is_some() + }), + }) +} + +#[cfg(not(target_os = "linux"))] +fn linux_software_rendering_unsupported(method: &str) -> Value { + json!({ + "code": "tauri_capability_unsupported", + "method": method, + "capability": "Linux software rendering", + "message": format!("{method} is available on Linux only."), + }) +} + +/// Saves the setting into `desktop-settings.json`; returns the stored value. +#[cfg(target_os = "linux")] +fn write_linux_software_rendering( + app: &AppHandle, + enabled: bool, +) -> Result { + let path = desktop_settings_path(app)?; + // Only the one key changes, so a bad value or a key from another version survives. + let document = crate::software_rendering::patch_setting(read_json_file(&path)?, enabled)?; + write_json_file(&path, &document)?; + Ok(enabled) +} + +#[tauri::command] +pub fn desktop_bridge_get_linux_software_rendering( + app: AppHandle, +) -> Result { + #[cfg(target_os = "linux")] + return desktop_settings_path(&app) + .and_then(|path| read_json_file(&path)) + .and_then(crate::software_rendering::stored_setting_for_settings) + .map(linux_software_rendering_state) + .map_err(Value::String); + #[cfg(not(target_os = "linux"))] + { + let _ = app; + Err(linux_software_rendering_unsupported( + "getLinuxSoftwareRendering", + )) + } +} + +#[tauri::command] +pub async fn desktop_bridge_set_linux_software_rendering( + app: AppHandle, + coordinator: State<'_, ServerExposureCoordinator>, + enabled: bool, +) -> Result { + #[cfg(target_os = "linux")] + return coordinator + .run_exclusive(async { write_linux_software_rendering(&app, enabled) }) + .await + .map(linux_software_rendering_state) + .map_err(Value::String); + #[cfg(not(target_os = "linux"))] + { + let _ = (app, coordinator, enabled); + Err(linux_software_rendering_unsupported( + "setLinuxSoftwareRendering", + )) + } +} + #[tauri::command] pub fn desktop_bridge_get_update_state( app: AppHandle, @@ -2223,7 +2337,7 @@ pub async fn desktop_bridge_set_theme( )) } }; - for window in app.webview_windows().values() { + for window in app.windows().values() { window .set_theme(native_theme) .map_err(|error| bridge_error("Could not update the Tauri window theme", error))?; @@ -2243,7 +2357,7 @@ pub async fn desktop_bridge_show_context_menu( return Ok(None); } - let Some(window) = app.get_webview_window("main") else { + let Some(window) = crate::window::main_window(&app) else { return Ok(None); }; let ticket = context_menus.begin(&request)?; @@ -3569,6 +3683,8 @@ mod tests { } #[test] + // The struct update fills the Linux-only field. + #[cfg_attr(not(target_os = "linux"), allow(clippy::needless_update))] fn normalizes_desktop_settings_with_legacy_wsl_mode() { let settings = normalize_desktop_settings_document(DesktopSettingsDocument { server_exposure_mode: Some("network-accessible".to_string()), @@ -3585,10 +3701,63 @@ mod tests { wsl_backend_enabled: true, wsl_distro: Some("Ubuntu-24.04".to_string()), wsl_only: true, + ..default_desktop_settings() } ); } + #[cfg(target_os = "linux")] + #[test] + fn software_rendering_setting_survives_a_bad_value_elsewhere_and_other_writes() { + // A wrong type for another key resets that document, but not this key. + let settings = desktop_settings_from_value(json!({ + "linuxSoftwareRendering": true, + "wslOnly": "not a boolean", + })); + assert!(settings.linux_software_rendering); + // A WSL or exposure write keeps it. + let value = desktop_settings_to_value(&settings); + assert_eq!(value["linuxSoftwareRendering"], json!(true)); + } + + #[cfg(target_os = "linux")] + #[test] + fn software_rendering_bad_value_does_not_reset_other_settings() { + let settings = desktop_settings_from_value(json!({ + "serverExposureMode": "network-accessible", + "wslOnly": true, + "linuxSoftwareRendering": "yes", + })); + assert!(!settings.linux_software_rendering); + assert_eq!(settings.server_exposure_mode, "network-accessible"); + assert!(settings.wsl_only); + } + + #[cfg(target_os = "linux")] + #[test] + fn software_rendering_save_keeps_bad_and_unknown_keys() { + let document = json!({ + "serverExposureMode": "network-accessible", + "wslOnly": "bad", + "keyFromANewerVersion": { "kept": true }, + }); + let saved = crate::software_rendering::patch_setting(Some(document.clone()), true).unwrap(); + let mut expected = document; + expected["linuxSoftwareRendering"] = json!(true); + assert_eq!(saved, expected); + } + + #[cfg(not(target_os = "linux"))] + #[test] + fn software_rendering_setting_is_not_written_off_linux() { + let settings = desktop_settings_from_value(json!({ "linuxSoftwareRendering": true })); + assert!( + desktop_settings_to_value(&settings) + .get("linuxSoftwareRendering") + .is_none() + ); + } + #[test] fn persisted_wsl_only_intent_normalizes_the_backend_to_enabled() { let settings = normalize_desktop_settings_document(DesktopSettingsDocument { @@ -3641,30 +3810,26 @@ mod tests { wsl_only: Some(false), }); - assert_eq!( - settings, - DesktopSettings { - server_exposure_mode: "local-only".to_string(), - wsl_backend_enabled: false, - wsl_distro: None, - wsl_only: false, - } - ); + // Every invalid value falls back to its default. + assert_eq!(settings, default_desktop_settings()); } #[test] fn desktop_settings_defaults_and_serialization_are_stable() { let settings = default_desktop_settings(); + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut expected = json!({ + "serverExposureMode": "local-only", + "wslBackendEnabled": false, + "wslDistro": null, + "wslOnly": false, + }); + #[cfg(target_os = "linux")] + { + expected["linuxSoftwareRendering"] = json!(false); + } - assert_eq!( - desktop_settings_to_value(&settings), - json!({ - "serverExposureMode": "local-only", - "wslBackendEnabled": false, - "wslDistro": null, - "wslOnly": false, - }) - ); + assert_eq!(desktop_settings_to_value(&settings), expected); assert_eq!(normalize_server_exposure_mode(None), "local-only"); } @@ -4538,6 +4703,8 @@ mod tests { desktop_bridge_set_wsl_backend_enabled, desktop_bridge_set_wsl_distro, desktop_bridge_set_wsl_only, + desktop_bridge_get_linux_software_rendering, + desktop_bridge_set_linux_software_rendering, desktop_bridge_set_theme, desktop_bridge_show_context_menu, desktop_bridge_get_update_state, @@ -4988,6 +5155,7 @@ mod tests { "desktop_bridge_set_tailscale_serve_enabled", "desktop_bridge_set_wsl_backend_enabled", "desktop_bridge_set_wsl_only", + "desktop_bridge_set_linux_software_rendering", "desktop_bridge_confirm", ] { assert!( diff --git a/apps/desktop/src-tauri/src/config.rs b/apps/desktop/src-tauri/src/config.rs index bb1c13790f..8bedeecd0f 100644 --- a/apps/desktop/src-tauri/src/config.rs +++ b/apps/desktop/src-tauri/src/config.rs @@ -144,35 +144,57 @@ fn resolve_data_root_from_home( .map_err(|error| config_error("Could not resolve the BiBCode data root", error)) } +/// The function Tauri's `home_dir()` calls, also usable before Tauri starts, so `main` and +/// the running app always resolve the same data root. +fn home_dir() -> Result { + dirs::home_dir().ok_or_else(|| "Could not resolve the home directory".to_owned()) +} + +#[cfg_attr(test, allow(dead_code))] +fn data_root_from_environment() -> Result { + resolve_data_root_from_home( + home_dir()?, + bibcode_env_var("BIBCODE_HOME").map(PathBuf::from), + ) +} + pub(crate) fn data_root(app: &AppHandle) -> Result { - let home = app - .path() - .home_dir() - .map_err(|error| config_error("Could not resolve the home directory", error))?; #[cfg(test)] - let requested = app + return app .try_state::() .map(|root| root.0.clone()) .ok_or_else(|| { "mock Tauri apps must install an explicit isolated test data root".to_owned() - })?; - #[cfg(test)] - return resolve_data_root_from_home(home, Some(requested)); + }) + .and_then(|requested| resolve_data_root_from_home(home_dir()?, Some(requested))); #[cfg(not(test))] - resolve_data_root_from_home(home, bibcode_env_var("BIBCODE_HOME").map(PathBuf::from)) + { + let _ = app; + data_root_from_environment() + } } pub(crate) fn base_dir(app: &AppHandle) -> Result { data_root(app).map(|resolved| resolved.effective) } -pub fn state_dir(app: &AppHandle) -> Result { - Ok(base_dir(app)?.join(if cfg!(debug_assertions) { +fn state_dir_in(data_root: PathBuf) -> PathBuf { + data_root.join(if cfg!(debug_assertions) { "dev" } else { "userdata" - })) + }) +} + +pub fn state_dir(app: &AppHandle) -> Result { + base_dir(app).map(state_dir_in) +} + +/// The state directory before Tauri starts, by the same rules as [`state_dir`]. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn state_dir_from_environment() -> Result { + data_root_from_environment().map(|resolved| state_dir_in(resolved.effective)) } pub fn read_json_file(path: &Path) -> Result, String> { diff --git a/apps/desktop/src-tauri/src/context_menu.rs b/apps/desktop/src-tauri/src/context_menu.rs index 6a4d340757..30b140cd01 100644 --- a/apps/desktop/src-tauri/src/context_menu.rs +++ b/apps/desktop/src-tauri/src/context_menu.rs @@ -2,7 +2,7 @@ use serde::Deserialize; use serde_json::{Map, Value}; use std::{collections::HashMap, sync::Mutex, time::Duration}; use tauri::{ - AppHandle, LogicalPosition, Manager, Runtime, WebviewWindow, + AppHandle, LogicalPosition, Manager, Runtime, Window, menu::{MenuItemBuilder, PredefinedMenuItem, Submenu, SubmenuBuilder}, }; use tokio::sync::oneshot; @@ -151,7 +151,7 @@ pub(crate) fn context_menu_request_from_values(items: Vec) -> NativeConte } pub(crate) fn show_native_context_menu( - window: &WebviewWindow, + window: &Window, request: &NativeContextMenuRequest, position: Option, ) -> Result<(), String> { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 2448fd6298..15ebc6c46e 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -42,6 +42,8 @@ macro_rules! desktop_bridge_commands { desktop_bridge_set_wsl_backend_enabled, desktop_bridge_set_wsl_distro, desktop_bridge_set_wsl_only, + desktop_bridge_get_linux_software_rendering, + desktop_bridge_set_linux_software_rendering, desktop_bridge_set_theme, desktop_bridge_show_context_menu, desktop_bridge_get_update_state, @@ -197,15 +199,17 @@ pub fn run() { #[cfg(unix)] backend::install_termination_signal_handler(app_handle.clone(), backend.clone()); tauri::async_runtime::spawn(async move { - match exposure_coordinator + let started = exposure_coordinator .run_exclusive(backend.start_default(app_handle)) - .await - { - Ok(_config) => {} - Err(error) => { - tracing::error!("failed to start Tauri desktop backend: {error}"); - backend.record_error(error); - } + .await; + // A release build's log sink exists only once the in-process server tried to + // start; a failed start still logs these with the error below. + software_rendering::record_startup(); + #[cfg(target_os = "linux")] + appdir_working_directory::record_startup(); + if let Err(error) = started { + tracing::error!("failed to start Tauri desktop backend: {error}"); + backend.record_error(error); } }); Ok(()) @@ -247,6 +251,8 @@ pub fn run() { bridge::desktop_bridge_set_wsl_backend_enabled, bridge::desktop_bridge_set_wsl_distro, bridge::desktop_bridge_set_wsl_only, + bridge::desktop_bridge_get_linux_software_rendering, + bridge::desktop_bridge_set_linux_software_rendering, bridge::desktop_bridge_set_theme, bridge::desktop_bridge_show_context_menu, bridge::desktop_bridge_get_update_state, @@ -306,7 +312,7 @@ pub fn run() { } // Mark after backend shutdown, at the last callback before Tauri's relaunch spawn. crate::relaunch::prepare_descriptors_for_relaunch(); - crate::relaunch::relaunch_outside_service_unit(app_handle); + crate::relaunch::relaunch_with_handoff(app_handle); #[cfg(windows)] if !EXIT_REQUESTED.load(std::sync::atomic::Ordering::Relaxed) { end_session(app_handle); @@ -388,6 +394,10 @@ fn desktop_e2e_logging_plugin() -> tauri::plugin::TauriPlugin .build() } +#[cfg(any(target_os = "linux", all(test, unix)))] +mod appdir_working_directory; +#[cfg(target_os = "linux")] +pub use appdir_working_directory::enter_appdir_usr; mod backend; mod bridge; mod config; @@ -407,6 +417,8 @@ pub use gstreamer_environment::repair_process_environment as repair_gstreamer_en mod linux_text_rendering; #[cfg(target_os = "linux")] mod linux_theme; +#[cfg(target_os = "macos")] +mod macos_webview; mod network_interfaces; mod preview; mod relaunch; @@ -414,6 +426,9 @@ mod remote_update_delegate; mod security; mod server_exposure; mod shell_environment; +mod software_rendering; +#[cfg(target_os = "linux")] +pub use software_rendering::apply_process_environment as apply_software_rendering_environment; pub mod ssh; mod tailscale; #[cfg(test)] @@ -493,11 +508,29 @@ mod tests { let capability = &config["app"]["security"]["capabilities"][0]; assert_main_webview_only(capability); + // The inline capability replaces `capabilities/`, so it repeats every product permission + // (#417: without `allow-desktop-preview` the preview never opened in test builds). + let production: Value = serde_json::from_str(include_str!("../capabilities/default.json")) + .expect("default capability JSON should parse"); + let granted = capability["permissions"] + .as_array() + .expect("desktop E2E capability should list permissions"); + for permission in production["permissions"] + .as_array() + .expect("default capability should list permissions") + { + assert!( + granted.contains(permission), + "desktop E2E capability lacks product permission {permission}", + ); + } assert_eq!( capability.get("permissions"), Some(&serde_json::json!([ "allow-desktop-bridge", + "allow-desktop-preview", "core:default", + "deep-link:default", "wdio:default", "allow-desktop-e2e-lifecycle" ])) diff --git a/apps/desktop/src-tauri/src/macos_webview.rs b/apps/desktop/src-tauri/src/macos_webview.rs new file mode 100644 index 0000000000..b48b9791bd --- /dev/null +++ b/apps/desktop/src-tauri/src/macos_webview.rs @@ -0,0 +1,101 @@ +//! Ownership of the objects a macOS `with_webview` callback receives (#410). + +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2_web_kit::WKWebView; + +/// Takes back the three objects tauri-runtime-wry 2.11.4 hands a `with_webview` callback as +/// `Retained::into_raw` (+1 retains it never releases) and returns the WKWebView; the controller +/// and window are released when this returns. It consumes `platform`, so a second release cannot +/// compile. `window::tests::with_webview_ownership_matches_the_pinned_runtime` fails when that +/// runtime version changes. Call it on the main thread where Tauri runs the callback, and never +/// borrow `platform.inner()` instead: each borrow leaks three retains. +pub(crate) fn take_platform_webview( + platform: tauri::webview::PlatformWebview, +) -> Option> { + // SAFETY: each pointer carries one retain the runtime gave up, adopted here once. + unsafe { + adopt( + platform.inner(), + platform.controller(), + platform.ns_window(), + ) + } +} + +/// # Safety +/// Each non-null pointer must carry one retain the caller owns and gives up, and `webview` must +/// point to a `T`. +unsafe fn adopt( + webview: *mut std::ffi::c_void, + controller: *mut std::ffi::c_void, + window: *mut std::ffi::c_void, +) -> Option> { + // SAFETY: the caller transfers one retain per pointer; from_raw adopts it once. + unsafe { + drop(Retained::::from_raw(controller.cast())); + drop(Retained::::from_raw(window.cast())); + Retained::::from_raw(webview.cast()) + } +} + +#[cfg(test)] +mod tests { + use objc2::rc::Retained; + use objc2::runtime::NSObject; + + fn retain_count(object: &NSObject) -> usize { + // SAFETY: `retainCount` is implemented by every NSObject. + unsafe { objc2::msg_send![object, retainCount] } + } + + #[test] + fn adopt_releases_every_retain_the_runtime_gave_up() { + let objects = [NSObject::new(), NSObject::new(), NSObject::new()]; + let before: Vec<_> = objects.iter().map(|object| retain_count(object)).collect(); + // The runtime's side: one `Retained::into_raw` per object. + let [webview, controller, window] = objects + .each_ref() + .map(|object| Retained::into_raw(object.clone()).cast()); + // SAFETY: each pointer carries the retain created just above. + let adopted = unsafe { super::adopt::(webview, controller, window) }; + let after_adopt: Vec<_> = objects.iter().map(|object| retain_count(object)).collect(); + assert_eq!(after_adopt, [before[0] + 1, before[1], before[2]]); + drop(adopted); + let after: Vec<_> = objects.iter().map(|object| retain_count(object)).collect(); + assert_eq!(after, before); + } + + #[test] + fn no_macos_with_webview_callback_borrows_the_platform_pointers() { + // shortcut: only catches a callback parameter named `platform`; widen if one is renamed. + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut offenders = Vec::new(); + let mut pending = vec![source]; + while let Some(directory) = pending.pop() { + for entry in std::fs::read_dir(&directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + pending.push(path); + } else if path.extension().is_some_and(|extension| extension == "rs") + && !path.ends_with("macos_webview.rs") + && std::fs::read_to_string(&path).unwrap().lines().any(|line| { + [ + "platform.inner().cast", + "platform.controller().cast", + "platform.ns_window().cast", + ] + .iter() + .any(|needle| line.contains(needle)) + }) + { + offenders.push(path); + } + } + } + assert!( + offenders.is_empty(), + "use macos_webview::take_platform_webview instead of casting the pointers: {offenders:?}" + ); + } +} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index b8ad837321..73b54893c3 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -30,6 +30,20 @@ fn main() { { std::process::exit(code); } + // An extracted AppDir's `bibcode://` handler skips `AppRun` (#412): restart through it + // before BiBCode sets any variable, which the restarted process would take as the user's. + // SAFETY: still single-threaded, for the same reasons as the step below. + #[cfg(target_os = "linux")] + unsafe { + bibcode_desktop_lib::enter_appdir_usr() + }; + // The GUI only, still single-threaded: before any webview, whose web processes inherit it. + // SAFETY: no thread exists yet. The crash hook spawns none on Linux, and the open-url and + // CLI branches that start a runtime have exited above. + #[cfg(target_os = "linux")] + unsafe { + bibcode_desktop_lib::apply_software_rendering_environment() + }; bibcode_desktop_lib::run(); } diff --git a/apps/desktop/src-tauri/src/preview/host.rs b/apps/desktop/src-tauri/src/preview/host.rs index dd6d6ac3aa..a80fd002fa 100644 --- a/apps/desktop/src-tauri/src/preview/host.rs +++ b/apps/desktop/src-tauri/src/preview/host.rs @@ -518,11 +518,13 @@ impl Drop for CreationLease { // Drop must stay best-effort and must never replace an active panic. let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { if let Some(webview) = self.child.as_ref() { + super::platform::return_focus(webview); let _ = webview.close(); } else if self.creation_attempted { // The label was absent before add_child and remains reserved by // this incarnation, so a newly registered child is ours. if let Some(webview) = self.app.webviews().get(&self.label) { + super::platform::return_focus(webview); let _ = webview.close(); } } @@ -983,6 +985,13 @@ pub fn create_tab( } }); + // shortcut: main frame only, so a text field inside an iframe keeps a dead Ctrl+Z; use + // `initialization_script_for_all_frames` if pages in frames need it. + #[cfg(target_os = "linux")] + { + builder = builder.initialization_script(include_str!("linux_text_field_undo.js")); + } + // Preview browsing data is isolated from the main application session and, // per environment, from other environments' previews. #[cfg(target_os = "macos")] @@ -1085,6 +1094,7 @@ pub fn create_tab( if snapshot.1 { webview.show() } else { + super::platform::return_focus(&webview); webview.hide() } }); @@ -1260,6 +1270,7 @@ pub fn set_bounds( if current.visible { current.webview.show().map_err(|error| error.to_string())?; } else { + super::platform::return_focus(¤t.webview); current.webview.hide().map_err(|error| error.to_string())?; } @@ -1309,7 +1320,10 @@ pub fn close_tab(app: &AppHandle, tab_id: &str) -> Result<(), String> { let close_result = app .webviews() .get(&label) - .map(|webview| webview.close().map_err(|error| error.to_string())) + .map(|webview| { + super::platform::return_focus(webview); + webview.close().map_err(|error| error.to_string()) + }) .unwrap_or(Ok(())); let mut registry = state.0.lock().map_err(|error| error.to_string())?; diff --git a/apps/desktop/src-tauri/src/preview/linux_text_field_undo.js b/apps/desktop/src-tauri/src/preview/linux_text_field_undo.js new file mode 100644 index 0000000000..202b56d413 --- /dev/null +++ b/apps/desktop/src-tauri/src/preview/linux_text_field_undo.js @@ -0,0 +1,42 @@ +// WebKitGTK binds no key to a text field's undo, so a preview page gets the chords the main +// window's #408 handler gives the app's own fields. WebKitGTK has no default action for these +// chords, so the script never cancels one: it decides after the page's own listeners have run, +// and leaves a chord the page cancelled, an input method is composing, or a synthetic event. +// WebKitGTK's undo stack is page-wide, so it undoes only when the page's latest user edit was +// in the focused field; otherwise the chord would revert another editor's change. +// shortcut: once the field's own steps are undone, a further Ctrl+Z there still pops an older +// step from another editor; track per-field step counts if that proves to matter. +(() => { + const textTypes = new Set(["", "text", "search", "url", "tel", "email", "password", "number"]); + let lastEdited = null; + const noteEdit = (event) => { + if (event.isTrusted) lastEdited = event.composedPath()[0]; + }; + window.addEventListener("beforeinput", noteEdit, true); + window.addEventListener("input", noteEdit, true); + window.addEventListener("keydown", (event) => { + if (!event.isTrusted || !event.ctrlKey || event.altKey || event.metaKey) return; + if (event.isComposing || event.keyCode === 229) return; + const target = event.composedPath()[0]; + const field = + target instanceof HTMLTextAreaElement || + (target instanceof HTMLInputElement && textTypes.has(target.type)); + if (!field || target.readOnly || target.disabled) return; + const key = event.key.toLowerCase(); + const command = + key === "z" + ? event.shiftKey + ? "redo" + : "undo" + : key === "y" && !event.shiftKey + ? "redo" + : null; + if (!command) return; + // Runs once dispatch has finished, after every listener the page registered later. + setTimeout(() => { + if (event.defaultPrevented || lastEdited !== target) return; + if (target.getRootNode().activeElement !== target) return; + document.execCommand(command); + }, 0); + }); +})(); diff --git a/apps/desktop/src-tauri/src/preview/platform/linux.rs b/apps/desktop/src-tauri/src/preview/platform/linux.rs index 5907250a4b..970fc24143 100644 --- a/apps/desktop/src-tauri/src/preview/platform/linux.rs +++ b/apps/desktop/src-tauri/src/preview/platform/linux.rs @@ -35,6 +35,45 @@ pub fn place_child(webview: &tauri::Webview, x: f64, y: f64, width: f64, height: } } +/// See `super::return_focus`. Runs on the GTK thread ahead of the hide or close +/// queued after it. Keys must not be left without a shown webview to go to: +/// moving the focused preview into the overlay layer can already have dropped +/// its focus, so the window's focus is checked, not only the preview's. +pub fn return_focus(webview: &tauri::Webview) { + use tauri::Manager; + + let app = webview.app_handle().clone(); + let result = webview.with_webview(move |platform| { + let preview: gtk::Widget = platform.inner().upcast(); + let window_focus = preview + .toplevel() + .and_then(|toplevel| toplevel.downcast::().ok()) + .map(|window| window.focused_widget()); + let preview_holds_focus = match window_focus { + Some(None) => true, + // Anything but another shown webview (the main one, or a preview in use) is + // no place for keys either. + Some(Some(focus)) => { + focus == preview + || focus.is_ancestor(&preview) + || !(focus.is::() && focus.is_visible()) + } + None => preview.is_focus(), + }; + if !preview_holds_focus { + return; + } + if let Some(main) = crate::window::main_webview(&app) + && let Err(error) = main.set_focus() + { + tracing::warn!("failed to return focus to the main webview: {error}"); + } + }); + if let Err(error) = result { + tracing::warn!("failed to reach the preview webview to return its focus: {error}"); + } +} + pub(super) fn place_in_preview_layer( child: >k::Widget, x: f64, diff --git a/apps/desktop/src-tauri/src/preview/platform/macos.rs b/apps/desktop/src-tauri/src/preview/platform/macos.rs index 9c7c23936f..5a8f16a56c 100644 --- a/apps/desktop/src-tauri/src/preview/platform/macos.rs +++ b/apps/desktop/src-tauri/src/preview/platform/macos.rs @@ -43,10 +43,10 @@ fn with_wk( let (tx, rx) = mpsc::sync_channel::(1); webview .with_webview(move |platform| { - // SAFETY: On macOS `PlatformWebview::inner()` is the live WKWebView - // pointer, and Tauri invokes this closure on the main/UI thread. - let wk: &WKWebView = unsafe { &*platform.inner().cast() }; - let _ = tx.send(f(wk)); + let Some(wk) = crate::macos_webview::take_platform_webview(platform) else { + return; + }; + let _ = tx.send(f(&wk)); }) .map_err(|error| PreviewPlatformError::Unavailable(error.to_string()))?; rx.recv_timeout(PLATFORM_CALL_TIMEOUT) @@ -64,9 +64,10 @@ impl PlatformWebviewOps for MacosWebviewOps { let (tx, rx) = mpsc::sync_channel::>(1); webview .with_webview(move |platform| { - // SAFETY: See `with_wk`; Tauri owns the WKWebView and runs the - // closure on the main/UI thread. - let wk: &WKWebView = unsafe { &*platform.inner().cast() }; + let Some(wk) = crate::macos_webview::take_platform_webview(platform) else { + return; + }; + let wk: &WKWebView = &wk; let ns_script = NSString::from_str(&script); let handler = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| { let outcome = if !error.is_null() { @@ -139,9 +140,10 @@ impl PlatformWebviewOps for MacosWebviewOps { let (tx, rx) = mpsc::sync_channel::, PreviewPlatformError>>(1); webview .with_webview(move |platform| { - // SAFETY: See `with_wk`; Tauri owns the WKWebView and runs the - // closure on the main/UI thread. - let wk: &WKWebView = unsafe { &*platform.inner().cast() }; + let Some(wk) = crate::macos_webview::take_platform_webview(platform) else { + return; + }; + let wk: &WKWebView = &wk; let Some(main_thread) = MainThreadMarker::new() else { let _ = tx.send(Err(PreviewPlatformError::Unavailable( "snapshot was not scheduled on the main thread".to_string(), @@ -208,10 +210,13 @@ impl PlatformWebviewOps for MacosWebviewOps { let (tx, rx) = mpsc::sync_channel::<()>(1); webview .with_webview(move |platform| { - // SAFETY: See `with_wk`; all WKWebView and WebKit data-store - // access remains inside Tauri's main/UI-thread closure. + let Some(wk) = crate::macos_webview::take_platform_webview(platform) else { + return; + }; + // SAFETY: all WKWebView and WebKit data-store access remains inside Tauri's + // main/UI-thread closure. unsafe { - let wk: &WKWebView = &*platform.inner().cast(); + let wk: &WKWebView = &wk; let store = wk.configuration().websiteDataStore(); let mut types: Vec<&NSString> = Vec::new(); if kinds.cookies { diff --git a/apps/desktop/src-tauri/src/preview/platform/mod.rs b/apps/desktop/src-tauri/src/preview/platform/mod.rs index 180de9b1eb..d42f8667ea 100644 --- a/apps/desktop/src-tauri/src/preview/platform/mod.rs +++ b/apps/desktop/src-tauri/src/preview/platform/mod.rs @@ -30,6 +30,19 @@ pub fn place_child(webview: &tauri::Webview, x: f64, y: f64, width: f64, height: let _ = (webview, x, y, width, height); } +/// Call before a preview webview hides or closes: if it holds keyboard focus, +/// the main webview takes it back. GTK and WebView2 need this: a hidden or +/// destroyed focus widget or window leaves keys going nowhere until a click. +/// macOS is unmeasured and unchanged. +pub fn return_focus(webview: &tauri::Webview) { + #[cfg(target_os = "linux")] + linux::return_focus(webview); + #[cfg(target_os = "windows")] + windows::return_focus(webview); + #[cfg(target_os = "macos")] + let _ = webview; +} + #[allow(dead_code)] #[derive(Debug, Clone, Copy)] pub struct ClearDataKinds { diff --git a/apps/desktop/src-tauri/src/preview/platform/windows.rs b/apps/desktop/src-tauri/src/preview/platform/windows.rs index aca7eaa64f..1f9265f65f 100644 --- a/apps/desktop/src-tauri/src/preview/platform/windows.rs +++ b/apps/desktop/src-tauri/src/preview/platform/windows.rs @@ -362,6 +362,50 @@ impl PlatformWebviewOps for WindowsWebviewOps { } } +/// See `super::return_focus`. Runs on the UI thread ahead of the hide or close queued after it. +/// WebView2 leaves Win32 focus in the preview's window tree when it hides, so keys must be moved +/// out first unless they already sit in another shown webview (the main one or another preview). +pub fn return_focus(webview: &tauri::Webview) { + use tauri::Manager; + use windows::Win32::UI::Input::KeyboardAndMouse::GetFocus; + use windows::Win32::UI::WindowsAndMessaging::{ + GA_ROOT, GetAncestor, GetForegroundWindow, IsChild, + }; + + let app = webview.app_handle().clone(); + let result = webview.with_webview(move |platform| { + let mut container = windows::Win32::Foundation::HWND::default(); + // SAFETY: Tauri invokes this closure on the UI thread that owns the live controller and + // its windows; `container` is a valid out parameter. + let preview_holds_focus = unsafe { + if platform.controller().ParentWindow(&mut container).is_err() { + return; + } + let focus = GetFocus(); + let root = GetAncestor(container, GA_ROOT); + if focus.is_invalid() { + // In front with no focus window, keys reach the bare frame (a "ding"); in the + // background, activation restores focus and there is nothing to take. + GetForegroundWindow() == root + } else { + // In the preview or on the bare frame, keys have no shown page to reach. + focus == container || IsChild(container, focus).as_bool() || focus == root + } + }; + if !preview_holds_focus { + return; + } + if let Some(main) = crate::window::main_webview(&app) + && let Err(error) = main.set_focus() + { + tracing::warn!("failed to return focus to the main webview: {error}"); + } + }); + if let Err(error) = result { + tracing::warn!("failed to reach the preview webview to return its focus: {error}"); + } +} + #[cfg(test)] mod tests { use std::sync::mpsc; diff --git a/apps/desktop/src-tauri/src/relaunch.rs b/apps/desktop/src-tauri/src/relaunch.rs index 6c0ce48473..ce338c8f00 100644 --- a/apps/desktop/src-tauri/src/relaunch.rs +++ b/apps/desktop/src-tauri/src/relaunch.rs @@ -2,7 +2,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; -/// An installed update asked for a relaunch; read at the last exit callback. +/// An installed update or Settings' restart asked for a relaunch; read at the last exit callback. static RELAUNCH_REQUESTED: AtomicBool = AtomicBool::new(false); /// Marks every descriptor above stderr close-on-exec before relaunch. @@ -12,7 +12,7 @@ pub(crate) fn prepare_descriptors_for_relaunch() { linux::mark_inherited_descriptors_close_on_exec(); } -/// Called just before `AppHandle::restart` after an update installs. +/// Called just before an update's or Settings' restart. pub(crate) fn note_relaunch_requested() { RELAUNCH_REQUESTED.store(true, Ordering::Release); } @@ -37,27 +37,45 @@ pub(crate) fn exit_takes_mount_from_children() -> bool { /// launcher such as `systemd-run --user`), its exit stops the unit, which kills that whole /// cgroup: the new AppImage's mount goes away and the relaunched app dies with SIGBUS /// (#94). Here the new app starts in its own transient scope instead, and this process -/// exits; when that is not needed or `systemd-run` fails, Tauri's relaunch runs as before. -pub(crate) fn relaunch_outside_service_unit(app: &tauri::AppHandle) { +/// exits. Tauri's relaunch also passes this process's environment on, so when BiBCode set +/// the software rendering variables itself (#411), the new app is started here without +/// them and reads the stored setting afresh. When neither applies, or a spawn fails, +/// Tauri's relaunch runs as before; with the variables that fails safe. +pub(crate) fn relaunch_with_handoff(app: &tauri::AppHandle) { if !RELAUNCH_REQUESTED.load(Ordering::Acquire) { return; } #[cfg(target_os = "linux")] { let cgroup = std::fs::read_to_string("/proc/self/cgroup").unwrap_or_default(); - if !linux::runs_in_service_unit(&cgroup) { + let in_service_unit = linux::runs_in_service_unit(&cgroup); + let set_by_bibcode = crate::software_rendering::variables_set_by_bibcode(); + if !in_service_unit && set_by_bibcode.is_empty() { return; } let env = tauri::Manager::env(app); let Ok(binary) = tauri::process::current_binary(&env) else { return; }; - let mut command = std::process::Command::new("systemd-run"); - command - .args(["--user", "--scope", "--collect", "--quiet", "--"]) - .arg(binary) - .args(env.args_os.iter().skip(1)); - bibcode_server::process::isolate_appimage_environment(&mut command); + if !in_service_unit { + let mut command = + relaunch_command(&binary, env.args_os.iter().skip(1), false, set_by_bibcode); + match command.spawn() { + Ok(_) => { + tracing::info!( + removed = ?set_by_bibcode, + "relaunching without the software rendering variables BiBCode set" + ); + std::process::exit(0); + } + Err(error) => { + tracing::warn!(%error, "could not relaunch without the software rendering variables; relaunching in place"); + return; + } + } + } + let mut command = + relaunch_command(&binary, env.args_os.iter().skip(1), true, set_by_bibcode); let mut child = match command.spawn() { Ok(child) => child, Err(error) => { @@ -71,12 +89,12 @@ pub(crate) fn relaunch_outside_service_unit(app: &tauri::AppH let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); loop { if let Ok(Some(status)) = child.try_wait() { - tracing::warn!(%status, "systemd-run did not start the update's relaunch scope; relaunching in place"); + tracing::warn!(%status, "systemd-run did not start the relaunch scope; relaunching in place"); return; } let cgroup = std::fs::read_to_string(&cgroup_path).unwrap_or_default(); if !cgroup.is_empty() && !linux::runs_in_service_unit(&cgroup) { - tracing::info!("relaunching the updated app in its own systemd scope"); + tracing::info!("relaunching the app in its own systemd scope"); std::process::exit(0); } if std::time::Instant::now() >= deadline { @@ -94,6 +112,40 @@ pub(crate) fn relaunch_outside_service_unit(app: &tauri::AppH let _ = app; } +/// The relaunch command: the binary itself, or inside `systemd-run` with the AppImage child +/// filter, and in both cases with only the WebKit variables BiBCode set removed (#411). +#[cfg(target_os = "linux")] +fn relaunch_command<'a>( + binary: &std::path::Path, + args: impl IntoIterator, + systemd: bool, + set_by_bibcode: &[&str], +) -> std::process::Command { + let mut command = if systemd { + let mut command = std::process::Command::new("systemd-run"); + command + .args(["--user", "--scope", "--collect", "--quiet", "--"]) + .arg(binary); + command + } else { + std::process::Command::new(binary) + }; + command.args(args); + if systemd { + bibcode_server::process::isolate_appimage_environment(&mut command); + } + let overrides = crate::software_rendering::relaunch_overrides(set_by_bibcode, |name| { + std::env::var_os(name) + }); + for (name, value) in overrides { + match value { + Some(value) => command.env(name, value), + None => command.env_remove(name), + }; + } + command +} + #[cfg(target_os = "linux")] mod linux { const FIRST_INHERITED_DESCRIPTOR: libc::c_uint = 3; @@ -182,6 +234,54 @@ mod tests { assert!(!runs_in_service_unit("")); } + #[test] + fn a_relaunch_keeps_the_users_webkit_variables_on_both_paths() { + use crate::test_support::reexec; + const NAME: &str = + "relaunch::tests::a_relaunch_keeps_the_users_webkit_variables_on_both_paths"; + const PHASE: &str = "relaunch-webkit-variables"; + let Some(isolated) = reexec::enter(NAME, PHASE) else { + // The fixture environment goes to the child process, never through `set_var`. + reexec::run(NAME, PHASE, None, |command| { + command + .env("APPIMAGE", "/tmp/bibcode-test.AppImage") + .env("APPDIR", "/tmp/bibcode-test-appdir") + // A user's value under the AppDir is one the AppImage child filter drops. + .env( + "WEBKIT_DISABLE_COMPOSITING_MODE", + "/tmp/bibcode-test-appdir/usr", + ) + .env("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); + }); + return; + }; + let env_of = |command: &Command, name: &str| { + command + .get_envs() + .find(|(key, _)| *key == name) + .map(|(_, value)| value.map(std::ffi::OsStr::to_owned)) + }; + for systemd in [true, false] { + let command = super::relaunch_command( + std::path::Path::new("/bin/true"), + &[], + systemd, + &["WEBKIT_DISABLE_DMABUF_RENDERER"], + ); + assert_eq!( + env_of(&command, "WEBKIT_DISABLE_DMABUF_RENDERER"), + Some(None), + "systemd={systemd}: the variable BiBCode set is removed" + ); + assert_eq!( + env_of(&command, "WEBKIT_DISABLE_COMPOSITING_MODE"), + Some(Some("/tmp/bibcode-test-appdir/usr".into())), + "systemd={systemd}: the user's variable survives" + ); + } + isolated.complete(); + } + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::process::Command; diff --git a/apps/desktop/src-tauri/src/software_rendering.rs b/apps/desktop/src-tauri/src/software_rendering.rs new file mode 100644 index 0000000000..d3a0687f04 --- /dev/null +++ b/apps/desktop/src-tauri/src/software_rendering.rs @@ -0,0 +1,462 @@ +//! Linux: run WebKitGTK without GPU compositing (#411). On some Intel GPUs the +//! driver hangs in WebKitGTK's compositor thread and takes the whole desktop +//! session down. When the user turns this on, `main` sets the two WebKit +//! variables below before any thread or webview exists, so every launch route +//! (menu, binary, `bibcode://` link) gets them. See +//! `docs/plans/2026-11-21-linux-software-rendering-design.md`. +// Compiled everywhere so its tests run on every host; only Linux applies it. +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use serde_json::Value; +use std::ffi::{OsStr, OsString}; +use std::path::Path; +use std::sync::OnceLock; + +/// The key in `desktop-settings.json`, decoded on its own so a bad value cannot +/// reset the other settings. +pub(crate) const SETTING_KEY: &str = "linuxSoftwareRendering"; +/// `1` turns the setting on for one launch, `0` makes BiBCode set nothing. +pub(crate) const OVERRIDE_VARIABLE: &str = "BIBCODE_SOFTWARE_RENDERING"; +pub(crate) const WEBKIT_VARIABLES: [&str; 2] = [ + "WEBKIT_DISABLE_COMPOSITING_MODE", + "WEBKIT_DISABLE_DMABUF_RENDERER", +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Override { + On, + Off, +} + +impl Override { + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::On => "on", + Self::Off => "off", + } + } +} + +/// What one launch does: the variables BiBCode sets itself, and why. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Decision { + pub(crate) stored: bool, + pub(crate) override_value: Option, + /// The override variable held a value other than `0` or `1`. + pub(crate) ignored_override: bool, + pub(crate) set: Vec<&'static str>, +} + +/// Decides which variables to set. A variable already present, with any value, +/// is the user's and is never touched. +pub(crate) fn decide( + stored: bool, + override_raw: Option<&OsStr>, + present: impl Fn(&str) -> bool, + linux: bool, +) -> Decision { + if !linux { + return Decision::default(); + } + let override_value = match override_raw.and_then(OsStr::to_str) { + Some("1") => Some(Override::On), + Some("0") => Some(Override::Off), + _ => None, + }; + let on = override_value.map_or(stored, |value| value == Override::On); + Decision { + stored, + override_value, + ignored_override: override_raw.is_some() && override_value.is_none(), + set: if on { + WEBKIT_VARIABLES + .into_iter() + .filter(|name| !present(name)) + .collect() + } else { + Vec::new() + }, + } +} + +/// Whether restarting from Settings would change what BiBCode sets: never while +/// the override decides, else when the setting wants a variable that is still +/// missing, or no longer wants one BiBCode set. +pub(crate) fn restart_applies( + enabled: bool, + decision: &Decision, + present: impl Fn(&str) -> bool, +) -> bool { + if decision.override_value.is_some() { + return false; + } + if enabled { + WEBKIT_VARIABLES.into_iter().any(|name| !present(name)) + } else { + !decision.set.is_empty() + } +} + +/// Whether WebKit runs without its GPU compositor: either variable present and not `0`. On +/// WebKitGTK 2.50 either one alone removes the `ThreadedCompositor` thread (checked in a +/// Hyprland VM), and `WEBKIT_DISABLE_COMPOSITING_MODE=0` alone keeps it. +pub(crate) fn gpu_compositing_disabled(value_of: impl Fn(&str) -> Option) -> bool { + WEBKIT_VARIABLES + .into_iter() + .any(|name| value_of(name).is_some_and(|value| value != "0")) +} + +/// The WebKit variables present in this process that BiBCode did not set: the user's, +/// which the switch cannot change. +pub(crate) fn user_variables( + set_by_bibcode: &[&str], + value_of: impl Fn(&str) -> Option, +) -> Vec<(&'static str, OsString)> { + WEBKIT_VARIABLES + .into_iter() + .filter(|name| !set_by_bibcode.contains(name)) + .filter_map(|name| Some((name, value_of(name)?))) + .collect() +} + +/// What a relaunch does with each WebKit variable, applied after the AppImage child filter: +/// remove the ones BiBCode set, and put back the user's, which that filter may have dropped. +pub(crate) fn relaunch_overrides( + set_by_bibcode: &[&str], + value_of: impl Fn(&str) -> Option, +) -> Vec<(&'static str, Option)> { + let removed = set_by_bibcode + .iter() + .filter_map(|name| WEBKIT_VARIABLES.into_iter().find(|known| known == name)) + .map(|name| (name, None)); + let kept = user_variables(set_by_bibcode, value_of) + .into_iter() + .map(|(name, value)| (name, Some(value))); + removed.chain(kept).collect() +} + +/// `desktop-settings.json` with only the setting changed; every other key, valid or not, +/// known to this version or not, is kept. A missing file starts an empty document. +pub(crate) fn patch_setting(document: Option, enabled: bool) -> Result { + match document.unwrap_or_else(|| Value::Object(Default::default())) { + Value::Object(mut object) => { + object.insert(SETTING_KEY.to_owned(), Value::Bool(enabled)); + Ok(Value::Object(object)) + } + _ => Err(NOT_AN_OBJECT.to_owned()), + } +} + +const NOT_AN_OBJECT: &str = "desktop-settings.json is not a JSON object; fix or remove it"; + +/// The stored setting for Settings, which refuses the document shapes a save would refuse, +/// so the row shows the repair guidance before the user tries to save. +pub(crate) fn stored_setting_for_settings(document: Option) -> Result { + match document { + None => Ok(false), + Some(document @ Value::Object(_)) => Ok(setting_from_document(&document)), + Some(_) => Err(NOT_AN_OBJECT.to_owned()), + } +} + +/// The stored setting from a parsed `desktop-settings.json`; anything but `true` is off. +pub(crate) fn setting_from_document(document: &Value) -> bool { + document + .get(SETTING_KEY) + .and_then(Value::as_bool) + .unwrap_or(false) +} + +/// Reads the stored setting. A missing file is off; an unreadable or malformed +/// one is off too, with the reason to log once the log sink is ready. +pub(crate) fn read_stored_setting(path: &Path) -> (bool, Option) { + match crate::config::read_json_file(path) { + Ok(Some(document)) => (setting_from_document(&document), None), + Ok(None) => (false, None), + Err(error) => (false, Some(error)), + } +} + +struct Startup { + decision: Decision, + settings_problem: Option, +} + +static STARTUP: OnceLock = OnceLock::new(); + +/// Applies the setting to this process. +/// +/// # Safety +/// +/// It changes the process environment, so no other thread may exist yet: `main` +/// calls it before Tauri, Tokio, GTK or WebKit start. +#[cfg(target_os = "linux")] +pub unsafe fn apply_process_environment() { + let (stored, settings_problem) = match crate::config::state_dir_from_environment() { + Ok(state_dir) => { + read_stored_setting(&state_dir.join(crate::bridge::DESKTOP_SETTINGS_FILE_NAME)) + } + Err(error) => (false, Some(error)), + }; + let decision = decide( + stored, + std::env::var_os(OVERRIDE_VARIABLE).as_deref(), + |name| std::env::var_os(name).is_some(), + true, + ); + for name in &decision.set { + // SAFETY: the caller guarantees the process is still single-threaded. + unsafe { std::env::set_var(name, "1") }; + } + let _ = STARTUP.set(Startup { + decision, + settings_problem, + }); +} + +/// This launch's decision; empty off Linux. +pub(crate) fn startup_decision() -> Decision { + STARTUP + .get() + .map(|startup| startup.decision.clone()) + .unwrap_or_default() +} + +/// The variables BiBCode set itself, which a relaunch must not pass on. +pub(crate) fn variables_set_by_bibcode() -> &'static [&'static str] { + STARTUP + .get() + .map_or(&[], |startup| startup.decision.set.as_slice()) +} + +/// Logs the start-up decision once the log sink exists. +pub(crate) fn record_startup() { + let Some(startup) = STARTUP.get() else { + return; + }; + if let Some(problem) = &startup.settings_problem { + tracing::warn!( + %problem, + "could not read the software rendering setting; GPU compositing stays on" + ); + } + if startup.decision.ignored_override { + tracing::warn!( + "{OVERRIDE_VARIABLE} must be 0 or 1; the stored software rendering setting applies" + ); + } + tracing::info!( + stored = startup.decision.stored, + override_value = startup.decision.override_value.map(Override::as_str), + set = ?startup.decision.set, + gpu_compositing_disabled = gpu_compositing_disabled(|name| std::env::var_os(name)), + "software rendering start-up decision" + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const COMPOSITING: &str = "WEBKIT_DISABLE_COMPOSITING_MODE"; + const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER"; + + fn decide_with(stored: bool, override_raw: Option<&str>, present: &[&str]) -> Decision { + decide( + stored, + override_raw.map(OsStr::new), + |name| present.contains(&name), + true, + ) + } + + #[test] + fn software_rendering_on_sets_both_variables() { + assert_eq!(decide_with(true, None, &[]).set, vec![COMPOSITING, DMABUF]); + } + + #[test] + fn software_rendering_off_sets_nothing() { + assert!(decide_with(false, None, &[]).set.is_empty()); + } + + #[test] + fn software_rendering_keeps_a_value_the_user_exported() { + // Per variable: the user's one is kept, the other is still set. + assert_eq!(decide_with(true, None, &[COMPOSITING]).set, vec![DMABUF]); + assert!( + decide_with(true, None, &[COMPOSITING, DMABUF]) + .set + .is_empty() + ); + } + + #[test] + fn software_rendering_override_wins_in_both_directions() { + let on = decide_with(false, Some("1"), &[]); + assert_eq!(on.set, vec![COMPOSITING, DMABUF]); + assert_eq!(on.override_value, Some(Override::On)); + let off = decide_with(true, Some("0"), &[]); + assert!(off.set.is_empty()); + assert_eq!(off.override_value, Some(Override::Off)); + } + + #[test] + fn software_rendering_ignores_an_unknown_override_value() { + for raw in ["", "true", "yes", "2"] { + let decision = decide_with(true, Some(raw), &[]); + assert_eq!(decision.set, vec![COMPOSITING, DMABUF], "{raw:?}"); + assert!(decision.ignored_override, "{raw:?}"); + assert_eq!(decision.override_value, None, "{raw:?}"); + } + } + + #[test] + fn software_rendering_changes_nothing_off_linux() { + let decision = decide(true, Some(OsStr::new("1")), |_| false, false); + assert_eq!(decision, Decision::default()); + } + + #[test] + fn software_rendering_restart_applies_only_when_it_changes_something() { + let off_now = decide_with(false, None, &[]); + assert!(restart_applies(true, &off_now, |_| false)); + assert!(!restart_applies(false, &off_now, |_| false)); + + let on_now = decide_with(true, None, &[]); + let all_present = |_: &str| true; + assert!(!restart_applies(true, &on_now, all_present)); + assert!(restart_applies(false, &on_now, all_present)); + + // The user exported both: a restart cannot change anything. + let exported = decide_with(true, None, &[COMPOSITING, DMABUF]); + assert!(!restart_applies(true, &exported, all_present)); + assert!(!restart_applies(false, &exported, all_present)); + + // The override decides this launch and the next one started the same way. + let overridden = decide_with(false, Some("1"), &[]); + assert!(!restart_applies(false, &overridden, all_present)); + assert!(!restart_applies( + true, + &decide_with(true, Some("0"), &[]), + |_| false + )); + } + + #[test] + fn software_rendering_reports_compositing_off_only_for_a_value_other_than_zero() { + let with = |values: &[(&str, &str)]| { + let values: Vec<(String, OsString)> = values + .iter() + .map(|(name, value)| ((*name).to_owned(), OsString::from(value))) + .collect(); + gpu_compositing_disabled(move |name| { + values + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.clone()) + }) + }; + assert!(with(&[(COMPOSITING, "1"), (DMABUF, "1")])); + assert!(with(&[(DMABUF, "1")])); + // A user's `0` for one variable does not hide the other. + assert!(with(&[(COMPOSITING, "0"), (DMABUF, "1")])); + assert!(!with(&[(COMPOSITING, "0")])); + assert!(!with(&[])); + } + + #[test] + fn software_rendering_setting_decodes_only_a_boolean() { + assert!(setting_from_document(&json!({ SETTING_KEY: true }))); + assert!(!setting_from_document(&json!({ SETTING_KEY: false }))); + assert!(!setting_from_document(&json!({ SETTING_KEY: "yes" }))); + assert!(!setting_from_document(&json!({}))); + assert!(!setting_from_document(&json!([]))); + } + + #[test] + fn software_rendering_reads_the_stored_setting_from_a_file() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("desktop-settings.json"); + assert_eq!(read_stored_setting(&path), (false, None)); + + std::fs::write(&path, r#"{"linuxSoftwareRendering":true,"wslOnly":"bad"}"#).unwrap(); + assert_eq!(read_stored_setting(&path), (true, None)); + + std::fs::write(&path, "{not json").unwrap(); + let (stored, problem) = read_stored_setting(&path); + assert!(!stored); + assert!(problem.is_some()); + } + + fn lookup(values: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + let values = values.to_vec(); + move |name| { + values + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| OsString::from(value)) + } + } + + #[test] + fn software_rendering_relaunch_removes_only_what_bibcode_set() { + // BiBCode set both: both go. + assert_eq!( + relaunch_overrides( + &[COMPOSITING, DMABUF], + lookup(&[(COMPOSITING, "1"), (DMABUF, "1")]) + ), + vec![(COMPOSITING, None), (DMABUF, None)] + ); + // The user exported one, even with a value the AppImage filter drops: it is put back. + assert_eq!( + relaunch_overrides( + &[DMABUF], + lookup(&[(COMPOSITING, "/opt/app/usr"), (DMABUF, "1")]) + ), + vec![(DMABUF, None), (COMPOSITING, Some("/opt/app/usr".into()))] + ); + // Nothing set by BiBCode and nothing exported: nothing to do. + assert!(relaunch_overrides(&[], lookup(&[])).is_empty()); + } + + #[test] + fn software_rendering_lists_only_the_users_variables() { + assert_eq!( + user_variables(&[DMABUF], lookup(&[(COMPOSITING, "0"), (DMABUF, "1")])), + vec![(COMPOSITING, OsString::from("0"))] + ); + assert!(user_variables(&[COMPOSITING, DMABUF], lookup(&[(COMPOSITING, "1")])).is_empty()); + } + + #[test] + fn software_rendering_settings_read_refuses_what_a_save_refuses() { + assert_eq!(stored_setting_for_settings(None), Ok(false)); + assert_eq!( + stored_setting_for_settings(Some(json!({ SETTING_KEY: true, "wslOnly": "bad" }))), + Ok(true) + ); + for root in [json!([]), json!("text"), json!(null)] { + let error = stored_setting_for_settings(Some(root.clone())).unwrap_err(); + assert!(error.contains("fix or remove"), "{root}: {error}"); + assert!(patch_setting(Some(root), true).is_err()); + } + } + + #[test] + fn software_rendering_patch_keeps_every_other_key() { + let document = json!({ + "serverExposureMode": "network-accessible", + "wslOnly": "bad", + "futureKey": { "nested": [1, 2] }, + SETTING_KEY: false, + }); + let mut expected = document.clone(); + expected[SETTING_KEY] = json!(true); + assert_eq!(patch_setting(Some(document), true), Ok(expected)); + assert_eq!(patch_setting(None, true), Ok(json!({ SETTING_KEY: true }))); + assert!(patch_setting(Some(json!([1])), true).is_err()); + } +} diff --git a/apps/desktop/src-tauri/src/webview_exit.rs b/apps/desktop/src-tauri/src/webview_exit.rs index 995c92563e..960137ba24 100644 --- a/apps/desktop/src-tauri/src/webview_exit.rs +++ b/apps/desktop/src-tauri/src/webview_exit.rs @@ -327,12 +327,13 @@ fn read_web_content_pid(app: &tauri::AppHandle, label: &st let read = webview.with_webview(|platform| { use objc2::{msg_send, runtime::NSObjectProtocol, sel}; - // SAFETY: on macOS Tauri passes its live WKWebView and runs this on the main - // thread. - let webview: &objc2_web_kit::WKWebView = unsafe { &*platform.inner().cast() }; + // Tauri runs this on the main thread. + let Some(webview) = crate::macos_webview::take_platform_webview(platform) else { + return; + }; if webview.respondsToSelector(sel!(_webProcessIdentifier)) { // SAFETY: the check above proves this WKWebView implements the private getter. - let pid: libc::pid_t = unsafe { msg_send![webview, _webProcessIdentifier] }; + let pid: libc::pid_t = unsafe { msg_send![&*webview, _webProcessIdentifier] }; if let Ok(pid) = u32::try_from(pid) && pid > 0 { diff --git a/apps/desktop/src-tauri/src/window.rs b/apps/desktop/src-tauri/src/window.rs index 619217f80e..0f0e8c3c21 100644 --- a/apps/desktop/src-tauri/src/window.rs +++ b/apps/desktop/src-tauri/src/window.rs @@ -4,8 +4,7 @@ use std::path::PathBuf; use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; use tauri::{ - AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, Position, Runtime, Size, - WebviewWindow, + AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, Position, Runtime, Size, Window, menu::{Menu, MenuBuilder, MenuItemBuilder, SubmenuBuilder}, }; @@ -16,8 +15,34 @@ pub const MENU_ACTION_EVENT: &str = "desktop:menu-action"; pub const MENU_ACTION_OPEN_SETTINGS: &str = "open-settings"; pub const MENU_ACTION_CHECK_FOR_UPDATES: &str = "check-for-updates"; pub const MENU_ACTION_CLOSE_SHORTCUT: &str = "close-shortcut"; +#[cfg(target_os = "macos")] +pub const MENU_ACTION_EDIT_UNDO: &str = "edit-undo"; +#[cfg(target_os = "macos")] +pub const MENU_ACTION_EDIT_REDO: &str = "edit-redo"; +#[cfg(target_os = "macos")] +const MENU_ID_EDIT_UNDO: &str = "bibcode:edit-undo"; +#[cfg(target_os = "macos")] +const MENU_ID_EDIT_REDO: &str = "bibcode:edit-redo"; +/// Id, label and accelerator of the macOS Edit menu's Undo and Redo, which replace the predefined +/// items: those send `undo:` to WebKit, whose own undo never holds the Files editors' edits. +#[cfg(target_os = "macos")] +const EDIT_MENU_ITEMS: [(&str, &str, &str); 2] = [ + (MENU_ID_EDIT_UNDO, "Undo", "CmdOrCtrl+Z"), + (MENU_ID_EDIT_REDO, "Redo", "CmdOrCtrl+Shift+Z"), +]; pub(crate) const MAIN_WINDOW_LABEL: &str = "main"; + +/// The main window. Not `get_webview_window`: Tauri leaves out a window that holds more than one +/// webview, and a preview browser's child webview stays in the main window for the session (#418). +pub(crate) fn main_window(app: &AppHandle) -> Option> { + app.get_window(MAIN_WINDOW_LABEL) +} + +/// The main window's own webview, found whether or not preview webviews share its window. +pub(crate) fn main_webview(app: &AppHandle) -> Option> { + app.get_webview(MAIN_WINDOW_LABEL) +} const MENU_ID_OPEN_SETTINGS: &str = "bibcode:open-settings"; const MENU_ID_CHECK_FOR_UPDATES: &str = "bibcode:check-for-updates"; const MENU_ID_CLOSE_SHORTCUT: &str = "bibcode:close-shortcut"; @@ -43,12 +68,19 @@ struct MainWindowState { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ApplicationMenuAction { Emit(&'static str), + /// Edit > Undo or Redo: the page's action when the main webview has focus, else native. + #[cfg(target_os = "macos")] + Edit(&'static str), CloseWindow, Quit, } fn menu_action_for_id(id: &str) -> Option { match id { + #[cfg(target_os = "macos")] + MENU_ID_EDIT_UNDO => Some(ApplicationMenuAction::Edit(MENU_ACTION_EDIT_UNDO)), + #[cfg(target_os = "macos")] + MENU_ID_EDIT_REDO => Some(ApplicationMenuAction::Edit(MENU_ACTION_EDIT_REDO)), MENU_ID_OPEN_SETTINGS => Some(ApplicationMenuAction::Emit(MENU_ACTION_OPEN_SETTINGS)), MENU_ID_CHECK_FOR_UPDATES => { Some(ApplicationMenuAction::Emit(MENU_ACTION_CHECK_FOR_UPDATES)) @@ -73,14 +105,16 @@ pub fn configure_application_menu(app: &AppHandle) -> tauri::Resu match menu_action_for_id(event.id().0.as_str()) { Some(ApplicationMenuAction::Emit(action)) => { if action == MENU_ACTION_OPEN_SETTINGS - && let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) + && let Some(window) = main_window(app) { let _ = window.set_focus(); } let _ = app.emit(MENU_ACTION_EVENT, action); } + #[cfg(target_os = "macos")] + Some(ApplicationMenuAction::Edit(action)) => run_edit_menu_action(app, action), Some(ApplicationMenuAction::CloseWindow) => { - if let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) { + if let Some(window) = main_window(app) { let _ = window.close(); } } @@ -113,15 +147,18 @@ fn build_application_menu(app: &AppHandle) -> tauri::Result(app: &AppHandle) -> tauri::Result Undo or Redo to the page when the main webview holds the key window's first +/// responder, and otherwise sends the native `undo:` or `redo:` up the responder chain, as the +/// predefined item does, so native panels and the preview webview keep their own undo. +#[cfg(target_os = "macos")] +fn run_edit_menu_action(app: &AppHandle, action: &'static str) { + if main_webview_has_first_responder(app) { + match app.emit_to(MAIN_WINDOW_LABEL, MENU_ACTION_EVENT, action) { + Ok(()) => return, + // The page never got it, so the native action below still runs. + Err(error) => { + tracing::warn!("failed to send the Edit menu action to the main webview: {error}"); + } + } + } + let Some(mtm) = objc2::MainThreadMarker::new() else { + tracing::warn!("the Edit menu ran off the main thread; its action was dropped"); + return; + }; + let selector = if action == MENU_ACTION_EDIT_UNDO { + objc2::sel!(undo:) + } else { + objc2::sel!(redo:) + }; + let application = objc2_app_kit::NSApplication::sharedApplication(mtm); + // SAFETY: a nil target makes AppKit walk the responder chain, as the predefined item does. + unsafe { application.sendAction_to_from(selector, None, None) }; +} + +/// Whether the key window is the main window and its first responder is the main `WKWebView` or a +/// view inside it. The preview's child webview is a sibling of the main one, so it does not count. +#[cfg(target_os = "macos")] +fn main_webview_has_first_responder(app: &AppHandle) -> bool { + use objc2_app_kit::{NSApplication, NSView}; + + let Some(main) = main_webview(app) else { + return false; + }; + let (sender, receiver) = std::sync::mpsc::sync_channel::(1); + let sent = main.with_webview(move |platform| { + // The closure runs on the main thread. + let Some(webview) = crate::macos_webview::take_platform_webview(platform) else { + let _ = sender.send(false); + return; + }; + let Some(mtm) = objc2::MainThreadMarker::new() else { + let _ = sender.send(false); + return; + }; + let owns_focus = NSApplication::sharedApplication(mtm) + .keyWindow() + .filter(|key_window| webview.window().is_some_and(|own| own == *key_window)) + .and_then(|key_window| key_window.firstResponder()) + .and_then(|responder| responder.downcast::().ok()) + .is_some_and(|view| view.isDescendantOf(&webview)); + let _ = sender.send(owns_focus); + }); + // The menu handler runs on the main thread, where Tauri runs this closure at once. + sent.is_ok() && receiver.try_recv().unwrap_or(false) +} + fn window_state_path(app: &AppHandle) -> Result { Ok(state_dir(app)?.join(WINDOW_STATE_FILE_NAME)) } @@ -179,7 +276,7 @@ fn decode_main_window_state(value: Value) -> Result { .map_err(|error| format!("Could not decode Tauri main window state: {error}")) } -fn apply_main_window_state(window: &WebviewWindow, state: &MainWindowState) { +fn apply_main_window_state(window: &Window, state: &MainWindowState) { if let Err(error) = window.set_size(Size::Physical(PhysicalSize { width: state.width, height: state.height, @@ -203,7 +300,7 @@ fn apply_main_window_state(window: &WebviewWindow, state: &MainWi } fn capture_main_window_state( - window: &WebviewWindow, + window: &Window, ) -> Result, String> { let size = window .outer_size() @@ -294,7 +391,7 @@ pub(crate) fn build_main_window(app: &AppHandle) -> tauri::Result /// Reports the main window's web content process dying to the profiler. macOS registers its /// hook on the app builder instead. #[cfg(any(target_os = "linux", target_os = "windows"))] -fn watch_web_content_process(window: &WebviewWindow) { +fn watch_web_content_process(window: &tauri::WebviewWindow) { let installed = window.with_webview(|webview| { #[cfg(target_os = "linux")] crate::webview_exit::watch(&webview.inner()); @@ -326,7 +423,7 @@ pub fn restore_main_window_state(app: &AppHandle) -> Result<(), S return Ok(()); } }; - let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) else { + let Some(window) = main_window(app) else { return Ok(()); }; apply_main_window_state(&window, &state); @@ -334,7 +431,7 @@ pub fn restore_main_window_state(app: &AppHandle) -> Result<(), S } pub fn persist_main_window_state(app: &AppHandle) -> Result<(), String> { - let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) else { + let Some(window) = main_window(app) else { return Ok(()); }; let Some(state) = capture_main_window_state(&window)? else { @@ -593,7 +690,7 @@ pub(crate) fn close_guard_for_app(app: &AppHandle) -> CloseGuard } fn ask_web_to_leave(app: &AppHandle, request_id: u64, reason: LeaveReason) { - let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) else { + let Some(window) = main_window(app) else { // No page can hold an edit, so leaving loses nothing. if let Some(guard) = app.try_state::() { guard.reply(request_id, CloseReply::Allow, Instant::now()); @@ -646,7 +743,7 @@ fn prompt_close_anyway(app: &AppHandle, request_id: u64) { fn leave_now(app: &AppHandle, reason: LeaveReason) { match reason { LeaveReason::Close => { - if let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) + if let Some(window) = main_window(app) && let Err(error) = window.destroy() { tracing::warn!(%error, "failed to close the main window"); @@ -878,6 +975,40 @@ mod tests { assert!(recorded.asked.lock().unwrap().is_empty()); } + #[test] + fn with_webview_ownership_matches_the_pinned_runtime() { + // `macos_webview::take_platform_webview` releases the retains this runtime version hands + // over; a newer one lends the pointers, which would make that an over-release on macOS. + // Checked on every platform so a bump made on Linux or Windows fails too. + let lock = include_str!("../../../../Cargo.lock").replace("\r\n", "\n"); + assert!( + lock.contains("name = \"tauri-runtime-wry\"\nversion = \"2.11.4\""), + "tauri-runtime-wry changed: recheck who owns the pointers `with_webview` passes" + ); + } + + #[cfg(target_os = "macos")] + #[test] + fn menu_edit_undo_and_redo_are_routed_items_on_macos() { + assert_eq!( + menu_action_for_id(MENU_ID_EDIT_UNDO), + Some(ApplicationMenuAction::Edit(MENU_ACTION_EDIT_UNDO)) + ); + assert_eq!( + menu_action_for_id(MENU_ID_EDIT_REDO), + Some(ApplicationMenuAction::Edit(MENU_ACTION_EDIT_REDO)) + ); + assert_eq!( + EDIT_MENU_ITEMS, + [ + (MENU_ID_EDIT_UNDO, "Undo", "CmdOrCtrl+Z"), + (MENU_ID_EDIT_REDO, "Redo", "CmdOrCtrl+Shift+Z"), + ] + ); + assert_eq!(MENU_ACTION_EDIT_UNDO, "edit-undo"); + assert_eq!(MENU_ACTION_EDIT_REDO, "edit-redo"); + } + #[test] fn close_request_quit_menu_item_replaces_the_predefined_quit() { assert_eq!( @@ -1039,6 +1170,45 @@ mod tests { assert!(decode_main_window_state(json!({ "width": "wide" })).is_err()); } + #[test] + fn main_window_is_found_after_a_child_webview_joins_it() { + use crate::config::IsolatedTestDataRoot; + use tauri::test::{mock_builder, mock_context, noop_assets}; + + let temp = tempfile::tempdir().expect("isolated desktop data root"); + let mut context = mock_context(noop_assets()); + context.config_mut().identifier = + format!("com.bibcode.window-child-tests-{}", std::process::id()); + let app = mock_builder() + .manage(IsolatedTestDataRoot::new(temp.path().join("data-root"))) + .build(context) + .expect("mock Tauri app"); + let handle = app.handle(); + let main = tauri::WebviewWindowBuilder::new(&app, MAIN_WINDOW_LABEL, Default::default()) + .data_directory(temp.path().join("webview-data")) + .build() + .expect("mock webview"); + main.as_ref() + .window() + .add_child( + tauri::webview::WebviewBuilder::new("preview-child", Default::default()), + tauri::LogicalPosition::new(0.0, 0.0), + tauri::LogicalSize::new(10.0, 10.0), + ) + .expect("mock child webview"); + + // Tauri's own lookup drops a window holding two webviews (#418). + assert!(handle.get_webview_window(MAIN_WINDOW_LABEL).is_none()); + assert_eq!( + main_window(handle).map(|window| window.label().to_string()), + Some(MAIN_WINDOW_LABEL.to_string()) + ); + assert_eq!( + main_webview(handle).map(|webview| webview.label().to_string()), + Some(MAIN_WINDOW_LABEL.to_string()) + ); + } + #[test] fn mock_window_exercises_menu_capture_and_restore_helpers() { use crate::config::IsolatedTestDataRoot; @@ -1065,6 +1235,7 @@ mod tests { .data_directory(temp.path().join("webview-data")) .build() .expect("mock webview"); + let window = window.as_ref().window(); assert!( !local_app_data.exists(), "the test leaves nothing in the local app-data folder" diff --git a/apps/desktop/src-tauri/tauri.e2e.conf.json b/apps/desktop/src-tauri/tauri.e2e.conf.json index 587eb3a4c2..7f9f063bd1 100644 --- a/apps/desktop/src-tauri/tauri.e2e.conf.json +++ b/apps/desktop/src-tauri/tauri.e2e.conf.json @@ -10,7 +10,9 @@ "webviews": ["main"], "permissions": [ "allow-desktop-bridge", + "allow-desktop-preview", "core:default", + "deep-link:default", "wdio:default", "allow-desktop-e2e-lifecycle" ] diff --git a/apps/server/examples/remote_update_fake_host.rs b/apps/server/examples/remote_update_fake_host.rs index d792aa7831..35a06f0611 100644 --- a/apps/server/examples/remote_update_fake_host.rs +++ b/apps/server/examples/remote_update_fake_host.rs @@ -626,7 +626,7 @@ mod tests { let path = temp.path().join("userdata/settings.json"); let value: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); assert_eq!(value["enableProviderUpdateChecks"], false); - for driver in ["codex", "claudeAgent", "cursor", "grok", "opencode"] { + for driver in hermetic_providers::BUILTIN_PROVIDER_DRIVERS { assert_eq!(value["providers"][driver]["enabled"], false); let pin = Path::new(value["providers"][driver]["binaryPath"].as_str().unwrap()); assert!(pin.is_absolute()); diff --git a/apps/server/src/git/manager/mod.rs b/apps/server/src/git/manager/mod.rs index 20d771194d..317ba346d3 100644 --- a/apps/server/src/git/manager/mod.rs +++ b/apps/server/src/git/manager/mod.rs @@ -336,9 +336,13 @@ mod telemetry { .await .expect("branch delete operation"); repository - .git_manager_delete_remote_branch(cwd, "origin", "renamed", &cancellation) + .git_manager_delete_remote_branch(cwd, "origin", "renamed", "abc123", &cancellation) .await .expect("remote branch delete operation"); + repository + .git_manager_remote_heads(cwd, "origin", "renamed", &cancellation) + .await + .expect("remote branch delete check"); repository .git_manager_fetch(cwd, "origin", &cancellation) .await diff --git a/apps/server/src/git/manager/operations.rs b/apps/server/src/git/manager/operations.rs index 6f71ce60e7..52701f9462 100644 --- a/apps/server/src/git/manager/operations.rs +++ b/apps/server/src/git/manager/operations.rs @@ -336,6 +336,18 @@ pub enum GitManagerOperationRequest { name: String, force: bool, delete_remote: bool, + /// A delete with its remote resumed after a sign-in its remote check needed (#325, + /// #397): refuse unless the remote still has exactly this one URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + expected_destination: Option, + /// With `expected_destination`: the local tip, remote and upstream branch the offer + /// froze. A resumed delete refuses when any of them changed (#397 round 3). + #[serde(default, skip_serializing_if = "Option::is_none")] + expected_tip: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + expected_remote: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + expected_remote_branch: Option, }, /// Deletes `branch` on `remote` only, leaving any local branch alone. RemoteBranchDelete { @@ -1233,23 +1245,34 @@ fn refuse_option_like_operands( } /// The remote a network operation contacts, its direction, and the request that resumes it -/// after a sign-in (#325). A branch delete resumes as a delete of its remote branch only, -/// because its local branch is already gone when the remote step fails. -fn network_step( - snapshot: &GitManagerRefsSnapshot, +/// after a sign-in (#325), and for a branch delete with its remote the request that resumes it +/// once its local branch is gone: a delete of the remote branch only. Before that, while the +/// `ls-remote` check needed the sign-in, the whole delete resumes, so its local guards run again +/// before anything is deleted (#397). +async fn network_step( + repository: &GitRepository, request: &GitManagerOperationRequest, -) -> Option<(String, SignInDirection, GitManagerOperationRequest)> { + cancellation: &CancellationToken, +) -> Option<( + String, + SignInDirection, + GitManagerOperationRequest, + Option, +)> { use GitManagerOperationRequest as Request; match request { - Request::Fetch { remote, .. } | Request::Pull { remote, .. } => { - Some((remote.clone(), SignInDirection::Fetch, request.clone())) - } + Request::Fetch { remote, .. } | Request::Pull { remote, .. } => Some(( + remote.clone(), + SignInDirection::Fetch, + request.clone(), + None, + )), Request::Push { remote, .. } | Request::PublishBranch { remote, .. } | Request::ForcePush { remote, .. } | Request::RemoteBranchDelete { remote, .. } | Request::TagPush { remote, .. } => { - Some((remote.clone(), SignInDirection::Push, request.clone())) + Some((remote.clone(), SignInDirection::Push, request.clone(), None)) } Request::BranchDelete { cwd, @@ -1258,17 +1281,31 @@ fn network_step( delete_remote: true, .. } => { - let (remote, branch) = remote_delete_target(snapshot, name)?; + let (remote, branch) = branch_upstream(repository, cwd, name, cancellation).await?; + // The whole delete's resume freezes the target the person approved (#397 round 3). + let mut whole = request.clone(); + if let Request::BranchDelete { + expected_tip, + expected_remote, + expected_remote_branch, + .. + } = &mut whole + { + *expected_tip = local_branch_tip(repository, cwd, name, cancellation).await; + *expected_remote = Some(remote.clone()); + *expected_remote_branch = Some(branch.clone()); + } Some(( - remote.to_owned(), + remote.clone(), SignInDirection::Push, - Request::RemoteBranchDelete { + whole, + Some(Request::RemoteBranchDelete { cwd: cwd.clone(), project_id: project_id.clone(), - remote: remote.to_owned(), - branch: branch.to_owned(), + remote, + branch, expected_destination: None, - }, + }), )) } _ => None, @@ -1317,6 +1354,10 @@ fn expected_destination_mut( expected_destination, .. } + | Request::BranchDelete { + expected_destination, + .. + } | Request::TagPush { expected_destination, .. @@ -1335,13 +1376,14 @@ async fn execute_branch_or_sync_operation( ) -> Result { let operation = request.operation(); refuse_option_like_operands(operation, request)?; - let mut network = network_step(snapshot, request); + refuse_changed_delete_target(repository, request, cancellation).await?; + let mut network = network_step(repository, request, cancellation).await; // Taken from the resume copy: a later offer sets the newly frozen destination there. let expected = network .as_mut() - .and_then(|(_, _, resume)| expected_destination_mut(resume)) + .and_then(|(_, _, resume, _)| expected_destination_mut(resume)) .and_then(Option::take); - if let (Some(expected), Some((remote, direction, _))) = (expected, &network) { + if let (Some(expected), Some((remote, direction, ..))) = (expected, &network) { let current = resolve_destination(repository, request.cwd(), remote, *direction, cancellation).await; if !matches!(current, Destination::Offer { ref destination, .. } if *destination == expected) @@ -1354,10 +1396,33 @@ async fn execute_branch_or_sync_operation( )); } } - let result = execute_operation_steps(repository, snapshot, request, cancellation).await; + let mut local_branch_deleted = false; + let result = execute_operation_steps( + repository, + snapshot, + request, + &mut local_branch_deleted, + cancellation, + ) + .await; let result = match (result, network, prompt) { - (Err(error), Some(step), CredentialPrompt::OfferSignIn) => { - Err(offer_sign_in(repository, request.cwd(), error, step, cancellation).await) + ( + Err(error), + Some((remote, direction, whole, after_local)), + CredentialPrompt::OfferSignIn, + ) => { + let resume = match after_local { + Some(remote_only) if local_branch_deleted => remote_only, + _ => whole, + }; + Err(offer_sign_in( + repository, + request.cwd(), + error, + (remote, direction, resume), + cancellation, + ) + .await) } (result, ..) => result, }; @@ -1454,10 +1519,13 @@ async fn offer_sign_in( error } +/// `local_branch_deleted` is set once a branch delete with its remote has deleted the local +/// branch, so a sign-in its push needs resumes the remote delete only. async fn execute_operation_steps( repository: &GitRepository, snapshot: &GitManagerRefsSnapshot, request: &GitManagerOperationRequest, + local_branch_deleted: &mut bool, cancellation: &CancellationToken, ) -> Result { let operation = request.operation(); @@ -1566,13 +1634,26 @@ async fn execute_operation_steps( .. } => { let remote_target = if *delete_remote { - Some(remote_delete_target(snapshot, name).ok_or_else(|| { - operation_error( - operation, - "no-upstream", - "Remote deletion is blocked because this branch has no upstream.", - ) - })?) + let (remote, remote_branch) = branch_upstream(repository, cwd, name, cancellation) + .await + .ok_or_else(|| { + operation_error( + operation, + "no-upstream", + "Remote deletion is blocked because this branch has no upstream.", + ) + })?; + refuse_unknown_remote_target(operation, snapshot, &remote, &remote_branch)?; + let checked = check_remote_branch_delete( + repository, + operation, + cwd, + &remote, + &remote_branch, + cancellation, + ) + .await?; + Some((remote, remote_branch, checked)) } else { None }; @@ -1582,9 +1663,16 @@ async fn execute_operation_steps( .git_manager_delete_branch(cwd, name, *force, cancellation) .await, )?; - if let Some((remote, remote_branch)) = remote_target { + *local_branch_deleted = true; + if let Some((remote, remote_branch, checked)) = remote_target { let remote_output = repository - .git_manager_delete_remote_branch(cwd, remote, remote_branch, cancellation) + .git_manager_delete_remote_branch( + cwd, + &remote, + &remote_branch, + &checked, + cancellation, + ) .await .map_err(|error| git_command_error(operation, error, outputs.clone()))?; outputs.push(remote_output); @@ -1598,24 +1686,20 @@ async fn execute_operation_steps( branch, .. } => { - if !snapshot.remotes.iter().any(|known| known == remote) { - return Err(operation_error( - operation, - "invalid-request", - "The remote is not one of this checkout's remotes.", - )); - } - if !is_branch_name(branch) { - return Err(operation_error( - operation, - "invalid-request", - "The remote branch name is not a valid branch name.", - )); - } + refuse_unknown_remote_target(operation, snapshot, remote, branch)?; + let checked = check_remote_branch_delete( + repository, + operation, + cwd, + remote, + branch, + cancellation, + ) + .await?; one_output( operation, repository - .git_manager_delete_remote_branch(cwd, remote, branch, cancellation) + .git_manager_delete_remote_branch(cwd, remote, branch, &checked, cancellation) .await, )? } @@ -2214,17 +2298,381 @@ fn remote_tracking_ref<'a>( }) } -fn remote_delete_target<'a>( - snapshot: &'a GitManagerRefsSnapshot, +/// A remote and branch a delete targets: a remote this checkout has, whose name Git cannot read +/// as an option, and a valid branch name (#139 slice G, #405). +fn refuse_unknown_remote_target( + operation: &str, + snapshot: &GitManagerRefsSnapshot, + remote: &str, branch: &str, -) -> Option<(&'a str, &'a str)> { - snapshot - .local_branches - .iter() - .find(|reference| reference.name == branch)? - .upstream - .as_deref()? - .split_once('/') +) -> Result<(), GitManagerOperationError> { + if remote.starts_with('-') || !snapshot.remotes.iter().any(|known| known == remote) { + return Err(operation_error( + operation, + "invalid-request", + "The remote is not one of this checkout's remotes.", + )); + } + if !is_branch_name(branch) { + return Err(operation_error( + operation, + "invalid-request", + "The remote branch name is not a valid branch name.", + )); + } + // With `team` and `team/fork`, `team/fork/x` names two possible targets (#397 round 3). + if snapshot.remotes.iter().any(|other| { + other != remote + && (other.starts_with(&format!("{remote}/")) + || remote.starts_with(&format!("{other}/"))) + }) { + return Err(operation_error( + operation, + "remote-name-ambiguous", + "Another remote's name starts with this one, so the branch cannot be told apart. Delete it with git on the command line.", + )); + } + Ok(()) +} + +/// The remote and the branch on it that `name` tracks, from Git's `%(upstream:remotename)` and +/// `%(upstream:remoteref)`, never a split of the tracking name (#405). +async fn branch_upstream( + repository: &GitRepository, + cwd: &Path, + name: &str, + cancellation: &CancellationToken, +) -> Option<(String, String)> { + let full = format!("refs/heads/{name}"); + let output = repository + .run( + "GitManager.branchUpstream", + cwd, + &[ + "for-each-ref".to_owned(), + "--format=%(refname)%09%(upstream:remotename)%09%(upstream:remoteref)".to_owned(), + full.clone(), + ], + cancellation, + ) + .await + .ok()?; + // A pattern also matches refs below it, so only the exact ref counts. + output.stdout.lines().find_map(|line| { + let mut fields = line.split('\t'); + if fields.next()? != full { + return None; + } + let remote = fields.next()?; + let branch = fields.next()?.strip_prefix("refs/heads/")?; + (!remote.is_empty() && !branch.is_empty()).then(|| (remote.to_owned(), branch.to_owned())) + }) +} + +/// The commit a local ref names, or `None` when it does not exist. +async fn local_ref_tip( + repository: &GitRepository, + operation: &str, + cwd: &Path, + reference: &str, + cancellation: &CancellationToken, +) -> Option { + let output = repository + .run_allowing_failure( + operation, + cwd, + &[ + "rev-parse".to_owned(), + "--verify".to_owned(), + "--quiet".to_owned(), + "--end-of-options".to_owned(), + format!("{reference}^{{commit}}"), + ], + cancellation, + ) + .await + .ok()?; + let tip = output.stdout.trim(); + (output.exit_code == 0 && !tip.is_empty()).then(|| tip.to_owned()) +} + +async fn local_branch_tip( + repository: &GitRepository, + cwd: &Path, + name: &str, + cancellation: &CancellationToken, +) -> Option { + let reference = format!("refs/heads/{name}"); + local_ref_tip( + repository, + "GitManager.branchDeleteTip", + cwd, + &reference, + cancellation, + ) + .await +} + +/// #397 round 3: a delete with its remote resumed after a sign-in refuses, before anything is +/// deleted, when the local branch's tip, its remote or its upstream branch is no longer the one +/// the offer froze (the branch was deleted, recreated, moved or retargeted meanwhile). +async fn refuse_changed_delete_target( + repository: &GitRepository, + request: &GitManagerOperationRequest, + cancellation: &CancellationToken, +) -> Result<(), GitManagerOperationError> { + let GitManagerOperationRequest::BranchDelete { + cwd, + name, + delete_remote: true, + expected_destination: Some(_), + expected_tip, + expected_remote, + expected_remote_branch, + .. + } = request + else { + return Ok(()); + }; + let tip = local_branch_tip(repository, cwd, name, cancellation).await; + let upstream = branch_upstream(repository, cwd, name, cancellation).await; + let frozen = expected_remote.clone().zip(expected_remote_branch.clone()); + if tip.is_none() || tip != *expected_tip || upstream.is_none() || upstream != frozen { + return Err(operation_error( + request.operation(), + "branch-changed", + "This branch or its upstream changed while you signed in, so nothing was deleted. Open Delete again.", + )); + } + Ok(()) +} + +/// Whether one `fetch` line is on the allowlist: the standard `refs/heads/*` wildcard into +/// `refs/remotes//*`, or one branch into the same name there, with or without `+`. +fn fetch_refspec_allowed(spec: &str, remote: &str) -> bool { + let spec = spec.strip_prefix('+').unwrap_or(spec); + let tracking = format!("refs/remotes/{remote}/"); + spec.split_once(':').is_some_and(|(source, destination)| { + match ( + source.strip_prefix("refs/heads/"), + destination.strip_prefix(tracking.as_str()), + ) { + (Some(branch), Some(tracked)) => { + branch == tracked && !branch.is_empty() && (branch == "*" || !branch.contains('*')) + } + _ => false, + } + }) +} + +const FETCH_SETTINGS_REFUSAL: &str = "This remote has custom fetch settings, so BiBCode cannot check the branch safely. Delete it with git on the command line."; + +/// #397 round 3: the remote's settings, read once NUL-delimited so no path character is +/// normalized, must be on an allowlist, fail closed. The remote has exactly one `url`, no +/// `pushurl` and no `pushInsteadOf` rewrite (so the push reaches the repository checked), is +/// not also a remote group (which `git push` would expand), and every `fetch` line is allowed. +async fn refuse_unsupported_remote_settings( + repository: &GitRepository, + operation: &str, + cwd: &Path, + remote: &str, + cancellation: &CancellationToken, +) -> Result<(), GitManagerOperationError> { + let refuse = |code: &str, message: &str| Err(operation_error(operation, code, message)); + // `GIT_CONFIG` redirects `git config` alone, so the read below would check another file + // than the push uses. The other configuration variables (`GIT_CONFIG_GLOBAL`, + // `GIT_CONFIG_COUNT`, `GIT_DIR`, ...) reach the read and the push alike through the same + // runner, so they leave the check sound. + if std::env::var_os("GIT_CONFIG").is_some_and(|value| !value.is_empty()) { + return refuse( + "remote-config-redirected", + "BiBCode was started with GIT_CONFIG set, so this remote's settings cannot be checked. Delete the branch from a terminal.", + ); + } + let Ok(output) = repository + .run( + "GitManager.remoteBranchDeleteCheck.config", + cwd, + &["config".to_owned(), "-z".to_owned(), "--list".to_owned()], + cancellation, + ) + .await + else { + return refuse("remote-fetch-mapping-unsupported", FETCH_SETTINGS_REFUSAL); + }; + // A read cut at the output limit may have dropped a later setting that refuses. + if output.stdout_truncated { + return refuse("remote-fetch-mapping-unsupported", FETCH_SETTINGS_REFUSAL); + } + let own = format!("remote.{remote}."); + let group = format!("remotes.{remote}"); + let mut urls = Vec::new(); + let mut push_url = false; + let mut is_group = false; + let mut fetch_allowed = true; + let mut push_rewrites = Vec::new(); + for entry in output.stdout.split('\0').filter(|entry| !entry.is_empty()) { + let (key, value) = entry.split_once('\n').unwrap_or((entry, "")); + if let Some(variable) = key.strip_prefix(own.as_str()) { + match variable { + "url" => urls.push(value), + "pushurl" => push_url = true, + "fetch" => fetch_allowed &= fetch_refspec_allowed(value, remote), + _ => {} + } + } else if key.eq_ignore_ascii_case(&group) { + is_group = true; + } else if key.starts_with("url.") && key.ends_with(".pushinsteadof") { + push_rewrites.push(value); + } + } + if is_group { + return refuse( + "remote-is-group", + "This remote's name is also a remote group, so the push could reach other remotes. Delete the branch with git on the command line.", + ); + } + let rewritten = |url: &str| push_rewrites.iter().any(|prefix| url.starts_with(prefix)); + if push_url || urls.len() != 1 || urls.iter().any(|url| rewritten(url)) { + return refuse( + "remote-push-url-differs", + "This remote pushes to another URL than it fetches from, so the branch cannot be checked. Delete it from a terminal.", + ); + } + if !fetch_allowed { + return refuse("remote-fetch-mapping-unsupported", FETCH_SETTINGS_REFUSAL); + } + Ok(()) +} + +/// R7 (#397, #404): the server decides every remote branch delete, and returns the commit it +/// checked so the push can lease it. Before anything is deleted it refuses a remote that pushes +/// to another URL than the one it reads, a fetch configuration that renames branches, a remote +/// it cannot ask, a `HEAD` that names the branch or no branch, a branch that is missing or +/// symbolic, and a tracking ref at another commit (a branch never fetched is not compared). The `ls-remote` +/// runs through the network runner, so a sign-in can be offered and a resumed request checks +/// again. A remote that answers with no `HEAD` (unborn) has no default branch to protect. +async fn check_remote_branch_delete( + repository: &GitRepository, + operation: &str, + cwd: &Path, + remote: &str, + branch: &str, + cancellation: &CancellationToken, +) -> Result { + let refuse = |code: &str, message: &str| Err(operation_error(operation, code, message)); + refuse_unsupported_remote_settings(repository, operation, cwd, remote, cancellation).await?; + let outputs = one_output( + operation, + repository + .git_manager_remote_heads(cwd, remote, branch, cancellation) + .await, + ) + .map_err(|mut error| { + // Git's own classification (authentication, a stall) says what to do; only an + // unclassified failure is named here. The stderr stays for a sign-in offer. + if error.code == GitManagerFailureCode::Unknown.as_str() { + "remote-default-unknown".clone_into(&mut error.code); + "The remote's default branch could not be checked.".clone_into(&mut error.message); + } + error + })?; + // A cut answer may have dropped the HEAD or the branch line the checks below rely on. + if outputs.iter().any(|output| output.stdout_truncated) { + return refuse( + "remote-default-unknown", + "The remote's default branch could not be checked.", + ); + } + let branch_ref = format!("refs/heads/{branch}"); + let mut default_ref = None; + let mut head_advertised = false; + let mut remote_tip = None; + let mut symbolic = false; + for line in outputs.iter().flat_map(|output| output.stdout.lines()) { + if let Some((target, name)) = line + .strip_prefix("ref: ") + .and_then(|rest| rest.split_once('\t')) + { + if name == "HEAD" { + default_ref = Some(target); + } else if name == branch_ref { + symbolic = true; + } + } else if let Some((sha, name)) = line.split_once('\t') { + if name == "HEAD" { + head_advertised = true; + } else if name == branch_ref { + remote_tip = Some(sha); + } + } + } + if default_ref == Some(branch_ref.as_str()) { + return refuse( + "default-branch", + "Delete is blocked: this is the remote's default branch.", + ); + } + // A HEAD with no branch name (detached) is a default that cannot be checked. + if default_ref.is_none() && head_advertised { + return refuse( + "remote-default-unknown", + "The remote's default branch could not be checked.", + ); + } + // Git reports a delete of a missing ref as a success, so say it here. Fetching cannot help + // a local delete whose remote branch is gone; clearing its remote option can. + let Some(remote_tip) = remote_tip else { + return refuse( + "remote-branch-not-found", + if operation == "branch-delete" { + "The branch no longer exists on the remote. Clear \"Also delete the branch from its remote\" to delete only the local branch." + } else { + "This branch no longer exists on the remote. Fetch to update the branch list." + }, + ); + }; + // Deleting a symbolic branch also deletes the ref it points to (reproduced on Git 2.56.1). + // Protocol v2 advertises the target; a remote that speaks only v0 does not. + if symbolic { + return refuse( + "remote-branch-symbolic", + "This branch on the remote points to another branch, and deleting it would delete that one too. Delete it with git on the command line.", + ); + } + let tracking = format!("refs/remotes/{remote}/{branch}"); + // Git's post-push cleanup deletes the tracking ref with dereferencing, so a symbolic one + // would take its target with it. Exit 1 is the only answer that means "not symbolic". + let symbolic_tracking = repository + .run_allowing_failure( + "GitManager.remoteBranchDeleteCheck.trackingSymref", + cwd, + &[ + "symbolic-ref".to_owned(), + "--quiet".to_owned(), + tracking.clone(), + ], + cancellation, + ) + .await + .map_or(true, |output| output.exit_code != 1); + if symbolic_tracking { + return refuse( + "remote-tracking-symbolic", + "This branch's tracking ref points to another ref, and deleting it could delete that one too. Delete it with git on the command line.", + ); + } + let tracking_check = "GitManager.remoteBranchDeleteCheck.trackingRef"; + if local_ref_tip(repository, tracking_check, cwd, &tracking, cancellation) + .await + .is_some_and(|tracking_tip| tracking_tip != remote_tip) + { + return refuse( + "remote-branch-changed", + "This branch changed on the remote since the last fetch. Fetch, then delete it.", + ); + } + Ok(remote_tip.to_owned()) } fn one_output( @@ -4347,6 +4795,10 @@ mod tests { name: "topic".into(), force: true, delete_remote: false, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, }; let reason = blocked_reason_for_operation(&snapshot, &request) @@ -6147,38 +6599,1091 @@ mod tests { "the local branch stays" ); } -} -/// Status reads during a held Git Manager network step (#345, R19, R21). -#[cfg(test)] -mod transfer_gate_tests { - use std::{path::PathBuf, process::Command, sync::Mutex}; + /// A bare remote whose `HEAD` is `main`, with `main` and `feature` pushed from a clone. + fn remote_delete_fixture() -> (tempfile::TempDir, tempfile::TempDir) { + let remote = tempfile::tempdir().expect("bare remote"); + let fixture = tempfile::tempdir().expect("clone"); + git(remote.path(), &["init", "-q", "--bare", "-b", "main"]); + git(fixture.path(), &["init", "-q", "-b", "main"]); + git( + fixture.path(), + &["remote", "add", "origin", &remote.path().to_string_lossy()], + ); + std::fs::write(fixture.path().join("a.txt"), "a\n").expect("file"); + git(fixture.path(), &["add", "a.txt"]); + git(fixture.path(), &["commit", "-q", "-m", "base"]); + git(fixture.path(), &["branch", "feature"]); + git(fixture.path(), &["push", "-q", "origin", "main", "feature"]); + (remote, fixture) + } - use serde_json::json; - use tokio::sync::{Notify, Semaphore}; - use tokio_util::sync::CancellationToken; + async fn delete_on_remote( + fixture: &Path, + request: &GitManagerOperationRequest, + ) -> Result { + let repository = GitRepository::default(); + let token = CancellationToken::new(); + let snapshot = build_refs_snapshot(&repository, fixture, &token) + .await + .expect("refs snapshot"); + execute_branch_or_sync_operation( + &repository, + &snapshot, + request, + CredentialPrompt::Never, + &ExecutionPlace::default(), + &token, + ) + .await + } - use super::*; - use crate::{ - git::{ - BoxGitProcessFuture, GitProcessRunner, ProcessError, ProcessOutput, ProcessRequest, - ProcessRunner, sign_in::CredentialPrompt, - }, - persistence::{Database, Repositories, run_migrations}, - worktree_catalog::{CatalogServiceOptions, WorkspaceAvailabilityRegistry}, - }; + fn remote_delete(fixture: &Path, branch: &str) -> GitManagerOperationRequest { + GitManagerOperationRequest::RemoteBranchDelete { + cwd: fixture.to_path_buf(), + project_id: "p".into(), + remote: "origin".into(), + branch: branch.into(), + expected_destination: None, + } + } - /// Shorter than any local status read takes to queue, well below the hang budget. - const ADMITTED_WITHIN: Duration = Duration::from_secs(3); - /// Long enough for a gate that would open to have opened. - const STILL_WAITING_AFTER: Duration = Duration::from_millis(300); + fn remote_refs(remote: &Path) -> String { + git(remote, &["for-each-ref", "--format=%(refname)"]) + } - /// Runs local Git for real and holds every fetch, pull and push until released, then - /// answers with `outcome` (success when empty). No network is contacted. - struct HeldNetworkRunner { + /// R7: a same-named tag survives a branch that is gone. The pre-check refuses the missing + /// branch, because Git reports a delete of a missing `refs/heads/` ref as a success, and the + /// push itself names `refs/heads/` (pinned by the repository argument test). + #[tokio::test] + async fn remote_branch_delete_never_deletes_a_same_named_tag() { + let (remote, fixture) = remote_delete_fixture(); + git(fixture.path(), &["tag", "gone"]); + git(fixture.path(), &["push", "-q", "origin", "gone"]); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "gone")) + .await + .expect_err("no branch named gone exists on the remote"); + + assert_eq!(failure.code, "remote-branch-not-found"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main\nrefs/tags/gone" + ); + } + + /// R7: the remote's default branch is refused before anything is pushed. + #[tokio::test] + async fn remote_branch_delete_refuses_the_remotes_default_branch() { + let (remote, fixture) = remote_delete_fixture(); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "main")) + .await + .expect_err("the default branch is refused"); + + assert_eq!( + failure.message, + "Delete is blocked: this is the remote's default branch." + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// R7: a remote that cannot be asked for its default branch deletes nothing. + #[tokio::test] + async fn remote_branch_delete_refuses_when_the_remote_cannot_be_asked() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &["branch", "--track", "topic", "origin/feature"], + ); + let unreachable = remote.path().join("missing"); + git( + fixture.path(), + &[ + "remote", + "set-url", + "origin", + &unreachable.to_string_lossy(), + ], + ); + + for request in [ + remote_delete(fixture.path(), "feature"), + GitManagerOperationRequest::BranchDelete { + cwd: fixture.path().to_path_buf(), + project_id: "p".into(), + name: "topic".into(), + force: true, + delete_remote: true, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, + }, + ] { + let failure = delete_on_remote(fixture.path(), &request) + .await + .expect_err("an unreachable remote is refused"); + assert_eq!(failure.code, "remote-default-unknown"); + assert_eq!( + failure.message, + "The remote's default branch could not be checked." + ); + } + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + assert_eq!( + git(fixture.path(), &["branch", "--format=%(refname:short)"]), + "feature\nmain\ntopic", + "the local branch stays" + ); + } + + /// R7: a remote that advertises `HEAD` without naming its branch (a detached `HEAD`) has a + /// default that cannot be checked, so nothing is deleted. + #[tokio::test] + async fn remote_branch_delete_refuses_a_head_that_names_no_branch() { + let (remote, fixture) = remote_delete_fixture(); + let main = git(remote.path(), &["rev-parse", "refs/heads/main"]); + git(remote.path(), &["update-ref", "--no-deref", "HEAD", &main]); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a detached remote HEAD is refused"); + + assert_eq!(failure.code, "remote-default-unknown"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// Ruling on P10: a remote that answers with no `HEAD` (unborn, as after `git init --bare` + /// with another default branch, or dangling) has no default to protect, so the delete runs. + #[tokio::test] + async fn remote_branch_delete_proceeds_when_the_remote_has_no_head() { + let (remote, fixture) = remote_delete_fixture(); + git( + remote.path(), + &["symbolic-ref", "HEAD", "refs/heads/missing"], + ); + + delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect("a remote without a default branch allows the delete"); + + assert_eq!(remote_refs(remote.path()), "refs/heads/main"); + } + + /// #397 review finding 1: a remote that pushes to another URL than it fetches from is + /// refused, because the check reads the fetch side. + #[tokio::test] + async fn remote_branch_delete_refuses_a_remote_that_pushes_elsewhere() { + let (remote, fixture) = remote_delete_fixture(); + let elsewhere = tempfile::tempdir().expect("push remote"); + let elsewhere_url = elsewhere.path().to_string_lossy().into_owned(); + git(elsewhere.path(), &["init", "-q", "--bare", "-b", "feature"]); + git( + fixture.path(), + &["push", "-q", &elsewhere_url, "main", "feature"], + ); + git( + fixture.path(), + &["remote", "set-url", "--push", "origin", &elsewhere_url], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a split remote is refused"); + + assert_eq!(failure.code, "remote-push-url-differs"); + assert_eq!( + remote_refs(elsewhere.path()), + "refs/heads/feature\nrefs/heads/main" + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// #397 review finding 2: the delete carries the checked commit as a lease, so a branch that + /// moved after the check is kept. + #[tokio::test] + async fn remote_branch_delete_keeps_a_branch_that_moved_after_the_check() { + let (remote, fixture) = remote_delete_fixture(); + let checked = git( + fixture.path(), + &["rev-parse", "refs/remotes/origin/feature"], + ); + let other = tempfile::tempdir().expect("second clone"); + git( + other.path(), + &[ + "clone", + "-q", + &remote.path().to_string_lossy(), + &other.path().to_string_lossy(), + ], + ); + git(other.path(), &["switch", "-q", "feature"]); + git( + other.path(), + &["commit", "-q", "--allow-empty", "-m", "moved"], + ); + git(other.path(), &["push", "-q", "origin", "feature"]); + + let output = GitRepository::default() + .git_manager_delete_remote_branch( + fixture.path(), + "origin", + "feature", + &checked, + &CancellationToken::new(), + ) + .await + .expect("git runs"); + + assert_ne!(output.exit_code, 0, "the stale lease is rejected"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// #405: a local delete with its remote deletes the upstream Git names. The old split at the + /// first `/` read the upstream of remote `team/fork` as branch `fork/topic` on `team`. (Git + /// 2.56 refuses to add `team/fork` beside a remote named `team`, so that pair is not built.) + #[tokio::test] + async fn local_delete_with_remote_deletes_the_upstream_git_names() { + let fork = tempfile::tempdir().expect("fork remote"); + let fixture = tempfile::tempdir().expect("clone"); + git(fork.path(), &["init", "-q", "--bare", "-b", "main"]); + git(fixture.path(), &["init", "-q", "-b", "main"]); + git( + fixture.path(), + &["commit", "-q", "--allow-empty", "-m", "base"], + ); + git( + fixture.path(), + &["remote", "add", "team/fork", &fork.path().to_string_lossy()], + ); + git( + fixture.path(), + &["push", "-q", "team/fork", "main", "main:refs/heads/topic"], + ); + git(fixture.path(), &["branch", "local"]); + git( + fixture.path(), + &["config", "branch.local.remote", "team/fork"], + ); + git( + fixture.path(), + &["config", "branch.local.merge", "refs/heads/topic"], + ); + + delete_on_remote( + fixture.path(), + &GitManagerOperationRequest::BranchDelete { + cwd: fixture.path().to_path_buf(), + project_id: "p".into(), + name: "local".into(), + force: true, + delete_remote: true, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, + }, + ) + .await + .expect("the upstream on team/fork is deleted"); + + assert_eq!(remote_refs(fork.path()), "refs/heads/main"); + assert_eq!( + git(fixture.path(), &["branch", "--format=%(refname:short)"]), + "main" + ); + } + + /// #405: an upstream remote whose name Git would read as an option is refused. + #[tokio::test] + async fn local_delete_with_remote_refuses_an_option_like_upstream_remote() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &["config", "remote.-q.url", &remote.path().to_string_lossy()], + ); + // Git reports an upstream only through a fetch mapping. + git( + fixture.path(), + &[ + "config", + "remote.-q.fetch", + "+refs/heads/*:refs/remotes/-q/*", + ], + ); + git(fixture.path(), &["branch", "dash"]); + git(fixture.path(), &["config", "branch.dash.remote", "-q"]); + git( + fixture.path(), + &["config", "branch.dash.merge", "refs/heads/feature"], + ); + + let failure = delete_on_remote( + fixture.path(), + &GitManagerOperationRequest::BranchDelete { + cwd: fixture.path().to_path_buf(), + project_id: "p".into(), + name: "dash".into(), + force: true, + delete_remote: true, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, + }, + ) + .await + .expect_err("an option-like remote is refused"); + + assert_eq!(failure.code, "invalid-request"); + assert_eq!( + git(fixture.path(), &["branch", "--format=%(refname:short)"]), + "dash\nfeature\nmain" + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// #397 review finding 4: a tracking ref that a custom fetch mapping fills from another + /// branch is refused, even at an equal commit. + #[tokio::test] + async fn remote_branch_delete_refuses_a_tracking_ref_mapped_from_another_branch() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &[ + "push", + "-q", + "origin", + "main:refs/heads/topic", + "main:refs/heads/alias", + ], + ); + git( + fixture.path(), + &[ + "config", + "--replace-all", + "remote.origin.fetch", + "+refs/heads/topic:refs/remotes/origin/alias", + ], + ); + git(fixture.path(), &["fetch", "-q", "origin"]); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "alias")) + .await + .expect_err("a mapped tracking ref is refused"); + + assert_eq!(failure.code, "remote-fetch-mapping-unsupported"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/alias\nrefs/heads/feature\nrefs/heads/main\nrefs/heads/topic" + ); + } + + fn local_delete_with_remote(fixture: &Path, name: &str) -> GitManagerOperationRequest { + GitManagerOperationRequest::BranchDelete { + cwd: fixture.to_path_buf(), + project_id: "p".into(), + name: name.into(), + force: true, + delete_remote: true, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, + } + } + + fn local_branches(fixture: &Path) -> String { + git(fixture, &["branch", "--format=%(refname:short)"]) + } + + /// Round 2 ruling B (Codex 5, 6, 8; Antigravity 3, 6, 8): a fetch configuration that is not + /// the identity `refs/heads/` to `refs/remotes//` is refused before anything is + /// deleted, by both operations. A first mapping into `refs/heads/` would let Git's + /// post-push tracking update delete the local branch; a negative refspec hides which branch + /// fills a tracking name. + #[tokio::test] + async fn every_delete_refuses_a_fetch_mapping_that_renames_branches() { + for mapping in [ + vec![ + "+refs/heads/feature:refs/heads/feature", + "+refs/heads/*:refs/remotes/origin/*", + ], + vec!["+refs/heads/*:refs/remotes/origin/*", "^refs/heads/secret"], + vec!["+refs/heads/*:refs/remotes/cache/*"], + vec!["refs/heads/feature"], + // A glob that covers `refs/heads/` without naming it: `--mirror=fetch` writes the + // first, and Git's post-push update then deletes the local branch (reproduced). + vec!["+refs/*:refs/*"], + vec!["+refs/*:refs/remotes/origin/*"], + // Round 3 allowlist (Codex 7, 9; Antigravity 1, 4): shorthand, tag, pull-request + // and negative refspecs refuse, even beside the standard wildcard. + vec!["+main:refs/remotes/origin/feature"], + vec!["+refs/tags/v1:refs/remotes/origin/feature"], + vec![ + "+refs/heads/*:refs/remotes/origin/*", + "+refs/pull/*/head:refs/remotes/origin/pr/*", + ], + vec!["+refs/heads/*:refs/remotes/origin/*", "^refs/tags/*"], + vec!["+refs/heads/*:refs/remotes/origin/*", "refs/heads/release"], + ] { + let (remote, fixture) = remote_delete_fixture(); + git(fixture.path(), &["fetch", "-q", "origin"]); + git( + fixture.path(), + &["branch", "--track", "topic", "origin/feature"], + ); + git( + fixture.path(), + &["config", "--unset-all", "remote.origin.fetch"], + ); + for spec in &mapping { + git( + fixture.path(), + &["config", "--add", "remote.origin.fetch", spec], + ); + } + for request in [ + remote_delete(fixture.path(), "feature"), + local_delete_with_remote(fixture.path(), "topic"), + ] { + let failure = delete_on_remote(fixture.path(), &request) + .await + .expect_err("a renaming fetch mapping is refused"); + // Without a mapping for `feature`, Git names no upstream for the local delete, + // which stops at `no-upstream` before anything is deleted. + let standard = mapping.contains(&"+refs/heads/*:refs/remotes/origin/*"); + if failure.code == "no-upstream" && !standard { + continue; + } + assert_eq!( + failure.code, + "remote-fetch-mapping-unsupported", + "{mapping:?} {}", + request.operation() + ); + assert_eq!( + failure.message, + "This remote has custom fetch settings, so BiBCode cannot check the branch safely. Delete it with git on the command line." + ); + } + assert_eq!( + local_branches(fixture.path()), + "feature\nmain\ntopic", + "{mapping:?}" + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main", + "{mapping:?}" + ); + } + } + + /// Round 2 ruling A (Codex 2): the whole delete runs its local guards before its push, so a + /// local branch checked out in another worktree keeps the remote branch too. + #[tokio::test] + async fn a_whole_delete_of_a_branch_held_by_a_worktree_keeps_the_remote_branch() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &["branch", "--track", "topic", "origin/feature"], + ); + let held = tempfile::tempdir().expect("worktree"); + let held_path = held.path().join("topic"); + git( + fixture.path(), + &[ + "worktree", + "add", + "-q", + &held_path.to_string_lossy(), + "topic", + ], + ); + + delete_on_remote( + fixture.path(), + &local_delete_with_remote(fixture.path(), "topic"), + ) + .await + .expect_err("a branch checked out elsewhere is not deleted"); + + assert_eq!(local_branches(fixture.path()), "feature\nmain\ntopic"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// The allowlist keeps ordinary clones working: a shallow single-branch clone and a default + /// clone (a pull-request refspec now refuses; see the test above). + #[tokio::test] + async fn a_single_branch_clone_and_a_default_clone_still_delete() { + let (remote, _seed) = remote_delete_fixture(); + git(remote.path(), &["branch", "gone-one", "main"]); + git(remote.path(), &["branch", "gone-two", "main"]); + let shallow = tempfile::tempdir().expect("shallow clone"); + git( + shallow.path(), + &[ + "clone", + "-q", + "--depth", + "1", + "--single-branch", + "--branch", + "feature", + &format!("file://{}", remote.path().to_string_lossy()), + &shallow.path().to_string_lossy(), + ], + ); + delete_on_remote(shallow.path(), &remote_delete(shallow.path(), "gone-one")) + .await + .expect("a single-branch clone deletes a branch it never fetched"); + git(shallow.path(), &["branch", "topic", "origin/feature"]); + git(shallow.path(), &["config", "branch.topic.remote", "origin"]); + git( + shallow.path(), + &["config", "branch.topic.merge", "refs/heads/feature"], + ); + delete_on_remote( + shallow.path(), + &local_delete_with_remote(shallow.path(), "topic"), + ) + .await + .expect("a single-branch clone deletes its upstream"); + + let fixture = tempfile::tempdir().expect("clone"); + git( + fixture.path(), + &[ + "clone", + "-q", + &remote.path().to_string_lossy(), + &fixture.path().to_string_lossy(), + ], + ); + delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "gone-two")) + .await + .expect("a default clone deletes"); + assert_eq!(remote_refs(remote.path()), "refs/heads/main"); + } + + /// Codex 3: the fetch and push URLs are compared exactly; a push URL that differs only by a + /// trailing space names another repository. + #[tokio::test] + async fn remote_branch_delete_compares_push_and_fetch_urls_exactly() { + let (remote, fixture) = remote_delete_fixture(); + let spaced = format!("{} ", remote.path().to_string_lossy()); + git( + fixture.path(), + &["remote", "set-url", "--push", "origin", &spaced], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a push URL that differs by a space is refused"); + + assert_eq!(failure.code, "remote-push-url-differs"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// A second bare repository holding `feature` at the fixture's commit, as another place a + /// push could be sent. + fn second_remote(fixture: &Path) -> tempfile::TempDir { + let other = tempfile::tempdir().expect("second remote"); + git(other.path(), &["init", "-q", "--bare", "-b", "main"]); + git( + fixture, + &[ + "push", + "-q", + &other.path().to_string_lossy(), + "main", + "feature", + ], + ); + other + } + + /// Round 3 (Codex 5): the push destination is an allowlist read NUL-delimited. A + /// `pushInsteadOf` rewrite of the one URL refuses, as `pushurl` and several URLs do. + #[tokio::test] + async fn remote_branch_delete_refuses_a_push_rewrite() { + let (remote, fixture) = remote_delete_fixture(); + let other = second_remote(fixture.path()); + git( + fixture.path(), + &[ + "config", + &format!("url.{}.pushInsteadOf", other.path().to_string_lossy()), + &remote.path().to_string_lossy(), + ], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a rewritten push is refused"); + + assert_eq!(failure.code, "remote-push-url-differs"); + for repository in [remote.path(), other.path()] { + assert_eq!( + remote_refs(repository), + "refs/heads/feature\nrefs/heads/main" + ); + } + } + + /// `GIT_CONFIG` redirects only `git config`: with it set, the settings read shows another + /// file than the push uses, so a remote that pushes elsewhere would pass. It refuses. + #[tokio::test] + async fn remote_branch_delete_refuses_when_git_config_redirects_the_settings_read() { + use crate::test_support::reexec; + const NAME: &str = "git::manager::operations::tests::remote_branch_delete_refuses_when_git_config_redirects_the_settings_read"; + const PHASE: &str = "git-config-view"; + let Some(isolated) = reexec::enter(NAME, PHASE) else { + let directory = tempfile::tempdir().expect("view directory"); + let view = directory.path().join("view.gitconfig"); + reexec::run(NAME, PHASE, None, |command| { + command.env("GIT_CONFIG", &view); + }); + return; + }; + let (remote, fixture) = remote_delete_fixture(); + let other = second_remote(fixture.path()); + git( + fixture.path(), + &[ + "config", + "remote.origin.pushurl", + &other.path().to_string_lossy(), + ], + ); + // The redirected view shows only the standard settings, as the reviewer described. + std::fs::write( + std::env::var_os("GIT_CONFIG").expect("GIT_CONFIG set for this run"), + format!( + "[remote \"origin\"]\n\turl = {}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n", + remote.path().to_string_lossy() + ), + ) + .expect("view config"); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a redirected settings read is refused"); + + assert_eq!(failure.code, "remote-config-redirected"); + for repository in [remote.path(), other.path()] { + assert_eq!( + remote_refs(repository), + "refs/heads/feature\nrefs/heads/main" + ); + } + isolated.complete(); + } + + /// A settings read cut at the output limit is not the whole allowlist: a `pushurl` past the + /// cut must still refuse, so a truncated read refuses before anything is deleted. + #[tokio::test] + async fn remote_branch_delete_refuses_when_the_settings_read_is_truncated() { + let (remote, fixture) = remote_delete_fixture(); + let other = second_remote(fixture.path()); + let config = fixture.path().join(".git/config"); + let mut contents = std::fs::read_to_string(&config).expect("config"); + contents.push_str("[padding]\n"); + let value = "x".repeat(1000); + for index in 0..1100 { + contents.push_str(&format!("\tentry{index} = {value}\n")); + } + // Git reads a backslash in an unquoted config value as an escape, so a Windows path is + // written with forward slashes, which Git accepts there too. + contents.push_str(&format!( + "[remote \"origin\"]\n\tpushurl = {}\n", + other.path().to_string_lossy().replace('\\', "/") + )); + std::fs::write(&config, contents).expect("padded config"); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a truncated settings read is refused"); + + assert_eq!(failure.code, "remote-fetch-mapping-unsupported"); + for repository in [remote.path(), other.path()] { + assert_eq!( + remote_refs(repository), + "refs/heads/feature\nrefs/heads/main" + ); + } + } + + /// Round 3 (Codex 3): `git push origin` expands a remote group named `origin`, so a remote + /// whose name is also a group refuses before either ref is deleted. + #[tokio::test] + async fn every_delete_refuses_a_remote_that_is_also_a_group() { + let (remote, fixture) = remote_delete_fixture(); + let other = second_remote(fixture.path()); + git( + fixture.path(), + &["remote", "add", "backup", &other.path().to_string_lossy()], + ); + git(fixture.path(), &["config", "remotes.origin", "backup"]); + git( + fixture.path(), + &["branch", "--track", "topic", "origin/feature"], + ); + + for request in [ + remote_delete(fixture.path(), "feature"), + local_delete_with_remote(fixture.path(), "topic"), + ] { + let failure = delete_on_remote(fixture.path(), &request) + .await + .expect_err("a remote group is refused"); + assert_eq!(failure.code, "remote-is-group", "{}", request.operation()); + } + assert_eq!(local_branches(fixture.path()), "feature\nmain\ntopic"); + for repository in [remote.path(), other.path()] { + assert_eq!( + remote_refs(repository), + "refs/heads/feature\nrefs/heads/main" + ); + } + } + + /// Round 3 (Codex 2): Git deletes the tracking ref with dereferencing after the push, so a + /// symbolic `refs/remotes//` refuses; both refs survive. + #[tokio::test] + async fn remote_branch_delete_refuses_a_symbolic_tracking_ref() { + let (remote, fixture) = remote_delete_fixture(); + git(fixture.path(), &["branch", "keep", "feature"]); + git( + fixture.path(), + &[ + "symbolic-ref", + "refs/remotes/origin/feature", + "refs/heads/keep", + ], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a symbolic tracking ref is refused"); + + assert_eq!(failure.code, "remote-tracking-symbolic"); + assert_eq!(local_branches(fixture.path()), "feature\nkeep\nmain"); + assert_eq!( + git( + fixture.path(), + &["symbolic-ref", "refs/remotes/origin/feature"] + ), + "refs/heads/keep" + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// Round 3 (Codex 4): with remotes `team` and `team/fork`, a tracking name can belong to + /// either, so both deletes refuse and MCP never derives a recovery target from it. + #[tokio::test] + async fn every_delete_refuses_nested_remote_names() { + let (remote, fixture) = remote_delete_fixture(); + let url = remote.path().to_string_lossy().into_owned(); + git(fixture.path(), &["config", "remote.origin/fork.url", &url]); + git( + fixture.path(), + &[ + "config", + "remote.origin/fork.fetch", + "+refs/heads/*:refs/remotes/origin/fork/*", + ], + ); + git( + fixture.path(), + &["branch", "--track", "topic", "origin/feature"], + ); + + for request in [ + remote_delete(fixture.path(), "feature"), + local_delete_with_remote(fixture.path(), "topic"), + ] { + let failure = delete_on_remote(fixture.path(), &request) + .await + .expect_err("nested remote names are refused"); + assert_eq!( + failure.code, + "remote-name-ambiguous", + "{}", + request.operation() + ); + } + assert_eq!(local_branches(fixture.path()), "feature\nmain\ntopic"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// Codex 4 (reproduced on Git 2.56.1): a delete push of a symbolic remote branch deletes its + /// referent too, so a branch the remote advertises as symbolic is refused. + #[tokio::test] + async fn remote_branch_delete_refuses_a_symbolic_remote_branch() { + let (remote, fixture) = remote_delete_fixture(); + git( + remote.path(), + &["symbolic-ref", "refs/heads/topic", "refs/heads/main"], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "topic")) + .await + .expect_err("a symbolic remote branch is refused"); + + assert_eq!(failure.code, "remote-branch-symbolic"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main\nrefs/heads/topic" + ); + } + + /// #407: a branch named `release/HEAD` keeps its stale-tip check. + #[tokio::test] + async fn remote_branch_delete_compares_a_branch_named_with_a_head_suffix() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &["push", "-q", "origin", "main:refs/heads/release/HEAD"], + ); + let other = tempfile::tempdir().expect("second clone"); + git( + other.path(), + &[ + "clone", + "-q", + &remote.path().to_string_lossy(), + &other.path().to_string_lossy(), + ], + ); + git( + other.path(), + &["commit", "-q", "--allow-empty", "-m", "moved"], + ); + git( + other.path(), + &["push", "-q", "origin", "HEAD:refs/heads/release/HEAD"], + ); + + let failure = delete_on_remote( + fixture.path(), + &remote_delete(fixture.path(), "release/HEAD"), + ) + .await + .expect_err("a moved branch is refused"); + + assert_eq!(failure.code, "remote-branch-changed"); + } + + /// R7: a branch that moved on the remote since the last fetch is refused. + #[tokio::test] + async fn remote_branch_delete_refuses_a_branch_that_differs_from_its_tracking_ref() { + let (remote, fixture) = remote_delete_fixture(); + let other = tempfile::tempdir().expect("second clone"); + git( + other.path(), + &[ + "clone", + "-q", + &remote.path().to_string_lossy(), + &other.path().to_string_lossy(), + ], + ); + git(other.path(), &["switch", "-q", "feature"]); + std::fs::write(other.path().join("b.txt"), "b\n").expect("file"); + git(other.path(), &["add", "b.txt"]); + git(other.path(), &["commit", "-q", "-m", "moved"]); + git(other.path(), &["push", "-q", "origin", "feature"]); + git( + fixture.path(), + &[ + "update-ref", + "refs/remotes/origin/topic", + "refs/remotes/origin/main", + ], + ); + + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "feature")) + .await + .expect_err("a stale tracking ref is refused"); + assert_eq!(failure.code, "remote-branch-changed"); + assert_eq!( + failure.message, + "This branch changed on the remote since the last fetch. Fetch, then delete it." + ); + // A branch gone from the remote reads as missing, not changed, though its tracking ref + // remains (#397 review finding 9). + let failure = delete_on_remote(fixture.path(), &remote_delete(fixture.path(), "topic")) + .await + .expect_err("a missing branch is refused"); + assert_eq!(failure.code, "remote-branch-not-found"); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// R7: a local delete that would also delete the remote's default branch deletes nothing. + #[tokio::test] + async fn local_delete_with_remote_refuses_the_remotes_default_before_deleting() { + let (remote, fixture) = remote_delete_fixture(); + git( + fixture.path(), + &["branch", "--track", "mainline", "origin/main"], + ); + + let failure = delete_on_remote( + fixture.path(), + &GitManagerOperationRequest::BranchDelete { + cwd: fixture.path().to_path_buf(), + project_id: "p".into(), + name: "mainline".into(), + force: true, + delete_remote: true, + expected_destination: None, + expected_tip: None, + expected_remote: None, + expected_remote_branch: None, + }, + ) + .await + .expect_err("the remote default is refused"); + + assert_eq!( + failure.message, + "Delete is blocked: this is the remote's default branch." + ); + assert_eq!( + git(fixture.path(), &["branch", "--format=%(refname:short)"]), + "feature\nmain\nmainline", + "the local branch stays" + ); + assert_eq!( + remote_refs(remote.path()), + "refs/heads/feature\nrefs/heads/main" + ); + } + + /// D5: deleting a remote branch touches neither the index nor the working tree, so no + /// in-progress operation blocks it. + #[test] + fn remote_branch_delete_is_allowed_during_every_in_progress_operation() { + let fixture = tempfile::tempdir().expect("repository"); + git(fixture.path(), &["init", "-q", "-b", "main"]); + git( + fixture.path(), + &["commit", "-q", "--allow-empty", "-m", "base"], + ); + for kind in [ + GitManagerInProgressKind::Merge, + GitManagerInProgressKind::Rebase, + GitManagerInProgressKind::CherryPick, + GitManagerInProgressKind::Revert, + GitManagerInProgressKind::Squash, + ] { + let mut snapshot = operation_snapshot(fixture.path()); + snapshot.remotes = vec!["origin".into()]; + snapshot.in_progress_operation = Some(crate::git::GitManagerInProgressOperation { + kind, + current: None, + total: None, + }); + assert_eq!( + blocked_reason_for_operation(&snapshot, &remote_delete(fixture.path(), "feature")), + None, + "{kind:?}" + ); + // A control: the guards block fetch for these three, and nothing for revert or squash. + let blocks_fetch = matches!( + kind, + GitManagerInProgressKind::Merge + | GitManagerInProgressKind::Rebase + | GitManagerInProgressKind::CherryPick + ); + assert_eq!( + blocked_reason_for_operation( + &snapshot, + &GitManagerOperationRequest::Fetch { + cwd: fixture.path().to_path_buf(), + project_id: "p".into(), + remote: "origin".into(), + expected_destination: None, + } + ) + .is_some(), + blocks_fetch, + "{kind:?}" + ); + } + } +} + +/// Status reads during a held Git Manager network step (#345, R19, R21). +#[cfg(test)] +mod transfer_gate_tests { + use std::{path::PathBuf, process::Command, sync::Mutex}; + + use serde_json::json; + use tokio::sync::{Notify, Semaphore}; + use tokio_util::sync::CancellationToken; + + use super::*; + use crate::{ + git::{ + BoxGitProcessFuture, GitProcessRunner, ProcessError, ProcessOutput, ProcessRequest, + ProcessRunner, sign_in::CredentialPrompt, + }, + persistence::{Database, Repositories, run_migrations}, + worktree_catalog::{CatalogServiceOptions, WorkspaceAvailabilityRegistry}, + }; + + /// Shorter than any local status read takes to queue, well below the hang budget. + const ADMITTED_WITHIN: Duration = Duration::from_secs(3); + /// Long enough for a gate that would open to have opened. + const STILL_WAITING_AFTER: Duration = Duration::from_millis(300); + + /// Runs local Git for real and holds every fetch, pull and push until released, then + /// answers with `outcome` (success when empty). No network is contacted. + struct HeldNetworkRunner { started: Notify, release: Semaphore, outcome: Mutex>, + /// What the remote advertises to the remote delete's `ls-remote` pre-check, unheld. + ls_remote: String, } impl GitProcessRunner for HeldNetworkRunner { @@ -6191,6 +7696,18 @@ mod transfer_gate_tests { .args .iter() .any(|arg| matches!(arg.to_str(), Some("fetch" | "pull" | "push"))); + if request.args.iter().any(|arg| arg == "ls-remote") { + let stdout = self.ls_remote.clone(); + return Box::pin(async move { + Ok(ProcessOutput { + exit_code: 0, + stdout, + stderr: String::new(), + stdout_truncated: false, + stderr_truncated: false, + }) + }); + } if !network { return Box::pin(ProcessRunner.run(request, cancellation)); } @@ -6262,10 +7779,19 @@ mod transfer_gate_tests { ] { git(&cwd, args); } + let head = Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(&cwd) + .output() + .expect("git rev-parse starts"); + let head = String::from_utf8_lossy(&head.stdout).trim().to_owned(); let runner = Arc::new(HeldNetworkRunner { started: Notify::new(), release: Semaphore::new(0), outcome: Mutex::new(None), + ls_remote: format!( + "ref: refs/heads/main\tHEAD\n{head}\tHEAD\n{head}\trefs/heads/topic\n" + ), }); let repository = Arc::new(GitRepository::with_runner_for_test(runner.clone())); let database = Database::open_in_memory().await.expect("database"); @@ -6331,6 +7857,103 @@ mod transfer_gate_tests { } } + fn tip(cwd: &Path, reference: &str) -> String { + let output = Command::new("git") + .args(["rev-parse", reference]) + .current_dir(cwd) + .output() + .expect("git rev-parse starts"); + String::from_utf8_lossy(&output.stdout).trim().to_owned() + } + + /// #397 round 3 (Codex 1, Antigravity 2): a whole delete resumed after its sign-in runs + /// through the real entry point, guards included, and deletes nothing unless the local + /// branch, its remote and its upstream are still the ones the offer froze. + #[tokio::test] + async fn a_resumed_whole_delete_refuses_a_changed_target_before_deleting() { + let resume = |harness: &Harness| { + json!({ + "_tag": "branch-delete", "name": "topic", "force": true, "deleteRemote": true, + "expectedDestination": + "https://gitlab.example.test/example-group/sample-project.git", + "expectedTip": tip(&harness.cwd, "refs/heads/topic"), + "expectedRemote": "origin", "expectedRemoteBranch": "topic", + }) + }; + let setup = |harness: &Harness| { + git(&harness.cwd, &["branch", "topic"]); + git(&harness.cwd, &["config", "branch.topic.remote", "origin"]); + git( + &harness.cwd, + &["config", "branch.topic.merge", "refs/heads/topic"], + ); + }; + type Change = (&'static str, fn(&Harness)); + let changes: [Change; 4] = [ + ("checked out in another worktree", |harness| { + // Git refuses a `\\?\` path as a worktree destination. + let held = without_verbatim_prefix(harness.cwd.join("held")); + git( + &harness.cwd, + &["worktree", "add", "-q", &held.to_string_lossy(), "topic"], + ); + }), + ("deleted", |harness| { + git(&harness.cwd, &["branch", "-D", "topic"]) + }), + ("recreated with new commits", |harness| { + git(&harness.cwd, &["branch", "-D", "topic"]); + git( + &harness.cwd, + &["commit", "-q", "--allow-empty", "-m", "new"], + ); + git(&harness.cwd, &["branch", "topic"]); + git(&harness.cwd, &["config", "branch.topic.remote", "origin"]); + git( + &harness.cwd, + &["config", "branch.topic.merge", "refs/heads/topic"], + ); + }), + ("retargeted", |harness| { + git( + &harness.cwd, + &["config", "branch.topic.merge", "refs/heads/main"], + ); + }), + ]; + for (change, apply) in changes { + let harness = harness().await; + setup(&harness); + let request = resume(&harness); + apply(&harness); + let before = tip(&harness.cwd, "refs/heads/topic"); + // A delete that got past the freeze waits at the held push: fail, never hang. + let result = tokio::time::timeout( + Duration::from_secs(30), + start(&harness, request, CancellationToken::new()), + ) + .await + .unwrap_or_else(|_| panic!("{change}: the resumed delete reached its push")) + .expect("operation task"); + let failure = result.expect_err(change); + if change != "checked out in another worktree" { + assert_eq!(failure.code, "branch-changed", "{change}"); + } + assert_eq!(tip(&harness.cwd, "refs/heads/topic"), before, "{change}"); + } + + // Unchanged, the resumed delete reaches its push. + let harness = harness().await; + setup(&harness); + let mut running = start(&harness, resume(&harness), CancellationToken::new()); + wait_for_network_step(&harness, &mut running, "unchanged").await; + harness.runner.release.add_permits(1); + running + .await + .expect("operation task") + .expect("the unchanged delete runs"); + } + async fn read_admitted(harness: &Harness, within: Duration) -> bool { tokio::time::timeout( within, diff --git a/apps/server/src/git/manager/operations/sign_in_tests.rs b/apps/server/src/git/manager/operations/sign_in_tests.rs index 6fc58029e2..5d0e2723f5 100644 --- a/apps/server/src/git/manager/operations/sign_in_tests.rs +++ b/apps/server/src/git/manager/operations/sign_in_tests.rs @@ -23,14 +23,24 @@ const DESTINATION: &str = concat!("https:", "//github.com/owner/repo.git"); struct RemoteRunner { urls: String, stderr: String, + /// When set, `ls-remote` succeeds with this output and only the push fails. + ls_remote: Option, + /// What `rev-parse` reports for the local tracking ref. + tracking_tip: String, requests: Mutex>, } impl RemoteRunner { fn new(urls: &str, stderr: &str) -> Arc { + Self::checked(urls, stderr, None, "") + } + + fn checked(urls: &str, stderr: &str, ls_remote: Option<&str>, tracking_tip: &str) -> Arc { Arc::new(Self { urls: urls.to_owned(), stderr: stderr.to_owned(), + ls_remote: ls_remote.map(str::to_owned), + tracking_tip: tracking_tip.to_owned(), requests: Mutex::default(), }) } @@ -57,7 +67,7 @@ fn is_network(request: &ProcessRequest) -> bool { !request.operation.starts_with("GitManager.signIn") && arguments(request) .iter() - .any(|arg| matches!(arg.as_str(), "fetch" | "pull" | "push")) + .any(|arg| matches!(arg.as_str(), "fetch" | "pull" | "push" | "ls-remote")) } impl GitProcessRunner for RemoteRunner { @@ -68,6 +78,34 @@ impl GitProcessRunner for RemoteRunner { ) -> BoxGitProcessFuture<'a> { let (exit_code, stdout, stderr) = if request.operation == "GitManager.signIn.remoteUrls" { (0, self.urls.clone(), String::new()) + } else if request.operation == "GitManager.branchUpstream" { + // `topic` tracks `topic` on `origin`, as Git's upstream fields report it. + ( + 0, + "refs/heads/topic\torigin\trefs/heads/topic\n".to_owned(), + String::new(), + ) + } else if request.operation == "GitManager.remoteBranchDeleteCheck.config" { + // `git config -z --list`: each URL line as `remote.origin.url`, the standard fetch. + let mut list = self + .urls + .lines() + .map(|url| format!("remote.origin.url\n{url}\0")) + .collect::(); + list.push_str("remote.origin.fetch\n+refs/heads/*:refs/remotes/origin/*\0"); + (0, list, String::new()) + } else if request.operation == "GitManager.remoteBranchDeleteCheck.trackingSymref" { + (1, String::new(), String::new()) + } else if request.operation == "GitManager.branchDeleteTip" { + (0, format!("{TIP}\n"), String::new()) + } else if request.operation == "GitManager.remoteBranchDeleteCheck.trackingRef" { + let found = !self.tracking_tip.is_empty(); + (i32::from(!found), self.tracking_tip.clone(), String::new()) + } else if let (Some(stdout), true) = ( + &self.ls_remote, + arguments(&request).iter().any(|arg| arg == "ls-remote"), + ) { + (0, stdout.clone(), String::new()) } else if is_network(&request) { (128, String::new(), self.stderr.clone()) } else { @@ -152,7 +190,8 @@ fn eligible_requests() -> Vec<(GitManagerOperationRequest, &'static str, &'stati "_tag": "branch-delete", "name": "topic", "force": false, "deleteRemote": true })), "push", - "remote-branch-delete", + // The remote check failed before the local delete, so the whole delete resumes. + "branch-delete", ), ] } @@ -204,14 +243,146 @@ async fn each_eligible_operation_reports_sign_in_required_once_without_retrying( assert_eq!(sign_in.resume["expectedDestination"], DESTINATION); assert_eq!(runner.network_spawns(), 1, "{operation}: no retry"); if matches!(request, GitManagerOperationRequest::BranchDelete { .. }) { - assert_eq!(sign_in.resume["remote"], "origin"); - assert_eq!(sign_in.resume["branch"], "topic"); + assert_eq!(sign_in.resume["name"], "topic"); + assert_eq!(sign_in.resume["deleteRemote"], true); + assert_eq!(sign_in.resume["force"], false); + // The approved target is frozen beside the address (#397 round 3). + assert_eq!(sign_in.resume["expectedTip"], TIP); + assert_eq!(sign_in.resume["expectedRemote"], "origin"); + assert_eq!(sign_in.resume["expectedRemoteBranch"], "topic"); } // The resume request decodes as an ordinary request. serde_json::from_value::(sign_in.resume).expect("resume"); } } +/// #397: a remote delete reads the remote with `ls-remote` before it pushes. A sign-in that +/// refusal needs is offered from that read, and nothing is deleted locally or remotely. +#[tokio::test] +async fn a_remote_delete_offers_sign_in_from_its_ls_remote_check() { + for request in [ + request(json!({"_tag": "remote-branch-delete", "remote": "origin", "branch": "topic"})), + request(json!({ + "_tag": "branch-delete", "name": "topic", "force": false, "deleteRemote": true + })), + ] { + let runner = RemoteRunner::new(DESTINATION, GCM_STDERR); + let error = run(&runner, &request, CredentialPrompt::OfferSignIn) + .await + .expect_err("GCM refused"); + let operation = request.operation(); + assert_eq!(error.code, "sign-in-required", "{operation}"); + let spawned = runner + .requests + .lock() + .expect("requests") + .iter() + .map(arguments) + .collect::>(); + let network = spawned + .iter() + .filter(|args| { + args.iter() + .any(|arg| matches!(arg.as_str(), "ls-remote" | "push")) + }) + .collect::>(); + assert_eq!(network.len(), 1, "{operation}: {spawned:?}"); + assert!( + network[0].iter().any(|arg| arg == "ls-remote"), + "{operation}" + ); + assert!( + !spawned + .iter() + .any(|args| args.iter().any(|arg| arg == "-d" || arg == "-D")), + "{operation}: the local branch is not deleted before the check passes" + ); + + // Without an offer the check keeps Git's own classification (#397 review finding 9). + let runner = RemoteRunner::new(DESTINATION, GCM_STDERR); + let error = run(&runner, &request, CredentialPrompt::Never) + .await + .expect_err("GCM refused"); + assert_eq!(error.code, "authentication", "{operation}"); + } +} + +const TIP: &str = "1111111111111111111111111111111111111111"; + +fn advertised(head: &str, topic_tip: &str) -> String { + format!("ref: refs/heads/{head}\tHEAD\n{TIP}\tHEAD\n{topic_tip}\trefs/heads/topic\n") +} + +/// #397 round 2 (ruling A): once the remote check passed and the local branch is deleted, a +/// sign-in the push needs resumes the remote delete only, frozen to the approved destination. +#[tokio::test] +async fn a_delete_whose_push_needs_sign_in_resumes_the_remote_delete_only() { + let runner = RemoteRunner::checked(DESTINATION, GCM_STDERR, Some(&advertised("main", TIP)), ""); + let request = request(json!({ + "_tag": "branch-delete", "name": "topic", "force": false, "deleteRemote": true + })); + let error = run(&runner, &request, CredentialPrompt::OfferSignIn) + .await + .expect_err("GCM refused the push"); + + assert_eq!(error.code, "sign-in-required"); + let resume = error.sign_in.expect("offer").resume; + assert_eq!(resume["_tag"], "remote-branch-delete"); + assert_eq!(resume["remote"], "origin"); + assert_eq!(resume["branch"], "topic"); + assert_eq!(resume["expectedDestination"], DESTINATION); + let spawned = runner.requests.lock().expect("requests").clone(); + assert!( + spawned + .iter() + .any(|request| arguments(request).iter().any(|arg| arg == "-d")), + "the local branch was deleted before the push" + ); +} + +/// #397 round 2 (Antigravity 11): a resumed remote delete checks the remote again, and refuses +/// a branch that became the default or moved since the sign-in was offered. +#[tokio::test] +async fn a_resumed_remote_delete_checks_the_remote_again() { + let resumed = |tag: &str| { + let mut value = if tag == "branch-delete" { + json!({ + "_tag": tag, "name": "topic", "force": true, "deleteRemote": true, + "expectedTip": TIP, "expectedRemote": "origin", "expectedRemoteBranch": "topic" + }) + } else { + json!({"_tag": tag, "remote": "origin", "branch": "topic"}) + }; + value["expectedDestination"] = json!(DESTINATION); + request(value) + }; + for tag in ["remote-branch-delete", "branch-delete"] { + for (ls_remote, tracking, code) in [ + (advertised("topic", TIP), "", "default-branch"), + ( + advertised("main", TIP), + "2222222222222222222222222222222222222222", + "remote-branch-changed", + ), + ] { + let runner = RemoteRunner::checked(DESTINATION, GCM_STDERR, Some(&ls_remote), tracking); + let error = run(&runner, &resumed(tag), CredentialPrompt::Never) + .await + .expect_err("the check refuses"); + assert_eq!(error.code, code, "{tag}"); + let spawned = runner.requests.lock().expect("requests").clone(); + assert!( + !spawned.iter().any(|request| { + arguments(request) + .iter() + .any(|arg| matches!(arg.as_str(), "push" | "-d" | "-D")) + }), + "{tag} {code}: nothing is deleted" + ); + } + } +} + #[tokio::test] async fn failures_without_an_offerable_refusal_stay_authentication_errors() { let refusal = "fatal: Cannot prompt because user interactivity has been disabled."; diff --git a/apps/server/src/git/manager/refs.rs b/apps/server/src/git/manager/refs.rs index 7007867338..8976a5ac78 100644 --- a/apps/server/src/git/manager/refs.rs +++ b/apps/server/src/git/manager/refs.rs @@ -188,6 +188,8 @@ struct RawRef { upstream: Option, worktree_path: Option, current: bool, + /// The target of a symbolic ref, such as `refs/remotes/origin/HEAD`. + symref: Option, } pub async fn build_refs_snapshot( @@ -297,6 +299,31 @@ pub async fn build_refs_snapshot( .map(str::to_owned) .collect::>(); + // A symbolic `/HEAD` is not a branch row, even one a removed remote left behind; a + // branch such as `origin/release/HEAD` is one (#407). Only a configured remote's own + // `/HEAD` names that remote's default branch (#397). + let remote_heads = raw_refs + .iter() + .filter(|reference| { + reference.kind == RawRefKind::RemoteBranch + && reference.symref.is_some() + && reference.name.ends_with("/HEAD") + }) + .collect::>(); + let remote_defaults = remote_heads + .iter() + .filter(|reference| { + reference + .name + .strip_suffix("/HEAD") + .is_some_and(|remote| remote_names.iter().any(|known| known == remote)) + }) + .filter_map(|reference| reference.symref.clone()) + .collect::>(); + let remote_heads = remote_heads + .into_iter() + .map(|reference| reference.name.clone()) + .collect::>(); let mut local_branches = Vec::new(); let mut remote_branches = Vec::new(); let mut tags = Vec::new(); @@ -312,8 +339,11 @@ pub async fn build_refs_snapshot( if !is_tag && !is_remote && reference.worktree_path.is_none() { reference.worktree_path = worktree_occupancy.get(&reference.name).cloned(); } - let is_default = - !is_tag && !is_remote && default_branch.as_deref() == Some(reference.name.as_str()); + let is_default = if is_remote { + remote_defaults.contains(&reference.name) + } else { + !is_tag && default_branch.as_deref() == Some(reference.name.as_str()) + }; let mut entry = GitManagerRefEntry { name: reference.name, tip_sha: reference.tip_sha, @@ -342,7 +372,7 @@ pub async fn build_refs_snapshot( if is_tag { tags.push(entry); } else if is_remote { - if !entry.name.ends_with("/HEAD") { + if !remote_heads.contains(&entry.name) { remote_branches.push(entry); } } else { @@ -385,7 +415,7 @@ fn parse_refs(output: &str) -> Result, GitManagerRefsError> { .lines() .map(|line| { let fields = line.split('\t').collect::>(); - let [name, tip_sha, upstream, worktree_path, head] = fields.as_slice() else { + let [name, tip_sha, upstream, worktree_path, head, symref] = fields.as_slice() else { return Err(GitManagerRefsError::MalformedRefs); }; let (kind, name) = parse_ref_name(name).ok_or(GitManagerRefsError::MalformedRefs)?; @@ -400,6 +430,7 @@ fn parse_refs(output: &str) -> Result, GitManagerRefsError> { worktree_path: (!worktree_path.is_empty()) .then(|| display_path(Path::new(worktree_path))), current: head.trim() == "*", + symref: (!symref.is_empty()).then(|| short_ref_name(symref).to_owned()), }) }) .collect() @@ -764,6 +795,125 @@ mod tests { assert_eq!(remote_names, ["origin/main"]); } + /// #397: each remote's `HEAD` marks that remote's default branch, and only that one. + #[tokio::test] + async fn each_remote_head_marks_its_own_default_branch() { + let repository = repository_with_one_commit(); + let path = repository.path(); + let url = path.to_str().expect("fixture path should be UTF-8"); + let head = String::from_utf8(git_output(path, &["rev-parse", "HEAD"]).stdout) + .expect("UTF-8 HEAD") + .trim() + .to_owned(); + for remote in ["origin", "upstream", "fork"] { + git(path, &["remote", "add", remote, url]); + } + for name in [ + "origin/main", + "origin/feature", + "upstream/main", + "upstream/trunk", + "fork/main", + ] { + git( + path, + &["update-ref", &format!("refs/remotes/{name}"), &head], + ); + } + for (remote, target) in [("origin", "main"), ("upstream", "trunk")] { + git( + path, + &[ + "symbolic-ref", + &format!("refs/remotes/{remote}/HEAD"), + &format!("refs/remotes/{remote}/{target}"), + ], + ); + } + + let snapshot = snapshot(&repository).await; + let remote_defaults = snapshot + .remote_branches + .iter() + .map(|branch| (branch.name.as_str(), branch.is_default)) + .collect::>(); + let local_defaults = snapshot + .local_branches + .iter() + .map(|branch| (branch.name.as_str(), branch.is_default)) + .collect::>(); + + assert_eq!( + remote_defaults, + [ + ("fork/main", false), + ("origin/feature", false), + ("origin/main", true), + ("upstream/main", false), + ("upstream/trunk", true), + ] + ); + assert_eq!(local_defaults, [("main", true)]); + } + + /// #407: only a remote's own symbolic `HEAD` is hidden; a branch named `release/HEAD` is + /// listed. + #[tokio::test] + async fn a_remote_branch_named_with_a_head_suffix_is_listed() { + let repository = repository_with_one_commit(); + let path = repository.path(); + let url = path.to_str().expect("fixture path should be UTF-8"); + git(path, &["remote", "add", "origin", url]); + git(path, &["update-ref", "refs/remotes/origin/main", "HEAD"]); + git( + path, + &["update-ref", "refs/remotes/origin/release/HEAD", "HEAD"], + ); + git( + path, + &[ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ], + ); + + let snapshot = snapshot(&repository).await; + let remote_names = snapshot + .remote_branches + .iter() + .map(|branch| branch.name.as_str()) + .collect::>(); + + assert_eq!(remote_names, ["origin/main", "origin/release/HEAD"]); + } + + /// #397 round 2 (Antigravity 9): a symbolic `/HEAD` left behind by a removed remote is + /// not a branch row either, and marks no default. + #[tokio::test] + async fn a_removed_remotes_symbolic_head_is_not_listed() { + let repository = repository_with_one_commit(); + let path = repository.path(); + git(path, &["update-ref", "refs/remotes/old/main", "HEAD"]); + git( + path, + &[ + "symbolic-ref", + "refs/remotes/old/HEAD", + "refs/remotes/old/main", + ], + ); + + let snapshot = snapshot(&repository).await; + let remote_rows = snapshot + .remote_branches + .iter() + .map(|branch| (branch.name.as_str(), branch.is_default)) + .collect::>(); + + assert_eq!(remote_rows, [("old/main", false)]); + } + #[tokio::test] async fn missing_remote_tracking_ref_does_not_make_the_snapshot_unavailable() { let repository = repository_with_one_commit(); diff --git a/apps/server/src/git/repository.rs b/apps/server/src/git/repository.rs index a47588c584..c8e10fa14b 100644 --- a/apps/server/src/git/repository.rs +++ b/apps/server/src/git/repository.rs @@ -814,7 +814,7 @@ impl GitRepository { cwd, &strings(&[ "for-each-ref", - "--format=%(refname)%09%(objectname)%09%(upstream)%09%(worktreepath)%09%(HEAD)", + "--format=%(refname)%09%(objectname)%09%(upstream)%09%(worktreepath)%09%(HEAD)%09%(symref)", "refs/heads", "refs/remotes", "refs/tags", @@ -4562,13 +4562,50 @@ impl GitRepository { cwd: &Path, remote: &str, name: &str, + expected_oid: &str, cancellation: &CancellationToken, ) -> Result { self.for_network_transfer() .execute( "GitManager.remoteBranchDelete", cwd, - &["push".into(), remote.into(), format!(":{name}")], + // A qualified destination, since an unqualified one can resolve to a same-named + // tag, and a lease on the checked commit, so a branch that moved is kept. + &[ + "push".into(), + format!("--force-with-lease=refs/heads/{name}:{expected_oid}"), + remote.into(), + format!(":refs/heads/{name}"), + ], + true, + cancellation, + ) + .await + } + + /// Reads the remote's `HEAD` target and one branch's commit with + /// `git ls-remote --symref HEAD refs/heads/`, before a remote branch delete. + pub(crate) async fn git_manager_remote_heads( + &self, + cwd: &Path, + remote: &str, + name: &str, + cancellation: &CancellationToken, + ) -> Result { + self.for_network_transfer() + .execute( + "GitManager.remoteBranchDeleteCheck", + cwd, + // Protocol v2 advertises the target of a symbolic branch, which v0 omits. + &[ + "-c".into(), + "protocol.version=2".into(), + "ls-remote".into(), + "--symref".into(), + remote.into(), + "HEAD".into(), + format!("refs/heads/{name}"), + ], true, cancellation, ) @@ -9695,6 +9732,10 @@ mod tests { "GitManager.remoteBranchDelete".into(), process_output("remote deleted\n"), ), + ( + "GitManager.remoteBranchDeleteCheck".into(), + process_output("ref: refs/heads/main\tHEAD\n"), + ), ]), requests: Mutex::new(Vec::new()), }); @@ -9709,10 +9750,20 @@ mod tests { Path::new("/repo"), "origin", "topic", + "abc123", &CancellationToken::new(), ) .await .expect("remote delete succeeds"); + repository + .git_manager_remote_heads( + Path::new("/repo"), + "origin", + "topic", + &CancellationToken::new(), + ) + .await + .expect("remote check succeeds"); let requests = runner.requests(); assert_eq!( @@ -9723,7 +9774,30 @@ mod tests { .collect::>() ); assert_default_budget(&requests[0]); - assert_network_transfer(&requests[1], &["push", "origin", ":topic"]); + // A qualified destination never resolves to a same-named tag (#403). + // The checked commit rides along as a lease, so a branch that moved is kept. + assert_network_transfer( + &requests[1], + &[ + "push", + "--force-with-lease=refs/heads/topic:abc123", + "origin", + ":refs/heads/topic", + ], + ); + assert_network_transfer( + &requests[2], + // Protocol v2 advertises a symbolic branch's target (#397 round 2, Codex 4). + &[ + "-c", + "protocol.version=2", + "ls-remote", + "--symref", + "origin", + "HEAD", + "refs/heads/topic", + ], + ); } #[tokio::test] diff --git a/apps/server/src/hermetic_guard.rs b/apps/server/src/hermetic_guard.rs index 62383a767d..2d29dae3cf 100644 --- a/apps/server/src/hermetic_guard.rs +++ b/apps/server/src/hermetic_guard.rs @@ -17,6 +17,7 @@ const GUARDED_PROGRAMS: &[&str] = &[ "cursor-agent", "agent", "grok", + "agy", "gh", "glab", "az", @@ -391,7 +392,7 @@ mod tests { } // Every possible built-in is a disposable tripwire. Even a broken guard // could not execute a developer-installed provider through this PATH. - for name in ["codex", "claude", "cursor-agent", "grok", "opencode"] { + for name in ["codex", "claude", "cursor-agent", "grok", "opencode", "agy"] { let name = if cfg!(windows) { format!("{name}.cmd") } else { @@ -660,6 +661,11 @@ mod tests { assert!(!String::from_utf8_lossy(&output.stderr).contains("hermetic-test-guard: refused")); } + #[test] + fn hermetic_guard_refuses_the_antigravity_cli() { + assert!(super::is_guarded_program(Path::new("agy"))); + } + #[cfg(windows)] #[test] fn windows_explicit_extensionless_provider_uses_checked_launch_extensions() { diff --git a/apps/server/src/mcp/outcome.rs b/apps/server/src/mcp/outcome.rs index 7c46f7d085..03eb13ff87 100644 --- a/apps/server/src/mcp/outcome.rs +++ b/apps/server/src/mcp/outcome.rs @@ -199,6 +199,21 @@ impl Owned { .map_err(|error| rpc_failure(&error)) } + /// [`Self::invoke`] for a read that settles what interrupted work already did, such as the + /// refs after a cut branch delete: the off switch, read-only and a revocation do not stop + /// it, so the recorded outcome keeps what is known; shutdown still does. + pub(crate) async fn invoke_settling(&self, tag: &str, payload: Value) -> Result { + self.registry + .invoke_local( + tag, + payload, + self.context.clone(), + self.control.shutdown_token(), + ) + .await + .map_err(|error| rpc_failure(&error)) + } + /// Runs stream method `tag` to its terminal event (C3). An early end is a failure tagged /// `McpStreamEndedError`, which [`ToolCall::recorded`] records as `unknown`. pub(crate) async fn invoke_stream( diff --git a/apps/server/src/mcp/tools/git.rs b/apps/server/src/mcp/tools/git.rs index c2d7bbb66e..3ae0af675a 100644 --- a/apps/server/src/mcp/tools/git.rs +++ b/apps/server/src/mcp/tools/git.rs @@ -586,6 +586,26 @@ fn upstream(refs: &Value, branch: &str) -> Result, Valu .map(|remote| (remote.to_owned(), upstream[remote.len() + 1..].to_owned()))) } +/// Whether two remotes both prefix `branch`'s upstream (`team` and `team/fork`): its target is +/// then unknown here, and the server refuses such a delete before anything is deleted. +fn upstream_is_ambiguous(refs: &Value, branch: &str) -> bool { + let upstream = refs["localBranches"] + .as_array() + .and_then(|branches| { + branches + .iter() + .find(|entry| entry["name"].as_str() == Some(branch)) + }) + .and_then(|entry| entry["upstream"].as_str()); + upstream.is_some_and(|upstream| { + remotes(refs) + .into_iter() + .filter(|remote| upstream.starts_with(&format!("{remote}/"))) + .count() + > 1 + }) +} + /// The remote to use: the one named, which the repository must have, else the upstream's, /// else `origin`, else the only remote. A remote chosen for the agent passes the same shape /// check as a named one: Git accepts a configured remote such as `--all`, which a command @@ -943,100 +963,155 @@ async fn delete_branch(call: &ToolCall<'_>) -> ToolResult { .recorded("git_delete_branch", &payload, move |owned| async move { let (cwd, project_id) = folder(&owned, &thread).await?; // The upstream is resolved before anything is deleted: afterwards it is gone. + // `None` inside when two remotes could own the upstream: the server then refuses. let target = if delete_remote { let refs = refs(&owned, &cwd).await?; - Some(upstream(&refs, &name)?.ok_or_else(|| { + let resolved = upstream(&refs, &name)?.ok_or_else(|| { let mut refused = typed_tool_failure( "GitOperationFailedError", "Remote deletion is refused because this branch has no upstream; nothing was deleted.", ); refused["structuredContent"]["error"]["code"] = "no-upstream".into(); refused - })?) + })?; + Some((!upstream_is_ambiguous(&refs, &name)).then_some(resolved)) } else { None }; - operate( + // One operation: the server checks the remote before it deletes the local branch, and + // pushes the remote delete after it (#406). + let deleted = operate( &owned, json!({ "_tag": "branch-delete", "cwd": cwd, "projectId": project_id, - "name": name, "force": force, "deleteRemote": false, + "name": name, "force": force, "deleteRemote": target.is_some(), }), ) - .await?; + .await; + // Read even when the off switch cut the delete: what it already did is recorded. + let after = owned + .invoke_settling("gitManager.getRefs", json!({ "cwd": cwd })) + .await + .ok(); + // `None` when the refs cannot be read: whether the local branch is gone is unknown. + let local_gone = after.as_ref().map(|refs| { + !refs["localBranches"].as_array().is_some_and(|branches| { + branches + .iter() + .any(|entry| entry["name"].as_str() == Some(name.as_str())) + }) + }); // A label must not name the branch this call deleted: it takes the folder's own. - if let Ok(thread_target) = owned.target(&thread).await + if local_gone == Some(true) + && let Ok(thread_target) = owned.target(&thread).await && thread_target.thread.branch.as_deref() == Some(name.as_str()) - && let Ok(refs) = refs(&owned, &cwd).await - && let Some(head) = refs["headRef"].as_str() + && let Some(head) = after.as_ref().and_then(|refs| refs["headRef"].as_str()) { follow_checkout(&owned, &thread, &cwd, &[head]).await; } - let Some((remote, remote_branch)) = target else { + let Some(target) = target else { + deleted?; return Ok(json!({ "branch": name, "local": "deleted", "remote": "not-requested" })); }; - let deleted = operate( - &owned, - json!({ - "_tag": "remote-branch-delete", "cwd": cwd, "projectId": project_id, - "remote": remote, "branch": remote_branch, - }), - ) - .await; match deleted { Ok(_) => Ok(json!({ "branch": name, "local": "deleted", "remote": "deleted" })), - // Whether a stream that stopped reporting reached the remote is unknown, and is - // recorded so, with the known local deletion and the remote target. + // Nothing was deleted: the remote check or the local delete refused it. + Err(failure) if local_gone == Some(false) => Err(failure), + // Unreadable refs leave both deletions unknown; a stream that stopped reporting + // leaves the remote one unknown. Either is recorded so, with the remote target. + Err(failure) if local_gone.is_none() => Err(outcome_unknown(partial( + target.as_ref(), + &failure, + Outcome::LocalUnknown, + ))), Err(failure) if failure["structuredContent"]["error"]["_tag"] == crate::rpc::STREAM_ENDED_TAG => { Err(outcome_unknown(partial( - &remote, - &remote_branch, + target.as_ref(), &failure, - true, + Outcome::RemoteUnknown, ))) } - Err(failure) => Err(partial(&remote, &remote_branch, &failure, false)), + Err(failure) => Err(partial( + target.as_ref(), + &failure, + Outcome::RemoteFailed, + )), } }) .await; finish(call, &thread_id, result).await } -/// The local branch is gone and the remote one is not, or may not be (`unknown`, when the -/// remote step stopped reporting): the truth, with the call that finishes it. A keyed retry -/// replays it. -fn partial(remote: &str, remote_branch: &str, failure: &Value, unknown: bool) -> Value { +/// What a failed delete with its remote is known to have done. +#[derive(Clone, Copy, PartialEq)] +enum Outcome { + /// The local branch is gone and the remote push failed. + RemoteFailed, + /// The local branch is gone; the remote step stopped before it reported. + RemoteUnknown, + /// The refs could not be read afterwards, so neither deletion is known. + LocalUnknown, +} + +/// A delete with its remote that did not fully succeed: the truth, with the call that finishes +/// it. A keyed retry replays it. +fn partial(target: Option<&(String, String)>, failure: &Value, outcome: Outcome) -> Value { let error = &failure["structuredContent"]["error"]; let reason = error["message"].as_str().unwrap_or("the remote refused it"); - let mut partial = typed_tool_failure( - PARTIAL_TAG, - &if unknown { - format!( - "The local branch was deleted, but whether the remote branch was deleted is unknown: {reason} Run git_fetch; if {remote}/{remote_branch} is still listed, call git_delete_remote_branch with this remote and branch to finish." - ) - } else { - format!( - "The local branch was deleted, but deleting the remote branch failed: {reason} Call git_delete_remote_branch with this remote and branch to finish." - ) - }, - ); + let what = match outcome { + Outcome::LocalUnknown => format!( + "The delete failed and the branches could not be read afterwards, so whether the local and the remote branch were deleted is unknown: {reason}" + ), + Outcome::RemoteUnknown => format!( + "The local branch was deleted, but whether the remote branch was deleted is unknown: {reason}" + ), + Outcome::RemoteFailed => { + format!("The local branch was deleted, but deleting the remote branch failed: {reason}") + } + }; + // Without a target the server resolved the same way, no destructive call is suggested. + let next = match (target, outcome) { + (None, _) => " The remote branch could not be determined, so no call is suggested; check it with git_status and git_fetch.".to_owned(), + (Some((remote, branch)), Outcome::RemoteFailed) => format!( + " Call git_delete_remote_branch with remote {remote} and branch {branch} to finish." + ), + (Some((remote, branch)), _) => format!( + " Run git_status and git_fetch; if {remote}/{branch} is still listed, call git_delete_remote_branch with this remote and branch to finish." + ), + }; + let mut partial = typed_tool_failure(PARTIAL_TAG, &format!("{what}{next}")); let fields = &mut partial["structuredContent"]["error"]; - fields["local"] = "deleted".into(); - fields["remote"] = if unknown { "unknown" } else { "failed" }.into(); - fields["remoteName"] = remote.into(); - fields["remoteBranch"] = remote_branch.into(); + fields["local"] = if outcome == Outcome::LocalUnknown { + "unknown" + } else { + "deleted" + } + .into(); + fields["remote"] = if outcome == Outcome::RemoteFailed { + "failed" + } else { + "unknown" + } + .into(); fields["reason"] = error .get("code") .or_else(|| error.get("reason")) .cloned() .unwrap_or(Value::Null); - fields["recovery"] = json!({ - "tool": "git_delete_remote_branch", - "arguments": { "remote": remote, "branch": remote_branch }, + let (remote, branch) = target.map_or((Value::Null, Value::Null), |(remote, branch)| { + (remote.as_str().into(), branch.as_str().into()) + }); + fields["recovery"] = target.map_or(Value::Null, |_| { + json!({ + "tool": "git_delete_remote_branch", + "arguments": { "remote": remote, "branch": branch }, + }) }); + fields["remoteName"] = remote; + fields["remoteBranch"] = branch; partial } diff --git a/apps/server/src/orchestration/engine.rs b/apps/server/src/orchestration/engine.rs index e5808f5a5d..f842c7db07 100644 --- a/apps/server/src/orchestration/engine.rs +++ b/apps/server/src/orchestration/engine.rs @@ -1007,6 +1007,9 @@ pub struct DispatchResult { pub thread_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub disposition: Option, + /// The engine judged this interrupt stale in its commit, so it must reach no provider. + #[serde(skip)] + pub stale_interrupt: bool, } #[derive(Clone, Debug, Default)] @@ -2038,6 +2041,75 @@ struct RestoreHolds { admitted: HashMap, } +/// What `LaunchStops::stop` found for the thread. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LaunchStopResult { + NoLaunch, + Stopped, + /// A launch for another message is in flight; it was left running. + OtherMessage, +} + +/// How each launching thread's start is ended from outside the provider supervisor's queue. +#[derive(Clone, Default)] +pub(crate) struct LaunchStops(Arc>>); + +impl LaunchStops { + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Stops the thread's launch that has not kept its session yet, whether its start has + /// returned or not. A stop for a dismissed message (`target`) ends only the launch for + /// that message, never the launch of another message the worker claimed; a plain stop ends + /// any launch. + pub(crate) fn stop(&self, thread_id: &str, target: Option<&str>) -> LaunchStopResult { + let stops = self.lock(); + match stops.get(thread_id) { + None => LaunchStopResult::NoLaunch, + Some(stop) if target.is_none() || stop.message_id.as_deref() == target => { + stop.token.cancel(); + LaunchStopResult::Stopped + } + Some(_) => LaunchStopResult::OtherMessage, + } + } + + /// Stops every launch in flight because the server shuts down: nothing was sent. + pub(crate) fn stop_all_for_shutdown(&self) { + for stop in self.lock().values() { + stop.shutdown.store(true, Ordering::SeqCst); + stop.token.cancel(); + } + } +} + +/// Ends a provider session launch until it keeps its session: during its start, and after the +/// start returned while it applies options and publishes the session. The supervisor awaits every launch in its one queue, so a +/// stop of the thread, or the server's shutdown, reaches the launch here instead of waiting +/// behind it. A targeted stop matches only the launch for its own message. +#[derive(Clone, Default)] +pub(crate) struct LaunchStop { + token: CancellationToken, + shutdown: Arc, + /// The message whose delivery this launch is for; `None` for a rewind, compaction or restart. + message_id: Option, +} + +impl LaunchStop { + /// Resolves once the launch is stopped. + pub(crate) async fn stopped(&self) { + self.token.cancelled().await; + } + + /// Whether the server's shutdown, not the user, stopped the launch. + pub(crate) fn by_shutdown(&self) -> bool { + self.shutdown.load(Ordering::SeqCst) + } +} + fn decrement(counts: &mut HashMap, thread_id: &str) { if let Some(count) = counts.get_mut(thread_id) { *count -= 1; @@ -2051,12 +2123,23 @@ fn decrement(counts: &mut HashMap, thread_id: &str) { pub(crate) struct SessionLaunch { engine: OrchestrationEngine, thread_id: String, + stop: LaunchStop, +} + +impl SessionLaunch { + /// Ends this launch's start when the thread is stopped or the server shuts down. + pub(crate) fn stop(&self) -> &LaunchStop { + &self.stop + } } impl Drop for SessionLaunch { fn drop(&mut self) { let mut holds = self.engine.lock_restore_holds(); decrement(&mut holds.launching, &self.thread_id); + if !holds.launching.contains_key(&self.thread_id) { + self.engine.launch_stops.lock().remove(&self.thread_id); + } } } /// Why a provider session cannot launch while another chat restores files in its checkout. @@ -2295,6 +2378,7 @@ pub struct OrchestrationEngine { thread_turns: ThreadTurnFence, checkout_turns: CheckoutTurnFence, restore_holds: Arc>, + launch_stops: LaunchStops, compaction_waiters: CompactionWaiters, ask_recovery_holds: AskRecoveryHolds, checkpoint_holds: CheckpointHolds, @@ -2395,6 +2479,7 @@ impl OrchestrationEngine { thread_turns: ThreadTurnFence::default(), checkout_turns: CheckoutTurnFence::default(), restore_holds: Arc::default(), + launch_stops: LaunchStops::default(), compaction_waiters: CompactionWaiters::default(), ask_recovery_holds: AskRecoveryHolds::default(), checkpoint_holds: CheckpointHolds::default(), @@ -2546,6 +2631,7 @@ impl OrchestrationEngine { thread_id: Some(thread_id), project_id: None, disposition: Some(disposition), + stale_interrupt: false, })) } @@ -3098,18 +3184,33 @@ impl OrchestrationEngine { /// Registers a provider session launch of the thread, or refuses it while a file restore of /// another chat in its checkout holds the thread. See `CheckoutRestore::hold_threads`. - pub(crate) fn begin_session_launch(&self, thread_id: &str) -> Result { + /// `message_id` names the message whose delivery needs this launch, if any. + pub(crate) fn begin_session_launch( + &self, + thread_id: &str, + message_id: Option<&str>, + ) -> Result { let mut holds = self.lock_restore_holds(); if holds.held.contains_key(thread_id) { return Err(RESTORING_FILES_DETAIL.to_owned()); } *holds.launching.entry(thread_id.to_owned()).or_default() += 1; + let mut stops = self.launch_stops.lock(); + let stop = stops.entry(thread_id.to_owned()).or_default(); + stop.message_id = message_id.map(str::to_owned); + let stop = stop.clone(); Ok(SessionLaunch { engine: self.clone(), thread_id: thread_id.to_owned(), + stop, }) } + /// The registry that stops this engine's provider launches that have not kept their session. + pub(crate) fn launch_stops(&self) -> LaunchStops { + self.launch_stops.clone() + } + fn lock_restore_holds(&self) -> std::sync::MutexGuard<'_, RestoreHolds> { self.restore_holds .lock() @@ -3943,6 +4044,7 @@ async fn process_envelope( }), project_id, disposition: replay_adoption.map(|result| result.1), + stale_interrupt: false, }, accepted_new: false, }); @@ -4003,6 +4105,7 @@ async fn process_envelope( thread_id: None, project_id: None, disposition: None, + stale_interrupt: false, }, accepted_new: true, }); @@ -4075,6 +4178,7 @@ async fn process_envelope( thread_id: canonical_default_thread_id(model, &existing_project_id), project_id: Some(existing_project_id), disposition: None, + stale_interrupt: false, }, accepted_new: true, }); @@ -4223,6 +4327,7 @@ async fn process_envelope( }), project_id, disposition: adoption_result.map(|result| result.1), + stale_interrupt: persisted.stale_interrupt, }, accepted_new: true, }) @@ -6398,6 +6503,7 @@ fn required_command_string( struct PersistCommandOutcome { committed: VecDeque, result_sequence: i64, + stale_interrupt: bool, } const STALE_QUEUED_DELIVERY: &str = "Queued delivery changed before promotion or steering."; @@ -6456,6 +6562,16 @@ async fn persist_command( )), _ => None, }; + // A Stop naming a turn other than the active one (a late Stop for a finished turn) is stale: + // it holds no queue, expires no request and leaves a running compaction alone. + let named_interrupt = match command { + OrchestrationCommand::ThreadTurnInterrupt { + thread_id, + turn_id: Some(turn_id), + .. + } => Some((thread_id.clone(), turn_id.clone())), + _ => None, + }; let hold = match command { OrchestrationCommand::ThreadTurnInterrupt { thread_id, @@ -6518,6 +6634,17 @@ async fn persist_command( .call(move |connection| { let transaction = connection.transaction()?; let mut hold = hold; + let mut expiry = expiry; + let mut compaction_step = compaction_step; + let mut stale_interrupt = false; + if let Some((thread_id, named)) = &named_interrupt + && interrupt_is_stale(Some(named), active_turn_of_tx(&transaction, thread_id)?.as_deref()) + { + stale_interrupt = true; + hold = None; + expiry = None; + compaction_step = None; + } let mut copy_receipts = Vec::new(); if let Some(step) = compaction_step { let applied = apply_compaction_step_tx( @@ -6733,6 +6860,7 @@ async fn persist_command( Ok(Ok(PersistCommandOutcome { committed, result_sequence, + stale_interrupt, })) }) .await @@ -8174,6 +8302,26 @@ fn request_expiry_summary(kind: &str) -> &'static str { } } +/// Whether a Stop naming `named` is stale: the session's active turn is a different one. Any +/// other Stop ends the running turn, and every request still open on the thread with it. +fn interrupt_is_stale(named: Option<&str>, active: Option<&str>) -> bool { + matches!((named, active), (Some(named), Some(active)) if named != active) +} + +fn active_turn_of_tx( + transaction: &Transaction<'_>, + thread_id: &str, +) -> Result, rusqlite::Error> { + Ok(transaction + .query_row( + "SELECT active_turn_id FROM projection_thread_sessions WHERE thread_id = ?", + [thread_id], + |row| row.get::<_, Option>(0), + ) + .optional()? + .flatten()) +} + /// Activities expiring every request still open on `thread_id` when `cause` proves nobody can /// answer them (#187); without this they read Pending Approval or Awaiting Input forever. A /// provider that asks one again reopens it. diff --git a/apps/server/src/orchestration/engine/agent_status_tests.rs b/apps/server/src/orchestration/engine/agent_status_tests.rs index 163867b061..0799185d65 100644 --- a/apps/server/src/orchestration/engine/agent_status_tests.rs +++ b/apps/server/src/orchestration/engine/agent_status_tests.rs @@ -789,6 +789,160 @@ async fn stopping_a_turn_expires_its_requests() { assert_eq!(open_requests(&engine, &thread_id).await, (0, 0)); } +/// Runs turn A to `ready`, then turn B to an open approval, a question, a request with no turn +/// of its own and one recorded under a child agent's turn, as a provider reports them. +async fn finished_turn_then_open_requests(engine: &OrchestrationEngine, thread_id: &str) { + let set = |status: &str, turn: Value| { + command(json!({ + "type":"thread.session.set", + "commandId":format!("provider-session:{}", uuid::Uuid::new_v4()), + "threadId":thread_id, "createdAt":AT, + "session":{ + "threadId":thread_id, "status":status, "providerName":"codex", + "runtimeMode":"approval-required", "activeTurnId":turn, + "lastError":null, "updatedAt":AT + } + })) + }; + for (status, turn) in [ + ("running", json!("turn-a")), + ("ready", Value::Null), + ("running", json!("turn-b")), + ] { + engine.dispatch(set(status, turn)).await.expect("session"); + } + for (kind, payload, turn) in [ + ( + "approval.requested", + json!({"requestId":"b-approval","requestKind":"command"}), + json!("turn-b"), + ), + ( + "user-input.requested", + json!({"requestId":"b-question","questions":[]}), + json!("turn-b"), + ), + ( + "approval.requested", + json!({"requestId":"turnless","requestKind":"command"}), + Value::Null, + ), + // A Codex child agent asks under its own turn while the parent's turn B runs. + ( + "approval.requested", + json!({"requestId":"child-approval","requestKind":"command"}), + json!("child-turn"), + ), + ] { + let id = uuid::Uuid::new_v4().to_string(); + engine + .dispatch(command(json!({ + "type":"thread.activity.append", "commandId":format!("provider:{id}"), + "threadId":thread_id, "createdAt":AT, + "activity":{ + "id":id, "tone":"approval", "kind":kind, "summary":kind, + "payload":payload, "turnId":turn, "createdAt":AT + } + }))) + .await + .expect("activity"); + } + assert_eq!(open_requests(engine, thread_id).await, (3, 1)); +} + +async fn interrupt(engine: &OrchestrationEngine, thread_id: &str, turn: Option<&str>) { + let mut value = json!({ + "type":"thread.turn.interrupt", "commandId":"stop", "threadId":thread_id, "createdAt":AT + }); + if let Some(turn) = turn { + value["turnId"] = json!(turn); + } + engine.dispatch(command(value)).await.expect("interrupt"); +} + +async fn expiry_payloads(engine: &OrchestrationEngine, thread_id: &str) -> Vec { + let thread_id = thread_id.to_owned(); + engine + .repositories() + .database() + .call(move |connection| { + let mut statement = connection.prepare( + "SELECT payload_json FROM projection_thread_activities WHERE thread_id = ? AND kind LIKE '%.expired' ORDER BY sequence", + )?; + let payloads = statement + .query_map([thread_id], |row| row.get::<_, String>(0))? + .collect::, _>>()?; + Ok(payloads) + }) + .await + .expect("expiries") + .iter() + .map(|payload| serde_json::from_str(payload).expect("payload")) + .collect() +} + +#[tokio::test] +async fn a_late_interrupt_for_a_finished_turn_keeps_the_running_turns_requests() { + // Mutation caught: a delayed Stop naming finished turn A expiring turn B's approvals, its + // child agent's included, which B's provider still waits on: the Stop is stale. + let (engine, thread_id) = engine().await; + finished_turn_then_open_requests(&engine, &thread_id).await; + interrupt(&engine, &thread_id, Some("turn-a")).await; + assert_eq!(open_requests(&engine, &thread_id).await, (3, 1)); + assert!(expiry_payloads(&engine, &thread_id).await.is_empty()); +} + +#[tokio::test] +async fn an_interrupt_naming_the_running_turn_expires_every_open_request() { + // Mutation caught: the Stop of the running turn keeping the approval its child agent asked + // under the child's own turn id, which nobody can answer once the turn ends. + let (engine, thread_id) = engine().await; + finished_turn_then_open_requests(&engine, &thread_id).await; + interrupt(&engine, &thread_id, Some("turn-b")).await; + assert_eq!(open_requests(&engine, &thread_id).await, (0, 0)); + let payloads = expiry_payloads(&engine, &thread_id).await; + assert_eq!(payloads.len(), 4); + for payload in payloads { + assert_eq!( + (&payload["reason"], &payload["sessionStatus"]), + (&json!("stopped"), &json!("interrupted")) + ); + } +} + +#[tokio::test] +async fn an_interrupt_naming_no_turn_expires_every_open_request() { + let (engine, thread_id) = engine().await; + finished_turn_then_open_requests(&engine, &thread_id).await; + // A request left open by finished turn A as well. + activity( + &engine, + &thread_id, + "approval.requested", + json!({"requestId":"a-approval","requestKind":"command"}), + ) + .await; + assert_eq!(open_requests(&engine, &thread_id).await, (4, 1)); + interrupt(&engine, &thread_id, None).await; + assert_eq!(open_requests(&engine, &thread_id).await, (0, 0)); + assert_eq!(expiry_payloads(&engine, &thread_id).await.len(), 5); +} + +#[tokio::test] +async fn a_named_interrupt_with_no_active_turn_expires_every_open_request() { + // Mutation caught: a Stop naming a turn other than the one a request was recorded under (an + // OpenCode request kept from before a resume) leaving it open when no turn is active. + let (engine, thread_id) = engine().await; + session(&engine, &thread_id, "running", AT).await; + session(&engine, &thread_id, "ready", AT).await; + // Recorded under turn-1, shown again after the resume while no turn runs. + ask_both(&engine, &thread_id).await; + assert_eq!(open_requests(&engine, &thread_id).await, (1, 1)); + interrupt(&engine, &thread_id, Some("resumed-turn")).await; + assert_eq!(open_requests(&engine, &thread_id).await, (0, 0)); + assert_eq!(expiry_payloads(&engine, &thread_id).await.len(), 2); +} + #[tokio::test] async fn a_settled_session_settling_again_or_relaunching_expires_nothing() { let (engine, thread_id) = engine().await; diff --git a/apps/server/src/process/appimage.rs b/apps/server/src/process/appimage.rs index 7e5db9e3f5..b43d5d83f6 100644 --- a/apps/server/src/process/appimage.rs +++ b/apps/server/src/process/appimage.rs @@ -59,6 +59,19 @@ pub fn isolate_appimage_environment<'a>(command: impl Into>) { let _ = command; } +/// The overrides that strip the AppImage bundle at `roots` (spellings of one AppDir) from +/// `environment`, by the rules [`isolate_appimage_environment`] applies: the launcher +/// variables, and every path entry under a root or a `.mount_` folder. For the desktop's +/// `AppRun` handoff, which drops the `APPDIR` this filter would otherwise find another bundle +/// by (#413). +#[cfg(target_os = "linux")] +pub fn appimage_bundle_overrides( + environment: &std::collections::BTreeMap, + roots: &[std::path::PathBuf], +) -> Vec<(std::ffi::OsString, Option)> { + linux::child_environment_overrides(environment, roots) +} + #[cfg(target_os = "linux")] mod linux { use super::{ChildCommand, EnvironmentInheritance}; diff --git a/apps/server/src/process/mod.rs b/apps/server/src/process/mod.rs index 253c453358..63c728b313 100644 --- a/apps/server/src/process/mod.rs +++ b/apps/server/src/process/mod.rs @@ -10,6 +10,8 @@ pub(crate) mod supervised; #[cfg(windows)] mod windows_job; +#[cfg(target_os = "linux")] +pub use appimage::appimage_bundle_overrides; pub use appimage::{ChildCommand, EnvironmentInheritance, isolate_appimage_environment}; #[cfg(windows)] diff --git a/apps/server/src/process/supervised.rs b/apps/server/src/process/supervised.rs index 0618e6fdb1..e7ef92f278 100644 --- a/apps/server/src/process/supervised.rs +++ b/apps/server/src/process/supervised.rs @@ -222,7 +222,15 @@ where deadline.unwrap_or_else(|| tokio::time::Instant::now() + execution.timeout); #[cfg(windows)] let child = { - let mut spawn = tokio::task::spawn_blocking(move || spawn_wrapped(&mut command)); + // A spawn still queued on the blocking pool when the run is cancelled never starts. + // shortcut: a cancellation that arrives while CreateProcess is already running is not + // observed until the spawn returns (the run then stops the child as usual), and a caller + // dropped meanwhile leaves the child to its job's kill-on-close; upgrade if a Windows + // caller needs cancellation to interrupt process creation. + let queued = cancellation.clone(); + let mut spawn = tokio::task::spawn_blocking(move || { + (!queued.is_cancelled()).then(|| spawn_wrapped(&mut command)) + }); match tokio::time::timeout_at(overall_deadline, &mut spawn).await { Ok(joined) => joined .map_err(|error| { @@ -230,12 +238,13 @@ where "supervised process spawn task failed: {error}" ))) })? + .ok_or(SupervisedRunError::Cancelled)? .map_err(SupervisedRunError::Spawn)?, Err(_) => { // The blocking spawn cannot be interrupted; reap whatever it // eventually produces so a late child never runs unsupervised. tokio::spawn(async move { - if let Ok(Ok(child)) = spawn.await { + if let Ok(Some(Ok(child))) = spawn.await { terminate_and_wait_owned( child, cleanup_timeout, @@ -250,10 +259,15 @@ where } } }; + // Dropping the retry loop on cancellation is safe: it holds a child only when it returns. #[cfg(not(windows))] - let child = spawn_retrying_busy_executable(&mut command, overall_deadline) - .await - .map_err(SupervisedRunError::Spawn)?; + let child = tokio::select! { + biased; + () = cancellation.cancelled() => return Err(SupervisedRunError::Cancelled), + spawned = spawn_retrying_busy_executable(&mut command, overall_deadline) => { + spawned.map_err(SupervisedRunError::Spawn)? + } + }; let mut guard = SupervisedChildGuard::arm_with(child, stop_policy, reports.clone()); let pid = guard.child().id(); observer(pid); @@ -1302,6 +1316,48 @@ mod tests { ); } + #[cfg(target_os = "linux")] + #[tokio::test] + async fn cancelling_a_held_spawn_never_starts_the_child() { + let directory = tempfile::tempdir().expect("temporary directory"); + let (path, writer) = busy_executable_fixture(directory.path()); + let cancellation = CancellationToken::new(); + let spawned = Arc::new(AtomicUsize::new(0)); + let run = tokio::spawn({ + let request = busy_executable_request(&path, Duration::from_secs(30)); + let (cancellation, spawned) = (cancellation.clone(), spawned.clone()); + async move { + run_supervised_with_spawn_observer(request, &cancellation, move |_| { + spawned.fetch_add(1, Ordering::SeqCst); + }) + .await + } + }); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + !run.is_finished(), + "the spawn is held while the script is busy" + ); + let started = std::time::Instant::now(); + cancellation.cancel(); + let error = run + .await + .expect("supervised run task") + .expect_err("a cancelled run must not succeed"); + assert!( + matches!(error, SupervisedRunError::Cancelled), + "unexpected error: {error:?}" + ); + assert!( + started.elapsed() < Duration::from_millis(500), + "cancellation must end the held spawn, not the retry budget" + ); + // Released after the cancelled call returned: nothing may start it now. + drop(writer); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(spawned.load(Ordering::SeqCst), 0, "the child was started"); + } + #[tokio::test] async fn pre_cancelled_run_rejects_before_spawning_the_command() { let cancellation = CancellationToken::new(); diff --git a/apps/server/src/production/control.rs b/apps/server/src/production/control.rs index f4d8d8c836..64f4688f26 100644 --- a/apps/server/src/production/control.rs +++ b/apps/server/src/production/control.rs @@ -66,6 +66,7 @@ fn merge_provider_snapshot( refreshed: provider_inventory::ProviderProbeResult, ) -> Value { let models_authoritative = refreshed.models_authoritative; + let session_reads = refreshed.session_reads; let mut next = refreshed.snapshot; if refreshed.rich_metadata == provider_inventory::RichMetadataOutcome::Succeeded { return next; @@ -79,8 +80,52 @@ fn merge_provider_snapshot( if provider_snapshot_identity(&next) != Some(current_identity) { return next; } - if !models_authoritative && let Some(value) = current.get("models") { - next["models"] = value.clone(); + let antigravity = next["driver"] == "antigravity"; + // A disabled or missing instance carries nothing a past session read, nor does one whose + // CLI, session or launch inputs failed or changed since (`SessionReads::Lost`). + let installed_and_enabled = + antigravity && next["installed"] != false && next["status"] != "disabled"; + let keeps_session_reads = + installed_and_enabled && session_reads == provider_inventory::SessionReads::NotRead; + // A session that answered without listing a model keeps the last catalog. + let keeps_catalog = + installed_and_enabled && session_reads != provider_inventory::SessionReads::Lost; + if !models_authoritative + && (keeps_catalog || !antigravity) + && let Some(value) = current.get("models") + { + next["models"] = if antigravity { + // The probed catalog stays until the next full probe; custom models follow settings. + let probed = value + .as_array() + .into_iter() + .flatten() + .filter(|model| model["isCustom"] != true) + .cloned() + .collect::>(); + let custom = next["models"] + .as_array() + .into_iter() + .flatten() + .filter(|model| !probed.iter().any(|listed| listed["slug"] == model["slug"])); + let custom = custom.cloned().collect::>(); + probed.into_iter().chain(custom).collect() + } else { + value.clone() + }; + } + // Only a full probe opens an Antigravity session, so the sign-in it read stays until the next. + if keeps_session_reads + && next["auth"]["status"] == "unknown" + && let Some(auth) = current.get("auth") + { + next["auth"] = auth.clone(); + if auth["status"] == "unauthenticated" + && next.get("message").is_none() + && let Some(message) = current.get("message") + { + next["message"] = message.clone(); + } } for field in ["slashCommands", "skills", "agents"] { if let Some(value) = current.get(field) { @@ -267,9 +312,60 @@ impl fmt::Debug for AgentActivityHandlerSlot { #[derive(Debug, Default)] struct ProviderRefreshState { last_completed: Option, + /// Per ACP-probed instance, when a full refresh last read its catalog and with which inputs. + catalog_reads: std::collections::HashMap, + /// Per Antigravity instance, the launch inputs its published session reads belong to. + session_read_inputs: std::collections::HashMap, manual_refreshes: usize, } +/// `settings` with each Antigravity instance's sensitive environment values read from the secret +/// store, as a chat launch reads them, instead of the redacted copy held and published here. +/// Only probes use it, so the inventory reads the account a chat runs with. Each value is read +/// on its own: one that cannot be read stays redacted, and only that instance goes unprobed. +/// Every other driver probes with the settings as they are. +async fn with_stored_secrets(state_directory: &Path, settings: &Value) -> Value { + let store = crate::server_settings::ProviderSettingsStore::new(state_directory); + let mut probe = settings.clone(); + let Some(instances) = probe + .get_mut("providerInstances") + .and_then(Value::as_object_mut) + else { + return probe; + }; + for (instance_id, instance) in instances.iter_mut() { + if instance["driver"] != "antigravity" { + continue; + } + let Some(environment) = instance + .get_mut("environment") + .and_then(Value::as_array_mut) + else { + continue; + }; + for variable in environment { + if variable["valueRedacted"] != true { + continue; + } + let Some(name) = variable["name"].as_str().map(str::to_owned) else { + continue; + }; + match store.stored_secret(instance_id, &name).await { + Ok(value) => { + variable["value"] = Value::String(value); + variable["valueRedacted"] = Value::Bool(false); + } + Err(error) => tracing::warn!( + instance_id, + kind = ?error.kind(), + "a stored provider secret could not be read for the inventory probe" + ), + } + } + } + probe +} + struct ManualFullProviderRefresh { state: Arc>, } @@ -362,6 +458,8 @@ pub struct NativeServerControl { providers: Arc>>, provider_maintenance: ProviderMaintenance, tools: ToolMaintenance, + /// Attributes the processes a full provider probe starts, once the runtime attaches it. + process_attribution: Arc>, capability_tasks: TaskTracker, capability_shutdown: CancellationToken, capability_admission: Arc>, @@ -460,8 +558,9 @@ impl NativeServerControl { }, ); // Nothing subscribes yet, so the tools' publish during startup reaches no one. + let probe_settings = with_stored_secrets(&state_directory, &settings).await; *providers.write().await = - probe_startup_inventory(&settings, &cwd, &provider_maintenance, &tools).await; + probe_startup_inventory(&probe_settings, &cwd, &provider_maintenance, &tools).await; let control = Self { config, auth_descriptor, @@ -510,6 +609,7 @@ impl NativeServerControl { providers, provider_maintenance, tools, + process_attribution: Arc::default(), capability_tasks: TaskTracker::new(), capability_shutdown: CancellationToken::new(), capability_admission: Arc::new(std::sync::Mutex::new(())), @@ -1005,7 +1105,7 @@ impl NativeServerControl { let cwd = std::env::current_dir().unwrap_or_else(|_| self.config.base_dir.clone()); let probe_sequence = self.begin_provider_probe(); let refreshed = self - .probe_full_provider_snapshots(&settings, instance_id, &cwd) + .probe_full_provider_snapshots(&settings, instance_id, &cwd, &Default::default()) .await; let providers = match self .publish_provider_snapshots_if_current( @@ -1065,6 +1165,7 @@ impl NativeServerControl { &self, registry: crate::diagnostics::ProcessAttributionRegistry, ) { + let _ = self.process_attribution.set(registry.clone()); self.tools.attach_attribution(registry); } @@ -1452,7 +1553,12 @@ impl NativeServerControl { let (generation, settings) = self.settings_snapshot().await; let probe_sequence = self.begin_provider_probe(); let refreshed = self - .probe_full_provider_snapshots(&settings, Some(&target.instance_id), &cwd) + .probe_full_provider_snapshots( + &settings, + Some(&target.instance_id), + &cwd, + &Default::default(), + ) .await; let verification = refreshed .iter() @@ -1650,14 +1756,17 @@ impl NativeServerControl { pause.entered.notify_one(); pause.release.notified().await; } + let settings = &with_stored_secrets(&self.state_directory, settings).await; provider_inventory::probe(settings, instance_id, cwd, &self.provider_maintenance).await } + /// `reuse` names the instances whose ACP catalog this probe keeps instead of reading again. async fn probe_full_provider_snapshots( &self, settings: &Value, instance_id: Option<&str>, cwd: &Path, + reuse: &std::collections::HashSet, ) -> Vec { #[cfg(test)] let pause = self.next_full_provider_probe_pause.lock().await.take(); @@ -1666,18 +1775,27 @@ impl NativeServerControl { pause.entered.notify_one(); pause.release.notified().await; } + let settings = &with_stored_secrets(&self.state_directory, settings).await; if instance_id.is_some() { return provider_inventory::probe_full( settings, instance_id, cwd, &self.provider_maintenance, + self.process_attribution.get(), ) .await; } // Tools are re-checked with every full refresh; they publish their own changes. let (providers, ()) = tokio::join!( - provider_inventory::probe_full(settings, None, cwd, &self.provider_maintenance), + provider_inventory::probe_full_reusing( + settings, + None, + cwd, + &self.provider_maintenance, + self.process_attribution.get(), + reuse, + ), self.tools.refresh(update_checks_enabled(settings), cwd), ); providers @@ -1732,12 +1850,73 @@ impl NativeServerControl { Some(providers) } + /// What an Antigravity probe that opened no session keeps from the last session reads: + /// nothing once the binary path or environment differ from those the reads were taken with, + /// or once the instance is disabled or missing. A probe that read or lost them records its + /// inputs as theirs. Only a signed-in session read starts a catalog reuse window; any other + /// outcome ends it, so a sign-in, an install or a fix is read on the next full refresh. + fn settle_session_reads(&self, result: &mut provider_inventory::ProviderProbeResult) { + use provider_inventory::SessionReads; + if result.snapshot["driver"] != "antigravity" { + return; + } + let Some(instance_id) = result.snapshot["instanceId"].as_str() else { + return; + }; + let mut state = self + .provider_refresh_state + .lock() + .expect("provider refresh state lock"); + if result.snapshot["installed"] == false || result.snapshot["status"] == "disabled" { + result.session_reads = SessionReads::Lost; + } + // A session that listed no model, read with other launch inputs than the last reads, + // must not carry those reads' models over. + if result.session_reads == SessionReads::Read + && !result.models_authoritative + && state.session_read_inputs.get(instance_id) != Some(&result.launch_inputs) + { + result.session_reads = SessionReads::Lost; + } + match result.session_reads { + // Only a signed-in read that listed models starts a reuse window. + SessionReads::Read + if result.snapshot["auth"]["status"] == "authenticated" + && result.models_authoritative => + { + state.catalog_reads.insert( + instance_id.to_owned(), + (Instant::now(), result.catalog_inputs), + ); + } + SessionReads::Read | SessionReads::Lost => { + state.catalog_reads.remove(instance_id); + } + SessionReads::NotRead => {} + } + if result.session_reads == SessionReads::NotRead + && state.session_read_inputs.get(instance_id) != Some(&result.launch_inputs) + { + result.session_reads = SessionReads::Lost; + state.catalog_reads.remove(instance_id); + } + if result.session_reads != SessionReads::NotRead { + state + .session_read_inputs + .insert(instance_id.to_owned(), result.launch_inputs); + } + } + async fn merge_provider_snapshots( &self, refreshed: Vec, partial: bool, ) -> (Vec, bool) { let mut current = self.providers.write().await; + let mut refreshed = refreshed; + for result in &mut refreshed { + self.settle_session_reads(result); + } let mut merged = if partial { let mut merged = current.clone(); for result in refreshed { @@ -1776,6 +1955,21 @@ impl NativeServerControl { if !partial { self.provider_maintenance .prune_update_states(merged.iter().filter_map(provider_snapshot_identity)); + // A removed instance's reads go with it: one re-added later is read afresh. + let listed = merged + .iter() + .filter_map(|row| row["instanceId"].as_str()) + .collect::>(); + let mut state = self + .provider_refresh_state + .lock() + .expect("provider refresh state lock"); + state + .catalog_reads + .retain(|instance_id, _| listed.contains(instance_id.as_str())); + state + .session_read_inputs + .retain(|instance_id, _| listed.contains(instance_id.as_str())); } for provider in merged.iter_mut() { self.provider_maintenance.overlay_update_state(provider); @@ -1803,6 +1997,8 @@ impl NativeServerControl { })); } + /// Records that a full refresh completed. Catalog reuse windows start where a signed-in + /// session read is merged (`settle_session_reads`). fn record_full_provider_refresh(&self) { self.provider_refresh_state .lock() @@ -1810,6 +2006,37 @@ impl NativeServerControl { .last_completed = Some(Instant::now()); } + /// Whether a full refresh completed after `since`. + fn full_provider_refresh_completed_since(&self, since: Instant) -> bool { + self.provider_refresh_state + .lock() + .expect("provider refresh state lock") + .last_completed + .is_some_and(|completed| completed >= since) + } + + /// The Antigravity instances whose catalog a full refresh with `settings` reuses: each was + /// read signed in, within the refresh TTL, with the inputs it has now. An Antigravity probe + /// opens a session in the user's account; Cursor is always probed again. + fn reusable_acp_catalogs(&self, settings: &Value) -> std::collections::HashSet { + let state = self + .provider_refresh_state + .lock() + .expect("provider refresh state lock"); + provider_inventory::antigravity_catalog_inputs(settings) + .into_iter() + .filter(|(instance_id, inputs)| { + state + .catalog_reads + .get(instance_id) + .is_some_and(|(read, read_inputs)| { + read_inputs == inputs && read.elapsed() <= PROVIDER_REFRESH_TTL + }) + }) + .map(|(instance_id, _)| instance_id) + .collect() + } + fn start_full_provider_refresh( &self, mut generation: u64, @@ -1839,6 +2066,11 @@ impl NativeServerControl { let mut owns_refresh = true; 'refresh: loop { loop { + let started = Instant::now(); + // The catalog inputs carry the stored secrets: a changed one is read again. + let probe_settings = + with_stored_secrets(&control.state_directory, &settings).await; + let reuse = control.reusable_acp_catalogs(&probe_settings); let probe_sequence = control.begin_provider_probe(); let providers = if let FullProviderRefreshTrigger::BackgroundCheck { cancellation, @@ -1846,11 +2078,11 @@ impl NativeServerControl { { tokio::select! { () = cancellation.cancelled() => break 'refresh, - providers = control.probe_full_provider_snapshots(&settings, None, &cwd) => providers, + providers = control.probe_full_provider_snapshots(&settings, None, &cwd, &reuse) => providers, } } else { control - .probe_full_provider_snapshots(&settings, None, &cwd) + .probe_full_provider_snapshots(&settings, None, &cwd, &reuse) .await }; if control @@ -1872,7 +2104,16 @@ impl NativeServerControl { .store(generation, Ordering::Release); break; } - (generation, settings) = control.settings_snapshot().await; + let (latest_generation, latest_settings) = control.settings_snapshot().await; + // A newer full refresh under the same settings already published; probing + // again would repeat it, and each Antigravity probe opens an account session. + if latest_generation == generation + && latest_settings == settings + && control.full_provider_refresh_completed_since(started) + { + break; + } + (generation, settings) = (latest_generation, latest_settings); } control .full_provider_refresh_running @@ -2827,6 +3068,7 @@ fn validate_legacy_provider_settings(providers: &Value) -> Result<(), String> { "opencode", &["binaryPath", "serverUrl", "serverPassword"][..], ), + ("antigravity", &["binaryPath"][..]), ] { let Some(settings) = providers.get(driver) else { continue; @@ -3015,6 +3257,27 @@ fn apply_settings_defaults(settings: &mut Value) { "agentMessaging": { "enabled": false }, }), ); + // A blank path reads as the default, as the settings contract decodes it. + if let Some(antigravity) = settings.pointer_mut("/providers/antigravity") + && antigravity["binaryPath"] + .as_str() + .is_some_and(|path| path.trim().is_empty()) + { + antigravity["binaryPath"] = json!("agy"); + } + for instance in settings + .get_mut("providerInstances") + .and_then(Value::as_object_mut) + .into_iter() + .flat_map(|instances| instances.values_mut()) + .filter(|instance| instance["driver"] == "antigravity") + { + if let Some(path) = instance.pointer_mut("/config/binaryPath") + && path.as_str().is_some_and(|path| path.trim().is_empty()) + { + *path = json!("agy"); + } + } let object = settings.as_object_mut().expect("settings object"); object .entry("defaultAgent") @@ -3718,7 +3981,8 @@ mod tests { "claudeAgent": missing_provider, "cursor": missing_provider, "grok": missing_provider, - "opencode": missing_provider + "opencode": missing_provider, + "antigravity": missing_provider }, "providerInstances": { "codex": { "driver": "codex", "enabled": true, "config": { "binaryPath": missing_binary } }, @@ -4406,7 +4670,12 @@ done let (_, settings) = control.settings_snapshot().await; let cwd = std::env::current_dir().unwrap_or_else(|_| control.config.base_dir.clone()); control - .probe_full_provider_snapshots(&settings, Some("cursor-work"), &cwd) + .probe_full_provider_snapshots( + &settings, + Some("cursor-work"), + &cwd, + &Default::default(), + ) .await; assert_eq!( requests.load(Ordering::SeqCst), @@ -4800,15 +5069,22 @@ done apply_settings_defaults(&mut settings); let missing_binary = missing_provider_executable(&temp); - let host_fallbacks = ["codex", "claudeAgent", "cursor", "grok", "opencode"] - .into_iter() - .filter_map(|driver| { - let target = provider_inventory::maintenance_target(&settings, driver, None) - .unwrap_or_else(|| panic!("{driver} has a provider definition")); - (target.binary_path != missing_binary) - .then(|| format!("{driver} -> {}", target.binary_path)) - }) - .collect::>(); + let host_fallbacks = [ + "codex", + "claudeAgent", + "cursor", + "grok", + "opencode", + "antigravity", + ] + .into_iter() + .filter_map(|driver| { + let target = provider_inventory::maintenance_target(&settings, driver, None) + .unwrap_or_else(|| panic!("{driver} has a provider definition")); + (target.binary_path != missing_binary) + .then(|| format!("{driver} -> {}", target.binary_path)) + }) + .collect::>(); assert!( host_fallbacks.is_empty(), "providers must not resolve CLIs from the host PATH: {host_fallbacks:?}" @@ -5972,6 +6248,45 @@ done assert_eq!(settings["providers"]["grok"]["enabled"], false); } + #[test] + fn native_settings_default_antigravity_to_disabled_with_the_agy_binary() { + let mut settings = json!({}); + apply_settings_defaults(&mut settings); + + assert_eq!(settings["providers"]["antigravity"]["enabled"], false); + assert_eq!(settings["providers"]["antigravity"]["binaryPath"], "agy"); + } + + #[test] + fn an_antigravity_settings_patch_keeps_an_explicit_enable_and_validates_its_fields() { + let patch = json!({ + "providers": { "antigravity": { "enabled": true, "binaryPath": "custom-agy" } } + }); + assert!(validate_settings_document(&patch).is_ok()); + let mut settings = json!({}); + apply_settings_defaults(&mut settings); + apply_settings_patch(&mut settings, patch); + apply_settings_defaults(&mut settings); + assert_eq!(settings["providers"]["antigravity"]["enabled"], true); + assert_eq!( + settings["providers"]["antigravity"]["binaryPath"], + "custom-agy" + ); + + assert!( + validate_settings_document(&json!({ + "providers": { "antigravity": { "binaryPath": 5 } } + })) + .is_err() + ); + assert!( + validate_settings_document(&json!({ + "providers": { "antigravity": { "enabled": "yes" } } + })) + .is_err() + ); + } + #[test] fn native_settings_default_provider_update_checks_to_enabled() { let mut settings = json!({}); @@ -6868,6 +7183,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, models_authoritative: false, + ..Default::default() }; let failed = provider_inventory::ProviderProbeResult { rich_metadata: provider_inventory::RichMetadataOutcome::Failed, @@ -6886,6 +7202,731 @@ done } } + /// A quick refresh starts no Antigravity session, so it keeps the sign-in state and the models + /// the last full probe read, while the custom models follow the settings. A full probe after + /// sign-in replaces both. Other drivers keep publishing the refreshed sign-in state. + #[test] + fn antigravity_quick_refresh_keeps_probed_models_and_sign_in_until_a_full_probe() { + let sign_in = "Antigravity is not signed in."; + let current = json!({ + "instanceId": "antigravity", + "driver": "antigravity", + "status": "ready", + "auth": { "status": "unauthenticated" }, + "message": sign_in, + "models": [ + { "slug": "model-alpha", "name": "Model Alpha", "isCustom": false }, + { "slug": "removed-custom", "name": "removed-custom", "isCustom": true } + ] + }); + let quick = |driver: &str| provider_inventory::ProviderProbeResult { + snapshot: json!({ + "instanceId": driver, + "driver": driver, + "status": "ready", + "auth": { "status": "unknown" }, + "models": [{ "slug": "added-custom", "name": "added-custom", "isCustom": true }] + }), + rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, + models_authoritative: false, + ..Default::default() + }; + + let merged = merge_provider_snapshot(Some(¤t), quick("antigravity")); + assert_eq!(merged["auth"], json!({ "status": "unauthenticated" })); + assert_eq!(merged["message"], sign_in); + assert_eq!( + merged["models"], + json!([ + { "slug": "model-alpha", "name": "Model Alpha", "isCustom": false }, + { "slug": "added-custom", "name": "added-custom", "isCustom": true } + ]) + ); + + let signed_in = provider_inventory::ProviderProbeResult { + snapshot: json!({ + "instanceId": "antigravity", + "driver": "antigravity", + "status": "ready", + "auth": { "status": "authenticated" }, + "models": [{ "slug": "model-beta", "name": "Model Beta", "isCustom": false }] + }), + rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, + models_authoritative: true, + ..Default::default() + }; + let replaced = merge_provider_snapshot(Some(&merged), signed_in.clone()); + assert_eq!(replaced, signed_in.snapshot); + + let cursor = json!({ + "instanceId": "cursor", + "driver": "cursor", + "status": "ready", + "auth": { "status": "authenticated" }, + "models": [] + }); + let merged = merge_provider_snapshot(Some(&cursor), quick("cursor")); + assert_eq!(merged["auth"], json!({ "status": "unknown" })); + } + + /// A blank Antigravity binary path reads as `agy`, as the settings contract decodes it, + /// never as an empty program the inventory would try to resolve. + #[test] + fn a_blank_antigravity_binary_path_falls_back_to_agy() { + for blank in ["", " "] { + let mut settings = json!({ + "providers": { "antigravity": { "enabled": true, "binaryPath": blank } } + }); + apply_settings_defaults(&mut settings); + assert_eq!( + settings["providers"]["antigravity"]["binaryPath"], "agy", + "{blank:?}" + ); + assert_eq!(settings["providers"]["antigravity"]["enabled"], true); + } + let mut custom = json!({ + "providers": { "antigravity": { "binaryPath": "custom-cli" } } + }); + apply_settings_defaults(&mut custom); + assert_eq!( + custom["providers"]["antigravity"]["binaryPath"], + "custom-cli" + ); + } + + /// A configured Antigravity instance with a blank binary path is saved (and loaded) as + /// `agy`, the program the refresh then probes. Through the settings RPC that refresh would + /// resolve the real `agy`, which the hermetic guard refuses, so the save's normalization + /// step is called directly. + #[test] + fn a_blank_antigravity_instance_binary_path_saves_and_probes_as_agy() { + let mut settings = json!({ "providerInstances": { + "work": { "driver": "antigravity", "enabled": true, "config": { "binaryPath": " " } }, + "other": { "driver": "codex", "enabled": true, "config": { "binaryPath": " " } } + } }); + apply_settings_defaults(&mut settings); + assert_eq!( + settings["providerInstances"]["work"]["config"]["binaryPath"], + "agy" + ); + // Only Antigravity's default is applied; another driver keeps what it was given. + assert_eq!( + settings["providerInstances"]["other"]["config"]["binaryPath"], + " " + ); + let target = provider_inventory::maintenance_target(&settings, "antigravity", Some("work")) + .expect("the Antigravity instance"); + assert_eq!(target.binary_path, "agy"); + } + + /// A disabled, missing or signed-out Antigravity snapshot carries no sign-in state, message + /// or probed model from the snapshot before it. + #[test] + fn antigravity_snapshots_that_are_off_or_missing_carry_nothing_stale() { + let probed = json!([ + { "slug": "model-alpha", "name": "Model Alpha", "isCustom": false } + ]); + let custom = json!([{ "slug": "custom-one", "name": "custom-one", "isCustom": true }]); + for auth in ["authenticated", "unauthenticated"] { + let mut current = json!({ + "instanceId": "antigravity", + "driver": "antigravity", + "enabled": true, + "installed": true, + "status": "ready", + "auth": { "status": auth }, + "models": probed + }); + if auth == "unauthenticated" { + current["message"] = json!("Antigravity is not signed in."); + } + for (status, enabled, message, rich_metadata) in [ + ( + "disabled", + false, + None, + provider_inventory::RichMetadataOutcome::NotRequested, + ), + ( + "error", + true, + Some("Provider executable was not found."), + provider_inventory::RichMetadataOutcome::Failed, + ), + ] { + let mut snapshot = json!({ + "instanceId": "antigravity", + "driver": "antigravity", + "enabled": enabled, + "installed": false, + "status": status, + "auth": { "status": "unknown" }, + "models": custom + }); + if let Some(message) = message { + snapshot["message"] = json!(message); + } + let merged = merge_provider_snapshot( + Some(¤t), + provider_inventory::ProviderProbeResult { + snapshot: snapshot.clone(), + rich_metadata, + models_authoritative: false, + ..Default::default() + }, + ); + assert_eq!( + merged["auth"], + json!({ "status": "unknown" }), + "{status} {auth}" + ); + assert_eq!( + merged.get("message"), + snapshot.get("message"), + "{status} {auth}" + ); + assert_eq!(merged["models"], custom, "{status} {auth}"); + } + } + } + + /// Counts the `session/new` requests the scripted Antigravity peer has read. + #[cfg(unix)] + fn antigravity_sessions(requests: &Path) -> usize { + provider_inventory::tests::antigravity_requests(requests) + .iter() + .filter(|request| request["method"] == "session/new") + .count() + } + + /// A control whose only enabled provider is a scripted Antigravity peer, after the save that + /// enabled it has finished its full refresh, with the peer's request log. + #[cfg(unix)] + async fn antigravity_control( + temp: &tempfile::TempDir, + sandbox: &crate::test_support::TestSandbox, + ) -> (NativeServerControl, PathBuf) { + let control = scheduler_control(temp).await; + let (binary, requests) = provider_inventory::tests::antigravity_acp_fixture( + sandbox, + "antigravity-cli-control", + "1.5.13", + r#""result":{"sessionId":"session-1","models":{"availableModels":[{"modelId":"alpha"}]}}"#, + ); + control + .update_settings(json!({ "patch": { "providerInstances": { + "antigravity": { "driver": "antigravity", "enabled": true, "config": { "binaryPath": binary } } + } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 1); + (control, requests) + } + + /// An automatic full refresh superseded by a manual one under the same settings does not + /// probe again: the manual one already published, and each probe opens an account session. + #[cfg(unix)] + #[tokio::test] + async fn a_superseded_automatic_refresh_opens_no_extra_antigravity_session() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-superseded"); + let (control, requests) = antigravity_control(&temp, &sandbox).await; + // Outside the catalog reuse window, so the automatic refresh opens its own session. + control + .provider_refresh_state + .lock() + .expect("provider refresh state lock") + .catalog_reads + .clear(); + let pause = control.install_next_full_provider_probe_pause().await; + let (generation, settings) = control.settings_snapshot().await; + let cwd = std::env::current_dir().unwrap_or_else(|_| control.config.base_dir.clone()); + let automatic = control + .start_full_provider_refresh( + generation, + settings, + cwd, + FullProviderRefreshTrigger::BackgroundCheck { + cancellation: CancellationToken::new(), + }, + ) + .expect("the automatic refresh starts"); + pause.wait_until_entered().await; + control.refresh_providers(&json!({})).await; + assert_eq!(antigravity_sessions(&requests), 2); + let probes = control.next_provider_probe_sequence.load(Ordering::Acquire); + pause.release(); + automatic.await.expect("the automatic refresh ends"); + // Its own, superseded probe, and no second one. + assert_eq!(antigravity_sessions(&requests), 3); + assert_eq!( + control.next_provider_probe_sequence.load(Ordering::Acquire), + probes + ); + } + + /// The published Antigravity row's sign-in status, message and probed model slugs. + #[cfg(unix)] + async fn antigravity_reads(control: &NativeServerControl) -> (Value, Value, Vec) { + let providers = control.providers.read().await; + let row = providers + .iter() + .find(|provider| provider["instanceId"] == "antigravity") + .expect("the Antigravity row"); + let probed = row["models"] + .as_array() + .into_iter() + .flatten() + .filter(|model| model["isCustom"] != true) + .map(|model| model["slug"].clone()) + .collect(); + ( + row["auth"]["status"].clone(), + row["message"].clone(), + probed, + ) + } + + /// The inventory probe launches with the environment a chat launches with: a sensitive + /// variable's stored value, not the redacted copy. A peer that answers "Authentication + /// required" without it lists its catalog with it, and a changed value is read again. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_probe_launches_with_the_stored_secret() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-stored-secret"); + let control = scheduler_control(&temp).await; + let binary = sandbox.path("agy-secret"); + let requests = sandbox.path("agy-secret.requests"); + let initialize = provider_inventory::tests::antigravity_initialize(1, "1.5.13", true); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + r#"#!/bin/sh +case "$1" in --version) echo 1.5.13; exit 0 ;; esac +while IFS= read -r request; do + printf '%s\n' "$request" >> '{requests}' + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$request" in + *'"method":"initialize"'*) body='{initialize}' ;; + *'"method":"session/new"'*) + if [ "$TEST_ACCOUNT_KEY" = test-account-value ]; then + body='"result":{{"sessionId":"session-1","models":{{"availableModels":[{{"modelId":"alpha"}}]}}}}' + else + body='"error":{{"code":-32000,"message":"Authentication required"}}' + fi ;; + *) body='"result":{{}}' ;; + esac + printf '{{"jsonrpc":"2.0","id":%s,%s}}\n' "$id" "$body" +done +"#, + requests = requests.display(), + ), + ); + let save = async |value: &str| { + control + .update_settings(json!({ "patch": { "providerInstances": { "antigravity": { + "driver": "antigravity", "enabled": true, + "config": { "binaryPath": binary }, + "environment": [{ "name": "TEST_ACCOUNT_KEY", "value": value, "sensitive": true }] + } } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + }; + save("test-account-value").await; + let (auth, _, models) = antigravity_reads(&control).await; + assert_eq!(auth, "authenticated"); + assert_eq!(models, [json!("alpha")]); + // Another stored value is another account: the reused catalog is not kept. + save("another-account-value").await; + let (auth, _, models) = antigravity_reads(&control).await; + assert_eq!(auth, "unauthenticated"); + assert!(models.is_empty(), "{models:?}"); + assert_eq!(antigravity_sessions(&requests), 2); + } + + /// Stored secrets reach Antigravity's probe only, one instance at a time, and never a + /// published field: a CLI that echoes its environment publishes no version, an instance + /// whose secret cannot be read is reported unprobed without stopping another, and a Codex + /// probe keeps the redacted environment it had before. + #[cfg(unix)] + #[tokio::test] + async fn stored_secrets_reach_only_antigravity_probes_and_no_published_field() { + const MARKER: &str = "test-marker-secret-4417"; + // A secret shaped like a release number passes the version parser on its own. + const DOTTED: &str = "123.456.789"; + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-secret-echo"); + let control = scheduler_control(&temp).await; + let echo = sandbox.path("agy-echo"); + // The same CLI answering protocol 2: refused, so no session version replaces the + // `--version` line it printed. + let refused = sandbox.path("agy-echo-refused"); + // A CLI that echoes its environment as the handshake's `agentInfo.version`. + let agent_echo = sandbox.path("agy-agent-echo"); + const KEY: &str = r#""$TEST_ACCOUNT_KEY""#; + for (binary, protocol, version_line, agent_version) in [ + (&echo, 1, KEY, "1.5.13"), + (&refused, 2, KEY, "1.5.13"), + (&agent_echo, 1, "1.5.13", r#"'"$TEST_ACCOUNT_KEY"'"#), + ] { + let initialize = + provider_inventory::tests::antigravity_initialize(protocol, "agent-version", true) + .replace("agent-version", agent_version); + crate::test_support::executable_fixture::write_executable( + binary, + format!( + r#"#!/bin/sh +printf '%s\n' "$TEST_ACCOUNT_KEY" >&2 +case "$1" in --version) printf '%s\n' {version_line}; exit 0 ;; esac +while IFS= read -r request; do + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$request" in + *'"method":"initialize"'*) body='{initialize}' ;; + *'"method":"session/new"'*) body='"result":{{"sessionId":"s1","models":{{"availableModels":[{{"modelId":"alpha"}}]}}}}' ;; + *) body='"result":{{}}' ;; + esac + printf '{{"jsonrpc":"2.0","id":%s,%s}}\n' "$id" "$body" +done +"# + ), + ); + } + let codex_seen = sandbox.path("codex-seen"); + let codex = sandbox.executable_script( + "codex-echo", + &format!( + "printf '%s' \"$CODEX_KEY\" > '{}'\necho 'codex-cli 0.1.0'", + codex_seen.display() + ), + "", + ); + let sensitive = + |name: &str, value: &str| json!([{ "name": name, "value": value, "sensitive": true }]); + control + .update_settings(json!({ "patch": { "providerInstances": { + "antigravity": { "driver": "antigravity", "enabled": true, + "config": { "binaryPath": echo }, + "environment": sensitive("TEST_ACCOUNT_KEY", MARKER) }, + "antigravity-two": { "driver": "antigravity", "enabled": true, + "config": { "binaryPath": echo }, + "environment": sensitive("TEST_ACCOUNT_KEY", "") }, + "antigravity-three": { "driver": "antigravity", "enabled": true, + "config": { "binaryPath": refused }, + "environment": sensitive("TEST_ACCOUNT_KEY", DOTTED) }, + // The version parser drops a leading `v`, so the raw text is what is checked. + "antigravity-four": { "driver": "antigravity", "enabled": true, + "config": { "binaryPath": refused }, + "environment": sensitive("TEST_ACCOUNT_KEY", "v987.654.321") }, + "antigravity-five": { "driver": "antigravity", "enabled": true, + "config": { "binaryPath": agent_echo }, + "environment": sensitive("TEST_ACCOUNT_KEY", "v876.543.210") }, + "codex": { "driver": "codex", "enabled": true, + "config": { "binaryPath": codex }, + "environment": sensitive("CODEX_KEY", MARKER) } + } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + let providers = control.providers.read().await.clone(); + let published = serde_json::to_string(&providers).expect("providers JSON"); + assert!(!published.contains(MARKER), "a stored secret was published"); + assert!( + !published.contains(DOTTED), + "a stored secret was published as a version" + ); + let leaked = ["987.654.321", "876.543.210"] + .into_iter() + .filter(|bare| published.contains(bare)) + .collect::>(); + assert!( + leaked.is_empty(), + "`v`-prefixed stored secrets were published as versions: {leaked:?}" + ); + let row = |id: &str| { + providers + .iter() + .find(|row| row["instanceId"] == id) + .cloned() + .expect("row") + }; + let first = row("antigravity"); + assert_eq!(first["auth"]["status"], "authenticated"); + assert!( + first["version"].is_null() || first["version"] == "1.5.13", + "{first}" + ); + let second = row("antigravity-two"); + assert!( + second["message"] + .as_str() + .is_some_and(|message| message.contains("could not be read")), + "{second}" + ); + assert_ne!(second["auth"]["status"], "authenticated"); + assert_eq!( + std::fs::read_to_string(&codex_seen).unwrap_or_default(), + "", + "a Codex probe keeps the redacted environment" + ); + } + + /// After the binary changes, or a probe of the same binary fails, the published row keeps + /// no sign-in, sign-in message or probed model from an earlier session; a manual refresh + /// clears them too. + #[cfg(unix)] + #[tokio::test] + async fn a_changed_or_failing_antigravity_cli_keeps_no_earlier_session_reads() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-stale-reads"); + let (control, _) = antigravity_control(&temp, &sandbox).await; + let signed_in = (json!("authenticated"), Value::Null, vec![json!("alpha")]); + assert_eq!(antigravity_reads(&control).await, signed_in); + + let bad_version = sandbox.executable_script("agy-bad-version", "exit 3", ""); + let (refused_protocol, _) = provider_inventory::tests::antigravity_acp_peer( + &sandbox, + "agy-protocol-2", + "1.5.13", + &provider_inventory::tests::antigravity_initialize(2, "1.5.13", true), + r#""result":{"sessionId":"session-2","models":{"availableModels":[{"modelId":"beta"}]}}"#, + r#""result":{}"#, + ); + let (internal_error, _) = provider_inventory::tests::antigravity_acp_fixture( + &sandbox, + "agy-internal-error", + "1.5.13", + r#""error":{"code":-32000,"message":"Internal error"}"#, + ); + let (signed_out, _) = provider_inventory::tests::antigravity_acp_fixture( + &sandbox, + "agy-signed-out", + "1.5.13", + r#""error":{"code":-32000,"message":"Authentication required"}"#, + ); + for binary in [ + &bad_version, + &refused_protocol, + &internal_error, + &signed_out, + ] { + // Each binary follows a signed-out one, so a kept sign-in message would show. + for binary in [&signed_out, binary] { + control + .update_settings(json!({ "patch": { "providerInstances": { "antigravity": { + "driver": "antigravity", "enabled": true, + "config": { "binaryPath": binary } + } } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + } + let (auth, message, models) = antigravity_reads(&control).await; + assert!(models.is_empty(), "{binary:?}: {models:?}"); + if binary == &signed_out { + assert_eq!(auth, "unauthenticated"); + } else { + assert_ne!(auth, "unauthenticated", "{binary:?}"); + assert_ne!(auth, "authenticated", "{binary:?}"); + assert!( + !message + .as_str() + .is_some_and(|message| message.contains("not signed in")), + "{binary:?}: {message}" + ); + } + } + + // The same binary path, now failing: a manual refresh clears what it read before. + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-stale-manual"); + let (control, _) = antigravity_control(&temp, &sandbox).await; + let binary = control.settings.read().await["providerInstances"]["antigravity"]["config"] + ["binaryPath"] + .as_str() + .expect("binary path") + .to_owned(); + crate::test_support::executable_fixture::write_executable( + Path::new(&binary), + "#!/bin/sh\nexit 3\n", + ); + control.refresh_providers(&json!({})).await; + let (auth, _, models) = antigravity_reads(&control).await; + assert_ne!(auth, "authenticated"); + assert!(models.is_empty(), "{models:?}"); + } + + /// A settings save that leaves Antigravity's settings alone reuses the catalog of a full + /// probe within the refresh TTL and opens no session; one that changes them probes again. + #[cfg(unix)] + #[tokio::test] + async fn an_unrelated_settings_save_opens_no_antigravity_session() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-unrelated-save"); + let (control, requests) = antigravity_control(&temp, &sandbox).await; + let catalog = control.providers.read().await.clone(); + + control + .update_settings(json!({ "patch": { "enableAssistantStreaming": true } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 1); + let antigravity = |providers: &[Value]| { + providers + .iter() + .find(|provider| provider["instanceId"] == "antigravity") + .map(|provider| (provider["auth"].clone(), provider["models"].clone())) + }; + assert_eq!( + antigravity(&control.providers.read().await), + antigravity(&catalog) + ); + + let (_, mut instances) = control.settings_snapshot().await; + instances["providerInstances"]["antigravity"]["config"]["customModels"] = + json!(["custom-one"]); + control + .update_settings( + json!({ "patch": { "providerInstances": instances["providerInstances"] } }), + ) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 2); + + // That signed-in read starts a new reuse window. + control + .update_settings(json!({ "patch": { "enableAssistantStreaming": false } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 2); + + // A disabled instance's window ends: enabled again, it is read afresh. + for enabled in [false, true] { + let (_, mut instances) = control.settings_snapshot().await; + instances["providerInstances"]["antigravity"]["enabled"] = json!(enabled); + control + .update_settings( + json!({ "patch": { "providerInstances": instances["providerInstances"] } }), + ) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + } + assert_eq!(antigravity_sessions(&requests), 3); + } + + /// A signed-out read starts no reuse window: once the user signs in, the next save reads + /// the session again. + #[cfg(unix)] + #[tokio::test] + async fn a_signed_out_antigravity_read_is_read_again_on_the_next_save() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-signed-out-save"); + let control = scheduler_control(&temp).await; + let (binary, requests) = provider_inventory::tests::antigravity_acp_fixture( + &sandbox, + "agy-signed-out-save", + "1.5.13", + r#""error":{"code":-32000,"message":"Authentication required"}"#, + ); + control + .update_settings(json!({ "patch": { "providerInstances": { + "antigravity": { "driver": "antigravity", "enabled": true, "config": { "binaryPath": binary } } + } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 1); + control + .update_settings(json!({ "patch": { "enableAssistantStreaming": true } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 2); + } + + /// A signed-in session that listed no model starts no reuse window either: the next save + /// reads the session again. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_read_without_models_is_read_again_on_the_next_save() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("antigravity-no-models-save"); + let control = scheduler_control(&temp).await; + let (binary, requests) = provider_inventory::tests::antigravity_acp_fixture( + &sandbox, + "agy-no-models-save", + "1.5.13", + r#""result":{"sessionId":"session-1"}"#, + ); + control + .update_settings(json!({ "patch": { "providerInstances": { + "antigravity": { "driver": "antigravity", "enabled": true, "config": { "binaryPath": binary } } + } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 1); + control + .update_settings(json!({ "patch": { "enableAssistantStreaming": true } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(antigravity_sessions(&requests), 2); + } + + /// Cursor has no catalog reuse window, as before Antigravity: every full refresh reads its + /// model list (and its workspace skills, commands and agents) again. + #[cfg(unix)] + #[tokio::test] + async fn every_full_refresh_reads_cursor_models_again() { + let temp = tempfile::tempdir().expect("state directory"); + let sandbox = crate::test_support::TestSandbox::new("cursor-no-reuse"); + let control = scheduler_control(&temp).await; + let binary = sandbox.path("cursor-agent-fixture"); + let requests = sandbox.path("cursor-agent-fixture.requests"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + r#"#!/bin/sh +case "$1" in --version) echo 2026.11.01; exit 0 ;; about) echo "Logged in"; exit 0 ;; esac +while IFS= read -r request; do + printf '%s\n' "$request" >> '{requests}' + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + printf '{{"jsonrpc":"2.0","id":%s,"result":{{}}}}\n' "$id" +done +"#, + requests = requests.display(), + ), + ); + let model_reads = || { + provider_inventory::tests::antigravity_requests(&requests) + .iter() + .filter(|request| request["method"] == "cursor/list_available_models") + .count() + }; + control + .update_settings(json!({ "patch": { "providerInstances": { + "cursor": { "driver": "cursor", "enabled": true, "config": { "binaryPath": binary } } + } } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + let first = model_reads(); + assert!(first >= 1, "the enabling save reads Cursor's models"); + control + .update_settings(json!({ "patch": { "enableAssistantStreaming": true } })) + .await + .expect("settings update succeeds"); + wait_for_full_refresh_idle(&control).await; + assert_eq!(model_reads(), first + 1); + } + /// A probe that read the instance's version tells whether its chats report context usage /// (an OpenCode CLI's version does), even when its catalogs could not be read, so a CLI /// downgraded to OpenCode 1 stops advertising it. One that read no version (a Server URL's @@ -6923,6 +7964,7 @@ done }), rich_metadata, models_authoritative: false, + ..Default::default() }; let merged = merge_provider_snapshot(Some(¤t), refreshed); assert_eq!( @@ -6948,6 +7990,7 @@ done snapshot, rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, models_authoritative: true, + ..Default::default() }) .collect(), partial, @@ -7128,6 +8171,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::Failed, models_authoritative: true, + ..Default::default() }; let merged = merge_provider_snapshot(Some(¤t), refreshed); @@ -7161,6 +8205,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, models_authoritative: false, + ..Default::default() }; let merged = merge_provider_snapshot(Some(¤t), replacement); @@ -7194,6 +8239,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, models_authoritative: true, + ..Default::default() }, ); @@ -7523,6 +8569,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, models_authoritative: true, + ..Default::default() }], false, generation, @@ -7549,6 +8596,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, models_authoritative: true, + ..Default::default() }], false, generation, @@ -8319,6 +9367,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, models_authoritative: false, + ..Default::default() }], true, ) @@ -8380,6 +9429,7 @@ done }), rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, models_authoritative: false, + ..Default::default() }], true, ) @@ -8992,6 +10042,7 @@ done snapshot: json!({"instanceId":"unit-provider","status":"disabled"}), rich_metadata: provider_inventory::RichMetadataOutcome::Succeeded, models_authoritative: true, + ..Default::default() }], true, ) diff --git a/apps/server/src/production/mcp_tools_tests/git.rs b/apps/server/src/production/mcp_tools_tests/git.rs index b89341f87e..3ef3fb0a81 100644 --- a/apps/server/src/production/mcp_tools_tests/git.rs +++ b/apps/server/src/production/mcp_tools_tests/git.rs @@ -634,6 +634,24 @@ async fn delete_branch_with_delete_remote_removes_both_branches() { fixture.harness.shutdown().await; } +/// #406: the remote check runs before the local delete, so a refused remote default leaves the +/// local branch in place. +#[tokio::test] +async fn delete_branch_with_delete_remote_checks_the_remote_before_deleting_locally() { + let fixture = fixture().await; + fixture.git(&["branch", "--track", "mainline", "origin/main"]); + let refused = fixture + .call( + "git_delete_branch", + json!({ "name": "mainline", "deleteRemote": true }), + ) + .await; + assert_eq!(error(&refused)["code"], "default-branch", "{refused}"); + assert_eq!(branches(&fixture.repo), "main\nmainline"); + assert_eq!(branches(&fixture.remote), "main"); + fixture.harness.shutdown().await; +} + #[tokio::test] async fn a_refused_remote_delete_is_a_partial_outcome_that_replays_and_recovers() { let fixture = fixture().await; @@ -1090,6 +1108,44 @@ async fn a_remote_delete_that_stops_reporting_keeps_the_local_deletion_and_its_t fixture.harness.shutdown().await; } +/// #397 round 2 (Antigravity 4): when the refs cannot be read after a failed delete, whether +/// either branch was deleted is unknown, and the answer says so instead of "nothing deleted". +#[cfg(unix)] +#[tokio::test] +async fn a_failed_delete_branch_whose_refs_cannot_be_read_is_an_unknown_outcome() { + let fixture = fixture().await; + publish_feature(&fixture).await; + let git_dir = fixture.repo.join(".git"); + let moved = fixture.repo.join("git-moved-away"); + hook( + &fixture, + &format!( + "mv '{}' '{}'\nexit 1", + git_dir.to_string_lossy(), + moved.to_string_lossy() + ), + ); + let failed = fixture + .call( + "git_delete_branch", + json!({ "name": "feature", "deleteRemote": true, "clientRequestId": "del-blind" }), + ) + .await; + assert_eq!(error_tag(&failed), "McpPartialOutcomeError", "{failed}"); + let outcome = error(&failed); + assert_eq!(outcome["local"], "unknown"); + assert_eq!(outcome["remote"], "unknown"); + assert_eq!(outcome["outcome"], "unknown"); + assert_eq!( + outcome["recovery"]["arguments"], + json!({ "remote": "origin", "branch": "feature" }) + ); + std::fs::rename(&moved, &git_dir).unwrap(); + assert_eq!(branches(&fixture.repo), "main"); + assert_eq!(branches(&fixture.remote), "feature\nmain"); + fixture.harness.shutdown().await; +} + #[tokio::test] async fn tools_list_carries_each_tools_hints_and_source_control_off_hides_them() { let fixture = fixture().await; diff --git a/apps/server/src/production/mod.rs b/apps/server/src/production/mod.rs index 913aa13b34..49ff7ba37b 100644 --- a/apps/server/src/production/mod.rs +++ b/apps/server/src/production/mod.rs @@ -23,8 +23,8 @@ pub mod operational_logs; pub mod orchestration_effects; pub mod orchestration_rpc; pub mod pipelines_rpc; -mod provider_inventory; -mod provider_maintenance; +pub(crate) mod provider_inventory; +pub(crate) mod provider_maintenance; pub mod provider_runtime; pub mod pull_requests_rpc; pub mod relay; diff --git a/apps/server/src/production/orchestration_rpc.rs b/apps/server/src/production/orchestration_rpc.rs index bf89d81a1f..d2a5e1001e 100644 --- a/apps/server/src/production/orchestration_rpc.rs +++ b/apps/server/src/production/orchestration_rpc.rs @@ -757,10 +757,15 @@ async fn dispatch_prepared_command( OrchestrationCommand::ThreadTurnDeliveryResolve { command_id, thread_id, + message_id, action: TurnDeliveryResolutionAction::Dismiss, created_at, - .. - } => Some((command_id.clone(), thread_id.clone(), created_at.clone())), + } => Some(( + command_id.clone(), + thread_id.clone(), + created_at.clone(), + Some(message_id.clone()), + )), // Closing a chat panel archives it. The server stops its work, including a delivery // claimed but not yet visible to clients as a running session. OrchestrationCommand::ThreadArchive { @@ -772,7 +777,7 @@ async fn dispatch_prepared_command( .await .map_err(|error| orchestration_error("OrchestrationDispatchCommandError", error))? .filter(|thread| thread.kind == "panel") - .map(|_| (command_id.clone(), thread_id.clone(), now_iso())), + .map(|_| (command_id.clone(), thread_id.clone(), now_iso(), None)), _ => None, }; let is_delivery_resolution = matches!( @@ -868,21 +873,25 @@ async fn dispatch_prepared_command( && accepted_new.load(Ordering::Acquire) && should_route { - if let Some((command_id, thread_id, created_at)) = delivery_cancellation { + if let Some((command_id, thread_id, created_at, dismissed)) = delivery_cancellation { + // Only the dismissed message's launch is stopped: the worker, woken at the commit, + // may already be launching the next message. let result = provider .provider - .handle_orchestration(OrchestrationCommand::ThreadTurnInterrupt { - command_id: format!("{command_id}:provider-interrupt"), - thread_id, - turn_id: None, - created_at, - }) + .interrupt_after_cancel(command_id, thread_id, created_at, dismissed.as_deref()) .await; if let Err(error) = result && !matches!(error, ProviderRuntimeError::SessionNotFound { .. }) { tracing::warn!(%error, "provider interrupt failed after cancelling provider work"); } + } else if result.stale_interrupt { + // The engine judged this Stop stale in its commit: it names a turn that is no longer + // active, and most providers would interrupt whatever runs now. + tracing::info!( + thread_id = command.aggregate_ref().1, + "a Stop for a turn that is no longer active was not sent to the provider" + ); } else if !is_delivery_resolution && !route_before_admission { route_orchestration_command( &provider.provider, @@ -4824,6 +4833,10 @@ mod tests { interrupt_calls: AtomicUsize, fail_set_model_calls: AtomicUsize, pause_next_set_model: std::sync::Mutex>>, + /// A start that never returns once `start_entered` fires. + start_hangs: AtomicBool, + start_entered: tokio::sync::Notify, + send_calls: AtomicUsize, } #[derive(Default)] @@ -4845,7 +4858,13 @@ mod tests { impl ProviderDriver for ModelMutationProbe { fn start(&self) -> BoxRuntimeFuture<'_, Result> { - Box::pin(async { Ok(StartedSession::default()) }) + Box::pin(async { + if self.start_hangs.load(Ordering::SeqCst) { + self.start_entered.notify_one(); + std::future::pending::<()>().await; + } + Ok(StartedSession::default()) + }) } fn send( @@ -4854,6 +4873,7 @@ mod tests { _attachments: Vec, _interaction_mode: String, ) -> BoxRuntimeFuture<'_, Result, ProviderRuntimeError>> { + self.send_calls.fetch_add(1, Ordering::SeqCst); Box::pin(async { Ok(None) }) } @@ -6620,6 +6640,419 @@ mod tests { engine.shutdown().await; } + /// A thread "t" whose provider start never returns once launched, with the real delivery + /// worker and supervisor behind the RPC registration. + async fn hung_start_fixture() -> ( + OrchestrationEngine, + tempfile::TempDir, + Arc, + ProviderRegistration, + ) { + let engine = migrated_engine().await; + let state = tempfile::tempdir().expect("provider state"); + for command in [ + json!({ + "type":"project.create", "commandId":"hung-project", "projectId":"hung-project", + "title":"Hung Project", "workspaceRoot":state.path(), + "defaultModelSelection":null, "createdAt":CREATED_AT + }), + json!({ + "type":"thread.create", "commandId":"hung-thread", "threadId":"t", + "projectId":"hung-project", "title":"t", "kind":"workspace", + "modelSelection":{"instanceId":"codex","model":"gpt-5"}, + "runtimeMode":"full-access", "interactionMode":"default", + "branch":null, "worktreePath":null, "createdAt":CREATED_AT + }), + ] { + engine + .dispatch(decode_command(command)) + .await + .expect("fixture command"); + } + let probe = Arc::new(ModelMutationProbe::default()); + probe.start_hangs.store(true, Ordering::SeqCst); + let provider = Arc::new(ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(ModelMutationProbeFactory(probe.clone())), + ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )), + SupervisorOptions::default(), + )); + let registration = ProviderRegistration { + provider: provider.clone(), + settings_root: state.path().to_path_buf(), + attachments: AttachmentMaterializer::new(state.path().join("attachments")), + turn_delivery: Arc::new(TurnDeliveryService::start( + engine.clone(), + provider, + state.path().to_path_buf(), + )), + uploads: test_upload_registry(), + }; + (engine, state, probe, registration) + } + + async fn wait_until_launch_ends(engine: &OrchestrationEngine) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while engine.thread_session_launching("t") { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("the hung start ends"); + } + + /// The app's Stop on a message whose provider start hangs: ChatView dismisses the message's + /// delivery by its message id, and the send's command id is a different client id. The + /// Dismiss through the RPC handler must end the launch the delivery worker started for it. + #[tokio::test] + async fn the_app_stop_dismiss_ends_a_hung_provider_start() { + let (engine, _state, probe, registration) = hung_start_fixture().await; + let send = decode_command(json!({ + "type":"thread.turn.start", "commandId":"send-command", "threadId":"t", + "message":{"messageId":"sent-message", "role":"user", "text":"hello", "attachments":[]}, + "createdAt":CREATED_AT + })); + let digest = canonical_command_digest(&send).expect("digest"); + dispatch_turn_for_test( + engine.clone(), + registration.clone(), + send, + digest, + "orchestration.dispatchCommand".into(), + None, + &UploadOwner::Unauthenticated, + ) + .await + .expect("the send is admitted"); + let row = engine + .repositories() + .get_provider_turn_delivery("send-command".into()) + .await + .expect("row read") + .expect("durable row"); + assert_eq!( + row.message_id, "sent-message", + "ids differ, as in production" + ); + tokio::time::timeout( + std::time::Duration::from_secs(5), + probe.start_entered.notified(), + ) + .await + .expect("the worker launched and the start hangs"); + assert!(engine.thread_session_launching("t")); + + tokio::time::timeout( + std::time::Duration::from_secs(5), + dispatch_prepared_for_test( + &engine, + Some(registration.clone()), + delivery_resolution("stop-command", "t", "sent-message", "dismiss"), + ), + ) + .await + .expect("the Dismiss answers") + .expect("the Dismiss is accepted"); + + wait_until_launch_ends(&engine).await; + assert_eq!( + probe.send_calls.load(Ordering::SeqCst), + 0, + "nothing was sent" + ); + let row = engine + .repositories() + .get_provider_turn_delivery("send-command".into()) + .await + .expect("row read") + .expect("durable row"); + assert_eq!(row.state, TurnDeliveryState::Dismissed); + registration.turn_delivery.shutdown().await; + registration + .provider + .shutdown() + .await + .expect("provider stops"); + engine.shutdown().await; + } + + /// The app's Stop on a thread with no cancellable message sends a turnless interrupt; it + /// must still end a start that does not return. + #[tokio::test] + async fn the_app_stop_interrupt_ends_a_hung_start_without_a_cancellable_message() { + let (engine, state, probe, registration) = hung_start_fixture().await; + let provider = registration.provider.clone(); + let cwd = state.path().to_path_buf(); + let launch = tokio::spawn(async move { + provider + .launch(ProviderLaunchRequest { + thread_id: "t".to_owned(), + activity_causal_revision: 0, + provider: "codex".to_owned(), + provider_label: "Codex".to_owned(), + provider_instance_id: Some("codex".to_owned()), + binary_path: "probe".to_owned(), + cwd, + runtime_mode: "full-access".to_owned(), + interaction_mode: "default".to_owned(), + model: Some("gpt-5".to_owned()), + options: Vec::new(), + custom_models: Vec::new(), + service_tier: None, + effort: None, + agent: None, + resume_cursor: None, + environment: Default::default(), + endpoint: None, + server_password: None, + mcp: None, + codex_home: None, + open_url: None, + host_thread_id: None, + side_chat_host_thread_id: None, + code_review: false, + }) + .await + }); + tokio::time::timeout( + std::time::Duration::from_secs(5), + probe.start_entered.notified(), + ) + .await + .expect("the start hangs"); + + // `buildThreadTurnInterruptInput` omits the turn id while the session is not running. + tokio::time::timeout( + std::time::Duration::from_secs(5), + dispatch_prepared_for_test( + &engine, + Some(registration.clone()), + decode_command(json!({ + "type":"thread.turn.interrupt", "commandId":"stop-command", "threadId":"t", + "createdAt":CREATED_AT + })), + ), + ) + .await + .expect("the interrupt answers") + .expect("the interrupt is accepted"); + + let result = tokio::time::timeout(std::time::Duration::from_secs(5), launch) + .await + .expect("the hung start ends") + .expect("launch task joins"); + assert!( + matches!(result, Err(ProviderRuntimeError::LaunchStopped { .. })), + "{result:?}" + ); + wait_until_launch_ends(&engine).await; + assert_eq!(probe.send_calls.load(Ordering::SeqCst), 0); + registration.turn_delivery.shutdown().await; + registration + .provider + .shutdown() + .await + .expect("provider stops"); + engine.shutdown().await; + } + + /// A late Stop naming finished turn A, committed while the projected session reads + /// `at_commit` and handled by the supervisor once it reads `at_supervisor`. Returns the + /// driver's interrupt calls and the requests the Stop expired. + async fn late_stop_case( + at_commit: (&str, Option<&str>), + at_supervisor: (&str, Option<&str>), + ) -> (usize, i64) { + let engine = migrated_engine().await; + let state = tempfile::tempdir().expect("provider state"); + let session = |id: &str, (status, turn): (&str, Option<&str>)| { + decode_command(json!({ + "type":"thread.session.set", "commandId":id, "threadId":"t", + "session":{"threadId":"t", "status":status, "providerName":"codex", + "activeTurnId":turn, "lastError":null, "updatedAt":CREATED_AT}, + "createdAt":CREATED_AT + })) + }; + for command in [ + json!({ + "type":"project.create", "commandId":"late-project", "projectId":"late-project", + "title":"Late Project", "workspaceRoot":state.path(), + "defaultModelSelection":null, "createdAt":CREATED_AT + }), + json!({ + "type":"thread.create", "commandId":"late-thread", "threadId":"t", + "projectId":"late-project", "title":"t", "kind":"workspace", + "modelSelection":{"instanceId":"codex","model":"gpt-5"}, + "runtimeMode":"full-access", "interactionMode":"default", + "branch":null, "worktreePath":null, "createdAt":CREATED_AT + }), + ] { + engine + .dispatch(decode_command(command)) + .await + .expect("fixture command"); + } + let probe = Arc::new(ModelMutationProbe::default()); + let provider = Arc::new(ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(ModelMutationProbeFactory(probe.clone())), + ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )), + SupervisorOptions::default(), + )); + provider + .launch(ProviderLaunchRequest { + thread_id: "t".to_owned(), + activity_causal_revision: 0, + provider: "codex".to_owned(), + provider_label: "Codex".to_owned(), + provider_instance_id: Some("codex".to_owned()), + binary_path: "probe".to_owned(), + cwd: state.path().to_path_buf(), + runtime_mode: "full-access".to_owned(), + interaction_mode: "default".to_owned(), + model: Some("gpt-5".to_owned()), + options: Vec::new(), + custom_models: Vec::new(), + service_tier: None, + effort: None, + agent: None, + resume_cursor: None, + environment: Default::default(), + endpoint: None, + server_password: None, + mcp: None, + codex_home: None, + open_url: None, + host_thread_id: None, + side_chat_host_thread_id: None, + code_review: false, + }) + .await + .expect("provider launches"); + let registration = ProviderRegistration { + provider: provider.clone(), + settings_root: state.path().to_path_buf(), + attachments: AttachmentMaterializer::new(state.path().join("attachments")), + turn_delivery: Arc::new(TurnDeliveryService::start_with_router( + engine.clone(), + 1, + Arc::new(|_| Box::pin(async { Ok(()) })), + )), + uploads: test_upload_registry(), + }; + // Turn A settled; turn B asked for an approval. + for (id, value) in [ + ("a-running", ("running", Some("turn-a"))), + ("a-ready", ("ready", None)), + ("commit", at_commit), + ] { + engine.dispatch(session(id, value)).await.expect("session"); + } + engine + .dispatch(decode_command(json!({ + "type":"thread.activity.append", "commandId":"provider:b-approval", + "threadId":"t", "createdAt":CREATED_AT, + "activity":{"id":"b-approval", "tone":"approval", "kind":"approval.requested", + "summary":"approval", "payload":{"requestId":"b-approval","requestKind":"command"}, + "turnId":"turn-b", "createdAt":CREATED_AT} + }))) + .await + .expect("approval"); + + // The supervisor is busy, so the Stop waits for it after the engine committed it. + let pause = probe.pause_next_set_model(); + let busy = tokio::spawn({ + let provider = provider.clone(); + async move { + provider + .handle_orchestration(decode_command(json!({ + "type":"thread.meta.update", "commandId":"busy", "threadId":"t", + "modelSelection":{"instanceId":"codex","model":"gpt-5.1"} + }))) + .await + } + }); + tokio::time::timeout(std::time::Duration::from_secs(5), pause.entered.notified()) + .await + .expect("the supervisor is busy"); + let stop = tokio::spawn({ + let engine = engine.clone(); + let registration = registration.clone(); + async move { + dispatch_prepared_for_test( + &engine, + Some(registration), + decode_command(json!({ + "type":"thread.turn.interrupt", "commandId":"late-stop", "threadId":"t", + "turnId":"turn-a", "createdAt":CREATED_AT + })), + ) + .await + } + }); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while !engine + .repositories() + .get_command_receipt("late-stop".to_owned()) + .await + .expect("receipt read") + .is_some_and(|receipt| receipt.status == "accepted") + { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("the Stop commits"); + engine + .dispatch(session("supervisor", at_supervisor)) + .await + .expect("session"); + pause.release.notify_one(); + busy.await.expect("busy joins").expect("model set"); + stop.await + .expect("stop joins") + .expect("the Stop is accepted"); + let expired = engine + .repositories() + .database() + .call(|connection| { + Ok(connection.query_row( + "SELECT COUNT(*) FROM projection_thread_activities WHERE thread_id = 't' AND kind LIKE '%.expired'", + [], + |row| row.get::<_, i64>(0), + )?) + }) + .await + .expect("expiries"); + registration.turn_delivery.shutdown().await; + provider.shutdown().await.expect("provider stops"); + engine.shutdown().await; + (probe.interrupt_calls.load(Ordering::SeqCst), expired) + } + + #[tokio::test] + async fn a_stop_the_engine_judged_live_reaches_the_driver_whatever_runs_later() { + // Mutation caught: the supervisor reading turn B running after the engine, which read no + // active turn, expired B's approval, and skipping the driver, so Claude keeps waiting + // on an approval the UI removed. + let (interrupts, expired) = + late_stop_case(("ready", None), ("running", Some("turn-b"))).await; + assert_eq!((interrupts, expired), (1, 1)); + } + + #[tokio::test] + async fn a_stop_the_engine_judged_stale_never_reaches_the_driver() { + // Mutation caught: the supervisor reading no active turn after the engine judged the + // Stop stale against running turn B, and interrupting the turn that runs next. + let (interrupts, expired) = + late_stop_case(("running", Some("turn-b")), ("ready", None)).await; + assert_eq!((interrupts, expired), (0, 0)); + } + #[tokio::test] async fn losing_generic_admission_never_reaches_the_provider() { let hooks = TestHooks::default(); diff --git a/apps/server/src/production/provider_inventory.rs b/apps/server/src/production/provider_inventory.rs index f5c2263a7f..190821648d 100644 --- a/apps/server/src/production/provider_inventory.rs +++ b/apps/server/src/production/provider_inventory.rs @@ -1,8 +1,11 @@ use std::{ collections::{HashMap, HashSet}, ffi::OsString, + future::Future, + hash::{Hash, Hasher}, path::Path, process::Stdio, + sync::{Arc, PoisonError}, time::Duration, }; @@ -16,10 +19,18 @@ use tokio::{ use tokio_util::sync::CancellationToken; use crate::{ + diagnostics::profiler::exits::{self, Exited, Watch}, + diagnostics::{ + AttributionKind, AttributionScope, NativeProcessSampler, ProcessAttributionRegistry, + ProcessRegistration, ProcessRegistrationMetadata, RegistrationSource, + }, git::{OutputPolicy, ProcessRequest, ProcessRunner}, process::{ Platform, configure_supervised_background_command_wrap, - supervised::{log_cleanup_failures, terminate_and_wait}, + supervised::{ + StopPolicy, SupervisedOverflow, SupervisedRunRequest, log_cleanup_failures, + run_supervised_with_spawn_observer, terminate_and_wait, + }, }, production::provider_maintenance::{ProviderMaintenance, ProviderMaintenanceTarget}, production::provider_runtime::{ @@ -36,7 +47,23 @@ mod capabilities; pub(crate) use capabilities::discover_capabilities; const PROBE_TIMEOUT: Duration = Duration::from_secs(10); +#[cfg(not(test))] const CURSOR_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(15); +#[cfg(test)] +const CURSOR_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(6); +/// How long the session that reads Cursor's advertised model values may take; a CLI that does +/// not answer still publishes its model list. +#[cfg(not(test))] +const CURSOR_SESSION_READ_TIMEOUT: Duration = Duration::from_secs(5); +#[cfg(test)] +const CURSOR_SESSION_READ_TIMEOUT: Duration = Duration::from_secs(2); +const ANTIGRAVITY_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(15); +/// The close is courtesy: the catalog is already read and the child stops next. +const ANTIGRAVITY_CLOSE_TIMEOUT: Duration = Duration::from_secs(2); +/// BiBCode's own words: the CLI's error text never reaches the snapshot. +/// An instance whose stored sensitive value could not be read is not probed. +const ANTIGRAVITY_MISSING_SECRET_MESSAGE: &str = "A saved environment value of this instance could not be read, so it was not checked. Save the instance's environment again."; +const ANTIGRAVITY_SIGN_IN_MESSAGE: &str = "Antigravity is not signed in. Open an Antigravity Terminal and run `agy`, or run `agy acp --login`."; const CLAUDE_CAPABILITIES_TIMEOUT: Duration = Duration::from_secs(45); const CLAUDE_SKILLS_TIMEOUT: Duration = Duration::from_secs(10); const CLAUDE_CAPABILITY_PROBE_ARGS: [&str; 12] = [ @@ -75,6 +102,10 @@ struct ProviderDefinition { endpoint: Option, server_password: Option, environment: Vec<(OsString, OsString)>, + /// A sensitive variable is still redacted: its stored value could not be supplied. + missing_secret: bool, + /// The supplied values of sensitive variables: never part of a published version. + secret_values: Vec, } struct ProviderSessionDefaults { @@ -103,18 +134,39 @@ struct ClaudeProbeMetadata { skills_loaded: bool, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub(crate) enum RichMetadataOutcome { + #[default] NotRequested, Succeeded, Failed, } -#[derive(Clone, Debug)] +/// What a probe learned about the reads only an Antigravity session gives (sign-in, its +/// message, the probed catalog). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) enum SessionReads { + /// No session was opened (a quick probe, a reused catalog): the last reads stay, while the + /// launch inputs are those they were read with. + #[default] + NotRead, + /// A session answered: its reads replace the last ones. + Read, + /// The CLI failed its version check, a session could not be opened, or the launch inputs + /// changed: nothing from the last reads stays. + Lost, +} + +#[derive(Clone, Debug, Default)] pub(crate) struct ProviderProbeResult { pub(crate) snapshot: Value, pub(crate) rich_metadata: RichMetadataOutcome, pub(crate) models_authoritative: bool, + pub(crate) session_reads: SessionReads, + /// A digest of the binary path and environment the probe launched with. + pub(crate) launch_inputs: u64, + /// [`Self::launch_inputs`] with the configured custom models: what a reused catalog keys on. + pub(crate) catalog_inputs: u64, } impl ProviderProbeResult { @@ -123,6 +175,7 @@ impl ProviderProbeResult { snapshot, rich_metadata, models_authoritative: rich_metadata == RichMetadataOutcome::Succeeded, + ..Self::default() } } @@ -138,16 +191,74 @@ pub(crate) async fn probe( cwd: &Path, maintenance: &ProviderMaintenance, ) -> Vec { - probe_inner(settings, selected, cwd, false, maintenance).await + probe_inner( + settings, + selected, + cwd, + false, + maintenance, + None, + &HashSet::new(), + ) + .await } +/// Probes with the slow capabilities too. `attribution` attributes the processes the probe +/// starts, when the runtime has attached a registry. pub(crate) async fn probe_full( settings: &Value, selected: Option<&str>, cwd: &Path, maintenance: &ProviderMaintenance, + attribution: Option<&ProcessAttributionRegistry>, +) -> Vec { + probe_full_reusing( + settings, + selected, + cwd, + maintenance, + attribution, + &HashSet::new(), + ) + .await +} + +/// [`probe_full`] that keeps the last ACP catalog of the instances in `reuse` instead of +/// probing it again (see [`antigravity_catalog_inputs`]). +pub(crate) async fn probe_full_reusing( + settings: &Value, + selected: Option<&str>, + cwd: &Path, + maintenance: &ProviderMaintenance, + attribution: Option<&ProcessAttributionRegistry>, + reuse: &HashSet, ) -> Vec { - probe_inner(settings, selected, cwd, true, maintenance).await + probe_inner( + settings, + selected, + cwd, + true, + maintenance, + attribution, + reuse, + ) + .await +} + +/// The enabled Antigravity instances, each with the inputs of its catalog read (a digest: the +/// environment carries the stored secrets). An Antigravity probe opens a session in the user's +/// account, so after a signed-in read with these same inputs a full refresh within the refresh +/// TTL may reuse its catalog. Cursor's model list is always read again; the session it opens to +/// read the advertised model values is opened once per CLI and model list. +pub(crate) fn antigravity_catalog_inputs(settings: &Value) -> HashMap { + definitions(settings) + .into_iter() + .filter(|definition| definition.driver == "antigravity" && definition.enabled) + .map(|definition| { + let inputs = catalog_inputs(&definition); + (definition.instance_id, inputs) + }) + .collect() } async fn probe_inner( @@ -156,6 +267,8 @@ async fn probe_inner( cwd: &Path, include_slow_capabilities: bool, maintenance: &ProviderMaintenance, + attribution: Option<&ProcessAttributionRegistry>, + reuse: &HashSet, ) -> Vec { let checks_enabled = settings .get("enableProviderUpdateChecks") @@ -166,12 +279,15 @@ async fn probe_inner( .into_iter() .filter(|definition| selected.is_none_or(|id| id == definition.instance_id)) .map(|definition| { + let reuse_catalog = reuse.contains(&definition.instance_id); probe_one( definition, cwd, include_slow_capabilities, checks_enabled, maintenance, + attribution, + reuse_catalog, ) }), ) @@ -183,10 +299,10 @@ fn provider_is_enabled(driver: &str, configured: bool) -> bool { } fn default_provider_binary(driver: &str) -> &str { - if driver == "cursor" { - "cursor-agent" - } else { - driver + match driver { + "cursor" => "cursor-agent", + "antigravity" => "agy", + other => other, } } @@ -237,15 +353,10 @@ fn definitions(settings: &Value) -> Vec { .map(str::to_owned), enabled: provider_is_enabled( driver, - instance - .get("enabled") - .and_then(Value::as_bool) - .or_else(|| { - legacy_settings - .and_then(|value| value.get("enabled")) - .and_then(Value::as_bool) - }) - .unwrap_or(true), + crate::server_settings::provider_instance_enabled( + settings, + instance_id, + ), ), binary_path: string_setting(config, "binaryPath") .or_else(|| string_setting(legacy_settings, "binaryPath")) @@ -269,16 +380,31 @@ fn definitions(settings: &Value) -> Vec { .filter(|value| !value.is_empty()) .map(str::to_owned), environment: provider_environment(instance), + missing_secret: instance + .get("environment") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|entry| entry["valueRedacted"] == true), + secret_values: secret_values(instance), } }) .collect::>() }) .unwrap_or_default(); - for driver in ["codex", "claudeAgent", "cursor", "grok", "opencode"] { + for driver in [ + "codex", + "claudeAgent", + "cursor", + "grok", + "opencode", + "antigravity", + ] { + // A configured instance may own a built-in's id from before that driver existed. if definitions .iter() - .any(|definition| definition.driver == driver) + .any(|definition| definition.driver == driver || definition.instance_id == driver) { continue; } @@ -288,12 +414,10 @@ fn definitions(settings: &Value) -> Vec { instance_id: driver.to_owned(), driver: driver.to_owned(), display_name: None, + // Raw settings carry no defaults; Antigravity must stay off until enabled. enabled: provider_is_enabled( driver, - driver_settings - .and_then(|value| value.get("enabled")) - .and_then(Value::as_bool) - .unwrap_or(true), + crate::server_settings::provider_instance_enabled(settings, driver), ), binary_path: string_setting(driver_settings, "binaryPath") .unwrap_or_else(|| default_provider_binary(driver)) @@ -311,6 +435,8 @@ fn definitions(settings: &Value) -> Vec { .filter(|value| !value.is_empty()) .map(str::to_owned), environment: Vec::new(), + missing_secret: false, + secret_values: Vec::new(), }); } definitions @@ -373,6 +499,20 @@ fn string_array(value: Option<&Value>, name: &str) -> Option> { ) } +/// The values of the instance's sensitive variables that were supplied (not redacted). +fn secret_values(instance: &Value) -> Vec { + instance + .get("environment") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|entry| entry["sensitive"] == true && entry["valueRedacted"] != true) + .filter_map(|entry| entry.get("value").and_then(Value::as_str)) + .filter(|value| !value.is_empty()) + .map(str::to_owned) + .collect() +} + fn provider_environment(instance: &Value) -> Vec<(OsString, OsString)> { let environment = instance .get("environment") @@ -414,19 +554,46 @@ async fn probe_one( include_slow_capabilities: bool, checks_enabled: bool, maintenance: &ProviderMaintenance, + attribution: Option<&ProcessAttributionRegistry>, + reuse_catalog: bool, ) -> ProviderProbeResult { // A driver this build does not ship has no binary to look up or version to advise on. if !definition.available { return unavailable_result(&definition); } let target = maintenance_target_from_definition(&definition); - let mut result = probe_one_snapshot(&definition, cwd, include_slow_capabilities).await; + let mut result = probe_one_snapshot( + &definition, + cwd, + include_slow_capabilities, + attribution, + reuse_catalog, + ) + .await; + result.launch_inputs = launch_inputs(&definition); + result.catalog_inputs = catalog_inputs(&definition); maintenance .enrich_snapshot(&target, &mut result.snapshot, checks_enabled) .await; result } +/// A digest of what a probe and a chat launch with: the binary path and the environment. +fn launch_inputs(definition: &ProviderDefinition) -> u64 { + use std::hash::{DefaultHasher, Hash, Hasher}; + let mut hasher = DefaultHasher::new(); + (&definition.binary_path, &definition.environment).hash(&mut hasher); + hasher.finish() +} + +/// The launch inputs and the custom models: a catalog read with other ones is read again. +fn catalog_inputs(definition: &ProviderDefinition) -> u64 { + use std::hash::{DefaultHasher, Hash, Hasher}; + let mut hasher = DefaultHasher::new(); + (launch_inputs(definition), &definition.custom_models).hash(&mut hasher); + hasher.finish() +} + fn maintenance_target_from_definition( definition: &ProviderDefinition, ) -> ProviderMaintenanceTarget { @@ -479,7 +646,7 @@ pub(crate) async fn probe_maintenance_target_version( version_output .as_ref() .filter(|output| output.success) - .and_then(|output| first_line(&output.stdout, &output.stderr)), + .and_then(|output| version_line(&target.driver, output)), ); if target.driver != "cursor" { return version; @@ -518,10 +685,14 @@ pub(crate) fn unsupported_instances(settings: &Value) -> Vec, + reuse_catalog: bool, ) -> ProviderProbeResult { if !definition.available { return unavailable_result(definition); @@ -728,12 +899,19 @@ async fn probe_one_snapshot( ); } - let version_output = - run_command(&executable, &["--version"], cwd, &definition.environment).await; + let version_output = if definition.driver == "antigravity" { + run_antigravity_version(&executable, cwd, &definition.environment, attribution).await + } else { + run_command(&executable, &["--version"], cwd, &definition.environment).await + }; let version = version_output .as_ref() - .and_then(|output| first_line(&output.stdout, &output.stderr)); - let version = normalize_provider_version(&definition.driver, version); + // A failed Antigravity `--version` may print anything, an account included. + .filter(|output| output.success || definition.driver != "antigravity") + .and_then(|output| version_line(&definition.driver, output)); + // The peer's own text, before any parsing could strip what identifies a stored secret. + let mut raw_versions = version.iter().cloned().collect::>(); + let mut version = normalize_provider_version(&definition.driver, version); let mut installed = version_output.is_some(); let mut status = match version_output.as_ref() { Some(output) if output.success => "ready", @@ -753,6 +931,12 @@ async fn probe_one_snapshot( }; let mut versioned_model_catalog = false; + // A CLI that fails its version check keeps nothing an earlier session read. + let mut session_reads = if version_output.as_ref().is_some_and(|output| output.success) { + SessionReads::NotRead + } else { + SessionReads::Lost + }; match definition.driver.as_str() { "codex" => { if include_slow_capabilities @@ -802,6 +986,7 @@ async fn probe_one_snapshot( if include_slow_capabilities && let Some(discovered) = probe_cursor_models( &executable, + about.version.as_deref(), definition.endpoint.as_deref(), &definition.custom_models, cwd, @@ -916,10 +1101,75 @@ async fn probe_one_snapshot( "grok" if version_output.as_ref().is_some_and(|output| output.success) => { rich_metadata = RichMetadataOutcome::Succeeded; } + "antigravity" + if include_slow_capabilities + && !reuse_catalog + && version_output.as_ref().is_some_and(|output| output.success) => + { + // A stored secret that could not be read: probing without it would read another + // account than the chat launches with (which refuses to start), so nothing is read. + let catalog = if definition.missing_secret { + message = Some(ANTIGRAVITY_MISSING_SECRET_MESSAGE); + None + } else { + probe_antigravity_catalog( + &definition.instance_id, + &executable, + &definition.custom_models, + &definition.environment, + attribution, + ) + .await + }; + // A session that could not be opened or answered keeps nothing an earlier one read. + session_reads = if catalog.is_some() { + SessionReads::Read + } else { + SessionReads::Lost + }; + match catalog { + Some(AntigravityCatalog::Session { + models: discovered, + version: agent_version, + }) => { + auth = json!({ "status": "authenticated" }); + if let Some(agent_version) = agent_version { + if let Some(release) = release_version(&agent_version) { + version = Some(release); + } + raw_versions.push(agent_version); + } + // A reply that listed no model keeps the last catalog until the next probe. + if let Some(discovered) = discovered { + models = discovered; + rich_metadata = RichMetadataOutcome::Succeeded; + } + } + Some(AntigravityCatalog::SignInRequired) => { + // Still ready: the terminal is where the user signs in. + auth = json!({ "status": "unauthenticated" }); + message = Some(ANTIGRAVITY_SIGN_IN_MESSAGE); + // The signed-out account's catalog is gone with it. + versioned_model_catalog = true; + } + None => {} + } + } _ => {} } - let result = ProviderProbeResult::new( + // A CLI that echoes its environment can print a secret shaped like a release number. The + // raw text is checked, since the parser drops a leading `v` (`v1.2.3` publishes `1.2.3`). + let leaks_secret = raw_versions.iter().any(|raw| { + definition.secret_values.iter().any(|secret| { + raw.contains(secret.as_str()) + || secret + .strip_prefix('v') + .is_some_and(|bare| !bare.is_empty() && raw.contains(bare)) + }) + }); + let version = version.filter(|_| !leaks_secret); + let mut result = ProviderProbeResult::new( snapshot( definition, installed, @@ -934,6 +1184,7 @@ async fn probe_one_snapshot( ), rich_metadata, ); + result.session_reads = session_reads; if versioned_model_catalog { result.with_authoritative_models() } else { @@ -1481,41 +1732,236 @@ async fn probe_codex( result } -async fn probe_cursor_models( +enum AntigravityCatalog { + /// A session opened, so the CLI is signed in. `models` is `None` when the reply listed no + /// model; `version` is the handshake's raw `agentInfo.version`, checked against the stored + /// secrets before it is parsed. + Session { + models: Option>, + version: Option, + }, + SignInRequired, +} + +/// An inventory probe's child, stopped and reaped however the probe ends. A probe dropped +/// mid-way signals the whole process group at once and hands only the reap to the runtime, so +/// a reap task dropped unpolled, or no runtime at all, leaves no descendant running. The +/// attribution ends after the reap. +struct ProbeChild { + child: Option>, + registration: Option, +} + +impl ProbeChild { + async fn stop(mut self) { + // Kept in place while it stops: a cancelled stop leaves the reap to `Drop`. + if let Some(child) = self.child.as_mut() { + stop_supervised_child(&mut **child).await; + } + self.child = None; + } + + /// The exit status of a child that ended on its own, waiting up to a second for it; `None` + /// while it runs. + async fn exited_on_its_own(&self) -> Option { + let child = self.child.as_deref()?; + let deadline = tokio::time::Instant::now() + Duration::from_secs(1); + loop { + if let Some(status) = crate::process::exited_status(child) { + return Some(status); + } + if tokio::time::Instant::now() >= deadline { + return None; + } + sleep(Duration::from_millis(20)).await; + } + } +} + +impl Drop for ProbeChild { + fn drop(&mut self) { + let Some(mut child) = self.child.take() else { + return; + }; + // The group kill, sent here rather than from a task that may never run. + let _ = child.start_kill(); + let registration = self.registration.take(); + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + runtime.spawn(async move { + stop_supervised_child(&mut *child).await; + drop(registration); + }); + } + } +} + +/// Ends an ACP probe's transport however the probe ends: the writer task, which owns the +/// agent's stdin, stops at once, and the readers end when the agent's output closes. +struct AcpProbeTransport(cursor::AcpJsonRpcConnection); + +impl AcpProbeTransport { + /// Spawns the transport and discards the agent's notifications, requests and stderr as + /// they arrive: the probe reads only responses. + fn spawn(stdout: R, stdin: W, stderr: E) -> Self + where + R: tokio::io::AsyncRead + Unpin + Send + 'static, + W: tokio::io::AsyncWrite + Unpin + Send + 'static, + E: tokio::io::AsyncRead + Unpin + Send + 'static, + { + let (connection, mut incoming) = cursor::AcpJsonRpcConnection::spawn( + stdout, + stdin, + stderr, + cursor::AcpConnectionConfig::default(), + ); + tokio::spawn(async move { while incoming.recv().await.is_some() {} }); + Self(connection) + } +} + +impl Drop for AcpProbeTransport { + fn drop(&mut self) { + self.0.shutdown(); + } +} + +fn warn_antigravity_probe(instance_id: &str, step: &str, failure: &str) { + tracing::warn!( + instance_id, + step, + failure, + "the Antigravity inventory probe read no models" + ); +} + +/// The process attribution of an Antigravity inventory child, `None` when the registry refuses. +fn register_antigravity_probe( + registry: &ProcessAttributionRegistry, + pid: u32, + label: &str, +) -> Option { + let identity = NativeProcessSampler::process_identity(pid).ok()?; + registry + .register_identity( + identity, + ProcessRegistrationMetadata { + scope: AttributionScope::External, + kind: AttributionKind::Provider, + label: label.to_owned(), + source: RegistrationSource::Provider, + driver: Some("antigravity".to_owned()), + survives_shutdown: false, + }, + ) + .ok() +} + +/// `agy --version`, supervised and attributed while it runs. +async fn run_antigravity_version( executable: &Path, - endpoint: Option<&str>, - custom_models: &[String], cwd: &Path, environment: &[(OsString, OsString)], -) -> Option> { - let mut arguments = Vec::new(); - if let Some(endpoint) = endpoint.filter(|value| !value.trim().is_empty()) { - arguments.extend([OsString::from("-e"), OsString::from(endpoint)]); - } - arguments.push(OsString::from("acp")); - let launch = prepare_provider_launch(executable, &arguments).ok()?; + attribution: Option<&ProcessAttributionRegistry>, +) -> Option { + let launch = prepare_provider_launch(executable, ["--version"]).ok()?; let mut command = Command::new(launch.program); command .args(launch.args) .current_dir(cwd) - .envs(environment.iter().cloned()); + .envs(environment.iter().cloned()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + sanitize_provider_subprocess_environment(&mut command); + let registration = std::sync::Mutex::new(None); + let output = run_supervised_with_spawn_observer( + SupervisedRunRequest { + command, + stdin: None, + timeout: PROBE_TIMEOUT, + cleanup_timeout: Duration::from_secs(2), + max_output_bytes: PROBE_OUTPUT_LIMIT, + overflow: SupervisedOverflow::Truncate, + stop_policy: StopPolicy::Force, + }, + &CancellationToken::new(), + |pid| { + if let (Some(registry), Some(pid)) = (attribution, pid) { + *registration.lock().unwrap_or_else(PoisonError::into_inner) = + register_antigravity_probe(registry, pid, "Antigravity version check"); + } + }, + ) + .await + .ok()?; + let code = output.status.code().unwrap_or(-1); + Some(CommandOutput { + success: output.status.success(), + code, + stdout: String::from_utf8_lossy(&output.stdout.bytes).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr.bytes).into_owned(), + }) +} + +/// Opens and closes one empty ACP session to read the models, thinking levels, sign-in state +/// and version. No prompt is sent. A peer that answers another protocol version than 1 gets no +/// session. Logs carry the step and the error code, never the CLI's text. +async fn probe_antigravity_catalog( + instance_id: &str, + executable: &Path, + configured_models: &[String], + environment: &[(OsString, OsString)], + attribution: Option<&ProcessAttributionRegistry>, +) -> Option { + // A neutral directory: the probe session must not open a user's checkout. + let session_cwd = std::env::temp_dir(); + let launch = prepare_provider_launch(executable, ["acp"]).ok()?; + let mut command = Command::new(launch.program); command + .args(launch.args) + .current_dir(&session_cwd) + .envs(environment.iter().cloned()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); sanitize_provider_subprocess_environment(&mut command); - let mut child = supervised_command(command).spawn().ok()?; - let stdout = child.stdout().take()?; - let stdin = child.stdin().take()?; - let stderr = child.stderr().take()?; - let (connection, _incoming) = cursor::AcpJsonRpcConnection::spawn( - stdout, - stdin, - stderr, - cursor::AcpConnectionConfig::default(), + let Ok(mut spawned) = supervised_command(command).spawn() else { + warn_antigravity_probe(instance_id, "launch", "could not start"); + return None; + }; + let started = std::time::Instant::now(); + let pid = spawned.id(); + let pipes = ( + spawned.stdout().take(), + spawned.stdin().take(), + spawned.stderr().take(), ); - let response = timeout(CURSOR_DISCOVERY_TIMEOUT, async { - connection + let registration = match attribution { + Some(registry) => { + let registration = pid.and_then(|pid| { + register_antigravity_probe(registry, pid, "Antigravity inventory probe") + }); + if registration.is_none() { + stop_supervised_child(&mut *spawned).await; + warn_antigravity_probe(instance_id, "launch", "could not attribute the process"); + return None; + } + registration + } + None => None, + }; + let child = ProbeChild { + child: Some(spawned), + registration, + }; + let (Some(stdout), Some(stdin), Some(stderr)) = pipes else { + child.stop().await; + return None; + }; + let transport = AcpProbeTransport::spawn(stdout, stdin, stderr); + let connection = &transport.0; + let handshake = timeout(ANTIGRAVITY_DISCOVERY_TIMEOUT, async { + let initialize = connection .request( "initialize", json!({ @@ -1527,75 +1973,514 @@ async fn probe_cursor_models( "clientInfo": { "name": "bibcode-rust", "version": env!("CARGO_PKG_VERSION") }, }), ) - .await - .ok()?; - connection - .request("authenticate", json!({ "methodId": "cursor_login" })) - .await - .ok()?; - connection - .request("cursor/list_available_models", json!({})) - .await - .ok() + .await?; + if initialize.get("protocolVersion").and_then(Value::as_u64) != Some(1) { + return Ok(None); + } + let session = connection + .request( + "session/new", + json!({ "cwd": session_cwd.to_string_lossy(), "mcpServers": [] }), + ) + .await?; + Ok::<_, cursor::acp::AcpProtocolError>(Some((initialize, session))) }) - .await - .ok() - .flatten(); - stop_supervised_child(&mut *child).await; - let models = - cursor::discover_models_from_list_available_models(&response?, custom_models).ok()?; - serde_json::to_value(models) - .ok() - .and_then(|value| value.as_array().cloned()) + .await; + let catalog = match handshake { + Ok(Ok(Some((initialize, session)))) => { + // The catalog is read; the close gets its own short step and never costs it. + if let Some(session_id) = session.get("sessionId").and_then(Value::as_str) + && antigravity_advertises_close(&initialize) + { + let close = connection.request("session/close", json!({ "sessionId": session_id })); + if timeout(ANTIGRAVITY_CLOSE_TIMEOUT, close).await.is_err() { + warn_antigravity_probe(instance_id, "session/close", "timed out"); + } + } + let models = antigravity_models(&session, configured_models); + if models.is_none() { + warn_antigravity_probe(instance_id, "session/new", "no models in the reply"); + } + Some(AntigravityCatalog::Session { + models, + version: initialize + .pointer("/agentInfo/version") + .and_then(Value::as_str) + .map(str::to_owned), + }) + } + Ok(Ok(None)) => { + warn_antigravity_probe(instance_id, "initialize", "unsupported protocol version"); + None + } + Ok(Err(cursor::acp::AcpProtocolError::RemoteRequest { + code: -32000, + message, + .. + })) if message + .trim() + .eq_ignore_ascii_case("authentication required") => + { + Some(AntigravityCatalog::SignInRequired) + } + Ok(Err(cursor::acp::AcpProtocolError::RemoteRequest { method, code, .. })) => { + warn_antigravity_probe(instance_id, &method, &format!("error {code}")); + None + } + Ok(Err(_)) => { + warn_antigravity_probe(instance_id, "probe", "connection failed"); + // The connection fails when the child dies; one that died on its own is a crash. + if exits::watching() + && let (Some(pid), Some(status)) = (pid, child.exited_on_its_own().await) + { + exits::report_exit( + Watch::Failures, + &Exited { + kind: "provider", + label: "antigravity", + exe: &executable.to_string_lossy(), + pid, + started, + }, + &status, + false, + ); + } + None + } + Err(_) => { + warn_antigravity_probe(instance_id, "probe", "timed out"); + None + } + }; + drop(transport); + child.stop().await; + catalog } -/// The wire a configured OpenCode server speaks, or the version it reports when BiBCode cannot -/// drive it. A server that does not answer is read as OpenCode 1, as before. -pub(super) async fn opencode_server_protocol( - endpoint: &str, - server_password: Option<&str>, -) -> Result { - let Ok(client) = reqwest::Client::builder() - .timeout(opencode::API_PROBE_TIMEOUT) - .build() - else { - return Ok(opencode::OpenCodeProtocol::V1); - }; - match opencode::probe_server_api(&client, endpoint, server_password).await { - opencode::OpenCodeServerApi::V2 { .. } => Ok(opencode::OpenCodeProtocol::V2), - opencode::OpenCodeServerApi::Unsupported { version } => Err(version), - opencode::OpenCodeServerApi::V1 | opencode::OpenCodeServerApi::Unavailable => { - Ok(opencode::OpenCodeProtocol::V1) - } - } +/// Whether `initialize` advertises `session/close`, under either key spelling the CLI writes. +fn antigravity_advertises_close(initialize: &Value) -> bool { + let capabilities = initialize + .get("agentCapabilities") + .or_else(|| initialize.get("agent_capabilities")); + ["sessionCapabilities", "session_capabilities"] + .iter() + .filter_map(|key| capabilities?.get(key)?.get("close")) + .any(|close| !close.is_null() && close != &Value::Bool(false)) } -async fn probe_opencode( - endpoint: &str, - server_password: Option<&str>, - custom_models: &[String], - protocol: opencode::OpenCodeProtocol, - cwd: &Path, -) -> Option { - probe_opencode_with_timeout( - endpoint, - server_password, - custom_models, - PROBE_TIMEOUT, - protocol, - cwd, - ) - .await +/// The first `major.minor.patch` in peer text, `None` when it holds none. +fn release_version(text: &str) -> Option { + text.split(|character: char| !character.is_ascii_digit() && character != '.') + .find_map(|token| { + let parts = token.split('.').take(3).collect::>(); + (parts.len() == 3 && parts.iter().all(|part| !part.is_empty())).then(|| parts.join(".")) + }) } -/// OpenCode 2 catalogs are read for `cwd`, the directory BiBCode's sessions use; OpenCode 1 -/// inventory reads stay unscoped, as they always were. -async fn probe_opencode_with_timeout( - endpoint: &str, - server_password: Option<&str>, - custom_models: &[String], - request_timeout: Duration, - protocol: opencode::OpenCodeProtocol, +/// The models a `session/new` answer advertises, in the CLI's order with its current model +/// first (the web picker's default is the first model), then the configured custom models it +/// does not list. Each model carries its own `reasoning` options: the current model's from the +/// `thought_level` option, the others' from their effort-suffixed `availableModels` ids, with a +/// default only where the CLI names one. Without model options the `availableModels` ids are +/// published unchanged. Repeated models and levels are listed once. `None` when the answer +/// lists no model. +fn antigravity_models(session: &Value, configured_models: &[String]) -> Option> { + let options = session + .get("configOptions") + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or_default(); + // The chat runtime's lookup: what is published here is what a turn can select. + let option = |category: &str| { + crate::provider::antigravity::runtime::option_by_category(options, category) + }; + let available = unique( + session + .pointer("/models/availableModels") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|model| { + let id = model.get("modelId")?.as_str()?; + Some((id, model.get("name").and_then(Value::as_str).unwrap_or(id))) + }), + ); + let model = option("model"); + let values = unique( + model + .and_then(|model| model.get("options")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|option| { + let value = option.get("value")?.as_str()?; + Some(( + value, + option.get("name").and_then(Value::as_str).unwrap_or(value), + )) + }), + ); + let (mut models, current) = if values.is_empty() { + ( + available + .iter() + .map(|&(id, name)| antigravity_model(id, name, None, &[])) + .collect::>(), + session + .pointer("/models/currentModelId") + .and_then(Value::as_str), + ) + } else { + let thought = option("thought_level"); + let label = thought + .and_then(|thought| thought.get("name")) + .and_then(Value::as_str); + let known = unique( + thought + .and_then(|thought| thought.get("options")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|option| { + let value = option.get("value")?.as_str()?; + Some(( + value, + option.get("name").and_then(Value::as_str).unwrap_or(value), + )) + }), + ); + let current_level = thought + .and_then(|thought| thought.get("currentValue")) + .and_then(Value::as_str); + let current = model + .and_then(|model| model.get("currentValue")) + .and_then(Value::as_str); + let models = values + .iter() + .map(|&(value, name)| { + let levels = if Some(value) == current && !known.is_empty() { + known + .iter() + .map(|&(level, label)| (level, label, Some(level) == current_level)) + .collect() + } else { + antigravity_model_levels(value, &values, &available, &known) + }; + antigravity_model(value, name, label, &levels) + }) + .collect(); + (models, current) + }; + if models.is_empty() { + return None; + } + if let Some(position) = models + .iter() + .position(|model| model["slug"].as_str() == current) + { + models[..=position].rotate_right(1); + } + let listed = models + .iter() + .filter_map(|model| model["slug"].as_str().map(str::to_owned)) + .collect::>(); + let unlisted = configured_models + .iter() + .filter(|slug| !listed.contains(slug.as_str())) + .cloned() + .collect::>(); + models.extend(custom_models(&unlisted)); + Some(models) +} + +/// The `(id, name)` pairs in order, each id once. +fn unique<'a>(pairs: impl Iterator) -> Vec<(&'a str, &'a str)> { + let mut seen = HashSet::new(); + pairs.filter(|(id, _)| seen.insert(*id)).collect() +} + +/// One catalog model, its thinking levels published as the `reasoning` option under the CLI's +/// own ids, which a chat sends back as ACP `thought_level` unchanged. +fn antigravity_model( + slug: &str, + name: &str, + label: Option<&str>, + levels: &[(&str, &str, bool)], +) -> Value { + let descriptors = if levels.is_empty() { + Vec::new() + } else { + vec![json!({ + "id": "reasoning", + "label": label.unwrap_or(cursor::model::REASONING_LABEL), + "type": "select", + "options": levels.iter().map(|&(id, label, default)| if default { + json!({ "id": id, "label": label, "isDefault": true }) + } else { + json!({ "id": id, "label": label }) + }).collect::>(), + })] + }; + json!({ + "slug": slug, + "name": name, + "isCustom": false, + "capabilities": { "optionDescriptors": descriptors }, + }) +} + +/// A model's thinking levels, read from the `availableModels` ids made of its value, `-` and a +/// level. An id that is itself a model value is that model, never a level. Any other id belongs +/// to the longest model value it extends, so `alpha-pro-high` is a level of `alpha-pro`, not of +/// `alpha`. Levels the `thought_level` option lists keep its order and names; others follow in +/// the CLI's order under their own id. No level is a default. +fn antigravity_model_levels<'a>( + value: &str, + values: &[(&'a str, &'a str)], + available: &[(&'a str, &'a str)], + known: &[(&'a str, &'a str)], +) -> Vec<(&'a str, &'a str, bool)> { + let owner = |id: &str| { + if values.iter().any(|&(value, _)| value == id) { + return None; + } + values + .iter() + .map(|&(value, _)| value) + .filter(|value| { + id.strip_prefix(value) + .is_some_and(|rest| rest.len() > 1 && rest.starts_with('-')) + }) + .max_by_key(|value| value.len()) + }; + let known_index = |level: &str| known.iter().position(|&(known, _)| known == level); + let mut levels = available + .iter() + .map(|&(id, _)| id) + .filter(|id| owner(id) == Some(value)) + .map(|id| &id[value.len() + 1..]) + .collect::>(); + levels.sort_by_key(|level| known_index(level).unwrap_or(usize::MAX)); + levels + .into_iter() + .map(|level| { + let name = known_index(level).map_or(level, |index| known[index].1); + (level, name, false) + }) + .collect() +} + +/// How long a failed read of Cursor's advertised model values is remembered before a refresh +/// opens another session. +const CURSOR_SESSION_READ_BACKOFF: Duration = Duration::from_secs(5 * 60); + +/// One launch environment's read of the model values Cursor advertises in a session. +enum CursorSessionRead { + Read(Vec), + Failed(tokio::time::Instant), +} + +/// The model values each Cursor launch environment advertises in a session, by executable, +/// version, endpoint, model list and instance environment. Reading them opens a session in the +/// user's Cursor account that ACP cannot close (an empty one, which Cursor does not list), so it +/// is read once per key: a refresh that finds a read in flight waits for it, and a failed read is +/// remembered for [`CURSOR_SESSION_READ_BACKOFF`]. +type CursorSessionReads = + std::sync::Mutex>>>>; +static CURSOR_ADVERTISED_MODEL_VALUES: std::sync::OnceLock = + std::sync::OnceLock::new(); + +/// The advertised values for `key`, read by `read` at most once per key at a time. +async fn shared_cursor_session_read(key: u64, read: F) -> Vec +where + F: Future>>, +{ + let slot = CURSOR_ADVERTISED_MODEL_VALUES + .get_or_init(Default::default) + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .entry(key) + .or_default() + .clone(); + let mut slot = slot.lock().await; + match &*slot { + Some(CursorSessionRead::Read(advertised)) => return advertised.clone(), + Some(CursorSessionRead::Failed(at)) if at.elapsed() < CURSOR_SESSION_READ_BACKOFF => { + return Vec::new(); + } + _ => {} + } + match timeout(CURSOR_SESSION_READ_TIMEOUT, read).await { + Ok(Some(advertised)) => { + *slot = Some(CursorSessionRead::Read(advertised.clone())); + advertised + } + // A session that cannot be read publishes the list as is. + _ => { + *slot = Some(CursorSessionRead::Failed(tokio::time::Instant::now())); + Vec::new() + } + } +} + +async fn probe_cursor_models( + executable: &Path, + version: Option<&str>, + endpoint: Option<&str>, + custom_models: &[String], + cwd: &Path, + environment: &[(OsString, OsString)], +) -> Option> { + let mut arguments = Vec::new(); + if let Some(endpoint) = endpoint.filter(|value| !value.trim().is_empty()) { + arguments.extend([OsString::from("-e"), OsString::from(endpoint)]); + } + arguments.push(OsString::from("acp")); + let launch = prepare_provider_launch(executable, &arguments).ok()?; + let mut command = Command::new(launch.program); + command + .args(launch.args) + .current_dir(cwd) + .envs(environment.iter().cloned()); + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + sanitize_provider_subprocess_environment(&mut command); + let mut spawned = supervised_command(command).spawn().ok()?; + let pipes = ( + spawned.stdout().take(), + spawned.stdin().take(), + spawned.stderr().take(), + ); + // A refresh that drops this probe still stops the whole group. + let child = ProbeChild { + child: Some(spawned), + registration: None, + }; + let (Some(stdout), Some(stdin), Some(stderr)) = pipes else { + child.stop().await; + return None; + }; + let transport = AcpProbeTransport::spawn(stdout, stdin, stderr); + let connection = &transport.0; + let list = timeout(CURSOR_DISCOVERY_TIMEOUT, async { + connection + .request( + "initialize", + json!({ + "protocolVersion": 1, + "clientCapabilities": { + "fs": { "readTextFile": false, "writeTextFile": false }, + "terminal": false, + // As the runtime asks, so the session read sees the values it will use. + "_meta": { "parameterizedModelPicker": true }, + }, + "clientInfo": { "name": "bibcode-rust", "version": env!("CARGO_PKG_VERSION") }, + }), + ) + .await + .ok()?; + connection + .request("authenticate", json!({ "methodId": "cursor_login" })) + .await + .ok()?; + connection + .request("cursor/list_available_models", json!({})) + .await + .ok() + }) + .await + .ok() + .flatten(); + // The optional session read starts only once the list is in hand, under its own deadline. + let response = match list { + Some(list) => { + let mut listed = list + .get("models") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|model| model.get("value").and_then(Value::as_str)) + .collect::>(); + listed.sort_unstable(); + let mut environment = environment.to_vec(); + environment.sort(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (executable, version, endpoint, listed, environment).hash(&mut hasher); + let advertised = shared_cursor_session_read(hasher.finish(), async { + connection + .request( + "session/new", + json!({ "cwd": cwd.to_string_lossy(), "mcpServers": [] }), + ) + .await + .ok() + .map(|session| cursor::advertised_model_values(&session)) + }) + .await; + Some((list, advertised)) + } + None => None, + }; + drop(transport); + child.stop().await; + let (list, advertised) = response?; + let models = + cursor::discover_models_with_advertised_values(&list, custom_models, &advertised).ok()?; + serde_json::to_value(models) + .ok() + .and_then(|value| value.as_array().cloned()) +} + +/// The wire a configured OpenCode server speaks, or the version it reports when BiBCode cannot +/// drive it. A server that does not answer is read as OpenCode 1, as before. +pub(super) async fn opencode_server_protocol( + endpoint: &str, + server_password: Option<&str>, +) -> Result { + let Ok(client) = reqwest::Client::builder() + .timeout(opencode::API_PROBE_TIMEOUT) + .build() + else { + return Ok(opencode::OpenCodeProtocol::V1); + }; + match opencode::probe_server_api(&client, endpoint, server_password).await { + opencode::OpenCodeServerApi::V2 { .. } => Ok(opencode::OpenCodeProtocol::V2), + opencode::OpenCodeServerApi::Unsupported { version } => Err(version), + opencode::OpenCodeServerApi::V1 | opencode::OpenCodeServerApi::Unavailable => { + Ok(opencode::OpenCodeProtocol::V1) + } + } +} + +async fn probe_opencode( + endpoint: &str, + server_password: Option<&str>, + custom_models: &[String], + protocol: opencode::OpenCodeProtocol, + cwd: &Path, +) -> Option { + probe_opencode_with_timeout( + endpoint, + server_password, + custom_models, + PROBE_TIMEOUT, + protocol, + cwd, + ) + .await +} + +/// OpenCode 2 catalogs are read for `cwd`, the directory BiBCode's sessions use; OpenCode 1 +/// inventory reads stay unscoped, as they always were. +async fn probe_opencode_with_timeout( + endpoint: &str, + server_password: Option<&str>, + custom_models: &[String], + request_timeout: Duration, + protocol: opencode::OpenCodeProtocol, cwd: &Path, ) -> Option { let client = reqwest::Client::builder() @@ -1874,8 +2759,24 @@ fn first_line(stdout: &str, stderr: &str) -> Option { .map(str::to_owned) } +/// The first line of a version check. Antigravity's never comes from stderr, where the CLI +/// may write anything. +fn version_line(driver: &str, output: &CommandOutput) -> Option { + let stderr = if driver == "antigravity" { + "" + } else { + &output.stderr + }; + first_line(&output.stdout, stderr) +} + fn normalize_provider_version(driver: &str, version: Option) -> Option { let version = version?; + // Only a release number is published: a CLI that prints anything else (its environment, + // a stored secret among it) publishes no version. + if driver == "antigravity" { + return release_version(&version); + } if driver != "codex" { return Some(version); } @@ -2045,8 +2946,11 @@ fn snapshot_owned_message( if matches!(definition.driver.as_str(), "codex" | "claudeAgent") { result["supportsMcpStatus"] = json!(true); } - if matches!(definition.driver.as_str(), "codex" | "claudeAgent") - || capabilities.context_window_usage + // Antigravity chats report ACP `usage_update` on every CLI the chat accepts. + if matches!( + definition.driver.as_str(), + "codex" | "claudeAgent" | "antigravity" + ) || capabilities.context_window_usage { result["supportsContextWindowUsage"] = json!(true); } @@ -2059,12 +2963,12 @@ fn snapshot_owned_message( fn is_builtin_driver(driver: &str) -> bool { matches!( driver, - "codex" | "claudeAgent" | "cursor" | "grok" | "opencode" + "codex" | "claudeAgent" | "cursor" | "grok" | "opencode" | "antigravity" ) } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; #[cfg(unix)] @@ -2288,7 +3192,7 @@ done check_inventory_probe_appimage_environment( "production::provider_inventory::tests::cursor_inventory_probe_ignores_appimage_environment", |executable, cwd, environment| async move { - probe_cursor_models(&executable, None, &[], &cwd, &environment) + probe_cursor_models(&executable, None, None, &[], &cwd, &environment) .await .is_some() }, @@ -2314,42 +3218,327 @@ done ); } + /// A Cursor CLI that folds options into bracketed model values: the inventory publishes only + /// what a session advertises, and opens that session once, not on every refresh. #[cfg(unix)] - fn write_version_fixture(directory: &Path, name: &str, version: &str) -> std::path::PathBuf { - let executable = directory.join(name); + #[tokio::test] + async fn cursor_inventory_publishes_only_advertised_values_and_opens_one_session() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let sessions = temp.path().join("sessions"); + let executable = temp.path().join("cursor-agent"); crate::test_support::executable_fixture::write_executable( &executable, format!( - "#!/bin/sh\nif [ \"$1\" = about ]; then printf '%s\\n' '{{\"cliVersion\":\"{version}\"}}'; else printf '%s\\n' '{version}'; fi\n" + r#"#!/bin/sh +while IFS= read -r line; do + id=${{line#*\"id\":}}; id=${{id%%[!0-9]*}} + case "$line" in + *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{{"jsonrpc":"2.0","id":%s,"result":{{}}}}\n' "$id" ;; + *'"method":"cursor/list_available_models"'*) printf '{{"jsonrpc":"2.0","id":%s,"result":{{"models":[{{"value":"m","name":"M","configOptions":[{{"id":"effort","category":"thought_level","type":"select","currentValue":"low","options":[{{"value":"low"}},{{"value":"high"}}]}}]}},{{"value":"gone","name":"Gone","configOptions":[]}}]}}}}\n' "$id" ;; + *'"method":"session/new"'*) printf 'opened\n' >> '{}'; printf '{{"jsonrpc":"2.0","id":%s,"result":{{"sessionId":"s","configOptions":[{{"id":"model","category":"model","type":"select","currentValue":"m[effort=high]","options":[{{"value":"m[effort=high]"}}]}}]}}}}\n' "$id" ;; + esac +done +"#, + sessions.display() ), ); - executable + let custom = ["mine".to_owned()]; + for _ in 0..2 { + let models = probe_cursor_models( + &executable, + Some("2026.11.22"), + None, + &custom, + temp.path(), + &[], + ) + .await + .expect("the fixture lists models"); + assert_eq!(models.len(), 1, "{models:?}"); + assert_eq!(models[0]["slug"], "m"); + let reasoning = &models[0]["capabilities"]["optionDescriptors"][0]; + assert_eq!(reasoning["id"], "reasoning"); + assert_eq!( + reasoning["options"], + json!([{ "id": "high", "label": "high", "isDefault": true }]) + ); + } + assert_eq!( + std::fs::read_to_string(&sessions).expect("a session was opened"), + "opened\n" + ); } + /// A Cursor CLI that switches to plain model names and separate options when BiBCode asks for + /// its parameterized model picker: Grok 4.7 publishes every Reasoning and Context value and + /// Fast. Without the request the CLI folds one combination into the model value. #[cfg(unix)] #[tokio::test] - async fn inventory_instance_path_outranks_ambient_path_in_an_isolated_process() { - const CASE: &str = "provider-inventory-path-precedence"; - const TEST_NAME: &str = "production::provider_inventory::tests::inventory_instance_path_outranks_ambient_path_in_an_isolated_process"; - const SENTINEL: &str = "BIBCODE_TEST_ISOLATED_CASE_DONE=provider-inventory-path-precedence"; + async fn cursor_inventory_publishes_every_grok_option_from_a_parameterized_session() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let executable = temp.path().join("cursor-agent"); + crate::test_support::executable_fixture::write_executable( + &executable, + r#"#!/bin/sh +picker=no +while IFS= read -r line; do + id=${line#*\"id\":}; id=${id%%[!0-9]*} + case "$line" in + *'"method":"initialize"'*'"parameterizedModelPicker":true'*) picker=yes; printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; + *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; + *'"method":"cursor/list_available_models"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"models":[{"value":"grok-4.7","name":"Grok 4.7","configOptions":[{"id":"context","category":"model_config","type":"select","currentValue":"256k","options":[{"value":"256k"},{"value":"500k"}]},{"id":"reasoning_effort","category":"thought_level","type":"select","currentValue":"high","options":[{"value":"low"},{"value":"medium"},{"value":"high"},{"value":"xhigh"}]},{"id":"fast","category":"model_config","type":"select","currentValue":"true","options":[{"value":"false"},{"value":"true"}]}]}]}}\n' "$id" ;; + *'"method":"session/new"'*) + if [ "$picker" = yes ]; then value='grok-4.7'; else value='grok-4.7[context=256k,reasoning_effort=high,fast=true]'; fi + printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s","configOptions":[{"id":"model","category":"model","type":"select","currentValue":"default","options":[{"value":"default"},{"value":"%s"}]}]}}\n' "$id" "$value" ;; + esac +done +"#, + ); + let models = + probe_cursor_models(&executable, Some("2026.11.22"), None, &[], temp.path(), &[]) + .await + .expect("the fixture lists models"); + assert_eq!(models.len(), 1, "{models:?}"); + assert_eq!(models[0]["slug"], "grok-4.7"); + let descriptors = &models[0]["capabilities"]["optionDescriptors"]; + let ids = |descriptor: &Value| { + descriptor["options"] + .as_array() + .unwrap() + .iter() + .map(|choice| choice["id"].as_str().unwrap().to_owned()) + .collect::>() + }; + assert_eq!(descriptors[0]["id"], "reasoning", "{descriptors}"); + assert_eq!(ids(&descriptors[0]), ["low", "medium", "high", "xhigh"]); + assert_eq!(descriptors[1]["id"], "contextWindow", "{descriptors}"); + assert_eq!(ids(&descriptors[1]), ["256k", "500k"]); + assert_eq!(descriptors[2]["id"], "fastMode", "{descriptors}"); + + // A custom model saved bracketed is not listed again beside its plain base model; one + // with no plain equivalent stays the user's entry. + let custom = [ + "grok-4.7[context=256k,reasoning_effort=high,fast=true]".to_owned(), + "mine[reasoning=high]".to_owned(), + ]; + let models = probe_cursor_models( + &executable, + Some("2026.11.22"), + None, + &custom, + temp.path(), + &[], + ) + .await + .expect("the fixture lists models"); + let listed = models + .iter() + .map(|model| (model["slug"].as_str(), model["isCustom"].as_bool())) + .collect::>(); + assert_eq!( + listed, + [ + (Some("grok-4.7"), Some(false)), + (Some("mine[reasoning=high]"), Some(true)) + ], + "{models:?}" + ); + } - if TestSandbox::is_isolated_case(CASE, TEST_NAME) { - let instance = std::path::PathBuf::from( - std::env::var_os("BIBCODE_TEST_INSTANCE_PATH").expect("isolated instance PATH"), - ); - let root = std::path::PathBuf::from( - std::env::var_os("BIBCODE_TEST_ROOT").expect("isolated inventory root"), - ); - let ambient_executable = std::path::PathBuf::from( - std::env::var_os("BIBCODE_TEST_AMBIENT_EXECUTABLE") - .expect("isolated ambient executable"), - ); - assert_eq!( - resolve_provider_executable_with_environment( - "cursor-agent", - std::iter::empty::<(&std::ffi::OsStr, &std::ffi::OsStr)>(), - ), - Some(ambient_executable), + /// A CLI that never answers the session read still publishes its model list, unnarrowed. + #[cfg(unix)] + #[tokio::test] + async fn cursor_inventory_keeps_the_list_when_the_session_read_hangs() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let executable = temp.path().join("cursor-agent"); + crate::test_support::executable_fixture::write_executable( + &executable, + r#"#!/bin/sh +while IFS= read -r line; do + id=${line#*\"id\":}; id=${id%%[!0-9]*} + case "$line" in + *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; + *'"method":"cursor/list_available_models"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"models":[{"value":"m","name":"M","configOptions":[{"id":"effort","category":"thought_level","type":"select","currentValue":"low","options":[{"value":"low"},{"value":"high"}]}]}]}}\n' "$id" ;; + esac +done +"#, + ); + let models = probe_cursor_models(&executable, None, None, &[], temp.path(), &[]) + .await + .expect("the list is published without the session read"); + assert_eq!(models.len(), 1); + assert_eq!( + models[0]["capabilities"]["optionDescriptors"][0]["options"] + .as_array() + .unwrap() + .len(), + 2 + ); + } + + /// A Cursor fixture whose `session/new` runs `session` (shell) and counts each call. + #[cfg(unix)] + fn cursor_session_fixture( + directory: &Path, + list_delay: &str, + session: &str, + ) -> (std::path::PathBuf, std::path::PathBuf) { + let sessions = directory.join("sessions"); + let executable = directory.join("cursor-agent"); + crate::test_support::executable_fixture::write_executable( + &executable, + format!( + r#"#!/bin/sh +while IFS= read -r line; do + id=${{line#*\"id\":}}; id=${{id%%[!0-9]*}} + case "$line" in + *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{{"jsonrpc":"2.0","id":%s,"result":{{}}}}\n' "$id" ;; + *'"method":"cursor/list_available_models"'*) sleep {list_delay}; printf '{{"jsonrpc":"2.0","id":%s,"result":{{"models":[{{"value":"m","name":"M","configOptions":[{{"id":"effort","category":"thought_level","type":"select","currentValue":"low","options":[{{"value":"low"}},{{"value":"high"}}]}}]}}]}}}}\n' "$id" ;; + *'"method":"session/new"'*) printf 'opened\n' >> '{sessions}'; {session} ;; + esac +done +"#, + sessions = sessions.display(), + ), + ); + (executable, sessions) + } + + #[cfg(unix)] + const ADVERTISE_HIGH: &str = r#"sleep 0.3; printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s","configOptions":[{"id":"model","category":"model","currentValue":"m[effort=high]","options":[{"value":"m[effort=high]"}]}]}}\n' "$id""#; + + #[cfg(unix)] + fn opened(sessions: &Path) -> usize { + std::fs::read_to_string(sessions).map_or(0, |text| text.lines().count()) + } + + /// Two refreshes of one Cursor read one session between them; an instance with another + /// environment reads its own, and never gets the first one's options. + #[cfg(unix)] + #[tokio::test] + async fn cursor_session_reads_are_shared_per_launch_environment() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let (executable, sessions) = cursor_session_fixture(temp.path(), "0", ADVERTISE_HIGH); + let probe = |environment: Vec<(OsString, OsString)>| { + let executable = executable.clone(); + let cwd = temp.path().to_path_buf(); + async move { + probe_cursor_models(&executable, Some("shared"), None, &[], &cwd, &environment) + .await + .expect("the fixture lists models") + } + }; + let account = |name: &str| vec![(OsString::from("CURSOR_ACCOUNT"), OsString::from(name))]; + let (first, second) = tokio::join!(probe(account("a")), probe(account("a"))); + assert_eq!(opened(&sessions), 1, "concurrent refreshes share one read"); + for models in [first, second] { + assert_eq!( + models[0]["capabilities"]["optionDescriptors"][0]["options"] + .as_array() + .unwrap() + .len(), + 1 + ); + } + probe(account("b")).await; + assert_eq!( + opened(&sessions), + 2, + "another environment reads its own session" + ); + } + + /// A failed session read is remembered for a while instead of opening a session on every + /// refresh; the model list is published meanwhile. + #[cfg(unix)] + #[tokio::test] + async fn a_failed_cursor_session_read_is_not_retried_on_every_refresh() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let (executable, sessions) = cursor_session_fixture( + temp.path(), + "0", + r#"printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"no"}}\n' "$id""#, + ); + for _ in 0..2 { + let models = + probe_cursor_models(&executable, Some("failing"), None, &[], temp.path(), &[]) + .await + .expect("the list is published"); + assert_eq!(models.len(), 1); + } + assert_eq!(opened(&sessions), 1); + } + + /// A model list that arrives late is kept even when the session read then hangs: the read + /// starts only once the list is in hand, under its own deadline. + #[cfg(unix)] + #[tokio::test] + async fn a_hung_cursor_session_read_never_discards_a_late_model_list() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let (executable, _sessions) = cursor_session_fixture(temp.path(), "4.5", ":"); + let models = probe_cursor_models(&executable, Some("late"), None, &[], temp.path(), &[]) + .await + .expect("the late list is published"); + assert_eq!(models.len(), 1); + } + + /// A Cursor that answers nothing at all, as when one of its MCP servers never connects, is + /// given up at the discovery deadline: the probe yields no list, so the snapshot keeps the + /// plain fallback models instead of waiting on it. + #[cfg(unix)] + #[tokio::test] + async fn a_cursor_that_never_answers_leaves_the_fallback_models() { + let temp = tempfile::TempDir::new().expect("fixture directory"); + let executable = temp.path().join("cursor-agent"); + crate::test_support::executable_fixture::write_executable( + &executable, + "#!/bin/sh\nwhile IFS= read -r line; do :; done\n", + ); + let models = timeout( + CURSOR_DISCOVERY_TIMEOUT + Duration::from_secs(5), + probe_cursor_models(&executable, Some("silent"), None, &[], temp.path(), &[]), + ) + .await + .expect("the discovery deadline ends the probe"); + assert!(models.is_none(), "{models:?}"); + } + + #[cfg(unix)] + fn write_version_fixture(directory: &Path, name: &str, version: &str) -> std::path::PathBuf { + let executable = directory.join(name); + crate::test_support::executable_fixture::write_executable( + &executable, + format!( + "#!/bin/sh\nif [ \"$1\" = about ]; then printf '%s\\n' '{{\"cliVersion\":\"{version}\"}}'; else printf '%s\\n' '{version}'; fi\n" + ), + ); + executable + } + + #[cfg(unix)] + #[tokio::test] + async fn inventory_instance_path_outranks_ambient_path_in_an_isolated_process() { + const CASE: &str = "provider-inventory-path-precedence"; + const TEST_NAME: &str = "production::provider_inventory::tests::inventory_instance_path_outranks_ambient_path_in_an_isolated_process"; + const SENTINEL: &str = "BIBCODE_TEST_ISOLATED_CASE_DONE=provider-inventory-path-precedence"; + + if TestSandbox::is_isolated_case(CASE, TEST_NAME) { + let instance = std::path::PathBuf::from( + std::env::var_os("BIBCODE_TEST_INSTANCE_PATH").expect("isolated instance PATH"), + ); + let root = std::path::PathBuf::from( + std::env::var_os("BIBCODE_TEST_ROOT").expect("isolated inventory root"), + ); + let ambient_executable = std::path::PathBuf::from( + std::env::var_os("BIBCODE_TEST_AMBIENT_EXECUTABLE") + .expect("isolated ambient executable"), + ); + assert_eq!( + resolve_provider_executable_with_environment( + "cursor-agent", + std::iter::empty::<(&std::ffi::OsStr, &std::ffi::OsStr)>(), + ), + Some(ambient_executable), "the child must have a competing ambient provider executable" ); let settings = json!({ @@ -2371,6 +3560,7 @@ done Some("cursor-work"), &root, &ProviderMaintenance::new(), + None, ) .await; @@ -2509,6 +3699,7 @@ done Some("opencode"), root.path(), &ProviderMaintenance::new(), + None, ) .await; @@ -2660,6 +3851,7 @@ done Some("remote"), sandbox.path(), &ProviderMaintenance::new(), + None, ) .await; server.abort(); @@ -2707,6 +3899,7 @@ done Some("remote"), sandbox.path(), &ProviderMaintenance::new(), + None, ) .await; server.abort(); @@ -2773,6 +3966,7 @@ done Some("remote"), root.path(), &ProviderMaintenance::new(), + None, ) .await; server.abort(); @@ -2846,7 +4040,7 @@ done }); let maintenance = ProviderMaintenance::new(); let quick = probe(&settings, Some("codex"), Path::new("."), &maintenance).await; - let full = probe_full(&settings, Some("codex"), Path::new("."), &maintenance).await; + let full = probe_full(&settings, Some("codex"), Path::new("."), &maintenance, None).await; for result in [quick, full] { assert_eq!(result[0].rich_metadata, RichMetadataOutcome::NotRequested); @@ -2891,6 +4085,1193 @@ done assert_eq!(explicit_cursor.binary_path, "cursor-agent"); } + /// An instance saved without `enabled` is off for the inventory, a chat launch and a + /// terminal launch alike when the legacy entry is off or absent (Antigravity's default). + #[tokio::test] + async fn an_antigravity_instance_without_enabled_is_off_for_every_launch() { + let sandbox = crate::test_support::TestSandbox::new("antigravity-enabled-rule"); + let binary = sandbox.executable_script("agy", "exit 0", ""); + let instance = json!({ + "driver": "antigravity", + "config": { "binaryPath": binary.to_string_lossy() } + }); + let root = sandbox.path("settings"); + std::fs::create_dir_all(&root).expect("settings root"); + for document in [ + json!({ + "providers": { "antigravity": { "enabled": false } }, + "providerInstances": { "antigravity": instance.clone() } + }), + json!({ "providerInstances": { "antigravity": instance.clone() } }), + ] { + std::fs::write(root.join("settings.json"), document.to_string()).expect("settings"); + let inventory = definitions(&document); + let listed = inventory + .iter() + .find(|definition| definition.instance_id == "antigravity") + .expect("the instance"); + assert!(!listed.enabled, "inventory: {document}"); + let chat = super::super::provider_runtime::resolve_provider_route_settings( + &root, + "antigravity", + None, + ) + .await; + assert!(chat.is_err(), "chat launch: {document}"); + let typed = crate::server_settings::ProviderSettingsStore::new(&root) + .get() + .await + .expect("typed settings"); + let terminal = + crate::provider_terminal::ProviderTerminalInventory::from_settings(&typed); + assert!( + !terminal.get("antigravity").expect("terminal entry").enabled, + "terminal launch: {document}" + ); + } + } + + /// Other drivers read a missing instance `enabled` exactly as before: the inventory falls + /// back to the legacy entry, while the typed settings (chat and terminal launches) read on. + #[tokio::test] + async fn a_custom_codex_instance_without_enabled_resolves_as_before() { + let sandbox = crate::test_support::TestSandbox::new("codex-enabled-unchanged"); + let binary = sandbox.executable_script("codex", "exit 0", ""); + let root = sandbox.path("settings"); + std::fs::create_dir_all(&root).expect("settings root"); + let document = json!({ + "providers": { "codex": { "enabled": false } }, + "providerInstances": { "codex-work": { + "driver": "codex", + "config": { "binaryPath": binary.to_string_lossy() } + } } + }); + std::fs::write(root.join("settings.json"), document.to_string()).expect("settings"); + let inventory = definitions(&document); + let listed = inventory + .iter() + .find(|definition| definition.instance_id == "codex-work") + .expect("the instance"); + assert!(!listed.enabled, "the inventory reads the legacy entry"); + let chat = super::super::provider_runtime::resolve_provider_route_settings( + &root, + "codex-work", + None, + ) + .await; + assert!(chat.is_ok(), "a chat launch reads it on"); + let typed = crate::server_settings::ProviderSettingsStore::new(&root) + .get() + .await + .expect("typed settings"); + assert!(typed.provider_instances["codex-work"].enabled); + let terminal = crate::provider_terminal::ProviderTerminalInventory::from_settings(&typed); + assert!(terminal.get("codex-work").expect("terminal entry").enabled); + } + + #[test] + fn fresh_antigravity_inventory_is_disabled_and_runs_agy_not_its_slug() { + let fresh = definitions(&json!({})); + let antigravity = fresh + .iter() + .find(|definition| definition.instance_id == "antigravity") + .expect("built-in Antigravity definition"); + assert!(!antigravity.enabled); + assert!(antigravity.available); + assert_eq!(antigravity.binary_path, "agy"); + assert_eq!(default_provider_binary("antigravity"), "agy"); + + let custom = definitions(&json!({ + "providerInstances": { + "antigravity_work": { "driver": "antigravity", "enabled": true, "config": {} } + } + })); + let custom = custom + .iter() + .find(|definition| definition.instance_id == "antigravity_work") + .expect("custom Antigravity definition"); + assert!(custom.enabled); + assert!(custom.available, "antigravity is a driver this build ships"); + assert_eq!(custom.binary_path, "agy"); + } + + /// Settings with one Antigravity instance whose binary is `binary`, every other built-in + /// pinned to an absent executable so the probe touches nothing else. + #[cfg(unix)] + fn antigravity_probe_settings(sandbox: &Path, binary: &Path, enabled: bool) -> Value { + let missing = crate::test_support::hermetic_providers::missing_provider_executable(sandbox); + let mut settings = + crate::test_support::hermetic_providers::hermetic_provider_settings(sandbox); + settings["providerInstances"] = json!({ + "antigravity": { + "driver": "antigravity", + "enabled": enabled, + "config": { "binaryPath": binary } + }, + "codex": { "driver": "codex", "enabled": false, "config": { "binaryPath": missing } } + }); + settings + } + + #[cfg(unix)] + async fn probe_antigravity_result( + sandbox: &TestSandbox, + settings: &Value, + ) -> ProviderProbeResult { + probe_full( + settings, + Some("antigravity"), + sandbox.root(), + &ProviderMaintenance::new(), + None, + ) + .await + .into_iter() + .next() + .expect("the Antigravity snapshot") + } + + #[cfg(unix)] + async fn probe_antigravity(sandbox: &TestSandbox, settings: &Value) -> Value { + probe_antigravity_result(sandbox, settings).await.snapshot + } + + #[cfg(unix)] + #[tokio::test] + async fn an_enabled_antigravity_instance_is_probed_with_version_then_acp() { + let sandbox = TestSandbox::new("antigravity-probe"); + let arguments = sandbox.path("arguments"); + let binary = sandbox.path("antigravity-cli-fixture"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" >> '{}'\nprintf '%s\\n' '1.5.13'\n", + arguments.display() + ), + ); + + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + + assert_eq!(snapshot["driver"], "antigravity"); + assert_eq!(snapshot["displayName"], "Antigravity"); + assert_eq!(snapshot["installed"], true); + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["version"], "1.5.13"); + assert_eq!( + std::fs::read_to_string(&arguments).expect("the probe ran the binary"), + "--version\nacp\n" + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_disabled_antigravity_instance_is_not_probed() { + let sandbox = TestSandbox::new("antigravity-disabled"); + let ran = sandbox.path("ran"); + let binary = sandbox.path("antigravity-cli-fixture"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!("#!/bin/sh\ntouch '{}'\n", ran.display()), + ); + + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, false), + ) + .await; + + assert_eq!(snapshot["driver"], "antigravity"); + assert_eq!(snapshot["enabled"], false); + assert!( + !ran.exists(), + "a disabled instance must not start its binary" + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn antigravity_probe_failures_follow_the_inventory_rules() { + let sandbox = TestSandbox::new("antigravity-probe-failures"); + let failing = sandbox.path("antigravity-cli-failing"); + crate::test_support::executable_fixture::write_executable( + &failing, + format!("#!/bin/sh\nprintf '%s\\n' 'account-{ANTIGRAVITY_MARKER}'\nexit 3\n"), + ); + let failing_snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &failing, true), + ) + .await; + assert_eq!(failing_snapshot["driver"], "antigravity"); + assert_eq!(failing_snapshot["installed"], true); + assert_eq!(failing_snapshot["status"], "warning"); + // A failed `--version` printed no version, whatever its output says. + assert_eq!(failing_snapshot["version"], Value::Null); + assert!(!failing_snapshot.to_string().contains(ANTIGRAVITY_MARKER)); + + let inert = sandbox.path("antigravity-cli-inert"); + std::fs::write(&inert, "not executable").expect("inert fixture"); + let inert_snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &inert, true), + ) + .await; + assert_eq!(inert_snapshot["driver"], "antigravity"); + assert_eq!(inert_snapshot["installed"], false); + } + + /// Every account value and stray output of the scripted Antigravity peer carries this text, + /// so one search proves none of it reached a snapshot or a log. + const ANTIGRAVITY_MARKER: &str = "7f3a-secret"; + + /// A `session/new` answer shaped like the one measured on CLI 1.5.13, with made-up models: + /// a model value that is a prefix of another (`alpha`, `alpha-pro`), effort suffixes out of + /// order, a model with no suffixed variant, a model value that ends in a level word, an + /// unknown level, a model whose own id reads as another model's level (`epsilon-high`), and + /// a repeated model and level. The current model is not listed first. + fn antigravity_session() -> Value { + json!({ + "sessionId": "session-1", + "models": { + "availableModels": [ + { "modelId": "alpha-high", "name": "Alpha (High)" }, + { "modelId": "alpha-low", "name": "Alpha (Low)" }, + { "modelId": "alpha-medium", "name": "Alpha (Medium)" }, + { "modelId": "alpha-pro-high", "name": "Alpha Pro (High)" }, + { "modelId": "alpha-pro-xhigh", "name": "Alpha Pro (Extra)" }, + { "modelId": "alpha-pro-medium", "name": "Alpha Pro (Medium)" }, + { "modelId": "alpha-pro-low", "name": "Alpha Pro (Low)" }, + { "modelId": "beta-orchestrator", "name": "Beta Orchestrator" }, + { "modelId": "gamma-120b-medium", "name": "Gamma 120B (Medium)" }, + { "modelId": "delta-max", "name": "Delta (Max)" }, + { "modelId": "delta-low", "name": "Delta (Low)" }, + { "modelId": "delta-low", "name": "Delta (Low)" }, + { "modelId": "epsilon-high", "name": "Epsilon High" }, + { "modelId": "epsilon-low", "name": "Epsilon (Low)" } + ], + "currentModelId": "alpha-pro-high" + }, + "modes": { + "currentModeId": "default", + "availableModes": [{ "id": "default", "name": "Default" }] + }, + "configOptions": [ + { + "id": "model", "name": "Model", "category": "model", "type": "select", + "currentValue": "alpha-pro", + "options": [ + { "value": "alpha", "name": "Alpha" }, + { "value": "alpha-pro", "name": "Alpha Pro" }, + { "value": "beta-orchestrator", "name": "Beta Orchestrator" }, + { "value": "gamma-120b-medium", "name": "Gamma 120B (Medium)" }, + { "value": "delta", "name": "Delta" }, + { "value": "delta", "name": "Delta" }, + { "value": "epsilon", "name": "Epsilon" }, + { "value": "epsilon-high", "name": "Epsilon High" } + ] + }, + { + "id": "thought_level", "name": "Thinking Level", "category": "thought_level", + "type": "select", "currentValue": "high", + "options": [ + { "value": "low", "name": "Low" }, + { "value": "medium", "name": "Medium" }, + { "value": "high", "name": "High" }, + { "value": "xhigh", "name": "Extra" } + ] + }, + { + "id": "mode", "name": "Mode", "category": "mode", "type": "select", + "currentValue": "default", + "options": [{ "value": "default", "name": "Default" }] + } + ], + "_meta": { "antigravity": { "tier": { "name": format!("plan-{ANTIGRAVITY_MARKER}") } } } + }) + } + + #[cfg(unix)] + fn reasoning(options: Value) -> Value { + json!({ "optionDescriptors": [ + { "id": "reasoning", "label": "Thinking Level", "type": "select", "options": options } + ] }) + } + + /// The catalog `antigravity_session` advertises: the current model first, each model with + /// its own thinking levels, a default only where the CLI names one. + #[cfg(unix)] + fn expected_antigravity_models() -> Vec { + let none = json!({ "optionDescriptors": [] }); + vec![ + json!({ "slug": "alpha-pro", "name": "Alpha Pro", "isCustom": false, + "capabilities": reasoning(json!([ + { "id": "low", "label": "Low" }, + { "id": "medium", "label": "Medium" }, + { "id": "high", "label": "High", "isDefault": true }, + { "id": "xhigh", "label": "Extra" } + ])) }), + json!({ "slug": "alpha", "name": "Alpha", "isCustom": false, + "capabilities": reasoning(json!([ + { "id": "low", "label": "Low" }, + { "id": "medium", "label": "Medium" }, + { "id": "high", "label": "High" } + ])) }), + json!({ "slug": "beta-orchestrator", "name": "Beta Orchestrator", "isCustom": false, + "capabilities": none }), + json!({ "slug": "gamma-120b-medium", "name": "Gamma 120B (Medium)", "isCustom": false, + "capabilities": none }), + json!({ "slug": "delta", "name": "Delta", "isCustom": false, + "capabilities": reasoning(json!([ + { "id": "low", "label": "Low" }, + { "id": "max", "label": "max" } + ])) }), + json!({ "slug": "epsilon", "name": "Epsilon", "isCustom": false, + "capabilities": reasoning(json!([{ "id": "low", "label": "Low" }])) }), + json!({ "slug": "epsilon-high", "name": "Epsilon High", "isCustom": false, + "capabilities": none }), + ] + } + + /// A scripted `agy`: `--version` prints `version` with a marker on stderr, and `acp` answers + /// `initialize` as measured on 1.5.13 (protocol 1, `session/close` advertised under both key + /// spellings), then `session/new` with the JSON-RPC member `session_new` (a `result` or an + /// `error`), and every other request with an empty result. It logs each request it reads. + #[cfg(unix)] + pub(crate) fn antigravity_acp_fixture( + sandbox: &TestSandbox, + name: &str, + version: &str, + session_new: &str, + ) -> (std::path::PathBuf, std::path::PathBuf) { + antigravity_acp_peer( + sandbox, + name, + version, + &antigravity_initialize(1, "1.5.13", true), + session_new, + r#""result":{}"#, + ) + } + + /// The JSON-RPC member of an `initialize` answer: `protocol`, `agent_version` as + /// `agentInfo.version`, and `session/close` advertised only when `close` is set. + #[cfg(unix)] + pub(crate) fn antigravity_initialize( + protocol: u64, + agent_version: &str, + close: bool, + ) -> String { + let session_capabilities = if close { + json!({ "close": {}, "resume": {} }) + } else { + json!({ "resume": {} }) + }; + format!( + r#""result":{}"#, + json!({ + "protocolVersion": protocol, + "agentCapabilities": { + "loadSession": true, + "sessionCapabilities": session_capabilities, + "session_capabilities": session_capabilities, + }, + "agentInfo": { "name": "antigravity", "version": agent_version }, + "authMethods": [], + "_meta": { "tier": format!("plan-{ANTIGRAVITY_MARKER}") } + }) + ) + } + + /// [`antigravity_acp_fixture`] with its `initialize` and `session/close` answers given; an + /// empty `close` never answers `session/close`. + #[cfg(unix)] + pub(crate) fn antigravity_acp_peer( + sandbox: &TestSandbox, + name: &str, + version: &str, + initialize: &str, + session_new: &str, + close: &str, + ) -> (std::path::PathBuf, std::path::PathBuf) { + let binary = sandbox.path(name); + let requests = sandbox.path(format!("{name}.requests")); + let close = if close.is_empty() { + "sleep 30".to_owned() + } else { + format!("body='{close}'") + }; + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + r#"#!/bin/sh +case "$1" in + --version) printf '%s\n' '{version}'; printf '%s\n' 'stderr-{ANTIGRAVITY_MARKER}' >&2; exit 0 ;; +esac +printf '%s\n' 'stderr-{ANTIGRAVITY_MARKER}' >&2 +while IFS= read -r request; do + printf '%s\n' "$request" >> '{requests}' + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$request" in + *'"method":"initialize"'*) body='{initialize}' ;; + *'"method":"session/new"'*) printf '%s\n' '{{"jsonrpc":"2.0","method":"session/update","params":{{"update":"{ANTIGRAVITY_MARKER}"}}}}'; body='{session_new}' ;; + *'"method":"session/close"'*) {close} ;; + *) body='"result":{{}}' ;; + esac + printf '{{"jsonrpc":"2.0","id":%s,%s}}\n' "$id" "$body" +done +"#, + requests = requests.display(), + ), + ); + (binary, requests) + } + + #[cfg(unix)] + pub(crate) fn antigravity_requests(requests: &Path) -> Vec { + std::fs::read_to_string(requests) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON-RPC request")) + .collect() + } + + #[cfg(unix)] + fn antigravity_methods(requests: &Path) -> Vec { + antigravity_requests(requests) + .iter() + .map(|request| request["method"].as_str().unwrap_or_default().to_owned()) + .collect() + } + + /// Each ACP probe ends its transport with it: the writer task that owns the agent's stdin, + /// the readers and the drain of unused messages. Cursor's probe uses the same transport. + #[cfg(unix)] + #[tokio::test] + async fn repeated_acp_probes_leave_no_transport_task_behind() { + let sandbox = TestSandbox::new("antigravity-transport"); + let (binary, _) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-transport", + "1.5.13", + &format!(r#""result":{}"#, antigravity_session()), + ); + let settings = antigravity_probe_settings(sandbox.root(), &binary, true); + let metrics = tokio::runtime::Handle::current().metrics(); + let baseline = metrics.num_alive_tasks(); + for _ in 0..5 { + let snapshot = probe_antigravity(&sandbox, &settings).await; + assert_eq!(snapshot["auth"], json!({ "status": "authenticated" })); + let _ = probe_cursor_models(&binary, None, None, &[], sandbox.root(), &[]).await; + } + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while metrics.num_alive_tasks() > baseline { + assert!( + tokio::time::Instant::now() < deadline, + "{} tasks alive after the probes, {baseline} before", + metrics.num_alive_tasks() + ); + sleep(Duration::from_millis(20)).await; + } + } + + /// A probe child dropped where no runtime runs still has its whole process group stopped: + /// `Drop` signals the group itself and hands off only the reap. + #[cfg(unix)] + #[test] + fn a_probe_child_dropped_outside_a_runtime_leaves_no_descendant() { + let sandbox = TestSandbox::new("antigravity-drop-outside"); + let pids = sandbox.path("pids"); + let script = sandbox.path("antigravity-cli-hangs"); + crate::test_support::executable_fixture::write_executable( + &script, + format!( + "#!/bin/sh\nsleep 30 &\nprintf '%s\\n' \"$!\" > '{0}.tmp'\nmv '{0}.tmp' '{0}'\nwait\n", + pids.display() + ), + ); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime"); + let (child, grandchild) = runtime.block_on(async { + let mut command = Command::new(&script); + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let spawned = supervised_command(command) + .spawn() + .expect("the fixture starts"); + let grandchild = loop { + if let Ok(text) = std::fs::read_to_string(&pids) + && let Ok(pid) = text.trim().parse::() + { + break pid; + } + sleep(Duration::from_millis(20)).await; + }; + ( + ProbeChild { + child: Some(spawned), + registration: None, + }, + grandchild, + ) + }); + std::thread::spawn(move || drop(child)) + .join() + .expect("the drop thread"); + let gone = || { + // SAFETY: signal 0 only checks that the pid exists. + let result = unsafe { libc::kill(grandchild as libc::pid_t, 0) }; + result == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) + }; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !gone() { + assert!( + std::time::Instant::now() < deadline, + "the descendant {grandchild} outlived the dropped probe" + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + + /// A `session/close` that never answers does not cost the catalog or the sign-in it read: + /// the close has its own short step. + #[cfg(unix)] + #[tokio::test] + async fn a_stalled_session_close_keeps_the_catalog_and_the_sign_in() { + let sandbox = TestSandbox::new("antigravity-close-stalls"); + let (binary, requests) = antigravity_acp_peer( + &sandbox, + "antigravity-cli-close-stalls", + "1.5.13", + &antigravity_initialize(1, "1.5.13", true), + &format!(r#""result":{}"#, antigravity_session()), + "", + ); + let started = tokio::time::Instant::now(); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + assert!(started.elapsed() < ANTIGRAVITY_DISCOVERY_TIMEOUT); + assert_eq!(snapshot["auth"], json!({ "status": "authenticated" })); + assert_eq!( + snapshot["models"], + Value::Array(expected_antigravity_models()) + ); + assert_eq!( + antigravity_methods(&requests), + ["initialize", "session/new", "session/close"] + ); + } + + /// `session/close` is sent only when `initialize` advertises it, and a session that lists no + /// model still proves the CLI is signed in. + #[cfg(unix)] + #[tokio::test] + async fn session_close_is_sent_only_when_advertised() { + let sandbox = TestSandbox::new("antigravity-close-unadvertised"); + let (binary, requests) = antigravity_acp_peer( + &sandbox, + "antigravity-cli-no-close", + "1.5.13", + &antigravity_initialize(1, "1.5.13", false), + r#""result":{"sessionId":"session-1"}"#, + r#""result":{}"#, + ); + let mut settings = antigravity_probe_settings(sandbox.root(), &binary, true); + settings["providerInstances"]["antigravity"]["config"]["customModels"] = + json!(["custom-one"]); + let snapshot = probe_antigravity(&sandbox, &settings).await; + assert_eq!( + antigravity_methods(&requests), + ["initialize", "session/new"] + ); + assert_eq!(snapshot["auth"], json!({ "status": "authenticated" })); + assert_eq!( + snapshot["models"], + Value::Array(custom_models(&["custom-one".to_owned()])) + ); + } + + /// A peer that answers another ACP version gets no session; the instance stays ready for + /// the terminal and keeps the version its `--version` printed. + #[cfg(unix)] + #[tokio::test] + async fn the_probe_refuses_another_acp_version_and_keeps_the_terminal() { + let sandbox = TestSandbox::new("antigravity-protocol-2"); + let (binary, requests) = antigravity_acp_peer( + &sandbox, + "antigravity-cli-protocol-2", + "1.5.13", + &antigravity_initialize(2, "1.5.20", true), + &format!(r#""result":{}"#, antigravity_session()), + r#""result":{}"#, + ); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + assert_eq!(antigravity_methods(&requests), ["initialize"]); + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["auth"], json!({ "status": "unknown" })); + assert_eq!(snapshot["version"], "1.5.13"); + assert_eq!(snapshot["models"], json!([])); + } + + /// The version published is the validated `agentInfo.version` of a protocol 1 handshake; + /// text there that is no version leaves the `--version` line. + #[cfg(unix)] + #[tokio::test] + async fn the_probe_publishes_the_validated_agent_version() { + let sandbox = TestSandbox::new("antigravity-agent-version"); + let session = format!(r#""result":{}"#, antigravity_session()); + let (newer, _) = antigravity_acp_peer( + &sandbox, + "antigravity-cli-agent-version", + "1.5.13", + &antigravity_initialize(1, "1.5.20", true), + &session, + r#""result":{}"#, + ); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &newer, true), + ) + .await; + assert_eq!(snapshot["version"], "1.5.20"); + + let (junk, _) = antigravity_acp_peer( + &sandbox, + "antigravity-cli-agent-junk", + "1.5.13", + &antigravity_initialize(1, &format!("build-{ANTIGRAVITY_MARKER}"), true), + &session, + r#""result":{}"#, + ); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &junk, true), + ) + .await; + assert_eq!(snapshot["version"], "1.5.13"); + assert!(!snapshot.to_string().contains(ANTIGRAVITY_MARKER)); + } + + /// An ACP child that dies on its own during the handshake is reported to the Profiler. + #[cfg(unix)] + #[tokio::test] + async fn an_acp_probe_child_that_dies_on_its_own_is_reported() { + let captured = crate::diagnostics::profiler::exits::CapturedExits::start(); + let sandbox = TestSandbox::new("antigravity-child-dies"); + let binary = sandbox.path("antigravity-cli-dies"); + crate::test_support::executable_fixture::write_executable( + &binary, + "#!/bin/sh\ncase \"$1\" in --version) printf '%s\\n' 1.5.13; exit 0 ;; esac\nread -r request\nexit 17\n", + ); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + assert_eq!(snapshot["status"], "ready"); + let findings = captured.take(); + assert!( + findings.iter().any( + |fields| fields.first().map(String::as_str) == Some("provider") + && fields.iter().any(|field| field == "antigravity") + ), + "{findings:?}" + ); + } + + /// The `--version` child of a full probe is attributed while it runs. + #[cfg(unix)] + #[tokio::test] + async fn the_antigravity_version_check_is_attributed() { + let sandbox = TestSandbox::new("antigravity-version-attributed"); + let pid = sandbox.path("pid"); + let binary = sandbox.path("antigravity-cli-slow-version"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + "#!/bin/sh\ncase \"$1\" in --version) printf '%s\\n' \"$$\" > '{0}.tmp'; mv '{0}.tmp' '{0}'; sleep 1; printf '%s\\n' 1.5.13; exit 0 ;; esac\nexit 0\n", + pid.display() + ), + ); + let settings = antigravity_probe_settings(sandbox.root(), &binary, true); + let maintenance = ProviderMaintenance::new(); + let registry = ProcessAttributionRegistry::new(); + let watch = async { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while tokio::time::Instant::now() < deadline { + if let Ok(text) = std::fs::read_to_string(&pid) + && let Ok(pid) = text.trim().parse::() + && registry + .registered_sources() + .iter() + .any(|(identity, _)| identity.pid == pid) + { + return true; + } + sleep(Duration::from_millis(20)).await; + } + false + }; + let (_, attributed) = tokio::join!( + probe_full( + &settings, + Some("antigravity"), + sandbox.root(), + &maintenance, + Some(®istry), + ), + watch + ); + assert!(attributed, "the version check was not attributed"); + } + + /// Catalog edge cases outside the measured shape: model options that list nothing fall back + /// to `availableModels`; a `thought_level` without a category, or with no options, still + /// gives the current model its levels; level ids stay the CLI's own. + #[test] + fn antigravity_catalog_edge_cases_follow_the_cli() { + let fallback = antigravity_models( + &json!({ + "configOptions": [{ "id": "model", "options": [] }], + "models": { "availableModels": [{ "modelId": "alpha-high" }], + "currentModelId": "alpha-high" } + }), + &[], + ) + .expect("a catalog"); + assert_eq!(fallback[0]["slug"], "alpha-high"); + + // The chat runtime's test sends a turn with the level published from these options. + let uncategorized = antigravity_models( + &json!({ + "configOptions": crate::provider::antigravity::runtime::uncategorized_level_options() + }), + &[], + ) + .expect("a catalog"); + assert_eq!( + uncategorized[0]["capabilities"], + json!({ "optionDescriptors": [{ "id": "reasoning", "label": "Thinking", "type": "select", + "options": [ + { "id": "extra-high", "label": "Extra High" }, + { "id": "low", "label": "low", "isDefault": true } + ] }] }) + ); + + let empty_levels = antigravity_models( + &json!({ + "configOptions": [ + { "id": "model", "currentValue": "alpha", "options": [{ "value": "alpha" }] }, + { "id": "thought_level", "category": "thought_level", "options": [] } + ], + "models": { "availableModels": [{ "modelId": "alpha-low" }] } + }), + &[], + ) + .expect("a catalog"); + assert_eq!( + empty_levels[0]["capabilities"]["optionDescriptors"][0]["options"], + json!([{ "id": "low", "label": "low" }]) + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_full_probe_reads_models_levels_and_sign_in_over_acp() { + let sandbox = TestSandbox::new("antigravity-acp"); + let (binary, requests) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-acp", + "1.5.13", + &format!(r#""result":{}"#, antigravity_session()), + ); + let mut settings = antigravity_probe_settings(sandbox.root(), &binary, true); + settings["providerInstances"]["antigravity"]["config"]["customModels"] = + json!(["custom-one", "alpha"]); + + let snapshot = probe_antigravity(&sandbox, &settings).await; + + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["installed"], true); + assert_eq!(snapshot["version"], "1.5.13"); + assert_eq!(snapshot["auth"], json!({ "status": "authenticated" })); + assert!(snapshot.get("message").is_none(), "{snapshot}"); + // The chat reports ACP `usage_update`, so the composer shows its context meter. + assert_eq!(snapshot["supportsContextWindowUsage"], true); + let mut expected = expected_antigravity_models(); + expected.extend(custom_models(&["custom-one".to_owned()])); + assert_eq!(snapshot["models"], Value::Array(expected)); + let requests = antigravity_requests(&requests); + let methods = requests + .iter() + .map(|request| request["method"].as_str().unwrap_or_default()) + .collect::>(); + assert_eq!(methods, ["initialize", "session/new", "session/close"]); + assert_eq!(requests[0]["params"]["protocolVersion"], 1); + assert_eq!( + requests[1]["params"], + json!({ "cwd": std::env::temp_dir(), "mcpServers": [] }) + ); + assert_eq!(requests[2]["params"], json!({ "sessionId": "session-1" })); + assert!( + !snapshot.to_string().contains(ANTIGRAVITY_MARKER), + "{snapshot}" + ); + } + + /// Without `configOptions` the CLI's `availableModels` ids are published unchanged, effort + /// suffix included, because the chat sends them back as they are. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_session_without_config_options_publishes_its_available_models() { + let sandbox = TestSandbox::new("antigravity-available-models"); + let session = json!({ + "sessionId": "session-1", + "models": { + "availableModels": [ + { "modelId": "alpha-high", "name": "Alpha (High)" }, + { "modelId": "alpha-pro-high", "name": "Alpha Pro (High)" } + ], + "currentModelId": "alpha-pro-high" + } + }); + let (binary, _) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-models", + "1.5.13", + &format!(r#""result":{session}"#), + ); + + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + + let none = json!({ "optionDescriptors": [] }); + assert_eq!( + snapshot["models"], + json!([ + { "slug": "alpha-pro-high", "name": "Alpha Pro (High)", "isCustom": false, + "capabilities": none }, + { "slug": "alpha-high", "name": "Alpha (High)", "isCustom": false, + "capabilities": none } + ]) + ); + assert_eq!(snapshot["auth"], json!({ "status": "authenticated" })); + } + + /// The CLI's order is kept when it lists its current model first, as the measured CLI does. + #[test] + fn antigravity_models_keep_the_cli_order_when_the_current_model_is_first() { + let mut session = antigravity_session(); + session["configOptions"][0]["currentValue"] = json!("alpha"); + session["models"]["currentModelId"] = json!("alpha-high"); + let models = antigravity_models(&session, &[]).expect("a catalog"); + let slugs = models + .iter() + .map(|model| model["slug"].as_str().unwrap_or_default()) + .collect::>(); + assert_eq!( + slugs, + [ + "alpha", + "alpha-pro", + "beta-orchestrator", + "gamma-120b-medium", + "delta", + "epsilon", + "epsilon-high" + ] + ); + // `alpha` is now the current model: its levels and default come from `thought_level`. + assert_eq!( + models[0]["capabilities"]["optionDescriptors"][0]["options"][2], + json!({ "id": "high", "label": "High", "isDefault": true }) + ); + assert!(antigravity_models(&json!({ "sessionId": "session-1" }), &[]).is_none()); + } + + /// Only "Authentication required" reads as signed out: another `-32000` leaves the sign-in + /// unknown and no sign-in message. + #[cfg(unix)] + #[tokio::test] + async fn another_antigravity_server_error_is_not_read_as_signed_out() { + let sandbox = TestSandbox::new("antigravity-other-32000"); + let (binary, _) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-other-32000", + "1.5.13", + r#""error":{"code":-32000,"message":"Rate limited"}"#, + ); + let snapshot = probe_antigravity( + &sandbox, + &antigravity_probe_settings(sandbox.root(), &binary, true), + ) + .await; + assert_eq!(snapshot["auth"], json!({ "status": "unknown" })); + assert!(snapshot.get("message").is_none(), "{snapshot}"); + } + + /// `-32000` "Authentication required" reads as signed out while the instance stays ready, + /// so the terminal the user signs in with stays available; the CLI's text never shows. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_sign_in_failure_reads_unauthenticated_and_ready() { + let sandbox = TestSandbox::new("antigravity-sign-in"); + let (binary, _) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-signed-out", + "1.5.13", + &format!( + r#""error":{{"code":-32000,"message":"Authentication required","data":{{"detail":"{ANTIGRAVITY_MARKER}"}}}}"# + ), + ); + let mut settings = antigravity_probe_settings(sandbox.root(), &binary, true); + settings["providerInstances"]["antigravity"]["config"]["customModels"] = + json!(["custom-one"]); + + let result = probe_antigravity_result(&sandbox, &settings).await; + // The signed-out account's catalog is gone: the merge must not keep the last one. + assert!(result.models_authoritative); + let snapshot = result.snapshot; + + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["auth"], json!({ "status": "unauthenticated" })); + assert_eq!(snapshot["message"], ANTIGRAVITY_SIGN_IN_MESSAGE); + assert_eq!( + snapshot["models"], + Value::Array(custom_models(&["custom-one".to_owned()])) + ); + assert!( + !snapshot.to_string().contains(ANTIGRAVITY_MARKER), + "{snapshot}" + ); + } + + /// Any other failure keeps the custom models and an unknown sign-in, and its log line names + /// the step and the error code only. In a process of its own for the log capture. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_probe_failure_keeps_custom_models_and_logs_no_peer_text() { + let Some(child) = crate::test_support::in_own_process( + "production::provider_inventory::tests::an_antigravity_probe_failure_keeps_custom_models_and_logs_no_peer_text", + ) else { + return; + }; + #[derive(Clone, Default)] + struct Captured(std::sync::Arc>>); + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let log = Captured::default(); + let _logging = tracing::subscriber::set_default( + tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .with_writer({ + let log = log.clone(); + move || log.clone() + }) + .finish(), + ); + let sandbox = TestSandbox::new("antigravity-probe-error"); + let (binary, _) = antigravity_acp_fixture( + &sandbox, + "antigravity-cli-error", + "1.5.13", + &format!( + r#""error":{{"code":-32603,"message":"Internal {ANTIGRAVITY_MARKER}","data":{{"detail":"{ANTIGRAVITY_MARKER}"}}}}"# + ), + ); + let mut settings = antigravity_probe_settings(sandbox.root(), &binary, true); + settings["providerInstances"]["antigravity"]["config"]["customModels"] = + json!(["custom-one"]); + + let snapshot = probe_antigravity(&sandbox, &settings).await; + + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["auth"], json!({ "status": "unknown" })); + assert_eq!( + snapshot["models"], + Value::Array(custom_models(&["custom-one".to_owned()])) + ); + assert!( + !snapshot.to_string().contains(ANTIGRAVITY_MARKER), + "{snapshot}" + ); + let text = String::from_utf8(log.0.lock().unwrap().clone()).unwrap(); + assert!( + text.lines() + .any(|line| line.contains("Antigravity inventory probe") + && line.contains("step=\"session/new\"") + && line.contains("failure=\"error -32603\"")), + "{text}" + ); + assert!(!text.contains(ANTIGRAVITY_MARKER), "{text}"); + child.complete(); + } + + /// The version comes from stdout only: a `--version` that writes only to stderr reports no + /// version, in the inventory and in the maintenance check. + #[cfg(unix)] + #[tokio::test] + async fn the_antigravity_version_never_takes_a_line_of_stderr() { + let sandbox = TestSandbox::new("antigravity-version-stderr"); + let binary = sandbox.path("antigravity-cli-stderr"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + "#!/bin/sh\nprintf '%s\\n' 'stderr-{ANTIGRAVITY_MARKER}' >&2\n[ \"$1\" = --version ] || exit 1\n" + ), + ); + let settings = antigravity_probe_settings(sandbox.root(), &binary, true); + + let snapshot = probe_antigravity(&sandbox, &settings).await; + assert_eq!(snapshot["version"], Value::Null, "{snapshot}"); + assert!(!snapshot.to_string().contains(ANTIGRAVITY_MARKER)); + + let target = maintenance_target(&settings, "antigravity", Some("antigravity")) + .expect("the Antigravity target"); + assert_eq!( + probe_maintenance_target_version(&target, sandbox.root()).await, + None + ); + } + + /// The quick probe starts no ACP process: it only resolves the executable. + #[cfg(unix)] + #[tokio::test] + async fn the_quick_antigravity_probe_starts_no_process() { + let sandbox = TestSandbox::new("antigravity-quick"); + let ran = sandbox.path("ran"); + let binary = sandbox.path("antigravity-cli-quick"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!("#!/bin/sh\nprintf '%s\\n' \"$@\" >> '{}'\n", ran.display()), + ); + let snapshot = probe( + &antigravity_probe_settings(sandbox.root(), &binary, true), + Some("antigravity"), + sandbox.root(), + &ProviderMaintenance::new(), + ) + .await + .into_iter() + .next() + .expect("the Antigravity snapshot") + .snapshot; + assert_eq!(snapshot["status"], "ready"); + assert_eq!(snapshot["auth"], json!({ "status": "unknown" })); + assert!(!ran.exists(), "the quick probe must start no process"); + } + + /// A refresh that drops the probe still stops the whole process group and reaps it, and the + /// probe's attribution ends with it. + #[cfg(unix)] + #[tokio::test] + async fn a_dropped_antigravity_probe_stops_and_reaps_its_processes() { + let sandbox = TestSandbox::new("antigravity-drop"); + let pids = sandbox.path("pids"); + let binary = sandbox.path("antigravity-cli-hangs"); + crate::test_support::executable_fixture::write_executable( + &binary, + format!( + "#!/bin/sh\ncase \"$1\" in --version) printf '%s\\n' 1.5.13; exit 0 ;; esac\nsleep 30 &\nprintf '%s %s\\n' \"$$\" \"$!\" > '{0}.tmp'\nmv '{0}.tmp' '{0}'\nwait\n", + pids.display() + ), + ); + let settings = antigravity_probe_settings(sandbox.root(), &binary, true); + let maintenance = ProviderMaintenance::new(); + let registry = ProcessAttributionRegistry::new(); + let probe = probe_full( + &settings, + Some("antigravity"), + sandbox.root(), + &maintenance, + Some(®istry), + ); + let wait_for_pids = async { + loop { + if let Ok(text) = std::fs::read_to_string(&pids) { + let mut parts = text.split_whitespace().map(|pid| pid.parse::()); + if let (Some(Ok(root)), Some(Ok(grandchild))) = (parts.next(), parts.next()) { + let attributed = + registry + .registered_sources() + .iter() + .any(|(identity, source)| { + identity.pid == root + && *source + == crate::diagnostics::RegistrationSource::Provider + }); + return (root, grandchild, attributed); + } + } + sleep(Duration::from_millis(20)).await; + } + }; + // `select!` drops the probe future before it returns, as a superseded refresh does. + let (root, grandchild, attributed) = tokio::select! { + _ = probe => panic!("the probe finished without an answer"), + pids = wait_for_pids => pids, + }; + assert!(attributed, "the running probe process is attributed"); + let gone = |pid: u32| { + // SAFETY: signal 0 only checks that the pid exists; a zombie still exists. + let result = unsafe { libc::kill(pid as libc::pid_t, 0) }; + result == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) + }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while !(gone(root) && gone(grandchild) && registry.registered_sources().is_empty()) { + assert!( + tokio::time::Instant::now() < deadline, + "root gone: {}, grandchild gone: {}, attributed: {:?}", + gone(root), + gone(grandchild), + registry.registered_sources() + ); + sleep(Duration::from_millis(20)).await; + } + } + + /// An instance the user configured under the id `antigravity` before this driver existed + /// keeps the id: the built-in default is not synthesized beside it. + #[test] + fn a_configured_instance_that_owns_the_antigravity_id_is_not_duplicated() { + let settings = json!({ + "providerInstances": { + "antigravity": { "driver": "codex", "enabled": true, "config": {} } + } + }); + let owners = definitions(&settings) + .into_iter() + .filter(|definition| definition.instance_id == "antigravity") + .map(|definition| definition.driver) + .collect::>(); + assert_eq!(owners, ["codex"]); + } + #[test] fn configured_instances_do_not_hide_enabled_legacy_providers() { let settings = json!({ @@ -2918,7 +5299,14 @@ done assert_eq!( drivers, - ["cursor", "codex", "claudeAgent", "grok", "opencode"] + [ + "cursor", + "codex", + "claudeAgent", + "grok", + "opencode", + "antigravity" + ] ); assert_eq!( drivers.iter().filter(|driver| **driver == "cursor").count(), @@ -3227,6 +5615,8 @@ done endpoint: None, server_password: None, environment: Vec::new(), + missing_secret: false, + secret_values: Vec::new(), }; assert_eq!( @@ -3389,7 +5779,8 @@ done "claudeAgent": { "enabled": false, "binaryPath": missing }, "cursor": { "enabled": false, "binaryPath": missing }, "grok": { "enabled": false, "binaryPath": missing }, - "opencode": { "enabled": false, "binaryPath": missing } + "opencode": { "enabled": false, "binaryPath": missing }, + "antigravity": { "enabled": false, "binaryPath": missing } }, "providerInstances": { "first": { @@ -3408,7 +5799,7 @@ done let maintenance = ProviderMaintenance::new(); let result = timeout( Duration::from_secs(2), - probe_full(&settings, None, Path::new("."), &maintenance), + probe_full(&settings, None, Path::new("."), &maintenance, None), ) .await; server.abort(); diff --git a/apps/server/src/production/provider_runtime.rs b/apps/server/src/production/provider_runtime.rs index 6355caf8ba..744d15f741 100644 --- a/apps/server/src/production/provider_runtime.rs +++ b/apps/server/src/production/provider_runtime.rs @@ -71,6 +71,14 @@ use crate::{ }, provider::{ OptionRefusal, + antigravity::{ + AcpConnectionConfig as AntigravityConnectionConfig, + AcpJsonRpcConnection as AntigravityConnection, AntigravityRuntimeError, + AntigravitySessionOptions, AntigravitySessionRuntime, + DEFAULT_CANCEL_GRACE as ANTIGRAVITY_CANCEL_GRACE, + DEFAULT_CONTROL_TIMEOUT as ANTIGRAVITY_CONTROL_TIMEOUT, + START_NOTICE_DELAY as ANTIGRAVITY_START_NOTICE_DELAY, + }, attachments::{ AttachmentMaterializer, MaterializedAttachment, append_file_references, split_native_images_and_file_references, @@ -135,6 +143,36 @@ const PROVIDER_STREAM_SETTLEMENT_TIMEOUT: Duration = Duration::from_secs(5); /// Providers normally settle an interrupt within a second or two. const PROVIDER_INTERRUPT_SETTLEMENT_TIMEOUT: Duration = Duration::from_secs(10); +/// How long any provider may take to start before BiBCode shows that it is slow. A CLI can wait +/// silently for an MCP server that never connects; the start keeps waiting, since a slow start +/// may still finish, and only a stop of the thread or the server's shutdown ends it. +const PROVIDER_START_NOTICE_DELAY: Duration = Duration::from_secs(120); + +/// The notice of a start that is taking long, naming the provider and, when its CLI has one, the +/// command that shows which MCP server does not answer. +fn start_notice(provider: &str) -> String { + let mut notice = format!( + "{} is taking longer than usual to start.", + provider_display_name(provider) + ); + // Each command checked with ` mcp --help` on the installed CLI; Grok has none. + let check = match provider { + "claudeAgent" | "claude" => Some("claude"), + "codex" => Some("codex"), + "opencode" => Some("opencode"), + "antigravity" => Some("agy"), + "cursor" => Some("cursor-agent"), + _ => None, + }; + if let Some(cli) = check { + notice.push_str(&format!( + " One of its MCP servers may not be responding; run `{cli} mcp list` in a terminal to \ + see which one." + )); + } + notice +} + const DEFAULT_QUEUE_CAPACITY: usize = 32; const DEFAULT_EVENT_QUEUE_CAPACITY: usize = 128; const CLAUDE_CONTROL_RESPONSE_CAPACITY: usize = 128; @@ -312,6 +350,9 @@ pub enum ProviderDeliveryOutcome { }, /// The provider already has the message, so it was not sent again and starts no turn. AlreadyDelivered, + /// The user stopped the message before any of it reached the provider: it is settled, never + /// sent again, and the provider has none of it, so a side chat still owes its host's context. + StoppedUnsent, /// Not sent, and the provider asked to wait at least `retry_after` before sending it again. NotSentRetryAfter { detail: String, @@ -398,6 +439,11 @@ impl ProviderDeliveryHandle { pub trait ProviderDriver: Send + Sync { fn start(&self) -> BoxRuntimeFuture<'_, Result>; + /// How long `start` may take before the thread shows that the provider is slow to start. + /// The launch keeps waiting. + fn start_notice_delay(&self) -> Duration { + PROVIDER_START_NOTICE_DELAY + } /// Whether `start`'s activity capabilities are all this process will report. When false, a /// startup `ActivityCapabilities::none()` means "not known yet": a restarted session keeps /// what its previous process reported until the new one reports its own. @@ -563,6 +609,11 @@ pub trait ProviderDriver: Send + Sync { fn resume_refused(&self) -> bool { false } + /// Whether the driver retired its process, such as a Cursor whose stopped turn ignored the + /// cancel: the session takes nothing more, so the next message launches it again. + fn retired(&self) -> bool { + false + } } pub trait ProviderDriverFactory: Send + Sync { @@ -622,6 +673,10 @@ pub enum ProviderRuntimeError { StaleSession { thread_id: String, action: String }, #[error("thread {thread_id} already has an active provider runtime")] SessionAlreadyExists { thread_id: String }, + /// The user stopped the thread while its provider was still starting. Nothing was sent, and + /// the message the launch was for is settled, never sent again. + #[error("thread {thread_id}'s provider start was stopped")] + LaunchStopped { thread_id: String }, /// A reconciliation launch found the frozen conversation gone and started nothing. #[error("the provider no longer has thread {thread_id}'s frozen conversation")] FrozenConversationLost { thread_id: String }, @@ -702,6 +757,8 @@ pub struct ProviderRuntimeSupervisor { connect_mcp: Arc>>>, open_url: Option, activity_cancellation: Arc>>, + /// Reaches a launch whose start has not returned, outside the queue the start blocks. + launch_stops: crate::orchestration::engine::LaunchStops, } #[derive(Clone)] @@ -732,6 +789,8 @@ enum SupervisorMessage { context_handoff: bool, /// The frozen start this launch resumes the conversation for. frozen_delivery: Option>, + /// The message whose delivery or reconciliation needs this launch; its Dismiss stops it. + message_id: Option, /// Fail with `FrozenConversationLost`, keeping the saved cursor, instead of continuing in /// a new conversation when the requested one is gone. abort_on_lost_resume: bool, @@ -907,6 +966,8 @@ impl PublicationTestGate { #[derive(Clone, Debug, Default)] struct AcceptedPublicationTestHook { before_publication: Option>, + /// Pauses a delivery after its row is frozen and before its prompt is sent. + before_send: Option>, after_runtime: Option>, publication_enqueued: Option>, admission_waiting: Option>, @@ -955,7 +1016,10 @@ struct SessionPublicationState { type SessionPublicationFence = Arc>; struct SessionEntry { + /// Holds the modes the thread asked for, confirmed or not: a restart launches with them. launch: ProviderLaunchRequest, + /// The modes the live driver acknowledged, per mode; a turn re-sends each one that differs. + confirmed_modes: Arc>, /// The retired Codex model the launch dropped, spelled as it was requested (#380 R4): the /// turns admitted before the drop fingerprint that spelling. dropped_model: Option, @@ -1296,6 +1360,7 @@ impl ProviderRuntimeSupervisor { let worker_sender = sender.clone(); let activity_cancellation = Arc::new(RwLock::new(None)); let worker_activity_cancellation = activity_cancellation.clone(); + let launch_stops = engine.launch_stops(); let worker = tokio::spawn(async move { run_supervisor( engine, @@ -1328,6 +1393,7 @@ impl ProviderRuntimeSupervisor { connect_mcp: Arc::new(RwLock::new(None)), open_url, activity_cancellation, + launch_stops, } } @@ -1343,7 +1409,7 @@ impl ProviderRuntimeSupervisor { } pub async fn launch(&self, request: ProviderLaunchRequest) -> Result<(), ProviderRuntimeError> { - self.launch_with_context_handoff(request, false, None, false) + self.launch_with_context_handoff(request, false, None, None, false) .await .map(|_| ()) } @@ -1353,8 +1419,9 @@ impl ProviderRuntimeSupervisor { async fn launch_for_reconciliation( &self, request: ProviderLaunchRequest, + message_id: Option, ) -> Result<(), ProviderRuntimeError> { - self.launch_with_context_handoff(request, false, None, true) + self.launch_with_context_handoff(request, false, None, message_id, true) .await .map(|_| ()) } @@ -1368,6 +1435,7 @@ impl ProviderRuntimeSupervisor { mut request: ProviderLaunchRequest, context_handoff: bool, frozen_delivery: Option, + message_id: Option, abort_on_lost_resume: bool, ) -> Result, ProviderRuntimeError> { if request.mcp.is_none() @@ -1407,6 +1475,7 @@ impl ProviderRuntimeSupervisor { request: Box::new(request), context_handoff, frozen_delivery: frozen_delivery.map(Box::new), + message_id, abort_on_lost_resume, response, }) @@ -1462,13 +1531,68 @@ impl ProviderRuntimeSupervisor { &self, command: OrchestrationCommand, ) -> Result<(), ProviderRuntimeError> { - self.request(|response| SupervisorMessage::Handle { - command: Box::new(command), - response, - }) + self.handle_orchestration_for(command, None).await + } + + /// Interrupts the thread after a server-side cancel committed: the Dismiss of + /// `dismissed_message_id`, or a panel's archive (`None`), which stops all of its work. + pub(crate) async fn interrupt_after_cancel( + &self, + command_id: String, + thread_id: String, + created_at: String, + dismissed_message_id: Option<&str>, + ) -> Result<(), ProviderRuntimeError> { + self.handle_orchestration_for( + OrchestrationCommand::ThreadTurnInterrupt { + command_id: format!("{command_id}:provider-interrupt"), + thread_id, + turn_id: None, + created_at, + }, + dismissed_message_id, + ) .await } + async fn handle_orchestration_for( + &self, + command: OrchestrationCommand, + launch_target: Option<&str>, + ) -> Result<(), ProviderRuntimeError> { + // A stop ends a start that has not returned first: the queue awaits that start. A launch + // has no turn yet, so an interrupt naming a turn (a late Stop, a compaction's own + // interrupt) is not aimed at it. + let launch = match &command { + OrchestrationCommand::ThreadTurnInterrupt { + thread_id, + turn_id: None, + .. + } + | OrchestrationCommand::ThreadSessionStop { thread_id, .. } => { + self.launch_stops.stop(thread_id, launch_target) + } + _ => crate::orchestration::engine::LaunchStopResult::NoLaunch, + }; + // Another message's launch is in flight, so the thread has no session the dismissed + // message could run in. Queued, the interrupt would wait behind that start. + if launch == crate::orchestration::engine::LaunchStopResult::OtherMessage { + return Ok(()); + } + let stopped_launch = launch == crate::orchestration::engine::LaunchStopResult::Stopped; + let result = self + .request(|response| SupervisorMessage::Handle { + command: Box::new(command), + response, + }) + .await; + match result { + // The stop ended the start, so there is no session left to stop. + Err(ProviderRuntimeError::SessionNotFound { .. }) if stopped_launch => Ok(()), + result => result, + } + } + pub async fn capture_session_identity( &self, thread_id: &str, @@ -1654,6 +1778,7 @@ impl ProviderRuntimeSupervisor { if self.stopped.is_cancelled() { return Ok(()); } + self.launch_stops.stop_all_for_shutdown(); let result = self .request(|response| SupervisorMessage::Shutdown { response }) .await; @@ -1786,12 +1911,17 @@ pub async fn route_orchestration_command( let action = command.command_type().to_owned(); match supervisor.handle_orchestration(command.clone()).await { - Ok(()) => Ok(()), + // The user stopped the thread while the command's restart started: nothing more to do. + Ok(()) | Err(ProviderRuntimeError::LaunchStopped { .. }) => Ok(()), Err(ProviderRuntimeError::SessionNotFound { .. }) if matches!(command, OrchestrationCommand::ThreadTurnStart { .. }) => { let request = launch_request_for_command(engine, settings_root, &command, None).await?; - supervisor.launch(request).await?; + match supervisor.launch(request).await { + // The user stopped the thread while it started: nothing more to do. + Err(ProviderRuntimeError::LaunchStopped { .. }) => return Ok(()), + launched => launched?, + } supervisor.handle_orchestration(command).await } Err(ProviderRuntimeError::SessionNotFound { .. }) @@ -2169,6 +2299,7 @@ async fn deliver_orchestration_turn_with_identity( request, started_new_conversation, frozen_delivery.clone(), + frozen_delivery.as_ref().map(|row| row.message_id.clone()), false, ) .await @@ -2253,10 +2384,11 @@ fn frozen_failure_outcome( label: Option<&str>, ) -> ProviderDeliveryOutcome { let detail = delivery_detail(error, label); - if matches!(error, ProviderRuntimeError::InvalidOption { .. }) { - ProviderDeliveryOutcome::Refused { detail } - } else { - ProviderDeliveryOutcome::Rejected { detail } + match error { + ProviderRuntimeError::InvalidOption { .. } => ProviderDeliveryOutcome::Refused { detail }, + // The user stopped the restart the delivery needed: settled, never sent again. + ProviderRuntimeError::LaunchStopped { .. } => ProviderDeliveryOutcome::StoppedUnsent, + _ => ProviderDeliveryOutcome::Rejected { detail }, } } @@ -2267,6 +2399,8 @@ fn frozen_failure_outcome( fn launch_failure_outcome(error: &ProviderRuntimeError, label: &str) -> ProviderDeliveryOutcome { let detail = delivery_detail(error, Some(label)); match error { + // The user stopped it: settled, so the stopped message is never sent again. + ProviderRuntimeError::LaunchStopped { .. } => ProviderDeliveryOutcome::StoppedUnsent, ProviderRuntimeError::InvalidOption { .. } => ProviderDeliveryOutcome::Refused { detail }, ProviderRuntimeError::IncompatibleProvider { .. } | ProviderRuntimeError::MissingExecutable { .. } @@ -2282,11 +2416,35 @@ fn launch_failure_outcome(error: &ProviderRuntimeError, label: &str) -> Provider mod delivery_failure_tests { use super::*; + /// A disabled Antigravity account is never retried: a launch or a send that meets it fails + /// the message once, with the clear sentence and Google's own words in the details. + #[test] + fn a_disabled_antigravity_account_fails_the_message_once() { + let disabled = || AntigravityRuntimeError::AccountDisabled { + google_message: "Placeholder notice from Google.".to_owned(), + }; + let error = super::antigravity_error(disabled()); + let detail = delivery_detail(&error, None); + assert_eq!( + detail, + "Google has disabled Antigravity for this account. Appeal through Google to restore \ + access. Google's message: Placeholder notice from Google." + ); + assert!(matches!( + launch_failure_outcome(&error, "Antigravity"), + ProviderDeliveryOutcome::Rejected { .. } + )); + assert!(matches!( + super::antigravity_unsent_outcome(disabled()), + ProviderDeliveryOutcome::Rejected { .. } + )); + } + #[test] fn transport_line_too_long_rejects_direct_and_nested_launch_errors() { use crate::provider::{codex::protocol::ProtocolError, cursor::acp::AcpProtocolError}; - for provider in ["codex", "cursor", "grok"] { + for provider in ["codex", "cursor", "grok", "antigravity"] { let detail = if provider == "codex" { ProtocolError::LineTooLong { stream: "stdout", @@ -2356,7 +2514,7 @@ mod delivery_failure_tests { let error = ProviderRuntimeError::InvalidOption { provider: "codex".to_owned(), detail: "invalid service tier".to_owned(), - refusal: "Fast Mode is not supported by the selected model.".to_owned(), + refusal: "Fast Mode is not supported by the selected model. Choose another option for this model.".to_owned(), }; let expected = ProviderDeliveryOutcome::Refused { detail: delivery_detail(&error, Some("Work Codex")), @@ -2491,6 +2649,9 @@ pub(crate) fn delivery_detail( ProviderRuntimeError::SessionAlreadyExists { .. } => { "A session is already running for this thread.".to_owned() } + ProviderRuntimeError::LaunchStopped { .. } => { + "The chat was stopped while its agent was starting.".to_owned() + } ProviderRuntimeError::FrozenConversationLost { .. } => { RECONCILED_CONVERSATION_LOST_DETAIL.to_owned() } @@ -2539,6 +2700,7 @@ pub(crate) fn provider_display_name(provider_kind: &str) -> &str { "cursor" => "Cursor", "grok" => "Grok", "opencode" => "OpenCode", + "antigravity" => "Antigravity", other => other, } } @@ -2639,6 +2801,8 @@ fn delivery_enqueue_failure( let detail = delivery_detail(error, provider_label); match error { ProviderRuntimeError::ResponseDropped => ProviderDeliveryOutcome::Ambiguous { detail }, + // The user stopped the restart the delivery needed: settled, never sent again. + ProviderRuntimeError::LaunchStopped { .. } => ProviderDeliveryOutcome::StoppedUnsent, _ => ProviderDeliveryOutcome::DefinitelyNotSent { detail }, } } @@ -2677,7 +2841,10 @@ pub async fn reconcile_orchestration_turn( }; } let label = request.provider_label.clone(); - match supervisor.launch_for_reconciliation(request).await { + match supervisor + .launch_for_reconciliation(request, Some(row.message_id.clone())) + .await + { Ok(()) => {} Err(ProviderRuntimeError::FrozenConversationLost { .. }) => { return ProviderReconciliationOutcome::ConversationLost { @@ -3184,6 +3351,29 @@ mod workspace_loss_tests { compact_hangs: Arc, interrupts: Arc, agent_deliveries: Arc, + /// Every runtime mode written, and whether the write fails. + mode_calls: Arc>>, + mode_fails: Arc, + /// A mode write waits for `mode_release` while set: a CLI that withholds its answer. + mode_held: Arc, + mode_release: Arc, + /// The first launch reports its process retired while set, and refuses settings. + first_launch_retired: Arc, + /// `start` waits for `start_release` while set, as a CLI waiting on an MCP server that + /// never connects, and the start notice shows sooner. + start_hangs: Arc, + start_release: Arc, + /// `set_options` signals `options_entered`, then waits for `options_release` while set, + /// as a Cursor `session/set_config_option` or a Codex `model/list` that withholds its + /// answer. + options_hang: Arc, + options_entered: Arc, + options_release: Arc, + launches: Arc, + launch_index: usize, + /// The text of every turn delivered, and the outcomes the next deliveries answer. + delivered_texts: Arc>>, + delivery_outcomes: Arc>>, } type CompactScript = (ProviderCompactionStart, Vec); @@ -3196,14 +3386,26 @@ mod workspace_loss_tests { Box::pin(async move { let mut driver = self.clone(); driver.thread_id = request.thread_id; + driver.launch_index = self.launches.fetch_add(1, Ordering::SeqCst) + 1; Ok(Arc::new(driver) as Arc) }) } } impl ProviderDriver for LossDriver { + fn start_notice_delay(&self) -> Duration { + if self.start_hangs.load(Ordering::SeqCst) { + Duration::from_millis(200) + } else { + PROVIDER_START_NOTICE_DELAY + } + } + fn start(&self) -> BoxRuntimeFuture<'_, Result> { Box::pin(async { + if self.start_hangs.load(Ordering::SeqCst) { + self.start_release.notified().await; + } Ok(StartedSession { resume_cursor: Some(json!({"threadId":"loss-native-session"})), ..StartedSession::default() @@ -3228,6 +3430,28 @@ mod workspace_loss_tests { }) } + fn deliver( + &self, + text: String, + attachments: Vec, + interaction_mode: String, + _: String, + ) -> BoxRuntimeFuture<'_, ProviderDeliveryOutcome> { + Box::pin(async move { + self.delivered_texts.lock().unwrap().push(text.clone()); + let scripted = self.delivery_outcomes.lock().unwrap().pop_front(); + if let Some(outcome) = scripted { + return outcome; + } + match self.send(text, attachments, interaction_mode).await { + Ok(turn_id) => ProviderDeliveryOutcome::Accepted { turn_id }, + Err(error) => ProviderDeliveryOutcome::Ambiguous { + detail: delivery_detail(&error, None), + }, + } + }) + } + fn deliver_agent_message( &self, text: String, @@ -3319,19 +3543,50 @@ mod workspace_loss_tests { Box::pin(async { Ok(()) }) } - fn set_mode(&self, _: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { - Box::pin(async { Ok(()) }) + fn set_mode(&self, mode: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.mode_calls.lock().unwrap().push(mode); + if self.mode_held.load(Ordering::SeqCst) { + self.mode_release.notified().await; + } + if self.mode_fails.load(Ordering::SeqCst) { + return Err(ProviderRuntimeError::Provider { + provider: "antigravity".to_owned(), + detail: "the mode was not confirmed".to_owned(), + }); + } + Ok(()) + }) } fn set_model(&self, _: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { - Box::pin(async { Ok(()) }) + let retired = self.retired(); + Box::pin(async move { + if retired { + return Err(ProviderRuntimeError::Provider { + provider: "codex".to_owned(), + detail: "the retired process is gone".to_owned(), + }); + } + Ok(()) + }) + } + + fn retired(&self) -> bool { + self.launch_index == 1 && self.first_launch_retired.load(Ordering::SeqCst) } fn set_options( &self, _: Vec, ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { - Box::pin(async { Ok(()) }) + Box::pin(async { + if self.options_hang.load(Ordering::SeqCst) { + self.options_entered.notify_one(); + self.options_release.notified().await; + } + Ok(()) + }) } fn rollback( @@ -3406,6 +3661,11 @@ mod workspace_loss_tests { } async fn with_hook(live: bool, hook: AcceptedPublicationTestHook) -> Self { + Self::build(live, hook, false).await + } + + /// With `side_chat`, `t1` is a side chat beside the host thread `h`. + async fn build(live: bool, hook: AcceptedPublicationTestHook, side_chat: bool) -> Self { let root = tempfile::tempdir().unwrap(); let database = Database::open_in_memory().await.unwrap(); database @@ -3419,10 +3679,21 @@ mod workspace_loss_tests { let engine = OrchestrationEngine::start(database, EngineOptions::default()) .await .unwrap(); - for command in [ + let threads = if side_chat { + vec![ + json!({"type":"thread.create","commandId":"host","threadId":"h","projectId":"p1","title":"Host","kind":"workspace","modelSelection":{"instanceId":"codex","model":"gpt-5"},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":BEFORE_LOSS}), + json!({"type":"thread.create","commandId":"thread","threadId":"t1","projectId":"p1","title":"Panel: Side chat · Codex","kind":"panel","hostThreadId":"h","sideChat":true,"modelSelection":{"instanceId":"codex","model":"gpt-5"},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":BEFORE_LOSS}), + ] + } else { + vec![ + json!({"type":"thread.create","commandId":"thread","threadId":"t1","projectId":"p1","title":"Thread","kind":"workspace","modelSelection":{"instanceId":"codex","model":"gpt-5"},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":BEFORE_LOSS}), + ] + }; + for command in std::iter::once( json!({"type":"project.create","commandId":"project","projectId":"p1","title":"Project","workspaceRoot":root.path(),"createdAt":BEFORE_LOSS}), - json!({"type":"thread.create","commandId":"thread","threadId":"t1","projectId":"p1","title":"Thread","kind":"workspace","modelSelection":{"instanceId":"codex","model":"gpt-5"},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":BEFORE_LOSS}), - ] { + ) + .chain(threads) + { engine .dispatch(serde_json::from_value(command).unwrap()) .await @@ -3876,264 +4147,1197 @@ mod workspace_loss_tests { f.shutdown().await; } - #[tokio::test] - async fn retrying_an_oversized_stdout_failure_delivers_on_a_healthy_relaunch() { - assert_oversized_head_recovers("retry").await; + /// A session whose process was retired (a Cursor stop the CLI ignored) is launched again for + /// the next message, even one that changes the model: it never reaches the retired process, + /// so it is delivered, not rejected. + const CODEX_START_NOTICE: &str = "Codex is taking longer than usual to start. One of its MCP \ + servers may not be responding; run `codex mcp list` in a \ + terminal to see which one."; + + impl Fixture { + /// Launches with a start that waits for `start_release`. + fn launch_hanging(&self) -> JoinHandle> { + self.driver.start_hangs.store(true, Ordering::SeqCst); + let supervisor = self.supervisor.clone(); + let launch = self.launch.clone(); + tokio::spawn(async move { supervisor.launch(launch).await }) + } + + async fn last_error(&self) -> Option { + self.engine + .repositories() + .get_thread_session("t1".into()) + .await + .unwrap() + .and_then(|session| session.last_error) + } + + async fn wait_for_start_notice(&self) { + timeout(Duration::from_secs(5), async { + while self.last_error().await.as_deref() != Some(CODEX_START_NOTICE) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the start notice is shown"); + } } + /// A start that does not return shows the notice at its notice delay and keeps waiting: the + /// driver is not stopped, and the launch completes normally once the start returns, which + /// clears the notice. #[tokio::test] - async fn dismissing_an_oversized_stdout_failure_releases_later_queued_messages() { - assert_oversized_head_recovers("dismiss").await; + async fn a_slow_start_shows_a_notice_and_completes_when_it_returns() { + let f = Fixture::new(false).await; + let launch = f.launch_hanging(); + f.wait_for_start_notice().await; + tokio::time::sleep(Duration::from_millis(400)).await; + assert!(!launch.is_finished(), "the start keeps waiting"); + assert_eq!( + f.driver.shutdowns.load(Ordering::SeqCst), + 0, + "never stopped" + ); + f.driver.start_release.notify_one(); + timeout(Duration::from_secs(5), launch) + .await + .expect("the launch ends once the start returns") + .unwrap() + .expect("the slow start completes normally"); + let session = f.session().await; + assert_eq!(session.status, "ready"); + assert_eq!(session.last_error, None, "the notice clears"); + assert_eq!(f.driver.shutdowns.load(Ordering::SeqCst), 0); + f.shutdown().await; } - /// A manual compaction of the fixture's live Codex conversation. - async fn request_compaction(f: &Fixture) -> String { - f.project("ready").await; - f.engine - .dispatch( - serde_json::from_value(json!({ - "type":"thread.compact", "commandId":"compact", "threadId":"t1", - "createdAt":BEFORE_LOSS, - })) - .unwrap(), + /// Stop, stopping the session, and deleting the thread each end a start that never returns, + /// although the supervisor's queue awaits it. The stopped message is settled, never sent + /// again, and none of them reports an error. + #[tokio::test] + async fn a_stop_ends_a_start_that_never_returns() { + for stop in ["interrupt", "session-stop", "delete"] { + let f = Fixture::new(false).await; + let launch = f.launch_hanging(); + f.wait_for_start_notice().await; + let command: OrchestrationCommand = serde_json::from_value(match stop { + "interrupt" => { + json!({"type":"thread.turn.interrupt","commandId":"stop","threadId":"t1","createdAt":BEFORE_LOSS}) + } + "session-stop" => { + json!({"type":"thread.session.stop","commandId":"stop","threadId":"t1","createdAt":BEFORE_LOSS}) + } + _ => json!({"type":"thread.delete","commandId":"stop","threadId":"t1"}), + }) + .unwrap(); + timeout( + Duration::from_secs(5), + route_orchestration_command( + &f.supervisor, + &f.engine, + &f._root.path().to_path_buf(), + command, + ), ) .await + .unwrap_or_else(|_| panic!("{stop} waited behind the start")) + .unwrap_or_else(|error| panic!("{stop} reported {error:?}")); + let error = timeout(Duration::from_secs(5), launch) + .await + .expect("the stop ends the launch") + .unwrap() + .expect_err("the start was stopped"); + assert!( + matches!(&error, ProviderRuntimeError::LaunchStopped { thread_id } if thread_id == "t1"), + "{stop}: {error:?}" + ); + assert!( + matches!( + launch_failure_outcome(&error, "launch"), + ProviderDeliveryOutcome::StoppedUnsent + ), + "{stop}: settled, so never sent again" + ); + assert_eq!(f.driver.shutdowns.load(Ordering::SeqCst), 1, "{stop}"); + assert_eq!(f.last_error().await, None, "{stop}: the notice clears"); + f.shutdown().await; + } + } + + /// Stop pressed while the started session's options are still being applied ends the launch + /// once they return: the session is shut down and never kept, so the message the user + /// stopped is settled as stopped and never sent. + #[tokio::test] + async fn a_stop_during_slow_options_settles_the_delivery_unsent() { + let f = Fixture::new(false).await; + f.driver.options_hang.store(true, Ordering::SeqCst); + let delivery = tokio::spawn({ + let supervisor = f.supervisor.clone(); + let engine = f.engine.clone(); + let root = f._root.path().to_path_buf(); + async move { + deliver_orchestration_turn( + &supervisor, + &engine, + &root, + turn("slow-options", false), + "slow-options-key".into(), + ) + .await + } + }); + timeout(Duration::from_secs(5), f.driver.options_entered.notified()) + .await + .expect("the start returned and options are being applied"); + let stop = tokio::spawn({ + let supervisor = f.supervisor.clone(); + let engine = f.engine.clone(); + let root = f._root.path().to_path_buf(); + async move { + route_orchestration_command( + &supervisor, + &engine, + &root, + serde_json::from_value(json!({ + "type":"thread.turn.interrupt","commandId":"stop","threadId":"t1", + "createdAt":BEFORE_LOSS, + })) + .unwrap(), + ) + .await + } + }); + tokio::time::sleep(Duration::from_millis(200)).await; + f.driver.options_release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("the delivery ends") .unwrap(); - f.engine - .unsettled_thread_compaction("t1") + assert_eq!(outcome, ProviderDeliveryOutcome::StoppedUnsent); + timeout(Duration::from_secs(5), stop) .await + .expect("Stop ends") .unwrap() - .expect("a requested compaction") - .compaction_id + .expect("Stop reports no error"); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "nothing was sent"); + assert_eq!( + f.driver.launches.load(Ordering::SeqCst), + 1, + "never relaunched" + ); + assert_eq!(f.driver.shutdowns.load(Ordering::SeqCst), 1); + f.shutdown().await; } - fn script(f: &Fixture, start: ProviderCompactionStart, events: Vec) { - *f.driver.compact_script.lock().unwrap() = Some((start, events)); - } + impl Fixture { + /// Seeds a durable start for `id` and claims it, as the delivery worker does: the + /// returned row is `sending`, the state the web Stop (Dismiss) cancels. + async fn claimed_delivery(&self, id: &str) -> (OrchestrationCommand, ProviderTurnDelivery) { + let command = self.admitted_delivery(id).await; + let row = self + .engine + .repositories() + .claim_provider_turn(id.into(), BEFORE_LOSS.into()) + .await + .unwrap() + .expect("the delivery is claimed"); + assert_eq!(row.state, TurnDeliveryState::Sending); + (command, row) + } - async fn drive(f: &Fixture, compaction_id: &str) -> ThreadCompactionRow { - timeout( - Duration::from_secs(10), - drive_thread_compaction( - &f.supervisor, - &f.engine, - &f._root.path().to_path_buf(), - compaction_id, - &CancellationToken::new(), - ), - ) - .await - .expect("a compaction settles within its bounds") - .unwrap(); - f.engine - .thread_compaction(compaction_id) + /// Seeds a durable start for `id`, left `pending`. + async fn admitted_delivery(&self, id: &str) -> OrchestrationCommand { + let command = turn(id, false); + let mut payload = serde_json::to_value(&command).unwrap(); + freeze_delivery_route( + &self.engine, + &self._root.path().to_path_buf(), + &command, + &mut payload, + ) .await - .unwrap() - .unwrap() - } - - fn started_compaction() -> ProviderCompactionStart { - ProviderCompactionStart::Started { - turn_id: Some("compaction-turn".to_owned()), + .unwrap(); + self.engine + .dispatch_with_admission( + command.clone(), + CommandAdmission { + payload_digest: canonical_command_digest(&command).unwrap(), + attachment_refs: Vec::new(), + provider_turn: Some(NewProviderTurnDelivery { + command_id: id.into(), + thread_id: "t1".into(), + message_id: id.into(), + provider_instance_id: "codex".into(), + provider_kind: "codex".into(), + provider_session_id: None, + delivery_key: format!("{id}-key"), + payload, + state: TurnDeliveryState::Pending, + mode: TurnDeliveryMode::Start, + created_at: BEFORE_LOSS.into(), + }), + agent_message: None, + }, + || {}, + ) + .await + .unwrap(); + command } - } - fn compaction_events(item: bool, state: &str) -> Vec { - let mut events = vec![core_event( - "turn.started", - "compaction-turn", - json!({"compactionId":"$id"}), - )]; - if item { - events.push(core_event( - "item.completed", - "compaction-turn", - json!({"itemType":"context_compaction","status":"completed","title":"Conversation compaction"}), - )); + /// The web Stop while the thread is not running: Dismiss of the message's delivery. + async fn dismiss(&self, id: &str) { + self.engine + .dispatch( + serde_json::from_value(json!({ + "type":"thread.turn-delivery.resolve","commandId":format!("dismiss-{id}"), + "threadId":"t1","messageId":id,"action":"dismiss","createdAt":BEFORE_LOSS, + })) + .unwrap(), + ) + .await + .unwrap(); } - events.push(core_event( - "turn.completed", - "compaction-turn", - json!({"state":state, "compactionId":"$id"}), - )); - events - } - fn with_bounds(run: Duration, grace: Duration, turn_start: Duration) { - COMPACTION_TEST_BOUNDS.with(|bounds| bounds.set(Some((run, grace, turn_start)))); - } + async fn delivery_state(&self, id: &str) -> TurnDeliveryState { + self.engine + .repositories() + .get_provider_turn_delivery(id.into()) + .await + .unwrap() + .unwrap() + .state + } - #[tokio::test] - async fn a_compaction_settles_completed_from_its_tagged_turn_and_item() { - let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - script( - &f, - started_compaction(), - compaction_events(true, "completed"), - ); - let row = drive(&f, &id).await; - assert_eq!(row.state, "completed"); - assert_eq!(row.turn_id.as_deref(), Some("compaction-turn")); - assert_eq!(*f.driver.compact_calls.lock().unwrap(), vec![id.clone()]); - assert_eq!(f.session().await.status, "ready"); - f.shutdown().await; + fn deliver_frozen( + &self, + command: OrchestrationCommand, + row: ProviderTurnDelivery, + ) -> JoinHandle { + let supervisor = self.supervisor.clone(); + let engine = self.engine.clone(); + let root = self._root.path().to_path_buf(); + tokio::spawn(async move { + let key = row.delivery_key.clone(); + deliver_orchestration_turn_with_identity( + &supervisor, + &engine, + &root, + command, + key, + Some(row), + ) + .await + }) + } } + /// The web Stop (Dismiss) landing while the launch the delivery needed is still applying + /// its options: the launch returns Ok and keeps the session, but the delivery reads the row + /// again after the launch, finds it dismissed, and sends nothing. #[tokio::test] - async fn a_compaction_turn_without_a_completed_compaction_item_fails() { - let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - script( - &f, - started_compaction(), - compaction_events(false, "completed"), - ); - let row = drive(&f, &id).await; - assert_eq!(row.state, "failed"); - let session = f.session().await; - assert_eq!(session.status, "error"); + async fn a_dismiss_during_the_launch_sends_nothing() { + let f = Fixture::new(false).await; + f.driver.options_hang.store(true, Ordering::SeqCst); + let (command, row) = f.claimed_delivery("dismissed-launch").await; + let delivery = f.deliver_frozen(command, row); + timeout(Duration::from_secs(5), f.driver.options_entered.notified()) + .await + .expect("the start returned and options are being applied"); + f.dismiss("dismissed-launch").await; + f.driver.options_release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("the delivery ends") + .unwrap(); assert!( - session - .last_error - .as_deref() - .is_some_and(|error| error.ends_with("couldn't compact the conversation.")), - "{:?}", - session.last_error + matches!(outcome, ProviderDeliveryOutcome::Rejected { .. }), + "{outcome:?}" + ); + assert_eq!(f.driver.launches.load(Ordering::SeqCst), 1); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "nothing was sent"); + assert!(f.driver.delivered_texts.lock().unwrap().is_empty()); + assert_eq!( + f.delivery_state("dismissed-launch").await, + TurnDeliveryState::Dismissed ); f.shutdown().await; } + /// The web Stop (Dismiss) landing after the launch returned Ok and its session was kept, but + /// before the queued Deliver runs, which still holds the row it read before the Dismiss: the + /// freeze only takes a `sending` row, so nothing is sent and the row stays dismissed. #[tokio::test] - async fn a_compaction_of_another_conversation_fails_without_asking_the_provider() { + async fn a_dismiss_after_the_launch_before_deliver_sends_nothing() { let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - f.engine - .repositories() - .database() - .call(|connection| { - connection.execute( - "UPDATE thread_compactions SET conversation_id = 'another-thread'", - [], - )?; - Ok(()) - }) + let (command, row) = f.claimed_delivery("dismissed-queued").await; + f.dismiss("dismissed-queued").await; + let outcome = timeout(Duration::from_secs(5), f.deliver_frozen(command, row)) .await + .expect("the delivery ends") .unwrap(); - script( - &f, - started_compaction(), - compaction_events(true, "completed"), + assert!( + matches!(outcome, ProviderDeliveryOutcome::DefinitelyNotSent { .. }), + "{outcome:?}" ); - let row = drive(&f, &id).await; - assert_eq!(row.state, "failed"); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "nothing was sent"); + assert!(f.driver.delivered_texts.lock().unwrap().is_empty()); assert_eq!( - row.detail.as_deref(), - Some("The thread's provider or conversation changed, so it wasn't compacted.") + f.delivery_state("dismissed-queued").await, + TurnDeliveryState::Dismissed ); - assert!(f.driver.compact_calls.lock().unwrap().is_empty()); f.shutdown().await; } + /// The web Stop (Dismiss) landing after Deliver froze the row and before the prompt is + /// written: the stopped prompt is settled unsent and never reaches the provider. #[tokio::test] - async fn an_unknown_request_that_starts_no_turn_ends_its_session() { - with_bounds( - Duration::from_secs(5), - Duration::from_millis(100), - Duration::from_millis(100), - ); - let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - script( - &f, - ProviderCompactionStart::Unknown { - detail: "the answer was lost".to_owned(), + async fn a_dismiss_after_the_freeze_before_the_send_sends_nothing() { + let gate = Arc::new(PublicationTestGate::default()); + let f = Fixture::with_hook( + true, + AcceptedPublicationTestHook { + before_send: Some(gate.clone()), + ..AcceptedPublicationTestHook::default() }, - Vec::new(), - ); - let row = drive(&f, &id).await; - assert_eq!(row.state, "failed"); + ) + .await; + let (command, row) = f.claimed_delivery("dismissed-frozen").await; + let delivery = f.deliver_frozen(command, row); + timeout(Duration::from_secs(5), gate.entered.notified()) + .await + .expect("the row is frozen and the send is next"); + f.dismiss("dismissed-frozen").await; + gate.release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("the delivery ends") + .unwrap(); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "nothing was sent"); + assert!(f.driver.delivered_texts.lock().unwrap().is_empty()); + assert_eq!(outcome, ProviderDeliveryOutcome::StoppedUnsent); assert_eq!( - row.detail.as_deref(), - Some("BiBCode couldn't confirm whether the conversation was compacted.") - ); - assert!( - f.supervisor - .capture_session_identity("t1") - .await - .unwrap() - .is_none(), - "the session that may hold the compaction ended" + f.delivery_state("dismissed-frozen").await, + TurnDeliveryState::Dismissed ); - // Its saved conversation stays, so the next message resumes it. - assert!(f.runtime().await["resume_cursor"].is_object()); f.shutdown().await; } + /// Dismissing a stuck message A commits, wakes the worker, and only then sends its follow-up + /// interrupt. The worker may claim the next message B and start B's launch in between; that + /// interrupt must not stop B's launch, which would settle B as stopped although the user + /// only stopped A. #[tokio::test] - async fn a_compaction_at_its_bound_is_interrupted_then_its_session_ended() { - with_bounds( - Duration::from_millis(200), - Duration::from_millis(100), - Duration::from_secs(5), - ); - let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - script( - &f, - started_compaction(), - vec![core_event( - "turn.started", - "compaction-turn", - json!({"compactionId":"$id"}), - )], - ); - let row = drive(&f, &id).await; - assert_eq!(row.state, "failed"); - assert!( - f.supervisor - .capture_session_identity("t1") - .await - .unwrap() - .is_none() + async fn a_dismiss_follow_up_does_not_stop_the_next_message_launch() { + let f = Fixture::new(false).await; + let _ = f.claimed_delivery("stuck-a").await; + f.dismiss("stuck-a").await; + f.driver.options_hang.store(true, Ordering::SeqCst); + let (command, row) = f.claimed_delivery("next-b").await; + let delivery = f.deliver_frozen(command, row); + timeout(Duration::from_secs(5), f.driver.options_entered.notified()) + .await + .expect("B's launch is applying its options"); + let follow_up = tokio::spawn({ + let supervisor = f.supervisor.clone(); + async move { + supervisor + .interrupt_after_cancel( + "dismiss-stuck-a".into(), + "t1".into(), + BEFORE_LOSS.into(), + Some("stuck-a"), + ) + .await + } + }); + // The Dismiss answers at once: it never waits behind the other message's launch. + timeout(Duration::from_secs(2), follow_up) + .await + .expect("the Dismiss follow-up answers while the other launch runs") + .unwrap() + .expect("the Dismiss follow-up reports no error"); + f.driver.options_release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("B's delivery ends") + .unwrap(); + assert_ne!( + outcome, + ProviderDeliveryOutcome::StoppedUnsent, + "B was dropped" ); - let session = f.session().await; - assert_eq!(session.status, "error"); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 1, "B was sent"); assert_eq!( - session.last_error.as_deref(), - Some("BiBCode couldn't confirm whether the conversation was compacted.") + f.delivery_state("stuck-a").await, + TurnDeliveryState::Dismissed + ); + assert_ne!( + f.delivery_state("next-b").await, + TurnDeliveryState::Dismissed ); - assert_eq!(session.active_turn_id, None); f.shutdown().await; } + /// Dismissing a newer pending message B, while the launch for the message A ahead of it is + /// running, must not stop A's launch: A is sent, never settled as stopped. #[tokio::test] - async fn the_completion_of_an_earlier_compaction_settles_nothing() { - with_bounds( - Duration::from_millis(300), - Duration::from_millis(100), - Duration::from_secs(5), + async fn dismissing_a_pending_message_does_not_stop_the_launch_ahead_of_it() { + let f = Fixture::new(false).await; + f.driver.options_hang.store(true, Ordering::SeqCst); + let (command, row) = f.claimed_delivery("running-a").await; + let delivery = f.deliver_frozen(command, row); + timeout(Duration::from_secs(5), f.driver.options_entered.notified()) + .await + .expect("A's launch is applying its options"); + f.admitted_delivery("pending-b").await; + f.dismiss("pending-b").await; + let follow_up = tokio::spawn({ + let supervisor = f.supervisor.clone(); + async move { + supervisor + .interrupt_after_cancel( + "dismiss-pending-b".into(), + "t1".into(), + BEFORE_LOSS.into(), + Some("pending-b"), + ) + .await + } + }); + // The Dismiss answers at once: it never waits behind the other message's launch. + timeout(Duration::from_secs(2), follow_up) + .await + .expect("the Dismiss follow-up answers while the other launch runs") + .unwrap() + .expect("the Dismiss follow-up reports no error"); + f.driver.options_release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("A's delivery ends") + .unwrap(); + assert_ne!( + outcome, + ProviderDeliveryOutcome::StoppedUnsent, + "A was dropped" ); - let f = Fixture::new(true).await; - let id = request_compaction(&f).await; - script( - &f, - started_compaction(), - vec![ - core_event( - "turn.started", - "compaction-turn", - json!({"compactionId":"$id"}), - ), - core_event( - "turn.completed", - "compaction-turn", - json!({"state":"completed", "compactionId":"compaction:earlier"}), - ), - ], + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 1, "A was sent"); + assert_eq!( + f.delivery_state("pending-b").await, + TurnDeliveryState::Dismissed ); - let row = drive(&f, &id).await; - assert_ne!(row.state, "completed"); + f.shutdown().await; + } + + /// The Dismiss of a message whose reconciliation launch hangs still ends that launch, and the + /// Dismiss of another message does not. + #[tokio::test] + async fn a_dismiss_ends_only_its_own_reconciliation_launch() { + for own in [false, true] { + let f = Fixture::new(false).await; + let (_, row) = f.claimed_delivery("reconciling").await; + f.driver.start_hangs.store(true, Ordering::SeqCst); + let reconcile = tokio::spawn({ + let supervisor = f.supervisor.clone(); + let engine = f.engine.clone(); + let root = f._root.path().to_path_buf(); + async move { reconcile_orchestration_turn(&supervisor, &engine, &root, row).await } + }); + timeout(Duration::from_secs(5), async { + while !f.engine.thread_session_launching("t1") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the reconciliation launch started"); + let stopped = f + .supervisor + .launch_stops + .stop("t1", Some(if own { "reconciling" } else { "another" })); + assert_eq!( + stopped, + if own { + crate::orchestration::engine::LaunchStopResult::Stopped + } else { + crate::orchestration::engine::LaunchStopResult::OtherMessage + } + ); + if !own { + f.driver.start_release.notify_one(); + } + timeout(Duration::from_secs(5), reconcile) + .await + .unwrap_or_else(|_| panic!("own={own}: the reconciliation ends")) + .unwrap(); + f.shutdown().await; + } + } + + /// A plain Stop, and the follow-up of a Dismiss of the launching message itself, still end + /// a launch made for a durable delivery. + #[tokio::test] + async fn a_plain_stop_or_own_dismiss_still_stops_a_delivery_launch() { + for own_dismiss in [false, true] { + let f = Fixture::new(false).await; + f.driver.options_hang.store(true, Ordering::SeqCst); + let (command, row) = f.claimed_delivery("launching").await; + let delivery = f.deliver_frozen(command, row); + timeout(Duration::from_secs(5), f.driver.options_entered.notified()) + .await + .expect("the launch is applying its options"); + let stop = tokio::spawn({ + let supervisor = f.supervisor.clone(); + async move { + supervisor + .interrupt_after_cancel( + "stop".into(), + "t1".into(), + BEFORE_LOSS.into(), + own_dismiss.then_some("launching"), + ) + .await + } + }); + tokio::time::sleep(Duration::from_millis(200)).await; + f.driver.options_release.notify_one(); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("the delivery ends") + .unwrap(); + assert_eq!( + outcome, + ProviderDeliveryOutcome::StoppedUnsent, + "{own_dismiss}" + ); + timeout(Duration::from_secs(5), stop) + .await + .expect("the stop ends") + .unwrap() + .expect("the stop reports no error"); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "{own_dismiss}"); + f.shutdown().await; + } + } + + impl Fixture { + /// Launches with a start that returns at once and options that wait for + /// `options_release`, once the options are being applied. + async fn launch_with_hanging_options( + &self, + ) -> JoinHandle> { + self.driver.options_hang.store(true, Ordering::SeqCst); + let supervisor = self.supervisor.clone(); + let launch = self.launch.clone(); + let handle = tokio::spawn(async move { supervisor.launch(launch).await }); + timeout( + Duration::from_secs(5), + self.driver.options_entered.notified(), + ) + .await + .expect("options are being applied"); + handle + } + } + + /// Stop, stopping the session and deleting the thread each end a launch whose options never + /// return, as they end a start that never returns. + #[tokio::test] + async fn a_stop_ends_options_that_never_return() { + for stop in ["interrupt", "session-stop", "delete"] { + let f = Fixture::new(false).await; + let launch = f.launch_with_hanging_options().await; + let command: OrchestrationCommand = serde_json::from_value(match stop { + "interrupt" => { + json!({"type":"thread.turn.interrupt","commandId":"stop","threadId":"t1","createdAt":BEFORE_LOSS}) + } + "session-stop" => { + json!({"type":"thread.session.stop","commandId":"stop","threadId":"t1","createdAt":BEFORE_LOSS}) + } + _ => json!({"type":"thread.delete","commandId":"stop","threadId":"t1"}), + }) + .unwrap(); + timeout( + Duration::from_secs(5), + route_orchestration_command( + &f.supervisor, + &f.engine, + &f._root.path().to_path_buf(), + command, + ), + ) + .await + .unwrap_or_else(|_| panic!("{stop} waited behind the options")) + .unwrap_or_else(|error| panic!("{stop} reported {error:?}")); + let error = timeout(Duration::from_secs(5), launch) + .await + .unwrap_or_else(|_| panic!("{stop} did not end the launch")) + .unwrap() + .expect_err("the launch was stopped"); + assert!( + matches!(&error, ProviderRuntimeError::LaunchStopped { thread_id } if thread_id == "t1"), + "{stop}: {error:?}" + ); + assert_eq!(f.driver.shutdowns.load(Ordering::SeqCst), 1, "{stop}"); + f.shutdown().await; + } + } + + /// The server's shutdown ends a launch whose options never return, mapped as a shutdown + /// that ended a start: nothing was sent. + #[tokio::test] + async fn shutdown_ends_options_that_never_return() { + let f = Fixture::new(false).await; + let launch = f.launch_with_hanging_options().await; + timeout(Duration::from_secs(5), f.supervisor.shutdown()) + .await + .expect("the shutdown is not stuck behind the options") + .unwrap(); + let error = timeout(Duration::from_secs(5), launch) + .await + .expect("the shutdown ends the launch") + .unwrap() + .expect_err("the launch was stopped"); + assert!(matches!(error, ProviderRuntimeError::Shutdown), "{error:?}"); + assert!( + matches!( + launch_failure_outcome(&error, "launch"), + ProviderDeliveryOutcome::DefinitelyNotSent { .. } + ), + "{error:?}" + ); + f.engine.shutdown().await; + } + + /// The delivery a hung start was for: Stop settles it as stopped (never sent again, so + /// never launched again), while an interrupt naming a turn, which cannot be aimed at a + /// start, leaves the start waiting. + #[tokio::test] + async fn a_stopped_start_settles_its_delivery_and_a_turn_interrupt_does_not_stop_it() { + let f = Fixture::new(false).await; + f.driver.start_hangs.store(true, Ordering::SeqCst); + let delivery = tokio::spawn({ + let supervisor = f.supervisor.clone(); + let engine = f.engine.clone(); + let root = f._root.path().to_path_buf(); + async move { + deliver_orchestration_turn( + &supervisor, + &engine, + &root, + turn("hung", false), + "hung-key".into(), + ) + .await + } + }); + f.wait_for_start_notice().await; + let interrupt = |turn_id: Option<&str>| -> OrchestrationCommand { + serde_json::from_value(json!({ + "type":"thread.turn.interrupt","commandId":format!("stop-{turn_id:?}"), + "threadId":"t1","turnId":turn_id,"createdAt":BEFORE_LOSS, + })) + .unwrap() + }; + let late = tokio::spawn({ + let supervisor = f.supervisor.clone(); + let command = interrupt(Some("earlier-turn")); + async move { supervisor.handle_orchestration(command).await } + }); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + !delivery.is_finished(), + "a turn's interrupt left the start waiting" + ); + timeout( + Duration::from_secs(5), + route_orchestration_command( + &f.supervisor, + &f.engine, + &f._root.path().to_path_buf(), + interrupt(None), + ), + ) + .await + .expect("Stop is not stuck behind the start") + .expect("Stop reports no error"); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("Stop ends the delivery's launch") + .unwrap(); + assert_eq!(outcome, ProviderDeliveryOutcome::StoppedUnsent); + let _ = timeout(Duration::from_secs(5), late).await; + assert_eq!(f.driver.launches.load(Ordering::SeqCst), 1); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 0, "nothing was sent"); + f.shutdown().await; + } + + /// The start notice keeps the session's own state: a ready session reads ready with the + /// notice, and Stop puts back what it showed before. + #[tokio::test] + async fn the_start_notice_keeps_and_restores_the_sessions_state() { + let f = Fixture::new(false).await; + f.project("ready").await; + let launch = f.launch_hanging(); + f.wait_for_start_notice().await; + let session = f.session().await; + assert_eq!(session.status, "ready"); + assert_eq!(session.active_turn_id, None); + timeout( + Duration::from_secs(5), + route_orchestration_command( + &f.supervisor, + &f.engine, + &f._root.path().to_path_buf(), + serde_json::from_value(json!({ + "type":"thread.turn.interrupt","commandId":"stop","threadId":"t1", + "createdAt":BEFORE_LOSS, + })) + .unwrap(), + ), + ) + .await + .expect("Stop is not stuck behind the start") + .expect("Stop reports no error"); + timeout(Duration::from_secs(5), launch) + .await + .expect("Stop ends the launch") + .unwrap() + .expect_err("the start was stopped"); + let session = f.session().await; + assert_eq!(session.status, "ready"); + assert_eq!(session.last_error, None); + f.shutdown().await; + } + + /// The server's shutdown ends a start that never returns too. Nothing was sent, so the + /// message waits for the next start of the server. + #[tokio::test] + async fn shutdown_ends_a_start_that_never_returns() { + let f = Fixture::new(false).await; + let launch = f.launch_hanging(); + f.wait_for_start_notice().await; + timeout(Duration::from_secs(5), f.supervisor.shutdown()) + .await + .expect("the shutdown is not stuck behind the start") + .unwrap(); + let error = timeout(Duration::from_secs(5), launch) + .await + .unwrap() + .unwrap() + .expect_err("the start was stopped"); + assert!( + matches!( + launch_failure_outcome(&error, "launch"), + ProviderDeliveryOutcome::DefinitelyNotSent { .. } + ), + "{error:?}" + ); + f.engine.shutdown().await; + } + + /// What a Cursor delivery answers for a prompt the user stopped before any of it was sent. + const STOPPED_UNSENT_OUTCOME: ProviderDeliveryOutcome = ProviderDeliveryOutcome::StoppedUnsent; + + /// (d) A side chat's first prompt that the user stopped before any of it was sent leaves its + /// host's context owed: the next prompt still carries it. + #[tokio::test] + async fn a_stopped_unsent_first_side_chat_prompt_leaves_the_host_context_owed() { + let f = Fixture::build(true, AcceptedPublicationTestHook::default(), true).await; + f.driver + .delivery_outcomes + .lock() + .unwrap() + .push_back(STOPPED_UNSENT_OUTCOME); + for id in ["first", "second"] { + let delivery = f + .supervisor + .deliver_turn(turn(id, false), format!("{id}-key")) + .await + .unwrap(); + timeout(Duration::from_secs(5), delivery.completion()) + .await + .expect("the delivery ends"); + } + let texts = f.driver.delivered_texts.lock().unwrap().clone(); + assert_eq!(texts.len(), 2, "{texts:?}"); + assert!( + texts[0].starts_with(""), + "{texts:?}" + ); + assert!( + texts[1].starts_with(""), + "the host's context is still owed: {texts:?}" + ); + f.shutdown().await; + } + + #[test] + fn a_start_notice_names_the_mcp_check_only_where_the_cli_has_one() { + assert_eq!( + start_notice("claudeAgent"), + "Claude is taking longer than usual to start. One of its MCP servers may not be \ + responding; run `claude mcp list` in a terminal to see which one." + ); + assert!(start_notice("opencode").contains("`opencode mcp list`")); + assert!(start_notice("antigravity").contains("`agy mcp list`")); + assert!(start_notice("cursor").contains("`cursor-agent mcp list`")); + assert_eq!( + start_notice("grok"), + "Grok is taking longer than usual to start." + ); + } + + #[tokio::test] + async fn the_next_message_after_a_retired_process_relaunches_the_session() { + use crate::production::turn_delivery::TurnDeliveryService; + let f = Fixture::new(false).await; + let supervisor = Arc::new(ProviderRuntimeSupervisor::start( + f.engine.clone(), + f.driver.clone(), + ActivityProjection::new(ActivityRepository::new( + f.engine.repositories().database().clone(), + )), + SupervisorOptions::default(), + )); + supervisor.launch(f.launch.clone()).await.unwrap(); + f.project("ready").await; + f.driver.first_launch_retired.store(true, Ordering::SeqCst); + let command: OrchestrationCommand = serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":"next", "threadId":"t1", "queued":false, + "message":{"messageId":"next","role":"user","text":"continue","attachments":[]}, + "modelSelection":{"instanceId":"codex","model":"gpt-5.5"}, + "runtimeMode":"full-access", "interactionMode":"default", "createdAt":BEFORE_LOSS, + })) + .unwrap(); + let mut payload = serde_json::to_value(&command).unwrap(); + freeze_delivery_route( + &f.engine, + &f._root.path().to_path_buf(), + &command, + &mut payload, + ) + .await + .unwrap(); + f.engine + .dispatch_with_admission( + command.clone(), + CommandAdmission { + payload_digest: canonical_command_digest(&command).unwrap(), + attachment_refs: Vec::new(), + provider_turn: Some(NewProviderTurnDelivery { + command_id: "next".into(), + thread_id: "t1".into(), + message_id: "next".into(), + provider_instance_id: "codex".into(), + provider_kind: "codex".into(), + provider_session_id: None, + delivery_key: "next-key".into(), + payload, + state: TurnDeliveryState::Pending, + mode: TurnDeliveryMode::Start, + created_at: BEFORE_LOSS.into(), + }), + agent_message: None, + }, + || {}, + ) + .await + .unwrap(); + let service = TurnDeliveryService::start( + f.engine.clone(), + supervisor.clone(), + f._root.path().to_path_buf(), + ); + let state = timeout(Duration::from_secs(10), async { + loop { + let row = f + .engine + .repositories() + .get_provider_turn_delivery("next".into()) + .await + .unwrap() + .unwrap(); + if matches!( + row.state, + TurnDeliveryState::Delivered | TurnDeliveryState::Failed + ) { + return row.state; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the message settles"); + assert_eq!(state, TurnDeliveryState::Delivered); + assert_eq!( + f.driver.launches.load(Ordering::SeqCst), + 2, + "launched again" + ); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 1); + service.shutdown().await; + supervisor.shutdown().await.unwrap(); + f.shutdown().await; + } + + #[tokio::test] + async fn retrying_an_oversized_stdout_failure_delivers_on_a_healthy_relaunch() { + assert_oversized_head_recovers("retry").await; + } + + #[tokio::test] + async fn dismissing_an_oversized_stdout_failure_releases_later_queued_messages() { + assert_oversized_head_recovers("dismiss").await; + } + + /// A manual compaction of the fixture's live Codex conversation. + async fn request_compaction(f: &Fixture) -> String { + f.project("ready").await; + f.engine + .dispatch( + serde_json::from_value(json!({ + "type":"thread.compact", "commandId":"compact", "threadId":"t1", + "createdAt":BEFORE_LOSS, + })) + .unwrap(), + ) + .await + .unwrap(); + f.engine + .unsettled_thread_compaction("t1") + .await + .unwrap() + .expect("a requested compaction") + .compaction_id + } + + fn script(f: &Fixture, start: ProviderCompactionStart, events: Vec) { + *f.driver.compact_script.lock().unwrap() = Some((start, events)); + } + + async fn drive(f: &Fixture, compaction_id: &str) -> ThreadCompactionRow { + timeout( + Duration::from_secs(10), + drive_thread_compaction( + &f.supervisor, + &f.engine, + &f._root.path().to_path_buf(), + compaction_id, + &CancellationToken::new(), + ), + ) + .await + .expect("a compaction settles within its bounds") + .unwrap(); + f.engine + .thread_compaction(compaction_id) + .await + .unwrap() + .unwrap() + } + + fn started_compaction() -> ProviderCompactionStart { + ProviderCompactionStart::Started { + turn_id: Some("compaction-turn".to_owned()), + } + } + + fn compaction_events(item: bool, state: &str) -> Vec { + let mut events = vec![core_event( + "turn.started", + "compaction-turn", + json!({"compactionId":"$id"}), + )]; + if item { + events.push(core_event( + "item.completed", + "compaction-turn", + json!({"itemType":"context_compaction","status":"completed","title":"Conversation compaction"}), + )); + } + events.push(core_event( + "turn.completed", + "compaction-turn", + json!({"state":state, "compactionId":"$id"}), + )); + events + } + + fn with_bounds(run: Duration, grace: Duration, turn_start: Duration) { + COMPACTION_TEST_BOUNDS.with(|bounds| bounds.set(Some((run, grace, turn_start)))); + } + + #[tokio::test] + async fn a_compaction_settles_completed_from_its_tagged_turn_and_item() { + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + script( + &f, + started_compaction(), + compaction_events(true, "completed"), + ); + let row = drive(&f, &id).await; + assert_eq!(row.state, "completed"); + assert_eq!(row.turn_id.as_deref(), Some("compaction-turn")); + assert_eq!(*f.driver.compact_calls.lock().unwrap(), vec![id.clone()]); + assert_eq!(f.session().await.status, "ready"); + f.shutdown().await; + } + + #[tokio::test] + async fn a_compaction_turn_without_a_completed_compaction_item_fails() { + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + script( + &f, + started_compaction(), + compaction_events(false, "completed"), + ); + let row = drive(&f, &id).await; + assert_eq!(row.state, "failed"); + let session = f.session().await; + assert_eq!(session.status, "error"); + assert!( + session + .last_error + .as_deref() + .is_some_and(|error| error.ends_with("couldn't compact the conversation.")), + "{:?}", + session.last_error + ); + f.shutdown().await; + } + + #[tokio::test] + async fn a_compaction_of_another_conversation_fails_without_asking_the_provider() { + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + f.engine + .repositories() + .database() + .call(|connection| { + connection.execute( + "UPDATE thread_compactions SET conversation_id = 'another-thread'", + [], + )?; + Ok(()) + }) + .await + .unwrap(); + script( + &f, + started_compaction(), + compaction_events(true, "completed"), + ); + let row = drive(&f, &id).await; + assert_eq!(row.state, "failed"); + assert_eq!( + row.detail.as_deref(), + Some("The thread's provider or conversation changed, so it wasn't compacted.") + ); + assert!(f.driver.compact_calls.lock().unwrap().is_empty()); + f.shutdown().await; + } + + #[tokio::test] + async fn an_unknown_request_that_starts_no_turn_ends_its_session() { + with_bounds( + Duration::from_secs(5), + Duration::from_millis(100), + Duration::from_millis(100), + ); + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + script( + &f, + ProviderCompactionStart::Unknown { + detail: "the answer was lost".to_owned(), + }, + Vec::new(), + ); + let row = drive(&f, &id).await; + assert_eq!(row.state, "failed"); + assert_eq!( + row.detail.as_deref(), + Some("BiBCode couldn't confirm whether the conversation was compacted.") + ); + assert!( + f.supervisor + .capture_session_identity("t1") + .await + .unwrap() + .is_none(), + "the session that may hold the compaction ended" + ); + // Its saved conversation stays, so the next message resumes it. + assert!(f.runtime().await["resume_cursor"].is_object()); + f.shutdown().await; + } + + #[tokio::test] + async fn a_compaction_at_its_bound_is_interrupted_then_its_session_ended() { + with_bounds( + Duration::from_millis(200), + Duration::from_millis(100), + Duration::from_secs(5), + ); + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + script( + &f, + started_compaction(), + vec![core_event( + "turn.started", + "compaction-turn", + json!({"compactionId":"$id"}), + )], + ); + let row = drive(&f, &id).await; + assert_eq!(row.state, "failed"); + assert!( + f.supervisor + .capture_session_identity("t1") + .await + .unwrap() + .is_none() + ); + let session = f.session().await; + assert_eq!(session.status, "error"); + assert_eq!( + session.last_error.as_deref(), + Some("BiBCode couldn't confirm whether the conversation was compacted.") + ); + assert_eq!(session.active_turn_id, None); + f.shutdown().await; + } + + #[tokio::test] + async fn the_completion_of_an_earlier_compaction_settles_nothing() { + with_bounds( + Duration::from_millis(300), + Duration::from_millis(100), + Duration::from_secs(5), + ); + let f = Fixture::new(true).await; + let id = request_compaction(&f).await; + script( + &f, + started_compaction(), + vec![ + core_event( + "turn.started", + "compaction-turn", + json!({"compactionId":"$id"}), + ), + core_event( + "turn.completed", + "compaction-turn", + json!({"state":"completed", "compactionId":"compaction:earlier"}), + ), + ], + ); + let row = drive(&f, &id).await; + assert_ne!(row.state, "completed"); f.shutdown().await; } @@ -4702,8 +5906,130 @@ mod workspace_loss_tests { f.shutdown().await; } - /// The delivery path asks the driver for agent treatment only for a turn whose agent message - /// row the server stored, never for a person's turn that pastes the same envelope. + /// A turn delivered to a live Antigravity session confirms the turn's own runtime mode + /// before the prompt; when the confirmation fails nothing is sent. Other providers' live + /// deliveries write no mode, as before. + #[tokio::test] + async fn a_live_antigravity_turn_confirms_its_mode_before_the_prompt() { + let turn_in = |id: &str, mode: &str| { + let mut command = serde_json::to_value(turn(id, false)).unwrap(); + command["runtimeMode"] = json!(mode); + serde_json::from_value::(command).unwrap() + }; + let codex = Fixture::new(true).await; + let delivery = codex + .supervisor + .deliver_turn( + turn_in("codex-turn", "approval-required"), + "codex-key".into(), + ) + .await + .unwrap(); + let _ = timeout(Duration::from_secs(5), delivery.completion()) + .await + .unwrap(); + assert!(codex.driver.mode_calls.lock().unwrap().is_empty()); + codex.shutdown().await; + + let f = Fixture::new(false).await; + let mut launch = f.launch.clone(); + launch.provider = "antigravity".to_owned(); + f.supervisor.launch(launch).await.unwrap(); + let delivery = f + .supervisor + .deliver_turn(turn_in("strict", "approval-required"), "strict-key".into()) + .await + .unwrap(); + let outcome = timeout(Duration::from_secs(5), delivery.completion()) + .await + .unwrap(); + assert!( + matches!(outcome, ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + assert_eq!(*f.driver.mode_calls.lock().unwrap(), ["approval-required"]); + let sent = f.driver.sends.load(Ordering::SeqCst); + + f.driver.mode_fails.store(true, Ordering::SeqCst); + let refused = f + .supervisor + .deliver_turn( + turn_in("permissive", "full-access"), + "permissive-key".into(), + ) + .await; + if let Ok(delivery) = refused { + let outcome = timeout(Duration::from_secs(5), delivery.completion()) + .await + .unwrap(); + assert!( + !matches!(outcome, ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + } + assert_eq!( + f.driver.sends.load(Ordering::SeqCst), + sent, + "no prompt was sent" + ); + f.shutdown().await; + } + + /// An Antigravity CLI that withholds its mode answer holds only its own thread's delivery: + /// the shared supervisor keeps handling other commands, and the prompt still waits for the + /// mode. + #[tokio::test] + async fn a_withheld_antigravity_mode_answer_holds_no_other_thread() { + let f = Fixture::new(false).await; + let mut launch = f.launch.clone(); + launch.provider = "antigravity".to_owned(); + f.supervisor.launch(launch).await.unwrap(); + f.driver.mode_held.store(true, Ordering::SeqCst); + let mut command = serde_json::to_value(turn("held", false)).unwrap(); + command["runtimeMode"] = json!("approval-required"); + let command = serde_json::from_value::(command).unwrap(); + let delivery = tokio::spawn({ + let supervisor = f.supervisor.clone(); + async move { supervisor.deliver_turn(command, "held-key".into()).await } + }); + timeout(Duration::from_secs(5), async { + while f.driver.mode_calls.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the mode write started"); + let other = timeout( + Duration::from_secs(1), + f.supervisor.capture_session_identity("another-thread"), + ) + .await + .expect("another thread's command waited for the withheld mode answer"); + assert!(other.unwrap().is_none()); + assert_eq!( + f.driver.sends.load(Ordering::SeqCst), + 0, + "prompt before mode" + ); + f.driver.mode_release.notify_one(); + let delivery = timeout(Duration::from_secs(5), delivery) + .await + .unwrap() + .unwrap() + .unwrap(); + let outcome = timeout(Duration::from_secs(5), delivery.completion()) + .await + .unwrap(); + assert!( + matches!(outcome, ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + assert_eq!(f.driver.sends.load(Ordering::SeqCst), 1); + f.shutdown().await; + } + + /// The delivery path asks the driver for agent treatment only for a turn whose agent message + /// row the server stored, never for a person's turn that pastes the same envelope. #[tokio::test] async fn only_a_stored_agent_message_is_delivered_as_one() { use crate::agent_messaging::{envelope, store}; @@ -5751,6 +7077,7 @@ mod workspace_loss_tests { f.launch.clone(), false, None, + None, false, None, None, @@ -5966,6 +7293,7 @@ mod workspace_loss_tests { "t1", launch, None, + None, ) .await .unwrap(); @@ -6021,6 +7349,7 @@ mod workspace_loss_tests { "t1", f.launch.clone(), None, + None, ) .await; let same = Arc::ptr_eq(&old_driver, &sessions["t1"].driver) @@ -6810,7 +8139,7 @@ fn validate_frozen_session_identity( }; let cursor_field = match row.provider_kind.as_str() { "codex" => "threadId", - "claudeAgent" | "cursor" | "opencode" => "sessionId", + "claudeAgent" | "cursor" | "antigravity" | "opencode" => "sessionId", _ => { return Err(ProviderRuntimeError::Provider { provider: row.provider_kind.clone(), @@ -6978,6 +8307,7 @@ pub(crate) fn canonical_provider_kind(driver: &str) -> Result<&'static str, Prov "codex" => Ok("codex"), "cursor" => Ok("cursor"), "grok" => Ok("grok"), + "antigravity" => Ok("antigravity"), "opencode" => Ok("opencode"), other => Err(ProviderRuntimeError::UnsupportedProvider { provider: other.to_owned(), @@ -6994,6 +8324,7 @@ fn provider_binary_settings( "claudeAgent" => providers.claude_agent.clone(), "cursor" => providers.cursor.clone(), "grok" => providers.grok.clone(), + "antigravity" => providers.antigravity.clone(), "opencode" => providers.opencode.clone(), _ => providers.codex.clone(), }; @@ -7089,6 +8420,7 @@ async fn run_supervisor( request, context_handoff, frozen_delivery, + message_id, abort_on_lost_resume, response, } => { @@ -7100,6 +8432,7 @@ async fn run_supervisor( *request, context_handoff, frozen_delivery.as_deref(), + message_id.as_deref(), abort_on_lost_resume, operational_log.as_ref(), None, @@ -7115,10 +8448,16 @@ async fn run_supervisor( let _ = response.send(result); } SupervisorMessage::Handle { command, response } => { + // A command waits behind a running delivery, and also behind older commands that + // the finished delivery has not drained yet, so a newer setting is never applied + // before an older one. if let Some(thread_id) = delivery_ordered_command_thread(command.as_ref()) - && let Some(generation) = delivery_sequences - .get(thread_id) - .and_then(|sequence| sequence.active_generation) + && let Some(generation) = deferral_generation( + delivery_sequences.get(thread_id), + deferred_configuration + .get(thread_id) + .is_some_and(|queued| !queued.is_empty()), + ) { let queued = deferred_configuration .entry(thread_id.to_owned()) @@ -7445,7 +8784,9 @@ async fn run_supervisor( entry.event_cancellation.cancel(); } if sessions.get(&thread_id).is_some_and(|entry| { - entry.event_task.is_finished() || entry.event_cancellation.is_cancelled() + entry.event_task.is_finished() + || entry.event_cancellation.is_cancelled() + || entry.driver.retired() }) { let entry = detach_session(&activity, &mut sessions, &thread_id).await?; if let Err(error) = entry.driver.shutdown().await { @@ -7476,9 +8817,40 @@ async fn run_supervisor( selection, operational_log.as_ref(), true, + frozen_delivery.as_ref().map(|row| row.message_id.as_str()), ) .await?; } + // A live Antigravity session runs the prompt in the mode it last confirmed, so + // the turn's own modes are confirmed first, in the thread's delivery task so a + // silent CLI holds no other thread; a failed confirmation refuses the delivery + // before any prompt is written. + let mut mode_changes = ModeChanges::default(); + if let OrchestrationCommand::ThreadTurnStart { + thread_id, + runtime_mode, + interaction_mode, + .. + } = command.as_ref() + && !frozen_delivery.as_ref().is_some_and(|row| row.mode == TurnDeliveryMode::Steer) + && let Some(entry) = sessions.get_mut(thread_id) + && entry.launch.provider == "antigravity" + { + // The saved launch takes the request at once; each mode not yet + // acknowledged for it is written (again) before the prompt, and stays + // unconfirmed until its own acknowledgement. + entry.launch.runtime_mode = runtime_mode.clone(); + entry.launch.interaction_mode = interaction_mode.clone(); + let mut confirmed = confirmed_modes(entry); + if confirmed.runtime.as_ref() != Some(runtime_mode) { + confirmed.runtime = None; + mode_changes.runtime = Some(runtime_mode.clone()); + } + if confirmed.interaction.as_ref() != Some(interaction_mode) { + confirmed.interaction = None; + mode_changes.interaction = Some(interaction_mode.clone()); + } + } next_delivery_generation = next_delivery_generation.checked_add(1).ok_or_else( || ProviderRuntimeError::Provider { provider: "orchestration".to_owned(), @@ -7498,6 +8870,7 @@ async fn run_supervisor( frozen_delivery.as_deref(), terminal_sender.clone(), generation, + mode_changes, ) .await; if result.is_ok() { @@ -7968,6 +9341,15 @@ fn delivery_ordered_command_thread(command: &OrchestrationCommand) -> Option<&st } } +/// The delivery generation a configuration command must queue behind, if any: the running +/// delivery's, or, while older commands still wait for their drain, the finished one's. +fn deferral_generation(sequence: Option<&ThreadDeliverySequence>, has_queued: bool) -> Option { + let sequence = sequence?; + sequence + .active_generation + .or_else(|| has_queued.then_some(sequence.completed_generation)) +} + fn schedule_deferred_drain( sender: mpsc::Sender, thread_id: String, @@ -8151,6 +9533,72 @@ async fn delivery_text( .map(DeliveryText::Turn) } +/// The last await before a frozen delivery's prompt is sent: the freeze's own guarded UPDATE +/// again, so it and the engine's Dismiss of a `sending` row exclude each other in the database. +/// A row that left `sending` was dismissed by the user's Stop and settles unsent. +async fn send_fence( + repositories: &Repositories, + row: &ProviderTurnDelivery, + provider_session_id: &str, +) -> Option { + let not_sent = + |error: crate::persistence::PersistenceError| ProviderDeliveryOutcome::DefinitelyNotSent { + detail: delivery_detail(&ProviderRuntimeError::Persistence(error.to_string()), None), + }; + match repositories + .freeze_provider_turn_session( + row.command_id.clone(), + row.attempts, + row.provider_instance_id.clone(), + row.provider_kind.clone(), + provider_session_id.to_owned(), + now(), + ) + .await + { + Ok(Some(_)) => None, + Ok(None) => Some( + match repositories + .get_provider_turn_delivery(row.command_id.clone()) + .await + { + Ok(Some(current)) if current.state == TurnDeliveryState::Dismissed => { + ProviderDeliveryOutcome::StoppedUnsent + } + Ok(_) => ProviderDeliveryOutcome::DefinitelyNotSent { + detail: format!( + "durable provider delivery {} changed before its send", + row.command_id + ), + }, + Err(error) => not_sent(error), + }, + ), + Err(error) => Some(not_sent(error)), + } +} + +/// Modes a live Antigravity session must confirm before a turn's prompt. +#[derive(Default)] +struct ModeChanges { + runtime: Option, + interaction: Option, +} + +/// The modes a live driver acknowledged; `None` while a write is unconfirmed. +struct ConfirmedModes { + runtime: Option, + interaction: Option, +} + +fn confirmed_modes(entry: &SessionEntry) -> std::sync::MutexGuard<'_, ConfirmedModes> { + entry + .confirmed_modes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +#[allow(clippy::too_many_arguments)] async fn spawn_delivery( engine: &OrchestrationEngine, sessions: &mut HashMap, @@ -8159,6 +9607,7 @@ async fn spawn_delivery( frozen_delivery: Option<&ProviderTurnDelivery>, terminal_sender: mpsc::UnboundedSender, generation: u64, + mode_changes: ModeChanges, ) -> Result { let OrchestrationCommand::ThreadTurnStart { command_id, @@ -8199,6 +9648,7 @@ async fn spawn_delivery( #[cfg(test)] let idle_deadline_test_observer = entry.idle_deadline_test_observer.clone(); let driver = entry.driver.clone(); + let confirmed = entry.confirmed_modes.clone(); let pending_context_handoff = entry.pending_context_handoff.clone(); let side_chat = side_chat_seed_state(entry); let seed_engine = engine.clone(); @@ -8220,14 +9670,35 @@ async fn spawn_delivery( completed: false, }; tokio::spawn(async move { - let freeze_failure = if let Some((row, provider_session_id)) = frozen_session { + let mode_failure = async { + let confirmed = || { + confirmed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + }; + if let Some(mode) = mode_changes.runtime { + driver.set_mode(mode.clone()).await?; + confirmed().runtime = Some(mode); + } + if let Some(mode) = mode_changes.interaction { + driver.set_interaction_mode(mode.clone()).await?; + confirmed().interaction = Some(mode); + } + Ok::<(), ProviderRuntimeError>(()) + } + .await + .err(); + // A refused mode is final; an unanswered write may be transient and is retried. + let freeze_failure = if let Some(error) = mode_failure { + Some(unsent_outcome(error)) + } else if let Some((row, provider_session_id)) = frozen_session.as_ref() { match repositories .freeze_provider_turn_session( row.command_id.clone(), row.attempts, row.provider_instance_id.clone(), row.provider_kind.clone(), - provider_session_id, + provider_session_id.clone(), now(), ) .await @@ -8272,7 +9743,14 @@ async fn spawn_delivery( }, } } else { - match delivery_text( + #[cfg(test)] + if let Some(gate) = accepted_publication_test_hook + .as_ref() + .and_then(|hook| hook.before_send.as_ref()) + { + gate.pause().await; + } + let text = delivery_text( &repositories, &pending_context_handoff, side_chat_seed_ref(&side_chat), @@ -8280,12 +9758,17 @@ async fn spawn_delivery( &command_id, &message, ) - .await - { + .await; + let stopped = match (&text, frozen_session.as_ref()) { + (Ok(_), Some((row, session))) => send_fence(&repositories, row, session).await, + _ => None, + }; + match (stopped, text) { + (Some(stopped), _) => stopped, // A side chat that owes its seed sends nothing without it, and an unreadable // provenance sends nothing either; the delivery fails and its retry reads again. - Err(detail) => ProviderDeliveryOutcome::DefinitelyNotSent { detail }, - Ok(DeliveryText::AgentMessage) => { + (None, Err(detail)) => ProviderDeliveryOutcome::DefinitelyNotSent { detail }, + (None, Ok(DeliveryText::AgentMessage)) => { driver .deliver_agent_message( message.text, @@ -8295,7 +9778,7 @@ async fn spawn_delivery( ) .await } - Ok(DeliveryText::Turn(handoff)) => { + (None, Ok(DeliveryText::Turn(handoff))) => { let (text, carried) = match handoff { Some(handoff) => (handoff.text, Some(handoff.side_chat_seed)), None => (message.text, None), @@ -9360,10 +10843,18 @@ async fn publish_running_session( return Ok(()); } if publication.terminal_revision != terminal_revision { - tracing::info!( - thread_id = %entry.launch.thread_id, - "a turn ended before this delivery was accepted; the session is not marked running" - ); + // A provider whose own `turn.started` marked the turn running lost nothing here. + if provider_reports_its_turns(&entry.launch.provider) { + tracing::debug!( + thread_id = %entry.launch.thread_id, + "the provider's turn ended before its delivery was accepted" + ); + } else { + tracing::info!( + thread_id = %entry.launch.thread_id, + "a turn ended before this delivery was accepted; the session is not marked running" + ); + } return Ok(()); } // An acceptance that names no turn (a Codex compaction, whose turn Codex reports after it @@ -9686,6 +11177,7 @@ fn normalize_agent_activity_transition_error(error: ProviderRuntimeError) -> Pro ProviderRuntimeError::SessionNotFound { .. } => "session missing", ProviderRuntimeError::StaleSession { .. } => "session stale", ProviderRuntimeError::SessionAlreadyExists { .. } => "session conflict", + ProviderRuntimeError::LaunchStopped { .. } => "session start stopped", ProviderRuntimeError::FrozenConversationLost { .. } => "provider conversation lost", ProviderRuntimeError::UnsupportedProvider { .. } => "unsupported provider", ProviderRuntimeError::UnsupportedCapability { .. } => "unsupported capability", @@ -9708,6 +11200,194 @@ fn normalize_agent_activity_transition_error(error: ProviderRuntimeError) -> Pro } } +/// The session state a start notice replaced: status, active turn, error and its class. +type SessionBeforeNotice = (String, Option, Option, Option); + +/// What a stopped launch answers: the server's shutdown, or the user's stop of the thread. +fn launch_stop_error( + request: &ProviderLaunchRequest, + stop: &crate::orchestration::engine::LaunchStop, +) -> ProviderRuntimeError { + if stop.by_shutdown() { + ProviderRuntimeError::Shutdown + } else { + ProviderRuntimeError::LaunchStopped { + thread_id: request.thread_id.clone(), + } + } +} + +/// Awaits `work` unless the launch is stopped first; a launch already stopped never polls it. +async fn unless_launch_stopped( + request: &ProviderLaunchRequest, + stop: &crate::orchestration::engine::LaunchStop, + work: impl Future, +) -> Result { + tokio::select! { + biased; + () = stop.stopped() => Err(launch_stop_error(request, stop)), + value = work => Ok(value), + } +} + +/// Ends a launch stopped after its start returned, as a stopped start ends: the started session +/// is shut down and never kept, and the runtime records the stop. Answers the stop's error. +async fn end_stopped_launch( + engine: &OrchestrationEngine, + request: &ProviderLaunchRequest, + driver: &dyn ProviderDriver, + resume_cursor: Option, + context_handoff: bool, + error: ProviderRuntimeError, +) -> ProviderRuntimeError { + tracing::info!( + thread_id = %request.thread_id, + provider = %request.provider, + shutdown = matches!(error, ProviderRuntimeError::Shutdown), + "a provider launch was stopped after its start returned" + ); + let _ = driver.shutdown().await; + if let Err(persist_error) = persist_runtime( + &engine.repositories(), + request, + "error", + resume_cursor, + runtime_payload_with_context_handoff( + Some(json!({ "error": error.to_string() })), + context_handoff, + ), + ) + .await + { + tracing::warn!(%persist_error, thread_id = %request.thread_id, "could not record a stopped launch"); + } + error +} + +/// Awaits the driver's start. Past the driver's notice delay the thread shows that the provider +/// is slow to start, and the start keeps waiting: a slow start may still finish. Only a stop of +/// the thread, or the server's shutdown, ends a start that does not return. The notice clears +/// once the start ends. +async fn start_with_notice( + engine: &OrchestrationEngine, + request: &ProviderLaunchRequest, + driver: &dyn ProviderDriver, + stop: &crate::orchestration::engine::LaunchStop, +) -> Result { + let start = driver.start(); + tokio::pin!(start); + let notice_delay = tokio::time::sleep(driver.start_notice_delay()); + tokio::pin!(notice_delay); + let mut notice_due = true; + let mut replaced = None; + let result = loop { + tokio::select! { + result = &mut start => break result, + () = stop.stopped() => { + tracing::info!( + thread_id = %request.thread_id, + provider = %request.provider, + shutdown = stop.by_shutdown(), + "a provider start was stopped before it finished" + ); + break Err(launch_stop_error(request, stop)); + } + () = &mut notice_delay, if notice_due => { + notice_due = false; + tracing::warn!( + thread_id = %request.thread_id, + provider = %request.provider, + "a provider is taking long to start; showing a notice and waiting" + ); + replaced = show_session_notice(engine, request, start_notice(&request.provider)).await; + } + } + }; + if let Some(previous) = replaced { + clear_start_notice(engine, request, previous).await; + } + result +} + +/// Shows `message` on the thread's session, keeping its status and turn. The state it replaced, +/// or `None` when it could not be shown. +async fn show_session_notice( + engine: &OrchestrationEngine, + request: &ProviderLaunchRequest, + message: String, +) -> Option { + let session = match engine + .repositories() + .get_thread_session(request.thread_id.clone()) + .await + { + Ok(session) => session, + Err(error) => { + tracing::warn!(%error, thread_id = %request.thread_id, "could not read the session for a notice"); + return None; + } + }; + let previous = session.map_or_else( + || ("idle".to_owned(), None, None, None), + |session| { + ( + session.status, + session.active_turn_id, + session.last_error, + session.last_error_class, + ) + }, + ); + let shown = dispatch_session_state( + engine, + request, + &previous.0, + previous.1.clone(), + Some(message), + None, + ) + .await; + match shown { + Ok(()) => Some(previous), + Err(error) => { + tracing::warn!(%error, thread_id = %request.thread_id, "could not show a notice"); + None + } + } +} + +/// Puts back the session state the start notice replaced, unless something newer replaced the +/// notice meanwhile. +async fn clear_start_notice( + engine: &OrchestrationEngine, + request: &ProviderLaunchRequest, + (status, active_turn_id, last_error, last_error_class): SessionBeforeNotice, +) { + let notice = start_notice(&request.provider); + let showing = engine + .repositories() + .get_thread_session(request.thread_id.clone()) + .await + .is_ok_and(|session| { + session.is_some_and(|session| session.last_error.as_deref() == Some(notice.as_str())) + }); + if !showing { + return; + } + if let Err(error) = dispatch_session_state( + engine, + request, + &status, + active_turn_id, + last_error, + last_error_class, + ) + .await + { + tracing::warn!(%error, thread_id = %request.thread_id, "could not clear a start notice"); + } +} + #[allow(clippy::too_many_arguments)] async fn launch_session( engine: &OrchestrationEngine, @@ -9717,6 +11397,7 @@ async fn launch_session( mut request: ProviderLaunchRequest, context_handoff: bool, frozen_delivery: Option<&ProviderTurnDelivery>, + message_id: Option<&str>, abort_on_lost_resume: bool, operational_log: Option<&ProviderOperationalLog>, inherited_activity_lifecycle: Option, @@ -9745,8 +11426,8 @@ async fn launch_session( // Every provider driver is created below, so this is the one place a session of a thread // held by another chat's file restore could start again (#279). Registered until the launch // ends, so a restore that marks the thread meanwhile refuses instead. - let _launch = engine - .begin_session_launch(&request.thread_id) + let launch_registration = engine + .begin_session_launch(&request.thread_id, message_id) .map_err(|detail| { tracing::warn!(thread_id = %request.thread_id, "a provider session launch was refused: another chat restores files in its checkout"); ProviderRuntimeError::Provider { @@ -9809,7 +11490,14 @@ async fn launch_session( driver .set_agent_activity_enabled(activity_enabled_at_launch) .await?; - let started = match driver.start().await { + let started = start_with_notice( + engine, + &request, + driver.as_ref(), + launch_registration.stop(), + ) + .await; + let started = match started { Ok(started) => started, Err(error) => { let _ = driver.shutdown().await; @@ -9853,20 +11541,56 @@ async fn launch_session( thread_id: request.thread_id, }); } + // Until the session is kept, a stop of the thread or the server's shutdown still ends the + // launch: every await below races it, and the started session is shut down, never kept. + let stop = launch_registration.stop(); let released = match frozen_delivery { Some(row) if resume_lost && row.provider_session_id.is_some() => { - match release_frozen_delivery(&engine.repositories(), &request, row).await { - Ok(released) => released, - Err(error) => { + match unless_launch_stopped( + &request, + stop, + release_frozen_delivery(&engine.repositories(), &request, row), + ) + .await + { + Ok(Ok(released)) => released, + Ok(Err(error)) => { let _ = driver.shutdown().await; return Err(error); } + Err(stopped) => { + return Err(end_stopped_launch( + engine, + &request, + driver.as_ref(), + started.resume_cursor.clone(), + context_handoff, + stopped, + ) + .await); + } } } _ => None, }; let context_handoff = context_handoff || resume_lost; - let options_result = driver.set_options(request.options.clone()).await; + let stopped_launch = |stopped| { + end_stopped_launch( + engine, + &request, + driver.as_ref(), + started.resume_cursor.clone(), + context_handoff, + stopped, + ) + }; + let options_result = + match unless_launch_stopped(&request, stop, driver.set_options(request.options.clone())) + .await + { + Ok(result) => result, + Err(stopped) => return Err(stopped_launch(stopped).await), + }; record_option_reconciliation( operational_log, &request, @@ -9920,27 +11644,45 @@ async fn launch_session( }); if let Some(effective_activity_capabilities) = effective_activity_capabilities && activity_controller.snapshot().enabled - && let Err(error) = ensure_live_activity_scope( - activity, + { + match unless_launch_stopped( &request, - &activity_lifecycle, - &effective_activity_capabilities, - format!("supervisor:launch-live:{activity_lifecycle_id}"), + stop, + ensure_live_activity_scope( + activity, + &request, + &activity_lifecycle, + &effective_activity_capabilities, + format!("supervisor:launch-live:{activity_lifecycle_id}"), + ), ) .await - { - tracing::warn!(%error, "activity scope unavailable; continuing provider session"); + { + Ok(Ok(())) => {} + Ok(Err(error)) => { + tracing::warn!(%error, "activity scope unavailable; continuing provider session"); + } + Err(stopped) => return Err(stopped_launch(stopped).await), + } } let pending_context_handoff = Arc::new(AtomicBool::new(context_handoff)); let resume_refusal_recorded = Arc::new(AtomicBool::new(false)); - persist_runtime( - &engine.repositories(), + match unless_launch_stopped( &request, - "ready", - started.resume_cursor.clone(), - runtime_payload_with_context_handoff(started.runtime_payload.clone(), context_handoff), + stop, + persist_runtime( + &engine.repositories(), + &request, + "ready", + started.resume_cursor.clone(), + runtime_payload_with_context_handoff(started.runtime_payload.clone(), context_handoff), + ), ) - .await?; + .await + { + Ok(result) => result?, + Err(stopped) => return Err(stopped_launch(stopped).await), + } // A resumed OpenCode session may hold asks BiBCode never recorded, shown only once its // event stream has read them: queued messages wait for that read to finish (#187). let ask_recovery = (crate::orchestration::EXTERNALLY_RESUMABLE_PROVIDERS @@ -9948,13 +11690,38 @@ async fn launch_session( && request.resume_cursor.is_some() && !resume_lost) .then(|| engine.hold_promotion_for_ask_recovery(&request.thread_id)); - dispatch_session_state(engine, &request, "ready", None, None, None).await?; - if resume_lost { - append_context_handoff_activity(engine, &request).await; + match unless_launch_stopped( + &request, + stop, + dispatch_session_state(engine, &request, "ready", None, None, None), + ) + .await + { + Ok(result) => result?, + Err(stopped) => return Err(stopped_launch(stopped).await), + } + if resume_lost + && let Err(stopped) = unless_launch_stopped( + &request, + stop, + append_context_handoff_activity(engine, &request), + ) + .await + { + return Err(stopped_launch(stopped).await); } if !activity_controller.snapshot().enabled { - activity_control.write().await.take(); + match unless_launch_stopped(&request, stop, activity_control.write()).await { + Ok(mut control) => { + control.take(); + } + Err(stopped) => return Err(stopped_launch(stopped).await), + } + } + // The last chance to stop: past it the session is kept and its event pump runs. + if let Err(stopped) = unless_launch_stopped(&request, stop, std::future::ready(())).await { + return Err(stopped_launch(stopped).await); } let cancellation = CancellationToken::new(); @@ -10001,6 +11768,11 @@ async fn launch_session( sessions.insert( request.thread_id.clone(), SessionEntry { + // A started driver acknowledged its launch modes (Antigravity's start confirms them). + confirmed_modes: Arc::new(StdMutex::new(ConfirmedModes { + runtime: Some(request.runtime_mode.clone()), + interaction: Some(request.interaction_mode.clone()), + })), launch: request, dropped_model, driver, @@ -10182,6 +11954,7 @@ async fn handle_command( // A settings change saved for a queued message must not restart the session // under the turn that is still running. The message's own start applies it. matches!(command, OrchestrationCommand::ThreadTurnStart { .. }), + None, ) .await?; } @@ -10298,6 +12071,7 @@ async fn handle_command( OrchestrationCommand::ThreadRuntimeModeSet { runtime_mode, .. } => { match entry.driver.set_mode(runtime_mode.clone()).await { Ok(()) => { + confirmed_modes(entry).runtime = Some(runtime_mode.clone()); entry.launch.runtime_mode = runtime_mode; persist_entry(&engine.repositories(), entry, "ready").await } @@ -10312,10 +12086,18 @@ async fn handle_command( &thread_id, launch, operational_log, + None, ) .await } - Err(error) => Err(error), + // The thread already asks for this mode: a restart must never start the + // session in the earlier, possibly more permissive one. + // The driver may hold the new mode unconfirmed: the next turn writes its own. + Err(error) => { + confirmed_modes(entry).runtime = None; + entry.launch.runtime_mode = runtime_mode; + Err(error) + } } } OrchestrationCommand::ThreadInteractionModeSet { @@ -10327,6 +12109,7 @@ async fn handle_command( .await { Ok(()) => { + confirmed_modes(entry).interaction = Some(interaction_mode.clone()); entry.launch.interaction_mode = interaction_mode; persist_entry(&engine.repositories(), entry, "ready").await } @@ -10341,10 +12124,16 @@ async fn handle_command( &thread_id, launch, operational_log, + None, ) .await } - Err(error) => Err(error), + // As for the runtime mode: a restart starts in the mode the thread asks for. + Err(error) => { + confirmed_modes(entry).interaction = None; + entry.launch.interaction_mode = interaction_mode; + Err(error) + } } } OrchestrationCommand::ThreadMetaUpdate { @@ -10482,7 +12271,7 @@ async fn reopen_for_rewind( )); } if let Err(error) = supervisor - .launch_with_context_handoff(request, false, None, true) + .launch_with_context_handoff(request, false, None, None, true) .await { let reason = match error { @@ -10747,7 +12536,7 @@ async fn reopen_for_compaction( ))); } if let Err(error) = supervisor - .launch_with_context_handoff(request, false, None, true) + .launch_with_context_handoff(request, false, None, None, true) .await { let reason = match error { @@ -11142,6 +12931,7 @@ async fn reconcile_model_selection( selection: &Value, operational_log: Option<&ProviderOperationalLog>, starting_turn: bool, + message_id: Option<&str>, ) -> Result<(), ProviderRuntimeError> { let target_model = model_from_selection(selection); let selection_options = selection_options(selection); @@ -11327,6 +13117,7 @@ async fn reconcile_model_selection( thread_id, launch, operational_log, + message_id, ) .await?; } @@ -11339,6 +13130,7 @@ async fn reconcile_model_selection( thread_id, launch, operational_log, + message_id, ) .await?; } @@ -11380,6 +13172,8 @@ fn record_option_reconciliation( return; }; let accepted = matches!(result, "applied" | "restart-required"); + // Antigravity's models and levels come from the user's account: no value is recorded (D-A11). + let records_values = launch.provider != "antigravity"; let provider_instance_id = launch .provider_instance_id .as_deref() @@ -11388,15 +13182,18 @@ fn record_option_reconciliation( let Some(option_id) = option.get("id").and_then(Value::as_str) else { continue; }; - let requested_value = option.get("value").and_then(|value| match value { - Value::Bool(_) => Some(value), - Value::String(_) if accepted => Some(value), - _ => None, - }); + let requested_value = option + .get("value") + .filter(|_| records_values) + .and_then(|value| match value { + Value::Bool(_) => Some(value), + Value::String(_) if accepted => Some(value), + _ => None, + }); let _ = log.record_option_reconciliation( &launch.thread_id, provider_instance_id, - launch.model.as_deref(), + launch.model.as_deref().filter(|_| records_values), if accepted { option_id } else { "unknown" }, requested_value, application_method, @@ -11405,6 +13202,7 @@ fn record_option_reconciliation( } } +#[allow(clippy::too_many_arguments)] async fn restart_session( engine: &OrchestrationEngine, factory: &Arc, @@ -11413,6 +13211,7 @@ async fn restart_session( thread_id: &str, mut launch: ProviderLaunchRequest, operational_log: Option<&ProviderOperationalLog>, + message_id: Option<&str>, ) -> Result<(), ProviderRuntimeError> { #[cfg(test)] let idle_deadline_test_observer = sessions @@ -11485,6 +13284,7 @@ async fn restart_session( launch, context_handoff, None, + message_id, false, operational_log, inherited_activity_lifecycle, @@ -12779,6 +14579,44 @@ async fn project_provider_event( { return Ok(()); } + // A notice about the session itself, such as Cursor keeping its current options, shows on + // the session whatever its state, until its next update. + if event.event_type == "session.notice" { + if let Some(message) = event.payload.get("message").and_then(Value::as_str) { + show_session_notice(engine, launch, message.to_owned()).await; + } + return Ok(()); + } + // A running turn's notice, such as a Cursor turn silent for minutes, shows on the running + // session and clears with a `null` message. It never revives a turn that already ended. + if event.event_type == "turn.notice" { + let running = engine + .repositories() + .get_thread_session(launch.thread_id.clone()) + .await + .map_err(|error| ProviderRuntimeError::Persistence(error.to_string()))? + .is_some_and(|session| { + session.status == "running" && session.active_turn_id == event.turn_id + }); + if running { + let message = event + .payload + .get("message") + .and_then(Value::as_str) + .map(str::to_owned); + dispatch_tagged_session_state( + engine, + launch, + "running", + event.turn_id.clone(), + (message, None), + None, + None, + ) + .await?; + } + return Ok(()); + } // A provider that keeps its asks across restarts (OpenCode) read its pending lists in full: // a request BiBCode still shows that they no longer hold cannot be answered (#187). if event.event_type == "requests.listed" { @@ -13631,6 +15469,7 @@ pub(crate) fn native_adapter_key(provider: &str) -> &'static str { "claude" | "claudeAgent" => "claude-stream-json", "cursor" => "cursor-acp", "grok" => "grok-acp", + "antigravity" => "antigravity-acp", "opencode" => "opencode-http", _ => "native-provider", } @@ -13680,11 +15519,17 @@ pub(crate) fn session_holds_a_turn(session: &ProjectionThreadSession) -> bool { /// Whether every `turn.started` the driver emits is a turn the provider reported running. Codex /// emits it for each `turn/started` notification, and Claude for a turn it starts itself (its -/// delivered turns begin on their replay). Cursor, OpenCode, and Grok announce a turn before -/// BiBCode sends it, so a send that then fails would leave the thread reading running; such a -/// driver marks a turn the provider started itself with `providerStarted: true` instead. +/// delivered turns begin on their replay). Antigravity and Cursor announce each prompt as they +/// write it and end every announced turn, an unsent one included, with `turn.completed`; ACP +/// answers the prompt only when the turn ends, so their delivery is accepted too late to mark it +/// running. OpenCode and Grok announce a turn before BiBCode sends it, so a send that then fails +/// would leave the thread reading running; such a driver marks a turn the provider started itself +/// with `providerStarted: true` instead. fn provider_reports_its_turns(provider: &str) -> bool { - matches!(provider, "codex" | "claude" | "claudeAgent") + matches!( + provider, + "codex" | "claude" | "claudeAgent" | "antigravity" | "cursor" + ) } /// Whether BiBCode can see the session's work outside a turn, so its absence means idle. Claude @@ -14788,6 +16633,14 @@ impl ProviderDriverFactory for NativeProviderDriverFactory { GrokDriver::spawn(request, self.attachments.clone(), self.attribution.clone()) .await?, ) as Arc), + "antigravity" => Ok(Arc::new( + AntigravityDriver::spawn( + request, + self.attachments.clone(), + self.attribution.clone(), + ) + .await?, + ) as Arc), "opencode" => Ok(Arc::new( OpenCodeDriver::spawn( request, @@ -15127,9 +16980,11 @@ where async fn kill_child(child: &SharedChild) { let mut child = child.lock().await; - if let Some(pid) = child.id() { - exits::note_stop_requested(pid); - } + // Already reaped: its process group id may belong to another process by now. + let Some(pid) = child.id() else { + return; + }; + exits::note_stop_requested(pid); let report = terminate_and_wait(&mut **child).await; log_cleanup_failures("provider process", &report); } @@ -15794,8 +17649,40 @@ struct CursorDriver { runtime: CursorSessionRuntime, child: SharedChild, attachments: AttachmentMaterializer, + /// Stops the child once the runtime abandons it; aborted with the driver. + abandon_watch: JoinHandle<()>, } + +impl Drop for CursorDriver { + fn drop(&mut self) { + self.abandon_watch.abort(); + } +} + impl CursorDriver { + fn new( + runtime: CursorSessionRuntime, + child: SharedChild, + attachments: AttachmentMaterializer, + ) -> Self { + let abandon_watch = tokio::spawn({ + let runtime = runtime.clone(); + let child = Arc::downgrade(&child); + async move { + runtime.abandoned().await; + if let Some(child) = child.upgrade() { + kill_child(&child).await; + } + } + }); + Self { + runtime, + child, + attachments, + abandon_watch, + } + } + async fn spawn( request: ProviderLaunchRequest, attachments: AttachmentMaterializer, @@ -15834,11 +17721,7 @@ impl CursorDriver { connection, incoming, ); - Ok(Self { - runtime, - child: Arc::new(Mutex::new(child)), - attachments, - }) + Ok(Self::new(runtime, Arc::new(Mutex::new(child)), attachments)) } async fn prepare_turn_input( @@ -15858,13 +17741,24 @@ impl CursorDriver { } impl ProviderDriver for CursorDriver { + fn start_notice_delay(&self) -> Duration { + crate::provider::cursor::runtime::START_NOTICE_DELAY + } + fn start(&self) -> BoxRuntimeFuture<'_, Result> { Box::pin(async move { let session_id = self .runtime .start() .await - .map_err(provider_error("cursor"))?; + // A model the session does not advertise is refused with its own sentence. + .map_err(|error| { + if error.option_refusal().is_some() { + option_error("cursor", error) + } else { + provider_error("cursor")(error) + } + })?; Ok(StartedSession { resume_cursor: Some(json!({ "schemaVersion": 1, @@ -15918,6 +17812,9 @@ impl ProviderDriver for CursorDriver { }; } }; + if receipt.stopped_unsent() { + return ProviderDeliveryOutcome::StoppedUnsent; + } let turn_id = receipt.turn_id.clone(); match receipt.completion().await { Ok(()) => ProviderDeliveryOutcome::Accepted { @@ -15938,11 +17835,11 @@ impl ProviderDriver for CursorDriver { } fn interrupt( &self, - _: Option, + turn_id: Option, ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { self.runtime - .interrupt_turn() + .interrupt_turn(turn_id.as_deref()) .await .map_err(provider_error("cursor")) }) @@ -16039,9 +17936,439 @@ impl ProviderDriver for CursorDriver { fn exited_process(&self) -> BoxRuntimeFuture<'_, Option<(u32, std::process::ExitStatus)>> { Box::pin(std::future::ready(exited_child(&self.child))) } + fn retired(&self) -> bool { + self.runtime.is_retired() + } + + fn shutdown(&self) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + // The writer task holds the CLI's stdin until the connection closes. + self.runtime.close().await; + kill_child(&self.child).await; + Ok(()) + }) + } +} + +struct AntigravityDriver { + runtime: AntigravitySessionRuntime, + child: SharedChild, + attachments: AttachmentMaterializer, + binary_path: String, + started: std::time::Instant, + /// Stops the child once the runtime abandons it; aborted with the driver. + abandon_watch: JoinHandle<()>, +} + +impl Drop for AntigravityDriver { + /// A driver dropped without `shutdown`, such as a cancelled start, still kills the child's + /// process group and waits for it, off the dropping task. + fn drop(&mut self) { + self.abandon_watch.abort(); + self.runtime.close(); + // The group kill is sent here, synchronously, so it happens even when no task can run + // any more (a runtime shutting down); only the reap is handed off. + // Only a child still owned is signalled: a reaped one's group id may be reused. + if let Ok(mut child) = self.child.try_lock() + && let Some(pid) = child.id() + { + exits::note_stop_requested(pid); + let _ = child.start_kill(); + } + if let Ok(handle) = tokio::runtime::Handle::try_current() { + let child = self.child.clone(); + handle.spawn(async move { kill_child(&child).await }); + } + } +} + +impl AntigravityDriver { + /// Spawns ` acp` in the checkout with no flag of its own (D-A5, D-A8). A cancelled + /// turn the CLI never ends stops the process; that stop is requested, not a crash. + async fn spawn( + request: ProviderLaunchRequest, + attachments: AttachmentMaterializer, + attribution: ProcessAttributionRegistry, + ) -> Result { + Self::spawn_with_cancel_grace(request, attachments, attribution, ANTIGRAVITY_CANCEL_GRACE) + .await + } + + async fn spawn_with_cancel_grace( + request: ProviderLaunchRequest, + attachments: AttachmentMaterializer, + attribution: ProcessAttributionRegistry, + cancel_grace: Duration, + ) -> Result { + let started = std::time::Instant::now(); + let binary_path = request.binary_path.clone(); + let mut child = spawn_child(&request, &["acp".to_owned()], true, attribution).await?; + let stdout = child + .stdout() + .take() + .ok_or_else(|| pipe_error(&request.provider, "stdout"))?; + let stdin = child + .stdin() + .take() + .ok_or_else(|| pipe_error(&request.provider, "stdin"))?; + let stderr = child + .stderr() + .take() + .ok_or_else(|| pipe_error(&request.provider, "stderr"))?; + let (connection, incoming) = AntigravityConnection::spawn( + stdout, + stdin, + stderr, + AntigravityConnectionConfig::default(), + ); + let runtime = AntigravitySessionRuntime::new( + AntigravitySessionOptions { + thread_id: request.thread_id, + cwd: request.cwd.to_string_lossy().into_owned(), + runtime_mode: request.runtime_mode, + interaction_mode: request.interaction_mode, + model: request.model, + resume_session_id: request.resume_cursor.as_ref().and_then(resume_string), + cancel_grace, + control_timeout: ANTIGRAVITY_CONTROL_TIMEOUT, + initial_options: request.options, + }, + connection, + incoming, + ); + let child: SharedChild = Arc::new(Mutex::new(child)); + let abandon_watch = tokio::spawn({ + let runtime = runtime.clone(); + let child = Arc::downgrade(&child); + async move { + runtime.abandoned().await; + if let Some(child) = child.upgrade() { + kill_child(&child).await; + } + } + }); + Ok(Self { + runtime, + child, + attachments, + binary_path, + started, + abandon_watch, + }) + } + + /// A child that died before the session pump starts is not seen by the pump's exit report, + /// so a failed start reports it here, before `shutdown` marks the process as stopped. + async fn report_startup_exit(&self) { + if !exits::watching() { + return; + } + // Every failure checks once, so a child that answered and then died is reported. Only a + // lost connection waits for the exit: a refusal from a live child must not hold the + // supervisor. The pipes close a moment before the exit status can be read. + let polls = if self.runtime.start_lost_connection() { + 40 + } else { + 1 + }; + for attempt in 0..polls { + if attempt > 0 { + tokio::time::sleep(Duration::from_millis(25)).await; + } + if let Some((pid, status)) = exited_child(&self.child) { + exits::report_exit( + Watch::Failures, + &Exited { + kind: "provider", + label: "antigravity", + exe: &self.binary_path, + pid, + started: self.started, + }, + &status, + false, + ); + return; + } + } + } + + async fn prepare_turn_input( + &self, + text: String, + attachments: Vec, + ) -> Result<(String, Vec), ProviderRuntimeError> { + let materialized = self + .attachments + .materialize(attachments) + .await + .map_err(attachment_error("antigravity"))?; + let (images, files) = split_native_images_and_file_references(materialized); + let text = append_file_references(text, &files).map_err(attachment_error("antigravity"))?; + Ok((text, images.into_iter().map(acp_image).collect())) + } +} + +/// Maps a runtime error. Sign-in, version and mode refusals need the user and are refused the +/// same way on every launch, so they are final for a delivery (D-A8). +fn antigravity_error(error: AntigravityRuntimeError) -> ProviderRuntimeError { + match error { + // Not retryable; the detail keeps Google's own notice. + AntigravityRuntimeError::AccountDisabled { .. } => { + ProviderRuntimeError::IncompatibleProvider { + provider: "antigravity".to_owned(), + detail: error.to_string(), + } + } + AntigravityRuntimeError::SignInRequired + | AntigravityRuntimeError::UnsupportedVersion { .. } + | AntigravityRuntimeError::ModeUnavailable { .. } => { + ProviderRuntimeError::IncompatibleProvider { + provider: "antigravity".to_owned(), + detail: error.to_string(), + } + } + // Option values stay out of the Display; only the refusal names them. + AntigravityRuntimeError::UnsupportedOption(_) => option_error("antigravity", error), + // The CLI's own words reach only the thread's turn error. Logs, delivery details and + // launch errors get the method we sent, the code and the class. + AntigravityRuntimeError::Protocol(error) => { + use crate::provider::antigravity::acp::{AcpProtocolError, acp_error_class}; + let class = acp_error_class(&error); + let line_too_long = match &error { + AcpProtocolError::LineTooLong { .. } => true, + AcpProtocolError::Closed { reason } => { + reason.starts_with("ACP JSON-RPC read line exceeded ") + } + _ => false, + }; + let detail = match &error { + AcpProtocolError::RemoteRequest { method, code, .. } => { + format!("Antigravity answered {method} with error {code} ({class})") + } + _ if line_too_long => { + "Antigravity sent a message longer than BiBCode accepts (transport_error)" + .to_owned() + } + _ => format!("Antigravity connection failed ({class})"), + }; + let provider = "antigravity".to_owned(); + if line_too_long { + ProviderRuntimeError::TransportLineTooLong { provider, detail } + } else { + ProviderRuntimeError::Provider { provider, detail } + } + } + // BiBCode's own texts. + error => ProviderRuntimeError::Provider { + provider: "antigravity".to_owned(), + detail: error.to_string(), + }, + } +} + +/// A turn the runtime refused before writing it: refusals the user must act on, and a line too +/// long, are final; anything else may be transient and is retried. +fn antigravity_unsent_outcome(error: AntigravityRuntimeError) -> ProviderDeliveryOutcome { + unsent_outcome(antigravity_error(error)) +} + +/// [`antigravity_unsent_outcome`] for an error already mapped, such as a refused mode write. +fn unsent_outcome(error: ProviderRuntimeError) -> ProviderDeliveryOutcome { + let detail = delivery_detail(&error, None); + match error { + ProviderRuntimeError::IncompatibleProvider { .. } + | ProviderRuntimeError::TransportLineTooLong { .. } => { + ProviderDeliveryOutcome::Rejected { detail } + } + _ => ProviderDeliveryOutcome::DefinitelyNotSent { detail }, + } +} + +impl ProviderDriver for AntigravityDriver { + fn start_notice_delay(&self) -> Duration { + ANTIGRAVITY_START_NOTICE_DELAY + } + fn start(&self) -> BoxRuntimeFuture<'_, Result> { + Box::pin(async move { + let session_id = match self.runtime.start().await { + Ok(session_id) => session_id, + Err(error) => { + self.report_startup_exit().await; + return Err(antigravity_error(error)); + } + }; + Ok(StartedSession { + resume_cursor: Some(json!({ "schemaVersion": 1, "sessionId": session_id })), + runtime_payload: None, + activity_capabilities: ActivityCapabilities::none(), + }) + }) + } + fn send( + &self, + text: String, + attachments: Vec, + _: String, + ) -> BoxRuntimeFuture<'_, Result, ProviderRuntimeError>> { + Box::pin(async move { + let (text, attachments) = self.prepare_turn_input(text, attachments).await?; + self.runtime + .send_turn_with_receipt(Some(&text), attachments) + .await + .map(|receipt| Some(receipt.turn_id)) + .map_err(antigravity_error) + }) + } + fn deliver( + &self, + text: String, + attachments: Vec, + _: String, + _: String, + ) -> BoxRuntimeFuture<'_, ProviderDeliveryOutcome> { + Box::pin(async move { + let (text, attachments) = match self.prepare_turn_input(text, attachments).await { + Ok(input) => input, + Err(error) => { + return ProviderDeliveryOutcome::Rejected { + detail: delivery_detail(&error, None), + }; + } + }; + let receipt = match self + .runtime + .send_turn_with_receipt(Some(&text), attachments) + .await + { + Ok(receipt) => receipt, + Err(error) => return antigravity_unsent_outcome(error), + }; + let turn_id = receipt.turn_id.clone(); + match receipt.completion().await { + Ok(()) => ProviderDeliveryOutcome::Accepted { + turn_id: Some(turn_id), + }, + Err( + error @ (AntigravityRuntimeError::SignInRequired + | AntigravityRuntimeError::AccountDisabled { .. } + | AntigravityRuntimeError::Protocol( + crate::provider::antigravity::acp::AcpProtocolError::RemoteRequest { + .. + }, + )), + ) => ProviderDeliveryOutcome::Rejected { + detail: delivery_detail(&antigravity_error(error), None), + }, + Err(error) => ProviderDeliveryOutcome::Ambiguous { + detail: delivery_detail(&antigravity_error(error), None), + }, + } + }) + } + fn interrupt( + &self, + turn_id: Option, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .interrupt_turn(turn_id.as_deref()) + .await + .map_err(antigravity_error) + }) + } + fn approve( + &self, + request_id: String, + decision: String, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .respond_to_request(&request_id, &decision) + .await + .map_err(antigravity_error) + }) + } + fn answer( + &self, + _: String, + _: Value, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + // The client advertises no elicitation, so no question is ever pending (D-A7). + unsupported("antigravity", "user input answers") + } + fn set_mode(&self, mode: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .set_runtime_mode(&mode) + .await + .map_err(antigravity_error) + }) + } + fn set_interaction_mode( + &self, + mode: String, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .set_interaction_mode(&mode) + .await + .map_err(antigravity_error) + }) + } + fn set_model(&self, model: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .set_model(&model) + .await + .map_err(antigravity_error) + }) + } + fn reapply_options_on_model_change(&self) -> bool { + true + } + fn set_options( + &self, + options: Vec, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + Box::pin(async move { + self.runtime + .set_options(options) + .await + .map_err(antigravity_error) + }) + } + fn rollback( + &self, + _: i64, + _: String, + ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { + unsupported("antigravity", "checkpoint rollback") + } + fn next_event(&self) -> BoxRuntimeFuture<'_, Option> { + Box::pin(async move { + self.runtime.next_event().await.map(|event| ProviderEvent { + native_event_id: None, + event_type: event.event_type, + thread_id: event.thread_id, + turn_id: event.turn_id, + item_id: None, + request_id: event.request_id, + payload: event.payload, + activity: Vec::new(), + activity_controls: Default::default(), + }) + }) + } + fn exited_process(&self) -> BoxRuntimeFuture<'_, Option<(u32, std::process::ExitStatus)>> { + Box::pin(std::future::ready(exited_child(&self.child))) + } fn shutdown(&self) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { + // One call closes the connection; killing the group closes the CLI's output, so the + // transport readers and the runtime's reader end too. + self.runtime.close(); kill_child(&self.child).await; Ok(()) }) @@ -20143,7 +22470,8 @@ impl ClaudeDriver { } ProviderDeliveryOutcome::Accepted { .. } | ProviderDeliveryOutcome::AcceptedInNewConversation { .. } - | ProviderDeliveryOutcome::AlreadyDelivered => ProviderCompactionStart::NotStarted { + | ProviderDeliveryOutcome::AlreadyDelivered + | ProviderDeliveryOutcome::StoppedUnsent => ProviderCompactionStart::NotStarted { detail: "the compaction was not written".to_owned(), }, }; @@ -21438,7 +23766,7 @@ fn provider_error( || detail.starts_with( "Codex JSON-RPC connection is closed: Codex JSON-RPC read line exceeded ", ), - "cursor" | "grok" => { + "cursor" | "grok" | "antigravity" => { detail.starts_with("ACP JSON-RPC read line exceeded ") || detail.starts_with( "ACP JSON-RPC connection is closed: ACP JSON-RPC read line exceeded ", @@ -21813,7 +24141,10 @@ mod tests { answers: usize, modes: Vec, set_mode_unsupported: bool, + /// `set_mode` fails as a CLI that did not confirm the mode would. + set_mode_fails: bool, interaction_modes: Vec, + set_interaction_mode_unsupported: bool, models: Vec, retired_model: Option<&'static str>, rollbacks: Vec, @@ -22225,6 +24556,12 @@ mod tests { capability: "runtime mode", }); } + if state.set_mode_fails { + return Err(super::ProviderRuntimeError::Provider { + provider: "codex".to_owned(), + detail: "the mode was not confirmed".to_owned(), + }); + } Ok(()) }) } @@ -22234,7 +24571,14 @@ mod tests { mode: String, ) -> super::BoxRuntimeFuture<'_, Result<(), super::ProviderRuntimeError>> { Box::pin(async move { - self.state.lock().unwrap().interaction_modes.push(mode); + let mut state = self.state.lock().unwrap(); + state.interaction_modes.push(mode); + if state.set_interaction_mode_unsupported { + return Err(super::ProviderRuntimeError::UnsupportedCapability { + provider: "codex".to_owned(), + capability: "interaction mode", + }); + } Ok(()) }) } @@ -22401,7 +24745,7 @@ mod tests { impl ProviderDriverFactory for SequencedSupervisorFactory { fn create( &self, - _: super::ProviderLaunchRequest, + request: super::ProviderLaunchRequest, ) -> super::BoxRuntimeFuture<'_, Result, super::ProviderRuntimeError>> { Box::pin(async move { @@ -22412,6 +24756,7 @@ mod tests { .pop_front() .expect("sequenced provider driver"); state.lock().unwrap().launches += 1; + state.lock().unwrap().launch_requests.push(request); Ok(Arc::new(SupervisorDriver { state, events: tokio::sync::Mutex::new(events), @@ -22843,7 +25188,10 @@ mod tests { refused.to_string(), "claudeAgent provider operation failed: option fastMode is not supported by the selected model/session" ); - assert_eq!(refusal, "Fast Mode is not supported by the selected model."); + assert_eq!( + refusal, + "Fast Mode is not supported by the selected model. Choose another option for this model." + ); } /// Every error a delivery can meet reads as plain words that name the provider by the @@ -22857,9 +25205,9 @@ mod tests { provider: "codex".to_owned(), detail: "option madeUp is not supported by the selected model/session" .to_owned(), - refusal: "madeUp is not supported by the selected model.".to_owned(), + refusal: "madeUp is not supported by the selected model. Choose another option for this model.".to_owned(), }, - "madeUp is not supported by the selected model.", + "madeUp is not supported by the selected model. Choose another option for this model.", ), ( Error::Provider { @@ -23013,7 +25361,14 @@ mod tests { Some((kinds[constant], name)) }) .collect::>(); - for kind in ["claudeAgent", "codex", "cursor", "grok", "opencode"] { + for kind in [ + "claudeAgent", + "codex", + "cursor", + "grok", + "opencode", + "antigravity", + ] { assert!( names.iter().any(|(listed, _)| *listed == kind), "contracts name {kind}" @@ -23133,7 +25488,7 @@ mod tests { assert_eq!( super::launch_failure_outcome(&error, "Work Claude"), super::ProviderDeliveryOutcome::Refused { - detail: "Fast Mode is not supported by the selected model.".to_owned() + detail: "Fast Mode is not supported by the selected model. Choose another option for this model.".to_owned() } ); } @@ -23501,7 +25856,7 @@ lines.on("line", (line) => { case "session/new": result = { sessionId: "cursor-session", - configOptions: [{ id: "model", category: "model" }], + configOptions: [{ id: "model", category: "model", options: [{ value: "test-model" }] }], modes: { currentModeId: "ask", availableModes: [ @@ -28454,7 +30809,7 @@ while IFS= read -r line; do id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') case "$line" in *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; - *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model"}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model","options":[{"value":"test-model"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}\n' "$id" ;; *'"method":"session/create"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"grok-session","modes":{"currentModeId":"code","availableModes":[{"id":"code","name":"Agent"},{"id":"ask","name":"Ask"}]}}}\n' "$id" ;; *'"method":"session/set_config_option"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[]}}\n' "$id" ;; *'"method":"session/set_mode"'*|*'"method":"session/set_model"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; @@ -28694,6 +31049,127 @@ done )); } + /// A Cursor that ignores the cancel of a stopped turn is stopped like a requested stop after + /// the cancel grace: the turn is accepted and ended, the driver is retired, and the child is + /// reaped. + #[cfg(unix)] + #[tokio::test] + async fn a_cursor_that_ignores_a_stops_cancel_is_stopped_as_a_requested_stop() { + let captured = crate::diagnostics::profiler::exits::CapturedExits::start(); + let temp = TempDir::new().expect("provider fixture directory"); + // The gate is never opened, so the prompt is never answered and the cancel is ignored. + let driver = cursor_delivery_fixture( + &temp, + &temp.path().join("requests.jsonl"), + Some(&temp.path().join("never-opened")), + false, + false, + ) + .await; + driver.start().await.expect("the chat starts"); + driver + .runtime + .set_stop_deadlines(Duration::from_millis(300), Duration::from_secs(30)); + let delivery = tokio::spawn({ + let driver = driver.clone(); + async move { + driver + .deliver( + "hello".to_owned(), + Vec::new(), + "default".to_owned(), + "key".to_owned(), + ) + .await + } + }); + captured_request( + ProviderFixtureDeadline::integration(), + &temp.path().join("requests.jsonl"), + |value| value["method"] == "session/prompt", + ) + .await + .expect("the prompt was written"); + driver.interrupt(None).await.expect("stop"); + let outcome = timeout(Duration::from_secs(5), delivery) + .await + .expect("the stop grace ends the delivery") + .unwrap(); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + assert!(driver.retired(), "the next message launches Cursor again"); + timeout(Duration::from_secs(5), async { + while driver.child.lock().await.id().is_some() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the child was stopped and reaped"); + // The stream ends with `session.exited`, which ends the supervised session, so the next + // message launches Cursor again and resumes the saved session. + timeout(Duration::from_secs(5), async { + while let Some(event) = driver.next_event().await { + if event.event_type == "session.exited" { + return; + } + } + panic!("the event stream closed without session.exited"); + }) + .await + .expect("the stopped child ends the session"); + driver.shutdown().await.expect("fixture shutdown"); + assert!( + captured.take().is_empty(), + "a requested stop is not a crash" + ); + } + + /// A Cursor that does not answer `session/new`, as when one of its MCP servers never + /// connects, is not given up: its start keeps waiting and its process keeps running. The + /// launch shows the start notice after a minute, and only a stop ends the start. + #[cfg(unix)] + #[tokio::test] + async fn a_cursor_that_does_not_finish_starting_keeps_waiting() { + let temp = TempDir::new().expect("provider fixture directory"); + let executable = executable_fixture( + &temp, + "cursor-never-starts", + r#"#!/bin/sh +while IFS= read -r line; do + id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; + esac +done +"#, + ); + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(&temp, "cursor"); + request.binary_path = executable.to_string_lossy().into_owned(); + let driver = super::CursorDriver::spawn( + request, + factory.attachments.clone(), + factory.attribution.clone(), + ) + .await + .expect("the fixture spawns"); + assert_eq!(driver.start_notice_delay(), Duration::from_secs(60)); + assert!( + timeout(Duration::from_secs(1), driver.start()) + .await + .is_err(), + "the start keeps waiting on session/new" + ); + assert!(!driver.runtime.is_retired()); + assert!( + driver.child.lock().await.id().is_some(), + "the process keeps running" + ); + driver.shutdown().await.expect("fixture shutdown"); + } + #[tokio::test] async fn cursor_delivery_prompt_write_zero_bytes_is_definitely_not_sent() { // Mutation caught: treating a proven zero-byte failure as possibly submitted prevents a @@ -28829,7 +31305,7 @@ done Some("initialize" | "authenticate" | "session/set_mode") => json!({}), Some("session/new") => json!({ "sessionId": "cursor-session", - "configOptions": [{ "id": "model", "category": "model" }], + "configOptions": [{ "id": "model", "category": "model", "currentValue": "test-model" }], "modes": { "currentModeId": "ask", "availableModes": [ @@ -28855,11 +31331,8 @@ done } let _ = hold_peer_open.await; }); - let driver = super::CursorDriver { - runtime, - child: dummy.child.clone(), - attachments: dummy.attachments.clone(), - }; + let driver = + super::CursorDriver::new(runtime, dummy.child.clone(), dummy.attachments.clone()); driver.start().await.expect("Cursor fixture should start"); let outcome = timeout( @@ -28873,6 +31346,20 @@ done ) .await .expect("writer failure should resolve delivery"); + // Every announced turn ends exactly once, an unsent one included, so the projection can + // mark Cursor turns running from their announcement. + let mut turn_events = Vec::new(); + while let Ok(Some(event)) = + timeout(std::time::Duration::from_millis(300), driver.next_event()).await + { + if event.event_type.starts_with("turn.") { + turn_events.push((event.event_type, event.turn_id)); + } + } + assert_eq!(turn_events.len(), 2, "{failure:?}: {turn_events:?}"); + assert_eq!(turn_events[0].0, "turn.started", "{failure:?}"); + assert_eq!(turn_events[1].0, "turn.completed", "{failure:?}"); + assert_eq!(turn_events[0].1, turn_events[1].1, "{failure:?}"); let pending_request_count = pending_connection.pending_request_count().await; let _ = release_peer.send(()); timeout(std::time::Duration::from_secs(2), driver.shutdown()) @@ -28892,7 +31379,7 @@ done ) } - #[derive(Clone, Copy, PartialEq, Eq)] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PromptWriteFailure { BeforeFirstByte, AfterPrefix, @@ -29066,6 +31553,7 @@ done connect_mcp: Arc::new(tokio::sync::RwLock::new(None)), open_url: None, activity_cancellation: Arc::new(tokio::sync::RwLock::new(None)), + launch_stops: Default::default(), }; assert_eq!( supervisor @@ -29086,6 +31574,7 @@ done connect_mcp: Arc::new(tokio::sync::RwLock::new(None)), open_url: None, activity_cancellation: Arc::new(tokio::sync::RwLock::new(None)), + launch_stops: Default::default(), }; let drop_response = tokio::spawn(async move { let Some(super::SupervisorMessage::CancelActivityTarget { response, .. }) = @@ -30719,6 +33208,73 @@ done engine.shutdown().await; } + /// A mode switch the driver could not confirm still becomes the session's launch mode: a + /// later restart (here for an interaction mode the driver cannot switch in place) starts + /// the replacement in the thread's current mode, never the more permissive earlier one. + #[tokio::test] + async fn a_restart_after_an_unconfirmed_mode_switch_launches_the_requested_mode() { + let engine = supervisor_engine().await; + let activity = super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )); + let first = Arc::new(StdMutex::new(SupervisorDriverState { + set_mode_fails: true, + set_interaction_mode_unsupported: true, + ..SupervisorDriverState::default() + })); + let replacement = Arc::new(StdMutex::new(SupervisorDriverState::default())); + let (_first_tx, first_rx) = mpsc::channel(1); + let (_replacement_tx, replacement_rx) = mpsc::channel(1); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(SequencedSupervisorFactory { + drivers: StdMutex::new(std::collections::VecDeque::from([ + (first.clone(), first_rx), + (replacement.clone(), replacement_rx), + ])), + }), + activity, + super::SupervisorOptions::default(), + ); + let temp = TempDir::new().expect("launch directory"); + let mut launch = native_launch(&temp, "codex"); + launch.thread_id = "t1".to_owned(); + launch.runtime_mode = "full-access".to_owned(); + supervisor.launch(launch).await.expect("launch runtime"); + + let switched = timeout( + std::time::Duration::from_secs(2), + supervisor.handle_orchestration(OrchestrationCommand::ThreadRuntimeModeSet { + command_id: "mode-unconfirmed".to_owned(), + thread_id: "t1".to_owned(), + runtime_mode: "approval-required".to_owned(), + created_at: "2026-07-16T00:00:00Z".to_owned(), + }), + ) + .await + .expect("mode switch returns"); + assert!(switched.is_err(), "the driver did not confirm the mode"); + timeout( + std::time::Duration::from_secs(2), + supervisor.handle_orchestration(OrchestrationCommand::ThreadInteractionModeSet { + command_id: "plan-restart".to_owned(), + thread_id: "t1".to_owned(), + interaction_mode: "plan".to_owned(), + created_at: "2026-07-16T00:00:01Z".to_owned(), + }), + ) + .await + .expect("restart returns") + .expect("restart succeeds"); + let relaunched = replacement.lock().unwrap().launch_requests.clone(); + assert_eq!(relaunched.len(), 1); + assert_eq!(relaunched[0].runtime_mode, "approval-required"); + assert_eq!(relaunched[0].interaction_mode, "plan"); + + supervisor.shutdown().await.expect("shutdown supervisor"); + engine.shutdown().await; + } + #[tokio::test] async fn supervisor_shutdown_cancels_and_reaps_held_late_dispatch_before_returning() { let runtime = start_held_late_runtime().await; @@ -32912,26 +35468,122 @@ done fixture.close().await; } - /// Cursor announces a turn before BiBCode sends it. If that send fails no `turn.completed` + /// A running turn's notice shows on the running session and clears with a `null` message; + /// one for a turn that already ended changes nothing. + #[tokio::test(start_paused = true)] + async fn a_turn_notice_shows_on_the_running_session_and_clears() { + let _clock = keep_idle_clock_paused(); + let fixture = + IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "cursor").await; + IdleDeadlineFixture::accepted(fixture.admit("first").await, "idle-turn-1").await; + let last_error = || async { + fixture + .engine + .repositories() + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .expect("projected session") + .last_error + }; + let settle = |wanted: Option<&'static str>| async move { + timeout(Duration::from_secs(5), async { + while last_error().await.as_deref() != wanted { + tokio::task::yield_now().await; + } + }) + .await + .unwrap_or_else(|_| panic!("last error never became {wanted:?}")); + }; + fixture + .emit_payload("turn.notice", "idle-turn-1", json!({ "message": "Quiet." })) + .await; + settle(Some("Quiet.")).await; + fixture + .assert_projection("running", Some("idle-turn-1")) + .await; + fixture + .emit_payload("turn.notice", "idle-turn-1", json!({ "message": null })) + .await; + settle(None).await; + fixture + .emit("turn.completed", "idle-turn-1", "assistant-first") + .await; + timeout(Duration::from_secs(5), async { + while fixture + .engine + .repositories() + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .is_some_and(|session| session.status == "running") + { + tokio::task::yield_now().await; + } + }) + .await + .expect("the turn completed"); + fixture + .emit_payload("turn.notice", "idle-turn-1", json!({ "message": "Late." })) + .await; + fixture.stream("idle-turn-1", "assistant-late").await; + fixture.assert_projection("ready", None).await; + assert_eq!(last_error().await, None); + fixture.close().await; + } + + /// A session's notice, such as Cursor keeping its current options because their previous + /// defaults are gone, shows on the session while it is idle and keeps its state. + #[tokio::test(start_paused = true)] + async fn a_session_notice_shows_on_an_idle_session() { + let _clock = keep_idle_clock_paused(); + let fixture = + IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "cursor").await; + fixture + .emit_payload("session.notice", "unused", json!({ "message": "Kept." })) + .await; + // The clock is paused, so the wait is bounded by a count of polls, not by time. + let mut shown = false; + for _ in 0..2_000 { + shown = fixture + .engine + .repositories() + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .and_then(|session| session.last_error) + .as_deref() + == Some("Kept."); + if shown { + break; + } + tokio::task::yield_now().await; + } + assert!(shown, "the notice shows"); + fixture.assert_projection("ready", None).await; + fixture.close().await; + } + + /// OpenCode announces a turn before BiBCode sends it. If that send fails no `turn.completed` /// follows, so the announcement must not leave the thread reading running. #[tokio::test(start_paused = true)] async fn a_turn_announced_before_its_send_does_not_mark_the_thread_running() { let _clock = keep_idle_clock_paused(); let fixture = - IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "cursor").await; + IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "opencode").await; fixture.emit("turn.started", "announced", "unused").await; fixture.stream("announced", "assistant-announced").await; fixture.assert_projection("ready", None).await; fixture.close().await; } - /// A stop after Cursor announced a turn and streamed part of its reply, but before the send + /// A stop after OpenCode announced a turn and streamed part of its reply, but before the send /// was accepted, leaves that turn failed at start-up, never completed. #[tokio::test(start_paused = true)] async fn startup_recovery_fails_a_turn_cut_off_before_its_send_was_accepted() { let _clock = keep_idle_clock_paused(); let fixture = - IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "cursor").await; + IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "opencode").await; fixture.emit("turn.started", "announced", "unused").await; fixture.stream("announced", "assistant-announced").await; fixture.assert_projection("ready", None).await; @@ -32957,7 +35609,7 @@ done async fn startup_recovery_fails_a_turn_cut_off_before_its_send_was_accepted_after_a_shutdown() { let _clock = keep_idle_clock_paused(); let fixture = - IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "cursor").await; + IdleDeadlineFixture::new_for_provider(BUSY_SESSION_IDLE_TIMEOUT, "opencode").await; fixture.emit("turn.started", "announced", "unused").await; fixture.stream("announced", "assistant-announced").await; fixture.assert_projection("ready", None).await; @@ -37704,6 +40356,7 @@ done ("claudeAgent", "claude-stream-json"), ("cursor", "cursor-acp"), ("grok", "grok-acp"), + ("antigravity", "antigravity-acp"), ("opencode", "opencode-http"), ("future-provider", "native-provider"), ] { @@ -38389,6 +41042,1289 @@ printf '2.1.0 (Claude Code)\n' assert!(cmd_index < powershell_index); } + + /// A scripted `agy acp`, shaped like CLI 1.5.13 with placeholder ids. Environment switches + /// pick the version, a signed-out CLI, a lost session, an exit during `initialize` and the + /// prompt outcomes. + #[cfg(unix)] + const ANTIGRAVITY_FIXTURE: &str = r#"#!/bin/sh +modes='{"value":"default"},{"value":"accept-edits"},{"value":"auto"},{"value":"plan"}' +options() { printf '[{"id":"mode","category":"mode","type":"select","currentValue":"%s","options":[%s]}]' "$1" "$modes"; } +[ -z "$BIBCODE_TEST_ARGV_CAPTURE" ] || { printf '%s\n' "$*" > "$BIBCODE_TEST_ARGV_CAPTURE"; pwd -P >> "$BIBCODE_TEST_ARGV_CAPTURE"; } +while IFS= read -r line; do + [ -z "$BIBCODE_TEST_REQUEST_CAPTURE" ] || printf '%s\n' "$line" >> "$BIBCODE_TEST_REQUEST_CAPTURE" + id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) + [ -z "$BIBCODE_TEST_EXIT_ON_INITIALIZE" ] || exit 7 + # The answer arrives after the CLI process itself has exited, so the order is fixed. + [ -z "$BIBCODE_TEST_REFUSE_THEN_EXIT" ] || { ( sleep 0.3; printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"Method not found"}}\n' "$id" ) & exit 7; } + if [ -n "$BIBCODE_TEST_DESCENDANT_PID" ]; then + sleep 300 & + printf '%s\n' "$!" > "$BIBCODE_TEST_DESCENDANT_PID" + continue + fi + printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"resume":{}}},"agentInfo":{"name":"fixture","version":"%s"}}}\n' "$id" "${BIBCODE_TEST_AGY_VERSION:-1.5.13}" ;; + *'"method":"session/new"'*) + [ -z "$BIBCODE_TEST_SIGNED_OUT" ] || { printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"Authentication required"}}\n' "$id"; continue; } + printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"antigravity-session","configOptions":%s}}\n' "$id" "$(options default)" ;; + *'"method":"session/resume"'*) + [ -z "$BIBCODE_TEST_MISSING_SESSION" ] || { printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Failed to read session; retry, or load it with session/load"}}\n' "$id"; continue; } + sid=$(printf '%s\n' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p') + printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s","configOptions":%s}}\n' "$id" "$sid" "$(options default)" ;; + *'"method":"session/set_config_option"'*) + value=$(printf '%s\n' "$line" | sed -n 's/.*"value":"\([^"]*\)".*/\1/p') + # Never answers the first `auto` write; the marker file records that it was withheld. + if [ "$value" = auto ] && [ -n "$BIBCODE_TEST_WITHHOLD_FIRST_AUTO" ] && [ ! -e "$BIBCODE_TEST_WITHHOLD_FIRST_AUTO" ]; then : > "$BIBCODE_TEST_WITHHOLD_FIRST_AUTO"; continue; fi + # Refuses one mode: the answer keeps the CLI in `default`. + [ -z "$BIBCODE_TEST_REFUSE_MODE" ] || [ "$value" != "$BIBCODE_TEST_REFUSE_MODE" ] || value=default + printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":%s}}\n' "$id" "$(options "$value")" ;; + *'"method":"session/prompt"'*) + [ -z "$BIBCODE_TEST_REJECT_PROMPT" ] || { printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"prompt rejected"}}\n' "$id"; continue; } + [ -z "$BIBCODE_TEST_DISCONNECT_AFTER_PROMPT" ] || exit 0 + [ -z "$BIBCODE_TEST_IGNORE_PROMPT" ] || continue + # Asks for a permission first and answers the prompt only once the reply arrives. + [ -z "$BIBCODE_TEST_APPROVAL_BEFORE_ANSWER" ] || { prompt_id=$id; printf '{"jsonrpc":"2.0","id":900,"method":"session/request_permission","params":{"sessionId":"antigravity-session","toolCall":{"toolCallId":"call-1","status":"pending","kind":"edit","title":"File notes.txt"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"},{"optionId":"deny","name":"Deny","kind":"reject_once"}]}}\n'; continue; } + printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id" ;; + *'"id":900'*) + printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$prompt_id" ;; + esac +done +"#; + + #[cfg(unix)] + async fn antigravity_fixture_driver( + temp: &TempDir, + instance: &str, + environment: &[(&str, &str)], + resume_session: Option<&str>, + ) -> Arc { + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(temp, "antigravity"); + request.provider_instance_id = Some(instance.to_owned()); + request.binary_path = executable_fixture(temp, "agy", ANTIGRAVITY_FIXTURE) + .to_string_lossy() + .into_owned(); + request.resume_cursor = + resume_session.map(|session| json!({ "schemaVersion": 1, "sessionId": session })); + for (name, value) in environment { + request + .environment + .insert((*name).to_owned(), (*value).to_owned()); + } + Arc::new( + super::AntigravityDriver::spawn( + request, + factory.attachments.clone(), + factory.attribution.clone(), + ) + .await + .expect("the Antigravity fixture spawns"), + ) + } + + #[cfg(unix)] + fn captured_methods(path: &std::path::Path) -> Vec { + std::fs::read_to_string(path) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter_map(|message| message["method"].as_str().map(str::to_owned)) + .collect() + } + + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_chat_runs_agy_acp_in_the_checkout_for_any_instance() { + assert_eq!( + super::canonical_provider_kind("antigravity").unwrap(), + "antigravity" + ); + for instance in ["antigravity", "antigravity-work"] { + let temp = TempDir::new().expect("provider fixture directory"); + let argv = temp.path().join("argv"); + let requests = temp.path().join("requests.jsonl"); + let driver = antigravity_fixture_driver( + &temp, + instance, + &[ + ("BIBCODE_TEST_ARGV_CAPTURE", argv.to_str().unwrap()), + ("BIBCODE_TEST_REQUEST_CAPTURE", requests.to_str().unwrap()), + ], + None, + ) + .await; + let started = driver.start().await.expect("the chat starts"); + assert_eq!( + started.resume_cursor, + Some(json!({ "schemaVersion": 1, "sessionId": "antigravity-session" })) + ); + driver.shutdown().await.expect("fixture shutdown"); + + let argv = std::fs::read_to_string(&argv).expect("argv captured"); + let mut lines = argv.lines(); + assert_eq!(lines.next(), Some("acp"), "no flag besides `acp`"); + assert_eq!( + lines.next().map(std::path::PathBuf::from), + Some(temp.path().canonicalize().unwrap()), + "the child runs in the checkout" + ); + assert_eq!( + captured_methods(&requests), + ["initialize", "session/new", "session/set_config_option"], + "{instance}: no authenticate, and the approval mode is written" + ); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn antigravity_version_and_sign_in_refusals_are_final_and_write_no_prompt() { + for (environment, expected) in [ + (vec![("BIBCODE_TEST_AGY_VERSION", "1.5.3")], "1.5.4"), + (vec![("BIBCODE_TEST_SIGNED_OUT", "1")], "agy acp --login"), + ] { + let temp = TempDir::new().expect("provider fixture directory"); + let requests = temp.path().join("requests.jsonl"); + let mut environment = environment; + environment.push(("BIBCODE_TEST_REQUEST_CAPTURE", requests.to_str().unwrap())); + let driver = antigravity_fixture_driver(&temp, "antigravity", &environment, None).await; + let error = driver.start().await.expect_err("refused"); + driver.shutdown().await.expect("fixture shutdown"); + assert!( + matches!(&error, super::ProviderRuntimeError::IncompatibleProvider { detail, .. } if detail.contains(expected)), + "{error:?}" + ); + assert!( + matches!( + super::launch_failure_outcome(&error, "Antigravity"), + super::ProviderDeliveryOutcome::Rejected { .. } + ), + "the durable launch path does not retry it" + ); + assert!(!captured_methods(&requests).contains(&"session/prompt".to_owned())); + } + + let temp = TempDir::new().expect("provider fixture directory"); + let driver = antigravity_fixture_driver( + &temp, + "antigravity", + &[("BIBCODE_TEST_AGY_VERSION", "1.5.4")], + None, + ) + .await; + driver.start().await.expect("1.5.4 is allowed"); + driver.shutdown().await.expect("fixture shutdown"); + } + + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_child_that_dies_during_initialize_is_an_unrequested_exit() { + let captured = crate::diagnostics::profiler::exits::CapturedExits::start(); + let temp = TempDir::new().expect("provider fixture directory"); + let driver = antigravity_fixture_driver( + &temp, + "antigravity", + &[("BIBCODE_TEST_EXIT_ON_INITIALIZE", "1")], + None, + ) + .await; + let error = driver.start().await.expect_err("the child exited"); + driver.shutdown().await.expect("fixture shutdown"); + assert!( + matches!(&error, super::ProviderRuntimeError::IncompatibleProvider { detail, .. } if detail.contains("1.5.4")), + "{error:?}" + ); + let findings = captured.take(); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!( + findings[0].iter().any(|field| field == "antigravity"), + "{findings:?}" + ); + + // A child that answers `initialize` with an error and then dies is reported too. + let temp = TempDir::new().expect("provider fixture directory"); + let driver = antigravity_fixture_driver( + &temp, + "antigravity", + &[("BIBCODE_TEST_REFUSE_THEN_EXIT", "1")], + None, + ) + .await; + driver.start().await.expect_err("refused"); + driver.shutdown().await.expect("fixture shutdown"); + assert_eq!( + captured.take().len(), + 1, + "the exit after a reply is reported" + ); + + // A session stopped on request is not a crash. + let temp = TempDir::new().expect("provider fixture directory"); + let driver = antigravity_fixture_driver(&temp, "antigravity", &[], None).await; + driver.start().await.expect("the chat starts"); + driver.shutdown().await.expect("fixture shutdown"); + assert!(captured.take().is_empty()); + } + + #[cfg(unix)] + #[tokio::test] + async fn antigravity_delivery_maps_each_prompt_outcome() { + // Not started: no session, so no prompt is written. + let temp = TempDir::new().expect("provider fixture directory"); + let requests = temp.path().join("requests.jsonl"); + let driver = antigravity_fixture_driver( + &temp, + "antigravity", + &[("BIBCODE_TEST_REQUEST_CAPTURE", requests.to_str().unwrap())], + None, + ) + .await; + let outcome = driver + .deliver( + "hello".to_owned(), + Vec::new(), + "default".to_owned(), + "key".to_owned(), + ) + .await; + driver.shutdown().await.expect("fixture shutdown"); + assert!( + matches!( + outcome, + super::ProviderDeliveryOutcome::DefinitelyNotSent { .. } + ), + "{outcome:?}" + ); + assert!(!captured_methods(&requests).contains(&"session/prompt".to_owned())); + + for (switch, expected) in [ + (None, "accepted"), + (Some("BIBCODE_TEST_REJECT_PROMPT"), "rejected"), + (Some("BIBCODE_TEST_DISCONNECT_AFTER_PROMPT"), "ambiguous"), + ] { + let temp = TempDir::new().expect("provider fixture directory"); + let environment = switch.map(|name| vec![(name, "1")]).unwrap_or_default(); + let driver = antigravity_fixture_driver(&temp, "antigravity", &environment, None).await; + driver.start().await.expect("the chat starts"); + let outcome = driver + .deliver( + "hello".to_owned(), + Vec::new(), + "default".to_owned(), + "key".to_owned(), + ) + .await; + driver.shutdown().await.expect("fixture shutdown"); + let actual = match outcome { + super::ProviderDeliveryOutcome::Accepted { .. } => "accepted", + super::ProviderDeliveryOutcome::Rejected { .. } => "rejected", + super::ProviderDeliveryOutcome::Ambiguous { .. } => "ambiguous", + other => panic!("unexpected outcome {other:?}"), + }; + assert_eq!(actual, expected); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn antigravity_reopens_a_saved_session_and_starts_a_new_one_when_it_is_gone() { + let temp = TempDir::new().expect("provider fixture directory"); + let driver = + antigravity_fixture_driver(&temp, "antigravity", &[], Some("saved-session")).await; + let started = driver.start().await.expect("resumed"); + driver.shutdown().await.expect("fixture shutdown"); + assert_eq!( + started + .resume_cursor + .as_ref() + .and_then(super::resume_string), + Some("saved-session".to_owned()) + ); + + let temp = TempDir::new().expect("provider fixture directory"); + let driver = antigravity_fixture_driver( + &temp, + "antigravity", + &[("BIBCODE_TEST_MISSING_SESSION", "1")], + Some("saved-session"), + ) + .await; + let started = driver.start().await.expect("a new session"); + driver.shutdown().await.expect("fixture shutdown"); + assert_eq!( + started + .resume_cursor + .as_ref() + .and_then(super::resume_string), + Some("antigravity-session".to_owned()), + "a different id tells the supervisor the resume was lost" + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn the_factory_dispatches_antigravity_to_its_driver() { + let temp = TempDir::new().expect("provider fixture directory"); + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(&temp, "antigravity"); + request.binary_path = executable_fixture(&temp, "agy", ANTIGRAVITY_FIXTURE) + .to_string_lossy() + .into_owned(); + let driver = factory + .create(request) + .await + .expect("the factory spawns it"); + let started = driver.start().await.expect("the chat starts"); + driver.shutdown().await.expect("fixture shutdown"); + assert_eq!( + started + .resume_cursor + .as_ref() + .and_then(super::resume_string), + Some("antigravity-session".to_owned()) + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn an_unanswered_antigravity_cancel_stops_the_child_as_a_requested_stop() { + let captured = crate::diagnostics::profiler::exits::CapturedExits::start(); + let temp = TempDir::new().expect("provider fixture directory"); + let requests = temp.path().join("requests.jsonl"); + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(&temp, "antigravity"); + request.binary_path = executable_fixture(&temp, "agy", ANTIGRAVITY_FIXTURE) + .to_string_lossy() + .into_owned(); + for (name, value) in [ + ("BIBCODE_TEST_IGNORE_PROMPT", "1"), + ("BIBCODE_TEST_REQUEST_CAPTURE", requests.to_str().unwrap()), + ] { + request + .environment + .insert(name.to_owned(), value.to_owned()); + } + let driver = Arc::new( + super::AntigravityDriver::spawn_with_cancel_grace( + request, + factory.attachments.clone(), + factory.attribution.clone(), + Duration::from_millis(100), + ) + .await + .expect("the Antigravity fixture spawns"), + ); + driver.start().await.expect("the chat starts"); + let delivery = tokio::spawn({ + let driver = driver.clone(); + async move { + driver + .deliver( + "hello".to_owned(), + Vec::new(), + "default".to_owned(), + "key".to_owned(), + ) + .await + } + }); + tokio::time::timeout(Duration::from_secs(5), async { + while !captured_methods(&requests).contains(&"session/prompt".to_owned()) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the prompt is written"); + driver.interrupt(None).await.expect("cancel sent"); + let outcome = tokio::time::timeout(Duration::from_secs(5), delivery) + .await + .expect("the delivery ends once the child is stopped") + .expect("delivery task"); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Ambiguous { .. }), + "{outcome:?}" + ); + // A reaped child has no id any more: the watcher killed and waited for it. + tokio::time::timeout(Duration::from_secs(5), async { + while driver.child.lock().await.id().is_some() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the child was stopped and reaped"); + driver.shutdown().await.expect("fixture shutdown"); + assert!( + captured.take().is_empty(), + "a requested stop is not a crash" + ); + } + + /// A start cancelled while `initialize` is unanswered (the supervisor drops the driver) kills + /// the child's whole process group, descendants included, and its attribution ends with it. + #[cfg(unix)] + #[tokio::test] + async fn a_cancelled_antigravity_start_kills_the_process_group_and_ends_attribution() { + let temp = TempDir::new().expect("provider fixture directory"); + let descendant = temp.path().join("descendant.pid"); + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(&temp, "antigravity"); + request.binary_path = executable_fixture(&temp, "agy", ANTIGRAVITY_FIXTURE) + .to_string_lossy() + .into_owned(); + request.environment.insert( + "BIBCODE_TEST_DESCENDANT_PID".to_owned(), + descendant.to_str().unwrap().to_owned(), + ); + let driver = Arc::new( + super::AntigravityDriver::spawn( + request, + factory.attachments.clone(), + factory.attribution.clone(), + ) + .await + .expect("the Antigravity fixture spawns"), + ); + let child_pid = driver.child.lock().await.id().expect("child pid"); + let attributed = |pid: u32| { + factory + .attribution + .registered_kinds() + .iter() + .any(|(identity, _, kind)| { + identity.pid == pid && kind.as_deref() == Some("antigravity") + }) + }; + assert!( + attributed(child_pid), + "the chat child is attributed to Antigravity" + ); + let start = tokio::spawn({ + let driver = driver.clone(); + async move { driver.start().await.map(|_| ()) } + }); + let pid = timeout(Duration::from_secs(5), async { + loop { + if let Ok(text) = std::fs::read_to_string(&descendant) + && let Ok(pid) = text.trim().parse::() + { + return pid; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the child started a descendant"); + start.abort(); + let _ = start.await; + drop(driver); + let alive = |pid: u32| { + std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .status() + .is_ok_and(|status| status.success()) + }; + timeout(Duration::from_secs(5), async { + while alive(pid) || alive(child_pid) || attributed(child_pid) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the group is gone and no longer attributed"); + } + + /// A driver dropped after its Tokio runtime is gone still signals its whole process group: + /// the kill is sent from `Drop` itself, not from a task. + #[cfg(unix)] + #[test] + fn an_antigravity_driver_dropped_outside_its_runtime_kills_the_process_group() { + let temp = TempDir::new().expect("provider fixture directory"); + let descendant = temp.path().join("descendant.pid"); + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("test runtime"); + let driver = runtime.block_on(async { + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let mut request = native_launch(&temp, "antigravity"); + request.binary_path = executable_fixture(&temp, "agy", ANTIGRAVITY_FIXTURE) + .to_string_lossy() + .into_owned(); + request.environment.insert( + "BIBCODE_TEST_DESCENDANT_PID".to_owned(), + descendant.to_str().unwrap().to_owned(), + ); + let driver = super::AntigravityDriver::spawn( + request, + factory.attachments.clone(), + factory.attribution.clone(), + ) + .await + .expect("the Antigravity fixture spawns"); + // `initialize` goes unanswered; the fixture starts a descendant instead. + let _ = timeout(Duration::from_millis(500), driver.start()).await; + driver + }); + let pid = std::fs::read_to_string(&descendant) + .expect("the child started a descendant") + .trim() + .parse::() + .expect("descendant pid"); + runtime.shutdown_background(); + drop(driver); + let alive = || { + std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .status() + .is_ok_and(|status| status.success()) + }; + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while alive() { + assert!( + std::time::Instant::now() < deadline, + "the descendant survived" + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + + /// A configuration command waits behind a running delivery, and also behind older commands + /// its finished delivery has not drained yet, so an older mode switch can never land after a + /// newer one. + #[test] + fn a_new_mode_command_waits_behind_older_undrained_commands() { + let running = super::ThreadDeliverySequence { + active_generation: Some(4), + completed_generation: 3, + }; + assert_eq!(super::deferral_generation(Some(&running), false), Some(4)); + let finished = super::ThreadDeliverySequence { + active_generation: None, + completed_generation: 4, + }; + assert_eq!( + super::deferral_generation(Some(&finished), true), + Some(4), + "queued behind the older commands, for the same drain" + ); + assert_eq!(super::deferral_generation(Some(&finished), false), None); + assert_eq!(super::deferral_generation(None, false), None); + } + + /// A scripted `agy` started through a wrapper that sets one fixture switch. + #[cfg(unix)] + fn antigravity_fixture_with(temp: &TempDir, switch: &str, capture: &std::path::Path) -> String { + let fixture = executable_fixture(temp, "agy-fixture", ANTIGRAVITY_FIXTURE); + executable_fixture( + temp, + "agy", + &format!( + "#!/bin/sh\n{switch} BIBCODE_TEST_REQUEST_CAPTURE='{}' exec '{}' \"$@\"\n", + capture.display(), + fixture.display() + ), + ) + .to_string_lossy() + .into_owned() + } + + #[cfg(unix)] + fn antigravity_turn(id: &str) -> OrchestrationCommand { + serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":id, "threadId":"t1", + "message":{"messageId":id,"role":"user","text":"hello","attachments":[]}, + "modelSelection":{"instanceId":"antigravity","model":"auto"}, + "runtimeMode":"full-access", "interactionMode":"default", + "createdAt":"2026-07-16T00:00:00Z", + })) + .unwrap() + } + + #[cfg(unix)] + async fn antigravity_supervisor( + engine: &super::OrchestrationEngine, + temp: &TempDir, + ) -> super::ProviderRuntimeSupervisor { + super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(super::NativeProviderDriverFactory::new( + temp.path().join("attachments"), + )), + super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )), + super::SupervisorOptions::default(), + ) + } + + /// Through the durable delivery path, a sign-in or version refusal is one final outcome with + /// the user's message: one launch, no prompt, nothing to retry. + #[cfg(unix)] + #[tokio::test] + async fn durable_antigravity_refusals_launch_once_and_are_not_retried() { + for (switch, expected) in [ + ("BIBCODE_TEST_SIGNED_OUT=1", "agy acp --login"), + ("BIBCODE_TEST_AGY_VERSION=1.5.3", "1.5.4"), + ] { + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let binary = antigravity_fixture_with(&temp, switch, &capture); + std::fs::write( + temp.path().join("settings.json"), + serde_json::to_vec(&json!({ + "providerInstances": { + "antigravity": { + "driver": "antigravity", "enabled": true, + "config": { "binaryPath": binary } + } + } + })) + .unwrap(), + ) + .unwrap(); + let engine = supervisor_engine().await; + for command in [ + json!({"type":"project.create","commandId":"ag-project","projectId":"ag","title":"Antigravity","workspaceRoot":temp.path(),"createdAt":"2026-07-16T00:00:00Z"}), + json!({"type":"thread.create","commandId":"ag-thread","threadId":"ag","projectId":"ag","title":"Thread","kind":"workspace","modelSelection":{"instanceId":"antigravity","model":"auto"},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-07-16T00:00:00Z"}), + ] { + engine + .dispatch(serde_json::from_value(command).unwrap()) + .await + .unwrap(); + } + let mut command = serde_json::to_value(antigravity_turn("refused")).unwrap(); + command["threadId"] = json!("ag"); + let command: OrchestrationCommand = serde_json::from_value(command).unwrap(); + let mut payload = serde_json::to_value(&command).unwrap(); + super::freeze_delivery_route( + &engine, + &temp.path().to_path_buf(), + &command, + &mut payload, + ) + .await + .expect("freeze the Antigravity route"); + let payload = payload.to_string(); + engine + .repositories() + .database() + .call(move |connection| { + connection.execute( + "INSERT INTO orchestration_command_receipts (command_id, aggregate_kind, aggregate_id, accepted_at, result_sequence, status, error, payload_digest) VALUES ('refused', 'thread', 'ag', '2026-07-16T00:00:00Z', 0, 'accepted', NULL, 'refusal-digest')", + [], + )?; + connection.execute( + "INSERT INTO provider_turn_outbox (command_id, thread_id, message_id, provider_instance_id, provider_kind, provider_session_id, delivery_key, payload_json, state, attempts, last_error, created_at, updated_at) VALUES ('refused', 'ag', 'refused', 'antigravity', 'antigravity', NULL, 'refused-key', ?, 'sending', 1, NULL, '2026-07-16T00:00:00Z', '2026-07-16T00:00:00Z')", + [payload], + )?; + Ok(()) + }) + .await + .expect("seed the delivery row"); + let supervisor = antigravity_supervisor(&engine, &temp).await; + let outcome = timeout( + Duration::from_secs(20), + super::deliver_durable_orchestration_turn( + &supervisor, + &engine, + &temp.path().to_path_buf(), + command, + "refused-key".to_owned(), + ), + ) + .await + .expect("delivery ends in time"); + let detail = match &outcome { + super::ProviderDeliveryOutcome::Rejected { detail } => detail.clone(), + other => panic!("{switch}: a final refusal, not {other:?}"), + }; + assert!(detail.contains(expected), "{detail}"); + let methods = captured_methods(&capture); + assert_eq!( + methods + .iter() + .filter(|method| *method == "initialize") + .count(), + 1, + "{switch}: one launch, {methods:?}" + ); + assert!( + !methods.contains(&"session/prompt".to_owned()), + "{methods:?}" + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + } + + /// After a crash the next turn starts a new process with the saved cursor: it reopens the + /// saved conversation with `session/resume`, never a new one, and sends the turn once. + #[cfg(unix)] + #[tokio::test] + async fn after_a_crash_the_next_antigravity_turn_reopens_the_saved_session() { + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let engine = supervisor_engine().await; + let supervisor = antigravity_supervisor(&engine, &temp).await; + let mut launch = native_launch(&temp, "antigravity"); + launch.thread_id = "t1".to_owned(); + launch.runtime_mode = "full-access".to_owned(); + launch.binary_path = antigravity_fixture_with(&temp, "", &capture); + launch.resume_cursor = Some(json!({ "schemaVersion": 1, "sessionId": "saved-session" })); + timeout(Duration::from_secs(10), supervisor.launch(launch)) + .await + .expect("launch in time") + .expect("reopened"); + let delivery = timeout( + Duration::from_secs(5), + supervisor.deliver_turn(antigravity_turn("next"), "next-key".to_owned()), + ) + .await + .expect("admitted in time") + .expect("admitted"); + let outcome = timeout(Duration::from_secs(10), delivery.completion()) + .await + .expect("delivered in time"); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + let requests = std::fs::read_to_string(&capture).unwrap_or_default(); + let methods = captured_methods(&capture); + assert!(!methods.contains(&"session/new".to_owned()), "{methods:?}"); + assert!( + requests + .lines() + .any(|line| line.contains("session/resume") && line.contains("saved-session")), + "{requests}" + ); + assert_eq!( + methods + .iter() + .filter(|method| *method == "session/prompt") + .count(), + 1 + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + + /// A turn asking for full access plus Plan in an approval-required Chat session: when the + /// CLI never answers the first `auto` write (retryable), the retry writes both modes again, + /// so Plan is acknowledged before the prompt; a refusal of either mode is final and sends no + /// prompt. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_retry_confirms_every_unconfirmed_mode_before_the_prompt() { + async fn deliver( + supervisor: &super::ProviderRuntimeSupervisor, + ) -> super::ProviderDeliveryOutcome { + let mut command = serde_json::to_value(antigravity_turn("plan")).unwrap(); + command["interactionMode"] = json!("plan"); + let command: OrchestrationCommand = serde_json::from_value(command).unwrap(); + // The previous delivery's completion can arrive before the supervisor retires it. + let delivery = timeout(Duration::from_secs(5), async { + loop { + match supervisor + .deliver_turn(command.clone(), "plan-key".to_owned()) + .await + { + Ok(delivery) => return delivery, + Err(_) => tokio::time::sleep(Duration::from_millis(20)).await, + } + } + }) + .await + .expect("admitted in time"); + timeout(Duration::from_secs(30), delivery.completion()) + .await + .expect("delivered in time") + } + fn writes(capture: &std::path::Path) -> Vec { + std::fs::read_to_string(capture) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter_map(|message| match message["method"].as_str() { + Some("session/set_config_option") => { + message["params"]["value"].as_str().map(str::to_owned) + } + Some("session/prompt") => Some("prompt".to_owned()), + _ => None, + }) + .collect() + } + async fn session( + engine: &super::OrchestrationEngine, + temp: &TempDir, + switch: &str, + capture: &std::path::Path, + ) -> super::ProviderRuntimeSupervisor { + let supervisor = antigravity_supervisor(engine, temp).await; + let mut launch = native_launch(temp, "antigravity"); + launch.thread_id = "t1".to_owned(); + launch.binary_path = antigravity_fixture_with(temp, switch, capture); + timeout(Duration::from_secs(10), supervisor.launch(launch)) + .await + .expect("launch in time") + .expect("started in approval-required Chat"); + supervisor + } + + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let withheld = temp.path().join("withheld"); + let engine = supervisor_engine().await; + let supervisor = session( + &engine, + &temp, + &format!("BIBCODE_TEST_WITHHOLD_FIRST_AUTO='{}'", withheld.display()), + &capture, + ) + .await; + let outcome = deliver(&supervisor).await; + assert!( + matches!( + outcome, + super::ProviderDeliveryOutcome::DefinitelyNotSent { .. } + ), + "{outcome:?}" + ); + assert!(withheld.exists(), "the first `auto` write was withheld"); + let outcome = deliver(&supervisor).await; + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + assert_eq!( + writes(&capture), + ["default", "auto", "auto", "plan", "prompt"], + "Plan is acknowledged before the prompt" + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + + for refused in ["auto", "plan"] { + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let engine = supervisor_engine().await; + let supervisor = session( + &engine, + &temp, + &format!("BIBCODE_TEST_REFUSE_MODE={refused}"), + &capture, + ) + .await; + let outcome = deliver(&supervisor).await; + // A refusal cannot succeed on retry: it is final, with the reason the user sees. + assert!( + matches!( + &outcome, + super::ProviderDeliveryOutcome::Rejected { detail } + if detail.contains("did not switch to its") + ), + "{refused}: {outcome:?}" + ); + assert!( + !writes(&capture).contains(&"prompt".to_owned()), + "{refused}: {:?}", + writes(&capture) + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + } + + /// ACP answers `session/prompt` only when the turn ends, so the thread must read running + /// from the prompt on: through a pending approval, until the answer ends the turn once. + #[cfg(unix)] + #[tokio::test] + async fn an_antigravity_turn_reads_running_while_its_approval_is_pending() { + #[derive(Clone, Default)] + struct Captured(Arc>>); + impl io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0 + .lock() + .expect("captured log") + .extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let log = Captured::default(); + let _logging = tracing::subscriber::set_default( + tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::INFO) + .with_writer({ + let log = log.clone(); + move || log.clone() + }) + .finish(), + ); + // The turn ends on the prompt answer, once after the approval and once after a Stop. + for stop in [false, true] { + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let engine = supervisor_engine().await; + let supervisor = antigravity_supervisor(&engine, &temp).await; + let mut launch = native_launch(&temp, "antigravity"); + launch.thread_id = "t1".to_owned(); + launch.runtime_mode = "full-access".to_owned(); + launch.binary_path = + antigravity_fixture_with(&temp, "BIBCODE_TEST_APPROVAL_BEFORE_ANSWER=1", &capture); + timeout(Duration::from_secs(10), supervisor.launch(launch)) + .await + .expect("launch in time") + .expect("started"); + let delivery = timeout( + Duration::from_secs(5), + supervisor.deliver_turn(antigravity_turn("approve"), "approve-key".to_owned()), + ) + .await + .expect("admitted in time") + .expect("admitted"); + let repositories = engine.repositories(); + let approval = timeout(Duration::from_secs(10), async { + loop { + let pending = repositories + .list_pending_approvals_by_thread("t1".to_owned()) + .await + .unwrap(); + if let Some(approval) = pending.into_iter().next() { + return approval; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the approval request reached the thread"); + let session = repositories + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .expect("session"); + assert_eq!(session.status, "running", "{session:?}"); + assert!(session.active_turn_id.is_some(), "{session:?}"); + assert_eq!(session.active_turn_id, approval.turn_id); + let thread = repositories + .get_thread("t1".to_owned()) + .await + .unwrap() + .expect("thread"); + assert_eq!(thread.latest_turn_id, session.active_turn_id); + + let command = if stop { + json!({"type":"thread.turn.interrupt","commandId":"stop","threadId":"t1","turnId":approval.turn_id,"createdAt":"2026-07-16T00:00:00Z"}) + } else { + json!({"type":"thread.approval.respond","commandId":"approve-reply","threadId":"t1","requestId":approval.request_id,"decision":"accept","createdAt":"2026-07-16T00:00:00Z"}) + }; + supervisor + .handle_orchestration(serde_json::from_value(command).unwrap()) + .await + .expect("approval answered or turn stopped"); + let outcome = timeout(Duration::from_secs(10), delivery.completion()) + .await + .expect("delivered in time"); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + timeout(Duration::from_secs(10), async { + while repositories + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .is_some_and(|session| session.status == "running") + { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the answer ended the turn"); + // Nothing marks the ended turn running again, and its approval is closed. + tokio::time::sleep(Duration::from_millis(300)).await; + let session = repositories + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .expect("session"); + assert_ne!(session.status, "running", "stop={stop}: {session:?}"); + assert!( + repositories + .list_pending_approvals_by_thread("t1".to_owned()) + .await + .unwrap() + .iter() + .all(|approval| approval.status != "pending"), + "stop={stop}" + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + let text = String::from_utf8(log.0.lock().expect("captured log").clone()).expect("UTF-8"); + assert!( + !text.contains("a turn ended before this delivery was accepted"), + "{text}" + ); + } + + /// Cursor's delivery, too, is accepted only when ACP answers the prompt at the end of the + /// turn, so the thread must read running from the prompt on, until the answer ends it. + #[cfg(unix)] + #[tokio::test] + async fn a_cursor_turn_reads_running_until_its_prompt_is_answered() { + let temp = TempDir::new().expect("provider fixture directory"); + let gate = temp.path().join("answer-gate"); + let engine = supervisor_engine().await; + let supervisor = antigravity_supervisor(&engine, &temp).await; + let mut launch = native_launch(&temp, "cursor"); + launch.thread_id = "t1".to_owned(); + launch.runtime_mode = "full-access".to_owned(); + launch.binary_path = executable_fixture(&temp, "cursor-agent", ACP_FIXTURE) + .to_string_lossy() + .into_owned(); + launch.environment.insert( + "BIBCODE_TEST_ACK_GATE".to_owned(), + gate.to_string_lossy().into_owned(), + ); + timeout(Duration::from_secs(10), supervisor.launch(launch)) + .await + .expect("launch in time") + .expect("started"); + let turn = serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":"hello", "threadId":"t1", + "message":{"messageId":"hello","role":"user","text":"hello","attachments":[]}, + "modelSelection":{"instanceId":"cursor","model":"test-model"}, + "runtimeMode":"full-access", "interactionMode":"default", + "createdAt":"2026-07-16T00:00:00Z", + })) + .unwrap(); + let delivery = timeout( + Duration::from_secs(5), + supervisor.deliver_turn(turn, "hello-key".to_owned()), + ) + .await + .expect("admitted in time") + .expect("admitted"); + let repositories = engine.repositories(); + let session = timeout(Duration::from_secs(10), async { + loop { + if let Some(session) = repositories + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .filter(|session| session.status == "running") + { + return session; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the thread reads running while Cursor holds the prompt answer"); + assert!(session.active_turn_id.is_some(), "{session:?}"); + + std::fs::write(&gate, b"").expect("open the answer gate"); + let outcome = timeout(Duration::from_secs(10), delivery.completion()) + .await + .expect("delivered in time"); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + timeout(Duration::from_secs(10), async { + while repositories + .get_thread_session("t1".to_owned()) + .await + .unwrap() + .is_some_and(|session| session.status == "running") + { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the answer ended the turn"); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + + /// An unsent frozen turn whose saved conversation is gone: the reconciliation launch fails + /// with `FrozenConversationLost`, sends nothing, and keeps the saved cursor, so no + /// replacement conversation silently takes the turn. + #[cfg(unix)] + #[tokio::test] + async fn an_unsent_frozen_antigravity_turn_whose_conversation_is_gone_sends_nothing() { + let temp = TempDir::new().expect("provider fixture directory"); + let capture = temp.path().join("requests.jsonl"); + let engine = supervisor_engine().await; + let supervisor = antigravity_supervisor(&engine, &temp).await; + let mut launch = native_launch(&temp, "antigravity"); + launch.thread_id = "t1".to_owned(); + launch.binary_path = + antigravity_fixture_with(&temp, "BIBCODE_TEST_MISSING_SESSION=1", &capture); + launch.resume_cursor = Some(json!({ "schemaVersion": 1, "sessionId": "saved-session" })); + let error = timeout( + Duration::from_secs(10), + supervisor.launch_for_reconciliation(launch, None), + ) + .await + .expect("launch in time") + .expect_err("the conversation is gone"); + assert!( + matches!( + error, + super::ProviderRuntimeError::FrozenConversationLost { .. } + ), + "{error:?}" + ); + assert!(!captured_methods(&capture).contains(&"session/prompt".to_owned())); + let runtime = engine + .repositories() + .get_provider_session_runtime("t1".to_owned()) + .await + .unwrap() + .expect("runtime row"); + assert_eq!( + runtime + .resume_cursor + .as_ref() + .and_then(super::resume_string), + Some("saved-session".to_owned()), + "the saved cursor stays with the lost conversation" + ); + timeout(Duration::from_secs(10), supervisor.shutdown()) + .await + .expect("shutdown in time") + .expect("shutdown"); + engine.shutdown().await; + } + + #[test] + fn antigravity_refusals_before_the_prompt_are_final_and_carry_no_provider_text() { + use crate::provider::antigravity::{ + AntigravityRuntimeError as Error, acp::AcpProtocolError, + }; + const MARKER: &str = "SYNTHETIC-PROVIDER-TEXT-91c2"; + let remote = || { + Error::Protocol(AcpProtocolError::RemoteRequest { + method: "session/set_config_option".to_owned(), + request_id: "4".to_owned(), + code: -32603, + message: MARKER.to_owned(), + data: Some(json!({ "text": MARKER })), + }) + }; + for (error, rejected) in [ + (Error::SignInRequired, true), + ( + Error::ModeUnavailable { + mode: "default".to_owned(), + }, + true, + ), + ( + Error::Protocol(AcpProtocolError::LineTooLong { + stream: "stdout", + maximum: 128 * 1024, + }), + true, + ), + (Error::ControlTimedOut, false), + (remote(), false), + ] { + let outcome = super::antigravity_unsent_outcome(error); + let (actual, detail) = match outcome { + super::ProviderDeliveryOutcome::Rejected { detail } => (true, detail), + super::ProviderDeliveryOutcome::DefinitelyNotSent { detail } => (false, detail), + other => panic!("unexpected outcome {other:?}"), + }; + assert_eq!(actual, rejected, "{detail}"); + assert!(!detail.contains(MARKER), "{detail}"); + } + let launch = super::antigravity_error(remote()); + assert!(!launch.to_string().contains(MARKER), "{launch}"); + assert!( + launch.to_string().contains("session/set_config_option") + && launch.to_string().contains("-32603"), + "{launch}" + ); + } + + #[test] + fn antigravity_dispatch_tables_name_it_and_never_fall_back_to_codex() { + assert_eq!(super::native_adapter_key("antigravity"), "antigravity-acp"); + let providers = ProvidersState::default(); + let resolved = super::provider_binary_settings(&providers, "antigravity", None); + assert_eq!(resolved.binary_path, "agy"); + assert!(!resolved.enabled, "disabled by default, unlike Codex"); + let detail = crate::provider::cursor::acp::AcpProtocolError::LineTooLong { + stream: "stdout", + maximum: 128 * 1024, + }; + assert!(matches!( + super::provider_error("antigravity")(detail), + super::ProviderRuntimeError::TransportLineTooLong { .. } + )); + } + + #[tokio::test] + async fn antigravity_option_logging_records_no_model_or_option_value() { + use crate::production::operational_logs::{OperationalLogOptions, ProviderOperationalLog}; + + let temp = TempDir::new().expect("provider option log directory"); + let path = temp.path().join("provider-options.log"); + let log = ProviderOperationalLog::start( + path.clone(), + OperationalLogOptions { + max_file_bytes: 4096, + retained_files: 1, + queue_capacity: 4, + }, + ) + .await + .expect("provider option log starts"); + let mut request = native_launch(&temp, "antigravity"); + request.model = Some("SYNTHETIC-MODEL-MARKER".to_owned()); + + super::record_option_reconciliation( + Some(&log), + &request, + &[json!({ "id": "reasoning", "value": "SYNTHETIC-VALUE-MARKER" })], + "live", + "applied", + ); + log.shutdown() + .await + .expect("provider option log shuts down"); + + let contents = std::fs::read_to_string(path).expect("read provider option log"); + assert!(!contents.contains("SYNTHETIC-MODEL-MARKER"), "{contents}"); + assert!(!contents.contains("SYNTHETIC-VALUE-MARKER"), "{contents}"); + let record: Value = serde_json::from_str(contents.trim()).expect("provider option record"); + assert_eq!(record["optionId"], "reasoning"); + } } #[cfg(test)] diff --git a/apps/server/src/production/restore_guard_supervisor_tests.rs b/apps/server/src/production/restore_guard_supervisor_tests.rs index 063d9cc630..ec3b663b49 100644 --- a/apps/server/src/production/restore_guard_supervisor_tests.rs +++ b/apps/server/src/production/restore_guard_supervisor_tests.rs @@ -173,6 +173,7 @@ async fn an_idle_sibling_session_is_suspended_and_no_path_reopens_it_during_the_ fixture.launch("t1", "claude", None), context_handoff, None, + None, false, ) .await diff --git a/apps/server/src/production/runtime.rs b/apps/server/src/production/runtime.rs index a60a3b3d60..c2bb29b5e9 100644 --- a/apps/server/src/production/runtime.rs +++ b/apps/server/src/production/runtime.rs @@ -143,6 +143,7 @@ pub struct ProductionRuntime { device_manager: crate::device::DeviceManager, /// Diff apps opened through `git difftool`, which outlive BiBCode. diff_tool_launcher: crate::production::diff_tool::DiffToolLauncher, + provider_usage: ProviderUsageService, preview_tunnels: PreviewTunnels, asset_access: AssetAccess, transfer_access: TransferAccess, @@ -332,10 +333,12 @@ impl ProductionRuntime { ) .await, ); - let provider_update_checks = control.start_provider_update_checks(); // Built before the profiler, whose sampler reads it; it has no dependencies. + // Attached before the first provider refresh is scheduled, so that refresh's probe + // children are attributed too. let process_attribution = ProcessAttributionRegistry::new(); control.attach_process_attribution(process_attribution.clone()); + let provider_update_checks = control.start_provider_update_checks(); let device_env = crate::device::android::sdk::SdkEnv::from_process(); let android_devices = crate::device::android::AndroidBackend::new( crate::device::android::AndroidBackendConfig { @@ -479,7 +482,9 @@ impl ProductionRuntime { .with_relay_hosts(relay_hosts.clone()); let provider_settings = ProviderSettingsStore::new(&state_paths.state_dir); let provider_terminal_preparer = ProviderTerminalActivitySupervisor::new_with_authority( - Arc::new(ProviderSettingsInventoryAuthority::new(provider_settings)), + Arc::new(ProviderSettingsInventoryAuthority::new( + provider_settings.clone(), + )), terminal_activity_controller.clone(), activity_projections.terminal(), process_attribution.clone(), @@ -686,8 +691,10 @@ impl ProductionRuntime { started_at_ms: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, }, )); - let provider_usage = - ProviderUsageService::new(production_fetchers(), Arc::new(OffsetDateTime::now_utc)); + let provider_usage = ProviderUsageService::new( + production_fetchers(provider_settings.clone(), Some(process_attribution.clone())), + Arc::new(OffsetDateTime::now_utc), + ); let relay = relay_client_service(config.state_dir()); let agent_activity = Arc::new(ProductionAgentActivity::new( activity_projections.clone(), @@ -712,7 +719,7 @@ impl ProductionRuntime { process_sampler, resource_sampler.clone(), process_monitor.clone(), - provider_usage, + provider_usage.clone(), relay, control.clone(), process_tree_cleanup, @@ -971,6 +978,7 @@ impl ProductionRuntime { preview_gateway, device_manager, diff_tool_launcher, + provider_usage, preview_tunnels, asset_access, transfer_access, @@ -1207,6 +1215,10 @@ impl ProductionRuntime { steps.mark("diff-tool-launcher"); self.preview_tunnels.shutdown(); steps.mark("preview-tunnels"); + // Before ownership is frozen: a running Antigravity usage read is stopped and its CLI + // reaped, and no read starts after this point. + self.provider_usage.shutdown().await; + steps.mark("provider-usage"); let process_ownership = self.terminal_services.freeze_process_ownership().await; steps.mark("freeze-process-ownership"); self.managed_endpoint.shutdown().await; diff --git a/apps/server/src/production/server_terminal.rs b/apps/server/src/production/server_terminal.rs index 5ee0e447bc..4a616461b0 100644 --- a/apps/server/src/production/server_terminal.rs +++ b/apps/server/src/production/server_terminal.rs @@ -31,7 +31,7 @@ use crate::{ provider_usage::{ CodexRateLimitResetOutcome, ConsumeCodexRateLimitResetResult, ProviderUsageCommandError, ProviderUsageProvider, ProviderUsageResult, ProviderUsageService, ProviderUsageSnapshot, - ProviderUsageStatus, ProviderUsageWindow, RateLimitResetCredits, + ProviderUsageStatus, ProviderUsageWindow, ProviderUsageWindowGroup, RateLimitResetCredits, }, rpc::{RpcRegistry, RpcResult, RpcStreamChunk}, terminal::{ @@ -760,9 +760,15 @@ fn register_diagnostics_rpcs(registry: &mut RpcRegistry, services: &ServerTermin fn register_provider_usage_rpcs(registry: &mut RpcRegistry, services: &ServerTerminalServices) { let usage = services.provider_usage.clone(); - registry.register_unary("server.getProviderUsage", move |_request, _cancellation| { + registry.register_unary("server.getProviderUsage", move |request, _cancellation| { let usage = usage.clone(); - async move { Ok(provider_usage_to_wire(usage.read().await)) } + async move { + let input: ReadProviderUsageInput = decode_payload(&request.payload)?; + let providers = parse_usage_providers(input.providers)?; + Ok(provider_usage_to_wire( + usage.read_selected(providers.as_deref()).await, + )) + } }); let usage = services.provider_usage.clone(); @@ -772,19 +778,7 @@ fn register_provider_usage_rpcs(registry: &mut RpcRegistry, services: &ServerTer let usage = usage.clone(); async move { let input: RefreshProviderUsageInput = decode_payload(&request.payload)?; - let providers = input - .providers - .map(|providers| { - providers - .into_iter() - .map(|provider| match provider.as_str() { - "claude" => Ok(ProviderUsageProvider::Claude), - "codex" => Ok(ProviderUsageProvider::Codex), - _ => Err(invalid_request("provider must be claude or codex")), - }) - .collect::, Value>>() - }) - .transpose()?; + let providers = parse_usage_providers(input.providers)?; let refreshed = if input.force { usage.refresh_forced(providers).await } else { @@ -1795,6 +1789,32 @@ struct SignalProcessInput { process_key: String, signal: String, } +#[derive(Deserialize)] +struct ReadProviderUsageInput { + providers: Option>, +} + +/// Antigravity is accepted and answered only when a request names it. +fn parse_usage_providers( + providers: Option>, +) -> Result>, Value> { + providers + .map(|providers| { + providers + .into_iter() + .map(|provider| match provider.as_str() { + "claude" => Ok(ProviderUsageProvider::Claude), + "codex" => Ok(ProviderUsageProvider::Codex), + "antigravity" => Ok(ProviderUsageProvider::Antigravity), + _ => Err(invalid_request( + "provider must be claude, codex or antigravity", + )), + }) + .collect::, Value>>() + }) + .transpose() +} + #[derive(Deserialize)] struct RefreshProviderUsageInput { providers: Option>, @@ -1846,7 +1866,11 @@ fn provider_usage_to_wire(result: ProviderUsageResult) -> Value { fn provider_usage_snapshot_to_wire(snapshot: ProviderUsageSnapshot) -> Value { json!({ - "provider": match snapshot.provider { ProviderUsageProvider::Claude => "claude", ProviderUsageProvider::Codex => "codex" }, + "provider": match snapshot.provider { + ProviderUsageProvider::Claude => "claude", + ProviderUsageProvider::Codex => "codex", + ProviderUsageProvider::Antigravity => "antigravity", + }, "status": match snapshot.status { ProviderUsageStatus::Idle => "idle", ProviderUsageStatus::Fetching => "fetching", ProviderUsageStatus::Ok => "ok", ProviderUsageStatus::Error => "error", @@ -1855,6 +1879,7 @@ fn provider_usage_snapshot_to_wire(snapshot: ProviderUsageSnapshot) -> Value { "session": snapshot.session.map(provider_usage_window_to_wire), "weekly": snapshot.weekly.map(provider_usage_window_to_wire), "fableWeekly": snapshot.fable_weekly.map(provider_usage_window_to_wire), + "windowGroups": snapshot.window_groups.into_iter().map(provider_usage_group_to_wire).collect::>(), "planType": snapshot.plan_type, "rateLimitResetCredits": snapshot.rate_limit_reset_credits.map(rate_limit_reset_credits_to_wire), "updatedAt": format_time(snapshot.updated_at), @@ -1890,6 +1915,15 @@ fn provider_usage_reset_error_to_wire(error: ProviderUsageCommandError) -> Value }) } +fn provider_usage_group_to_wire(group: ProviderUsageWindowGroup) -> Value { + json!({ + "id": group.id, + "label": group.label, + "session": group.session.map(provider_usage_window_to_wire), + "weekly": group.weekly.map(provider_usage_window_to_wire), + }) +} + fn provider_usage_window_to_wire(window: ProviderUsageWindow) -> Value { json!({ "usedPercent": window.used_percent, @@ -3158,6 +3192,36 @@ mod tests { assert_eq!(format_epoch_ms(i128::MAX), "1970-01-01T00:00:00Z"); } + #[test] + fn usage_provider_lists_name_antigravity_only_when_asked() { + assert_eq!(parse_usage_providers(None).unwrap(), None); + assert_eq!( + parse_usage_providers(Some(vec!["antigravity".to_owned()])).unwrap(), + Some(vec![ProviderUsageProvider::Antigravity]) + ); + assert!(parse_usage_providers(Some(vec!["mystery".to_owned()])).is_err()); + let wire = provider_usage_snapshot_to_wire(ProviderUsageSnapshot { + provider: ProviderUsageProvider::Antigravity, + status: ProviderUsageStatus::Ok, + session: None, + weekly: None, + fable_weekly: None, + window_groups: vec![ProviderUsageWindowGroup { + id: "gemini", + label: "Gemini models", + session: None, + weekly: None, + }], + plan_type: None, + rate_limit_reset_credits: None, + updated_at: OffsetDateTime::UNIX_EPOCH, + error: None, + metadata: BTreeMap::new(), + }); + assert_eq!(wire["provider"], "antigravity"); + assert_eq!(wire["windowGroups"][0]["id"], "gemini"); + } + #[test] fn terminal_resize_claim_decoding_accepts_legacy_and_bounds_new_claims() { assert!(validate_terminal_size_claim(None).unwrap().is_none()); @@ -3724,6 +3788,7 @@ mod tests { }), weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -3736,6 +3801,7 @@ mod tests { session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -3892,6 +3958,7 @@ mod tests { session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -3909,6 +3976,7 @@ mod tests { resets_at: None, reset_description: None, }), + window_groups: Vec::new(), plan_type: Some("pro".to_owned()), rate_limit_reset_credits: Some(RateLimitResetCredits { available_count: 2, diff --git a/apps/server/src/production/shared_checkout_restore_tests.rs b/apps/server/src/production/shared_checkout_restore_tests.rs index 2f5c8ff30d..0d2d533bc4 100644 --- a/apps/server/src/production/shared_checkout_restore_tests.rs +++ b/apps/server/src/production/shared_checkout_restore_tests.rs @@ -959,7 +959,7 @@ async fn a_sibling_that_starts_writing_after_planning_is_caught_before_the_rewin #[tokio::test] async fn a_launch_in_flight_makes_the_restore_refuse() { let fixture = Fixture::new().await; - let launch = fixture.engine.begin_session_launch("b").unwrap(); + let launch = fixture.engine.begin_session_launch("b", None).unwrap(); let failure = fixture.revert("a", 1, "full", None).await.unwrap_err(); assert!( detail(&failure).contains("is starting its session"), @@ -970,13 +970,17 @@ async fn a_launch_in_flight_makes_the_restore_refuse() { let gate = fixture.provider.pause_at(Stage::Prepare); let outcome = fixture.request_revert("a", 1, "full", None).await; entered(&gate).await; - let refused = fixture.engine.begin_session_launch("b").err().unwrap(); + let refused = fixture + .engine + .begin_session_launch("b", None) + .err() + .unwrap(); assert!(refused.contains("restoring files"), "{refused}"); // The restoring thread's own reopen is not held. - assert!(fixture.engine.begin_session_launch("a").is_ok()); + assert!(fixture.engine.begin_session_launch("a", None).is_ok()); gate.release.notify_one(); outcome.await.unwrap().unwrap(); - assert!(fixture.engine.begin_session_launch("b").is_ok()); + assert!(fixture.engine.begin_session_launch("b", None).is_ok()); fixture.shutdown().await; } diff --git a/apps/server/src/production/thread_compaction_tests.rs b/apps/server/src/production/thread_compaction_tests.rs index 0e0662743f..3ce09d9e2c 100644 --- a/apps/server/src/production/thread_compaction_tests.rs +++ b/apps/server/src/production/thread_compaction_tests.rs @@ -629,6 +629,53 @@ async fn stop_during_the_compaction_wins_even_if_it_completes() { engine.shutdown().await; } +#[tokio::test] +async fn a_late_stop_for_a_finished_turn_does_not_stop_the_compaction() { + // Mutation caught: a delayed Stop naming the failed turn marking the compaction running + // under its own turn stop-requested, so its success settles as interrupted. + let engine = engine().await; + delivered_turn(&engine, "failed", "turn-1", near_full()).await; + fail_at_limit(&engine, "failure", "turn-1", before_output()).await; + let recovery = only_compaction(&engine).await; + engine + .start_thread_compaction(&recovery.compaction_id, TIME) + .await + .unwrap(); + session( + &engine, + "running", + "compaction-running", + Some("compaction-turn"), + ) + .await; + let stop = |id: &str, turn: &str| { + command( + json!({"type":"thread.turn.interrupt", "commandId":id, "threadId":"t", "turnId":turn, "createdAt":TIME}), + ) + }; + engine.dispatch(stop("late-stop", "turn-1")).await.unwrap(); + let running = engine + .thread_compaction(&recovery.compaction_id) + .await + .unwrap() + .unwrap(); + assert_eq!(running.state, "running"); + assert!(!running.stop_requested); + engine + .dispatch(stop("stop", "compaction-turn")) + .await + .unwrap(); + assert!( + engine + .thread_compaction(&recovery.compaction_id) + .await + .unwrap() + .unwrap() + .stop_requested + ); + engine.shutdown().await; +} + #[tokio::test] async fn an_unsettled_compaction_holds_claims_and_promotion() { let engine = engine().await; diff --git a/apps/server/src/production/turn_delivery.rs b/apps/server/src/production/turn_delivery.rs index 4649b93df9..18254aaeeb 100644 --- a/apps/server/src/production/turn_delivery.rs +++ b/apps/server/src/production/turn_delivery.rs @@ -2035,6 +2035,13 @@ fn provider_delivery_outcome( Some(TurnDeliveryFailureReason::FoundWithoutTurn), DeliveryTaskOutcome::Finished, ), + // Settled, never sent again, and no turn of it runs: its pending marker goes. + ProviderDeliveryOutcome::StoppedUnsent => ( + TurnDeliveryState::Delivered, + None, + Some(TurnDeliveryFailureReason::FoundWithoutTurn), + DeliveryTaskOutcome::Finished, + ), ProviderDeliveryOutcome::NotSentRetryAfter { detail, retry_after, diff --git a/apps/server/src/production/turn_delivery_queue_tests.rs b/apps/server/src/production/turn_delivery_queue_tests.rs index b619d70008..a064f183bd 100644 --- a/apps/server/src/production/turn_delivery_queue_tests.rs +++ b/apps/server/src/production/turn_delivery_queue_tests.rs @@ -406,6 +406,20 @@ async fn interrupt_holds_queued_rows_until_client_promotes_only_the_head() { engine.shutdown().await; } +#[tokio::test] +async fn a_late_interrupt_for_a_finished_turn_leaves_the_queue_unheld() { + // Mutation caught: a delayed Stop naming an earlier turn holding the follow-ups of the turn + // running now, which that Stop does not end. + let engine = engine().await; + session(&engine, "running", "running").await; + enqueue(&engine, "queued-1", true).await; + engine.dispatch(command(json!({"type":"thread.turn.interrupt", "commandId":"late-stop", "threadId":"t", "turnId":"finished", "createdAt":TIME}))).await.unwrap(); + assert!(!row(&engine, "queued-1").await.held); + engine.dispatch(command(json!({"type":"thread.turn.interrupt", "commandId":"stop", "threadId":"t", "turnId":"running", "createdAt":TIME}))).await.unwrap(); + assert!(row(&engine, "queued-1").await.held); + engine.shutdown().await; +} + #[tokio::test] async fn dismissing_a_failed_head_allows_the_next_queued_turn() { let engine = engine().await; diff --git a/apps/server/src/provider/antigravity/mod.rs b/apps/server/src/provider/antigravity/mod.rs new file mode 100644 index 0000000000..91a532eab2 --- /dev/null +++ b/apps/server/src/provider/antigravity/mod.rs @@ -0,0 +1,14 @@ +//! Antigravity chat over `agy acp`: ACP v1 on stdio, through the transport Cursor and Grok share. + +pub use crate::provider::cursor::acp; + +pub mod runtime; + +#[cfg_attr(test, allow(unused_imports))] +pub use acp::{AcpConnectionConfig, AcpJsonRpcConnection, IncomingEvent}; +#[cfg_attr(test, allow(unused_imports))] +pub use runtime::{ + AntigravityPromptReceipt, AntigravityRuntimeError, AntigravityRuntimeEvent, + AntigravitySessionOptions, AntigravitySessionRuntime, DEFAULT_CANCEL_GRACE, + DEFAULT_CONTROL_TIMEOUT, START_NOTICE_DELAY, +}; diff --git a/apps/server/src/provider/antigravity/runtime.rs b/apps/server/src/provider/antigravity/runtime.rs new file mode 100644 index 0000000000..8f9e5e4b3e --- /dev/null +++ b/apps/server/src/provider/antigravity/runtime.rs @@ -0,0 +1,1511 @@ +//! One Antigravity chat session over `agy acp` (ACP v1). See +//! `docs/plans/2026-11-20-antigravity-terminal-design.md`, decisions D-A4 to D-A11. +//! +//! Logs carry method names, error codes and classes only: provider text, option values and +//! `_meta` (which names the account's plan) never reach `tracing`. +//! +//! Known limit: the shared transport closes the connection on a stdout line over 128 KiB +//! (`AcpConnectionConfig::max_stdout_line_bytes`). `agy` repeats a written file's content in the +//! non-standard `args` of every `tool_call` and `tool_call_update`, so writing a large file can +//! end the session with a line-too-long error. + +use std::{ + collections::{HashMap, HashSet}, + future::Future, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; + +use serde_json::{Value, json}; +use thiserror::Error; +use tokio::sync::{Mutex, Notify, mpsc, oneshot}; +use uuid::Uuid; + +use super::acp::{ + AcpJsonRpcConnection, AcpProtocolError, IncomingEvent, JsonRpcErrorShape, acp_error_class, + acp_turn_state, +}; +use crate::provider::{ + OptionRefusal, RefusedOption, model_unavailable_refusal, option_needs_value_refusal, + option_without_id_refusal, unsupported_option_refusal, +}; + +const PROVIDER: &str = "antigravity"; +const PROTOCOL_VERSION: u64 = 1; +const MINIMUM_VERSION: (u64, u64, u64) = (1, 5, 4); +/// The BiBCode option id of the thinking level, the id the ACP option parser publishes for the +/// `thought_level` category (`provider/cursor/model.rs`). +const REASONING_OPTION_ID: &str = "reasoning"; +const THINKING_LEVEL_LABEL: &str = "Thinking level"; + +/// How long a cancelled turn may run before the runtime gives up on the process (D-A10). +pub const DEFAULT_CANCEL_GRACE: Duration = Duration::from_secs(10); + +/// How long the handshake and session open may take before the chat shows that Antigravity is +/// slow to start. A live open answered in a few seconds. The start keeps waiting. +pub const START_NOTICE_DELAY: Duration = Duration::from_secs(60); + +/// How long a configuration write on a running session may take. The CLI answers them at once +/// (measured); the bound keeps a wedged CLI from holding the shared provider supervisor. +pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Clone, Debug)] +pub struct AntigravitySessionOptions { + pub thread_id: String, + pub cwd: String, + pub runtime_mode: String, + pub interaction_mode: String, + pub model: Option, + pub resume_session_id: Option, + pub cancel_grace: Duration, + /// Bounds each configuration request (model, thinking level, mode). + pub control_timeout: Duration, + /// The thread's options (the thinking level), written during the start. + pub initial_options: Vec, +} + +#[derive(Clone, Debug)] +pub struct AntigravityRuntimeEvent { + pub event_type: String, + pub thread_id: String, + pub turn_id: Option, + pub request_id: Option, + pub payload: Value, +} + +#[derive(Debug, Error)] +pub enum AntigravityRuntimeError { + #[error(transparent)] + Protocol(#[from] AcpProtocolError), + /// The CLI answered `-32000` "Authentication required". The user signs in; BiBCode never does. + #[error( + "Antigravity is not signed in. Open an Antigravity Terminal and run `agy`, or run `agy acp --login`, then send the message again." + )] + SignInRequired, + /// Google disabled Antigravity for the signed-in account. Sending again cannot help, so the + /// message fails once. Google's own notice follows the sentence, in the turn's error and the + /// delivery's details alike. + #[error( + "Google has disabled Antigravity for this account. Appeal through Google to restore access. Google's message: {google_message}" + )] + AccountDisabled { google_message: String }, + /// The CLI is older than 1.5.4, speaks another ACP version, or has no working `agy acp`. + #[error("{}", unsupported_version_message(.version.as_deref()))] + UnsupportedVersion { version: Option }, + /// The session did not acknowledge the mode the thread's permission setting needs. + #[error( + "Antigravity did not switch to its `{mode}` mode, so BiBCode stopped the chat to keep your permission setting. Run `agy update`, then try again." + )] + ModeUnavailable { mode: String }, + /// A configuration request went unanswered; the CLI's mode is unknown until rewritten. + #[error( + "Antigravity did not answer a settings change in time. Send the message again; if it keeps happening, stop the chat and start it again." + )] + ControlTimedOut, + /// A resume or load answer named another conversation than the one asked for. + #[error( + "Antigravity reopened a different conversation than this chat's, so BiBCode stopped. Send the message again." + )] + SessionMismatch, + #[error("Antigravity runtime has not started a provider session")] + MissingProviderSessionId, + #[error("Unknown pending request id {request_id}")] + PendingRequestNotFound { request_id: String }, + #[error("Antigravity option update is unsupported: {0}")] + UnsupportedOption(RefusedOption), + #[error("Antigravity config update acknowledgement omitted configOptions")] + MalformedConfigAcknowledgement, +} + +impl AntigravityRuntimeError { + /// The class a log line may carry instead of the error's text. + #[must_use] + pub fn class(&self) -> &'static str { + match self { + Self::Protocol(error) => acp_error_class(error), + Self::SignInRequired => "sign_in_required", + Self::AccountDisabled { .. } => "account_disabled", + Self::UnsupportedVersion { .. } => "unsupported_version", + Self::ModeUnavailable { .. } => "mode_unavailable", + Self::ControlTimedOut => "control_timeout", + Self::SessionMismatch => "session_mismatch", + Self::UnsupportedOption(_) => "unsupported_option", + Self::MissingProviderSessionId + | Self::PendingRequestNotFound { .. } + | Self::MalformedConfigAcknowledgement => "runtime_error", + } + } +} + +impl OptionRefusal for AntigravityRuntimeError { + fn refused_option(&self) -> Option<&RefusedOption> { + match self { + Self::UnsupportedOption(refused) => Some(refused), + _ => None, + } + } +} + +fn unsupported_version_message(version: Option<&str>) -> String { + match version { + Some(version) => format!( + "Antigravity chat needs CLI 1.5.4 or later; this one is {version}. Run `agy update`, then try again. The Antigravity Terminal still works." + ), + None => "Antigravity chat needs CLI 1.5.4 or later with a working `agy acp` that speaks ACP protocol 1. Run `agy update`, then try again. The Antigravity Terminal still works.".to_owned(), + } +} + +#[derive(Debug)] +pub struct AntigravityPromptReceipt { + pub turn_id: String, + completion: oneshot::Receiver>, +} + +impl AntigravityPromptReceipt { + /// Resolves when the CLI answers the prompt, that is when the turn ends. + pub async fn completion(self) -> Result<(), AntigravityRuntimeError> { + self.completion.await.unwrap_or_else(|_| { + Err(AcpProtocolError::Closed { + reason: "Antigravity prompt receipt task ended without an outcome".to_owned(), + } + .into()) + }) + } +} + +#[derive(Clone)] +pub struct AntigravitySessionRuntime { + inner: Arc, +} + +struct RuntimeInner { + options: AntigravitySessionOptions, + connection: AcpJsonRpcConnection, + /// Everything a permission decision reads. A decision and its reply are made under this + /// lock, and cancel and mode changes take it too, so none can slip between them. It is never + /// held across a request to the CLI or a barrier. + gate: Mutex, + /// Held by each mode confirmation from reading its target to settling its answer, so mode + /// writes reach the CLI one at a time and each writes the latest target. + mode_writes: Mutex<()>, + config_options: Mutex>, + legacy_models: AtomicBool, + /// The start failed because the connection to the child broke, not on a refusal. + start_lost_connection: AtomicBool, + /// Google's message, when the CLI wrote on its error output that the account is disabled. + account_disabled: std::sync::Mutex>, + abandoned_turns: Mutex>, + events_tx: mpsc::UnboundedSender, + events_rx: Mutex>, + abandon: Notify, +} + +struct Gate { + /// `None` until the open call and every update queued before its answer are handled, so a + /// replayed history is dropped and no request during the open is answered. + session_id: Option, + active_turn: Option, + cancelled_turn: Option, + runtime_mode: String, + interaction_mode: String, + /// The CLI's mode may differ from the one the thread needs: the next prompt writes it first. + /// True until the first acknowledgement, so a failed start leaves no confirmed mode. + mode_unconfirmed: bool, + /// Bumped by every mode change: a mode write's answer counts only for the generation that + /// sent it, so an older answer never confirms a newer setting. + mode_generation: u64, + pending: HashMap, +} + +impl Gate { + fn mode_target(&self) -> &'static str { + mode_for(&self.runtime_mode, &self.interaction_mode) + } + + /// Also a new generation: a confirmation in flight can no longer clear it. + fn unconfirm(&mut self) { + self.mode_unconfirmed = true; + self.mode_generation += 1; + } + + /// The approvals of a turn that ended or was cancelled; they can never answer a later one. + fn take_pending(&mut self, turn_id: &str) -> Vec<(String, PendingRequest)> { + let ids = self + .pending + .iter() + .filter(|(_, pending)| pending.turn_id == turn_id) + .map(|(id, _)| id.clone()) + .collect::>(); + ids.into_iter() + .filter_map(|id| self.pending.remove(&id).map(|pending| (id, pending))) + .collect() + } +} + +struct PendingRequest { + /// The id exactly as the CLI sent it: numeric 1 and string "1" are different requests. + wire_id: Value, + turn_id: String, + request_type: &'static str, + allow_once: Option, + allow_always: Option, + reject_once: Option, +} + +impl AntigravitySessionRuntime { + pub fn new( + options: AntigravitySessionOptions, + connection: AcpJsonRpcConnection, + mut incoming: mpsc::UnboundedReceiver, + ) -> Self { + let (events_tx, events_rx) = mpsc::unbounded_channel(); + let gate = Gate { + session_id: None, + active_turn: None, + cancelled_turn: None, + runtime_mode: options.runtime_mode.clone(), + interaction_mode: options.interaction_mode.clone(), + mode_unconfirmed: true, + mode_generation: 0, + pending: HashMap::new(), + }; + let runtime = Self { + inner: Arc::new(RuntimeInner { + options, + connection, + gate: Mutex::new(gate), + mode_writes: Mutex::new(()), + config_options: Mutex::new(Vec::new()), + legacy_models: AtomicBool::new(false), + start_lost_connection: AtomicBool::new(false), + account_disabled: std::sync::Mutex::new(None), + abandoned_turns: Mutex::new(HashSet::new()), + events_tx, + events_rx: Mutex::new(events_rx), + abandon: Notify::new(), + }), + }; + let reader = runtime.clone(); + tokio::spawn(async move { + while let Some(event) = incoming.recv().await { + let closed = matches!(event, IncomingEvent::Closed { .. }); + reader.handle_incoming(event).await; + // Nothing follows a close, and the transport may keep the channel open. + if closed { + break; + } + } + }); + runtime + } + + /// Initializes, checks the CLI, opens the session (resume, else load, else new), then + /// writes the model, the thinking level and the mode. Returns the ACP session id. + pub async fn start(&self) -> Result { + let mut result = self.start_session().await; + if let Err(error) = &result { + if matches!( + error, + AntigravityRuntimeError::Protocol( + AcpProtocolError::Closed { .. } + | AcpProtocolError::ReadFailure { .. } + | AcpProtocolError::WriteFailure { .. } + ) + ) { + self.inner + .start_lost_connection + .store(true, Ordering::SeqCst); + } + // A CLI that exits on a disabled account says so only on its error output, however + // its start then failed. + let disabled = self + .inner + .account_disabled + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + if let Some(google_message) = disabled { + result = Err(AntigravityRuntimeError::AccountDisabled { google_message }); + } + // A start that failed mid-way: no session id may survive it. + let mut gate = self.inner.gate.lock().await; + gate.session_id = None; + gate.unconfirm(); + } + result + } + + /// Closes the connection: the writer task ends and the CLI's stdin closes. The readers, and + /// this runtime's reader task, end when the CLI's output closes. + pub fn close(&self) { + self.inner.connection.shutdown(); + } + + /// Whether a failed start lost its connection, so the child is exiting or gone. + pub fn start_lost_connection(&self) -> bool { + self.inner.start_lost_connection.load(Ordering::SeqCst) + } + + async fn start_session(&self) -> Result { + let initialized = match self + .request( + "initialize", + json!({ + "protocolVersion": PROTOCOL_VERSION, + "clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false }, + // This server, at its own version. + "clientInfo": { "name": "bibcode-rust", "version": env!("CARGO_PKG_VERSION") }, + }), + ) + .await + { + Ok(initialized) => initialized, + // No working `agy acp`: the command is unknown, or the child exited before answering. + Err(AntigravityRuntimeError::Protocol( + AcpProtocolError::RemoteRequest { code: -32601, .. }, + )) => return Err(AntigravityRuntimeError::UnsupportedVersion { version: None }), + Err(AntigravityRuntimeError::Protocol( + AcpProtocolError::Closed { .. } + | AcpProtocolError::WriteFailure { .. } + | AcpProtocolError::ReadFailure { .. }, + )) => { + self.inner + .start_lost_connection + .store(true, Ordering::SeqCst); + return Err(AntigravityRuntimeError::UnsupportedVersion { version: None }); + } + Err(error) => return Err(error), + }; + if initialized.get("protocolVersion").and_then(Value::as_u64) != Some(PROTOCOL_VERSION) { + return Err(AntigravityRuntimeError::UnsupportedVersion { version: None }); + } + // A version that cannot be established is refused like an old one. Only the parsed + // numbers reach the message, never the CLI's text. + let Some(version) = initialized + .pointer("/agentInfo/version") + .and_then(Value::as_str) + .and_then(parse_version) + else { + return Err(AntigravityRuntimeError::UnsupportedVersion { version: None }); + }; + if version < MINIMUM_VERSION { + let (major, minor, patch) = version; + return Err(AntigravityRuntimeError::UnsupportedVersion { + version: Some(format!("{major}.{minor}.{patch}")), + }); + } + let capabilities = initialized.get("agentCapabilities"); + let session_capabilities = capabilities.and_then(|capabilities| { + capabilities + .get("sessionCapabilities") + .or_else(|| capabilities.get("session_capabilities")) + }); + // Advertised as an object (`"resume": {}`), so presence is the signal. + let can_resume = session_capabilities + .and_then(|capabilities| capabilities.get("resume")) + .is_some_and(|resume| !resume.is_null() && resume != &Value::Bool(false)); + let can_load = capabilities + .and_then(|capabilities| { + capabilities + .get("loadSession") + .or_else(|| capabilities.get("load_session")) + }) + .and_then(Value::as_bool) + == Some(true); + let session_id = self.open(can_resume, can_load).await?; + // A resumed session is back at the CLI's defaults (measured), so every open writes the + // model, the thinking level and, last, the mode again, all inside the start deadline. + self.apply_model(self.inner.options.model.as_deref()) + .await?; + match self + .set_options(self.inner.options.initial_options.clone()) + .await + { + // A refused level writes nothing; the supervisor's `set_options` reports it. + Ok(()) | Err(AntigravityRuntimeError::UnsupportedOption(_)) => {} + Err(error) => return Err(error), + } + self.confirm_mode().await?; + self.emit("session.started", None, None, json!({})); + self.emit("thread.started", None, None, json!({})); + Ok(session_id) + } + + async fn open( + &self, + can_resume: bool, + can_load: bool, + ) -> Result { + let cwd = &self.inner.options.cwd; + let new_session = json!({ "cwd": cwd, "mcpServers": [] }); + let saved = self.inner.options.resume_session_id.clone(); + let (requested, response) = match saved { + Some(saved) if can_resume => match self + .request( + "session/resume", + json!({ "sessionId": saved, "cwd": cwd, "mcpServers": [] }), + ) + .await + { + Ok(response) => (Some(saved), response), + // Load of an unknown id succeeds (measured), so only resume can tell the + // conversation is gone. Any other failure may be transient and keeps the id. + Err(error) if is_missing_session(&error) => { + (None, self.request("session/new", new_session).await?) + } + Err(error) => return Err(error), + }, + Some(saved) if can_load => { + let response = self + .request( + "session/load", + json!({ "sessionId": saved, "cwd": cwd, "mcpServers": [] }), + ) + .await?; + (Some(saved), response) + } + _ => (None, self.request("session/new", new_session).await?), + }; + let answered = response.get("sessionId").and_then(Value::as_str); + let session_id = match (requested, answered) { + // A reopen must come back as the conversation asked for; only `session/new` + // creates a replacement. + (Some(requested), Some(answered)) if answered != requested => { + return Err(AntigravityRuntimeError::SessionMismatch); + } + (Some(requested), _) => requested, + (None, answered) => answered + .map(str::to_owned) + .ok_or(AntigravityRuntimeError::MissingProviderSessionId)?, + }; + // The answer resolves on the reader task while replayed updates may still wait in the + // incoming queue; drain them while no session is accepted. + let _ = self.inner.connection.barrier().await; + *self.inner.config_options.lock().await = response + .get("configOptions") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + self.inner.legacy_models.store( + response.pointer("/models/availableModels").is_some(), + Ordering::SeqCst, + ); + self.inner.gate.lock().await.session_id = Some(session_id.clone()); + Ok(session_id) + } + + pub async fn set_model(&self, model: &str) -> Result<(), AntigravityRuntimeError> { + self.apply_model(Some(model)).await + } + + async fn apply_model(&self, model: Option<&str>) -> Result<(), AntigravityRuntimeError> { + let Some(model) = model.map(str::trim).filter(|model| { + !model.is_empty() + && !model.eq_ignore_ascii_case("auto") + && !model.eq_ignore_ascii_case("default") + }) else { + return Ok(()); + }; + let session_id = self.provider_session_id().await?; + let options = self.inner.config_options.lock().await.clone(); + if let Some(descriptor) = option_by_category(&options, "model") { + if !advertises(descriptor, model) { + return Err(AntigravityRuntimeError::UnsupportedOption( + RefusedOption::new( + "Antigravity session does not advertise the requested model", + model_unavailable_refusal(model, "Antigravity"), + ), + )); + } + self.write_config(&session_id, option_id(descriptor), json!(model)) + .await?; + } else if self.inner.legacy_models.load(Ordering::SeqCst) { + // Only the combined model-and-effort ids exist: they go out unchanged. The answer is + // `{}`, so it cannot show the mode; the next prompt writes it again. + let result = self + .control( + "session/set_model", + json!({ "sessionId": session_id, "modelId": model }), + ) + .await; + self.inner.gate.lock().await.unconfirm(); + result?; + } + Ok(()) + } + + /// A configuration request on a running session, bounded so a silent CLI cannot hold it. + async fn control( + &self, + method: &'static str, + params: Value, + ) -> Result { + tokio::time::timeout( + self.inner.options.control_timeout, + self.request(method, params), + ) + .await + .unwrap_or_else(|_| { + tracing::warn!( + provider = PROVIDER, + method, + "the provider did not answer a settings change in time" + ); + Err(AntigravityRuntimeError::ControlTimedOut) + }) + } + + /// Writes the turn's options. Only the thinking level (`reasoning`) exists, written to the + /// advertised `thought_level` option. Its levels depend on the model, so the level is checked + /// against the options the last model write returned. + pub async fn set_options(&self, options: Vec) -> Result<(), AntigravityRuntimeError> { + for option in options { + let id = option.get("id").and_then(Value::as_str).ok_or_else(|| { + AntigravityRuntimeError::UnsupportedOption(RefusedOption::new( + "Antigravity option is missing an id", + option_without_id_refusal(), + )) + })?; + if id != REASONING_OPTION_ID { + return Err(AntigravityRuntimeError::UnsupportedOption( + RefusedOption::new( + format!("Antigravity does not support option {id}"), + unsupported_option_refusal(id), + ), + )); + } + let current = self.inner.config_options.lock().await.clone(); + let Some(descriptor) = option_by_category(¤t, "thought_level") else { + return Err(AntigravityRuntimeError::UnsupportedOption( + RefusedOption::new( + "Antigravity session did not advertise a thinking level", + unsupported_option_refusal(THINKING_LEVEL_LABEL), + ), + )); + }; + let label = descriptor + .get("name") + .and_then(Value::as_str) + .unwrap_or(THINKING_LEVEL_LABEL); + let Some(value) = option.get("value").and_then(Value::as_str) else { + return Err(AntigravityRuntimeError::UnsupportedOption( + RefusedOption::new( + "Antigravity thinking level must be a string", + option_needs_value_refusal(label), + ), + )); + }; + if !advertises(descriptor, value) { + return Err(AntigravityRuntimeError::UnsupportedOption( + RefusedOption::new( + "Antigravity session does not advertise the requested thinking level", + unsupported_option_refusal(&format!("{label} {value}")), + ), + )); + } + // The level the start wrote is already current: the supervisor's write after the + // start sends nothing. + if descriptor.get("currentValue").and_then(Value::as_str) == Some(value) { + continue; + } + let session_id = self.provider_session_id().await?; + self.write_config(&session_id, option_id(descriptor), json!(value)) + .await?; + } + Ok(()) + } + + /// Writes one config option. Every answer lists the session's effective mode; one that is not + /// the mode the thread needs leaves the mode unconfirmed, and so does an unanswered write. + async fn write_config( + &self, + session_id: &str, + config_id: &str, + value: Value, + ) -> Result, AntigravityRuntimeError> { + let response = self + .control( + "session/set_config_option", + json!({ "sessionId": session_id, "configId": config_id, "value": value }), + ) + .await; + let options = response.and_then(|response| { + response + .get("configOptions") + .and_then(Value::as_array) + .cloned() + .ok_or(AntigravityRuntimeError::MalformedConfigAcknowledgement) + }); + let mut gate = self.inner.gate.lock().await; + let Ok(options) = options else { + gate.unconfirm(); + return options; + }; + if current_mode(&options) != Some(gate.mode_target()) { + gate.unconfirm(); + } + drop(gate); + *self.inner.config_options.lock().await = options.clone(); + Ok(options) + } + + /// Switches the runtime mode. Auto-answering stops before the write and comes back only when + /// the CLI acknowledges `auto`. A failed switch to full access keeps the previous mode. + pub async fn set_runtime_mode(&self, mode: &str) -> Result<(), AntigravityRuntimeError> { + self.change_modes(Some(mode), None).await + } + + pub async fn set_interaction_mode(&self, mode: &str) -> Result<(), AntigravityRuntimeError> { + self.change_modes(None, Some(mode)).await + } + + /// Records the thread's new mode as the one the CLI must run in, then writes it. There is no + /// rollback: a failed write leaves the new mode unconfirmed, so the next prompt writes it + /// first and is refused until the CLI acknowledges it. + async fn change_modes( + &self, + runtime_mode: Option<&str>, + interaction_mode: Option<&str>, + ) -> Result<(), AntigravityRuntimeError> { + { + let mut gate = self.inner.gate.lock().await; + if let Some(mode) = runtime_mode { + gate.runtime_mode = mode.to_owned(); + } + if let Some(mode) = interaction_mode { + gate.interaction_mode = mode.to_owned(); + } + gate.unconfirm(); + } + self.confirm_mode().await + } + + /// Writes the mode the thread needs and confirms it from the answer, but only if no mode + /// change happened meanwhile; otherwise the mode stays unconfirmed for the newer write. + async fn confirm_mode(&self) -> Result<(), AntigravityRuntimeError> { + let _serial = self.inner.mode_writes.lock().await; + let (target, generation) = { + let gate = self.inner.gate.lock().await; + // A confirmation that held the lock before this one already confirmed the latest + // setting. + if !gate.mode_unconfirmed { + return Ok(()); + } + (gate.mode_target(), gate.mode_generation) + }; + let result = self.apply_mode(target).await; + let mut gate = self.inner.gate.lock().await; + match result { + Ok(()) if gate.mode_generation == generation => { + gate.mode_unconfirmed = false; + Ok(()) + } + Ok(()) => Ok(()), + Err(error) => { + if gate.mode_generation == generation { + gate.unconfirm(); + } + Err(error) + } + } + } + + /// Writes the advertised `mode` option and requires the answer to show it. No fallback to + /// another mode or to `session/set_mode`: a missing or refused mode refuses (D-A5). + async fn apply_mode(&self, target: &'static str) -> Result<(), AntigravityRuntimeError> { + let unavailable = || AntigravityRuntimeError::ModeUnavailable { + mode: target.to_owned(), + }; + let session_id = self.provider_session_id().await?; + let options = self.inner.config_options.lock().await.clone(); + let descriptor = option_by_category(&options, "mode") + .filter(|descriptor| advertises(descriptor, target)) + .ok_or_else(unavailable)?; + // The answer, not a later `current_mode_update`, acknowledges the mode: the CLI sends its + // notifications late, inside the next prompt (measured). + let acknowledged = match self + .write_config(&session_id, option_id(descriptor), json!(target)) + .await + { + Ok(options) => options, + // Answered, but without the options that would confirm the mode: refused like a + // mode the answer does not show. Only an unanswered write stays retryable. + Err( + AntigravityRuntimeError::Protocol(AcpProtocolError::RemoteRequest { .. }) + | AntigravityRuntimeError::MalformedConfigAcknowledgement, + ) => { + return Err(unavailable()); + } + Err(error) => return Err(error), + }; + if current_mode(&acknowledged) != Some(target) { + return Err(unavailable()); + } + Ok(()) + } + + pub async fn send_turn_with_receipt( + &self, + input: Option<&str>, + attachments: Vec, + ) -> Result { + let session_id = self.provider_session_id().await?; + let turn_id = format!("turn-{}", Uuid::new_v4()); + // A mode change landing during the confirmation gets one more confirmation; a second + // one sends no prompt. + let mut attempts = 0; + loop { + { + let mut gate = self.inner.gate.lock().await; + if !gate.mode_unconfirmed { + gate.active_turn = Some(turn_id.clone()); + gate.cancelled_turn = None; + break; + } + if attempts == 2 { + return Err(AntigravityRuntimeError::ModeUnavailable { + mode: gate.mode_target().to_owned(), + }); + } + } + attempts += 1; + self.confirm_mode().await?; + } + self.emit("turn.started", Some(turn_id.clone()), None, json!({})); + let connection = self.inner.connection.clone(); + let prompt = crate::provider::attachments::prompt_parts(input, attachments); + let mut request = match connection + .start_request( + "session/prompt", + json!({ "sessionId": session_id, "prompt": prompt }), + ) + .await + { + Ok(request) => request, + Err(error) => return Err(self.end_unsent_turn(&turn_id, error).await), + }; + let completion = match request.written().await { + Ok(()) => self.track_prompt_response(turn_id.clone(), request.response()), + Err(failure) if failure.is_definitely_not_sent() => { + return Err(self.end_unsent_turn(&turn_id, failure.into_error()).await); + } + Err(failure) => self.track_prompt_response( + turn_id.clone(), + std::future::ready(Err(failure.into_error())), + ), + }; + Ok(AntigravityPromptReceipt { + turn_id, + completion, + }) + } + + /// A prompt that never reached the CLI: its turn is no longer active and ends as failed. + async fn end_unsent_turn( + &self, + turn_id: &str, + error: AcpProtocolError, + ) -> AntigravityRuntimeError { + let error = classify(error); + self.finish_turn(turn_id).await; + self.emit( + "turn.completed", + Some(turn_id.to_owned()), + None, + json!({ + "state": "failed", + "stopReason": "error", + "errorMessage": error.to_string(), + "errorClass": error.class(), + }), + ); + error + } + + /// Clears the turn if it is still the active one and closes the approvals it left open. + async fn finish_turn(&self, turn_id: &str) { + let pending = { + let mut gate = self.inner.gate.lock().await; + if gate.active_turn.as_deref() == Some(turn_id) { + gate.active_turn = None; + } + gate.take_pending(turn_id) + }; + for (request_id, pending) in pending { + self.emit( + "request.resolved", + Some(pending.turn_id), + Some(request_id), + json!({ "requestType": pending.request_type, "decision": "cancel" }), + ); + } + } + + fn track_prompt_response( + &self, + turn_id: String, + response: F, + ) -> oneshot::Receiver> + where + F: Future> + Send + 'static, + { + let runtime = self.clone(); + let (completion_tx, completion) = oneshot::channel(); + tokio::spawn(async move { + let result = response.await; + // Chunks the agent wrote before its answer may still wait in the incoming queue. + let _ = runtime.inner.connection.barrier().await; + runtime.finish_turn(&turn_id).await; + // An abandoned turn already completed as cancelled. + let abandoned = runtime.inner.abandoned_turns.lock().await.remove(&turn_id); + let outcome = match result { + Ok(response) => { + let stop_reason = response + .get("stopReason") + .and_then(Value::as_str) + .unwrap_or("end_turn"); + let (state, failure_message) = acp_turn_state(stop_reason); + let mut payload = json!({ "state": state, "stopReason": stop_reason }); + if let Some(message) = failure_message { + payload["errorMessage"] = json!(message); + } + if !abandoned { + runtime.emit("turn.completed", Some(turn_id), None, payload); + } + Ok(()) + } + Err(error) => { + let error = classify(error); + if !abandoned { + runtime.emit( + "turn.completed", + Some(turn_id), + None, + json!({ + "state": "failed", + "stopReason": "error", + "errorMessage": error.to_string(), + "errorClass": error.class(), + }), + ); + } + Err(error) + } + }; + let _ = completion_tx.send(outcome); + }); + completion + } + + /// Cancels the active turn: answers its pending approvals with `cancelled` (the ACP rule), + /// sends `session/cancel`, and, if the CLI does not end the prompt within the grace period, + /// completes the turn as cancelled and signals [`Self::abandoned`] so the driver stops the + /// process (D-A10). With `requested`, only when it is that turn: a late stop for a turn that + /// already ended must not stop the next one. + pub async fn interrupt_turn( + &self, + requested: Option<&str>, + ) -> Result<(), AntigravityRuntimeError> { + let (turn_id, session_id) = { + let mut gate = self.inner.gate.lock().await; + let Some(turn_id) = gate.active_turn.clone() else { + return Ok(()); + }; + if requested.is_some_and(|requested| requested != turn_id) { + return Ok(()); + } + // From here no request of this turn is answered with anything but `cancelled`. + gate.cancelled_turn = Some(turn_id.clone()); + for (request_id, pending) in gate.take_pending(&turn_id) { + let _ = self + .inner + .connection + .respond( + pending.wire_id, + json!({ "outcome": { "outcome": "cancelled" } }), + ) + .await; + self.emit( + "request.resolved", + Some(pending.turn_id), + Some(request_id), + json!({ "requestType": pending.request_type, "decision": "cancel" }), + ); + } + let session_id = gate + .session_id + .clone() + .ok_or(AntigravityRuntimeError::MissingProviderSessionId)?; + (turn_id, session_id) + }; + self.inner + .connection + .notify("session/cancel", json!({ "sessionId": session_id })) + .await + .map_err(classify)?; + let runtime = self.clone(); + let grace = self.inner.options.cancel_grace; + tokio::spawn(async move { + tokio::time::sleep(grace).await; + { + let mut gate = runtime.inner.gate.lock().await; + if gate.active_turn.as_deref() != Some(turn_id.as_str()) { + return; + } + gate.active_turn = None; + runtime + .inner + .abandoned_turns + .lock() + .await + .insert(turn_id.clone()); + } + tracing::warn!( + provider = PROVIDER, + "the provider did not end a cancelled turn; stopping its process" + ); + runtime.emit( + "turn.completed", + Some(turn_id), + None, + json!({ "state": "cancelled", "stopReason": "cancelled" }), + ); + runtime.inner.abandon.notify_one(); + }); + Ok(()) + } + + /// Resolves once a cancelled turn went unanswered; the driver then stops the process. + pub async fn abandoned(&self) { + self.inner.abandon.notified().await; + } + + pub async fn respond_to_request( + &self, + request_id: &str, + decision: &str, + ) -> Result<(), AntigravityRuntimeError> { + let mut gate = self.inner.gate.lock().await; + let pending = gate.pending.remove(request_id).ok_or_else(|| { + AntigravityRuntimeError::PendingRequestNotFound { + request_id: request_id.to_owned(), + } + })?; + let selected = match decision { + "acceptForSession" => pending.allow_always.or(pending.allow_once), + "accept" => pending.allow_once, + "decline" => pending.reject_once, + _ => None, + }; + let outcome = selected.map_or_else( + || json!({ "outcome": "cancelled" }), + |option_id| json!({ "outcome": "selected", "optionId": option_id }), + ); + self.inner + .connection + .respond(pending.wire_id, json!({ "outcome": outcome })) + .await + .map_err(classify)?; + drop(gate); + self.emit( + "request.resolved", + Some(pending.turn_id), + Some(request_id.to_owned()), + json!({ "requestType": pending.request_type, "decision": decision }), + ); + Ok(()) + } + + pub async fn next_event(&self) -> Option { + self.inner.events_rx.lock().await.recv().await + } + + #[cfg(test)] + async fn pending_request_ids(&self) -> Vec { + self.inner + .gate + .lock() + .await + .pending + .keys() + .cloned() + .collect() + } + + async fn handle_incoming(&self, event: IncomingEvent) { + match event { + IncomingEvent::Notification { method, params } => { + self.handle_notification(&method, params).await; + } + IncomingEvent::Request { + wire_id, + method, + params, + .. + } => { + if let Err(error) = self.handle_request(wire_id, &method, params).await { + tracing::warn!( + provider = PROVIDER, + method = request_label(&method), + class = error.class(), + "failed to answer an ACP request" + ); + } + } + IncomingEvent::Stderr { message } => { + if let Some(notice) = account_disabled_notice(&message) { + *self + .inner + .account_disabled + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(notice); + } + // Provider stderr can hold anything; only its size is logged. + tracing::debug!( + provider = PROVIDER, + bytes = message.len(), + "dropped a provider stderr line" + ); + } + IncomingEvent::Closed { reason } => { + self.emit("session.exited", None, None, json!({ "reason": reason })); + } + IncomingEvent::Barrier(reached) => { + let _ = reached.send(()); + } + } + } + + async fn handle_notification(&self, method: &str, params: Value) { + if method != "session/update" { + // The method name comes from the CLI, so it stays out of the log. + tracing::debug!(provider = PROVIDER, "dropped an unhandled ACP notification"); + return; + } + let (session_id, turn_id) = { + let gate = self.inner.gate.lock().await; + let turn_id = gate + .active_turn + .clone() + .filter(|turn| gate.cancelled_turn.as_ref() != Some(turn)); + // A cancelled turn's updates stay dropped after it ended, until the next prompt. + ( + gate.session_id.clone(), + ( + turn_id, + gate.active_turn.is_some() || gate.cancelled_turn.is_some(), + ), + ) + }; + if session_id.is_none() + || params.get("sessionId").and_then(Value::as_str) != session_id.as_deref() + { + // A replay during open, or an update for another session. + return; + } + let update = params.get("update").cloned().unwrap_or(Value::Null); + let kind = update.get("sessionUpdate").and_then(Value::as_str); + if kind == Some("config_option_update") { + if let Some(options) = update.get("configOptions").and_then(Value::as_array) { + *self.inner.config_options.lock().await = options.clone(); + } + return; + } + // Updates of a cancelled turn are dropped; between turns they carry no turn. + let (turn_id, has_active_turn) = turn_id; + if has_active_turn && turn_id.is_none() { + return; + } + match kind { + Some("agent_message_chunk") => { + let content = update.get("content"); + if content + .and_then(|content| content.get("type")) + .and_then(Value::as_str) + != Some("text") + { + return; + } + let delta = content + .and_then(|content| content.get("text")) + .and_then(Value::as_str) + .unwrap_or_default(); + self.emit( + "content.delta", + turn_id, + None, + json!({ "streamKind": "assistant_text", "delta": delta }), + ); + } + Some("tool_call" | "tool_call_update") => { + // Only the ACP fields: agy's non-standard `name` and `args` are ignored. + // shortcut: a partial `tool_call_update` without `kind` reads as a generic tool; + // agy sends every field each time (measured). Remember kinds per call if not. + let (event_type, status) = match update.get("status").and_then(Value::as_str) { + Some("completed") => ("item.completed", "completed"), + Some("failed") => ("item.completed", "failed"), + _ => ("item.updated", "inProgress"), + }; + self.emit( + event_type, + turn_id, + None, + json!({ + "itemType": item_type(update.get("kind").and_then(Value::as_str)), + "itemId": update.get("toolCallId").and_then(Value::as_str).unwrap_or("tool-call"), + "status": status, + "detail": update.get("title").and_then(Value::as_str).unwrap_or_default(), + }), + ); + } + Some("usage_update") => { + // `used` is the context the session holds and `size` its window (measured). + let Some(used) = update.get("used").and_then(Value::as_u64) else { + return; + }; + let mut usage = json!({ "usedTokens": used }); + if let Some(size) = update.get("size").and_then(Value::as_u64) { + usage["maxTokens"] = json!(size); + } + self.emit( + "thread.token-usage.updated", + turn_id, + None, + json!({ "usage": usage }), + ); + } + Some("plan") => { + let entries = update + .get("entries") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|entry| { + let step = entry.get("content").and_then(Value::as_str)?.trim(); + let status = match entry.get("status").and_then(Value::as_str) { + Some("completed") => "completed", + Some("in_progress") => "inProgress", + _ => "pending", + }; + (!step.is_empty()).then(|| json!({ "step": step, "status": status })) + }) + .collect::>(); + self.emit( + "turn.plan.updated", + turn_id, + None, + json!({ "entries": entries }), + ); + } + _ => { + tracing::debug!( + provider = PROVIDER, + "dropped an unhandled ACP session update" + ); + } + } + } + + async fn handle_request( + &self, + wire_id: Value, + method: &str, + params: Value, + ) -> Result<(), AntigravityRuntimeError> { + let connection = &self.inner.connection; + if method != "session/request_permission" { + // No elicitation or other client method is offered (D-A7). + tracing::debug!(provider = PROVIDER, "answered an unknown ACP request"); + connection + .respond_error( + wire_id, + JsonRpcErrorShape { + code: -32601, + message: format!("Method not found: {method}"), + data: None, + }, + ) + .await?; + return Ok(()); + } + // BiBCode never approves by itself, in any mode: full access is the CLI's own `auto` + // mode, which asks nothing (measured), and any request that still arrives goes to the + // user. Only a cancel, the user's own, answers `cancelled` for them. + let mut gate = self.inner.gate.lock().await; + if gate + .pending + .values() + .any(|pending| pending.wire_id == wire_id) + { + // Checked first: a reply in this id's name would read as the answer to the + // outstanding request, which stays bound to its own operation. + tracing::warn!( + provider = PROVIDER, + "refused a permission request reusing an outstanding id" + ); + connection + .respond_error( + wire_id, + JsonRpcErrorShape { + code: -32600, + message: "Invalid Request: id already in use".to_owned(), + data: None, + }, + ) + .await?; + return Ok(()); + } + let open_session = gate.session_id.is_some() + && params.get("sessionId").and_then(Value::as_str) == gate.session_id.as_deref(); + let turn_id = gate + .active_turn + .clone() + .filter(|turn| gate.cancelled_turn.as_ref() != Some(turn)); + let Some(turn_id) = turn_id.filter(|_| open_session) else { + // Not this session's running turn: during the open, between turns, after a cancel, + // or another session. Refused, never approved and never shown. + connection + .respond(wire_id, json!({ "outcome": { "outcome": "cancelled" } })) + .await?; + return Ok(()); + }; + let options = params + .get("options") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let allow_once = find_option_id(&options, "allow_once"); + let request_id = format!("approval:{}", Uuid::new_v4()); + let tool_call = params.get("toolCall"); + let request_type = match item_type( + tool_call + .and_then(|tool| tool.get("kind")) + .and_then(Value::as_str), + ) { + "file_change" => "file_change_approval", + _ => "exec_command_approval", + }; + let detail = tool_call + .and_then(|tool| tool.get("title")) + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + gate.pending.insert( + request_id.clone(), + PendingRequest { + wire_id, + turn_id: turn_id.clone(), + request_type, + allow_once, + allow_always: find_option_id(&options, "allow_always"), + reject_once: find_option_id(&options, "reject_once"), + }, + ); + // Emitted under the gate, so a cancel cannot resolve the request before it opens. + self.emit( + "request.opened", + Some(turn_id), + Some(request_id), + json!({ "requestType": request_type, "detail": detail }), + ); + Ok(()) + } + + async fn request(&self, method: &str, params: Value) -> Result { + self.inner + .connection + .request(method, params) + .await + .map_err(classify) + } + + async fn provider_session_id(&self) -> Result { + self.inner + .gate + .lock() + .await + .session_id + .clone() + .ok_or(AntigravityRuntimeError::MissingProviderSessionId) + } + + fn emit( + &self, + event_type: &str, + turn_id: Option, + request_id: Option, + payload: Value, + ) { + let _ = self.inner.events_tx.send(AntigravityRuntimeEvent { + event_type: event_type.to_owned(), + thread_id: self.inner.options.thread_id.clone(), + turn_id, + request_id, + payload, + }); + } +} + +/// Google's notice that the account may no longer use the service, when `message` carries it: +/// it says the service was disabled in this account and names the Terms of Service. Only the +/// notice is kept, cut out of whatever else the line holds, best effort: from "This service" +/// (or "disabled in this account") through "Terms of Service", and the appeal sentence when one +/// follows it. +fn account_disabled_notice(message: &str) -> Option { + const DISABLED: &str = "disabled in this account"; + const TERMS: &str = "terms of service"; + const OPENING: &str = "this service has been "; + const APPEAL_END: &str = "this product."; + // ASCII lowercasing keeps every byte offset, so the offsets index `message` too. + let lower = message.to_ascii_lowercase(); + let disabled = lower.find(DISABLED)?; + let terms = disabled + lower[disabled..].find(TERMS)? + TERMS.len(); + let start = lower[..disabled] + .rfind(OPENING) + .filter(|opening| opening + OPENING.len() == disabled) + .unwrap_or(disabled); + let notice = terms + usize::from(lower[terms..].starts_with('.')); + let end = lower[notice..] + .find(APPEAL_END) + .filter(|offset| *offset < 200) + .map_or(notice, |offset| notice + offset + APPEAL_END.len()); + Some(message[start..end].to_owned()) +} + +/// One classifier for every request: `-32000` "Authentication required" is the sign-in error, +/// and Google's notice that the account is disabled is its own error, whatever its code; any +/// other error passes through. +fn classify(error: AcpProtocolError) -> AntigravityRuntimeError { + if let AcpProtocolError::RemoteRequest { message, .. } = &error + && let Some(google_message) = account_disabled_notice(message) + { + return AntigravityRuntimeError::AccountDisabled { google_message }; + } + match &error { + AcpProtocolError::RemoteRequest { + code: -32000, + message, + .. + } if message + .to_ascii_lowercase() + .contains("authentication required") => + { + AntigravityRuntimeError::SignInRequired + } + _ => AntigravityRuntimeError::Protocol(error), + } +} + +/// `session/resume` of an unknown id answers `-32603` "Failed to read session ..." (measured). +fn is_missing_session(error: &AntigravityRuntimeError) -> bool { + matches!( + error, + AntigravityRuntimeError::Protocol(AcpProtocolError::RemoteRequest { code: -32603, message, .. }) + if message.contains("Failed to read session") + ) +} + +/// The ACP mode a thread's permission and interaction modes ask for. An unknown runtime mode +/// asks before acting. +pub(crate) fn mode_for(runtime_mode: &str, interaction_mode: &str) -> &'static str { + if interaction_mode == "plan" { + return "plan"; + } + match runtime_mode { + "full-access" => "auto", + "auto-accept-edits" => "accept-edits", + _ => "default", + } +} + +fn item_type(kind: Option<&str>) -> &'static str { + match kind { + Some("edit" | "delete" | "move") => "file_change", + Some("execute") => "command_execution", + _ => "dynamic_tool_call", + } +} + +/// The config option for `category` (`model`, `thought_level`, `mode`): the one with that ACP +/// category, else one whose id is the category name, as the CLI may omit the category. The +/// inventory reads the session's options through it too, so a chat accepts what it advertised. +pub(crate) fn option_by_category<'a>(options: &'a [Value], category: &str) -> Option<&'a Value> { + let named = |key: &str| { + options + .iter() + .find(|option| option.get(key).and_then(Value::as_str) == Some(category)) + }; + named("category").or_else(|| named("id")) +} + +/// The session's effective mode, as a config answer lists it. +fn current_mode(options: &[Value]) -> Option<&str> { + option_by_category(options, "mode") + .and_then(|descriptor| descriptor.get("currentValue")) + .and_then(Value::as_str) +} + +/// A fixed name for a request method from the CLI, safe to log. +fn request_label(method: &str) -> &'static str { + if method == "session/request_permission" { + "session/request_permission" + } else { + "unknown" + } +} + +fn option_id(descriptor: &Value) -> &str { + descriptor + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() +} + +fn advertises(descriptor: &Value, value: &str) -> bool { + descriptor + .get("options") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|option| option.get("value").and_then(Value::as_str) == Some(value)) +} + +fn find_option_id(options: &[Value], kind: &str) -> Option { + options.iter().find_map(|option| { + (option.get("kind").and_then(Value::as_str) == Some(kind)) + .then(|| option.get("optionId").and_then(Value::as_str)) + .flatten() + .map(str::to_owned) + }) +} + +/// The first `major.minor.patch` in `text`. +fn parse_version(text: &str) -> Option<(u64, u64, u64)> { + text.split(|character: char| !(character.is_ascii_digit() || character == '.')) + .find_map(|token| { + let mut parts = token.split('.'); + Some(( + parts.next()?.parse().ok()?, + parts.next()?.parse().ok()?, + parts.next()?.parse().ok()?, + )) + }) +} + +/// A `model` and a `thought_level` option without a category, as the inventory's catalog test +/// reads them; the runtime test selects the level the inventory publishes from them. +#[cfg(test)] +pub(crate) fn uncategorized_level_options() -> Value { + json!([ + { "id": "model", "currentValue": "alpha", "options": [{ "value": "alpha" }] }, + { "id": "thought_level", "name": "Thinking", "currentValue": "low", + "options": [{ "value": "extra-high", "name": "Extra High" }, { "value": "low" }] } + ]) +} + +#[cfg(test)] +#[path = "runtime_tests.rs"] +mod tests; diff --git a/apps/server/src/provider/antigravity/runtime_tests.rs b/apps/server/src/provider/antigravity/runtime_tests.rs new file mode 100644 index 0000000000..a0a81ef96d --- /dev/null +++ b/apps/server/src/provider/antigravity/runtime_tests.rs @@ -0,0 +1,1991 @@ +//! Fixture-peer tests: the runtime talks to a scripted ACP agent over in-memory pipes. The +//! shapes follow `agy` 1.5.13 as measured on 2026-11-20, with placeholder ids, models and paths. + +use super::*; +use crate::provider::antigravity::{AcpConnectionConfig, AcpJsonRpcConnection}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, Lines, duplex}; +use tokio::task::JoinHandle; +use tokio::time::{Duration, timeout}; + +const SESSION: &str = "session-a"; +const SAVED: &str = "saved-session"; +const CWD: &str = "/workspace/checkout"; +const MARKER: &str = "SYNTHETIC-SECRET-7f3a"; + +struct Peer { + requests: Lines>, + output: DuplexStream, + stderr: DuplexStream, +} + +impl Peer { + async fn next(&mut self) -> Value { + let line = timeout(Duration::from_secs(5), self.requests.next_line()) + .await + .expect("the client wrote nothing in time") + .expect("peer read") + .expect("client stream open"); + serde_json::from_str(&line).expect("the client writes JSON") + } + + async fn expect(&mut self, method: &str) -> Value { + let message = self.next().await; + assert_eq!(message["method"], method, "{message}"); + message + } + + async fn send(&mut self, message: Value) { + let mut line = message.to_string(); + line.push('\n'); + self.output + .write_all(line.as_bytes()) + .await + .expect("peer write"); + } + + async fn reply(&mut self, request: &Value, result: Value) { + self.send(json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })) + .await; + } + + async fn fail(&mut self, request: &Value, code: i64, message: &str) { + self.send(json!({ + "jsonrpc": "2.0", + "id": request["id"], + "error": { "code": code, "message": message }, + })) + .await; + } + + async fn update(&mut self, session: &str, update: Value) { + self.send(json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { "sessionId": session, "update": update }, + })) + .await; + } + + async fn permission(&mut self, options: Value) { + self.permission_as(json!("1"), SESSION, "edit", options) + .await; + } + + async fn permission_as(&mut self, id: Value, session: &str, kind: &str, options: Value) { + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": "session/request_permission", + "params": { + "sessionId": session, + "toolCall": { + "toolCallId": "call-1", + "status": "pending", + "kind": kind, + "title": "File notes.txt", + "_meta": { "marker": MARKER }, + }, + "options": options, + }, + })) + .await; + } + + async fn silent(&mut self) -> bool { + timeout(Duration::from_millis(200), self.requests.next_line()) + .await + .is_err() + } +} + +fn allow_or_deny() -> Value { + json!([ + { "optionId": "allow", "name": "Allow", "kind": "allow_once" }, + { "optionId": "deny", "name": "Deny", "kind": "reject_once" }, + ]) +} + +fn options(runtime_mode: &str) -> AntigravitySessionOptions { + AntigravitySessionOptions { + thread_id: "thread-a".to_owned(), + cwd: CWD.to_owned(), + runtime_mode: runtime_mode.to_owned(), + interaction_mode: "default".to_owned(), + model: None, + resume_session_id: None, + cancel_grace: Duration::from_secs(5), + control_timeout: Duration::from_secs(3), + initial_options: Vec::new(), + } +} + +fn connect(options: AntigravitySessionOptions) -> (AntigravitySessionRuntime, Peer) { + let (stdout, output) = duplex(1 << 16); + let (requests, stdin) = duplex(1 << 16); + let (stderr_reader, stderr) = duplex(4096); + let (connection, incoming) = + AcpJsonRpcConnection::spawn(stdout, stdin, stderr_reader, AcpConnectionConfig::default()); + ( + AntigravitySessionRuntime::new(options, connection, incoming), + Peer { + requests: BufReader::new(requests).lines(), + output, + stderr, + }, + ) +} + +fn spawn_start( + runtime: &AntigravitySessionRuntime, +) -> JoinHandle> { + let runtime = runtime.clone(); + tokio::spawn(async move { runtime.start().await }) +} + +/// A start that ends in time; a hang fails the test instead of stalling the run. +async fn finish( + start: JoinHandle>, +) -> Result { + timeout(Duration::from_secs(5), start) + .await + .expect("start ended in time") + .expect("start task") +} + +fn initialize_result(version: &str, protocol: u64, capabilities: Value) -> Value { + json!({ + "protocolVersion": protocol, + "agentCapabilities": capabilities, + "agentInfo": { "name": "Antigravity ACP Server", "version": version }, + "authMethods": [{ "id": "oauth-personal", "name": "Log in" }], + }) +} + +fn all_capabilities() -> Value { + json!({ + "loadSession": true, + "load_session": true, + "sessionCapabilities": { "resume": {}, "close": {}, "load": {}, "list": {} }, + "session_capabilities": { "resume": {}, "close": {}, "load": {}, "list": {} }, + "_meta": { "antigravity": { "tier": MARKER } }, + }) +} + +fn config_options(model: &str, levels: &[&str], level: &str, mode: &str, modes: &[&str]) -> Value { + json!([ + { + "id": "model", "name": "Model", "category": "model", "type": "select", + "currentValue": model, + "options": [ + { "value": "test-model-a", "name": "Test Model A" }, + { "value": "test-model-b", "name": "Test Model B" }, + ], + }, + { + "id": "thought_level", "name": "Thinking Level", "category": "thought_level", + "type": "select", "currentValue": level, + "options": levels.iter().map(|level| json!({ "value": level, "name": level })).collect::>(), + }, + { + "id": "mode", "name": "Mode", "category": "mode", "type": "select", + "currentValue": mode, + "options": modes.iter().map(|mode| json!({ "value": mode, "name": mode })).collect::>(), + }, + ]) +} + +const ALL_MODES: &[&str] = &["default", "accept-edits", "auto", "plan"]; + +fn standard_options(mode: &str) -> Value { + config_options( + "test-model-a", + &["low", "medium", "high"], + "high", + mode, + ALL_MODES, + ) +} + +fn session_result(session: &str, config: Value) -> Value { + json!({ + "sessionId": session, + "models": { + "availableModels": [{ "modelId": "test-model-a-high", "name": "Test Model A (High)" }], + "currentModelId": "test-model-a-high", + }, + "modes": { "currentModeId": "default", "availableModes": [{ "id": "default" }] }, + "configOptions": config, + "_meta": { "antigravity": { "tier": { "name": MARKER } } }, + }) +} + +async fn answer_mode(peer: &mut Peer, expected: &str) { + let request = peer.expect("session/set_config_option").await; + assert_eq!(request["params"]["sessionId"], SESSION); + assert_eq!(request["params"]["configId"], "mode"); + assert_eq!(request["params"]["value"], expected); + peer.reply( + &request, + json!({ "configOptions": standard_options(expected) }), + ) + .await; +} + +/// A started runtime whose peer advertised every capability and acknowledged `mode`. +async fn started_with( + options: AntigravitySessionOptions, + mode: &str, +) -> (AntigravitySessionRuntime, Peer) { + let (runtime, mut peer) = connect(options); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, mode).await; + assert_eq!(finish(start).await.expect("start"), SESSION); + (runtime, peer) +} + +async fn started(runtime_mode: &str, mode: &str) -> (AntigravitySessionRuntime, Peer) { + started_with(options(runtime_mode), mode).await +} + +async fn next_event(runtime: &AntigravitySessionRuntime) -> AntigravityRuntimeEvent { + timeout(Duration::from_secs(5), runtime.next_event()) + .await + .expect("an event in time") + .expect("event stream open") +} + +/// Events up to and including the first of type `last`, without the session lifecycle ones. +async fn events_until(runtime: &AntigravitySessionRuntime, last: &str) -> Vec<(String, Value)> { + let mut events = Vec::new(); + loop { + let event = next_event(runtime).await; + if matches!( + event.event_type.as_str(), + "session.started" | "thread.started" + ) { + continue; + } + let done = event.event_type == last; + events.push((event.event_type, event.payload)); + if done { + return events; + } + } +} + +fn types(events: &[(String, Value)]) -> Vec<&str> { + events.iter().map(|(kind, _)| kind.as_str()).collect() +} + +async fn begin_turn( + runtime: &AntigravitySessionRuntime, + peer: &mut Peer, +) -> (AntigravityPromptReceipt, Value) { + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("prompt written"); + let prompt = peer.expect("session/prompt").await; + assert_eq!(prompt["params"]["sessionId"], SESSION); + (receipt, prompt) +} + +async fn opened_request_id(runtime: &AntigravitySessionRuntime) -> String { + loop { + let event = next_event(runtime).await; + if event.event_type == "request.opened" { + return event.request_id.expect("an opened request has an id"); + } + } +} + +#[tokio::test] +async fn the_handshake_speaks_protocol_one_and_never_authenticates() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + assert_eq!(initialize["params"]["protocolVersion"], 1); + assert_eq!( + initialize["params"]["clientCapabilities"]["terminal"], + false + ); + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + // The next request opens the session: no `authenticate` in between. + let new = peer.expect("session/new").await; + assert_eq!( + new["params"], + json!({ "cwd": CWD, "mcpServers": [] }), + "a new session carries the checkout and no MCP servers" + ); + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); + assert!(peer.silent().await); +} + +/// A slow start is never given up here: the launch shows a notice and only a stop ends it. A +/// start whose answers come late completes normally. +#[tokio::test] +async fn a_slow_peer_keeps_the_start_waiting_until_it_answers() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + !start.is_finished(), + "an unanswered initialize keeps waiting" + ); + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + !start.is_finished(), + "an unanswered session/new keeps waiting" + ); + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); +} + +#[tokio::test] +async fn another_protocol_version_is_refused_before_a_session_opens() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 2, all_capabilities()), + ) + .await; + let error = finish(start).await.expect_err("protocol 2 is refused"); + assert!( + matches!(error, AntigravityRuntimeError::UnsupportedVersion { .. }), + "{error:?}" + ); + assert!(error.to_string().contains("1.5.4"), "{error}"); + assert!( + peer.silent().await, + "no session opens on a refused handshake" + ); +} + +#[tokio::test] +async fn the_cli_version_from_initialize_gates_the_chat_at_1_5_4() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.3", 1, all_capabilities()), + ) + .await; + let error = finish(start).await.expect_err("1.5.3 is refused"); + let message = error.to_string(); + assert!( + message.contains("1.5.4") + && message.contains("1.5.3") + && message.contains("agy update") + && message.contains("Antigravity Terminal still works"), + "{message}" + ); + assert!(peer.silent().await); + + // A version that cannot be established is refused too, naming the minimum. + for version in [Some("unknown"), None] { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + let mut result = initialize_result("1.5.13", 1, all_capabilities()); + match version { + Some(version) => result["agentInfo"]["version"] = json!(version), + None => { + result["agentInfo"] + .as_object_mut() + .unwrap() + .remove("version"); + } + } + peer.reply(&initialize, result).await; + let error = finish(start) + .await + .expect_err("an unverified version is refused"); + assert!( + matches!( + error, + AntigravityRuntimeError::UnsupportedVersion { version: None } + ), + "{error:?}" + ); + assert!(error.to_string().contains("1.5.4"), "{error}"); + assert!(peer.silent().await, "{version:?} opens no session"); + } + + for version in ["1.5.4", "1.6.0-preview"] { + let (runtime, mut peer) = connect(options("full-access")); + let _start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result(version, 1, all_capabilities()), + ) + .await; + peer.expect("session/new").await; + } +} + +#[tokio::test] +async fn a_cli_without_a_working_acp_gets_the_version_message() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.fail(&initialize, -32601, "Method not found: initialize") + .await; + let error = finish(start).await.expect_err("no acp"); + assert!( + matches!( + error, + AntigravityRuntimeError::UnsupportedVersion { version: None } + ), + "{error:?}" + ); + + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + peer.expect("initialize").await; + drop(peer); + let error = finish(start).await.expect_err("the child exited"); + assert!( + matches!( + error, + AntigravityRuntimeError::UnsupportedVersion { version: None } + ), + "{error:?}" + ); +} + +#[tokio::test] +async fn a_signed_out_cli_gets_the_sign_in_steps_and_other_server_errors_pass_through() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.fail(&new, -32000, "Authentication required").await; + let error = finish(start).await.expect_err("signed out"); + assert!( + matches!(error, AntigravityRuntimeError::SignInRequired), + "{error:?}" + ); + assert!(error.to_string().contains("agy acp --login"), "{error}"); + + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.fail(&new, -32000, "Quota exhausted").await; + let error = finish(start).await.expect_err("a server error"); + assert!( + matches!(error, AntigravityRuntimeError::Protocol(_)), + "{error:?}" + ); +} + +#[tokio::test] +async fn resume_reopens_the_saved_session_and_reapplies_model_thinking_level_and_mode() { + let mut options = options("approval-required"); + options.resume_session_id = Some(SAVED.to_owned()); + options.model = Some("test-model-b".to_owned()); + let (runtime, mut peer) = connect(options); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let resume = peer.expect("session/resume").await; + assert_eq!( + resume["params"], + json!({ "sessionId": SAVED, "cwd": CWD, "mcpServers": [] }) + ); + // Measured: a resumed session is back at the CLI's default model and thinking level. + peer.reply(&resume, session_result(SAVED, standard_options("default"))) + .await; + let model = peer.expect("session/set_config_option").await; + assert_eq!( + model["params"], + json!({ "sessionId": SAVED, "configId": "model", "value": "test-model-b" }) + ); + // The thinking levels depend on the model: this one offers `max` and no `medium`. + let levels_of_b = config_options("test-model-b", &["low", "max"], "low", "default", ALL_MODES); + peer.reply(&model, json!({ "configOptions": levels_of_b.clone() })) + .await; + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["configId"], "mode"); + assert_eq!(mode["params"]["value"], "default"); + peer.reply(&mode, json!({ "configOptions": levels_of_b.clone() })) + .await; + assert_eq!(finish(start).await.unwrap(), SAVED); + + let refused = runtime + .set_options(vec![json!({ "id": "reasoning", "value": "medium" })]) + .await + .expect_err("model B does not offer medium"); + assert!( + refused.refused_option().is_some(), + "an unadvertised level is a permanent refusal: {refused:?}" + ); + assert!(peer.silent().await, "a refused level writes nothing"); + + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "max" })]) + .await + } + }); + let level = peer.expect("session/set_config_option").await; + assert_eq!( + level["params"], + json!({ "sessionId": SAVED, "configId": "thought_level", "value": "max" }) + ); + peer.reply(&level, json!({ "configOptions": levels_of_b })) + .await; + set.await.unwrap().expect("level applied"); +} + +#[tokio::test] +async fn load_replays_are_dropped_and_so_are_updates_for_another_session() { + let mut options = options("full-access"); + options.resume_session_id = Some(SESSION.to_owned()); + let (runtime, mut peer) = connect(options); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, json!({ "loadSession": true })), + ) + .await; + let load = peer.expect("session/load").await; + assert_eq!( + load["params"], + json!({ "sessionId": SESSION, "cwd": CWD, "mcpServers": [] }) + ); + peer.update( + SESSION, + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "replayed" } }), + ) + .await; + peer.reply(&load, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); + + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.update( + "other-session", + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "stale" } }), + ) + .await; + peer.update( + SESSION, + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "live" } }), + ) + .await; + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + let deltas = events + .iter() + .filter(|(kind, _)| kind == "content.delta") + .map(|(_, payload)| payload["delta"].as_str().unwrap_or_default()) + .collect::>(); + assert_eq!(deltas, ["live"]); +} + +#[tokio::test] +async fn without_resume_or_load_a_saved_session_starts_a_new_one() { + let mut options = options("full-access"); + options.resume_session_id = Some(SAVED.to_owned()); + let (runtime, mut peer) = connect(options); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply(&initialize, initialize_result("1.5.13", 1, json!({}))) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); +} + +#[tokio::test] +async fn only_a_missing_session_answer_starts_a_new_session() { + let mut resuming = options("full-access"); + resuming.resume_session_id = Some(SAVED.to_owned()); + + let (runtime, mut peer) = connect(resuming.clone()); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let resume = peer.expect("session/resume").await; + peer.fail( + &resume, + -32603, + "Failed to read session saved-session; retry, or load it with session/load", + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); + + for (code, message) in [ + (-32603, "Internal error"), + (-32000, "Authentication required"), + ] { + let (runtime, mut peer) = connect(resuming.clone()); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let resume = peer.expect("session/resume").await; + peer.fail(&resume, code, message).await; + assert!(finish(start).await.is_err(), "{message} keeps the saved id"); + assert!(peer.silent().await, "{message} opens no new session"); + } +} + +#[tokio::test] +async fn approval_required_refuses_to_start_without_an_acknowledged_default_mode() { + // `default` is not advertised: no write is tried. + let (runtime, mut peer) = connect(options("approval-required")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + let without_default = config_options( + "test-model-a", + &["low"], + "low", + "auto", + &["accept-edits", "auto", "plan"], + ); + peer.reply(&new, session_result(SESSION, without_default)) + .await; + let error = finish(start).await.expect_err("no default mode"); + assert!( + matches!(error, AntigravityRuntimeError::ModeUnavailable { .. }), + "{error:?}" + ); + assert!(peer.silent().await); + + // `default` is rejected, or acknowledged as another mode. + for acknowledgement in [None, Some("auto")] { + let (runtime, mut peer) = connect(options("approval-required")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("auto"))) + .await; + let mode = peer.expect("session/set_config_option").await; + match acknowledgement { + None => peer.fail(&mode, -32602, "Unknown mode: default").await, + Some(other) => { + peer.reply(&mode, json!({ "configOptions": standard_options(other) })) + .await; + } + } + let error = finish(start).await.expect_err("unacknowledged default"); + assert!( + matches!(error, AntigravityRuntimeError::ModeUnavailable { .. }), + "{error:?}" + ); + assert!(peer.silent().await, "no prompt follows a refused start"); + } +} + +#[tokio::test] +async fn modes_follow_the_runtime_and_interaction_mode() { + started("full-access", "auto").await; + started("auto-accept-edits", "accept-edits").await; + started("approval-required", "default").await; + let mut planning = options("approval-required"); + planning.interaction_mode = "plan".to_owned(); + started_with(planning, "plan").await; +} + +#[tokio::test] +async fn without_a_model_config_option_the_suffixed_model_id_goes_to_set_model() { + let mut options = options("full-access"); + options.model = Some("test-model-a-high".to_owned()); + let (runtime, mut peer) = connect(options); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + let only_modes = json!([standard_options("default")[2].clone()]); + peer.reply(&new, session_result(SESSION, only_modes)).await; + let model = peer.expect("session/set_model").await; + assert_eq!( + model["params"], + json!({ "sessionId": SESSION, "modelId": "test-model-a-high" }) + ); + peer.reply(&model, json!({})).await; + answer_mode(&mut peer, "auto").await; + assert_eq!(finish(start).await.unwrap(), SESSION); +} + +#[tokio::test] +async fn a_scripted_turn_projects_text_tool_activity_and_one_approval() { + let (runtime, mut peer) = started("approval-required", "default").await; + let (receipt, prompt) = begin_turn(&runtime, &mut peer).await; + let tool = |status: &str| { + json!({ + "sessionUpdate": if status == "in_progress" { "tool_call" } else { "tool_call_update" }, + "toolCallId": "call-1", + "status": status, + "kind": "edit", + "title": "File notes.txt", + "locations": [{ "path": "/workspace/checkout/notes.txt" }], + "rawInput": { "Path": "/workspace/checkout/notes.txt" }, + "name": "write_file", + "args": { "Content": MARKER }, + "_meta": { "marker": MARKER }, + }) + }; + peer.update(SESSION, tool("in_progress")).await; + peer.update(SESSION, tool("pending")).await; + peer.permission(allow_or_deny()).await; + let mut events = events_until(&runtime, "request.opened").await; + assert_eq!( + events.last().unwrap().1["requestType"], + "file_change_approval" + ); + assert_eq!(events.last().unwrap().1["detail"], "File notes.txt"); + let request_id = runtime + .pending_request_ids() + .await + .pop() + .expect("one pending approval"); + runtime + .respond_to_request(&request_id, "accept") + .await + .expect("answer forwarded"); + let answer = peer.next().await; + assert_eq!( + answer["id"], + json!("1"), + "the string id comes back as a string" + ); + assert_eq!( + answer["result"], + json!({ "outcome": { "outcome": "selected", "optionId": "allow" } }) + ); + peer.update(SESSION, tool("completed")).await; + peer.update( + SESSION, + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "done" } }), + ) + .await; + peer.update( + SESSION, + json!({ "sessionUpdate": "usage_update", "used": 1, "size": 2 }), + ) + .await; + peer.reply( + &prompt, + json!({ "stopReason": "end_turn", "usage": { "totalTokens": 3 } }), + ) + .await; + events.extend(events_until(&runtime, "turn.completed").await); + assert_eq!( + types(&events), + [ + "turn.started", + "item.updated", + "item.updated", + "request.opened", + "request.resolved", + "item.completed", + "content.delta", + "thread.token-usage.updated", + "turn.completed", + ] + ); + assert_eq!( + events[7].1, + json!({ "usage": { "usedTokens": 1, "maxTokens": 2 } }), + "usage_update feeds the context window meter" + ); + assert_eq!( + events[4].1["requestType"], "file_change_approval", + "the resolved event names the kind the opened one did" + ); + assert_eq!(events[1].1["itemType"], "file_change"); + assert_eq!(events[1].1["itemId"], "call-1"); + assert_eq!(events[1].1["detail"], "File notes.txt"); + assert_eq!(events[5].1["status"], "completed"); + assert_eq!(events[6].1["delta"], "done"); + assert_eq!(events[8].1["state"], "completed"); + for (_, payload) in &events { + assert!(!payload.to_string().contains(MARKER), "{payload}"); + } + timeout(Duration::from_secs(2), receipt.completion()) + .await + .unwrap() + .expect("accepted"); +} + +/// Full access is the CLI's own `auto` mode, which asks nothing (measured): BiBCode writes no +/// permission reply without the user's decision in any mode, whatever the options offered. +#[tokio::test] +async fn no_mode_writes_a_permission_reply_without_the_users_decision() { + let mut planning = options("full-access"); + planning.interaction_mode = "plan".to_owned(); + let every_option = json!([ + { "optionId": "always", "kind": "allow_always" }, + { "optionId": "once", "kind": "allow_once" }, + { "optionId": "deny", "kind": "reject_once" }, + ]); + for (options, mode) in [ + (options("full-access"), "auto"), + (options("auto-accept-edits"), "accept-edits"), + (options("approval-required"), "default"), + (planning, "plan"), + ] { + let (runtime, mut peer) = started_with(options, mode).await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(every_option.clone()).await; + let request_id = opened_request_id(&runtime).await; + assert!( + peer.silent().await, + "{mode}: nothing until the user answers" + ); + runtime + .respond_to_request(&request_id, "accept") + .await + .expect("the user's answer"); + let answer = peer.next().await; + assert_eq!(answer["id"], json!("1")); + assert_eq!(answer["result"]["outcome"]["optionId"], "once", "{mode}"); + } +} + +#[tokio::test] +async fn a_switch_to_approval_required_rewrites_the_mode_before_the_next_prompt() { + let (runtime, mut peer) = started("full-access", "auto").await; + let switch = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("approval-required").await } + }); + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["value"], "default"); + peer.fail(&mode, -32603, "Internal error").await; + assert!(switch.await.unwrap().is_err()); + + // The CLI may still run in `auto`, so the next prompt first writes the mode again, and is + // refused if that fails too. + let send = || { + let runtime = runtime.clone(); + tokio::spawn(async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + }) + }; + let refused = send(); + let retry = peer.expect("session/set_config_option").await; + assert_eq!(retry["params"]["value"], "default"); + peer.fail(&retry, -32603, "Internal error").await; + assert!(refused.await.unwrap().is_err()); + assert!( + peer.silent().await, + "no prompt while the mode is unconfirmed" + ); + + let accepted = send(); + let retry = peer.expect("session/set_config_option").await; + assert_eq!(retry["params"]["value"], "default"); + peer.reply( + &retry, + json!({ "configOptions": standard_options("default") }), + ) + .await; + let _receipt = accepted + .await + .unwrap() + .expect("prompt written once confirmed"); + peer.expect("session/prompt").await; + peer.permission(allow_or_deny()).await; + opened_request_id(&runtime).await; + assert!(peer.silent().await, "no auto answer after the switch"); +} + +#[tokio::test] +async fn cancel_answers_pending_approvals_and_drops_a_later_answer() { + let (runtime, mut peer) = started("approval-required", "default").await; + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(allow_or_deny()).await; + let request_id = opened_request_id(&runtime).await; + runtime.interrupt_turn(None).await.expect("cancel sent"); + let answer = peer.next().await; + assert_eq!(answer["id"], json!("1")); + assert_eq!( + answer["result"], + json!({ "outcome": { "outcome": "cancelled" } }) + ); + let cancel = peer.expect("session/cancel").await; + assert_eq!(cancel["params"]["sessionId"], SESSION); + assert!(cancel.get("id").is_none(), "cancel is a notification"); + let stale = runtime + .respond_to_request(&request_id, "accept") + .await + .expect_err("the approval was dropped on cancel"); + assert!( + matches!( + stale, + AntigravityRuntimeError::PendingRequestNotFound { .. } + ), + "{stale:?}" + ); + assert!(peer.silent().await, "a stale answer writes nothing"); + // Measured: the CLI ends the prompt with `cancelled` at once. + peer.reply(&prompt, json!({ "stopReason": "cancelled" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(events.last().unwrap().1["state"], "cancelled"); +} + +#[tokio::test] +async fn an_unanswered_cancel_ends_the_turn_and_abandons_the_process() { + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(50); + let (runtime, mut peer) = started_with(options, "auto").await; + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + runtime.interrupt_turn(None).await.expect("cancel sent"); + peer.expect("session/cancel").await; + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(events.last().unwrap().1["state"], "cancelled"); + timeout(Duration::from_secs(2), runtime.abandoned()) + .await + .expect("the driver is told to stop the process"); + // A late answer does not complete the turn twice. + peer.reply(&prompt, json!({ "stopReason": "cancelled" })) + .await; + assert!( + timeout(Duration::from_millis(200), runtime.next_event()) + .await + .is_err() + ); +} + +/// Updates a cancelled turn still sends after it ended, answered or abandoned, are dropped: +/// they never reach the thread as turnless output. +#[tokio::test] +async fn a_cancelled_turns_updates_after_its_end_are_dropped() { + for answered in [true, false] { + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(50); + let (runtime, mut peer) = started_with(options, "auto").await; + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + runtime.interrupt_turn(None).await.expect("cancel sent"); + peer.expect("session/cancel").await; + if answered { + peer.reply(&prompt, json!({ "stopReason": "cancelled" })) + .await; + } + events_until(&runtime, "turn.completed").await; + peer.update( + SESSION, + json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "late" } }), + ) + .await; + peer.update( + SESSION, + json!({ "sessionUpdate": "plan", "entries": [{ "content": "late", "status": "pending" }] }), + ) + .await; + assert!( + timeout(Duration::from_millis(300), runtime.next_event()) + .await + .is_err(), + "answered: {answered}" + ); + } +} + +#[tokio::test] +async fn an_answered_cancel_does_not_abandon_the_process() { + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(100); + let (runtime, mut peer) = started_with(options, "auto").await; + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + runtime.interrupt_turn(None).await.expect("cancel sent"); + peer.expect("session/cancel").await; + peer.reply(&prompt, json!({ "stopReason": "cancelled" })) + .await; + events_until(&runtime, "turn.completed").await; + assert!( + timeout(Duration::from_millis(300), runtime.abandoned()) + .await + .is_err() + ); +} + +/// A late stop for a finished turn leaves the running turn alone: no `session/cancel`, and the +/// turn completes normally even past the cancel grace period. +#[tokio::test] +async fn a_late_stop_for_a_finished_turn_leaves_the_running_turn_alone() { + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(50); + let (runtime, mut peer) = started_with(options, "auto").await; + let (first, prompt) = begin_turn(&runtime, &mut peer).await; + let finished = first.turn_id.clone(); + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + events_until(&runtime, "turn.completed").await; + first.completion().await.expect("the first turn finishes"); + + let (second, prompt) = begin_turn(&runtime, &mut peer).await; + assert_ne!(second.turn_id, finished); + runtime + .interrupt_turn(Some(&finished)) + .await + .expect("a stale stop is no error"); + assert!(peer.silent().await, "no session/cancel for a finished turn"); + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(events.last().unwrap().1["state"], "completed"); + second + .completion() + .await + .expect("the running turn finishes"); + assert!( + timeout(Duration::from_millis(200), runtime.abandoned()) + .await + .is_err(), + "no stop timer was armed" + ); +} + +/// A stop that names the running turn still stops it. +#[tokio::test] +async fn a_stop_naming_the_active_turn_stops_it() { + let (runtime, mut peer) = started("full-access", "auto").await; + let (receipt, prompt) = begin_turn(&runtime, &mut peer).await; + runtime + .interrupt_turn(Some(&receipt.turn_id)) + .await + .expect("cancel sent"); + let cancel = peer.expect("session/cancel").await; + assert_eq!(cancel["params"]["sessionId"], SESSION); + peer.reply(&prompt, json!({ "stopReason": "cancelled" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(events.last().unwrap().1["state"], "cancelled"); +} + +#[tokio::test] +async fn an_empty_end_turn_completes_with_no_reply() { + let (runtime, mut peer) = started("full-access", "auto").await; + let (receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(types(&events), ["turn.started", "turn.completed"]); + assert_eq!(events[1].1["state"], "completed"); + receipt.completion().await.expect("accepted"); +} + +#[tokio::test] +async fn secret_markers_stay_out_of_logs() { + let Some(child) = crate::test_support::in_own_process( + "provider::antigravity::runtime::tests::secret_markers_stay_out_of_logs", + ) else { + return; + }; + let log = CapturedLog::default(); + let _logging = tracing::subscriber::set_default( + tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .with_writer({ + let log = log.clone(); + move || log.clone() + }) + .finish(), + ); + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(50); + let (runtime, mut peer) = started_with(options, "auto").await; + peer.stderr + .write_all(format!("stderr {MARKER}\n").as_bytes()) + .await + .unwrap(); + peer.send( + json!({ "jsonrpc": "2.0", "method": format!("x/{MARKER}"), "params": { "text": MARKER } }), + ) + .await; + peer.send( + json!({ "jsonrpc": "2.0", "id": 9, "method": format!("x/ask-{MARKER}"), "params": { "text": MARKER } }), + ) + .await; + assert_eq!(peer.next().await["error"]["code"], -32601); + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": MARKER })]) + .await + } + }); + assert!(set.await.unwrap().is_err()); + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.update( + SESSION, + json!({ "sessionUpdate": MARKER, "title": MARKER, "_meta": { "x": MARKER } }), + ) + .await; + peer.fail(&prompt, -32603, &format!("provider failed {MARKER}")) + .await; + events_until(&runtime, "turn.completed").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + runtime.interrupt_turn(None).await.unwrap(); + runtime.abandoned().await; + tracing::info!("the capture saw the run"); + + let log = String::from_utf8(log.0.lock().unwrap().clone()).unwrap(); + assert!(log.contains("the capture saw the run"), "{log}"); + assert!(log.contains("antigravity"), "the runtime logged: {log}"); + assert!(!log.contains(MARKER), "a marker reached the log:\n{log}"); + child.complete(); +} + +#[derive(Clone, Default)] +struct CapturedLog(std::sync::Arc>>); + +impl std::io::Write for CapturedLog { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[test] +fn versions_parse_from_the_first_three_part_number() { + assert_eq!(parse_version("1.5.13"), Some((1, 5, 13))); + assert_eq!(parse_version("v1.5.4-beta"), Some((1, 5, 4))); + assert_eq!(parse_version("1.5"), None); + assert_eq!(parse_version(""), None); +} + +async fn expect_refused_permission(peer: &mut Peer, id: Value) { + let answer = peer.next().await; + assert_eq!(answer["id"], id, "{answer}"); + assert_eq!( + answer["result"], + json!({ "outcome": { "outcome": "cancelled" } }), + "BiBCode refuses instead of approving: {answer}" + ); +} + +async fn spawn_send( + runtime: &AntigravitySessionRuntime, +) -> JoinHandle> { + let runtime = runtime.clone(); + tokio::spawn(async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + }) +} + +#[tokio::test] +async fn requests_outside_an_active_turn_of_the_open_session_are_refused() { + // During the open, before the session is accepted. + let mut resuming = options("full-access"); + resuming.resume_session_id = Some(SESSION.to_owned()); + let (runtime, mut peer) = connect(resuming); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let resume = peer.expect("session/resume").await; + peer.permission(allow_or_deny()).await; + expect_refused_permission(&mut peer, json!("1")).await; + peer.reply( + &resume, + session_result(SESSION, standard_options("default")), + ) + .await; + answer_mode(&mut peer, "auto").await; + finish(start).await.expect("start"); + + // Between turns. + peer.permission(allow_or_deny()).await; + expect_refused_permission(&mut peer, json!("1")).await; + + // For another session, during a turn. + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission_as(json!("2"), "other-session", "edit", allow_or_deny()) + .await; + expect_refused_permission(&mut peer, json!("2")).await; + + // After the turn ended. + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + events_until(&runtime, "turn.completed").await; + peer.permission(allow_or_deny()).await; + expect_refused_permission(&mut peer, json!("1")).await; +} + +#[tokio::test] +async fn requests_after_a_cancel_are_refused_even_once_the_turn_was_abandoned() { + let mut options = options("full-access"); + options.cancel_grace = Duration::from_millis(50); + let (runtime, mut peer) = started_with(options, "auto").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + runtime.interrupt_turn(None).await.expect("cancel sent"); + peer.expect("session/cancel").await; + peer.permission(allow_or_deny()).await; + expect_refused_permission(&mut peer, json!("1")).await; + timeout(Duration::from_secs(2), runtime.abandoned()) + .await + .expect("abandoned"); + peer.permission(allow_or_deny()).await; + expect_refused_permission(&mut peer, json!("1")).await; +} + +#[tokio::test] +async fn plan_mode_or_a_missing_allow_once_leaves_full_access_requests_to_the_user() { + let mut planning = options("full-access"); + planning.interaction_mode = "plan".to_owned(); + let (runtime, mut peer) = started_with(planning, "plan").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(allow_or_deny()).await; + opened_request_id(&runtime).await; + assert!(peer.silent().await, "plan never answers by itself"); + + let (runtime, mut peer) = started("full-access", "auto").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(json!([ + { "optionId": "always", "kind": "allow_always" }, + { "optionId": "deny", "kind": "reject_once" }, + ])) + .await; + opened_request_id(&runtime).await; + assert!(peer.silent().await, "no allow_once, no automatic answer"); +} + +#[tokio::test] +async fn a_failed_switch_keeps_the_new_mode_and_refuses_prompts_until_acknowledged() { + let (runtime, mut peer) = started("approval-required", "default").await; + let switch = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("auto-accept-edits").await } + }); + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["value"], "accept-edits"); + peer.fail(&mode, -32603, "Internal error").await; + assert!(switch.await.unwrap().is_err()); + // No rollback to an older mode: the prompt writes the thread's mode and is refused until + // the CLI acknowledges it. + let send = spawn_send(&runtime).await; + let retry = peer.expect("session/set_config_option").await; + assert_eq!(retry["params"]["value"], "accept-edits"); + peer.reply( + &retry, + json!({ "configOptions": standard_options("default") }), + ) + .await; + assert!( + send.await.unwrap().is_err(), + "a mismatched mode sends no prompt" + ); + assert!(peer.silent().await); +} + +/// A mode write the CLI answers without listing its options confirms nothing: the switch is +/// refused as unavailable, final for the delivery, never read as a write that may be retried. +#[tokio::test] +async fn an_answered_mode_write_without_its_options_is_refused() { + let (runtime, mut peer) = started("full-access", "auto").await; + let switch = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("approval-required").await } + }); + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["value"], "default"); + peer.reply(&mode, json!({})).await; + let error = switch + .await + .unwrap() + .expect_err("an unconfirmed mode refuses"); + assert!( + matches!(error, AntigravityRuntimeError::ModeUnavailable { .. }), + "{error:?}" + ); +} + +/// Mode writes reach the CLI one at a time, and each writes the latest setting: an older +/// switch's answer never confirms a newer one, and a newer switch waits for the older write. +#[tokio::test] +async fn an_older_mode_answer_never_confirms_a_newer_switch() { + let (runtime, mut peer) = started("full-access", "auto").await; + let to_default = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("approval-required").await } + }); + let older = peer.expect("session/set_config_option").await; + assert_eq!(older["params"]["value"], "default"); + let to_auto = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("full-access").await } + }); + assert!( + peer.silent().await, + "the newer write waits for the older one" + ); + peer.reply( + &older, + json!({ "configOptions": standard_options("default") }), + ) + .await; + let _ = timeout(Duration::from_secs(5), to_default) + .await + .expect("older switch in time"); + let newer = peer.expect("session/set_config_option").await; + assert_eq!(newer["params"]["value"], "auto", "the latest setting wins"); + peer.reply(&newer, json!({ "configOptions": standard_options("auto") })) + .await; + timeout(Duration::from_secs(5), to_auto) + .await + .expect("newer switch in time") + .unwrap() + .expect("newer switch acknowledged"); +} + +/// The reverse: a switch to full access in flight when the thread moves back to approval- +/// required. Its `auto` answer confirms nothing, `default` is written after it, and the prompt +/// follows that confirmed `default`, never an `auto` written later. +#[tokio::test] +async fn a_full_access_write_in_flight_never_runs_the_next_prompt_in_auto() { + let (runtime, mut peer) = started("approval-required", "default").await; + let to_auto = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("full-access").await } + }); + let older = peer.expect("session/set_config_option").await; + assert_eq!(older["params"]["value"], "auto"); + let to_default = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_runtime_mode("approval-required").await } + }); + let send = spawn_send(&runtime).await; + assert!( + peer.silent().await, + "nothing is written past the unanswered mode write" + ); + peer.reply(&older, json!({ "configOptions": standard_options("auto") })) + .await; + let _ = timeout(Duration::from_secs(5), to_auto) + .await + .expect("older switch in time"); + let newer = peer.expect("session/set_config_option").await; + assert_eq!(newer["params"]["value"], "default"); + peer.reply( + &newer, + json!({ "configOptions": standard_options("default") }), + ) + .await; + timeout(Duration::from_secs(5), to_default) + .await + .expect("newer switch in time") + .unwrap() + .expect("default acknowledged"); + let prompt = peer.next().await; + assert_eq!(prompt["method"], "session/prompt", "{prompt}"); + drop(send); +} + +#[tokio::test] +async fn every_approval_gets_a_fresh_id_and_ends_with_its_turn() { + let (runtime, mut peer) = started("approval-required", "default").await; + let (_receipt, prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(allow_or_deny()).await; + let first = opened_request_id(&runtime).await; + // The CLI ends the turn without waiting for the answer: the approval closes with it. + peer.reply(&prompt, json!({ "stopReason": "end_turn" })) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert!( + events + .iter() + .any(|(kind, payload)| kind == "request.resolved" + && payload["requestType"] == "file_change_approval"), + "{events:?}" + ); + assert!(runtime.pending_request_ids().await.is_empty()); + + // The next turn reuses wire id "1" for another tool: the old card cannot answer it. + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission_as(json!("1"), SESSION, "execute", allow_or_deny()) + .await; + let second = opened_request_id(&runtime).await; + assert_ne!(first, second); + let stale = runtime + .respond_to_request(&first, "accept") + .await + .expect_err("a closed approval answers nothing"); + assert!( + matches!( + stale, + AntigravityRuntimeError::PendingRequestNotFound { .. } + ), + "{stale:?}" + ); + assert!(peer.silent().await); +} + +#[tokio::test] +async fn numeric_and_string_ids_stay_apart_and_a_duplicate_is_not_recorded() { + let (runtime, mut peer) = started("approval-required", "default").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission_as(json!(1), SESSION, "execute", allow_or_deny()) + .await; + let numeric = opened_request_id(&runtime).await; + peer.permission_as(json!("1"), SESSION, "edit", allow_or_deny()) + .await; + let string = opened_request_id(&runtime).await; + assert_ne!(numeric, string); + // A second outstanding request with the same typed id is refused with an error. + peer.permission_as(json!(1), SESSION, "delete", allow_or_deny()) + .await; + assert_eq!(peer.next().await["error"]["code"], -32600); + assert_eq!(runtime.pending_request_ids().await.len(), 2); + + runtime + .respond_to_request(&string, "decline") + .await + .unwrap(); + let answer = peer.next().await; + assert_eq!(answer["id"], json!("1")); + assert_eq!(answer["result"]["outcome"]["optionId"], "deny"); + runtime + .respond_to_request(&numeric, "accept") + .await + .unwrap(); + let answer = peer.next().await; + assert_eq!(answer["id"], json!(1)); + assert_eq!(answer["result"]["outcome"]["optionId"], "allow"); +} + +#[tokio::test] +async fn a_config_answer_showing_another_mode_blocks_the_next_prompt_until_reconfirmed() { + let (runtime, mut peer) = started("approval-required", "default").await; + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "low" })]) + .await + } + }); + let level = peer.expect("session/set_config_option").await; + assert_eq!(level["params"]["configId"], "thought_level"); + peer.reply(&level, json!({ "configOptions": standard_options("auto") })) + .await; + set.await.unwrap().expect("level written"); + + let send = spawn_send(&runtime).await; + let mode = peer.expect("session/set_config_option").await; + assert_eq!( + mode["params"]["value"], "default", + "the mode is written first" + ); + peer.reply( + &mode, + json!({ "configOptions": standard_options("default") }), + ) + .await; + send.await.unwrap().expect("sent once reconfirmed"); + peer.expect("session/prompt").await; +} + +#[tokio::test] +async fn a_failed_start_leaves_nothing_a_prompt_could_use() { + let (runtime, mut peer) = connect(options("approval-required")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("auto"))) + .await; + let mode = peer.expect("session/set_config_option").await; + peer.fail(&mode, -32602, "Unknown mode: default").await; + finish(start).await.expect_err("refused"); + let refused = timeout( + Duration::from_secs(2), + runtime.send_turn_with_receipt(Some("hello"), Vec::new()), + ) + .await + .expect("refused in time"); + assert!(refused.is_err()); + assert!(peer.silent().await, "no prompt after a failed start"); +} + +#[tokio::test] +async fn a_reopen_answer_naming_another_session_is_a_failure() { + for capabilities in [all_capabilities(), json!({ "loadSession": true })] { + let mut resuming = options("full-access"); + resuming.resume_session_id = Some(SAVED.to_owned()); + let (runtime, mut peer) = connect(resuming); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply(&initialize, initialize_result("1.5.13", 1, capabilities)) + .await; + let open = peer.next().await; + peer.reply( + &open, + session_result("another-session", standard_options("default")), + ) + .await; + let error = finish(start).await.expect_err("a mismatched id"); + assert!( + matches!(error, AntigravityRuntimeError::SessionMismatch), + "{error:?}" + ); + assert!(peer.silent().await, "no new session and no mode write"); + } +} + +#[tokio::test] +async fn a_silent_control_request_ends_in_time_and_unconfirms_the_mode() { + let mut options = options("approval-required"); + options.control_timeout = Duration::from_millis(100); + let (runtime, mut peer) = started_with(options, "default").await; + let set = timeout( + Duration::from_secs(2), + runtime.set_options(vec![json!({ "id": "reasoning", "value": "low" })]), + ); + let (result, _) = tokio::join!(set, peer.expect("session/set_config_option")); + let error = result.expect("bounded").expect_err("no answer"); + assert!( + matches!(error, AntigravityRuntimeError::ControlTimedOut), + "{error:?}" + ); + // The CLI's configuration is unknown now: the next prompt writes the mode first. + let _send = spawn_send(&runtime).await; + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["configId"], "mode"); +} + +#[tokio::test] +async fn the_initial_thinking_level_is_written_during_the_start() { + let level_low = || vec![json!({ "id": "reasoning", "value": "low" })]; + let mut withheld = options("full-access"); + withheld.initial_options = level_low(); + let (runtime, mut peer) = connect(withheld); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + let level = peer.expect("session/set_config_option").await; + assert_eq!(level["params"]["configId"], "thought_level"); + // Withheld: the start keeps waiting; only a stop of the launch ends it. + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + !start.is_finished(), + "a silent level write keeps the start waiting" + ); + start.abort(); + + // Acknowledged: the supervisor's later write of the same level writes nothing. + let mut acknowledged = options("full-access"); + acknowledged.initial_options = level_low(); + let (runtime, mut peer) = connect(acknowledged); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, standard_options("default"))) + .await; + let level = peer.expect("session/set_config_option").await; + let low = config_options( + "test-model-a", + &["low", "medium", "high"], + "low", + "default", + ALL_MODES, + ); + peer.reply(&level, json!({ "configOptions": low })).await; + let mode = peer.expect("session/set_config_option").await; + assert_eq!(mode["params"]["configId"], "mode"); + let auto_at_low = config_options( + "test-model-a", + &["low", "medium", "high"], + "low", + "auto", + ALL_MODES, + ); + peer.reply(&mode, json!({ "configOptions": auto_at_low })) + .await; + finish(start).await.expect("start"); + timeout(Duration::from_secs(2), runtime.set_options(level_low())) + .await + .expect("in time") + .expect("already applied"); + assert!(peer.silent().await); +} + +#[tokio::test] +async fn a_prompt_that_was_never_written_ends_its_turn() { + let (runtime, peer) = started("full-access", "auto").await; + let Peer { + requests, + output: _output, + stderr: _stderr, + } = peer; + // The CLI stopped reading but its stdout stays open: zero bytes of the prompt are written. + drop(requests); + let error = timeout( + Duration::from_secs(2), + runtime.send_turn_with_receipt(Some("hello"), Vec::new()), + ) + .await + .expect("in time") + .expect_err("not written"); + assert!( + matches!(error, AntigravityRuntimeError::Protocol(_)), + "{error:?}" + ); + let events = events_until(&runtime, "turn.completed").await; + assert_eq!(events.last().unwrap().1["state"], "failed"); + timeout(Duration::from_secs(1), runtime.interrupt_turn(None)) + .await + .expect("in time") + .expect("nothing to cancel"); + assert!( + timeout(Duration::from_millis(200), runtime.abandoned()) + .await + .is_err(), + "no active turn is left to cancel or abandon" + ); +} + +#[tokio::test] +async fn the_reader_task_lets_go_of_the_runtime_once_the_connection_closes() { + let (runtime, peer) = started("full-access", "auto").await; + drop(peer); + events_until(&runtime, "session.exited").await; + timeout(Duration::from_secs(2), async { + while Arc::strong_count(&runtime.inner) > 1 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("only the test holds the runtime"); +} + +#[tokio::test] +async fn a_reused_outstanding_id_gets_an_error_and_the_original_stays_bound() { + let (runtime, mut peer) = started("approval-required", "default").await; + let (_receipt, _prompt) = begin_turn(&runtime, &mut peer).await; + peer.permission(allow_or_deny()).await; + let original = opened_request_id(&runtime).await; + // The same id again, for this session and for another one: an error, never `cancelled`. + for session in [SESSION, "other-session"] { + peer.permission_as(json!("1"), session, "execute", allow_or_deny()) + .await; + let answer = peer.next().await; + assert_eq!(answer["id"], json!("1")); + assert_eq!(answer["error"]["code"], -32600, "{answer}"); + assert!(answer.get("result").is_none(), "{answer}"); + } + assert_eq!( + runtime.pending_request_ids().await, + std::slice::from_ref(&original) + ); + runtime + .respond_to_request(&original, "decline") + .await + .unwrap(); + let answer = peer.next().await; + assert_eq!(answer["result"]["outcome"]["optionId"], "deny"); +} + +#[tokio::test] +async fn a_partly_written_prompt_is_ambiguous_not_unsent() { + let (runtime, peer) = started("full-access", "auto").await; + let Peer { + requests, + output: _output, + stderr: _stderr, + } = peer; + let mut reader = requests.into_inner(); + let large = "x".repeat(256 * 1024); + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some(&large), Vec::new()) + .await + } + }); + // The CLI reads part of the prompt, then stops reading. + let mut start = vec![0_u8; 1024]; + timeout( + Duration::from_secs(2), + tokio::io::AsyncReadExt::read_exact(&mut reader, &mut start), + ) + .await + .expect("part of the prompt in time") + .expect("read"); + drop(reader); + let receipt = timeout(Duration::from_secs(2), send) + .await + .expect("in time") + .unwrap() + .expect("a partial write still returns a receipt"); + let outcome = timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("in time"); + assert!(outcome.is_err(), "{outcome:?}"); +} + +#[tokio::test] +async fn a_string_id_response_does_not_complete_a_numeric_request() { + let (runtime, mut peer) = started("full-access", "auto").await; + let (receipt, prompt) = begin_turn(&runtime, &mut peer).await; + let id = prompt["id"].as_u64().expect("numeric request id"); + // The string spelling of the prompt's id answers nothing: the turn is never accepted. + peer.send( + json!({ "jsonrpc": "2.0", "id": id.to_string(), "result": { "stopReason": "end_turn" } }), + ) + .await; + let events = events_until(&runtime, "turn.completed").await; + assert_ne!(events.last().unwrap().1["state"], "completed"); + let outcome = timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("in time"); + assert!(outcome.is_err(), "{outcome:?}"); +} + +/// The options the inventory publishes from uncategorized descriptors reach the session: the +/// model and the thinking level are written to their config ids, not refused. +#[tokio::test] +async fn uncategorized_model_and_level_options_the_inventory_publishes_are_written() { + let mut advertised = super::uncategorized_level_options(); + let mode = standard_options("default")[2].clone(); + advertised.as_array_mut().expect("options").push(mode); + let (runtime, mut peer) = connect(options("approval-required")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.reply(&new, session_result(SESSION, advertised.clone())) + .await; + let confirm = peer.expect("session/set_config_option").await; + assert_eq!(confirm["params"]["configId"], "mode"); + peer.reply(&confirm, json!({ "configOptions": advertised.clone() })) + .await; + assert_eq!(finish(start).await.expect("start"), SESSION); + + let model = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_model("alpha").await } + }); + let write = peer.expect("session/set_config_option").await; + assert_eq!(write["params"]["configId"], "model"); + assert_eq!(write["params"]["value"], "alpha"); + peer.reply(&write, json!({ "configOptions": advertised.clone() })) + .await; + timeout(Duration::from_secs(5), model) + .await + .expect("model write in time") + .unwrap() + .expect("model written"); + + let level = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "extra-high" })]) + .await + } + }); + let write = peer.expect("session/set_config_option").await; + assert_eq!(write["params"]["configId"], "thought_level"); + assert_eq!(write["params"]["value"], "extra-high"); + peer.reply(&write, json!({ "configOptions": advertised })) + .await; + timeout(Duration::from_secs(5), level) + .await + .expect("level write in time") + .unwrap() + .expect("level written"); +} + +/// BiBCode names itself to the CLI at this server's own version. +#[tokio::test] +async fn the_handshake_names_bibcode_at_its_own_version() { + let (runtime, mut peer) = connect(options("full-access")); + let _start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + assert_eq!( + initialize["params"]["clientInfo"], + json!({ "name": "bibcode-rust", "version": env!("CARGO_PKG_VERSION") }) + ); +} + +/// Google's generic notice that an account may no longer use the service. +const ACCOUNT_DISABLED: &str = "This service has been disabled in this account for violation of \ + Terms of Service. Please submit an appeal to continue using this \ + product."; + +/// Google's notice that the account is disabled is its own error, whether an ACP answer or the +/// error output of a CLI that exits carries it. It keeps only Google's notice, never the rest of +/// the line. +#[tokio::test] +async fn a_disabled_account_is_its_own_error() { + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.reply( + &initialize, + initialize_result("1.5.13", 1, all_capabilities()), + ) + .await; + let new = peer.expect("session/new").await; + peer.fail( + &new, + -32603, + &format!("upstream error: {ACCOUNT_DISABLED} (request placeholder-id)"), + ) + .await; + let error = finish(start).await.expect_err("the account is disabled"); + assert_eq!( + error.to_string(), + format!( + "Google has disabled Antigravity for this account. Appeal through Google to restore \ + access. Google's message: {ACCOUNT_DISABLED}" + ) + ); + assert!( + matches!(&error, AntigravityRuntimeError::AccountDisabled { google_message } + if google_message == ACCOUNT_DISABLED), + "{error:?}" + ); + + // Worded a little differently, the notice is still recognised, and only it is kept. + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + let initialize = peer.expect("initialize").await; + peer.fail( + &initialize, + -32603, + "request placeholder-id: Disabled in this account for violation of Terms of Service; \ + contact support", + ) + .await; + let error = finish(start).await.expect_err("the account is disabled"); + assert!( + matches!(&error, AntigravityRuntimeError::AccountDisabled { google_message } + if google_message == "Disabled in this account for violation of Terms of Service"), + "{error:?}" + ); + + // The CLI prints it on its error output and exits before it answers. + let (runtime, mut peer) = connect(options("full-access")); + let start = spawn_start(&runtime); + peer.expect("initialize").await; + peer.stderr + .write_all(format!("Error: {ACCOUNT_DISABLED}\n").as_bytes()) + .await + .expect("stderr write"); + tokio::time::sleep(Duration::from_millis(200)).await; + drop(peer); + let error = finish(start).await.expect_err("the CLI exited"); + assert!( + matches!(&error, AntigravityRuntimeError::AccountDisabled { google_message } + if google_message == ACCOUNT_DISABLED), + "{error:?}" + ); +} diff --git a/apps/server/src/provider/codex/runtime.rs b/apps/server/src/provider/codex/runtime.rs index 609700463b..1710d81b2f 100644 --- a/apps/server/src/provider/codex/runtime.rs +++ b/apps/server/src/provider/codex/runtime.rs @@ -4608,7 +4608,9 @@ mod tests { .expect_err("an unadvertised service tier is refused"); assert_eq!( refused.option_refusal(), - Some("Service Tier slow is not supported by the selected model.") + Some( + "Service Tier slow is not supported by the selected model. Choose another option for this model." + ) ); // A model the list does not offer is refused on every retry too, naming the instance. let missing = runtime diff --git a/apps/server/src/provider/cursor/acp.rs b/apps/server/src/provider/cursor/acp.rs index 38d2a97f6f..22985c1a86 100644 --- a/apps/server/src/provider/cursor/acp.rs +++ b/apps/server/src/provider/cursor/acp.rs @@ -152,6 +152,8 @@ enum WriterMessage { bytes: Vec, written: oneshot::Sender>, }, + /// Ends the writer task, which owns the agent's stdin. + Shutdown, } #[derive(Debug)] @@ -166,6 +168,17 @@ impl AcpRequestWriteFailure { self.bytes_written == Some(0) } + /// A write whose outcome is unknown: some of it may have reached the agent. + #[must_use] + pub fn unconfirmed(message: &str) -> Self { + Self { + error: AcpProtocolError::WriteFailure { + message: message.to_owned(), + }, + bytes_written: None, + } + } + #[must_use] pub fn into_error(self) -> AcpProtocolError { self.error @@ -179,12 +192,16 @@ pub struct AcpRequestReceipt { } impl AcpRequestReceipt { + /// Cancel-safe: a caller that stops waiting, such as a timeout, can wait again and still gets + /// the writer's answer. The confirmation is dropped only once it has resolved. #[allow(clippy::result_large_err)] pub async fn written(&mut self) -> Result<(), AcpRequestWriteFailure> { - let Some(written) = self.written.take() else { + let Some(written) = self.written.as_mut() else { return Ok(()); }; - match written.await { + let confirmation = written.await; + self.written = None; + match confirmation { Ok(result) => result, Err(_) => { self.registration.remove(); @@ -331,6 +348,7 @@ impl AcpJsonRpcConnection { } let _ = written.send(Ok(())); } + WriterMessage::Shutdown => break, } } }); @@ -377,6 +395,13 @@ impl AcpJsonRpcConnection { (connection, incoming_rx) } + /// Ends the writer task and closes the agent's stdin; later writes fail as closed. The + /// writer holds this connection's own sender, so without it the task and the pipe outlive + /// the agent. The readers end when the agent's output closes. Safe to call from `Drop`. + pub fn shutdown(&self) { + let _ = self.inner.writer.send(WriterMessage::Shutdown); + } + pub async fn request(&self, method: &str, params: Value) -> Result { let mut receipt = self.start_request(method, params).await?; receipt @@ -603,9 +628,13 @@ async fn route_stdout_message( if let Some(wire_id) = object.get("id") { let correlation_id = normalize_request_id(wire_id)?; - let pending = inner.pending().remove(&correlation_id); + // Outbound ids are numbers: a string id answers none of them, whatever its text. + let outbound = wire_id.is_number(); + let pending = outbound + .then(|| inner.pending().remove(&correlation_id)) + .flatten(); let Some(pending) = pending else { - if is_stale_outbound_response(&correlation_id, inner) { + if outbound && is_stale_outbound_response(&correlation_id, inner) { return Ok(()); } return Err(AcpProtocolError::UnknownResponse { @@ -1039,6 +1068,34 @@ mod tests { ); } + /// Outbound ids are numbers, so a response whose id is the string "1" never answers request + /// 1: it is not correlated, and the request never takes its result. + #[tokio::test] + async fn a_string_response_id_never_answers_a_numeric_request() { + let (stdout, mut stdout_peer) = duplex(4096); + let (_stdin_peer, stdin) = duplex(4096); + let (stderr, _stderr_peer) = duplex(4096); + let (connection, _incoming) = + AcpJsonRpcConnection::spawn(stdout, stdin, stderr, AcpConnectionConfig::default()); + let mut receipt = connection + .start_request("session/new", json!({})) + .await + .expect("request receipt"); + receipt.written().await.expect("request written"); + + stdout_peer + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":{\"forged\":true}}\n") + .await + .expect("write string-id response"); + stdout_peer.flush().await.expect("flush string-id response"); + + assert!(matches!( + receipt.response().await, + Err(AcpProtocolError::Closed { reason }) + if reason.contains("response for id 1 was not correlated") + )); + } + #[tokio::test] async fn genuinely_unknown_response_id_fails_connection_closed() { let (stdout, mut stdout_peer) = duplex(4096); diff --git a/apps/server/src/provider/cursor/mod.rs b/apps/server/src/provider/cursor/mod.rs index 19a6aca101..73d8266ca1 100644 --- a/apps/server/src/provider/cursor/mod.rs +++ b/apps/server/src/provider/cursor/mod.rs @@ -11,10 +11,10 @@ pub use capabilities::{ }; #[cfg_attr(test, allow(unused_imports))] pub use model::{ - CursorAboutResult, CursorProviderModel, CursorProviderSnapshot, + CursorAboutResult, CursorProviderModel, CursorProviderSnapshot, advertised_model_values, build_capabilities_from_config_options, discover_models_from_list_available_models, - parse_about_output, parse_cli_config_channel, parse_version_date, resolve_acp_base_model_id, - resolve_acp_config_updates, + discover_models_with_advertised_values, parse_about_output, parse_cli_config_channel, + parse_version_date, resolve_acp_base_model_id, resolve_acp_config_updates, }; #[cfg_attr(test, allow(unused_imports))] pub use runtime::{ diff --git a/apps/server/src/provider/cursor/model.rs b/apps/server/src/provider/cursor/model.rs index 567d63590d..c3237829cc 100644 --- a/apps/server/src/provider/cursor/model.rs +++ b/apps/server/src/provider/cursor/model.rs @@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::provider::{ - RefusedOption, option_needs_value_refusal, option_on_or_off_refusal, option_without_id_refusal, - unsupported_option_refusal, + RefusedOption, model_unavailable_refusal, option_needs_value_refusal, option_on_or_off_refusal, + option_without_id_refusal, unsupported_option_refusal, }; /// BiBCode's labels for Cursor's options, used when the session gives an option no name of its @@ -15,6 +15,11 @@ pub(crate) const CONTEXT_LABEL: &str = "Context"; pub(crate) const FAST_LABEL: &str = "Fast"; pub(crate) const THINKING_LABEL: &str = "Thinking"; +/// Shown when a turn that clears its options cannot go back to the model's defaults, which the +/// session no longer offers: Cursor keeps the options it uses now. +pub const CLEARED_OPTIONS_KEPT_NOTE: &str = + "Cursor no longer offers this model's previous default options, so it keeps its current ones."; + #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct CursorAboutResult { @@ -155,80 +160,411 @@ pub fn resolve_acp_base_model_id(model_id: &str) -> String { .to_owned() } +/// A bracketed model value's base and its `key=value` parameters, such as +/// `gpt-5.4[context=272k,reasoning=medium]`; `None` for a plain value. +fn bracketed_model_value(value: &str) -> Option<(&str, Vec<(&str, &str)>)> { + let (base, rest) = value.split_once('[')?; + let params = rest + .strip_suffix(']')? + .split(',') + .filter_map(|param| param.split_once('=')) + .map(|(key, value)| (key.trim(), value.trim())) + .collect(); + Some((base.trim(), params)) +} + +/// The session's model config option. +pub fn acp_model_descriptor(options: &[Value]) -> Option<&Value> { + options + .iter() + .find(|option| option.get("category").and_then(Value::as_str) == Some("model")) +} + +/// The model values a `session/new` or `session/load` answer advertises. +pub fn advertised_model_values(session: &Value) -> Vec { + session + .get("configOptions") + .and_then(Value::as_array) + .and_then(|options| acp_model_descriptor(options)) + .map(|descriptor| { + advertised_values(descriptor) + .into_iter() + .filter_map(|value| value.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +/// Whether the session folds a model's options into its model values, as Cursor CLIs since +/// 2026.11 do (`gpt-5.4-nano[reasoning=medium]`), instead of advertising them as options. +pub fn acp_model_values_are_bracketed(options: &[Value]) -> bool { + acp_model_descriptor(options).is_some_and(|descriptor| { + advertised_values(descriptor) + .iter() + .any(|value| value.as_str().is_some_and(|value| value.contains('['))) + }) +} + +/// The advertised model value for the chosen `model`: the value itself when advertised, otherwise +/// the value whose base is `model` (the inventory publishes bases), the session's current one +/// first. A model the session does not advertise is refused, so BiBCode never sends a value the +/// CLI did not offer; an option listing no values advertises only its current value. +pub fn resolve_advertised_model_value( + descriptor: &Value, + model: &str, +) -> Result { + let current = descriptor.get("currentValue"); + let mut advertised = advertised_values(descriptor); + if advertised.is_empty() { + advertised.extend(current.cloned()); + } + let model = model.trim(); + if advertised.iter().any(|value| value.as_str() == Some(model)) { + return Ok(json!(model)); + } + let base_of = |value: &Value| value.as_str().map(resolve_acp_base_model_id); + current + .filter(|current| { + advertised.contains(current) && base_of(current).as_deref() == Some(model) + }) + .cloned() + .or_else(|| { + advertised + .iter() + .find(|value| base_of(value).as_deref() == Some(model)) + .cloned() + }) + .ok_or_else(|| { + RefusedOption::new( + format!("Cursor session does not advertise model {model}"), + model_unavailable_refusal(model, "Cursor"), + ) + }) +} + +/// A model saved as a bracketed value, such as `grok-4.7[context=256k,reasoning_effort=high]`, +/// for a session that advertises plain model values: its base and its parameters as the turn +/// options they mean, which the runtime checks against the session like any other option. +/// `None` for a plain saved model, a session that advertises bracketed values itself, or a base +/// the session does not advertise, which is then refused under the saved name as before. +pub fn split_saved_bracketed_model(options: &[Value], model: &str) -> Option<(String, Vec)> { + let descriptor = acp_model_descriptor(options)?; + if acp_model_values_are_bracketed(options) { + return None; + } + let (base, params) = bracketed_model_value(model.trim())?; + if !advertised_values(descriptor).contains(&json!(base)) { + return None; + } + let updates = params + .into_iter() + .map(|(key, value)| { + let on_off = |value: &str| match value { + "true" => json!(true), + "false" => json!(false), + // Not on/off: the option resolver refuses it. + other => json!(other), + }; + match key { + key if REASONING_KEYS.contains(&key) => { + json!({ "id": "reasoning", "value": value }) + } + "context" => json!({ "id": "contextWindow", "value": value }), + "fast" => json!({ "id": "fastMode", "value": on_off(value) }), + "thinking" => json!({ "id": "thinking", "value": on_off(value) }), + // An unknown parameter is refused as an option the session does not support. + key => json!({ "id": key, "value": value }), + } + }) + .collect(); + Some((base.to_owned(), updates)) +} + +/// A turn's options checked against a session that folds options into its model values: the +/// advertised value with the current model's base whose parameters hold every requested option, +/// the current value first. `Ok(None)` when the current value already holds them, `Ok(Some)` with +/// the value to switch to otherwise. An option the turn leaves out goes back to the model's +/// `baseline` value, as a session with separate options resets it. An option no advertised value +/// of the model holds is refused: BiBCode never composes a value the CLI did not offer. +pub fn resolve_bracketed_model_options( + descriptor: &Value, + updates: &Value, + baseline: Option<&str>, +) -> Result, RefusedOption> { + let Some(updates) = updates.as_array() else { + return Err(RefusedOption::unusable( + "Cursor option updates must be an array", + )); + }; + let current = descriptor + .get("currentValue") + .and_then(Value::as_str) + .ok_or_else(|| { + RefusedOption::unusable("Cursor model config option has no current value") + })?; + let base = resolve_acp_base_model_id(current); + let mut wanted = Vec::new(); + for update in updates { + let (keys, label, value): (&[&str], &str, String) = + match update.get("id").and_then(Value::as_str) { + Some("reasoning") => ( + REASONING_KEYS, + REASONING_LABEL, + update + .get("value") + .and_then(Value::as_str) + .ok_or_else(|| { + RefusedOption::new( + "Cursor reasoning option must be a string", + option_needs_value_refusal(REASONING_LABEL), + ) + })? + .to_owned(), + ), + Some("contextWindow") => ( + &["context"], + CONTEXT_LABEL, + update + .get("value") + .and_then(Value::as_str) + .ok_or_else(|| { + RefusedOption::new( + "Cursor context window option is missing a value", + option_needs_value_refusal(CONTEXT_LABEL), + ) + })? + .to_owned(), + ), + Some(id @ ("fastMode" | "thinking")) => { + let label = if id == "fastMode" { + FAST_LABEL + } else { + THINKING_LABEL + }; + let value = update + .get("value") + .and_then(Value::as_bool) + .ok_or_else(|| { + RefusedOption::new( + format!("Cursor {id} option must be boolean"), + option_on_or_off_refusal(label), + ) + })?; + let keys: &[&str] = if id == "fastMode" { + &["fast"] + } else { + &["thinking"] + }; + (keys, label, value.to_string()) + } + Some(id) => { + return Err(RefusedOption::new( + format!("Cursor does not support option {id}"), + unsupported_option_refusal(id), + )); + } + None => { + return Err(RefusedOption::new( + "Cursor option is missing an id", + option_without_id_refusal(), + )); + } + }; + wanted.push((keys, label, value)); + } + let baseline = baseline.filter(|baseline| resolve_acp_base_model_id(baseline) == base); + let advertised = advertised_values(descriptor) + .into_iter() + .filter_map(|value| value.as_str().map(str::to_owned)) + .collect::>(); + // The baseline was read before later switches: it is a value to send only while the latest + // answer still advertises it. + let candidates = baseline + .filter(|baseline| advertised.iter().any(|value| value == baseline)) + .into_iter() + .map(str::to_owned) + .chain(std::iter::once(current.to_owned())) + .chain(advertised) + .filter(|value| resolve_acp_base_model_id(value) == base) + .collect::>(); + let holds = |value: &str, (keys, _, wanted): &(&[&str], &str, String)| { + bracketed_model_value(value).is_some_and(|(_, params)| { + params.iter().any(|(key, value)| { + keys.contains(key) + && (value == wanted || (wanted == "xhigh" && *value == "extra-high")) + }) + }) + }; + // Every option the turn leaves out keeps the baseline's value, when an advertised value can. + let keeps_baseline = |value: &str| { + let (Some((_, own)), Some((_, base_params))) = ( + bracketed_model_value(value), + baseline.and_then(bracketed_model_value), + ) else { + return true; + }; + base_params.iter().all(|(key, base_value)| { + wanted.iter().any(|(keys, _, _)| keys.contains(key)) + || own.contains(&(*key, *base_value)) + }) + }; + let holds_all = |value: &&String| wanted.iter().all(|option| holds(value, option)); + // Cleared options go back to the baseline only while the latest answer still offers it; + // otherwise Cursor keeps its current value. + if wanted.is_empty() && cleared_options_lose_the_baseline(descriptor, baseline) { + return Ok(None); + } + if let Some(value) = candidates + .iter() + .filter(holds_all) + .find(|value| keeps_baseline(value)) + .or_else(|| candidates.iter().find(holds_all)) + { + return Ok((value != current).then(|| json!(value))); + } + // Name the first option no value of the model holds: unknown to the model, or not this value. + let (keys, label, value) = wanted + .iter() + .find(|option| !candidates.iter().any(|value| holds(value, option))) + .unwrap_or(&wanted[0]); + let known = candidates.iter().any(|candidate| { + bracketed_model_value(candidate) + .is_some_and(|(_, params)| params.iter().any(|(key, _)| keys.contains(key))) + }); + let option = if !known || matches!(*label, FAST_LABEL | THINKING_LABEL) { + (*label).to_owned() + } else { + format!("{label} {value}") + }; + Err(RefusedOption::new( + format!("Cursor session does not advertise {base} with {label} {value}"), + unsupported_option_refusal(&option), + )) +} + +/// Whether clearing every option can no longer go back to `baseline`, the model's value when the +/// session started: the latest answer advertises neither it nor, for a bracketed baseline, a +/// value of the model that holds its options. Cursor then keeps its current value. +pub fn cleared_options_lose_the_baseline(descriptor: &Value, baseline: Option<&str>) -> bool { + let Some(current) = descriptor.get("currentValue").and_then(Value::as_str) else { + return false; + }; + let base = resolve_acp_base_model_id(current); + let Some(baseline) = baseline.filter(|baseline| resolve_acp_base_model_id(baseline) == base) + else { + return false; + }; + let advertised = advertised_values(descriptor) + .into_iter() + .filter_map(|value| value.as_str().map(str::to_owned)) + .collect::>(); + if advertised.iter().any(|value| value == baseline) { + return false; + } + let Some((_, base_params)) = bracketed_model_value(baseline) else { + return true; + }; + // As the resolver keeps the baseline: a value of the model that holds every baseline option. + !std::iter::once(current.to_owned()) + .chain(advertised) + .filter(|value| resolve_acp_base_model_id(value) == base) + .any(|value| { + bracketed_model_value(&value) + .is_none_or(|(_, own)| base_params.iter().all(|param| own.contains(param))) + }) +} + pub fn build_capabilities_from_config_options(options: &Value) -> Value { let Some(options) = options.as_array() else { return json!({ "optionDescriptors": [] }); }; - let mut descriptors = Vec::new(); - let reasoning_source = options + let descriptors = published_options(options) + .into_iter() + .map(|(id, default_label, option)| { + let label = option_label(option, default_label); + match id { + "reasoning" | "contextWindow" => select_descriptor( + id, + label, + option + .get("options") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + option.get("currentValue").and_then(Value::as_str), + ), + _ => boolean_descriptor(id, label, option.get("currentValue")), + } + }) + .collect::>(); + json!({ "optionDescriptors": descriptors }) +} + +/// The config options the descriptors publish, each with its descriptor id and default label, at +/// most one per descriptor: Reasoning first, then Context, Fast and Thinking as listed. Every +/// other option is the CLI's own and is left out. +fn published_options(options: &[Value]) -> Vec<(&'static str, &'static str, &Value)> { + let mut published = reasoning_option(options) + .map(|option| ("reasoning", REASONING_LABEL, option)) + .into_iter() + .collect::>(); + for option in options { + let (descriptor, label) = match (category(option), id(option)) { + (Some("model_config"), Some("context")) => ("contextWindow", CONTEXT_LABEL), + (Some("model_config"), Some("fast")) => ("fastMode", FAST_LABEL), + (Some("model_config" | "thought_level"), Some("thinking")) => { + ("thinking", THINKING_LABEL) + } + _ => continue, + }; + if !published.iter().any(|(id, _, _)| *id == descriptor) { + published.push((descriptor, label, option)); + } + } + published +} + +fn category(option: &Value) -> Option<&str> { + option.get("category").and_then(Value::as_str) +} + +fn id(option: &Value) -> Option<&str> { + option.get("id").and_then(Value::as_str) +} + +/// The option the descriptors publish as Reasoning, whatever the session calls it: `effort`, +/// `reasoning` or `reasoning_effort`. +fn reasoning_option(options: &[Value]) -> Option<&Value> { + options .iter() - .find(|option| { - matches!( - option.get("category").and_then(Value::as_str), - Some("model_option") - ) && option.get("id").and_then(Value::as_str) == Some("effort") + .find(|option| category(option) == Some("model_option") && id(option) == Some("effort")) + .or_else(|| { + options.iter().find(|option| { + category(option) == Some("thought_level") + && id(option).is_some_and(|id| REASONING_KEYS.contains(&id)) + }) }) .or_else(|| { + // Cursor lists Thinking as a `thought_level` too; it is the on/off option. options.iter().find(|option| { - matches!( - option.get("category").and_then(Value::as_str), - Some("thought_level") - ) + category(option) == Some("thought_level") && id(option) != Some("thinking") }) - }); - if let Some(reasoning) = reasoning_source { - descriptors.push(select_descriptor( - "reasoning", - reasoning - .get("name") - .and_then(Value::as_str) - .unwrap_or(REASONING_LABEL), - reasoning - .get("options") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(), - reasoning.get("currentValue").and_then(Value::as_str), - )); - } - for option in options { - match ( - option.get("category").and_then(Value::as_str), - option.get("id").and_then(Value::as_str), - ) { - (Some("model_config"), Some("context")) => descriptors.push(select_descriptor( - "contextWindow", - option - .get("name") - .and_then(Value::as_str) - .unwrap_or(CONTEXT_LABEL), - option - .get("options") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(), - option.get("currentValue").and_then(Value::as_str), - )), - (Some("model_config"), Some("fast")) => descriptors.push(boolean_descriptor( - "fastMode", - option - .get("name") - .and_then(Value::as_str) - .unwrap_or(FAST_LABEL), - option.get("currentValue"), - )), - (Some("model_config"), Some("thinking")) => descriptors.push(boolean_descriptor( - "thinking", - option - .get("name") - .and_then(Value::as_str) - .unwrap_or(THINKING_LABEL), - option.get("currentValue"), - )), - _ => {} - } + }) +} + +/// `xhigh` and `extra-high` name one Reasoning value: send the one the option advertises. +fn advertised_reasoning_value<'a>(descriptor: &Value, value: &'a str) -> &'a str { + let alias = match value { + "xhigh" => "extra-high", + "extra-high" => "xhigh", + _ => return value, + }; + let advertised = advertised_values(descriptor); + if !advertised.contains(&json!(value)) && advertised.contains(&json!(alias)) { + alias + } else { + value } - json!({ "optionDescriptors": descriptors }) } /// Resolves a turn's options into Cursor config updates, checked against what the session @@ -256,29 +592,25 @@ pub fn resolve_acp_config_updates( for update in updates { let (config_id, value) = match update.get("id").and_then(Value::as_str) { Some("reasoning") => { - let (config_id, descriptor) = if let Some(descriptor) = - options.iter().find(|option| { - option.get("category").and_then(Value::as_str) == Some("model_option") - && option.get("id").and_then(Value::as_str) == Some("effort") - }) { - ("effort", descriptor) - } else { - ( + // The same option the descriptors publish as Reasoning; without one, the + // lookup below refuses as before. + let descriptor = match reasoning_option(options) { + Some(descriptor) => descriptor, + None => requested_config_option( + options, "reasoning", - requested_config_option( - options, - "reasoning", - "thought_level", - REASONING_LABEL, - )?, - ) + &["thought_level"], + REASONING_LABEL, + )?, }; + let config_id = id(descriptor).unwrap_or("reasoning"); let label = option_label(descriptor, REASONING_LABEL); ensure_select_config_option(descriptor, config_id) .map_err(RefusedOption::unusable)?; let (requested, value) = match update.get("value") { - Some(Value::String(value)) if value == "xhigh" => (value, json!("extra-high")), - Some(Value::String(value)) => (value, json!(value)), + Some(Value::String(value)) => { + (value, json!(advertised_reasoning_value(descriptor, value))) + } None => { return Err(RefusedOption::new( "Cursor reasoning option is missing a value", @@ -302,7 +634,7 @@ pub fn resolve_acp_config_updates( } Some("contextWindow") => { let descriptor = - requested_config_option(options, "context", "model_config", CONTEXT_LABEL)?; + requested_config_option(options, "context", &["model_config"], CONTEXT_LABEL)?; let label = option_label(descriptor, CONTEXT_LABEL); ensure_select_config_option(descriptor, "context") .map_err(RefusedOption::unusable)?; @@ -323,7 +655,7 @@ pub fn resolve_acp_config_updates( } Some("fastMode") => { let descriptor = - requested_config_option(options, "fast", "model_config", FAST_LABEL)?; + requested_config_option(options, "fast", &["model_config"], FAST_LABEL)?; let label = option_label(descriptor, FAST_LABEL); ensure_select_config_option(descriptor, "fast").map_err(RefusedOption::unusable)?; let value = update @@ -340,8 +672,12 @@ pub fn resolve_acp_config_updates( ("fast", value) } Some("thinking") => { - let descriptor = - requested_config_option(options, "thinking", "model_config", THINKING_LABEL)?; + let descriptor = requested_config_option( + options, + "thinking", + &["model_config", "thought_level"], + THINKING_LABEL, + )?; let label = option_label(descriptor, THINKING_LABEL); ensure_select_config_option(descriptor, "thinking") .map_err(RefusedOption::unusable)?; @@ -377,13 +713,15 @@ pub fn resolve_acp_config_updates( } /// [`resolve_acp_config_updates`], plus the updates that restore every supported option the turn -/// leaves out to the session's baseline. Restoring depends only on the session's configuration, -/// so a failure there is a configuration BiBCode can't work with. +/// leaves out to the session's baseline, and whether one could not be restored. The baseline was +/// read when the session started: an option whose baseline value the latest answer no longer +/// offers keeps its current value. Restoring depends only on the session's configuration, so a +/// failure there is a configuration BiBCode can't work with. pub fn resolve_acp_config_updates_with_baseline( options: &Value, baseline: &Value, updates: &Value, -) -> Result, RefusedOption> { +) -> Result<(Vec, bool), RefusedOption> { let mut resolved = resolve_acp_config_updates(options, updates)?; let requested_config_ids = resolved .iter() @@ -397,7 +735,11 @@ pub fn resolve_acp_config_updates_with_baseline( let baseline = baseline.as_array().ok_or_else(|| { RefusedOption::unusable("Cursor session did not advertise baseline config options") })?; + let latest = options.as_array().ok_or_else(|| { + RefusedOption::unusable("Cursor session did not advertise config options") + })?; + let mut kept = false; for (config_id, category) in supported_baseline_config_options(baseline) { if requested_config_ids .iter() @@ -405,20 +747,24 @@ pub fn resolve_acp_config_updates_with_baseline( { continue; } - let descriptor = expected_config_option(baseline, config_id, category) - .map_err(RefusedOption::unusable)?; - ensure_select_config_option(descriptor, config_id).map_err(RefusedOption::unusable)?; let baseline_value = acp_config_option_baseline_value(baseline, config_id) .map_err(RefusedOption::unusable)?; - ensure_advertised_value(descriptor, &baseline_value, config_id) - .map_err(RefusedOption::unusable)?; + let Ok(descriptor) = expected_config_option(latest, config_id, category) else { + kept = true; + continue; + }; + ensure_select_config_option(descriptor, config_id).map_err(RefusedOption::unusable)?; + if ensure_advertised_value(descriptor, &baseline_value, config_id).is_err() { + kept = true; + continue; + } let current_value = acp_config_option_current_value(options, config_id)?; if current_value != baseline_value { resolved.push(json!({ "configId": config_id, "value": baseline_value })); } } - Ok(resolved) + Ok((resolved, kept)) } pub fn resolve_acp_default_model_config(options: &Value) -> Result<(String, Value), String> { @@ -434,13 +780,16 @@ pub fn resolve_acp_default_model_config(options: &Value) -> Result<(String, Valu .and_then(Value::as_str) .map(str::to_owned) .ok_or_else(|| "Cursor model config option is missing an id".to_owned())?; - let value = descriptor - .get("options") - .and_then(Value::as_array) - .into_iter() - .flatten() - .find(|option| option.get("isDefault") == Some(&Value::Bool(true))) - .and_then(advertised_option_value) + let value = advertised_auto_model_value(descriptor) + .or_else(|| { + descriptor + .get("options") + .and_then(Value::as_array) + .into_iter() + .flatten() + .find(|option| option.get("isDefault") == Some(&Value::Bool(true))) + .and_then(advertised_option_value) + }) .filter(|value| !value.is_null()) .or_else(|| { descriptor @@ -456,6 +805,16 @@ pub fn resolve_acp_default_model_config(options: &Value) -> Result<(String, Valu Ok((config_id, value)) } +/// Cursor's own Auto model as the session advertises it (`default[]` since 2026.11), so Auto never +/// means the model the CLI last remembered as current. +pub fn advertised_auto_model_value(descriptor: &Value) -> Option { + advertised_values(descriptor).into_iter().find(|value| { + value + .as_str() + .is_some_and(|value| resolve_acp_base_model_id(value) == "default") + }) +} + /// The session's current value for an option it advertises, or its advertised default. Its /// absence is a session configuration BiBCode can't work with. pub fn acp_config_option_current_value( @@ -493,25 +852,27 @@ pub fn acp_config_option_current_value( }) } -fn supported_baseline_config_options(options: &[Value]) -> Vec<(&'static str, &'static str)> { - let mut supported = Vec::new(); - if options.iter().any(|option| { - option.get("id").and_then(Value::as_str) == Some("effort") - && option.get("category").and_then(Value::as_str) == Some("model_option") - }) { - supported.push(("effort", "model_option")); - } else if options.iter().any(|option| { - option.get("id").and_then(Value::as_str) == Some("reasoning") - && option.get("category").and_then(Value::as_str) == Some("thought_level") - }) { - supported.push(("reasoning", "thought_level")); +/// The config id and category of each option a turn can set, found as the resolver finds them, +/// so an option the turn sets is never also restored. +fn supported_baseline_config_options(options: &[Value]) -> Vec<(&str, &str)> { + fn id_and_category(option: &Value) -> Option<(&str, &str)> { + Some((id(option)?, category(option)?)) } + let mut supported = reasoning_option(options) + .and_then(id_and_category) + .into_iter() + .collect::>(); for config_id in ["context", "fast", "thinking"] { - if options.iter().any(|option| { - option.get("id").and_then(Value::as_str) == Some(config_id) - && option.get("category").and_then(Value::as_str) == Some("model_config") - }) { - supported.push((config_id, "model_config")); + if let Some(found) = options + .iter() + .filter_map(id_and_category) + .find(|(id, category)| { + *id == config_id + && (*category == "model_config" + || (config_id == "thinking" && *category == "thought_level")) + }) + { + supported.push(found); } } supported @@ -546,7 +907,7 @@ fn acp_config_option_baseline_value(options: &[Value], config_id: &str) -> Resul fn requested_config_option<'a>( options: &'a [Value], config_id: &str, - category: &str, + categories: &[&str], label: &str, ) -> Result<&'a Value, RefusedOption> { let descriptor = options @@ -558,7 +919,7 @@ fn requested_config_option<'a>( unsupported_option_refusal(label), ) })?; - if descriptor.get("category").and_then(Value::as_str) != Some(category) { + if !category(descriptor).is_some_and(|category| categories.contains(&category)) { return Err(RefusedOption::unusable(format!( "Cursor config option {config_id} has an unsupported category" ))); @@ -655,11 +1016,28 @@ fn advertised_option_value(option: &Value) -> Option { pub fn discover_models_from_list_available_models( response: &Value, custom_models: &[String], +) -> Result, String> { + discover_models_with_advertised_values(response, custom_models, &[]) +} + +/// The models `cursor/list_available_models` lists, narrowed to what a session advertises. +/// When the session folds options into bracketed model values, a model is published only with +/// the option values some advertised value of its base carries, so the picker cannot offer a +/// combination the runtime refuses; a model or custom model the session does not offer is left +/// out. Plain advertised values, or none (the session could not be read), publish the list as is. +pub fn discover_models_with_advertised_values( + response: &Value, + custom_models: &[String], + advertised: &[String], ) -> Result, String> { let models = response .get("models") .and_then(Value::as_array) .ok_or_else(|| "cursor/list_available_models response missing models".to_owned())?; + let bracketed = advertised + .iter() + .filter_map(|value| bracketed_model_value(value)) + .collect::>(); let mut discovered = Vec::new(); let mut seen = std::collections::BTreeSet::new(); for model in models { @@ -668,24 +1046,58 @@ pub fn discover_models_from_list_available_models( .and_then(Value::as_str) .ok_or_else(|| "cursor model missing value".to_owned())?; let name = model.get("name").and_then(Value::as_str).unwrap_or(slug); + let base = resolve_acp_base_model_id(slug); + let config_options = model + .get("configOptions") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let config_options = if bracketed.is_empty() { + config_options + } else { + let carriers = bracketed + .iter() + .filter(|(carrier, _)| *carrier == base) + .map(|(_, params)| params.as_slice()) + .collect::>(); + if carriers.is_empty() { + // A plain advertised value keeps its model, with no option a bracketed session + // could apply to it. + if !advertised.contains(&base) { + continue; + } + Vec::new() + } else { + narrow_config_options(config_options, &carriers) + } + }; discovered.push(CursorProviderModel { - slug: resolve_acp_base_model_id(slug), + slug: base.clone(), name: name.to_owned(), is_custom: false, - capabilities: build_capabilities_from_config_options(&json!( - model - .get("configOptions") - .cloned() - .unwrap_or(Value::Array(Vec::new())) - )), + capabilities: build_capabilities_from_config_options(&Value::Array(config_options)), }); - seen.insert(resolve_acp_base_model_id(slug)); + seen.insert(base); } for custom in custom_models { let trimmed = custom.trim(); if trimmed.is_empty() || seen.contains(trimmed) { continue; } + // Over a plain session a bracketed custom model runs as its listed base plus options. + if !advertised.is_empty() + && bracketed.is_empty() + && seen.contains(&resolve_acp_base_model_id(trimmed)) + { + continue; + } + let offered = bracketed.is_empty() + || advertised + .iter() + .any(|value| value == trimmed || resolve_acp_base_model_id(value) == trimmed); + if !offered { + continue; + } discovered.push(CursorProviderModel { slug: trimmed.to_owned(), name: trimmed.to_owned(), @@ -696,6 +1108,122 @@ pub fn discover_models_from_list_available_models( Ok(discovered) } +/// Bracket keys that all mean Reasoning, as the runtime reads them. +const REASONING_KEYS: &[&str] = &["reasoning", "effort", "reasoning_effort"]; + +/// Whether a bracket parameter carries an option's value, with the aliases the runtime accepts. +fn carries(params: &[(&str, &str)], id: &str, value: &str) -> bool { + params.iter().any(|(key, carried)| { + (*key == id || (REASONING_KEYS.contains(key) && REASONING_KEYS.contains(&id))) + && (*carried == value + || matches!( + (*carried, value), + ("extra-high", "xhigh") | ("xhigh", "extra-high") + )) + }) +} + +/// A model's listed options, each keeping only the values one of its advertised bracketed values +/// carries under the option's id (the bracket keys are the CLI's option ids). An option no value +/// carries is dropped, as is an on/off option left with one state, which a toggle cannot show. +/// The picker sets each option on its own, so only the largest set of options whose every +/// combination some advertised value holds is published; the runtime reads an omitted option as +/// no constraint. A narrowed option's current value is one it keeps. +fn narrow_config_options(options: Vec, carriers: &[&[(&str, &str)]]) -> Vec { + // Only the options the descriptors publish take part: one the CLI keeps to itself could + // otherwise win the search below and drop a published one. + let narrowed = published_options(&options) + .into_iter() + .map(|(_, _, option)| option.clone()) + .filter_map(|mut option| { + let id = option.get("id").and_then(Value::as_str)?.to_owned(); + let carried = |value: &str| carriers.iter().any(|params| carries(params, &id, value)); + let kept = option + .get("options") + .and_then(Value::as_array)? + .iter() + .filter(|choice| { + choice + .get("value") + .and_then(Value::as_str) + .is_some_and(carried) + }) + .cloned() + .collect::>(); + let on_off = kept.iter().all(|choice| { + matches!( + choice.get("value").and_then(Value::as_str), + Some("true" | "false") + ) + }); + if kept.is_empty() || (on_off && kept.len() < 2) { + return None; + } + let current = option.get("currentValue").and_then(Value::as_str); + if !current.is_some_and(carried) { + option["currentValue"] = kept[0]["value"].clone(); + } + option["options"] = Value::Array(kept); + Some(option) + }) + .collect::>(); + let choices = |option: &Value| -> Vec<(String, String)> { + let id = option["id"].as_str().unwrap_or_default().to_owned(); + option["options"] + .as_array() + .into_iter() + .flatten() + .filter_map(|choice| choice.get("value").and_then(Value::as_str)) + .map(|value| (id.clone(), value.to_owned())) + .collect() + }; + let every_combination_advertised = |subset: &[&Value]| { + let mut combinations = vec![Vec::<(String, String)>::new()]; + for option in subset { + combinations = combinations + .into_iter() + .flat_map(|combination| { + choices(option).into_iter().map(move |choice| { + let mut next = combination.clone(); + next.push(choice); + next + }) + }) + .collect(); + } + combinations.iter().all(|combination| { + carriers.iter().any(|params| { + combination + .iter() + .all(|(id, value)| carries(params, id, value)) + }) + }) + }; + // Largest first, earlier options first among sets of one size. At most four options are + // published, so the masks stay few and the shift cannot overflow. + let count = narrowed.len(); + let mut masks = (0..1u32 << count).collect::>(); + masks.sort_by_key(|mask| { + ( + std::cmp::Reverse(mask.count_ones()), + std::cmp::Reverse(mask.reverse_bits()), + ) + }); + masks + .into_iter() + .map(|mask| { + narrowed + .iter() + .enumerate() + .filter(|(index, _)| mask & (1 << index) != 0) + .map(|(_, option)| option) + .collect::>() + }) + .find(|subset| every_combination_advertised(subset)) + .map(|subset| subset.into_iter().cloned().collect()) + .unwrap_or_default() +} + fn select_descriptor(id: &str, label: &str, options: Vec, current: Option<&str>) -> Value { json!({ "id": id, @@ -778,4 +1306,786 @@ mod tests { assert_eq!(models[0].name, "model[fast]"); assert_eq!(models[1].slug, "custom"); } + + /// `cursor/list_available_models` of `cursor-agent` 2026.11 lists Thinking as a + /// `thought_level` beside the effort: it stays the on/off option, not the reasoning select. + #[test] + fn thinking_listed_as_a_thought_level_stays_an_on_off_option() { + let capabilities = build_capabilities_from_config_options(&json!([ + { "id": "thinking", "category": "thought_level", "type": "select", "name": "Thinking", + "currentValue": "true", "options": [{ "value": "false" }, { "value": "true" }] }, + { "id": "effort", "category": "thought_level", "type": "select", "name": "Effort", + "currentValue": "high", + "options": [{ "value": "low" }, { "value": "high" }, { "value": "xhigh" }] }, + { "id": "fast", "category": "model_config", "type": "select", "name": "Fast", + "currentValue": "false", "options": [{ "value": "false" }, { "value": "true" }] } + ])); + let descriptors = capabilities["optionDescriptors"].as_array().unwrap(); + let ids = descriptors + .iter() + .map(|descriptor| { + ( + descriptor["id"].as_str().unwrap(), + descriptor["type"].as_str().unwrap(), + ) + }) + .collect::>(); + assert_eq!( + ids, + [ + ("reasoning", "select"), + ("thinking", "boolean"), + ("fastMode", "boolean") + ] + ); + assert_eq!(descriptors[0]["label"], "Effort"); + assert_eq!(descriptors[0]["options"][2]["id"], "xhigh"); + assert_eq!(descriptors[1]["currentValue"], true); + } + + /// The shapes `cursor-agent` 2026.11 lists and advertises: the picker gets only the option + /// values an advertised value carries, never a combination the runtime would refuse. + #[test] + fn bracketed_sessions_narrow_the_published_options_to_advertised_values() { + let select = |id: &str, category: &str, current: &str, values: &[&str]| { + json!({ + "id": id, "category": category, "type": "select", "currentValue": current, + "options": values.iter().map(|value| json!({ "value": value, "name": value })) + .collect::>() + }) + }; + let list = json!({ "models": [ + { "value": "default", "name": "Auto", "configOptions": [] }, + { "value": "grok-4.7", "name": "Grok 4.7", "configOptions": [ + select("context", "model_config", "256k", &["256k", "500k"]), + select("reasoning_effort", "thought_level", "high", &["low", "high", "xhigh"]), + select("fast", "model_config", "true", &["false", "true"]) + ] }, + { "value": "claude-sonnet-4", "name": "Claude Sonnet 4", "configOptions": [ + select("thinking", "thought_level", "false", &["false", "true"]) + ] }, + { "value": "unadvertised", "name": "Unadvertised", "configOptions": [] } + ] }); + let advertised = [ + "default[]", + "grok-4.7[context=256k,reasoning_effort=high,fast=true]", + "grok-4.7[context=256k,reasoning_effort=low,fast=false]", + "claude-sonnet-4[thinking=false,context=200k]", + ] + .map(str::to_owned); + let custom = [ + "claude-sonnet-4".to_owned(), + "mine".to_owned(), + "grok-4.7".to_owned(), + ]; + let models = discover_models_with_advertised_values(&list, &custom, &advertised).unwrap(); + let summary = models + .iter() + .map(|model| { + let options = model.capabilities["optionDescriptors"] + .as_array() + .unwrap() + .iter() + .map(|descriptor| { + let values = descriptor["options"] + .as_array() + .map(|options| { + options + .iter() + .map(|option| option["id"].as_str().unwrap().to_owned()) + .collect::>() + .join("|") + }) + .unwrap_or_else(|| "on/off".to_owned()); + format!("{}={values}", descriptor["id"].as_str().unwrap()) + }) + .collect::>() + .join(" "); + format!("{} {options}", model.slug) + }) + .collect::>(); + assert_eq!( + summary, + [ + "default ", + "grok-4.7 reasoning=low|high contextWindow=256k", + "claude-sonnet-4 ", + ] + ); + // The custom models the session offers are listed models already; `mine` is not offered. + assert!(models.iter().all(|model| !model.is_custom)); + + // A plain-value session, or none read, publishes the list as before. + for advertised in [vec![], vec!["grok-4.7".to_owned(), "mine".to_owned()]] { + let models = + discover_models_with_advertised_values(&list, &custom, &advertised).unwrap(); + assert_eq!(models.len(), 5, "{advertised:?}"); + assert_eq!( + models[1].capabilities["optionDescriptors"][0]["options"] + .as_array() + .unwrap() + .len(), + 3 + ); + assert!(models[4].is_custom); + } + } + + /// Every combination the picker can build from a bracketed catalog is one the runtime sends: + /// from any advertised value of the model, each choice resolves to an advertised value. + #[test] + fn every_published_combination_resolves_to_an_advertised_value() { + let select = |id: &str, category: &str, values: &[&str]| { + json!({ + "id": id, "category": category, "type": "select", "currentValue": values[0], + "options": values.iter().map(|value| json!({ "value": value })).collect::>() + }) + }; + let list = json!({ "models": [ + { "value": "default", "name": "Auto", "configOptions": [] }, + { "value": "m", "name": "M", "configOptions": [ + select("effort", "model_option", &["low", "high", "xhigh"]), + select("fast", "model_config", &["false", "true"]) + ] }, + { "value": "n", "name": "N", "configOptions": [ + select("reasoning", "thought_level", &["low", "high"]), + select("context", "model_config", &["200k", "1m"]) + ] } + ] }); + let advertised = [ + "default", + "m[effort=low,fast=false]", + "m[effort=high,fast=true]", + "m[effort=extra-high,fast=true]", + "n[reasoning=low,context=200k]", + "n[reasoning=low,context=1m]", + "n[reasoning=high,context=200k]", + "n[reasoning=high,context=1m]", + ] + .map(str::to_owned); + let models = discover_models_with_advertised_values(&list, &[], &advertised).unwrap(); + // A mixed catalog keeps its plain model, with no options to refuse. + assert_eq!( + models + .iter() + .map(|model| model.slug.as_str()) + .collect::>(), + ["default", "m", "n"] + ); + assert_eq!(models[0].capabilities["optionDescriptors"], json!([])); + let descriptor = |current: &str| { + json!({ + "id": "model", "category": "model", "currentValue": current, + "options": advertised.iter().map(|value| json!({ "value": value })).collect::>() + }) + }; + let mut checked = 0; + for model in &models { + let mut combinations = vec![Vec::::new()]; + for option in model.capabilities["optionDescriptors"].as_array().unwrap() { + let values = option["options"].as_array().map_or_else( + || vec![json!(true), json!(false)], + |choices| choices.iter().map(|choice| choice["id"].clone()).collect(), + ); + combinations = combinations + .into_iter() + .flat_map(|combination| { + values.iter().map(move |value| { + let mut next = combination.clone(); + next.push(json!({ "id": option["id"], "value": value })); + next + }) + }) + .collect(); + } + for current in advertised + .iter() + .filter(|value| resolve_acp_base_model_id(value) == model.slug) + { + for combination in &combinations { + let resolved = resolve_bracketed_model_options( + &descriptor(current), + &Value::Array(combination.clone()), + None, + ); + assert!( + resolved.is_ok(), + "{} from {current}: {combination:?} -> {resolved:?}", + model.slug + ); + checked += 1; + } + } + } + // m keeps only Reasoning (Fast is not free of it); n keeps both, every pair advertised. + assert_eq!( + models[1].capabilities["optionDescriptors"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + models[2].capabilities["optionDescriptors"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert!(checked > 0); + } + + #[test] + fn a_bracketed_model_option_holds_its_folded_in_options() { + let descriptor = json!({ + "id": "model", "category": "model", "type": "select", + "currentValue": "m[effort=extra-high,fast=false]", + "options": [ + { "value": "m[effort=extra-high,fast=false]" }, + { "value": "m[effort=low,fast=true]" }, + { "value": "other[]" } + ] + }); + let refusal = |updates: Value| { + resolve_bracketed_model_options(&descriptor, &updates, None) + .unwrap_err() + .refusal + }; + assert_eq!( + resolve_bracketed_model_options( + &descriptor, + &json!([{ "id": "reasoning", "value": "xhigh" }]), + None + ) + .unwrap(), + None + ); + // A second advertised value of the same model is chosen when it holds every option. + assert_eq!( + resolve_bracketed_model_options( + &descriptor, + &json!([{ "id": "reasoning", "value": "low" }, { "id": "fastMode", "value": true }]), + None + ) + .unwrap(), + Some(json!("m[effort=low,fast=true]")) + ); + // Each option is advertised, but no single value holds both. + assert_eq!( + refusal( + json!([{ "id": "reasoning", "value": "low" }, { "id": "fastMode", "value": false }]) + ), + "Reasoning low is not supported by the selected model. Choose another option for this model." + ); + assert_eq!( + refusal(json!([{ "id": "thinking", "value": true }])), + "Thinking is not supported by the selected model. Choose another option for this model." + ); + assert_eq!( + refusal(json!([{ "id": "unknown", "value": true }])), + "unknown is not supported by the selected model. Choose another option for this model." + ); + assert_eq!( + resolve_advertised_model_value(&descriptor, "other").unwrap(), + json!("other[]") + ); + assert_eq!( + resolve_advertised_model_value(&descriptor, "m").unwrap(), + json!("m[effort=extra-high,fast=false]") + ); + } + + /// A thread or custom model saved as a bracketed value before the parameterized picker meets a + /// session that advertises plain names: it is its base model plus its parameters as separate + /// options, each refused only when the session does not advertise it. + #[test] + fn a_saved_bracketed_model_is_its_base_and_options_on_a_plain_session() { + let select = |id: &str, category: &str, values: &[&str], current: &str| { + json!({ + "id": id, "category": category, "type": "select", "currentValue": current, + "options": values.iter().map(|value| json!({ "value": value })).collect::>() + }) + }; + let plain = [select( + "model", + "model", + &["default", "gpt-5.4-nano", "grok-4.7"], + "default", + )]; + assert_eq!( + split_saved_bracketed_model(&plain, "gpt-5.4-nano[reasoning=medium]"), + Some(( + "gpt-5.4-nano".to_owned(), + vec![json!({ "id": "reasoning", "value": "medium" })] + )) + ); + let (base, grok) = split_saved_bracketed_model( + &plain, + "grok-4.7[context=256k,reasoning_effort=high,fast=true,thinking=false]", + ) + .expect("a bracketed saved model splits"); + assert_eq!(base, "grok-4.7"); + assert_eq!( + grok, + [ + json!({ "id": "contextWindow", "value": "256k" }), + json!({ "id": "reasoning", "value": "high" }), + json!({ "id": "fastMode", "value": true }), + json!({ "id": "thinking", "value": false }), + ] + ); + assert_eq!( + resolve_advertised_model_value(&plain[0], &base).unwrap(), + json!("grok-4.7") + ); + // Plain saved models, and sessions that advertise bracketed values, resolve as before. + assert_eq!(split_saved_bracketed_model(&plain, "grok-4.7"), None); + // A base the session does not advertise is refused under its saved name. + assert_eq!( + split_saved_bracketed_model(&plain, "mine[reasoning=high]"), + None + ); + let bracketed = [select( + "model", + "model", + &["gpt-5.4-nano[reasoning=medium]"], + "gpt-5.4-nano[reasoning=medium]", + )]; + assert_eq!( + split_saved_bracketed_model(&bracketed, "gpt-5.4-nano[reasoning=medium]"), + None + ); + + // Once the base model is set, its parameters are checked as the session's options. + let session = json!([ + plain[0], + select("context", "model_config", &["256k", "500k"], "256k"), + select( + "reasoning_effort", + "thought_level", + &["low", "medium", "high", "xhigh"], + "medium" + ), + select("fast", "model_config", &["false", "true"], "false"), + ]); + let (_, advertised) = split_saved_bracketed_model( + &plain, + "grok-4.7[context=256k,reasoning_effort=high,fast=true]", + ) + .unwrap(); + assert_eq!( + resolve_acp_config_updates(&session, &Value::Array(advertised)).unwrap(), + [ + json!({ "configId": "context", "value": "256k" }), + json!({ "configId": "reasoning_effort", "value": "high" }), + json!({ "configId": "fast", "value": "true" }), + ] + ); + let (_, unadvertised) = + split_saved_bracketed_model(&plain, "grok-4.7[context=1m,reasoning_effort=high]") + .unwrap(); + assert_eq!( + resolve_acp_config_updates(&session, &Value::Array(unadvertised)) + .unwrap_err() + .refusal, + "Context 1m is not supported by the selected model. Choose another option for this model." + ); + } + + /// Over a plain session, a custom model saved bracketed is not published again beside its + /// listed base model; one without a plain equivalent stays the user's entry. + #[test] + fn a_custom_bracketed_model_over_a_plain_session_is_not_a_duplicate() { + let list = json!({ "models": [ + { "value": "grok-4.7", "name": "Grok 4.7", "configOptions": [] } + ] }); + let custom = [ + "grok-4.7[context=256k,reasoning_effort=high,fast=true]".to_owned(), + "mine[reasoning=high]".to_owned(), + ]; + let plain = ["default".to_owned(), "grok-4.7".to_owned()]; + let slugs = |advertised: &[String]| { + discover_models_with_advertised_values(&list, &custom, advertised) + .unwrap() + .into_iter() + .map(|model| (model.slug, model.is_custom)) + .collect::>() + }; + assert_eq!( + slugs(&plain), + [ + ("grok-4.7".to_owned(), false), + ("mine[reasoning=high]".to_owned(), true) + ] + ); + // A bracketed session keeps today's behaviour: only advertised custom values appear. + let bracketed = ["grok-4.7[context=256k,reasoning_effort=high,fast=true]".to_owned()]; + assert_eq!( + slugs(&bracketed), + [ + ("grok-4.7".to_owned(), false), + ( + "grok-4.7[context=256k,reasoning_effort=high,fast=true]".to_owned(), + true + ) + ] + ); + } + + /// An option listing no values offers only its current value: any other model is refused, + /// never sent as typed. + #[test] + fn an_option_without_values_refuses_every_model_but_its_current_one() { + let descriptor = + json!({ "id": "model", "category": "model", "currentValue": "m", "options": [] }); + assert_eq!( + resolve_advertised_model_value(&descriptor, "m").unwrap(), + json!("m") + ); + assert!(resolve_advertised_model_value(&descriptor, "other").is_err()); + assert!( + resolve_advertised_model_value(&json!({ "id": "model", "category": "model" }), "x") + .is_err() + ); + } + + fn published(options: Vec, advertised: &[String]) -> Vec { + let list = json!({ "models": [{ "value": "m", "name": "M", "configOptions": options }] }); + let models = discover_models_with_advertised_values(&list, &[], advertised).unwrap(); + models[0].capabilities["optionDescriptors"] + .as_array() + .unwrap() + .iter() + .map(|descriptor| { + let values = descriptor["options"].as_array().map_or_else( + || "on/off".to_owned(), + |choices| { + choices + .iter() + .map(|choice| choice["id"].as_str().unwrap()) + .collect::>() + .join("|") + }, + ); + format!("{}={values}", descriptor["id"].as_str().unwrap()) + }) + .collect() + } + + fn option(id: &str, category: &str, values: &[&str]) -> Value { + json!({ + "id": id, "category": category, "type": "select", "currentValue": values[0], + "options": values.iter().map(|value| json!({ "value": value })).collect::>() + }) + } + + /// Only the options the descriptors publish take part in narrowing: an option the CLI keeps + /// to itself never drops a published one. Every (effort, verbosity) and (effort, fast) pair + /// is advertised, not every triple. + #[test] + fn narrowing_ignores_options_the_descriptors_do_not_publish() { + let advertised = [ + "m[effort=low,verbosity=a,fast=false]", + "m[effort=low,verbosity=b,fast=true]", + "m[effort=high,verbosity=a,fast=false]", + "m[effort=high,verbosity=b,fast=true]", + ] + .map(str::to_owned); + assert_eq!( + published( + vec![ + option("effort", "model_option", &["low", "high"]), + option("verbosity", "model_option", &["a", "b"]), + option("fast", "model_config", &["false", "true"]), + ], + &advertised + ), + ["reasoning=low|high", "fastMode=on/off"] + ); + } + + /// A CLI-only `variant` listed before `reasoning` does not take Reasoning's place. + #[test] + fn a_cli_only_option_listed_first_does_not_hide_reasoning() { + let advertised = [ + "m[variant=x,reasoning=low]", + "m[variant=x,reasoning=high]", + "m[variant=y,reasoning=low]", + ] + .map(str::to_owned); + assert_eq!( + published( + vec![ + option("variant", "thought_level", &["x", "y"]), + option("reasoning", "thought_level", &["low", "high"]), + ], + &advertised + ), + ["reasoning=low|high"] + ); + } + + /// Forty options the CLI keeps to itself, every one carried, before the effort: the subset + /// search never sees them, so its mask cannot overflow. + #[test] + fn many_unpublished_options_do_not_overflow_the_narrowing() { + let carried = (0..40) + .map(|index| format!("o{index}=v")) + .collect::>() + .join(","); + let advertised = ["low", "high"].map(|effort| format!("m[{carried},effort={effort}]")); + let mut options = (0..40) + .map(|index| option(&format!("o{index}"), "model_option", &["v"])) + .collect::>(); + options.push(option("effort", "model_option", &["low", "high"])); + assert_eq!(published(options, &advertised), ["reasoning=low|high"]); + } + + /// Cleared options go back to the baseline only while the latest answer still advertises a + /// value that holds it; otherwise Cursor keeps its current value, and the stale baseline is + /// never sent. + #[test] + fn cleared_options_keep_the_current_value_when_the_baseline_is_gone() { + let descriptor = json!({ + "id": "model", "category": "model", "currentValue": "m[reasoning=high]", + "options": [{ "value": "m[reasoning=high]" }, { "value": "m[reasoning=max]" }] + }); + assert_eq!( + resolve_bracketed_model_options(&descriptor, &json!([]), Some("m[reasoning=medium]")) + .expect("not refused"), + None, + "medium is no longer advertised" + ); + assert!(cleared_options_lose_the_baseline( + &descriptor, + Some("m[reasoning=medium]") + )); + // A plain baseline value the latest answer no longer advertises. + assert_eq!( + resolve_bracketed_model_options(&descriptor, &json!([]), Some("m")).unwrap(), + None + ); + assert!(cleared_options_lose_the_baseline(&descriptor, Some("m"))); + // A baseline still advertised is restored. + let descriptor = json!({ + "id": "model", "category": "model", "currentValue": "m[reasoning=high]", + "options": [{ "value": "m[reasoning=medium]" }, { "value": "m[reasoning=high]" }] + }); + assert_eq!( + resolve_bracketed_model_options(&descriptor, &json!([]), Some("m[reasoning=medium]")) + .unwrap(), + Some(json!("m[reasoning=medium]")) + ); + } + + /// `option` with `current` as its current value. + fn option_at(id: &str, category: &str, values: &[&str], current: &str) -> Value { + let mut option = option(id, category, values); + option["currentValue"] = json!(current); + option + } + + /// The separate options `cursor-agent acp` 2026.11.22 advertises in parameterized mode, after + /// the model is set: Grok 4.7, GPT-5.5, GPT-5.6 and a Claude model with Thinking. + fn grok(reasoning: &str, context: &str, fast: &str) -> Value { + json!([ + option_at("context", "model_config", &["256k", "500k"], context), + option_at( + "reasoning_effort", + "thought_level", + &["low", "medium", "high", "xhigh"], + reasoning + ), + option_at("fast", "model_config", &["false", "true"], fast), + ]) + } + + fn gpt(values: &[&str], reasoning: &str) -> Value { + json!([ + option_at("context", "model_config", &["272k", "1m"], "272k"), + option_at("reasoning", "thought_level", values, reasoning), + option_at("fast", "model_config", &["false", "true"], "false"), + ]) + } + + const GPT_5_5: &[&str] = &["none", "low", "medium", "high", "extra-high"]; + const GPT_5_6: &[&str] = &["none", "low", "medium", "high", "xhigh", "max"]; + + fn claude(thinking: &str, effort: &str) -> Value { + json!([ + option_at("thinking", "thought_level", &["false", "true"], thinking), + option_at("context", "model_config", &["300k", "1m"], "300k"), + option_at( + "effort", + "thought_level", + &["low", "medium", "high", "xhigh", "max"], + effort + ), + option_at("fast", "model_config", &["false", "true"], "false"), + ]) + } + + fn resolved(options: &Value, updates: Value) -> Vec<(String, String)> { + resolve_acp_config_updates(options, &updates) + .expect("resolved") + .iter() + .map(|update| { + ( + update["configId"].as_str().unwrap().to_owned(), + update["value"].as_str().unwrap().to_owned(), + ) + }) + .collect() + } + + fn pairs(expected: &[(&str, &str)]) -> Vec<(String, String)> { + expected + .iter() + .map(|(id, value)| ((*id).to_owned(), (*value).to_owned())) + .collect() + } + + /// Each option resolves to the config id the session advertises, with a value it advertises: + /// `xhigh` stays `xhigh` where the session lists it and becomes `extra-high` where it does not. + #[test] + fn parameterized_sessions_resolve_each_option_to_its_advertised_id_and_value() { + let grok = grok("high", "256k", "true"); + for (requested, sent) in [("low", "low"), ("xhigh", "xhigh")] { + assert_eq!( + resolved(&grok, json!([{ "id": "reasoning", "value": requested }])), + pairs(&[("reasoning_effort", sent)]) + ); + } + assert_eq!( + resolved( + &grok, + json!([ + { "id": "contextWindow", "value": "500k" }, + { "id": "fastMode", "value": false } + ]) + ), + pairs(&[("context", "500k"), ("fast", "false")]) + ); + assert_eq!( + resolved( + &gpt(GPT_5_5, "medium"), + json!([{ "id": "reasoning", "value": "xhigh" }]) + ), + pairs(&[("reasoning", "extra-high")]) + ); + assert_eq!( + resolved( + &gpt(GPT_5_6, "medium"), + json!([{ "id": "reasoning", "value": "xhigh" }]) + ), + pairs(&[("reasoning", "xhigh")]) + ); + assert_eq!( + resolved( + &claude("true", "high"), + json!([ + { "id": "reasoning", "value": "max" }, + { "id": "thinking", "value": false } + ]) + ), + pairs(&[("effort", "max"), ("thinking", "false")]) + ); + } + + /// A value the session does not advertise is still refused, before anything is sent. + #[test] + fn parameterized_sessions_refuse_values_they_do_not_advertise() { + let refusal = |options: Value, updates: Value| { + resolve_acp_config_updates(&options, &updates) + .map(|_| ()) + .map_err(|refused| refused.refusal) + .err() + }; + assert_eq!( + refusal( + grok("high", "256k", "true"), + json!([{ "id": "reasoning", "value": "max" }]) + ), + Some(unsupported_option_refusal("Reasoning max")) + ); + assert_eq!( + refusal( + gpt(GPT_5_5, "medium"), + json!([{ "id": "reasoning", "value": "max" }]) + ), + Some(unsupported_option_refusal("Reasoning max")) + ); + assert_eq!( + refusal( + grok("high", "256k", "true"), + json!([{ "id": "contextWindow", "value": "1m" }]) + ), + Some(unsupported_option_refusal("Context 1m")) + ); + } + + /// Options a turn leaves out go back to the session's baseline, under the same config ids the + /// turn's own options resolve to, so a requested option is never reset right after it is set. + #[test] + fn parameterized_sessions_restore_the_baseline_of_options_a_turn_leaves_out() { + let restored = |latest: Value, baseline: Value, updates: Value| { + let (updates, kept) = + resolve_acp_config_updates_with_baseline(&latest, &baseline, &updates) + .expect("resolved"); + assert!(!kept); + updates + .iter() + .map(|update| { + ( + update["configId"].as_str().unwrap().to_owned(), + update["value"].as_str().unwrap().to_owned(), + ) + }) + .collect::>() + }; + let baseline = grok("high", "256k", "true"); + assert_eq!( + restored(grok("low", "500k", "false"), baseline.clone(), json!([])), + pairs(&[ + ("reasoning_effort", "high"), + ("context", "256k"), + ("fast", "true") + ]) + ); + assert_eq!( + restored( + grok("high", "256k", "true"), + baseline, + json!([{ "id": "reasoning", "value": "low" }]) + ), + pairs(&[("reasoning_effort", "low")]) + ); + assert_eq!( + restored( + gpt(GPT_5_5, "extra-high"), + gpt(GPT_5_5, "medium"), + json!([]) + ), + pairs(&[("reasoning", "medium")]) + ); + assert_eq!( + restored(claude("false", "max"), claude("true", "high"), json!([])), + pairs(&[("effort", "high"), ("thinking", "true")]) + ); + } + + /// The inventory publishes every option a parameterized session lists for Grok 4.7. + #[test] + fn plain_advertised_values_publish_every_listed_option() { + let options = grok("high", "256k", "true").as_array().unwrap().clone(); + let advertised = ["default", "grok-4.7", "gpt-5.5"].map(str::to_owned); + assert_eq!( + published(options, &advertised), + [ + "reasoning=low|medium|high|xhigh", + "contextWindow=256k|500k", + "fastMode=on/off" + ] + ); + } } diff --git a/apps/server/src/provider/cursor/runtime.rs b/apps/server/src/provider/cursor/runtime.rs index 332302e7c7..45d7e0b325 100644 --- a/apps/server/src/provider/cursor/runtime.rs +++ b/apps/server/src/provider/cursor/runtime.rs @@ -1,12 +1,20 @@ #![cfg_attr(test, allow(dead_code))] -use std::{collections::HashMap, future::Future, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + future::Future, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use thiserror::Error; use tokio::{ - sync::{Mutex, mpsc, oneshot}, + sync::{Mutex, Notify, mpsc, oneshot}, task::JoinHandle, }; use uuid::Uuid; @@ -17,16 +25,36 @@ use crate::provider::{ use super::{ acp::{ - AcpJsonRpcConnection, AcpProtocolError, IncomingEvent, JsonRpcErrorShape, acp_error_class, - acp_turn_state, + AcpJsonRpcConnection, AcpProtocolError, AcpRequestWriteFailure, IncomingEvent, + JsonRpcErrorShape, acp_error_class, acp_turn_state, }, model::{ - acp_config_option_current_value, resolve_acp_config_updates_with_baseline, - resolve_acp_default_model_config, + CLEARED_OPTIONS_KEPT_NOTE, acp_config_option_current_value, acp_model_descriptor, + acp_model_values_are_bracketed, advertised_auto_model_value, + cleared_options_lose_the_baseline, resolve_acp_config_updates_with_baseline, + resolve_acp_default_model_config, resolve_advertised_model_value, + resolve_bracketed_model_options, split_saved_bracketed_model, }, }; const PROVIDER: &str = "cursor"; + +/// How long a Cursor turn may go without any update before BiBCode shows a notice on it. The turn +/// keeps running: the user decides whether to stop it. The clock pauses while the turn waits on +/// the user or on a tool Cursor reports running, and the notice clears with the next update. +pub const DEFAULT_SILENCE_TIMEOUT: Duration = Duration::from_secs(5 * 60); + +/// How long a stopped turn's cancelled prompt may take to be answered before BiBCode ends the turn +/// and stops the process, so nothing the old prompt still produces reaches the next message. +const STOP_CANCEL_GRACE: Duration = Duration::from_secs(10); +/// How long writing a prompt to the CLI may block before BiBCode stops the process. +const PROMPT_WRITE_TIMEOUT: Duration = Duration::from_secs(30); +/// How long a stopped process may take to fail the blocked write, which tells how much was sent. +const RETIRED_WRITE_SETTLE: Duration = Duration::from_secs(10); +/// How long starting the session (initialize, authenticate, session/new or session/load, and the +/// initial model and mode) may take before the chat shows that Cursor is slow to start. A CLI +/// waits silently for an MCP server that never connects; the start keeps waiting. +pub const START_NOTICE_DELAY: Duration = Duration::from_secs(60); const FIXED_EVENT_TIME: &str = "2026-07-10T00:00:00.000Z"; /// Phrases that mean the saved Cursor session itself is gone. A `session/load` @@ -83,9 +111,31 @@ pub struct CursorRuntimeEvent { pub struct CursorPromptReceipt { pub turn_id: String, completion: oneshot::Receiver>, + /// The user stopped the prompt before any of it was sent: it is settled, never sent again, + /// and Cursor has nothing of it. + stopped_unsent: bool, +} + +/// A receipt whose outcome is already known. +fn settled_receipt( + turn_id: String, + outcome: Result<(), CursorRuntimeError>, + stopped_unsent: bool, +) -> CursorPromptReceipt { + let (settled, completion) = oneshot::channel(); + let _ = settled.send(outcome); + CursorPromptReceipt { + turn_id, + completion, + stopped_unsent, + } } impl CursorPromptReceipt { + pub fn stopped_unsent(&self) -> bool { + self.stopped_unsent + } + pub async fn completion(self) -> Result<(), CursorRuntimeError> { self.completion.await.unwrap_or_else(|_| { Err(CursorRuntimeError::Protocol(AcpProtocolError::Closed { @@ -174,17 +224,52 @@ struct RuntimeInner { config_options: Mutex>, baseline_config_options: Mutex>, default_model_config: Mutex>, + /// The options a model saved bracketed carries, set as separate options on a session that + /// advertises plain model values; a turn's own option of the same id takes precedence. + saved_model_options: Mutex>, configuration_uncertain: Mutex>, mode_state: Mutex>, runtime_mode: Mutex, interaction_mode: Mutex, active_turn_id: Mutex>, + /// Turns announced with `turn.started` whose `turn.completed` is not emitted yet, each with + /// whether the user stopped it. Every path that ends a turn claims it here first, so a turn + /// ends exactly once, and learns from that one claim whether it was stopped. + unsettled_turns: std::sync::Mutex>, events_tx: mpsc::UnboundedSender, events_rx: Mutex>, event_counter: Mutex, pending_requests: Mutex>, task: Mutex>>, + /// The stopped turn whose late messages are dropped before any handler runs. ignore_turn_output: Mutex>, + /// When the CLI last sent anything, and whether the active turn shows the silence notice. One + /// lock covers both and is held while the notice or its clearing is emitted, so a notice is + /// never published after newer activity. + silence: Mutex, + silence_timeout: std::sync::Mutex, + cancel_grace: std::sync::Mutex, + prompt_write_timeout: std::sync::Mutex, + retired_write_settle: std::sync::Mutex, + /// Tool calls of the active turn Cursor reports `in_progress`: a long command is silent, not + /// stalled. + open_tool_calls: std::sync::Mutex>, + /// Set once the process is retired (a stop's cancel went unanswered, or a prompt write + /// blocked): the CLI may still run the old prompt, so this runtime takes nothing more and the + /// driver stops the process. + abandoned: AtomicBool, + abandon: Notify, + /// Cursor kept its current options because their previous defaults are gone; the next turn + /// shows it once, since that turn's own session update replaces an idle notice at once. + kept_options_note: std::sync::Mutex, + /// Pauses the next claim of a turn until released, for tests: (entered, release). + #[cfg(test)] + before_claim: std::sync::Mutex, Arc)>>, +} + +struct SilenceClock { + last_activity: tokio::time::Instant, + notice_shown: bool, } #[derive(Clone)] @@ -220,23 +305,141 @@ impl CursorSessionRuntime { config_options: Mutex::new(Vec::new()), baseline_config_options: Mutex::new(Vec::new()), default_model_config: Mutex::new(None), + saved_model_options: Mutex::new(Vec::new()), configuration_uncertain: Mutex::new(None), mode_state: Mutex::new(None), runtime_mode: Mutex::new(runtime_mode), interaction_mode: Mutex::new(interaction_mode), active_turn_id: Mutex::new(None), + unsettled_turns: std::sync::Mutex::new(HashMap::new()), events_tx, events_rx: Mutex::new(events_rx), event_counter: Mutex::new(0), pending_requests: Mutex::new(HashMap::new()), task: Mutex::new(None), ignore_turn_output: Mutex::new(None), + silence: Mutex::new(SilenceClock { + last_activity: tokio::time::Instant::now(), + notice_shown: false, + }), + silence_timeout: std::sync::Mutex::new(DEFAULT_SILENCE_TIMEOUT), + cancel_grace: std::sync::Mutex::new(STOP_CANCEL_GRACE), + prompt_write_timeout: std::sync::Mutex::new(PROMPT_WRITE_TIMEOUT), + retired_write_settle: std::sync::Mutex::new(RETIRED_WRITE_SETTLE), + open_tool_calls: std::sync::Mutex::new(HashSet::new()), + abandoned: AtomicBool::new(false), + abandon: Notify::new(), + kept_options_note: std::sync::Mutex::new(false), + #[cfg(test)] + before_claim: std::sync::Mutex::new(None), }); let runtime = Self { inner }; runtime.attach_incoming(connection, incoming); runtime } + /// Replaces [`DEFAULT_SILENCE_TIMEOUT`] for the turns sent from now on. + pub fn set_silence_timeout(&self, timeout: Duration) { + *lock(&self.inner.silence_timeout) = timeout; + } + + /// Replaces the stop grace and the prompt write deadline, for tests. + pub fn set_stop_deadlines(&self, cancel_grace: Duration, prompt_write: Duration) { + *lock(&self.inner.cancel_grace) = cancel_grace; + *lock(&self.inner.prompt_write_timeout) = prompt_write; + } + + /// Resolves once the process is retired; the driver then stops it. + pub async fn abandoned(&self) { + self.inner.abandon.notified().await; + } + + /// Closes the connection: the writer task ends and the CLI's stdin closes. The readers and + /// the incoming task end when the CLI's output closes. + pub async fn close(&self) { + self.inner.connection.lock().await.shutdown(); + } + + #[cfg(test)] + async fn pause_before_claim(&self) { + let gate = lock(&self.inner.before_claim).take(); + if let Some((entered, release)) = gate { + entered.notify_one(); + release.notified().await; + } + } + + /// Whether the process is retired: the session takes nothing more and must be launched again. + pub fn is_retired(&self) -> bool { + self.inner.abandoned.load(Ordering::SeqCst) + } + + /// An update arrived: the silence clock starts again and a shown notice clears. + async fn note_activity(&self) { + let mut silence = self.inner.silence.lock().await; + silence.last_activity = tokio::time::Instant::now(); + if std::mem::take(&mut silence.notice_shown) { + let turn_id = self.inner.active_turn_id.lock().await.clone(); + self.emit("turn.notice", turn_id, None, json!({ "message": null })) + .await; + } + } + + /// Shows a notice on the turn once it has gone the silence timeout without an update while + /// waiting on neither the user nor a tool Cursor reports running. It never ends the turn. + fn watch_silence(&self, turn_id: String) { + let inner = Arc::downgrade(&self.inner); + tokio::spawn(async move { + loop { + let Some(inner) = inner.upgrade() else { + return; + }; + let runtime = Self { inner }; + if runtime.inner.active_turn_id.lock().await.as_deref() != Some(turn_id.as_str()) { + return; + } + let waiting = runtime + .inner + .pending_requests + .lock() + .await + .values() + .any(|pending| pending.turn_id.as_deref() == Some(turn_id.as_str())) + || !lock(&runtime.inner.open_tool_calls).is_empty(); + let timeout = *lock(&runtime.inner.silence_timeout); + // Held through the publish: an update waits for it, then clears the notice. + let mut silence = runtime.inner.silence.lock().await; + if waiting { + silence.last_activity = tokio::time::Instant::now(); + } + let quiet = silence.last_activity.elapsed(); + let pause = if quiet < timeout { + (timeout - quiet).min(Duration::from_secs(1)) + } else { + if !std::mem::replace(&mut silence.notice_shown, true) { + tracing::warn!( + provider = PROVIDER, + quiet_secs = timeout.as_secs(), + "Cursor sent no update for the silence timeout; showing a notice" + ); + runtime + .emit( + "turn.notice", + Some(turn_id.clone()), + None, + json!({ "message": silence_message(timeout) }), + ) + .await; + } + Duration::from_secs(1).min(timeout) + }; + drop(silence); + drop(runtime); + tokio::time::sleep(pause).await; + } + }); + } + pub async fn start(&self) -> Result { self.emit("session.started", None, None, json!({})).await; let connection = self.inner.connection.lock().await.clone(); @@ -245,7 +448,13 @@ impl CursorSessionRuntime { "initialize", json!({ "protocolVersion": 1, - "clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false }, + // Asks Cursor for plain model names with separate options, so every value the + // CLI lists can be chosen; a CLI that ignores it keeps bracketed values. + "clientCapabilities": { + "fs": { "readTextFile": false, "writeTextFile": false }, + "terminal": false, + "_meta": { "parameterizedModelPicker": true }, + }, "clientInfo": { "name": "bibcode-rust", "version": "0.1.1" }, }), ) @@ -295,15 +504,19 @@ impl CursorSessionRuntime { *self.inner.config_options.lock().await = config_options.clone(); *self.inner.baseline_config_options.lock().await = config_options; *self.inner.mode_state.lock().await = response.get("modes").cloned(); - if !self.inner.options.model.trim().is_empty() - && !self - .inner - .options - .model - .trim() - .eq_ignore_ascii_case("default") - { - self.set_model(&self.inner.options.model).await?; + let model = self.inner.options.model.trim(); + // No model selected is Cursor's Auto as well. + if model.is_empty() || model.eq_ignore_ascii_case("default") { + // Auto is Cursor's advertised default value; without one it stays Cursor's choice. + let options = self.inner.config_options.lock().await.clone(); + if acp_model_descriptor(&options).is_some_and(|descriptor| { + advertised_auto_model_value(descriptor) + .is_some_and(|auto| descriptor.get("currentValue") != Some(&auto)) + }) { + self.set_model("default").await?; + } + } else { + self.set_model(model).await?; } self.apply_mode().await?; self.emit("thread.started", None, None, json!({})).await; @@ -311,7 +524,8 @@ impl CursorSessionRuntime { } pub async fn set_model(&self, model: &str) -> Result<(), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; + let mut saved_options = Vec::new(); let (config_id, value) = if model.trim().eq_ignore_ascii_case("default") { self.inner .default_model_config @@ -325,41 +539,67 @@ impl CursorSessionRuntime { )) })? } else { - let config_id = self - .inner - .config_options - .lock() - .await - .iter() - .find(|option| option.get("category").and_then(Value::as_str) == Some("model")) - .and_then(|option| option.get("id").and_then(Value::as_str)) - .map(str::to_owned); - let Some(config_id) = config_id else { + let options = self.inner.config_options.lock().await.clone(); + let Some(descriptor) = acp_model_descriptor(&options) else { + self.inner.saved_model_options.lock().await.clear(); + return Ok(()); + }; + let Some(config_id) = descriptor.get("id").and_then(Value::as_str) else { + self.inner.saved_model_options.lock().await.clear(); return Ok(()); }; - (config_id, json!(model)) + // A model saved bracketed before the parameterized picker is its base plus options. + let model = match split_saved_bracketed_model(&options, model) { + Some((base, carried)) => { + saved_options = carried; + base + } + None => model.to_owned(), + }; + let value = resolve_advertised_model_value(descriptor, &model) + .map_err(CursorRuntimeError::UnsupportedOption)?; + (config_id.to_owned(), value) }; let options = self .set_config_option(&self.provider_session_id().await?, &config_id, value) .await?; *self.inner.config_options.lock().await = options.clone(); *self.inner.baseline_config_options.lock().await = options; + *self.inner.saved_model_options.lock().await = saved_options; Ok(()) } pub async fn set_options(&self, options: Vec) -> Result<(), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; let mut current = self.inner.config_options.lock().await.clone(); - let baseline = self.inner.baseline_config_options.lock().await.clone(); - let updates = resolve_acp_config_updates_with_baseline( - &Value::Array(current.clone()), - &Value::Array(baseline), - &Value::Array(options), - ) - .map_err(CursorRuntimeError::UnsupportedOption)?; + // The saved model's own options first, each unless the turn requests that option itself. + let mut saved = self.inner.saved_model_options.lock().await.clone(); + saved.retain(|saved| !options.iter().any(|option| option["id"] == saved["id"])); + let options = saved.into_iter().chain(options).collect::>(); + if acp_model_values_are_bracketed(¤t) { + return self.set_bracketed_options(¤t, options).await; + } + let baseline = Value::Array(self.inner.baseline_config_options.lock().await.clone()); + let options = Value::Array(options); let session_id = self.provider_session_id().await?; - let mut applied = Vec::new(); - for update in updates { + let mut applied: Vec<(String, Value)> = Vec::new(); + let kept = loop { + // The whole batch is checked before the first write, and again against each of + // Cursor's acknowledgements, which can withdraw a value an earlier write made + // unavailable. A refusal sends nothing more; earlier writes stay applied. + let (updates, kept) = resolve_acp_config_updates_with_baseline( + &Value::Array(current.clone()), + &baseline, + &options, + ) + .map_err(CursorRuntimeError::UnsupportedOption)?; + let Some(update) = updates.into_iter().find(|update| { + !applied + .iter() + .any(|(written, _)| update["configId"] == written.as_str()) + }) else { + break kept; + }; let config_id = update["configId"] .as_str() .expect("resolved ACP config updates have a string config id"); @@ -391,10 +631,83 @@ impl CursorSessionRuntime { return Err(error); } } + }; + if kept { + self.note_kept_options().await; } Ok(()) } + /// Says that Cursor keeps its current options because their previous defaults are gone: on + /// the session now, and on the next turn once it starts. + async fn note_kept_options(&self) { + *lock(&self.inner.kept_options_note) = true; + self.emit( + "session.notice", + None, + None, + json!({ "message": CLEARED_OPTIONS_KEPT_NOTE }), + ) + .await; + } + + /// Options of a session that folds them into its model values: a switch to the advertised + /// value of the current model that holds them, or a refusal before anything is sent. + async fn set_bracketed_options( + &self, + current: &[Value], + options: Vec, + ) -> Result<(), CursorRuntimeError> { + let descriptor = acp_model_descriptor(current) + .expect("bracketed model values come from a model config option"); + let baseline = self.inner.baseline_config_options.lock().await.clone(); + let baseline = acp_model_descriptor(&baseline) + .and_then(|descriptor| descriptor.get("currentValue")) + .and_then(Value::as_str); + let cleared = options.is_empty(); + let Some(value) = + resolve_bracketed_model_options(descriptor, &Value::Array(options), baseline) + .map_err(CursorRuntimeError::UnsupportedOption)? + else { + if cleared && cleared_options_lose_the_baseline(descriptor, baseline) { + self.note_kept_options().await; + } + return Ok(()); + }; + let config_id = descriptor + .get("id") + .and_then(Value::as_str) + .unwrap_or("model") + .to_owned(); + let previous = descriptor + .get("currentValue") + .cloned() + .unwrap_or(Value::Null); + let session_id = self.provider_session_id().await?; + match self.set_config_option(&session_id, &config_id, value).await { + Ok(next) => { + *self.inner.config_options.lock().await = next; + Ok(()) + } + // The switch may have applied: it is written back, and a failed write-back latches + // the session as uncertain, so a restore cannot read the stale value as current. + Err(error @ CursorRuntimeError::MalformedConfigAcknowledgement) => { + let mut current = current.to_vec(); + let error = self + .compensate_config_updates( + &session_id, + &mut current, + vec![(config_id, previous)], + error, + ) + .await; + self.latch_failed_compensation(&error).await; + Err(error) + } + Err(error) => Err(error), + } + } + async fn set_config_option( &self, session_id: &str, @@ -445,19 +758,19 @@ impl CursorSessionRuntime { } pub async fn set_runtime_mode(&self, mode: &str) -> Result<(), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; *self.inner.runtime_mode.lock().await = mode.to_owned(); self.apply_mode().await } pub async fn set_interaction_mode(&self, mode: &str) -> Result<(), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; *self.inner.interaction_mode.lock().await = mode.to_owned(); self.apply_mode().await } async fn apply_mode(&self) -> Result<(), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; let mode_state = self.inner.mode_state.lock().await.clone(); let runtime_mode = self.inner.runtime_mode.lock().await.clone(); let interaction_mode = self.inner.interaction_mode.lock().await.clone(); @@ -509,6 +822,7 @@ impl CursorSessionRuntime { Ok(turn_id) } + #[allow(clippy::result_large_err)] pub async fn send_turn_with_receipt( &self, input: Option<&str>, @@ -516,7 +830,7 @@ impl CursorSessionRuntime { ) -> Result { let (session_id, turn_id, connection, prompt) = self.prepare_prompt(input, attachments).await?; - let mut request = connection + let mut request = match connection .start_request( "session/prompt", json!({ @@ -524,11 +838,69 @@ impl CursorSessionRuntime { "prompt": prompt, }), ) - .await?; - let completion = match request.written().await { + .await + { + Ok(request) => request, + Err(error) => return self.end_unsent_turn(turn_id, error).await, + }; + let write_deadline = *lock(&self.inner.prompt_write_timeout); + let written = match tokio::time::timeout(write_deadline, request.written()).await { + Ok(written) => written, + Err(_) => { + // A CLI that stops reading its input holds the write forever. The process is + // stopped, which fails the write with the count of bytes it took: none means + // the prompt was never sent. + tracing::warn!( + provider = PROVIDER, + "writing a prompt to Cursor blocked past its deadline; stopping its process" + ); + const NOT_TAKEN: &str = + "Cursor did not take the prompt and its process was stopped"; + // The turn ends before the process is stopped, so its `turn.completed` comes + // before the `session.exited` the stop causes. + let claimed = self.claim_turn(&turn_id, false).await; + if let Some(stopped) = claimed { + let error = AcpProtocolError::WriteFailure { + message: NOT_TAKEN.to_owned(), + }; + self.emit_turn_end(turn_id.clone(), stopped, &error).await; + } + self.retire(); + let settle = *lock(&self.inner.retired_write_settle); + let written = tokio::time::timeout(settle, request.written()) + .await + .unwrap_or_else(|_| Err(AcpRequestWriteFailure::unconfirmed(NOT_TAKEN))); + // Only a stop ends a turn before its prompt's own path does. + let stopped = claimed.unwrap_or(true); + return match written { + Err(failure) if failure.is_definitely_not_sent() && !stopped => { + Err(failure.into_error().into()) + } + Err(failure) if failure.is_definitely_not_sent() => { + Ok(settled_receipt(turn_id, Ok(()), true)) + } + // A stopped prompt settles however much of it was sent. + _ if stopped => Ok(settled_receipt(turn_id, Ok(()), false)), + Ok(()) => Ok(settled_receipt( + turn_id, + Err(AcpProtocolError::Closed { + reason: NOT_TAKEN.to_owned(), + } + .into()), + false, + )), + Err(failure) => Ok(settled_receipt( + turn_id, + Err(failure.into_error().into()), + false, + )), + }; + } + }; + let completion = match written { Ok(()) => self.track_prompt_response(connection, turn_id.clone(), request.response()), Err(failure) if failure.is_definitely_not_sent() => { - return Err(failure.into_error().into()); + return self.end_unsent_turn(turn_id, failure.into_error()).await; } Err(failure) => self.track_prompt_response( connection, @@ -539,19 +911,90 @@ impl CursorSessionRuntime { Ok(CursorPromptReceipt { turn_id, completion, + stopped_unsent: false, }) } + /// A prompt that never reached the CLI: its announced turn ends once, so every `turn.started` + /// has its `turn.completed`. An unsent prompt fails and may be sent again. One the user + /// stopped ends as cancelled and settles with Cursor having none of it, so it is never sent + /// again; an unanswered stop may already have ended it. + async fn end_unsent_turn( + &self, + turn_id: String, + error: AcpProtocolError, + ) -> Result { + match self.claim_turn(&turn_id, false).await { + Some(false) => { + self.emit_turn_end(turn_id, false, &error).await; + return Err(error.into()); + } + Some(true) => self.emit_turn_end(turn_id.clone(), true, &error).await, + // Only a stop ends a turn before its prompt's own path does. + None => {} + } + Ok(settled_receipt(turn_id, Ok(()), true)) + } + + /// The `turn.completed` of a turn its prompt's answer did not end: cancelled when the user + /// stopped it, failed with `error` otherwise. + async fn emit_turn_end(&self, turn_id: String, stopped: bool, error: &AcpProtocolError) { + let payload = if stopped { + json!({ "state": "cancelled", "stopReason": "cancelled" }) + } else { + json!({ + "state": "failed", + "stopReason": "error", + "errorMessage": error.to_string(), + "errorClass": acp_error_class(error), + }) + }; + self.emit("turn.completed", Some(turn_id), None, payload) + .await; + } + + /// Claims the end of `turn_id`, with whether the user stopped it. Of every path that can end + /// a turn (its prompt's answer, a prompt that was never sent, a stop the CLI did not + /// answer), only the one that gets `Some` emits its `turn.completed` and settles its + /// delivery, both from that one answer. With `only_if_active`, a turn a newer one has + /// replaced is not claimed. + async fn claim_turn(&self, turn_id: &str, only_if_active: bool) -> Option { + #[cfg(test)] + self.pause_before_claim().await; + let mut active = self.inner.active_turn_id.lock().await; + let is_active = active.as_deref() == Some(turn_id); + if only_if_active && !is_active { + return None; + } + let stopped = lock(&self.inner.unsettled_turns).remove(turn_id)?; + if is_active { + *active = None; + } + Some(stopped) + } + async fn prepare_prompt( &self, input: Option<&str>, attachments: Vec, ) -> Result<(String, String, AcpJsonRpcConnection, Vec), CursorRuntimeError> { - self.ensure_configuration_certain().await?; + self.ensure_usable().await?; let session_id = self.provider_session_id().await?; let turn_id = format!("turn-{}", Uuid::new_v4()); - *self.inner.active_turn_id.lock().await = Some(turn_id.clone()); - *self.inner.ignore_turn_output.lock().await = None; + { + // Under the stop's own locks: a stop targets the previous turn, or is recorded for + // this one after the previous stop is cleared, never wiped by it. + let mut ignored = self.inner.ignore_turn_output.lock().await; + let mut active = self.inner.active_turn_id.lock().await; + lock(&self.inner.unsettled_turns).insert(turn_id.clone(), false); + *active = Some(turn_id.clone()); + *ignored = None; + } + lock(&self.inner.open_tool_calls).clear(); + *self.inner.silence.lock().await = SilenceClock { + last_activity: tokio::time::Instant::now(), + notice_shown: false, + }; self.emit( "turn.started", Some(turn_id.clone()), @@ -559,12 +1002,31 @@ impl CursorSessionRuntime { json!({ "model": self.inner.options.model }), ) .await; + if std::mem::take(&mut *lock(&self.inner.kept_options_note)) { + self.emit( + "turn.notice", + Some(turn_id.clone()), + None, + json!({ "message": CLEARED_OPTIONS_KEPT_NOTE }), + ) + .await; + } + // Armed when the turn is announced, so a prompt write that blocks is silent too. + self.watch_silence(turn_id.clone()); let connection = self.inner.connection.lock().await.clone(); let prompt = crate::provider::attachments::prompt_parts(input, attachments); Ok((session_id, turn_id, connection, prompt)) } - async fn ensure_configuration_certain(&self) -> Result<(), CursorRuntimeError> { + /// Refuses every prompt and setting once the process is retired, or while the session's + /// configuration is uncertain. + async fn ensure_usable(&self) -> Result<(), CursorRuntimeError> { + if self.inner.abandoned.load(Ordering::SeqCst) { + return Err(AcpProtocolError::Closed { + reason: "Cursor stopped responding and its process was stopped".to_owned(), + } + .into()); + } self.inner .configuration_uncertain .lock() @@ -598,11 +1060,12 @@ impl CursorSessionRuntime { // it may still wait in the incoming queue. Handle them first, so they keep this turn // and come before its `turn.completed`. let _ = connection.barrier().await; - if runtime.inner.active_turn_id.lock().await.as_deref() - == Some(background_turn_id.as_str()) - { - *runtime.inner.active_turn_id.lock().await = None; - } + // A turn already ended, by a stop the CLI did not answer: its prompt was written, so + // the delivery stays accepted, and the answer ends nothing twice. + let Some(stopped) = runtime.claim_turn(&background_turn_id, false).await else { + let _ = completion_tx.send(Ok(())); + return; + }; match result { Ok(response) => { let stop_reason = response @@ -623,35 +1086,66 @@ impl CursorSessionRuntime { let _ = completion_tx.send(Ok(())); } Err(error) => { - let detail = error.to_string(); - // Attribute from the variant, not the flattened string: a - // JSON-RPC error is the agent's, a broken pipe is ours. - let class = acp_error_class(&error); runtime - .emit( - "turn.completed", - Some(background_turn_id), - None, - json!({ - "state": "failed", - "stopReason": "error", - "errorMessage": detail, - "errorClass": class, - }), - ) + .emit_turn_end(background_turn_id, stopped, &error) .await; - let _ = completion_tx.send(Err(error.into())); + // A prompt the user stopped settles however its write or answer broke, so + // it is never sent again. + let _ = completion_tx.send(if stopped { Ok(()) } else { Err(error.into()) }); } } }); completion } - pub async fn interrupt_turn(&self) -> Result<(), CursorRuntimeError> { - let Some(turn_id) = self.inner.active_turn_id.lock().await.clone() else { - return Ok(()); + /// Latches the retirement before anything else, so no next prompt or setting reaches a CLI + /// that may still run the old prompt, and asks the driver to stop the process. + fn retire(&self) { + self.inner.abandoned.store(true, Ordering::SeqCst); + self.inner.abandon.notify_one(); + } + + /// Ends a stopped turn whose cancel the CLI did not answer within the grace: the turn ends + /// once, as cancelled, and the process is retired. + async fn end_unanswered_stop(&self, turn_id: String) { + let Some(stopped) = self.claim_turn(&turn_id, true).await else { + return; + }; + tracing::warn!( + provider = PROVIDER, + "Cursor did not answer the cancel of a stopped turn; stopping its process" + ); + lock(&self.inner.open_tool_calls).clear(); + // Retired before the turn ends, so the next message never reaches this process. + self.inner.abandoned.store(true, Ordering::SeqCst); + let unanswered = AcpProtocolError::Closed { + reason: "Cursor did not answer the stop".to_owned(), + }; + self.emit_turn_end(turn_id, stopped, &unanswered).await; + self.inner.abandon.notify_one(); + } + + /// Stops the running turn. With `requested`, only when it is that turn: a late stop for a + /// turn that already ended must not stop the next one. + pub async fn interrupt_turn(&self, requested: Option<&str>) -> Result<(), CursorRuntimeError> { + let turn_id = { + let mut ignored = self.inner.ignore_turn_output.lock().await; + let active = self.inner.active_turn_id.lock().await; + let Some(turn_id) = active.clone() else { + return Ok(()); + }; + if requested.is_some_and(|requested| requested != turn_id) { + return Ok(()); + } + *ignored = Some(turn_id.clone()); + // Recorded with the turn's claim, so whichever path ends the turn sees the stop. + if let Some(stopped) = lock(&self.inner.unsettled_turns).get_mut(&turn_id) { + *stopped = true; + } + turn_id }; - *self.inner.ignore_turn_output.lock().await = Some(turn_id.clone()); + // The turn's output is ignored from here on, so its tool calls never report closing. + lock(&self.inner.open_tool_calls).clear(); let pending_ids = self .inner .pending_requests @@ -675,6 +1169,12 @@ impl CursorSessionRuntime { json!({ "sessionId": self.provider_session_id().await? }), ) .await?; + let runtime = self.clone(); + let grace = *lock(&self.inner.cancel_grace); + tokio::spawn(async move { + tokio::time::sleep(grace).await; + runtime.end_unanswered_stop(turn_id).await; + }); Ok(()) } @@ -830,8 +1330,35 @@ impl CursorSessionRuntime { request_scope: RequestScope, event: IncomingEvent, ) { + // The one gate for a stopped turn's late messages, before any handler runs: none is + // projected, none opens an approval or question, none is approved. Held across the + // handler, so a stop cannot land between this check and a request being recorded. + let ignored = self.inner.ignore_turn_output.lock().await; + // A retired process's messages are late too: it is being stopped. + let late = self.is_retired() + || match ignored.as_deref() { + Some(ignored) => { + let active = self.inner.active_turn_id.lock().await; + active.is_none() || active.as_deref() == Some(ignored) + } + None => false, + }; match event { + IncomingEvent::Notification { .. } if late => { + tracing::debug!( + provider = PROVIDER, + "dropped a stopped turn's late notification" + ); + } + IncomingEvent::Request { + wire_id, method, .. + } if late => { + if let Err(error) = refuse_late_request(&connection, wire_id, &method).await { + tracing::warn!(provider = PROVIDER, %error, "could not refuse a late request"); + } + } IncomingEvent::Notification { method, params } => { + self.note_activity().await; self.handle_notification(method, params).await; } IncomingEvent::Request { @@ -840,6 +1367,7 @@ impl CursorSessionRuntime { method, params, } => { + self.note_activity().await; if let Err(error) = self .handle_request( connection, @@ -916,11 +1444,6 @@ impl CursorSessionRuntime { return; } let turn_id = self.inner.active_turn_id.lock().await.clone(); - if let Some(ignored_turn_id) = self.inner.ignore_turn_output.lock().await.clone() - && turn_id.as_deref() == Some(ignored_turn_id.as_str()) - { - return; - } match params .get("update") .and_then(|value| value.get("sessionUpdate")) @@ -955,6 +1478,24 @@ impl CursorSessionRuntime { .get("status") .and_then(Value::as_str) .unwrap_or("pending"); + // Only a call Cursor reports running pauses the silence clock; a pending, + // finished or unknown status does not. An update without a status leaves it. + let reported = update.get("status").and_then(Value::as_str).or_else(|| { + (update.get("sessionUpdate").and_then(Value::as_str) == Some("tool_call")) + .then_some("pending") + }); + { + let mut open = lock(&self.inner.open_tool_calls); + match reported { + Some("in_progress") => { + open.insert(tool_call_id.to_owned()); + } + Some(_) => { + open.remove(tool_call_id); + } + None => {} + } + } let event_type = if status == "completed" { "item.completed" } else { @@ -1242,6 +1783,54 @@ impl CursorSessionRuntime { } } +fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The notice a running Cursor turn shows after the silence timeout without an update. +fn silence_message(timeout: Duration) -> String { + let quiet = match timeout.as_secs() { + seconds if seconds >= 120 => format!("{} minutes", seconds / 60), + seconds => format!("{seconds} seconds"), + }; + format!( + "Cursor has sent nothing for {quiet}. It may be waiting for you to sign in to Cursor in \ + your browser, or one of its MCP servers may not be responding; otherwise stop the turn if \ + it seems stuck." + ) +} + +/// A stopped turn's late request gets the refusal a cancel gives, never an approval: a +/// permission or question is `cancelled` and a plan is not accepted. +async fn refuse_late_request( + connection: &AcpJsonRpcConnection, + wire_id: Value, + method: &str, +) -> Result<(), AcpProtocolError> { + let refusal = match method { + "session/request_permission" => json!({ "outcome": { "outcome": "cancelled" } }), + "cursor/ask_question" | "_x.ai/ask_user_question" | "x.ai/ask_user_question" => { + json!({ "outcome": "cancelled" }) + } + "cursor/create_plan" => json!({ "accepted": false }), + _ => { + return connection + .respond_error( + wire_id, + JsonRpcErrorShape { + code: -32601, + message: format!("Method not found: {method}"), + data: None, + }, + ) + .await; + } + }; + connection.respond(wire_id, refusal).await +} + fn find_option_id(options: &[Value], kind: &str) -> Option { options.iter().find_map(|option| { (option.get("kind").and_then(Value::as_str) == Some(kind)) @@ -1268,6 +1857,17 @@ mod tests { CursorSessionRuntime, Lines>, DuplexStream, + ) { + runtime_with_model(provider_session_id, "default") + } + + fn runtime_with_model( + provider_session_id: Option<&str>, + model: &str, + ) -> ( + CursorSessionRuntime, + Lines>, + DuplexStream, ) { let (stdout, stdout_peer) = duplex(4096); let (stdin_peer, stdin) = duplex(4096); @@ -1280,7 +1880,7 @@ mod tests { cwd: "/workspace".to_owned(), runtime_mode: "full-access".to_owned(), interaction_mode: "default".to_owned(), - model: "default".to_owned(), + model: model.to_owned(), resume_session_id: None, mcp_servers: Vec::new(), }, @@ -1447,6 +2047,1426 @@ mod tests { ); } + async fn read_request(requests: &mut Lines>) -> Value { + let line = timeout(Duration::from_secs(5), requests.next_line()) + .await + .expect("request in time") + .expect("request read") + .expect("request line"); + serde_json::from_str(&line).expect("valid JSON-RPC message") + } + + async fn write_frame(responses: &mut DuplexStream, frame: Value) { + responses + .write_all(format!("{frame}\n").as_bytes()) + .await + .expect("provider output write"); + } + + fn session_update(kind: &str) -> Value { + json!({ + "jsonrpc": "2.0", "method": "session/update", + "params": { "sessionId": "cursor-session", "update": { "sessionUpdate": kind } } + }) + } + + fn tool_update(kind: &str, status: &str) -> Value { + json!({ + "jsonrpc": "2.0", "method": "session/update", + "params": { "sessionId": "cursor-session", "update": { + "sessionUpdate": kind, "toolCallId": "tool-1", "status": status + } } + }) + } + + async fn next_of(runtime: &CursorSessionRuntime, wanted: &str) -> CursorRuntimeEvent { + timeout(Duration::from_secs(5), async { + loop { + let event = runtime.next_event().await.expect("event"); + if event.event_type == wanted { + return event; + } + } + }) + .await + .unwrap_or_else(|_| panic!("no {wanted} event")) + } + + /// The measured stall: one `session_info_update`, then nothing. The turn shows a notice and + /// keeps running, nothing is cancelled, and the next update clears the notice. + #[tokio::test] + async fn a_silent_turn_shows_a_notice_keeps_running_and_clears_it_on_the_next_update() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + runtime.set_silence_timeout(Duration::from_millis(300)); + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + let prompt = read_request(&mut requests).await; + write_frame(&mut responses, session_update("session_info_update")).await; + + let events = timeout(Duration::from_secs(5), runtime.collect_events(2)) + .await + .expect("two events"); + assert_eq!(events[0].event_type, "turn.started"); + assert_eq!(events[1].event_type, "turn.notice"); + assert_eq!(events[1].turn_id.as_deref(), Some(receipt.turn_id.as_str())); + assert_eq!( + events[1].payload["message"], + "Cursor has sent nothing for 0 seconds. It may be waiting for you to sign in to Cursor in your browser, or one of its MCP servers may not be responding; otherwise stop the turn if it seems stuck." + ); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + timeout(Duration::from_millis(50), requests.next_line()) + .await + .is_err(), + "nothing, a cancel included, is sent" + ); + write_frame(&mut responses, session_update("agent_message_chunk")).await; + let events = timeout(Duration::from_secs(2), runtime.collect_events(2)) + .await + .expect("cleared, then the update"); + assert_eq!(events[0].event_type, "turn.notice"); + assert!(events[0].payload["message"].is_null()); + assert_eq!(events[1].event_type, "content.delta"); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": prompt["id"], "result": { "stopReason": "end_turn" } }), + ) + .await; + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("answered") + .expect("accepted"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "completed"); + } + + /// A tool call that is only pending, or that ended in any status, leaves the clock running; + /// only one Cursor reports `in_progress` pauses it. + #[tokio::test] + async fn only_a_running_tool_call_pauses_the_silence_clock() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + runtime.set_silence_timeout(Duration::from_millis(300)); + let _receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + read_request(&mut requests).await; + write_frame(&mut responses, tool_update("tool_call", "pending")).await; + assert!( + next_of(&runtime, "turn.notice").await.payload["message"].is_string(), + "a pending call does not pause the clock" + ); + write_frame( + &mut responses, + tool_update("tool_call_update", "in_progress"), + ) + .await; + assert!(next_of(&runtime, "turn.notice").await.payload["message"].is_null()); + next_of(&runtime, "item.updated").await; + assert!( + timeout(Duration::from_millis(800), next_of(&runtime, "turn.notice")) + .await + .is_err(), + "a running call pauses the clock" + ); + write_frame(&mut responses, tool_update("tool_call_update", "cancelled")).await; + assert!( + next_of(&runtime, "turn.notice").await.payload["message"].is_string(), + "an ended call, in any status, no longer pauses the clock" + ); + } + + /// After Stop, every late message of the turn stops at one gate: no update is projected, no + /// approval or question opens, nothing is approved, and a plan is not accepted. + #[tokio::test] + async fn a_stopped_turns_late_messages_are_dropped_or_refused() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + let prompt = read_request(&mut requests).await; + assert_eq!( + next_of(&runtime, "turn.started").await.turn_id.as_deref(), + Some(receipt.turn_id.as_str()) + ); + runtime.interrupt_turn(None).await.expect("stop"); + assert_eq!( + read_request(&mut requests).await["method"], + "session/cancel" + ); + + async fn late(responses: &mut DuplexStream) { + let frames = [ + session_update("agent_message_chunk"), + json!({ "jsonrpc": "2.0", "method": "session/update", "params": { + "sessionId": "cursor-session", + "update": { "sessionUpdate": "plan", "entries": [{ "content": "x" }] } } }), + json!({ "jsonrpc": "2.0", "method": "cursor/update_todos", "params": { + "todos": [{ "content": "late", "status": "pending" }] } }), + tool_update("tool_call", "in_progress"), + json!({ "jsonrpc": "2.0", "id": 81, "method": "session/request_permission", + "params": { "options": [{ "optionId": "yes", "kind": "allow_once" }] } }), + json!({ "jsonrpc": "2.0", "id": 82, "method": "cursor/ask_question", + "params": { "questions": [{ "id": "q", "prompt": "Which?" }] } }), + json!({ "jsonrpc": "2.0", "id": 83, "method": "cursor/create_plan", + "params": { "plan": "# Late" } }), + ]; + let text = frames + .iter() + .map(|frame| format!("{frame}\n")) + .collect::(); + responses + .write_all(text.as_bytes()) + .await + .expect("late write"); + } + late(&mut responses).await; + let mut answers = Vec::new(); + for _ in 0..3 { + let answer = read_request(&mut requests).await; + answers.push((answer["id"].clone(), answer["result"].clone())); + } + assert_eq!( + answers, + [ + (json!(81), json!({ "outcome": { "outcome": "cancelled" } })), + (json!(82), json!({ "outcome": "cancelled" })), + (json!(83), json!({ "accepted": false })), + ] + ); + // The prompt's own answer still ends the turn once, as cancelled. + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": prompt["id"], "result": { "stopReason": "cancelled" } }), + ) + .await; + let completed = timeout(Duration::from_secs(2), runtime.next_event()) + .await + .expect("an event") + .expect("event"); + assert_eq!(completed.event_type, "turn.completed", "{completed:?}"); + assert_eq!(completed.payload["state"], "cancelled"); + // After its end, the stopped turn's messages are still dropped or refused. + late(&mut responses).await; + for _ in 0..3 { + read_request(&mut requests).await; + } + assert!( + timeout(Duration::from_millis(300), runtime.next_event()) + .await + .is_err(), + "nothing of the stopped turn was projected" + ); + } + + /// A stop whose cancel the CLI ignores: after the grace the turn ends once, as cancelled, the + /// runtime is retired so the driver stops the process, and it takes no further prompt. + #[tokio::test] + async fn an_unanswered_stop_retires_the_runtime_before_any_next_prompt() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(Duration::from_millis(300), PROMPT_WRITE_TIMEOUT); + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + assert_eq!( + read_request(&mut requests).await["method"], + "session/prompt" + ); + runtime.interrupt_turn(None).await.expect("stop"); + assert_eq!( + read_request(&mut requests).await["method"], + "session/cancel" + ); + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the unanswered cancel retires the runtime"); + assert!(runtime.is_retired()); + let events = timeout(Duration::from_secs(2), runtime.collect_events(2)) + .await + .expect("the turn's events"); + assert_eq!(events[1].event_type, "turn.completed"); + assert_eq!(events[1].payload["state"], "cancelled"); + + write_frame(&mut responses, session_update("agent_message_chunk")).await; + let refused = runtime + .send_turn_with_receipt(Some("again"), Vec::new()) + .await + .expect_err("a retired runtime takes no prompt"); + assert!( + matches!(refused, CursorRuntimeError::Protocol(_)), + "{refused}" + ); + assert!( + timeout(Duration::from_millis(200), requests.next_line()) + .await + .is_err(), + "nothing was written after the retirement" + ); + // The stopped process closes the connection: the prompt's failed answer ends nothing twice. + drop(responses); + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved") + .expect("the written prompt stays accepted"); + let rest = timeout(Duration::from_secs(1), runtime.collect_events(1)).await; + assert!( + rest.as_ref().is_ok_and(|rest| rest + .iter() + .all(|event| event.event_type == "session.exited")), + "{rest:?}" + ); + } + + /// A CLI that stops reading its input: the prompt write is bounded, the process is retired, + /// and a prompt it may have partly read is reported as possibly delivered, not unsent. + #[tokio::test] + async fn a_blocked_prompt_write_retires_the_runtime_and_keeps_a_partial_write_ambiguous() { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(STOP_CANCEL_GRACE, Duration::from_millis(200)); + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some(&"x".repeat(64 * 1024)), Vec::new()) + .await + } + }); + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the blocked write retires the runtime"); + // The driver stops the process, which closes its input. + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("part of the prompt was written"); + let outcome = timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved"); + // The writer's own count of the partial write, not the closed connection's answer. + assert!( + matches!( + outcome, + Err(CursorRuntimeError::Protocol( + AcpProtocolError::WriteFailure { .. } + )) + ), + "{outcome:?}" + ); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "failed"); + } + + /// Fills the CLI's 4096-byte input exactly, so the next write takes no byte until it closes. + async fn fill_cli_input(runtime: &CursorSessionRuntime) { + let frame = + serde_json::to_vec(&json!({ "jsonrpc": "2.0", "method": "fill", "params": "" })) + .expect("frame") + .len() + + 1; + runtime + .inner + .connection + .lock() + .await + .clone() + .notify("fill", json!("x".repeat(4096 - frame))) + .await + .expect("filler queued"); + } + + /// Fails when another `turn.completed` arrives soon. + async fn assert_no_second_completion(runtime: &CursorSessionRuntime) { + let more = timeout(Duration::from_millis(300), async { + loop { + let event = runtime.next_event().await; + if event + .as_ref() + .is_none_or(|event| event.event_type == "turn.completed") + { + return event; + } + } + }) + .await; + assert!(more.is_err(), "the turn ended twice: {more:?}"); + } + + /// A blocked write that took no byte before the stopped process closed the CLI's input was + /// never sent, so it may be sent again. + #[tokio::test] + async fn a_prompt_write_blocked_before_its_first_byte_is_definitely_not_sent() { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(STOP_CANCEL_GRACE, Duration::from_millis(200)); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the blocked write retires the runtime"); + drop(requests); + let error = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect_err("nothing of the prompt was written"); + assert!( + matches!( + error, + CursorRuntimeError::Protocol(AcpProtocolError::WriteFailure { .. }) + ), + "{error:?}" + ); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "failed"); + assert_no_second_completion(&runtime).await; + } + + /// A stopped process that does not fail the blocked write within the settle leaves it + /// unconfirmed: possibly delivered, never sent again on its own. + #[tokio::test] + async fn a_blocked_prompt_write_that_never_settles_is_unconfirmed() { + let (runtime, _requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(STOP_CANCEL_GRACE, Duration::from_millis(200)); + *lock(&runtime.inner.retired_write_settle) = Duration::from_millis(200); + let receipt = timeout( + Duration::from_secs(5), + runtime.send_turn_with_receipt(Some(&"x".repeat(64 * 1024)), Vec::new()), + ) + .await + .expect("the settle bounds the send") + .expect("part of the prompt may have been read"); + assert!(runtime.is_retired()); + let outcome = timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved"); + assert!( + matches!( + &outcome, + Err(CursorRuntimeError::Protocol(AcpProtocolError::WriteFailure { message })) + if message.contains("did not take the prompt") + ), + "{outcome:?}" + ); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "failed"); + } + + async fn stop_a_blocked_prompt( + cancel_grace: Duration, + prompt_write: Duration, + ) -> (CursorSessionRuntime, Result<(), CursorRuntimeError>) { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(cancel_grace, prompt_write); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + next_of(&runtime, "turn.started").await; + runtime.interrupt_turn(None).await.expect("stop"); + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the runtime is retired"); + // The driver stops the process: the blocked write fails with nothing sent. + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("a stopped prompt settles; it is not reported unsent"); + let outcome = timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved"); + (runtime, outcome) + } + + /// Stop while the prompt write blocks: the unanswered stop ends the turn once, as cancelled, + /// and the prompt the user stopped settles as delivered, so it is never sent again. + #[tokio::test] + async fn a_stop_during_a_blocked_prompt_write_ends_the_turn_once_and_never_resends() { + let (runtime, outcome) = + stop_a_blocked_prompt(Duration::from_millis(200), PROMPT_WRITE_TIMEOUT).await; + outcome.expect("settled, so the stopped prompt is not sent again"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + assert_no_second_completion(&runtime).await; + } + + /// The same when the write deadline retires the process before the stop's grace ends. + #[tokio::test] + async fn a_stopped_prompt_whose_write_fails_before_the_grace_ends_settles_as_cancelled() { + let (runtime, outcome) = + stop_a_blocked_prompt(STOP_CANCEL_GRACE, Duration::from_millis(500)).await; + outcome.expect("settled, so the stopped prompt is not sent again"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + assert_no_second_completion(&runtime).await; + } + + /// The prompt's answer waits on the barrier while the stop's grace expires: the turn still + /// ends once. + #[tokio::test] + async fn a_prompt_answer_and_an_expired_stop_end_the_turn_once() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(Duration::from_millis(300), PROMPT_WRITE_TIMEOUT); + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + let prompt = read_request(&mut requests).await; + runtime.interrupt_turn(None).await.expect("stop"); + assert_eq!( + read_request(&mut requests).await["method"], + "session/cancel" + ); + // Every incoming event takes this lock first, so the answer's barrier waits on it. + let held = runtime.inner.ignore_turn_output.lock().await; + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": prompt["id"], "result": { "stopReason": "cancelled" } }), + ) + .await; + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the stop's grace expired"); + drop(held); + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved") + .expect("the written prompt stays accepted"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + assert_no_second_completion(&runtime).await; + } + + /// A retired runtime takes no setting either: the next message launches Cursor again. + #[tokio::test] + async fn a_retired_runtime_refuses_every_setting() { + let (runtime, mut requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.retire(); + let refusals = [ + runtime.set_model("m").await, + runtime.set_options(Vec::new()).await, + runtime.set_runtime_mode("approval-required").await, + runtime.set_interaction_mode("plan").await, + ]; + for refused in refusals { + assert!( + matches!( + refused, + Err(CursorRuntimeError::Protocol( + AcpProtocolError::Closed { .. } + )) + ), + "{refused:?}" + ); + } + assert_eq!(*runtime.inner.runtime_mode.lock().await, "full-access"); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing was written" + ); + } + + /// (a) Stop, then the partial write of the prompt breaks before the stop's grace ends: the + /// turn ends once, as cancelled, and the stopped prompt settles: not uncertain, never sent + /// again. + #[tokio::test] + async fn a_stopped_prompt_whose_partial_write_breaks_ends_once_as_cancelled() { + let (runtime, mut requests, _responses) = delivery_runtime(Some("cursor-session")); + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some(&"x".repeat(64 * 1024)), Vec::new()) + .await + } + }); + next_of(&runtime, "turn.started").await; + // Part of the prompt reached the CLI's input before it stopped reading. + let mut first = [0_u8; 1]; + timeout( + Duration::from_secs(5), + tokio::io::AsyncReadExt::read_exact(requests.get_mut().get_mut(), &mut first), + ) + .await + .expect("part of the prompt was written") + .expect("read"); + runtime.interrupt_turn(None).await.expect("stop"); + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("part of the prompt was written"); + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved") + .expect("settled, so it is neither uncertain nor sent again"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + assert_no_second_completion(&runtime).await; + } + + /// (b) A stop recorded after the write failed with nothing sent but before the turn was + /// claimed is honoured: the prompt is never sent again. + #[tokio::test] + async fn a_stop_recorded_just_before_the_claim_is_never_resent() { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + let (entered, release) = (Arc::new(Notify::new()), Arc::new(Notify::new())); + *lock(&runtime.inner.before_claim) = Some((entered.clone(), release.clone())); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + next_of(&runtime, "turn.started").await; + // The CLI's input closes: the blocked write fails with nothing of the prompt sent. + drop(requests); + timeout(Duration::from_secs(5), entered.notified()) + .await + .expect("the unsent prompt reaches its claim"); + let _ = runtime.interrupt_turn(None).await; + release.notify_one(); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("a stopped prompt settles; it is not reported unsent"); + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved") + .expect("settled"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + assert_no_second_completion(&runtime).await; + } + + /// (c) A stop while the prompt write takes no byte, with the write deadline firing before + /// the stop's grace: the turn ends once, as cancelled, before the stopped process's + /// `session.exited`. + #[tokio::test] + async fn a_stopped_unsent_prompt_ends_before_the_session_exits() { + let (runtime, requests, responses) = delivery_runtime(Some("cursor-session")); + runtime.set_stop_deadlines(STOP_CANCEL_GRACE, Duration::from_millis(500)); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + next_of(&runtime, "turn.started").await; + runtime.interrupt_turn(None).await.expect("stop"); + timeout(Duration::from_secs(5), runtime.abandoned()) + .await + .expect("the write deadline retires the runtime"); + // The driver stops the process: its output closes first, then its input. + drop(responses); + tokio::time::sleep(Duration::from_millis(200)).await; + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("a stopped prompt settles"); + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("resolved") + .expect("settled"); + let mut ends = Vec::new(); + timeout(Duration::from_secs(5), async { + while ends.len() < 2 { + let event = runtime.next_event().await.expect("event"); + if matches!( + event.event_type.as_str(), + "turn.completed" | "session.exited" + ) { + ends.push((event.event_type, event.payload)); + } + } + }) + .await + .expect("both ends arrive"); + assert_eq!(ends[0].0, "turn.completed", "{ends:?}"); + assert_eq!(ends[0].1["state"], "cancelled"); + assert_eq!(ends[1].0, "session.exited", "{ends:?}"); + assert_no_second_completion(&runtime).await; + } + + /// (d) A stopped prompt that sent nothing tells the delivery so: it settles without the + /// provider having any of it, so a side chat's host context is still owed. + #[tokio::test] + async fn a_stopped_unsent_prompt_says_it_sent_nothing() { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + next_of(&runtime, "turn.started").await; + runtime.interrupt_turn(None).await.expect("stop"); + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("a stopped prompt settles"); + assert!(receipt.stopped_unsent(), "nothing of the prompt was sent"); + } + + /// A late stop for a finished turn leaves the next one alone: its prompt that took no byte + /// is still unsent and may be sent again, and it does not end as cancelled. + #[tokio::test] + async fn a_late_stop_for_a_finished_turn_leaves_the_unsent_next_prompt_retryable() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + let first = runtime + .send_turn_with_receipt(Some("first"), Vec::new()) + .await + .expect("the first prompt is written"); + let request: Value = serde_json::from_str( + &requests + .next_line() + .await + .expect("request read") + .expect("first prompt"), + ) + .expect("valid JSON-RPC request"); + responses + .write_all( + format!( + "{{\"jsonrpc\":\"2.0\",\"id\":{},\"result\":{{\"stopReason\":\"end_turn\"}}}}\n", + request["id"] + ) + .as_bytes(), + ) + .await + .expect("prompt response write"); + let finished = first.turn_id.clone(); + timeout(Duration::from_secs(2), first.completion()) + .await + .expect("resolved") + .expect("the first turn finishes"); + assert_eq!( + next_of(&runtime, "turn.completed").await.turn_id.as_deref(), + Some(finished.as_str()) + ); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("second"), Vec::new()) + .await + } + }); + let started = next_of(&runtime, "turn.started").await; + assert_ne!(started.turn_id.as_deref(), Some(finished.as_str())); + runtime + .interrupt_turn(Some(&finished)) + .await + .expect("a stale stop is no error"); + // The CLI's input closes: the blocked write fails with nothing of the prompt sent. + drop(requests); + let error = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect_err("the unsent prompt is not settled as stopped"); + assert!( + matches!( + error, + CursorRuntimeError::Protocol(AcpProtocolError::WriteFailure { .. }) + ), + "{error:?}" + ); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.turn_id, started.turn_id); + assert_eq!(completed.payload["state"], "failed"); + assert_no_second_completion(&runtime).await; + } + + /// A stop that names the running turn still stops it. + #[tokio::test] + async fn a_stop_naming_the_active_turn_stops_it() { + let (runtime, requests, _responses) = delivery_runtime(Some("cursor-session")); + fill_cli_input(&runtime).await; + let send = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + } + }); + let started = next_of(&runtime, "turn.started").await; + runtime + .interrupt_turn(started.turn_id.as_deref()) + .await + .expect("stop"); + drop(requests); + let receipt = timeout(Duration::from_secs(5), send) + .await + .expect("the send ends") + .unwrap() + .expect("a stopped prompt settles"); + assert!(receipt.stopped_unsent(), "nothing of the prompt was sent"); + let completed = next_of(&runtime, "turn.completed").await; + assert_eq!(completed.payload["state"], "cancelled"); + } + + /// Cleared options whose baseline the latest answer no longer advertises keep the value + /// Cursor uses now: nothing is sent, nothing is refused, and a note says so. + async fn clearing_keeps_the_current_options(current: Vec, baseline: Vec) { + let (runtime, mut requests, _responses) = delivery_runtime(Some("cursor-session")); + *runtime.inner.config_options.lock().await = current; + *runtime.inner.baseline_config_options.lock().await = baseline; + timeout(Duration::from_secs(2), runtime.set_options(Vec::new())) + .await + .expect("clearing waits on no answer") + .expect("clearing is not refused"); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing was sent" + ); + let note = "Cursor no longer offers this model's previous default options, so it keeps \ + its current ones."; + assert_eq!( + next_of(&runtime, "session.notice").await.payload["message"], + note + ); + // The next turn's own session update replaces the idle notice, so the turn shows it. + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("the prompt is written"); + let started = next_of(&runtime, "turn.started").await; + let shown = timeout(Duration::from_secs(2), runtime.next_event()) + .await + .expect("the turn shows the note") + .expect("event"); + assert_eq!(shown.event_type, "turn.notice"); + assert_eq!(shown.turn_id, started.turn_id); + assert_eq!(shown.payload["message"], note); + assert_eq!(shown.turn_id.as_deref(), Some(receipt.turn_id.as_str())); + } + + #[tokio::test] + async fn clearing_keeps_bracketed_options_whose_baseline_is_gone() { + let gone = |value: &str| { + vec![json!({ + "id": "model", "category": "model", "type": "select", "currentValue": value, + "options": [{ "value": value }] + })] + }; + clearing_keeps_the_current_options( + bracketed_options("m[reasoning=high,fast=false]"), + gone("m[reasoning=low,fast=false]"), + ) + .await; + // A plain baseline value the latest answer no longer advertises. + clearing_keeps_the_current_options( + bracketed_options("m[reasoning=high,fast=false]"), + gone("m"), + ) + .await; + } + + #[tokio::test] + async fn clearing_keeps_separate_options_whose_baseline_is_gone() { + let effort = |current: &str, values: &[&str]| { + vec![json!({ + "id": "effort", "category": "model_option", "type": "select", + "currentValue": current, + "options": values.iter().map(|value| json!({ "value": value })).collect::>() + })] + }; + clearing_keeps_the_current_options( + effort("high", &["low", "high"]), + effort("medium", &["low", "medium", "high"]), + ) + .await; + } + + /// Closing the runtime ends the connection's writer task, so the CLI's input closes and the + /// connection does not outlive the stopped process. + #[tokio::test] + async fn close_ends_the_cli_input() { + let (runtime, mut requests, _responses) = delivery_runtime(Some("cursor-session")); + runtime.close().await; + let line = timeout(Duration::from_secs(5), requests.next_line()) + .await + .expect("the input closes") + .expect("read"); + assert_eq!(line, None); + } + + /// A turn that keeps sending updates, or waits on the user or a running tool, is never cut + /// off, however long it runs. + #[tokio::test] + async fn a_turn_that_keeps_reporting_or_waits_on_the_user_is_not_cut_off() { + let (runtime, mut requests, mut responses) = delivery_runtime(Some("cursor-session")); + runtime.set_silence_timeout(Duration::from_millis(300)); + let receipt = runtime + .send_turn_with_receipt(Some("hello"), Vec::new()) + .await + .expect("session prompt should write"); + let prompt = read_request(&mut requests).await; + for _ in 0..6 { + write_frame(&mut responses, session_update("agent_thought_chunk")).await; + tokio::time::sleep(Duration::from_millis(150)).await; + } + // A tool call in progress, then a question to the user, each silent past the deadline. + write_frame( + &mut responses, + json!({ + "jsonrpc": "2.0", "method": "session/update", + "params": { "sessionId": "cursor-session", "update": { + "sessionUpdate": "tool_call", "toolCallId": "tool-1", "status": "in_progress" + } } + }), + ) + .await; + tokio::time::sleep(Duration::from_millis(700)).await; + write_frame( + &mut responses, + json!({ + "jsonrpc": "2.0", "method": "session/update", + "params": { "sessionId": "cursor-session", "update": { + "sessionUpdate": "tool_call_update", "toolCallId": "tool-1", "status": "completed" + } } + }), + ) + .await; + write_frame( + &mut responses, + json!({ + "jsonrpc": "2.0", "id": 77, "method": "cursor/ask_question", + "params": { "questions": [{ "id": "q1", "prompt": "Which file?" }] } + }), + ) + .await; + tokio::time::sleep(Duration::from_millis(700)).await; + assert!( + timeout(Duration::from_millis(50), requests.next_line()) + .await + .is_err(), + "nothing, a cancel included, was sent while the turn reported or waited" + ); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": prompt["id"], "result": { "stopReason": "end_turn" } }), + ) + .await; + timeout(Duration::from_secs(2), receipt.completion()) + .await + .expect("answered") + .expect("accepted"); + let completed = timeout(Duration::from_secs(2), async { + loop { + let event = runtime.next_event().await.expect("event"); + assert_ne!( + event.event_type, "turn.notice", + "no notice while reporting or waiting" + ); + if event.event_type == "turn.completed" { + return event; + } + } + }) + .await + .expect("the turn completed"); + assert_eq!(completed.payload["state"], "completed"); + } + + fn bracketed_options(current: &str) -> Vec { + vec![json!({ + "id": "model", "category": "model", "type": "select", "currentValue": current, + "options": [ + { "value": "m[reasoning=medium,fast=false]" }, + { "value": "m[reasoning=high,fast=false]" }, + { "value": "m[reasoning=high,fast=true]" } + ] + })] + } + + async fn bracketed_runtime() -> ( + CursorSessionRuntime, + Lines>, + DuplexStream, + ) { + let (runtime, requests, responses) = delivery_runtime(Some("cursor-session")); + let baseline = bracketed_options("m[reasoning=medium,fast=false]"); + *runtime.inner.config_options.lock().await = baseline.clone(); + *runtime.inner.baseline_config_options.lock().await = baseline; + (runtime, requests, responses) + } + + /// Clearing a bracketed session's options goes back to the model's baseline value, as a + /// session with separate options does. + #[tokio::test] + async fn cleared_bracketed_options_return_to_the_models_baseline() { + let (runtime, mut requests, mut responses) = bracketed_runtime().await; + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "high" })]) + .await + } + }); + let write = read_request(&mut requests).await; + assert_eq!(write["params"]["value"], "m[reasoning=high,fast=false]"); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": write["id"], "result": { + "configOptions": bracketed_options("m[reasoning=high,fast=false]") + } }), + ) + .await; + set.await.unwrap().expect("high applied"); + + let clear = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.set_options(Vec::new()).await } + }); + let write = read_request(&mut requests).await; + assert_eq!(write["params"]["value"], "m[reasoning=medium,fast=false]"); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": write["id"], "result": { + "configOptions": bracketed_options("m[reasoning=medium,fast=false]") + } }), + ) + .await; + clear.await.unwrap().expect("baseline restored"); + } + + /// An option switch answered without its options may have applied: it is written back, so + /// the runtime's view and the CLI agree before the error reaches the supervisor. + #[tokio::test] + async fn a_bracketed_switch_answered_without_options_is_rolled_back() { + let (runtime, mut requests, mut responses) = bracketed_runtime().await; + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "high" })]) + .await + } + }); + let write = read_request(&mut requests).await; + assert_eq!(write["params"]["value"], "m[reasoning=high,fast=false]"); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": write["id"], "result": {} }), + ) + .await; + let rollback = read_request(&mut requests).await; + assert_eq!( + rollback["params"]["value"], + "m[reasoning=medium,fast=false]" + ); + write_frame( + &mut responses, + json!({ "jsonrpc": "2.0", "id": rollback["id"], "result": { + "configOptions": bracketed_options("m[reasoning=medium,fast=false]") + } }), + ) + .await; + let error = set.await.unwrap().expect_err("the switch failed"); + assert!( + matches!(error, CursorRuntimeError::ConfigUpdateRolledBack { .. }), + "{error:?}" + ); + } + + /// Answers the next request, which must be `method`, with `result`, and returns its params. + async fn answer( + requests: &mut Lines>, + responses: &mut DuplexStream, + method: &str, + result: Value, + ) -> Value { + let request = read_request(requests).await; + assert_eq!(request["method"], method, "{request}"); + write_frame( + responses, + json!({ "jsonrpc": "2.0", "id": request["id"], "result": result }), + ) + .await; + request["params"].clone() + } + + /// Grok 4.7 as `cursor-agent acp` 2026.11.22 advertises it in parameterized mode. + fn parameterized_grok(reasoning: &str, fast: &str) -> Value { + let select = |id: &str, category: &str, values: &[&str], current: &str| { + json!({ + "id": id, "category": category, "type": "select", "currentValue": current, + "options": values.iter().map(|value| json!({ "value": value })).collect::>() + }) + }; + json!([ + select( + "model", + "model", + &["default", "grok-4.7", "gpt-5.5"], + "grok-4.7" + ), + select("context", "model_config", &["256k", "500k"], "256k"), + select( + "reasoning_effort", + "thought_level", + &["low", "medium", "high", "xhigh"], + reasoning + ), + select("fast", "model_config", &["false", "true"], fast), + ]) + } + + /// BiBCode asks Cursor for its parameterized model picker, so the session advertises plain + /// model names and separate options: Grok 4.7 Low without Fast is the base model, then each + /// option on its own, and nothing else. + #[tokio::test] + async fn a_parameterized_session_sets_the_base_model_then_each_option() { + let (runtime, mut requests, mut responses) = runtime_with_model(None, "grok-4.7"); + let start = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.start().await } + }); + let initialize = answer(&mut requests, &mut responses, "initialize", json!({})).await; + assert_eq!( + initialize["clientCapabilities"]["_meta"]["parameterizedModelPicker"], + true + ); + answer(&mut requests, &mut responses, "authenticate", json!({})).await; + let mut opened = parameterized_grok("high", "true"); + opened[0]["currentValue"] = json!("default"); + answer( + &mut requests, + &mut responses, + "session/new", + json!({ "sessionId": "cursor-session", "configOptions": [opened[0]] }), + ) + .await; + let model = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": parameterized_grok("high", "true") }), + ) + .await; + assert_eq!( + (&model["configId"], &model["value"]), + (&json!("model"), &json!("grok-4.7")) + ); + start.await.unwrap().expect("started"); + + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![ + json!({ "id": "reasoning", "value": "low" }), + json!({ "id": "fastMode", "value": false }), + ]) + .await + } + }); + let reasoning = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": parameterized_grok("low", "true") }), + ) + .await; + assert_eq!( + (&reasoning["configId"], &reasoning["value"]), + (&json!("reasoning_effort"), &json!("low")) + ); + let fast = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": parameterized_grok("low", "false") }), + ) + .await; + assert_eq!( + (&fast["configId"], &fast["value"]), + (&json!("fast"), &json!("false")) + ); + set.await.unwrap().expect("options applied"); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing else was sent" + ); + } + + /// Starts a parameterized Grok session for the saved `model` and returns it once the model + /// write, which must send `grok-4.7`, is acknowledged. + async fn started_parameterized_grok( + model: &str, + ) -> ( + CursorSessionRuntime, + Lines>, + DuplexStream, + ) { + let (runtime, mut requests, mut responses) = runtime_with_model(None, model); + let start = tokio::spawn({ + let runtime = runtime.clone(); + async move { runtime.start().await } + }); + answer(&mut requests, &mut responses, "initialize", json!({})).await; + answer(&mut requests, &mut responses, "authenticate", json!({})).await; + let mut opened = parameterized_grok("high", "true"); + opened[0]["currentValue"] = json!("default"); + answer( + &mut requests, + &mut responses, + "session/new", + json!({ "sessionId": "cursor-session", "configOptions": [opened[0]] }), + ) + .await; + let write = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": parameterized_grok("high", "true") }), + ) + .await; + assert_eq!( + (&write["configId"], &write["value"]), + (&json!("model"), &json!("grok-4.7")) + ); + start.await.unwrap().expect("started"); + (runtime, requests, responses) + } + + /// Each option write is checked against Cursor's latest acknowledgement: when setting + /// Reasoning low narrows Context to 256k, the requested 500k is refused, not sent. + #[tokio::test] + async fn an_option_the_previous_acknowledgement_withdrew_is_refused_unsent() { + let (runtime, mut requests, mut responses) = started_parameterized_grok("grok-4.7").await; + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![ + json!({ "id": "reasoning", "value": "low" }), + json!({ "id": "contextWindow", "value": "500k" }), + ]) + .await + } + }); + let mut narrowed = parameterized_grok("low", "true"); + narrowed[1]["options"] = json!([{ "value": "256k" }]); + let reasoning = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": narrowed }), + ) + .await; + assert_eq!( + (&reasoning["configId"], &reasoning["value"]), + (&json!("reasoning_effort"), &json!("low")) + ); + let error = timeout(Duration::from_secs(2), set) + .await + .expect("the batch ended without another write") + .unwrap() + .expect_err("Context 500k is no longer advertised"); + assert_eq!( + error.option_refusal(), + Some( + "Context 500k is not supported by the selected model. Choose another option for this model." + ) + ); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing else was sent" + ); + } + + /// A baseline value an acknowledgement withdraws mid-batch is not restored: Cursor keeps its + /// current value and the chat says so, as when the session no longer offers it at the start. + #[tokio::test] + async fn a_baseline_the_previous_acknowledgement_withdrew_is_kept() { + let (runtime, mut requests, mut responses) = started_parameterized_grok("grok-4.7").await; + let mut on_500k = parameterized_grok("high", "true"); + on_500k[1]["currentValue"] = json!("500k"); + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "contextWindow", "value": "500k" })]) + .await + } + }); + answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": on_500k }), + ) + .await; + set.await.unwrap().expect("500k applied"); + + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "reasoning", "value": "low" })]) + .await + } + }); + let mut narrowed = parameterized_grok("low", "true"); + narrowed[1]["currentValue"] = json!("500k"); + narrowed[1]["options"] = json!([{ "value": "500k" }]); + let reasoning = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": narrowed }), + ) + .await; + assert_eq!(reasoning["configId"], "reasoning_effort"); + set.await.unwrap().expect("Context keeps 500k"); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "the withdrawn 256k was not sent" + ); + timeout(Duration::from_secs(2), async { + loop { + let event = runtime.next_event().await.expect("event"); + if event.event_type == "session.notice" { + assert_eq!(event.payload["message"], CLEARED_OPTIONS_KEPT_NOTE); + return; + } + } + }) + .await + .expect("the kept options are noted"); + } + + /// A model saved bracketed before the parameterized picker sets its base model, then its + /// parameters as separate options; an option the turn requests overrides the saved one. + #[tokio::test] + async fn a_saved_bracketed_model_sets_its_base_then_its_options() { + let (runtime, mut requests, mut responses) = + started_parameterized_grok("grok-4.7[context=500k,reasoning_effort=low,fast=true]") + .await; + let set = tokio::spawn({ + let runtime = runtime.clone(); + async move { + runtime + .set_options(vec![json!({ "id": "fastMode", "value": false })]) + .await + } + }); + let mut sent = Vec::new(); + for ack in [ + { + let mut ack = parameterized_grok("high", "true"); + ack[1]["currentValue"] = json!("500k"); + ack + }, + { + let mut ack = parameterized_grok("low", "true"); + ack[1]["currentValue"] = json!("500k"); + ack + }, + { + let mut ack = parameterized_grok("low", "false"); + ack[1]["currentValue"] = json!("500k"); + ack + }, + ] { + let write = answer( + &mut requests, + &mut responses, + "session/set_config_option", + json!({ "configOptions": ack }), + ) + .await; + sent.push((write["configId"].clone(), write["value"].clone())); + } + set.await.unwrap().expect("options applied"); + assert_eq!( + sent, + [ + (json!("context"), json!("500k")), + (json!("reasoning_effort"), json!("low")), + (json!("fast"), json!("false")), + ] + ); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing else was sent" + ); + } + + /// A saved parameter the session does not advertise is refused before any option is sent. + #[tokio::test] + async fn a_saved_bracketed_parameter_the_session_does_not_advertise_is_refused() { + let (runtime, mut requests, _responses) = + started_parameterized_grok("grok-4.7[context=1m,reasoning_effort=low]").await; + let error = runtime + .set_options(Vec::new()) + .await + .expect_err("Context 1m is not advertised"); + assert_eq!( + error.option_refusal(), + Some( + "Context 1m is not supported by the selected model. Choose another option for this model." + ) + ); + assert!( + timeout(Duration::from_millis(100), requests.next_line()) + .await + .is_err(), + "nothing was sent" + ); + } + #[test] fn only_a_missing_session_load_error_abandons_the_saved_session() { assert!(session_load_is_permanently_gone("Session not found")); diff --git a/apps/server/src/provider/mod.rs b/apps/server/src/provider/mod.rs index 52b26ae44c..cced3f7964 100644 --- a/apps/server/src/provider/mod.rs +++ b/apps/server/src/provider/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod acp_mode; +pub mod antigravity; pub(crate) mod attachments; pub mod claude; pub mod codex; @@ -95,7 +96,9 @@ pub(crate) fn rewind_keeps_files(provider: &str, api_version: u32) -> bool { /// The selected model refuses `option`. pub(crate) fn unsupported_option_refusal(option: &str) -> String { - format!("{option} is not supported by the selected model.") + format!( + "{option} is not supported by the selected model. Choose another option for this model." + ) } /// A turn option carries no id. diff --git a/apps/server/src/provider_usage/antigravity.rs b/apps/server/src/provider_usage/antigravity.rs new file mode 100644 index 0000000000..17287e05cb --- /dev/null +++ b/apps/server/src/provider_usage/antigravity.rs @@ -0,0 +1,1405 @@ +//! Antigravity account usage, read from `agy -p "/usage" --output-format json`. +//! +//! The command answers without a model turn since CLI 1.1.11; an older CLI would send the text as +//! a prompt and spend quota, so nothing is run until `--version` proves a new enough CLI. The +//! CLI's free text (group names, descriptions, the response) is never read: a plan name can sit +//! there. Design: `docs/plans/2026-11-21-antigravity-usage-design.md`. + +use std::{ + collections::BTreeMap, + fmt, + path::{Path, PathBuf}, + process::Stdio, + sync::{Arc, Mutex as StdMutex}, + time::{Duration, SystemTime}, +}; + +use serde::{ + Deserialize, Deserializer, + de::{IgnoredAny, MapAccess, SeqAccess, Visitor}, +}; +use serde_json::Value; +use time::OffsetDateTime; +use tokio::process::Command; +use tokio_util::sync::CancellationToken; + +use super::{ + FetchFuture, ProviderUsageFetchError, ProviderUsageFetcher, ProviderUsageProvider, + ProviderUsageSnapshot, ProviderUsageStatus, ProviderUsageWindow, ProviderUsageWindowGroup, + unavailable_snapshot, +}; +use crate::{ + diagnostics::{ + AttributionKind, AttributionScope, NativeProcessSampler, ProcessAttributionRegistry, + ProcessRegistration, ProcessRegistrationMetadata, RegistrationSource, + }, + process::{ + configure_background_command, + supervised::{ + StopPolicy, SupervisedOverflow, SupervisedRunError, SupervisedRunOutput, + SupervisedRunRequest, run_supervised_with_spawn_observer, + }, + }, + production::{ + provider_inventory::maintenance_target, + provider_runtime::{prepare_provider_launch, resolve_provider_executable_with_environment}, + }, + provider::environment::sanitize_provider_subprocess_environment, + server_settings::ProviderSettingsStore, +}; + +/// Automatic refreshes run the CLI at most this often; a forced refresh bypasses it. +pub(super) const MIN_INTERVAL: Duration = Duration::from_secs(5 * 60); +/// The service's deadline for one attempt: the settings read, both runs and their cleanup. +pub(super) const ATTEMPT_DEADLINE: Duration = DEADLINE; +/// After the deadline cancels the runs, how long the supervisor gets to reap them. +pub(super) const CLEANUP_GRACE: Duration = Duration::from_secs(5); +/// One deadline for the version probe and the usage read together. +const DEADLINE: Duration = Duration::from_secs(20); +const PROBE_TIMEOUT: Duration = Duration::from_secs(5); +const CLEANUP_TIMEOUT: Duration = Duration::from_secs(2); +const OUTPUT_LIMIT: usize = 64 * 1024; +const MINIMUM_VERSION: (u64, u64, u64) = (1, 1, 11); +/// The documented exit code of `-p "/usage"` for a Gemini API key sign-in (no account quota). +const API_KEY_EXIT_CODE: i32 = 2; + +pub(super) const MESSAGE_DISABLED: &str = + "Antigravity is turned off. Turn it on in Settings, Providers."; +pub(super) const MESSAGE_NOT_STARTED: &str = "The Antigravity CLI could not be started."; +pub(super) const MESSAGE_VERSION: &str = + "Antigravity usage needs CLI 1.1.11 or newer, and its version could not be confirmed."; +pub(super) const MESSAGE_API_KEY: &str = + "This Antigravity sign-in uses an API key, which has no account quota."; +pub(super) const MESSAGE_TRANSIENT: &str = + "Antigravity usage could not be read. It will be tried again."; +pub(super) const MESSAGE_FORMAT: &str = + "Antigravity reported usage in a format this version of BiBCode does not read."; + +/// What identifies the executable whose version was verified. +type VerifiedExecutable = (PathBuf, SystemTime, u64); + +pub(super) fn fetcher( + settings: ProviderSettingsStore, + attribution: Option, +) -> ProviderUsageFetcher { + let verified: Arc>> = Arc::default(); + ProviderUsageFetcher { + provider: ProviderUsageProvider::Antigravity, + fetch: Arc::new(move || -> FetchFuture { + let settings = settings.clone(); + let attribution = attribution.clone(); + let verified = verified.clone(); + Box::pin(async move { + let unreadable = + || ProviderUsageFetchError::new("Antigravity settings could not be read."); + let cancellation = super::attempt_cancellation(); + // The environment with its stored secrets, as the chat provider reads it: an + // API-key instance is not read with the host's account. + let read = async { serde_json::to_value(settings.get().await.ok()?).ok() }; + let document = tokio::select! { + document = read => document.ok_or_else(unreadable)?, + () = cancellation.cancelled() => { + return Err(ProviderUsageFetchError::new(MESSAGE_TRANSIENT)); + } + }; + fetch_for_document(&document, attribution.as_ref(), &verified, DEADLINE).await + }) + }), + } +} + +/// Whether the default Antigravity instance is on, by the rule every launch uses. +pub(super) fn default_instance_enabled(document: &Value) -> bool { + crate::server_settings::provider_instance_enabled(document, "antigravity") +} + +pub(super) async fn fetch_for_document( + document: &Value, + attribution: Option<&ProcessAttributionRegistry>, + verified: &StdMutex>, + deadline: Duration, +) -> Result { + let now = OffsetDateTime::now_utc(); + let unavailable = |message: &str| -> Result { + Ok(unavailable_snapshot( + ProviderUsageProvider::Antigravity, + now, + message, + )) + }; + if !default_instance_enabled(document) { + return unavailable(MESSAGE_DISABLED); + } + let Some(target) = maintenance_target(document, "antigravity", Some("antigravity")) else { + return unavailable(MESSAGE_NOT_STARTED); + }; + let Some(executable) = resolve_provider_executable_with_environment( + &target.binary_path, + target + .environment + .iter() + .map(|(name, value)| (name.as_os_str(), value.as_os_str())), + ) else { + return unavailable(MESSAGE_NOT_STARTED); + }; + let Some(identity) = executable_identity(&executable) else { + return unavailable(MESSAGE_NOT_STARTED); + }; + let started = tokio::time::Instant::now(); + let ends_at = started + deadline; + let workdir = + ScratchDirectory::create().map_err(|_| ProviderUsageFetchError::new(MESSAGE_TRANSIENT))?; + // Stopped by the service's attempt deadline and its shutdown, and by this fetch's deadline. + let cancellation = super::attempt_cancellation(); + // Both runs launch the file whose version was verified (the canonical path), never a path a + // symlink could retarget in between; the name it was called by stays its argv[0]. + let run = |arguments: &'static [&'static str], timeout: Duration| { + until_deadline( + run_cli( + CliLaunch { + program: &identity.0, + called_as: &executable, + }, + arguments, + &target.environment, + workdir.path(), + timeout, + &cancellation, + attribution, + ), + ends_at, + &cancellation, + ) + }; + + let already_verified = verified + .lock() + .unwrap_or_else(|error| error.into_inner()) + .as_ref() + == Some(&identity); + if !already_verified { + let output = match run(&["--version"], PROBE_TIMEOUT).await { + Ok(output) => output, + Err(SupervisedRunError::Spawn(_)) => return unavailable(MESSAGE_NOT_STARTED), + Err(_) => return unavailable(MESSAGE_VERSION), + }; + if !output.status.success() + || is_truncated(&output.stdout) + || !version_is_supported(&output.stdout.bytes) + { + return unavailable(MESSAGE_VERSION); + } + *verified.lock().unwrap_or_else(|error| error.into_inner()) = Some(identity.clone()); + } + + let remaining = deadline.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(ProviderUsageFetchError::new(MESSAGE_TRANSIENT)); + } + let output = match run(&["-p", "/usage", "--output-format", "json"], remaining).await { + Ok(output) => output, + Err(SupervisedRunError::Spawn(_)) => return unavailable(MESSAGE_NOT_STARTED), + Err(error) => { + tracing::warn!(failure = %run_error_class(&error), "Antigravity usage run failed"); + return Err(ProviderUsageFetchError::new(MESSAGE_TRANSIENT)); + } + }; + if output.status.code() == Some(API_KEY_EXIT_CODE) { + return unavailable(MESSAGE_API_KEY); + } + if !output.status.success() { + tracing::warn!(code = ?output.status.code(), "Antigravity usage exited unsuccessfully"); + return Err(ProviderUsageFetchError::new(MESSAGE_TRANSIENT)); + } + if is_truncated(&output.stdout) { + return unavailable(MESSAGE_FORMAT); + } + match parse_usage(&output.stdout.bytes, now) { + Some(snapshot) => Ok(snapshot), + None => unavailable(MESSAGE_FORMAT), + } +} + +/// Cancels the runs through the supervisor's token at the deadline, then waits for the run to +/// settle: the supervisor stops the whole process group, a descendant that kept the output pipes +/// open included, before the run returns. +async fn until_deadline( + run: F, + ends_at: tokio::time::Instant, + cancellation: &CancellationToken, +) -> F::Output { + tokio::pin!(run); + tokio::select! { + output = &mut run => return output, + () = tokio::time::sleep_until(ends_at) => cancellation.cancel(), + } + run.await +} + +fn run_error_class(error: &SupervisedRunError) -> &'static str { + match error { + SupervisedRunError::Spawn(_) => "spawn", + _ => "run", + } +} + +fn is_truncated(stream: &crate::process::supervised::SupervisedStreamOutput) -> bool { + stream.observed_bytes > stream.bytes.len() +} + +fn executable_identity(executable: &Path) -> Option { + // Without Windows' `\\?\` prefix, which a `.cmd` launched through `cmd.exe` does not accept. + let path = crate::git::without_verbatim_prefix(std::fs::canonicalize(executable).ok()?); + let metadata = std::fs::metadata(&path).ok()?; + Some((path, metadata.modified().ok()?, metadata.len())) +} + +/// The probe passes only for one `major.minor.patch` token at or above 1.1.11. +fn version_is_supported(stdout: &[u8]) -> bool { + let Ok(text) = std::str::from_utf8(stdout) else { + return false; + }; + let token = text.trim(); + if token.is_empty() || token.split_whitespace().count() != 1 { + return false; + } + let Ok(version) = semver::Version::parse(token) else { + return false; + }; + (version.major, version.minor, version.patch) >= MINIMUM_VERSION && version.pre.is_empty() +} + +/// The verified file to run, and the path it was configured as (its argv[0], which a +/// version-manager shim dispatches on). +#[derive(Clone, Copy)] +struct CliLaunch<'a> { + program: &'a Path, + called_as: &'a Path, +} + +async fn run_cli( + launch: CliLaunch<'_>, + arguments: &[&str], + environment: &[(std::ffi::OsString, std::ffi::OsString)], + workdir: &Path, + timeout: Duration, + cancellation: &CancellationToken, + attribution: Option<&ProcessAttributionRegistry>, +) -> Result { + let CliLaunch { program, called_as } = launch; + // Only the usage command can spend quota: its spawn starts the cooldown. + let usage_run = arguments.first() == Some(&"-p"); + let launch = prepare_provider_launch(program, arguments) + .map_err(|error| SupervisedRunError::Spawn(std::io::Error::other(error)))?; + let mut command = Command::new(&launch.program); + #[cfg(unix)] + if launch.program.as_path() == program { + command.arg0(called_as); + } + #[cfg(not(unix))] + let _ = called_as; + configure_background_command(&mut command); + command + .args(&launch.args) + .current_dir(workdir) + .envs(environment.iter().map(|(name, value)| (name, value))) + // Not the server's stdin: the CLI sees end-of-file at once if it ever reads. + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + sanitize_provider_subprocess_environment(&mut command); + let registration: Arc>> = Arc::default(); + let observed = registration.clone(); + let attribution = attribution.cloned(); + let output = run_supervised_with_spawn_observer( + SupervisedRunRequest { + command, + stdin: None, + timeout, + cleanup_timeout: CLEANUP_TIMEOUT, + max_output_bytes: OUTPUT_LIMIT, + stop_policy: StopPolicy::Force, + overflow: SupervisedOverflow::Truncate, + }, + cancellation, + move |pid| { + if usage_run { + super::note_usage_spawned(); + } + let (Some(pid), Some(attribution)) = (pid, attribution) else { + return; + }; + let Ok(identity) = NativeProcessSampler::process_identity(pid) else { + return; + }; + match attribution.register_identity( + identity, + ProcessRegistrationMetadata { + scope: AttributionScope::External, + kind: AttributionKind::Helper, + label: "antigravity usage".to_owned(), + source: RegistrationSource::Helper, + driver: None, + survives_shutdown: false, + }, + ) { + Ok(held) => { + *observed.lock().unwrap_or_else(|error| error.into_inner()) = Some(held); + } + Err(error) => { + tracing::warn!(%error, "could not attribute the Antigravity usage process"); + } + } + }, + ) + .await; + drop(registration); + output +} + +/// A scratch working directory, removed when dropped. Not the data root: that can sit inside a +/// checkout, and the CLI reads project files from its working directory. +struct ScratchDirectory(PathBuf); + +impl ScratchDirectory { + fn create() -> std::io::Result { + // A random name, as the codebase names its temporary files: never two alike. + let path = std::env::temp_dir().join(format!("bibcode-agy-usage-{}", uuid::Uuid::new_v4())); + // Only the Unix mode call mutates it. + #[cfg_attr(not(unix), allow(unused_mut))] + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(&path)?; + Ok(Self(path)) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for ScratchDirectory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The only fields read. Every other field, free text included, is skipped by the decoder and +/// never stored. The guard fields and the containers are strict: a wrong type there is not the +/// shape BiBCode reads. +#[derive(Deserialize)] +struct UsageOutput { + status: Option, + num_turns: Option, + command: Option>, +} + +#[derive(Deserialize)] +struct UsageCommand { + name: Option, + data: Option>, +} + +#[derive(Deserialize)] +struct UsageData { + groups: Option>>, +} + +/// A JSON object, never an array: serde's derived decoder also accepts a positional array, which +/// would let a reply with no `name` field pass the guard. +struct Object(T); + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Object { + fn deserialize>(deserializer: D) -> Result { + struct ObjectVisitor(std::marker::PhantomData); + + impl<'de, T: Deserialize<'de>> Visitor<'de> for ObjectVisitor { + type Value = Object; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a JSON object") + } + + fn visit_map>(self, map: A) -> Result { + T::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(Object) + } + } + + deserializer.deserialize_map(ObjectVisitor(std::marker::PhantomData)) + } +} + +#[derive(Deserialize)] +struct UsageGroup { + #[serde(default)] + buckets: Lenient>, +} + +/// A bucket's fields are each optional: one of the wrong type drops the bucket, not the payload. +#[derive(Deserialize)] +struct UsageBucket { + #[serde(default)] + id: Lenient, + #[serde(default)] + window: Lenient, + #[serde(default)] + remaining_fraction: Lenient, + #[serde(default)] + reset_time: Lenient, +} + +/// A value of the expected kind, or `None` for anything else, skipped without being stored. +struct Lenient(Option); + +impl Default for Lenient { + fn default() -> Self { + Self(None) + } +} + +/// What a lenient field accepts. +trait LenientKind: Sized { + fn from_str(_: &str) -> Option { + None + } + fn from_f64(_: f64) -> Option { + None + } + fn from_seq<'de, A: SeqAccess<'de>>(seq: A) -> Result, A::Error> { + skip_seq(seq).map(|()| None) + } + fn from_map<'de, A: MapAccess<'de>>(mut map: A) -> Result, A::Error> { + while map.next_entry::()?.is_some() {} + Ok(None) + } +} + +impl LenientKind for UsageBucket { + fn from_map<'de, A: MapAccess<'de>>(map: A) -> Result, A::Error> { + Self::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(Some) + } +} + +impl LenientKind for String { + fn from_str(value: &str) -> Option { + Some(value.to_owned()) + } +} + +impl LenientKind for f64 { + fn from_f64(value: f64) -> Option { + Some(value) + } +} + +impl LenientKind for Vec { + fn from_seq<'de, A: SeqAccess<'de>>(mut seq: A) -> Result, A::Error> { + // An entry that is not an object is skipped like a bucket with no usable field. + let mut buckets = Vec::new(); + while let Some(Lenient(bucket)) = seq.next_element::>()? { + buckets.extend(bucket); + } + Ok(Some(buckets)) + } +} + +fn skip_seq<'de, A: SeqAccess<'de>>(mut seq: A) -> Result<(), A::Error> { + while seq.next_element::()?.is_some() {} + Ok(()) +} + +impl<'de, T: LenientKind> Deserialize<'de> for Lenient { + fn deserialize>(deserializer: D) -> Result { + struct LenientVisitor(std::marker::PhantomData); + + impl<'de, T: LenientKind> Visitor<'de> for LenientVisitor { + type Value = Lenient; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("any JSON value") + } + + fn visit_str(self, value: &str) -> Result { + Ok(Lenient(T::from_str(value))) + } + + fn visit_f64(self, value: f64) -> Result { + Ok(Lenient(T::from_f64(value))) + } + + #[allow(clippy::cast_precision_loss)] // a fraction: whole numbers are 0 and 1 + fn visit_u64(self, value: u64) -> Result { + Ok(Lenient(T::from_f64(value as f64))) + } + + #[allow(clippy::cast_precision_loss)] + fn visit_i64(self, value: i64) -> Result { + Ok(Lenient(T::from_f64(value as f64))) + } + + fn visit_bool(self, _: bool) -> Result { + Ok(Lenient(None)) + } + + fn visit_unit(self) -> Result { + Ok(Lenient(None)) + } + + fn visit_seq>(self, seq: A) -> Result { + T::from_seq(seq).map(Lenient) + } + + fn visit_map>(self, map: A) -> Result { + T::from_map(map).map(Lenient) + } + } + + deserializer.deserialize_any(LenientVisitor(std::marker::PhantomData)) + } +} + +/// Reads the allowlisted fields of the CLI's JSON. `None` means "not the shape BiBCode reads". +/// A group with no usable bucket is skipped. When two buckets land on the same group and window +/// (two unknown prefixes both become "Other models"), the tighter one is kept: it is the limit +/// that stops work first. +pub(super) fn parse_usage(stdout: &[u8], now: OffsetDateTime) -> Option { + let Object(output) = serde_json::from_slice::>(stdout).ok()?; + let Object(command) = output.command?; + // The guard: a CLI that answered the text as a prompt has no command and spent a turn. + if command.name.as_deref() != Some("usage") + || output.num_turns != Some(0) + || output.status.as_deref() != Some("SUCCESS") + { + return None; + } + let Object(data) = command.data?; + let groups = data.groups?; + let mut by_class: BTreeMap = BTreeMap::new(); + for bucket in groups + .into_iter() + .flat_map(|Object(group)| group.buckets.0.unwrap_or_default()) + { + let Some((rank, id, label)) = bucket.id.0.as_deref().map(classify_bucket) else { + continue; + }; + let Some((is_session, minutes)) = + bucket.window.0.as_deref().and_then(|window| match window { + "5h" => Some((true, 300)), + "weekly" => Some((false, 10_080)), + _ => None, + }) + else { + continue; + }; + let Some(remaining) = bucket + .remaining_fraction + .0 + .filter(|fraction| fraction.is_finite()) + else { + continue; + }; + let window = ProviderUsageWindow { + used_percent: ((1.0 - remaining) * 100.0).round().clamp(0.0, 100.0) as u32, + window_minutes: minutes, + resets_at: bucket.reset_time.0.as_deref().and_then(|text| { + OffsetDateTime::parse(text, &time::format_description::well_known::Rfc3339).ok() + }), + reset_description: None, + }; + let entry = by_class.entry(rank).or_insert(ProviderUsageWindowGroup { + id, + label, + session: None, + weekly: None, + }); + let slot = if is_session { + &mut entry.session + } else { + &mut entry.weekly + }; + if slot + .as_ref() + .is_none_or(|kept| window.used_percent > kept.used_percent) + { + *slot = Some(window); + } + } + let window_groups: Vec<_> = by_class.into_values().collect(); + if window_groups.is_empty() { + return None; + } + Some(ProviderUsageSnapshot { + provider: ProviderUsageProvider::Antigravity, + status: ProviderUsageStatus::Ok, + session: None, + weekly: None, + fable_weekly: None, + window_groups, + plan_type: None, + rate_limit_reset_credits: None, + updated_at: now, + error: None, + metadata: BTreeMap::new(), + }) +} + +/// The group a bucket belongs to, from its id prefix only (the CLI's group name is free text). +fn classify_bucket(id: &str) -> (usize, &'static str, &'static str) { + if id.starts_with("gemini-") { + (0, "gemini", "Gemini models") + } else if id.starts_with("3p-") { + (1, "third-party", "Claude and GPT models") + } else { + (2, "other", "Other models") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// A private marker in every free-text field: none may reach the snapshot. + const MARKER: &str = "PRIVATE-PLAN-MARKER"; + + fn payload() -> Value { + json!({ + "status": "SUCCESS", + "num_turns": 0, + "response": MARKER, + "conversation_id": MARKER, + "command": { + "name": "usage", + "data": { + "description": MARKER, + "groups": [ + { + "name": MARKER, + "description": MARKER, + "buckets": [ + {"id": "gemini-weekly", "name": MARKER, "description": MARKER, "window": "weekly", "remaining_fraction": 0.986, "reset_time": "2026-11-28T21:28:19Z"}, + {"id": "gemini-5h", "name": MARKER, "window": "5h", "remaining_fraction": 0.5, "reset_time": "2026-11-22T02:28:19Z"} + ] + }, + { + "name": MARKER, + "buckets": [ + {"id": "3p-weekly", "window": "weekly", "remaining_fraction": 1, "reset_time": "2026-11-28T21:50:39Z"}, + {"id": "3p-5h", "window": "5h", "remaining_fraction": 0, "reset_time": "2026-11-22T02:50:39Z"} + ] + } + ] + } + } + }) + } + + fn parse(value: &Value) -> Option { + parse_usage(value.to_string().as_bytes(), OffsetDateTime::UNIX_EPOCH) + } + + #[test] + fn the_measured_shape_maps_to_two_groups_with_used_percent_and_minutes() { + let snapshot = parse(&payload()).expect("measured shape"); + assert_eq!(snapshot.status, ProviderUsageStatus::Ok); + assert!(snapshot.session.is_none() && snapshot.weekly.is_none()); + let [gemini, third] = snapshot.window_groups.as_slice() else { + panic!("two groups"); + }; + assert_eq!((gemini.id, gemini.label), ("gemini", "Gemini models")); + assert_eq!(third.label, "Claude and GPT models"); + let weekly = gemini.weekly.as_ref().expect("weekly"); + assert_eq!((weekly.used_percent, weekly.window_minutes), (1, 10_080)); + assert!(weekly.resets_at.is_some()); + let session = gemini.session.as_ref().expect("session"); + assert_eq!((session.used_percent, session.window_minutes), (50, 300)); + assert_eq!(third.session.as_ref().expect("3p 5h").used_percent, 100); + assert_eq!(third.weekly.as_ref().expect("3p weekly").used_percent, 0); + } + + #[test] + fn no_free_text_field_reaches_the_snapshot() { + let snapshot = parse(&payload()).expect("measured shape"); + assert!(!format!("{snapshot:?}").contains(MARKER)); + } + + #[test] + fn the_guard_rejects_another_command_a_turn_or_a_failed_status() { + for (pointer, replacement) in [ + ("/command/name", json!("credits")), + ("/num_turns", json!(1)), + ("/status", json!("ERROR")), + ] { + let mut value = payload(); + *value.pointer_mut(pointer).expect("field") = replacement; + assert!(parse(&value).is_none(), "{pointer}"); + } + let mut missing_turns = payload(); + missing_turns.as_object_mut().unwrap().remove("num_turns"); + assert!(parse(&missing_turns).is_none()); + let mut no_command = payload(); + no_command.as_object_mut().unwrap().remove("command"); + assert!(parse(&no_command).is_none()); + } + + #[test] + fn fraction_and_time_boundaries_are_handled() { + let cases = [ + (json!(0), 100), + (json!(1), 0), + (json!(0.004), 100), + (json!(0.996), 0), + (json!(0.5), 50), + (json!(-0.3), 100), + (json!(1.7), 0), + ]; + for (fraction, used) in cases { + let mut value = payload(); + *value + .pointer_mut("/command/data/groups/0/buckets/1/remaining_fraction") + .unwrap() = fraction.clone(); + let snapshot = parse(&value).expect("shape"); + assert_eq!( + snapshot.window_groups[0] + .session + .as_ref() + .unwrap() + .used_percent, + used, + "{fraction}" + ); + } + let mut value = payload(); + *value + .pointer_mut("/command/data/groups/0/buckets/1/remaining_fraction") + .unwrap() = json!("0.5"); + let snapshot = parse(&value).expect("the other buckets still parse"); + assert!( + snapshot.window_groups[0].session.is_none(), + "non-numeric fraction is dropped" + ); + for reset in [ + json!(1_790_000_000), + json!("1790000000"), + json!("2026-11-22"), + json!("soon"), + ] { + let mut value = payload(); + *value + .pointer_mut("/command/data/groups/0/buckets/1/reset_time") + .unwrap() = reset.clone(); + let snapshot = parse(&value).expect("shape"); + assert!( + snapshot.window_groups[0] + .session + .as_ref() + .unwrap() + .resets_at + .is_none(), + "{reset} is not RFC 3339" + ); + } + } + + #[test] + fn an_unknown_window_or_prefix_is_dropped_or_grouped_as_other() { + let mut value = payload(); + *value + .pointer_mut("/command/data/groups/0/buckets/1/window") + .unwrap() = json!("daily"); + value + .pointer_mut("/command/data/groups/1/buckets") + .unwrap() + .as_array_mut() + .unwrap() + .push(json!({"id": "new-5h", "window": "5h", "remaining_fraction": 0.9})); + let snapshot = parse(&value).expect("shape"); + assert!(snapshot.window_groups[0].session.is_none()); + assert_eq!(snapshot.window_groups.last().unwrap().label, "Other models"); + let empty = json!({"status": "SUCCESS", "num_turns": 0, "command": {"name": "usage", "data": {"groups": []}}}); + assert!(parse(&empty).is_none()); + } + + #[test] + fn a_group_without_usable_buckets_is_skipped_not_the_payload() { + for extra in [ + json!({"name": MARKER}), + json!({"name": MARKER, "buckets": "none"}), + json!({"buckets": {"id": "gemini-5h"}}), + json!({"buckets": [{"id": 7, "window": ["5h"], "remaining_fraction": {"v": 1}}]}), + json!({"buckets": [7, "gemini-5h", null, [MARKER]]}), + ] { + let mut value = payload(); + value + .pointer_mut("/command/data/groups") + .unwrap() + .as_array_mut() + .unwrap() + .push(extra.clone()); + let snapshot = parse(&value).unwrap_or_else(|| panic!("{extra} rejected the payload")); + assert_eq!(snapshot.window_groups.len(), 2, "{extra}"); + } + } + + #[test] + fn positional_arrays_never_stand_in_for_the_guard_objects() { + let groups = payload().pointer("/command/data/groups").unwrap().clone(); + for value in [ + json!({"status": "SUCCESS", "num_turns": 0, "command": ["usage", {"groups": groups}]}), + json!(["SUCCESS", 0, {"name": "usage", "data": {"groups": groups}}]), + json!({"status": "SUCCESS", "num_turns": 0, "command": {"name": "usage", "data": [groups]}}), + ] { + assert!(parse(&value).is_none(), "{value}"); + } + } + + #[test] + fn two_buckets_on_one_group_and_window_keep_the_tighter() { + let mut value = payload(); + let buckets = value + .pointer_mut("/command/data/groups/1/buckets") + .unwrap() + .as_array_mut() + .unwrap(); + buckets.push(json!({"id": "new-5h", "window": "5h", "remaining_fraction": 0.9})); + buckets.push(json!({"id": "other-5h", "window": "5h", "remaining_fraction": 0.2})); + buckets.push(json!({"id": "late-5h", "window": "5h", "remaining_fraction": 0.6})); + let snapshot = parse(&value).expect("shape"); + let other = snapshot.window_groups.last().unwrap(); + assert_eq!(other.label, "Other models"); + assert_eq!(other.session.as_ref().unwrap().used_percent, 80); + } + + #[test] + fn only_one_version_token_at_or_above_the_minimum_passes() { + for (text, ok) in [ + ("1.5.14\n", true), + ("1.1.11", true), + ("1.1.10", false), + ("0.9.0", false), + ("2.0.0", true), + ("1.5.14\nextra", false), + ("agy 1.5.14", false), + ("1.5.14-beta.1", false), + ("", false), + ] { + assert_eq!(version_is_supported(text.as_bytes()), ok, "{text:?}"); + } + } + + #[test] + fn the_default_instance_is_read_explicit_first_and_legacy_as_fallback() { + assert!(!default_instance_enabled(&json!({}))); + assert!(default_instance_enabled( + &json!({"providers": {"antigravity": {"enabled": true}}}) + )); + // Saving the default card writes the explicit instance and resets the legacy entry. + assert!(default_instance_enabled(&json!({ + "providers": {"antigravity": {"enabled": false}}, + "providerInstances": {"antigravity": {"driver": "antigravity", "enabled": true}} + }))); + assert!(!default_instance_enabled(&json!({ + "providers": {"antigravity": {"enabled": true}}, + "providerInstances": {"antigravity": {"driver": "antigravity", "enabled": false}} + }))); + } + + #[cfg(unix)] + mod fake_cli { + use super::*; + use crate::test_support::TestSandbox; + + const USAGE_JSON: &str = r#"{"status":"SUCCESS","num_turns":0,"response":"PRIVATE-PLAN-MARKER","command":{"name":"usage","data":{"groups":[{"name":"PRIVATE-PLAN-MARKER","buckets":[{"id":"gemini-5h","window":"5h","remaining_fraction":0.5,"reset_time":"2026-11-22T02:28:19Z"}]}]}}}"#; + + struct Fixture { + sandbox: TestSandbox, + log: PathBuf, + } + + impl Fixture { + fn new() -> Self { + let sandbox = TestSandbox::new("agy-usage"); + let log = sandbox.path("calls.log"); + Self { sandbox, log } + } + + /// Writes the fake `agy`; `version` is what `--version` prints, `exit_code` the + /// usage run's exit status. Returns the settings document pointing at it. + fn install(&self, version: &str, exit_code: i32, padding: &str) -> Value { + let body = format!( + "# {padding}\necho \"$1\" >> '{log}'\nif [ \"$1\" = \"--version\" ]; then printf '%s' '{version}'; exit 0; fi\nprintf '%s' '{usage}'\necho PRIVATE-PLAN-MARKER >&2\nexit {exit_code}", + log = self.log.display(), + usage = USAGE_JSON, + ); + let path = self.sandbox.executable_script("agy", &body, ""); + json!({ + "providerInstances": {"antigravity": { + "driver": "antigravity", + "enabled": true, + "config": {"binaryPath": path.to_string_lossy()} + }} + }) + } + + fn calls(&self) -> Vec { + std::fs::read_to_string(&self.log) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + } + + async fn fetch( + document: &Value, + verified: &StdMutex>, + ) -> Result { + fetch_for_document(document, None, verified, DEADLINE).await + } + + #[tokio::test] + async fn a_verified_cli_is_probed_once_and_never_leaks_its_free_text() { + let fixture = Fixture::new(); + let document = fixture.install("1.5.14", 0, "a"); + let verified = StdMutex::default(); + let snapshot = fetch(&document, &verified).await.expect("fetch"); + assert_eq!(snapshot.status, ProviderUsageStatus::Ok); + assert!(!format!("{snapshot:?}").contains(MARKER)); + fetch(&document, &verified).await.expect("second fetch"); + assert_eq!(fixture.calls(), ["--version", "-p", "-p"]); + } + + #[tokio::test] + async fn a_same_path_downgrade_is_probed_again_and_spawns_no_usage_run() { + let fixture = Fixture::new(); + let document = fixture.install("1.5.14", 0, "a"); + let verified = StdMutex::default(); + fetch(&document, &verified).await.expect("fetch"); + // The executable at the same path is replaced by an older CLI. + fixture.install("1.1.10", 0, "a longer padding changes the size"); + let snapshot = fetch(&document, &verified).await.expect("fetch"); + assert_eq!(snapshot.status, ProviderUsageStatus::Unavailable); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_VERSION)); + assert_eq!(fixture.calls(), ["--version", "-p", "--version"]); + } + + #[tokio::test] + async fn unconfirmable_versions_never_run_usage() { + for version in ["agy 1.5.14", "1.5.14 extra", "", "1.1.10"] { + let fixture = Fixture::new(); + let document = fixture.install(version, 0, "a"); + let snapshot = fetch(&document, &StdMutex::default()).await.expect("fetch"); + assert_eq!( + snapshot.error.as_deref(), + Some(MESSAGE_VERSION), + "{version:?}" + ); + assert_eq!(fixture.calls(), ["--version"], "{version:?}"); + } + } + + #[tokio::test] + async fn exit_code_two_means_no_account_quota_and_other_failures_are_transient() { + let fixture = Fixture::new(); + let document = fixture.install("1.5.14", 2, "a"); + let snapshot = fetch(&document, &StdMutex::default()).await.expect("fetch"); + assert_eq!(snapshot.status, ProviderUsageStatus::Unavailable); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_API_KEY)); + let fixture = Fixture::new(); + let document = fixture.install("1.5.14", 1, "a"); + let error = fetch(&document, &StdMutex::default()) + .await + .expect_err("failure"); + assert_eq!(error.message, MESSAGE_TRANSIENT); + assert!(!error.message.contains(MARKER)); + } + + #[tokio::test] + async fn a_disabled_default_instance_spawns_nothing() { + let fixture = Fixture::new(); + let mut document = fixture.install("1.5.14", 0, "a"); + document["providerInstances"]["antigravity"]["enabled"] = json!(false); + let snapshot = fetch(&document, &StdMutex::default()).await.expect("fetch"); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_DISABLED)); + assert!(fixture.calls().is_empty()); + } + + fn document_for(path: &Path) -> Value { + json!({ + "providerInstances": {"antigravity": { + "driver": "antigravity", + "enabled": true, + "config": {"binaryPath": path.to_string_lossy()} + }} + }) + } + + /// A fake `agy` that logs `$1` and answers `--version` with 1.5.14 unless `version` + /// replaces that branch, and the usage run with `usage`. + fn script(fixture: &Fixture, name: &str, version: &str, usage: &str) -> PathBuf { + let body = format!( + "echo \"$1\" >> '{log}'\nif [ \"$1\" = \"--version\" ]; then {version}; fi\n{usage}", + log = fixture.log.display(), + ); + fixture.sandbox.executable_script(name, &body, "") + } + + const VERSION_OK: &str = "printf 1.5.14; exit 0"; + fn usage_ok() -> String { + format!("printf '%s' '{USAGE_JSON}'") + } + + #[tokio::test] + async fn both_runs_launch_the_verified_file_even_when_its_symlink_is_retargeted() { + let fixture = Fixture::new(); + let old_log = fixture.sandbox.path("old.log"); + // The newer CLI holds its version answer while the link is switched to an older one. + let newer = script( + &fixture, + "agy-new", + "sleep 1; printf 1.5.14; exit 0", + &usage_ok(), + ); + let older = fixture.sandbox.executable_script( + "agy-old", + &format!( + "echo \"$1\" >> '{}'\nif [ \"$1\" = \"--version\" ]; then printf 1.1.10; exit 0; fi\nexit 0", + old_log.display() + ), + "", + ); + let link = fixture.sandbox.path("agy"); + std::os::unix::fs::symlink(&newer, &link).expect("link"); + let document = document_for(&link); + let fetch = tokio::spawn(async move { + fetch_for_document(&document, None, &StdMutex::default(), DEADLINE).await + }); + tokio::time::sleep(Duration::from_millis(300)).await; + std::fs::remove_file(&link).expect("unlink"); + std::os::unix::fs::symlink(&older, &link).expect("relink"); + let snapshot = fetch.await.expect("task").expect("fetch"); + assert_eq!(snapshot.status, ProviderUsageStatus::Ok); + assert_eq!(fixture.calls(), ["--version", "-p"]); + assert!( + std::fs::read_to_string(&old_log) + .unwrap_or_default() + .is_empty(), + "the unverified CLI ran" + ); + } + + #[tokio::test] + async fn both_runs_see_end_of_file_on_stdin() { + let fixture = Fixture::new(); + let body = format!( + "if [ /dev/stdin -ef /dev/null ]; then s=closed; else s=open; fi\necho \"$1:$s\" >> '{log}'\nif [ \"$1\" = \"--version\" ]; then {VERSION_OK}; fi\n{usage}", + log = fixture.log.display(), + usage = usage_ok(), + ); + let path = fixture.sandbox.executable_script("agy", &body, ""); + let snapshot = fetch(&document_for(&path), &StdMutex::default()) + .await + .expect("fetch"); + assert_eq!(snapshot.status, ProviderUsageStatus::Ok); + assert_eq!(fixture.calls(), ["--version:closed", "-p:closed"]); + } + + #[tokio::test] + async fn the_instance_environment_includes_its_stored_secret() { + use crate::server_settings::{ + ProviderEnvironmentVariableInput, ProviderInstanceInput, ServerSettingsPatch, + }; + let fixture = Fixture::new(); + let body = format!( + "echo \"$1:$GEMINI_API_KEY\" >> '{log}'\nif [ \"$1\" = \"--version\" ]; then {VERSION_OK}; fi\nexit 2", + log = fixture.log.display(), + ); + let path = fixture.sandbox.executable_script("agy", &body, ""); + let root = fixture.sandbox.path("settings"); + let store = ProviderSettingsStore::new(&root); + store + .update(ServerSettingsPatch { + provider_instances: Some(BTreeMap::from([( + "antigravity".to_owned(), + ProviderInstanceInput { + driver: "antigravity".to_owned(), + enabled: true, + display_name: None, + environment: vec![ProviderEnvironmentVariableInput { + name: "GEMINI_API_KEY".to_owned(), + value: "test-key-value".to_owned(), + sensitive: true, + value_redacted: false, + }], + config: json!({"binaryPath": path.to_string_lossy()}), + }, + )])), + ..ServerSettingsPatch::default() + }) + .await + .expect("save"); + let persisted = std::fs::read_to_string(root.join("settings.json")).expect("saved"); + assert!( + !persisted.contains("test-key-value"), + "the secret is stored apart" + ); + let snapshot = (fetcher(store, None).fetch)().await.expect("fetch"); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_API_KEY)); + assert_eq!( + fixture.calls(), + ["--version:test-key-value", "-p:test-key-value"] + ); + } + + #[tokio::test] + async fn a_saved_legacy_disable_still_wins_over_an_instance_without_enabled() { + let fixture = Fixture::new(); + let path = script(&fixture, "agy", VERSION_OK, &usage_ok()); + let root = fixture.sandbox.path("settings"); + std::fs::create_dir_all(&root).expect("settings root"); + let instance = json!({ + "driver": "antigravity", + "config": {"binaryPath": path.to_string_lossy()} + }); + // Without a legacy entry the built-in default (off) decides, as for the inventory. + for document in [ + json!({ + "providers": {"antigravity": {"enabled": false}}, + "providerInstances": {"antigravity": instance.clone()} + }), + json!({ "providerInstances": {"antigravity": instance.clone()} }), + ] { + std::fs::write(root.join("settings.json"), document.to_string()).expect("settings"); + let snapshot = (fetcher(ProviderSettingsStore::new(&root), None).fetch)() + .await + .expect("fetch"); + assert_eq!( + snapshot.error.as_deref(), + Some(MESSAGE_DISABLED), + "{document}" + ); + assert!(fixture.calls().is_empty()); + } + } + + #[tokio::test] + async fn a_descendant_holding_stdout_open_is_stopped_at_the_deadline() { + let fixture = Fixture::new(); + let pid_file = fixture.sandbox.path("descendant.pid"); + let path = script( + &fixture, + "agy", + VERSION_OK, + &format!( + "sleep 30 &\necho $! > '{}'\nprintf partial\nexit 0", + pid_file.display() + ), + ); + let started = std::time::Instant::now(); + let error = fetch_for_document( + &document_for(&path), + None, + &StdMutex::default(), + Duration::from_secs(1), + ) + .await + .expect_err("the deadline cancels the run"); + assert_eq!(error.message, MESSAGE_TRANSIENT); + assert!(started.elapsed() < Duration::from_secs(10)); + let pid: libc::pid_t = std::fs::read_to_string(&pid_file) + .expect("pid") + .trim() + .parse() + .expect("pid"); + let mut alive = true; + for _ in 0..50 { + // SAFETY: signal 0 only checks whether the process exists. + alive = unsafe { libc::kill(pid, 0) } == 0; + if !alive { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(!alive, "the descendant survived the deadline"); + } + + #[tokio::test] + async fn truncated_version_or_usage_output_is_never_trusted() { + let fixture = Fixture::new(); + let path = script( + &fixture, + "agy", + "printf 1.5.14; head -c 70000 /dev/zero | tr '\\0' ' '; exit 0", + &usage_ok(), + ); + let snapshot = fetch(&document_for(&path), &StdMutex::default()) + .await + .expect("fetch"); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_VERSION)); + assert_eq!(fixture.calls(), ["--version"]); + + let fixture = Fixture::new(); + let path = script( + &fixture, + "agy", + VERSION_OK, + &format!("{}; head -c 70000 /dev/zero | tr '\\0' ' '", usage_ok()), + ); + let snapshot = fetch(&document_for(&path), &StdMutex::default()) + .await + .expect("fetch"); + assert_eq!(snapshot.error.as_deref(), Some(MESSAGE_FORMAT)); + } + + /// Shutdown while the usage run's spawn is held (the script is still open for writing, + /// `ETXTBSY`): once shutdown returns, the CLI neither runs nor starts later (#414). + #[cfg(target_os = "linux")] + #[tokio::test] + async fn shutdown_during_a_held_usage_spawn_leaves_no_cli_process() { + let fixture = Fixture::new(); + let release = fixture.sandbox.path("release"); + let ready = fixture.sandbox.path("ready"); + let version_pid = fixture.sandbox.path("version.pid"); + // `--version` records its process id, leaves a writer on the script until `release` + // exists (for at most 30 s), and answers only once that writer is open. + let holder = format!( + "echo $$ > '{pid}'\n(exec 3>>\"$0\"; : > '{ready}'; i=0; while [ ! -e '{release}' ] && [ $i -lt 3000 ]; do sleep 0.01; i=$((i+1)); done) /dev/null 2>&1 &\nwhile [ ! -e '{ready}' ]; do sleep 0.01; done\n{VERSION_OK}", + pid = version_pid.display(), + ready = ready.display(), + release = release.display() + ); + let path = script(&fixture, "agy", &holder, &usage_ok()); + let document = document_for(&path); + let verified: Arc>> = Arc::default(); + let fetcher = ProviderUsageFetcher { + provider: ProviderUsageProvider::Antigravity, + fetch: Arc::new(move || -> FetchFuture { + let (document, verified) = (document.clone(), verified.clone()); + Box::pin(async move { + fetch_for_document(&document, None, &verified, DEADLINE).await + }) + }), + }; + let service = crate::provider_usage::ProviderUsageService::new( + vec![fetcher], + Arc::new(OffsetDateTime::now_utc), + ); + let refresh = tokio::spawn({ + let service = service.clone(); + async move { + service + .refresh_forced(Some(vec![ProviderUsageProvider::Antigravity])) + .await + } + }); + // Ready once the version probe was reaped: the attempt then goes straight to the + // usage spawn, which retries against the busy script for up to one second. + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Ok(pid) = std::fs::read_to_string(&version_pid) + && !Path::new(&format!("/proc/{}", pid.trim())).exists() + { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the version probe ended"); + tokio::time::sleep(Duration::from_millis(50)).await; + // Still inside the retry window: the attempt ends only when the spawn gives up. + assert!( + service.read().await.is_fetching, + "the usage spawn gave up before shutdown" + ); + let shutdown = tokio::spawn({ + let service = service.clone(); + async move { service.shutdown().await } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + // Released after shutdown cancelled the attempt: a spawn still retrying would start. + std::fs::write(&release, "").expect("release the writer"); + shutdown.await.expect("shutdown task"); + let _ = refresh.await; + let held = service.single_flights[&ProviderUsageProvider::Antigravity] + .lock() + .unwrap() + .cooldown_from; + assert!(held.is_none(), "the usage CLI was spawned after shutdown"); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(fixture.calls(), ["--version"]); + let running = std::process::Command::new("pgrep") + .arg("-f") + .arg(&path) + .status() + .expect("pgrep"); + assert!(!running.success(), "a usage CLI process is still running"); + } + + #[tokio::test] + async fn failures_log_a_class_never_the_cli_text() { + let Some(child) = crate::test_support::in_own_process( + "provider_usage::antigravity::tests::fake_cli::failures_log_a_class_never_the_cli_text", + ) else { + return; + }; + let log = CapturedLog::default(); + let _logging = tracing::subscriber::set_default( + tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .with_writer({ + let log = log.clone(); + move || log.clone() + }) + .finish(), + ); + // A non-zero exit, then a run cut off by the deadline, both with the marker on + // stdout and stderr. + for (usage, deadline) in [ + ( + format!("{}; echo {MARKER} >&2; exit 1", usage_ok()), + DEADLINE, + ), + ( + format!("echo {MARKER}; echo {MARKER} >&2; sleep 30"), + Duration::from_secs(1), + ), + ] { + let fixture = Fixture::new(); + let path = script(&fixture, "agy", VERSION_OK, &usage); + let error = + fetch_for_document(&document_for(&path), None, &StdMutex::default(), deadline) + .await + .expect_err("failure"); + assert!(!error.message.contains(MARKER)); + } + let log = String::from_utf8(log.0.lock().unwrap().clone()).unwrap(); + assert!( + log.contains("Antigravity usage exited unsuccessfully"), + "{log}" + ); + assert!(log.contains("Antigravity usage run failed"), "{log}"); + assert!( + !log.contains(MARKER), + "the CLI's text reached the log:\n{log}" + ); + child.complete(); + } + + #[derive(Clone, Default)] + struct CapturedLog(Arc>>); + + impl std::io::Write for CapturedLog { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + } +} diff --git a/apps/server/src/provider_usage/mod.rs b/apps/server/src/provider_usage/mod.rs index 28e4afd466..fc02f0ab51 100644 --- a/apps/server/src/provider_usage/mod.rs +++ b/apps/server/src/provider_usage/mod.rs @@ -5,7 +5,7 @@ use std::{ path::PathBuf, pin::Pin, process::Stdio, - sync::Arc, + sync::{Arc, Mutex as StdMutex, PoisonError}, time::Duration, }; @@ -18,6 +18,7 @@ use tokio::{ process::Command, sync::Mutex, }; +use tokio_util::sync::CancellationToken; use crate::{ process::configure_background_command, @@ -25,6 +26,7 @@ use crate::{ provider::environment::sanitize_provider_subprocess_environment, }; +mod antigravity; mod codex_backend; pub const MIN_MANUAL_REFRESH_MS: i64 = 30_000; @@ -48,6 +50,7 @@ struct MacOsKeychainCommand { pub enum ProviderUsageProvider { Claude, Codex, + Antigravity, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -67,6 +70,16 @@ pub struct ProviderUsageWindow { pub reset_description: Option, } +/// One quota group of a provider that reports several (Antigravity: one per model family). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProviderUsageWindowGroup { + /// `gemini`, `third-party` or `other`. + pub id: &'static str, + pub label: &'static str, + pub session: Option, + pub weekly: Option, +} + #[derive(Clone, Debug, Eq, PartialEq)] pub struct RateLimitResetCredits { pub available_count: u32, @@ -81,6 +94,7 @@ pub struct ProviderUsageSnapshot { pub session: Option, pub weekly: Option, pub fable_weekly: Option, + pub window_groups: Vec, pub plan_type: Option, pub rate_limit_reset_credits: Option, pub updated_at: OffsetDateTime, @@ -224,6 +238,29 @@ pub struct ProviderUsageService { state: Arc>, consume_codex_reset: ConsumeCodexReset, codex_reset_lock: Arc>, + /// Providers whose fetch runs as one attempt at a time that no caller owns (Antigravity). + single_flights: Arc>>>, +} + +/// One attempt at a time for a provider whose fetch is expensive. The attempt is a task of its +/// own: a caller that goes away neither stops it nor loses its result for the others, and its +/// result is committed once. +#[derive(Default)] +struct SingleFlight { + /// The running attempt; a caller that arrives meanwhile waits for its result. + running: Option, + /// When the last attempt that spawned the provider's command finished: the cooldown starts + /// here. + cooldown_from: Option, + /// Set at shutdown: no attempt starts after it. + closed: bool, +} + +/// The service owns a running attempt: its result channel, the token that stops it, and its +/// task, which shutdown waits for. +struct RunningAttempt { + receiver: tokio::sync::watch::Receiver>, + cancel: CancellationToken, } #[derive(Clone, Copy)] @@ -249,6 +286,10 @@ impl ProviderUsageService { state: Arc::new(Mutex::new(ProviderUsageState::default())), consume_codex_reset: production_codex_rate_limit_reset_consumer(), codex_reset_lock: Arc::new(Mutex::new(())), + single_flights: Arc::new(BTreeMap::from([( + ProviderUsageProvider::Antigravity, + Arc::default(), + )])), } } @@ -266,12 +307,21 @@ impl ProviderUsageService { } pub async fn read(&self) -> ProviderUsageResult { + self.read_selected(None).await + } + + /// The legacy providers, plus any other provider the request names: a client that does not + /// know a provider never receives it, because it would fail to decode the whole result. + pub async fn read_selected( + &self, + selected: Option<&[ProviderUsageProvider]>, + ) -> ProviderUsageResult { let read_at = (self.now)(); let state = self.state.lock().await; ProviderUsageResult { read_at, is_fetching: state.active_refreshes > 0, - providers: providers() + providers: response_providers(selected) .into_iter() .map(|provider| { let snapshot = state.snapshots.get(&provider).cloned().unwrap_or_else(|| { @@ -328,6 +378,201 @@ impl ProviderUsageService { &self, selected_providers: Option>, policy: RefreshPolicy, + ) -> ProviderUsageResult { + // Nothing to fetch: answer from the cache without taking the 30-second slot. + if selected_providers.as_ref().is_some_and(Vec::is_empty) { + return self.read_selected(Some(&[])).await; + } + let named = selected_providers.clone().unwrap_or_default(); + if !named + .iter() + .any(|provider| self.single_flights.contains_key(provider)) + { + return self.refresh_legacy(selected_providers, policy).await; + } + let (flights, legacy): (Vec<_>, Vec<_>) = named + .iter() + .copied() + .partition(|provider| self.single_flights.contains_key(provider)); + // The global slot only ever throttles the legacy part; Antigravity has its own cooldown. + let legacy_refresh = async { + if !legacy.is_empty() { + self.refresh_legacy(Some(legacy), policy).await; + } + }; + let attempts = + futures_util::future::join_all(flights.into_iter().map(|provider| async move { + (provider, self.join_single_flight(provider, policy).await) + })); + let ((), attempts) = tokio::join!(legacy_refresh, attempts); + let mut result = self.read_selected(Some(&named)).await; + for (provider, attempt) in attempts { + let (Some(snapshot), Some(slot)) = ( + attempt, + result + .providers + .iter_mut() + .find(|snapshot| snapshot.provider == provider), + ) else { + continue; + }; + // Every waiter answers with the attempt it waited for, not a later one. + *slot = apply_staleness(snapshot, result.read_at); + } + result + } + + /// Waits for the running attempt, or starts one unless a throttled request is inside the + /// cooldown (then the cache answers). `None` means "read the cache". + async fn join_single_flight( + &self, + provider: ProviderUsageProvider, + policy: RefreshPolicy, + ) -> Option { + let flight = self.single_flights.get(&provider)?; + let mut receiver = { + let mut held = flight.lock().unwrap_or_else(PoisonError::into_inner); + if held.closed { + return None; + } + // A closed channel is an attempt that died without answering: start another. + match held + .running + .as_ref() + .map(|running| running.receiver.clone()) + .filter(|running| running.has_changed().is_ok()) + { + Some(running) => running, + None => { + if matches!(policy, RefreshPolicy::Throttled) + && held + .cooldown_from + .is_some_and(|from| from.elapsed() < antigravity::MIN_INTERVAL) + { + return None; + } + let (sender, receiver) = tokio::sync::watch::channel(None); + let cancel = CancellationToken::new(); + tokio::spawn( + self.clone() + .run_single_flight(provider, sender, cancel.clone()), + ); + held.running = Some(RunningAttempt { + receiver: receiver.clone(), + cancel, + }); + receiver + } + } + }; + receiver + .wait_for(Option::is_some) + .await + .ok() + .and_then(|snapshot| snapshot.clone()) + } + + /// Closes Antigravity admission, stops a running attempt through its token and waits for it, + /// processes reaped included. The runtime calls it before process ownership is frozen. + pub async fn shutdown(&self) { + // Each call waits on its own receiver until the attempt drops its sender (it ends), so + // a shutdown cancelled while waiting leaves a retried one nothing less to wait for. + let attempts: Vec<_> = self + .single_flights + .values() + .filter_map(|flight| { + let mut held = flight.lock().unwrap_or_else(PoisonError::into_inner); + held.closed = true; + let running = held.running.as_ref()?; + running.cancel.cancel(); + Some(running.receiver.clone()) + }) + .collect(); + for mut attempt in attempts { + while attempt.changed().await.is_ok() {} + } + } + + /// One attempt: fetch under one deadline, commit once, release the flight, then answer every + /// waiter. The flight is released only after the fetch task has stopped. + async fn run_single_flight( + self, + provider: ProviderUsageProvider, + sender: tokio::sync::watch::Sender>, + cancel: CancellationToken, + ) { + let read_at = (self.now)(); + { + let mut state = self.state.lock().await; + state.active_refreshes = state.active_refreshes.saturating_add(1); + } + let spawned = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let snapshot = match self.fetchers.get(&provider).cloned() { + None => { + unavailable_snapshot(provider, read_at, "Provider usage fetcher is unavailable.") + } + Some(fetcher) => { + let attempt = UsageAttempt { + cancel: cancel.clone(), + spawned: spawned.clone(), + }; + // The factory runs inside the task too: a panic anywhere ends only the task. + let mut fetch = tokio::spawn( + USAGE_ATTEMPT.scope(attempt, async move { (fetcher.fetch)().await }), + ); + // One deadline covers the settings read, both runs and their cleanup. + let settled = tokio::select! { + joined = &mut fetch => Some(joined), + () = tokio::time::sleep(antigravity::ATTEMPT_DEADLINE) => None, + () = cancel.cancelled() => None, + }; + let joined = match settled { + Some(joined) => joined, + None => { + // Stop the processes through the supervisor, let it reap them, and stop + // a fetch that ignores the token: it never outlives the flight. + cancel.cancel(); + match tokio::time::timeout(antigravity::CLEANUP_GRACE, &mut fetch).await { + Ok(joined) => joined, + Err(_) => { + fetch.abort(); + fetch.await + } + } + } + }; + match joined { + Ok(Ok(snapshot)) => snapshot, + Ok(Err(error)) => error_snapshot(provider, read_at, error.message), + Err(_) => { + tracing::warn!(?provider, "provider usage attempt failed or was stopped"); + error_snapshot(provider, read_at, antigravity::MESSAGE_TRANSIENT.to_owned()) + } + } + } + }; + let ran = spawned.load(std::sync::atomic::Ordering::SeqCst); + let committed = { + let mut state = self.state.lock().await; + let snapshot = retain_last_good_usage(state.snapshots.get(&provider), snapshot); + state.snapshots.insert(provider, snapshot.clone()); + state.active_refreshes = state.active_refreshes.saturating_sub(1); + snapshot + }; + if let Some(flight) = self.single_flights.get(&provider) { + let mut held = flight.lock().unwrap_or_else(PoisonError::into_inner); + held.running = None; + if ran { + held.cooldown_from = Some(tokio::time::Instant::now()); + } + } + sender.send_replace(Some(committed)); + } + + async fn refresh_legacy( + &self, + selected_providers: Option>, + policy: RefreshPolicy, ) -> ProviderUsageResult { let (caller_lifetime, caller_dropped) = tokio::sync::oneshot::channel(); let service = self.clone(); @@ -469,6 +714,36 @@ impl ProviderUsageService { } } +/// What a single-flight attempt hands its fetch: the token that stops it, and where it records +/// that the provider's command was spawned. Only a spawn starts the cooldown, so a failure before +/// it (settings unreadable, CLI missing, version not confirmed) is retried at once. +#[derive(Clone)] +struct UsageAttempt { + cancel: CancellationToken, + spawned: Arc, +} + +tokio::task_local! { + static USAGE_ATTEMPT: UsageAttempt; +} + +/// Called by a fetch once its usage command was spawned. +pub(super) fn note_usage_spawned() { + let _ = USAGE_ATTEMPT.try_with(|attempt| { + attempt + .spawned + .store(true, std::sync::atomic::Ordering::SeqCst); + }); +} + +/// The token a fetch's processes must stop on: cancelled at the attempt's deadline and at +/// service shutdown. Outside an attempt, a token nothing cancels. +pub(super) fn attempt_cancellation() -> CancellationToken { + USAGE_ATTEMPT + .try_with(|attempt| attempt.cancel.child_token()) + .unwrap_or_default() +} + fn production_codex_rate_limit_reset_consumer() -> ConsumeCodexReset { Arc::new(|request_id| { Box::pin(async move { @@ -490,8 +765,15 @@ fn production_codex_rate_limit_reset_consumer() -> ConsumeCodexReset { } #[must_use] -pub fn production_fetchers() -> Vec { - vec![claude_fetcher(), codex_fetcher()] +pub fn production_fetchers( + settings: crate::server_settings::ProviderSettingsStore, + attribution: Option, +) -> Vec { + vec![ + claude_fetcher(), + codex_fetcher(), + antigravity::fetcher(settings, attribution), + ] } fn claude_fetcher() -> ProviderUsageFetcher { @@ -800,6 +1082,7 @@ async fn fetch_codex_usage() -> Result( session, weekly, fable_weekly, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -1131,6 +1415,15 @@ fn providers() -> Vec { vec![ProviderUsageProvider::Claude, ProviderUsageProvider::Codex] } +/// The legacy pair, plus Antigravity only when the request names it. +fn response_providers(selected: Option<&[ProviderUsageProvider]>) -> Vec { + let mut list = providers(); + if selected.is_some_and(|named| named.contains(&ProviderUsageProvider::Antigravity)) { + list.push(ProviderUsageProvider::Antigravity); + } + list +} + fn unavailable_snapshot( provider: ProviderUsageProvider, now: OffsetDateTime, @@ -1142,6 +1435,7 @@ fn unavailable_snapshot( session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -1161,6 +1455,7 @@ fn error_snapshot( session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -1170,11 +1465,22 @@ fn error_snapshot( } fn apply_staleness(snapshot: ProviderUsageSnapshot, now: OffsetDateTime) -> ProviderUsageSnapshot { - if snapshot.status != ProviderUsageStatus::Ok { - return snapshot; - } let age_ms = (now - snapshot.updated_at).whole_milliseconds(); - if age_ms <= i128::from(STALE_THRESHOLD_MS) { + let expired = age_ms > i128::from(STALE_THRESHOLD_MS); + if snapshot.provider == ProviderUsageProvider::Antigravity { + // Its quota moves fast: expired data, also data retained on an error, is not shown. + return if expired && has_usable_usage(&snapshot) { + ProviderUsageSnapshot { + status: ProviderUsageStatus::Unavailable, + error: Some("Provider usage snapshot is stale.".to_owned()), + window_groups: Vec::new(), + ..snapshot + } + } else { + snapshot + }; + } + if snapshot.status != ProviderUsageStatus::Ok || !expired { return snapshot; } ProviderUsageSnapshot { @@ -1206,6 +1512,7 @@ fn has_usable_usage(snapshot: &ProviderUsageSnapshot) -> bool { snapshot.session.is_some() || snapshot.weekly.is_some() || snapshot.fable_weekly.is_some() + || !snapshot.window_groups.is_empty() || snapshot.plan_type.is_some() || snapshot.rate_limit_reset_credits.is_some() } @@ -1389,6 +1696,7 @@ done"#, session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: Some(RateLimitResetCredits { available_count, @@ -1417,6 +1725,7 @@ done"#, }), weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at, @@ -2510,6 +2819,7 @@ done"#, }), weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -2556,7 +2866,14 @@ done"#, missing.providers[0].status, ProviderUsageStatus::Unavailable ); - assert_eq!(production_fetchers().len(), 2); + assert_eq!( + production_fetchers( + crate::server_settings::ProviderSettingsStore::new(std::env::temp_dir()), + None + ) + .len(), + 3 + ); } #[test] @@ -2568,6 +2885,7 @@ done"#, session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -2615,4 +2933,587 @@ done"#, ); assert_eq!(rpc_error(&json!({}), "fallback"), "fallback"); } + + type AntigravityScript = + Arc Result + Send + Sync>; + + fn ok_antigravity() -> ProviderUsageSnapshot { + ProviderUsageSnapshot { + provider: ProviderUsageProvider::Antigravity, + status: ProviderUsageStatus::Ok, + session: None, + weekly: None, + fable_weekly: None, + window_groups: vec![ProviderUsageWindowGroup { + id: "gemini", + label: "Gemini models", + session: Some(ProviderUsageWindow { + used_percent: 3, + window_minutes: 300, + resets_at: None, + reset_description: None, + }), + weekly: None, + }], + plan_type: None, + rate_limit_reset_credits: None, + updated_at: OffsetDateTime::now_utc(), + error: None, + metadata: BTreeMap::new(), + } + } + + /// An Antigravity fetcher whose answer depends on the call number (0-based). + fn scripted_antigravity( + calls: Arc, + delay: Duration, + script: AntigravityScript, + ) -> ProviderUsageFetcher { + ProviderUsageFetcher { + provider: ProviderUsageProvider::Antigravity, + fetch: Arc::new(move || { + let calls = calls.clone(); + let script = script.clone(); + Box::pin(async move { + let call = calls.fetch_add(1, Ordering::SeqCst); + tokio::time::sleep(delay).await; + let result = script(call); + // Like the real fetcher: an answer that is data or a failure ran the CLI. + if result + .as_ref() + .is_ok_and(|snapshot| snapshot.status != ProviderUsageStatus::Unavailable) + { + note_usage_spawned(); + } + result + }) + }), + } + } + + fn antigravity_fetcher(calls: Arc, delay: Duration) -> ProviderUsageFetcher { + scripted_antigravity(calls, delay, Arc::new(|_| Ok(ok_antigravity()))) + } + + fn codex_counter(codex: Arc) -> ProviderUsageFetcher { + test_fetcher(move || { + let codex = codex.clone(); + async move { + codex.fetch_add(1, Ordering::SeqCst); + Ok(snapshot_with_session( + ProviderUsageProvider::Codex, + OffsetDateTime::now_utc(), + 10, + )) + } + }) + } + + fn service_with( + calls: &Arc, + delay: Duration, + codex: Arc, + ) -> ProviderUsageService { + ProviderUsageService::new( + vec![ + antigravity_fetcher(calls.clone(), delay), + codex_counter(codex), + ], + Arc::new(OffsetDateTime::now_utc), + ) + } + + fn names(result: &ProviderUsageResult) -> Vec { + result + .providers + .iter() + .map(|snapshot| snapshot.provider) + .collect() + } + + fn antigravity_of(result: &ProviderUsageResult) -> &ProviderUsageSnapshot { + result + .providers + .iter() + .find(|snapshot| snapshot.provider == ProviderUsageProvider::Antigravity) + .expect("the request named Antigravity") + } + + fn only_antigravity() -> Option> { + Some(vec![ProviderUsageProvider::Antigravity]) + } + + #[tokio::test] + async fn antigravity_appears_only_when_a_request_names_it() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, Arc::default()); + let legacy = vec![ProviderUsageProvider::Claude, ProviderUsageProvider::Codex]; + assert_eq!(names(&service.read().await), legacy); + assert_eq!(names(&service.refresh(None).await), legacy); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "an omitted list never fetches it" + ); + let named = service.refresh_forced(only_antigravity()).await; + assert_eq!( + names(&named).last(), + Some(&ProviderUsageProvider::Antigravity) + ); + let antigravity = named.providers.last().unwrap(); + assert_eq!(antigravity.status, ProviderUsageStatus::Ok); + assert_eq!(antigravity.window_groups.len(), 1); + let read = service + .read_selected(Some(&[ProviderUsageProvider::Antigravity])) + .await; + assert_eq!(read.providers.len(), 3); + // Naming only Codex (as the Codex reset result does) keeps the legacy shape. + let codex_only = service + .refresh_forced(Some(vec![ProviderUsageProvider::Codex])) + .await; + assert_eq!(names(&codex_only), legacy); + } + + #[tokio::test] + async fn the_interval_serves_the_cache_and_a_forced_refresh_bypasses_it() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, Arc::default()); + service.refresh(only_antigravity()).await; + let cached = service.refresh(only_antigravity()).await; + assert_eq!(calls.load(Ordering::SeqCst), 1, "inside the interval"); + assert_eq!(antigravity_of(&cached).status, ProviderUsageStatus::Ok); + service.refresh_forced(only_antigravity()).await; + assert_eq!( + calls.load(Ordering::SeqCst), + 2, + "forced bypasses the cooldown" + ); + } + + #[tokio::test] + async fn the_global_slot_and_the_interval_do_not_starve_each_other() { + let calls = Arc::new(AtomicUsize::new(0)); + let codex = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, codex.clone()); + // A legacy poll first, then the Antigravity request of the same cycle. + service + .refresh(Some(vec![ProviderUsageProvider::Codex])) + .await; + service.refresh(only_antigravity()).await; + assert_eq!( + (codex.load(Ordering::SeqCst), calls.load(Ordering::SeqCst)), + (1, 1) + ); + // An Antigravity-only request does not consume the slot a later legacy poll needs. + let calls = Arc::new(AtomicUsize::new(0)); + let codex = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, codex.clone()); + service.refresh(only_antigravity()).await; + service + .refresh(Some(vec![ProviderUsageProvider::Codex])) + .await; + assert_eq!( + (codex.load(Ordering::SeqCst), calls.load(Ordering::SeqCst)), + (1, 1) + ); + } + + #[tokio::test] + async fn a_mixed_request_inside_the_global_cooldown_still_reads_antigravity() { + let calls = Arc::new(AtomicUsize::new(0)); + let codex = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, codex.clone()); + service + .refresh(Some(vec![ProviderUsageProvider::Codex])) + .await; + let mixed = service + .refresh(Some(vec![ + ProviderUsageProvider::Codex, + ProviderUsageProvider::Antigravity, + ])) + .await; + assert_eq!(codex.load(Ordering::SeqCst), 1, "Codex stays throttled"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "Antigravity is not"); + assert_eq!(antigravity_of(&mixed).status, ProviderUsageStatus::Ok); + } + + #[tokio::test] + async fn simultaneous_forced_refreshes_run_one_attempt_and_both_callers_get_it() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::from_millis(80), Arc::default()); + let (first, second) = tokio::join!( + service.refresh_forced(only_antigravity()), + service.refresh_forced(only_antigravity()) + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "the second joins the first" + ); + assert_eq!(antigravity_of(&first).status, ProviderUsageStatus::Ok); + assert_eq!(antigravity_of(&second).status, ProviderUsageStatus::Ok); + } + + #[tokio::test] + async fn a_caller_cancelled_mid_attempt_neither_aborts_it_nor_poisons_the_cooldown() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::from_millis(200), Arc::default()); + let abandoned = tokio::time::timeout( + Duration::from_millis(30), + service.refresh_forced(only_antigravity()), + ) + .await; + assert!(abandoned.is_err(), "the caller gave up mid-fetch"); + // A throttled poll joins the attempt that is still running and gets its answer. + let next = service.refresh(only_antigravity()).await; + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(antigravity_of(&next).status, ProviderUsageStatus::Ok); + } + + #[tokio::test] + async fn a_waiter_cancelled_before_the_attempt_finishes_leaves_the_first_caller_its_result() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::from_millis(150), Arc::default()); + let first = tokio::spawn({ + let service = service.clone(); + async move { service.refresh_forced(only_antigravity()).await } + }); + tokio::time::sleep(Duration::from_millis(20)).await; + let waiter = tokio::time::timeout( + Duration::from_millis(30), + service.refresh_forced(only_antigravity()), + ) + .await; + assert!(waiter.is_err(), "the waiter gave up"); + let first = first.await.expect("first caller"); + assert_eq!(antigravity_of(&first).status, ProviderUsageStatus::Ok); + let read = service + .read_selected(Some(&[ProviderUsageProvider::Antigravity])) + .await; + assert_eq!(antigravity_of(&read).status, ProviderUsageStatus::Ok); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn an_attempt_every_caller_abandoned_is_committed_once_and_starts_the_cooldown() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::from_millis(60), Arc::default()); + let abandoned = tokio::time::timeout( + Duration::from_millis(10), + service.refresh_forced(only_antigravity()), + ) + .await; + assert!(abandoned.is_err()); + tokio::time::sleep(Duration::from_millis(200)).await; + let read = service + .read_selected(Some(&[ProviderUsageProvider::Antigravity])) + .await; + assert_eq!(antigravity_of(&read).status, ProviderUsageStatus::Ok); + let cooled = service.refresh(only_antigravity()).await; + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "the finished run cools down" + ); + assert_eq!(antigravity_of(&cooled).status, ProviderUsageStatus::Ok); + } + + #[tokio::test] + async fn a_result_that_ran_nothing_starts_no_cooldown() { + for message in [ + antigravity::MESSAGE_DISABLED, + antigravity::MESSAGE_NOT_STARTED, + antigravity::MESSAGE_VERSION, + ] { + let calls = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![scripted_antigravity( + calls.clone(), + Duration::ZERO, + Arc::new(move |call| { + Ok(if call == 0 { + unavailable_snapshot( + ProviderUsageProvider::Antigravity, + OffsetDateTime::now_utc(), + message, + ) + } else { + ok_antigravity() + }) + }), + )], + Arc::new(OffsetDateTime::now_utc), + ); + let first = service.refresh(only_antigravity()).await; + assert_eq!(antigravity_of(&first).error.as_deref(), Some(message)); + // The user fixed the cause; the next automatic refresh runs at once. + let second = service.refresh(only_antigravity()).await; + assert_eq!(calls.load(Ordering::SeqCst), 2, "{message}"); + assert_eq!(antigravity_of(&second).status, ProviderUsageStatus::Ok); + } + } + + #[tokio::test] + async fn a_panicking_attempt_releases_its_waiters_and_the_next_one_runs() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![scripted_antigravity( + calls.clone(), + Duration::ZERO, + Arc::new(|call| { + assert!(call != 0, "the first attempt fails hard"); + Ok(ok_antigravity()) + }), + )], + Arc::new(OffsetDateTime::now_utc), + ); + let first = tokio::time::timeout( + Duration::from_secs(5), + service.refresh_forced(only_antigravity()), + ) + .await + .expect("a panic does not leave the caller waiting"); + assert_eq!(antigravity_of(&first).status, ProviderUsageStatus::Error); + let second = service.refresh_forced(only_antigravity()).await; + assert_eq!(antigravity_of(&second).status, ProviderUsageStatus::Ok); + assert!(!service.read().await.is_fetching); + } + + #[tokio::test] + async fn expired_antigravity_data_live_or_retained_on_an_error_shows_no_windows() { + let fetched_at = OffsetDateTime::UNIX_EPOCH + time::Duration::days(20_000); + let clock = Arc::new(StdMutex::new(fetched_at)); + let calls = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![scripted_antigravity( + calls.clone(), + Duration::ZERO, + Arc::new(move |call| { + if call == 0 { + Ok(ProviderUsageSnapshot { + updated_at: fetched_at, + ..ok_antigravity() + }) + } else { + Err(ProviderUsageFetchError::new(antigravity::MESSAGE_TRANSIENT)) + } + }), + )], + Arc::new({ + let clock = clock.clone(); + move || *clock.lock().unwrap() + }), + ); + let named = [ProviderUsageProvider::Antigravity]; + service.refresh_forced(only_antigravity()).await; + *clock.lock().unwrap() = fetched_at + time::Duration::minutes(31); + for (label, result) in [ + ("live", service.read_selected(Some(&named)).await), + // A failed fetch retains the old data with its old time; it is expired too. + ("retained", service.refresh_forced(only_antigravity()).await), + ("retained read", service.read_selected(Some(&named)).await), + ] { + let snapshot = antigravity_of(&result); + assert_eq!(snapshot.status, ProviderUsageStatus::Unavailable, "{label}"); + assert!(snapshot.window_groups.is_empty(), "{label}"); + assert_eq!( + snapshot.error.as_deref(), + Some("Provider usage snapshot is stale."), + "{label}" + ); + } + // Inside the limit, an error keeps the last data. + *clock.lock().unwrap() = fetched_at + time::Duration::minutes(5); + let retained = service.read_selected(Some(&named)).await; + assert_eq!(antigravity_of(&retained).status, ProviderUsageStatus::Error); + assert_eq!(antigravity_of(&retained).window_groups.len(), 1); + } + + #[tokio::test] + async fn the_codex_reset_result_never_carries_cached_antigravity() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = service_with(&calls, Duration::ZERO, Arc::default()) + .with_codex_rate_limit_reset_consumer(|_| async { + Ok(CodexRateLimitResetOutcome::Reset) + }); + service.refresh_forced(only_antigravity()).await; + let reset = service + .consume_codex_rate_limit_reset("request-1") + .await + .expect("reset"); + assert_eq!( + names(&reset.usage), + [ProviderUsageProvider::Claude, ProviderUsageProvider::Codex] + ); + } + + /// An Antigravity fetcher whose first call waits for `gate` (not watching cancellation, like + /// a stuck settings read) before it would run the CLI; later calls run at once. + fn gated_antigravity( + gate: Arc, + runs: Arc, + ) -> ProviderUsageFetcher { + let calls = Arc::new(AtomicUsize::new(0)); + ProviderUsageFetcher { + provider: ProviderUsageProvider::Antigravity, + fetch: Arc::new(move || { + let (gate, runs, call) = ( + gate.clone(), + runs.clone(), + calls.fetch_add(1, Ordering::SeqCst), + ); + Box::pin(async move { + if call == 0 { + gate.notified().await; + } + runs.fetch_add(1, Ordering::SeqCst); + note_usage_spawned(); + Ok(ok_antigravity()) + }) + }), + } + } + + #[tokio::test(start_paused = true)] + async fn an_attempt_stuck_before_its_spawn_is_stopped_at_the_deadline_and_runs_never() { + let gate = Arc::new(tokio::sync::Notify::new()); + let runs = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![gated_antigravity(gate.clone(), runs.clone())], + Arc::new(OffsetDateTime::now_utc), + ); + let stuck = service.refresh_forced(only_antigravity()).await; + assert_eq!(antigravity_of(&stuck).status, ProviderUsageStatus::Error); + let next = service.refresh_forced(only_antigravity()).await; + assert_eq!(antigravity_of(&next).status, ProviderUsageStatus::Ok); + gate.notify_waiters(); + tokio::time::sleep(Duration::from_secs(60)).await; + assert_eq!( + runs.load(Ordering::SeqCst), + 1, + "the stuck attempt was stopped, not detached" + ); + assert!(!service.read().await.is_fetching); + } + + #[tokio::test(start_paused = true)] + async fn a_refresh_paused_before_its_spawn_never_spawns_after_shutdown() { + let gate = Arc::new(tokio::sync::Notify::new()); + let runs = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![gated_antigravity(gate.clone(), runs.clone())], + Arc::new(OffsetDateTime::now_utc), + ); + let abandoned = tokio::time::timeout( + Duration::from_millis(10), + service.refresh_forced(only_antigravity()), + ) + .await; + assert!(abandoned.is_err(), "the caller went away"); + service.shutdown().await; + gate.notify_waiters(); + tokio::time::sleep(Duration::from_secs(60)).await; + // After shutdown, no new attempt is admitted either. + service.refresh_forced(only_antigravity()).await; + tokio::time::sleep(Duration::from_secs(60)).await; + assert_eq!(runs.load(Ordering::SeqCst), 0); + } + + /// A shutdown cancelled while it waits does not let a retried one return early: every + /// shutdown waits until the running attempt has stopped. + #[tokio::test(start_paused = true)] + async fn a_retried_shutdown_still_waits_for_the_running_attempt() { + let gate = Arc::new(tokio::sync::Notify::new()); + let runs = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![gated_antigravity(gate.clone(), runs.clone())], + Arc::new(OffsetDateTime::now_utc), + ); + let refresh = tokio::spawn({ + let service = service.clone(); + async move { service.refresh_forced(only_antigravity()).await } + }); + tokio::time::sleep(Duration::from_millis(1)).await; + assert!(service.read().await.is_fetching); + let cut = tokio::time::timeout(Duration::from_millis(10), service.shutdown()).await; + assert!( + cut.is_err(), + "the first shutdown was cancelled while it waited" + ); + assert!(service.read().await.is_fetching); + service.shutdown().await; + assert!( + !service.read().await.is_fetching, + "the retried shutdown returned before the attempt stopped" + ); + let _ = refresh.await; + } + + #[tokio::test] + async fn a_failure_before_the_spawn_starts_no_cooldown() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![scripted_antigravity( + calls.clone(), + Duration::ZERO, + Arc::new(|call| { + if call == 0 { + Err(ProviderUsageFetchError::new( + "Antigravity settings could not be read.", + )) + } else { + Ok(ok_antigravity()) + } + }), + )], + Arc::new(OffsetDateTime::now_utc), + ); + service.refresh(only_antigravity()).await; + let second = service.refresh(only_antigravity()).await; + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_eq!(antigravity_of(&second).status, ProviderUsageStatus::Ok); + } + + #[tokio::test] + async fn an_empty_provider_list_reserves_no_refresh_slot() { + let codex = Arc::new(AtomicUsize::new(0)); + let service = service_with(&Arc::default(), Duration::ZERO, codex.clone()); + service.refresh(Some(Vec::new())).await; + service + .refresh(Some(vec![ + ProviderUsageProvider::Claude, + ProviderUsageProvider::Codex, + ])) + .await; + assert_eq!(codex.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn a_fetcher_that_panics_before_its_future_leaves_no_fetch_running() { + let calls = Arc::new(AtomicUsize::new(0)); + let service = ProviderUsageService::new( + vec![ProviderUsageFetcher { + provider: ProviderUsageProvider::Antigravity, + fetch: Arc::new({ + let calls = calls.clone(); + move || { + assert!( + calls.fetch_add(1, Ordering::SeqCst) != 0, + "the factory fails" + ); + Box::pin(async { + note_usage_spawned(); + Ok(ok_antigravity()) + }) + } + }), + }], + Arc::new(OffsetDateTime::now_utc), + ); + let first = service.refresh_forced(only_antigravity()).await; + assert_eq!(antigravity_of(&first).status, ProviderUsageStatus::Error); + let second = service.refresh_forced(only_antigravity()).await; + assert_eq!(antigravity_of(&second).status, ProviderUsageStatus::Ok); + assert!(!service.read().await.is_fetching); + } } diff --git a/apps/server/src/send_requests/terminal/tests.rs b/apps/server/src/send_requests/terminal/tests.rs index 2666a7a720..2c434f69ee 100644 --- a/apps/server/src/send_requests/terminal/tests.rs +++ b/apps/server/src/send_requests/terminal/tests.rs @@ -169,6 +169,21 @@ impl Fixture { self.request(request_id).await.state } + /// A stream on thread `api` that has sent its snapshot. It subscribes to changes + /// before the snapshot, so every change after this returns reaches it as an upsert. + async fn subscribed(&self) -> tokio::sync::mpsc::Receiver { + let mut stream = + self.service + .subscribe(&person(), Some("api".to_owned()), CancellationToken::new()); + let snapshot = tokio::time::timeout(Duration::from_secs(5), stream.recv()) + .await + .expect("the snapshot") + .expect("the stream stays open") + .expect("not an error"); + assert_eq!(snapshot[0]["type"], "snapshot"); + stream + } + async fn until_state(&self, request_id: &str, state: SendState) { tokio::time::timeout(Duration::from_secs(5), async { while self.state(request_id).await != state { @@ -858,10 +873,7 @@ async fn cancel_racing_a_pointer_paste_has_exactly_one_winner() { async fn a_subscribed_stream_sees_every_terminal_transition_without_a_reload() { let fixture = fixture(true).await; fixture.start(); - let mut stream = - fixture - .service - .subscribe(&person(), Some("api".to_owned()), CancellationToken::new()); + let mut stream = fixture.subscribed().await; let mut states = Vec::new(); let mut next_state = async || loop { let chunk = tokio::time::timeout(Duration::from_secs(5), stream.recv()) @@ -995,10 +1007,7 @@ async fn a_server_restart_fails_open_terminal_requests() { async fn generation_end_is_published_to_a_subscribed_stream() { let fixture = fixture(true).await; fixture.start(); - let mut stream = - fixture - .service - .subscribe(&person(), Some("api".to_owned()), CancellationToken::new()); + let mut stream = fixture.subscribed().await; fixture.send(review("r1")).await.unwrap(); fixture.end("term-1", End::Close); let state = tokio::time::timeout(Duration::from_secs(5), async { diff --git a/apps/server/src/server_settings/mod.rs b/apps/server/src/server_settings/mod.rs index edba492c5f..f0aee04602 100644 --- a/apps/server/src/server_settings/mod.rs +++ b/apps/server/src/server_settings/mod.rs @@ -18,9 +18,66 @@ pub(crate) fn built_in_provider_defaults() -> Value { "cursor": { "enabled": true, "binaryPath": "cursor-agent", "apiEndpoint": "", "customModels": [] }, "grok": { "enabled": false, "binaryPath": "grok", "customModels": [] }, "opencode": { "enabled": true, "binaryPath": "opencode", "serverUrl": "", "serverPassword": "", "customModels": [] }, + "antigravity": { "enabled": false, "binaryPath": "agy", "customModels": [] }, }) } +/// Whether provider instance `instance_id` is on, read from a settings document: the instance's +/// own `enabled`, else its driver's legacy `providers..enabled`. For Antigravity (off by +/// default) that falls back to its built-in default, a missing instance being off, and it is the +/// one rule for the inventory, usage, chat and terminal launches. Every other driver keeps the +/// inventory's earlier reading (on when neither says), and its typed decode is left as it was. +pub(crate) fn provider_instance_enabled(document: &Value, instance_id: &str) -> bool { + let instance = document + .get("providerInstances") + .and_then(|instances| instances.get(instance_id)); + let driver = instance + .and_then(|instance| instance.get("driver")) + .and_then(Value::as_str) + .unwrap_or(instance_id); + instance + .and_then(|instance| instance.get("enabled")) + .and_then(Value::as_bool) + .or_else(|| { + document + .get("providers") + .and_then(|providers| providers.get(driver)) + .and_then(|legacy| legacy.get("enabled")) + .and_then(Value::as_bool) + }) + .or_else(|| { + if driver == "antigravity" { + built_in_provider_defaults()[driver]["enabled"].as_bool() + } else { + Some(true) + } + }) + .unwrap_or(instance.is_some()) +} + +/// Writes the resolved `enabled` into every Antigravity instance that omits it, before the typed +/// decode; other drivers' instances decode as before. +fn resolve_instance_enabled(settings: &mut Value) { + let resolved = settings + .get("providerInstances") + .and_then(Value::as_object) + .into_iter() + .flat_map(|instances| instances.iter()) + .filter(|(_, instance)| { + instance.get("enabled").is_none() && instance["driver"] == "antigravity" + }) + .map(|(id, _)| (id.clone(), provider_instance_enabled(settings, id))) + .collect::>(); + for (id, enabled) in resolved { + if let Some(Value::Object(instance)) = settings + .get_mut("providerInstances") + .and_then(|instances| instances.get_mut(&id)) + { + instance.insert("enabled".to_owned(), Value::Bool(enabled)); + } + } +} + /// Recursively fills missing keys in `target` from `defaults` without overwriting existing values. pub(crate) fn merge_missing(target: &mut Value, defaults: &Value) { if let (Some(target), Some(defaults)) = (target.as_object_mut(), defaults.as_object()) { @@ -59,6 +116,7 @@ pub struct ProvidersState { pub cursor: ProviderBinarySettingsState, pub grok: ProviderBinarySettingsState, pub opencode: ProviderBinarySettingsState, + pub antigravity: ProviderBinarySettingsState, } impl ProvidersState { @@ -76,6 +134,7 @@ impl ProvidersState { cursor: provider("cursor"), grok: provider("grok"), opencode: provider("opencode"), + antigravity: provider("antigravity"), } } } @@ -193,6 +252,7 @@ pub struct ProvidersPatch { pub cursor: Option, pub grok: Option, pub opencode: Option, + pub antigravity: Option, } #[derive(Clone, Debug, Default)] @@ -331,6 +391,7 @@ impl ProviderSettingsStore { source, })?; normalize_agent_activity_settings(&mut settings); + resolve_instance_enabled(&mut settings); if let Some(providers) = settings.get_mut("providers") { merge_missing(providers, &built_in_provider_defaults()); } @@ -447,6 +508,15 @@ impl ProviderSettingsStore { Ok(settings) } + /// The stored value of instance `instance_id`'s sensitive variable `name`. + pub(crate) async fn stored_secret( + &self, + instance_id: &str, + name: &str, + ) -> std::io::Result { + fs::read_to_string(self.secret_path(instance_id, name)).await + } + fn secret_path(&self, instance_id: &str, name: &str) -> PathBuf { self.secrets_dir().join(format!( "provider-env-{}-{}", @@ -493,6 +563,11 @@ fn apply_patch( providers.opencode, "opencode", ); + apply_provider_patch( + &mut current.providers.antigravity, + providers.antigravity, + "agy", + ); } if let Some(instances) = patch.provider_instances { current.provider_instances = instances @@ -640,8 +715,31 @@ mod tests { ("cursor", true, "cursor-agent"), ("grok", false, "grok"), ("opencode", true, "opencode"), + ("antigravity", false, "agy"), ]; + #[tokio::test] + async fn antigravity_explicit_enable_survives_a_reload() { + let temp = tempfile::tempdir().expect("settings root"); + fs::write( + temp.path().join("settings.json"), + serde_json::to_vec(&serde_json::json!({ + "providers": { "antigravity": { "enabled": true } } + })) + .expect("enabled settings JSON"), + ) + .await + .expect("enabled settings file"); + + let settings = ProviderSettingsStore::new(temp.path()) + .get() + .await + .expect("enabled settings load"); + let providers = serde_json::to_value(settings.providers).expect("providers JSON"); + assert_eq!(providers["antigravity"]["enabled"], true); + assert_eq!(providers["antigravity"]["binaryPath"], "agy"); + } + #[tokio::test] async fn partial_builtin_provider_objects_preserve_enabled_defaults_and_custom_paths() { let temp = tempfile::tempdir().expect("settings root"); @@ -731,6 +829,38 @@ mod tests { assert_eq!(reloaded, updated); } + #[tokio::test] + async fn antigravity_enable_patch_persists_with_the_agy_binary() { + let temp = tempfile::tempdir().expect("settings root"); + let store = ProviderSettingsStore::new(temp.path()); + assert!( + !store + .get() + .await + .expect("defaults") + .providers + .antigravity + .enabled + ); + store + .update(ServerSettingsPatch { + providers: Some(ProvidersPatch { + antigravity: Some(ProviderSettingsPatch { + enabled: Some(true), + ..ProviderSettingsPatch::default() + }), + ..ProvidersPatch::default() + }), + ..ServerSettingsPatch::default() + }) + .await + .expect("enable Antigravity"); + + let reloaded = store.get().await.expect("reload Antigravity settings"); + assert!(reloaded.providers.antigravity.enabled); + assert_eq!(reloaded.providers.antigravity.binary_path, "agy"); + } + #[test] fn grok_is_disabled_by_default() { assert!(!ProviderSettingsState::default().providers.grok.enabled); diff --git a/apps/server/src/terminal/pty.rs b/apps/server/src/terminal/pty.rs index 7888dba2f7..99014b8c02 100644 --- a/apps/server/src/terminal/pty.rs +++ b/apps/server/src/terminal/pty.rs @@ -1586,7 +1586,13 @@ mod tests { let printed = format!("{command:?}"); - assert!(printed.contains("BIBCODE_AGENT_AUTH"), "{printed}"); + // Windows keys are case-insensitive, so the builder keeps and prints them lowercased. + let key = if cfg!(windows) { + "bibcode_agent_auth" + } else { + "BIBCODE_AGENT_AUTH" + }; + assert!(printed.contains(key), "{printed}"); assert!( !printed.contains("agent-token-value"), "the PTY command printed an environment value" diff --git a/apps/server/src/test_support/mod.rs b/apps/server/src/test_support/mod.rs index e9f362b71f..938f6caac1 100644 --- a/apps/server/src/test_support/mod.rs +++ b/apps/server/src/test_support/mod.rs @@ -159,6 +159,7 @@ mod tests { ("cursor", &runtime_settings.providers.cursor), ("grok", &runtime_settings.providers.grok), ("opencode", &runtime_settings.providers.opencode), + ("antigravity", &runtime_settings.providers.antigravity), ] { assert_eq!( settings.enabled, @@ -251,7 +252,7 @@ mod tests { assert_eq!(written["enableAssistantStreaming"], true); assert_eq!(written["providers"]["codex"], overlay["providers"]["codex"]); assert_eq!(written["providerInstances"], overlay["providerInstances"]); - for driver in ["claudeAgent", "cursor", "grok", "opencode"] { + for driver in ["claudeAgent", "cursor", "grok", "opencode", "antigravity"] { assert_eq!( written["providers"][driver]["binaryPath"], state_dir diff --git a/apps/server/tests/cli_smoke.rs b/apps/server/tests/cli_smoke.rs index 7361ef1185..bada72ffcd 100644 --- a/apps/server/tests/cli_smoke.rs +++ b/apps/server/tests/cli_smoke.rs @@ -49,7 +49,7 @@ fn hermetic_settings_are_seeded_in_the_selected_state_directory() { ) .expect("hermetic settings JSON"); assert_eq!(settings["enableProviderUpdateChecks"], false); - for driver in ["codex", "claudeAgent", "cursor", "grok", "opencode"] { + for driver in hermetic_providers::BUILTIN_PROVIDER_DRIVERS { let binary = settings["providers"][driver]["binaryPath"] .as_str() .expect("pinned provider binary"); diff --git a/apps/server/tests/production_provider_runtime.rs b/apps/server/tests/production_provider_runtime.rs index 28774f9268..569a710caa 100644 --- a/apps/server/tests/production_provider_runtime.rs +++ b/apps/server/tests/production_provider_runtime.rs @@ -159,7 +159,7 @@ while ($null -ne ($line = [Console]::In.ReadLine())) { switch ([string]$request.method) { "initialize" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{}}' } "authenticate" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{}}' } - "session/new" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model"}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}' } + "session/new" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model","options":[{"value":"test-model"},{"value":"gpt-5"},{"value":"gpt-5.4"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}' } "session/create" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{"sessionId":"grok-session","modes":{"currentModeId":"code","availableModes":[{"id":"code","name":"Agent"},{"id":"ask","name":"Ask"}]}}}' } "session/set_config_option" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{"configOptions":[]}}' } "session/set_mode" { $response = '{"jsonrpc":"2.0","id":' + $id + ',"result":{}}' } @@ -3945,7 +3945,7 @@ async fn durable_claude_turn_with_an_option_the_session_refuses_fails_once_inste settled.last_error ); // The undelivered turn states the refusal plainly, without the driver's internal id. - let refusal = "contextWindow is not supported by the selected model."; + let refusal = "contextWindow is not supported by the selected model. Choose another option for this model."; assert_eq!(settled.last_error.as_deref(), Some(refusal)); // A failed row is terminal: the worker claims only pending rows. Stopping the service drains // its in-flight work, so the row read afterwards is final and the check needs no timing bound. @@ -4139,9 +4139,9 @@ done #[cfg(unix)] const REFUSING_CURSOR_FIXTURE: &str = r#"#!/bin/sh if [ -n "$BIBCODE_TEST_FAST_WRONG_CATEGORY" ]; then - options='[{"id":"model","category":"model"},{"id":"fast","category":"model","type":"select","options":[{"value":"false"},{"value":"true"}]}]' + options='[{"id":"model","category":"model","options":[{"value":"test-model"},{"value":"gpt-5"}]},{"id":"fast","category":"model","type":"select","options":[{"value":"false"},{"value":"true"}]}]' else - options='[{"id":"model","category":"model"}]' + options='[{"id":"model","category":"model","options":[{"value":"test-model"},{"value":"gpt-5"}]}]' fi while IFS= read -r line; do id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') @@ -4214,7 +4214,7 @@ fn cursor_case(fixtures: &TempDir) -> OptionCase { async fn codex_option_the_model_does_not_advertise_fails_the_turn_once() { let fixtures = TempDir::new().expect("fixture directory"); assert_option_case_settles_once(OptionCase { - refusal: Some("Reasoning Extra High is not supported by the selected model."), + refusal: Some("Reasoning Extra High is not supported by the selected model. Choose another option for this model."), ..codex_case(&fixtures, None) }) .await; @@ -4260,7 +4260,9 @@ async fn codex_custom_model_with_an_effort_is_delivered() { async fn cursor_option_the_session_does_not_advertise_fails_the_turn_once() { let fixtures = TempDir::new().expect("fixture directory"); assert_option_case_settles_once(OptionCase { - refusal: Some("Fast is not supported by the selected model."), + refusal: Some( + "Fast is not supported by the selected model. Choose another option for this model.", + ), ..cursor_case(&fixtures) }) .await; @@ -4336,7 +4338,9 @@ async fn opencode_option_the_model_does_not_advertise_fails_the_turn_once() { environment: Vec::new(), model: "openai/gpt-5", option: json!({"id":"fastMode","value":true}), - refusal: Some("Fast is not supported by the selected model."), + refusal: Some( + "Fast is not supported by the selected model. Choose another option for this model.", + ), }) .await; server.abort(); @@ -19858,7 +19862,7 @@ while IFS= read -r line; do id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') case "$line" in *'"method":"initialize"'*|*'"method":"authenticate"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; - *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model"}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}\n' "$id" ;; + *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"cursor-session","configOptions":[{"id":"model","category":"model","options":[{"value":"test-model"},{"value":"gpt-5"},{"value":"gpt-5.4"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"ask","name":"Ask"},{"id":"code","name":"Agent"},{"id":"architect","name":"Plan"}]}}}\n' "$id" ;; *'"method":"session/create"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"grok-session","modes":{"currentModeId":"code","availableModes":[{"id":"code","name":"Agent"},{"id":"ask","name":"Ask"}]}}}\n' "$id" ;; *'"method":"session/set_config_option"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[]}}\n' "$id" ;; *'"method":"session/set_mode"'*|*'"method":"session/set_model"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; diff --git a/apps/server/tests/production_server_terminal_rpc.rs b/apps/server/tests/production_server_terminal_rpc.rs index 6b1fcb7bce..b2791658bc 100644 --- a/apps/server/tests/production_server_terminal_rpc.rs +++ b/apps/server/tests/production_server_terminal_rpc.rs @@ -1016,6 +1016,7 @@ async fn provider_usage_refresh_rpc_forces_a_fetch_only_when_requested() { session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at: now, @@ -1079,6 +1080,137 @@ async fn provider_usage_refresh_rpc_forces_a_fetch_only_when_requested() { } } +/// A fake `agy` (Unix shell) whose answer carries a marker in every free-text field. +#[cfg(unix)] +fn fake_antigravity_cli(directory: &std::path::Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let usage = r#"{"status":"SUCCESS","num_turns":0,"response":"PRIVATE-PLAN-MARKER","command":{"name":"usage","data":{"description":"PRIVATE-PLAN-MARKER","groups":[{"name":"PRIVATE-PLAN-MARKER","buckets":[{"id":"gemini-5h","name":"PRIVATE-PLAN-MARKER","window":"5h","remaining_fraction":0.25,"reset_time":"2026-11-22T02:28:19Z"},{"id":"gemini-weekly","window":"weekly","remaining_fraction":0.5,"reset_time":"2026-11-28T21:28:19Z"}]}]}}}"#; + let path = directory.join("agy"); + std::fs::write( + &path, + format!( + "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then printf 1.5.14; exit 0; fi\nprintf '%s' '{usage}'\necho PRIVATE-PLAN-MARKER >&2\n" + ), + ) + .expect("fake agy"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("executable"); + path +} + +/// Antigravity is answered only when a request names it, on the read and on the refresh, and +/// its wire shape carries the groups and no free text from the CLI. +#[cfg(unix)] +#[tokio::test] +async fn provider_usage_rpcs_answer_antigravity_only_when_named() { + let temp = TempDir::new().expect("temporary directory"); + let agy = fake_antigravity_cli(temp.path()); + let settings_root = temp.path().join("settings"); + std::fs::create_dir_all(&settings_root).expect("settings root"); + std::fs::write( + settings_root.join("settings.json"), + json!({ + "providerInstances": {"antigravity": { + "driver": "antigravity", + "enabled": true, + "config": {"binaryPath": agy.to_string_lossy()} + }} + }) + .to_string(), + ) + .expect("settings"); + // Only the Antigravity fetcher is real; Claude and Codex never touch the host account here. + let antigravity = provider_usage::production_fetchers( + bibcode_server::server_settings::ProviderSettingsStore::new(&settings_root), + None, + ) + .into_iter() + .filter(|fetcher| fetcher.provider == provider_usage::ProviderUsageProvider::Antigravity) + .collect::>(); + assert_eq!(antigravity.len(), 1); + let usage = provider_usage::ProviderUsageService::new( + antigravity, + Arc::new(time::OffsetDateTime::now_utc), + ); + let mut registry = RpcRegistry::empty(); + register_server_terminal_rpc(&mut registry, fixture_services_with_usage(usage)); + let handle = ServerRuntime::start_with_registry(test_config(&temp), registry) + .await + .expect("Rust server starts"); + let mut socket = Some(open_socket(handle.local_addr()).await); + + let result = AssertUnwindSafe(async { + let socket = socket.as_mut().expect("socket"); + let names = |value: &Value| -> Vec { + value["providers"] + .as_array() + .expect("providers") + .iter() + .map(|snapshot| snapshot["provider"].as_str().unwrap().to_owned()) + .collect() + }; + let legacy = ["claude", "codex"]; + let omitted = + success_value(request(socket, "1", "server.refreshProviderUsage", json!({})).await); + assert_eq!(names(&omitted), legacy); + let named = success_value( + request( + socket, + "2", + "server.refreshProviderUsage", + json!({ "providers": ["antigravity"], "force": true }), + ) + .await, + ); + assert_eq!(names(&named), ["claude", "codex", "antigravity"]); + let antigravity = &named["providers"][2]; + assert_eq!(antigravity["status"], "ok", "{antigravity}"); + assert_eq!(antigravity["windowGroups"][0]["id"], "gemini"); + assert_eq!(antigravity["windowGroups"][0]["label"], "Gemini models"); + assert_eq!(antigravity["windowGroups"][0]["session"]["usedPercent"], 75); + assert_eq!( + antigravity["windowGroups"][0]["weekly"]["windowMinutes"], + 10_080 + ); + assert!(!named.to_string().contains("PRIVATE-PLAN-MARKER")); + + // Cached now, it still stays out of an answer that does not name it. + let read_omitted = + success_value(request(socket, "3", "server.getProviderUsage", json!({})).await); + assert_eq!(names(&read_omitted), legacy); + let read_named = success_value( + request( + socket, + "4", + "server.getProviderUsage", + json!({ "providers": ["antigravity"] }), + ) + .await, + ); + assert_eq!(names(&read_named), ["claude", "codex", "antigravity"]); + assert_eq!(read_named["providers"][2]["status"], "ok"); + assert!(!read_named.to_string().contains("PRIVATE-PLAN-MARKER")); + let refresh_omitted = success_value( + request( + socket, + "5", + "server.refreshProviderUsage", + json!({ "force": true }), + ) + .await, + ); + assert_eq!(names(&refresh_omitted), legacy); + }) + .catch_unwind() + .await; + + close_socket(&mut socket).await; + handle.shutdown(); + handle.join().await.expect("server joins"); + if let Err(panic) = result { + std::panic::resume_unwind(panic); + } +} + #[tokio::test] async fn terminal_command_activity_hint_decodes_strictly_without_entering_launch_env() { let temp = TempDir::new().expect("temporary directory"); diff --git a/apps/server/tests/provider_cursor.rs b/apps/server/tests/provider_cursor.rs index a6fb7e5fb2..7629ddf9ae 100644 --- a/apps/server/tests/provider_cursor.rs +++ b/apps/server/tests/provider_cursor.rs @@ -117,7 +117,7 @@ fn cursor_config_updates_reject_stale_or_malformed_descriptors_before_rpc() { }; assert_eq!( refusal(json!([]), json!([{ "id": "fastMode", "value": true }])).as_deref(), - Some("Fast is not supported by the selected model.") + Some("Fast is not supported by the selected model. Choose another option for this model.") ); assert_eq!( refusal( @@ -125,7 +125,7 @@ fn cursor_config_updates_reject_stale_or_malformed_descriptors_before_rpc() { json!([{ "id": "contextWindow", "value": "1m" }]), ) .as_deref(), - Some("Context 1m is not supported by the selected model.") + Some("Context 1m is not supported by the selected model. Choose another option for this model.") ); assert_eq!( refusal( @@ -362,7 +362,7 @@ async fn cursor_runtime_matches_approval_and_cancel_traces() { .expect("cancel join") .expect("cancel turn"); assert_eq!(returned_cancel_turn_id, cancel_turn_id); - runtime.interrupt_turn().await.expect("interrupt"); + runtime.interrupt_turn(None).await.expect("interrupt"); let mut cancel_events = vec![cancel_started.stable_view(), request_opened.stable_view()]; cancel_events.extend(runtime.collect_events(2).await); normalize_turn_ids(&mut cancel_events, &cancel_turn_id, "turn-10"); @@ -371,7 +371,7 @@ async fn cursor_runtime_matches_approval_and_cancel_traces() { peer_task.await.expect("peer"); runtime - .interrupt_turn() + .interrupt_turn(None) .await .expect("interrupt without an active turn is a no-op"); let failed_turn = runtime @@ -416,7 +416,7 @@ async fn cursor_runtime_applies_the_selected_model_after_session_creation() { .respond(json!({ "status": "ok" })); peer.expect_request("session/new").respond(json!({ "sessionId": "cursor-model-session", - "configOptions": [{ "id": "model", "category": "model" }], + "configOptions": [{ "id": "model", "category": "model", "options": [{ "value": "gpt-5.4" }, { "value": "gpt-5.5" }] }], "modes": { "currentModeId": "ask", "availableModes": [ @@ -427,12 +427,12 @@ async fn cursor_runtime_applies_the_selected_model_after_session_creation() { } })); peer.expect_request("session/set_config_option") - .respond(json!({ "configOptions": [{ "id": "model", "category": "model" }] })); + .respond(json!({ "configOptions": [{ "id": "model", "category": "model", "options": [{ "value": "gpt-5.4" }, { "value": "gpt-5.5" }] }] })); peer.expect_request("session/set_mode") .expect_params(json!({ "sessionId": "cursor-model-session", "modeId": "code" })) .respond(json!({})); peer.expect_request("session/set_config_option") - .respond(json!({ "configOptions": [{ "id": "model", "category": "model" }] })); + .respond(json!({ "configOptions": [{ "id": "model", "category": "model", "options": [{ "value": "gpt-5.4" }, { "value": "gpt-5.5" }] }] })); peer.expect_request("session/set_mode") .expect_params(json!({ "sessionId": "cursor-model-session", "modeId": "architect" })) .respond(json!({})); @@ -688,8 +688,10 @@ async fn cursor_model_switch_uses_target_baselines_and_revalidates_active_option incoming, ); let config_options = |model: &str, fast: Option<&str>| { - let mut options = - vec![json!({ "id": "model", "category": "model", "currentValue": model })]; + let mut options = vec![json!({ + "id": "model", "category": "model", "currentValue": model, + "options": [{ "value": "old" }, { "value": "target" }, { "value": "no-fast" }] + })]; if let Some(fast) = fast { options.push(json!({ "id": "fast", "category": "model_config", "type": "select", @@ -701,7 +703,10 @@ async fn cursor_model_switch_uses_target_baselines_and_revalidates_active_option let old_baseline = config_options("old", Some("false")); let old_active = config_options("old", Some("true")); let target_advertisement = vec![ - json!({ "id": "model", "category": "model", "currentValue": "target" }), + json!({ + "id": "model", "category": "model", "currentValue": "target", + "options": [{ "value": "old" }, { "value": "target" }, { "value": "no-fast" }] + }), json!({ "id": "fast", "category": "model_config", "type": "select", "currentValue": "true", @@ -770,7 +775,7 @@ async fn cursor_model_switch_uses_target_baselines_and_revalidates_active_option // The model does not advertise the option, so a retry of the same turn cannot succeed. assert_eq!( refused.option_refusal(), - Some("Fast is not supported by the selected model."), + Some("Fast is not supported by the selected model. Choose another option for this model."), "{refused}" ); runtime @@ -785,6 +790,279 @@ async fn cursor_model_switch_uses_target_baselines_and_revalidates_active_option peer_task.await.expect("peer"); } +fn cursor_model_runtime(model: &str) -> (CursorSessionRuntime, ScriptedPeer) { + let (connection, incoming, peer) = scripted_peer(); + let runtime = CursorSessionRuntime::new( + CursorSessionOptions { + thread_id: "cursor-advertised-model-thread".to_owned(), + cwd: "/tmp/project".to_owned(), + runtime_mode: "full-access".to_owned(), + interaction_mode: "default".to_owned(), + model: model.to_owned(), + resume_session_id: None, + mcp_servers: Vec::new(), + }, + connection, + incoming, + ); + (runtime, peer) +} + +/// The model option of `cursor-agent` 2026.11: one bracketed value per model, its options folded +/// in, and no separate effort, context, fast or thinking option. +fn bracketed_model_options(current: &str) -> Value { + json!([ + { + "id": "mode", "name": "Mode", "category": "mode", "type": "select", + "currentValue": "agent", + "options": [{ "value": "agent", "name": "Agent" }, { "value": "ask", "name": "Ask" }] + }, + { + "id": "model", "name": "Model", "category": "model", "type": "select", + "currentValue": current, + "options": [ + { "value": "default[]", "name": "Auto" }, + { "value": "gpt-5.4-nano[reasoning=medium]", "name": "gpt-5.4-nano" }, + { + "value": "claude-opus-5[thinking=true,context=300k,effort=high,fast=false]", + "name": "claude-opus-5" + } + ] + } + ]) +} + +#[tokio::test] +async fn cursor_sends_only_advertised_bracketed_model_values() { + const OPUS: &str = "claude-opus-5[thinking=true,context=300k,effort=high,fast=false]"; + const NANO: &str = "gpt-5.4-nano[reasoning=medium]"; + let (runtime, mut peer) = cursor_model_runtime("gpt-5.4-nano"); + peer.expect_request("initialize").respond(json!({})); + peer.expect_request("authenticate").respond(json!({})); + peer.expect_request("session/new") + .respond(json!({ "sessionId": "s1", "configOptions": bracketed_model_options(OPUS) })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": NANO })) + .respond(json!({ "configOptions": bracketed_model_options(NANO) })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": OPUS })) + .respond(json!({ "configOptions": bracketed_model_options(OPUS) })); + peer.expect_no_request(); + let peer_task = tokio::spawn(peer.run()); + let within = Duration::from_secs(5); + let refusal = |result: Result<(), cursor::runtime::CursorRuntimeError>| { + let error = result.expect_err("refused"); + error.option_refusal().map(str::to_owned) + }; + + timeout(within, runtime.start()) + .await + .unwrap() + .expect("start"); + // The options the selected value already holds need no request. + timeout( + within, + runtime.set_options(vec![json!({ "id": "reasoning", "value": "medium" })]), + ) + .await + .unwrap() + .expect("the advertised reasoning"); + assert_eq!( + refusal( + timeout( + within, + runtime.set_options(vec![json!({ "id": "reasoning", "value": "low" })]) + ) + .await + .unwrap() + ) + .as_deref(), + Some( + "Reasoning low is not supported by the selected model. Choose another option for this model." + ) + ); + timeout(within, runtime.set_model("claude-opus-5")) + .await + .unwrap() + .expect("switch by base"); + timeout( + within, + runtime.set_options(vec![ + json!({ "id": "thinking", "value": true }), + json!({ "id": "contextWindow", "value": "300k" }), + json!({ "id": "reasoning", "value": "high" }), + json!({ "id": "fastMode", "value": false }), + ]), + ) + .await + .unwrap() + .expect("the folded-in options"); + assert_eq!( + refusal( + timeout( + within, + runtime.set_options(vec![json!({ "id": "fastMode", "value": true })]) + ) + .await + .unwrap() + ) + .as_deref(), + Some("Fast is not supported by the selected model. Choose another option for this model.") + ); + assert_eq!( + refusal( + timeout( + within, + runtime.set_options(vec![json!({ "id": "contextWindow", "value": "1m" })]) + ) + .await + .unwrap() + ) + .as_deref(), + Some( + "Context 1m is not supported by the selected model. Choose another option for this model." + ) + ); + assert_eq!( + refusal(timeout(within, runtime.set_model("gpt-9")).await.unwrap()).as_deref(), + Some("gpt-9 is not available in Cursor.") + ); + peer_task.await.expect("peer"); +} + +#[tokio::test] +async fn cursor_sends_only_advertised_plain_model_values() { + let plain = |current: &str| { + json!([{ + "id": "model", "category": "model", "type": "select", "currentValue": current, + "options": [{ "value": "gpt-5.4" }, { "value": "gpt-5.5" }] + }]) + }; + let (runtime, mut peer) = cursor_model_runtime("gpt-5.5"); + peer.expect_request("initialize").respond(json!({})); + peer.expect_request("authenticate").respond(json!({})); + peer.expect_request("session/new") + .respond(json!({ "sessionId": "s1", "configOptions": plain("gpt-5.4") })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": "gpt-5.5" })) + .respond(json!({ "configOptions": plain("gpt-5.5") })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": "gpt-5.4" })) + .respond(json!({ "configOptions": plain("gpt-5.4") })); + peer.expect_no_request(); + let peer_task = tokio::spawn(peer.run()); + let within = Duration::from_secs(5); + + timeout(within, runtime.start()) + .await + .unwrap() + .expect("start"); + timeout(within, runtime.set_model("gpt-5.4")) + .await + .unwrap() + .expect("switch"); + let refused = timeout(within, runtime.set_model("gpt-9")) + .await + .unwrap() + .expect_err("the session does not advertise the model"); + assert_eq!( + refused.option_refusal(), + Some("gpt-9 is not available in Cursor."), + "{refused}" + ); + peer_task.await.expect("peer"); +} + +/// Auto is the advertised `default[]` value, never the model the CLI remembers as current. +#[tokio::test] +async fn cursor_auto_selects_the_advertised_default_value() { + for auto in ["default", ""] { + auto_selects_the_advertised_default_value(auto).await; + } +} + +async fn auto_selects_the_advertised_default_value(auto: &str) { + const NANO: &str = "gpt-5.4-nano[reasoning=medium]"; + let (runtime, mut peer) = cursor_model_runtime(auto); + peer.expect_request("initialize").respond(json!({})); + peer.expect_request("authenticate").respond(json!({})); + peer.expect_request("session/new") + .respond(json!({ "sessionId": "s1", "configOptions": bracketed_model_options(NANO) })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": "default[]" })) + .respond(json!({ "configOptions": bracketed_model_options("default[]") })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": NANO })) + .respond(json!({ "configOptions": bracketed_model_options(NANO) })); + peer.expect_request("session/set_config_option") + .expect_params(json!({ "sessionId": "s1", "configId": "model", "value": "default[]" })) + .respond(json!({ "configOptions": bracketed_model_options("default[]") })); + peer.expect_no_request(); + let peer_task = tokio::spawn(peer.run()); + let within = Duration::from_secs(5); + + timeout(within, runtime.start()) + .await + .unwrap() + .expect("start"); + timeout(within, runtime.set_model("gpt-5.4-nano")) + .await + .unwrap() + .expect("switch away"); + timeout(within, runtime.set_model("default")) + .await + .unwrap() + .expect("back to Auto"); + peer_task.await.expect("peer"); +} + +/// A session that advertises no default value leaves Auto to Cursor, as before. +#[tokio::test] +async fn cursor_auto_without_an_advertised_default_is_left_to_cursor() { + let (runtime, mut peer) = cursor_model_runtime("default"); + peer.expect_request("initialize").respond(json!({})); + peer.expect_request("authenticate").respond(json!({})); + peer.expect_request("session/new").respond(json!({ + "sessionId": "s1", + "configOptions": [{ + "id": "model", "category": "model", "type": "select", "currentValue": "gpt-5.4", + "options": [{ "value": "gpt-5.4" }, { "value": "gpt-5.5" }] + }] + })); + peer.expect_no_request(); + let peer_task = tokio::spawn(peer.run()); + + timeout(Duration::from_secs(5), runtime.start()) + .await + .unwrap() + .expect("start"); + peer_task.await.expect("peer"); +} + +#[tokio::test] +async fn cursor_refuses_an_unadvertised_launch_model_before_any_prompt() { + let (runtime, mut peer) = cursor_model_runtime("gpt-5.4"); + peer.expect_request("initialize").respond(json!({})); + peer.expect_request("authenticate").respond(json!({})); + peer.expect_request("session/new").respond(json!({ + "sessionId": "s1", + "configOptions": bracketed_model_options("gpt-5.4-nano[reasoning=medium]") + })); + peer.expect_no_request(); + let peer_task = tokio::spawn(peer.run()); + + let refused = timeout(Duration::from_secs(5), runtime.start()) + .await + .unwrap() + .expect_err("gpt-5.4 is not advertised"); + assert_eq!( + refused.option_refusal(), + Some("gpt-5.4 is not available in Cursor."), + "{refused}" + ); + peer_task.await.expect("peer"); +} + #[tokio::test] async fn cursor_default_model_restoration_uses_the_advertised_provider_value() { let (connection, incoming, mut peer) = scripted_peer(); @@ -1370,7 +1648,7 @@ async fn cursor_runtime_covers_resume_permission_and_notification_edges() { peer.expect_request("session/load") .expect_params(json!({ "sessionId": "cursor-resumed" })) .respond(json!({ - "configOptions": [{ "id": "model", "category": "model" }], + "configOptions": [{ "id": "model", "category": "model", "options": [{ "value": "gpt-edge" }] }], "modes": { "currentModeId": "code", "availableModes": [ diff --git a/apps/server/tests/provider_opencode.rs b/apps/server/tests/provider_opencode.rs index 210203c1cb..c0e17769dd 100644 --- a/apps/server/tests/provider_opencode.rs +++ b/apps/server/tests/provider_opencode.rs @@ -2525,7 +2525,9 @@ async fn opencode_options_use_exact_model_variants_and_reject_conflicts_before_p .expect_err("an unknown option is refused"); assert_eq!( unknown.option_refusal(), - Some("madeUp is not supported by the selected model.") + Some( + "madeUp is not supported by the selected model. Choose another option for this model." + ) ); // The shape checks name each option by the label its descriptor shows. for (options, refusal) in [ @@ -2555,7 +2557,9 @@ async fn opencode_options_use_exact_model_variants_and_reject_conflicts_before_p .expect_err("a variant the model does not advertise is refused"); assert_eq!( unadvertised.option_refusal(), - Some("Variant medium is not supported by the selected model.") + Some( + "Variant medium is not supported by the selected model. Choose another option for this model." + ) ); assert!(state.prompt_body.lock().await.is_none()); diff --git a/apps/server/tests/provider_usage_domain.rs b/apps/server/tests/provider_usage_domain.rs index 8f5b19745b..40c6198d57 100644 --- a/apps/server/tests/provider_usage_domain.rs +++ b/apps/server/tests/provider_usage_domain.rs @@ -159,6 +159,7 @@ fn snapshot(provider: ProviderUsageProvider, updated_at: OffsetDateTime) -> Prov session: None, weekly: None, fable_weekly: None, + window_groups: Vec::new(), plan_type: None, rate_limit_reset_credits: None, updated_at, @@ -776,8 +777,12 @@ async fn production_fetchers_handle_local_credentials_and_codex_rpc_responses() set_provider_usage_environment("BIBCODE_CLAUDE_KEYCHAIN_ACCESS", "disabled"); set_provider_usage_environment("CODEX_HOME", &codex_home); - let fetchers = production_fetchers(); - assert_eq!(fetchers.len(), 2); + let fetchers = production_fetchers( + bibcode_server::server_settings::ProviderSettingsStore::new(temporary.path().join("state")), + None, + ); + assert_eq!(fetchers.len(), 3); + assert_eq!(fetchers[2].provider, ProviderUsageProvider::Antigravity); assert_eq!(fetchers[0].provider, ProviderUsageProvider::Claude); assert_eq!(fetchers[1].provider, ProviderUsageProvider::Codex); let claude_fetch = &fetchers[0].fetch; diff --git a/apps/server/tests/support/hermetic_providers.rs b/apps/server/tests/support/hermetic_providers.rs index a2ff403035..f24d9c1550 100644 --- a/apps/server/tests/support/hermetic_providers.rs +++ b/apps/server/tests/support/hermetic_providers.rs @@ -1,8 +1,8 @@ //! Test-only settings that keep provider probing, provider update checks, and //! hosting-CLI discovery confined to fixtures. //! -//! No test may resolve `claude`, `codex`, `opencode`, `cursor-agent`, or -//! `grok` from the host's real `PATH`, and no test may reach the network for +//! No test may resolve `claude`, `codex`, `opencode`, `cursor-agent`, `grok`, +//! or `agy` from the host's real `PATH`, and no test may reach the network for //! a version/update check. See `docs/testing/README.md`. //! //! Integration binaries include this file with @@ -25,8 +25,14 @@ use serde_json::{Map, Value, json}; /// Keep this list checked against the server's settings and inventory by /// `test_support::tests::hermetic_helper_pins_every_provider_driver_the_server_defines_as_built_in`, /// which fails if a driver is added or removed without updating this list. -pub(crate) const BUILTIN_PROVIDER_DRIVERS: &[&str] = - &["codex", "claudeAgent", "cursor", "grok", "opencode"]; +pub(crate) const BUILTIN_PROVIDER_DRIVERS: &[&str] = &[ + "codex", + "claudeAgent", + "cursor", + "grok", + "opencode", + "antigravity", +]; /// An absolute, absent path in a test-owned sandbox. Executable resolution /// must not fall back to PATH when this path is missing. @@ -50,7 +56,7 @@ pub(crate) fn missing_hosting_executable_dir(sandbox: &Path) -> PathBuf { } /// Settings that explicitly preserve the built-in enabled defaults (Codex, -/// Claude, Cursor, and OpenCode enabled; Grok disabled) in both settings readers, +/// Claude, Cursor, and OpenCode enabled; Grok and Antigravity disabled) in both settings readers, /// while pinning each legacy `binaryPath` to [`missing_provider_executable`] and /// disabling the update check that would otherwise call registry.npmjs.org / /// downloads.claude.ai. @@ -70,6 +76,7 @@ pub(crate) fn hermetic_provider_settings(sandbox: &Path) -> Value { ("cursor", true), ("grok", false), ("opencode", true), + ("antigravity", false), ] { providers.insert( driver.to_owned(), diff --git a/apps/server/tests/turn_delivery_recovery.rs b/apps/server/tests/turn_delivery_recovery.rs index 796b773cab..9c4d59a89c 100644 --- a/apps/server/tests/turn_delivery_recovery.rs +++ b/apps/server/tests/turn_delivery_recovery.rs @@ -685,13 +685,14 @@ fn crash_model(provider: &str) -> &'static str { "claudeAgent" => "claude-sonnet-4-5", "opencode" => "openai/gpt-5", "cursor" => "cursor-default", + "antigravity" => "test-model-a", _ => "gpt-5", } } fn crash_binary_path(provider: &str, state: &Path) -> String { match provider { - "cursor" => hermetic_providers::missing_provider_executable(state) + "cursor" | "antigravity" => hermetic_providers::missing_provider_executable(state) .to_str() .expect("crash fixture path is UTF-8") .to_owned(), @@ -739,15 +740,15 @@ fn crash_launch(provider: &str, state: &Path) -> ProviderLaunchRequest { } fn configure_crash_provider(state: &Path, provider: &str) { - if provider != "cursor" { + if !matches!(provider, "cursor" | "antigravity") { return; } hermetic_providers::write_hermetic_settings( state, serde_json::json!({ "providerInstances": { - "cursor": { - "driver": "cursor", + (provider): { + "driver": provider, "enabled": true, "config": {"binaryPath": crash_binary_path(provider, state)} } @@ -1135,6 +1136,18 @@ async fn subprocess_crash_truth_table_preserves_exact_delivery_state_and_send_co }, false, ), + // An Antigravity prompt already written stays at one send after a restart and becomes + // uncertain: ACP has no delivery lookup, so it is never replayed. + ( + "antigravity", + "after-provider-write", + TurnDeliveryState::Sending, + TurnDeliveryState::Uncertain, + ProviderReconciliationOutcome::Unavailable { + detail: "Antigravity cannot reconcile exact delivery".to_owned(), + }, + false, + ), ] { let state = TempDir::new().expect("crash state"); let sends = state.path().join("provider-sends"); diff --git a/apps/web/src/codeReview.test.ts b/apps/web/src/codeReview.test.ts index 81119e6e88..51fae9ad42 100644 --- a/apps/web/src/codeReview.test.ts +++ b/apps/web/src/codeReview.test.ts @@ -8,6 +8,7 @@ import { import { describe, expect, it } from "vite-plus/test"; import { + buildCodeReviewMenuReviewers, CODE_REVIEW_INSTRUCTIONS_MAX_LENGTH, codeReviewGuardLine, codeReviewScopeText, @@ -154,6 +155,37 @@ describe("codeReviewGuardLine", () => { expect(line("terminal", "codex")).toBe("Runs in Codex's read-only sandbox."); }); + it("offers the Antigravity chat as a reviewer with the instructed guard, and no terminal review", () => { + const antigravity = { + instanceId: ProviderInstanceId.make("antigravity"), + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + enabled: true, + installed: true, + status: "ready", + availability: "available", + models: [], + } as unknown as ServerProvider; + const actions = buildProviderAgentActions([antigravity], { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [antigravity.instanceId]: { driver: antigravity.driver, enabled: true }, + }, + }); + + expect( + buildCodeReviewMenuReviewers(actions, () => null).map(({ value, guardLine }) => ({ + value, + guardLine, + })), + ).toEqual([ + { + value: "chat:antigravity", + guardLine: "Told not to edit. BiBCode cannot block edits for this agent.", + }, + ]); + }); + it("says a Codex chat review runs on its own only on a server with read-only Codex reviews", () => { const codex = ProviderDriverKind.make("codex"); expect(codeReviewGuardLine({ kind: "chat", driver: codex, readOnlyCodexReviews: true })).toBe( diff --git a/apps/web/src/components/ChatView.test.tsx b/apps/web/src/components/ChatView.test.tsx index 67f7b3ac73..fd648eef8e 100644 --- a/apps/web/src/components/ChatView.test.tsx +++ b/apps/web/src/components/ChatView.test.tsx @@ -204,6 +204,16 @@ vi.mock("../state/threads", () => ({ }, })); +// Only the real ChatHeaderPanelMenu reads closed chats; the menu test needs none. +vi.mock("../lib/archivedThreadsState", () => ({ + useArchivedThreadSnapshots: () => ({ + snapshots: [], + isLoading: false, + error: null, + refresh: () => undefined, + }), +})); + vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: { key: "terminal.open" }, @@ -886,6 +896,7 @@ import { newDraftId } from "../lib/utils"; import type { ProviderInstanceEntry } from "../providerInstances"; import type { ChatComposerHandle } from "./chat/ChatComposer"; import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack"; +import { ChatHeaderPanelMenu } from "./chat/ChatHeaderPanelMenu"; import { FileEditingSessionRegistry } from "./files/fileEditingSessionRegistry"; import { toastManager } from "./ui/toast"; import type { @@ -6061,6 +6072,120 @@ describe("ChatView handlers (captured from mocked children)", () => { }); }); + describe("Antigravity from the AI Terminal menu (R12, R13)", () => { + const antigravityInstanceId = ProviderInstanceId.make("antigravity_work"); + const antigravityProvider: ServerProvider = { + ...codexProvider, + instanceId: antigravityInstanceId, + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + models: [{ slug: "model-alpha", name: "Model Alpha", isCustom: false, capabilities: null }], + }; + + it("opens the selected instance's Antigravity Terminal in the thread checkout", async () => { + seedEnvironment( + makeEnvironmentPresentation({ + serverConfig: { providers: [codexProvider, antigravityProvider] }, + } as never), + ); + seedProject(makeProject()); + seedServerThread( + makeThread({ branch: "feature", worktreePath: "X:/demo-worktrees/feature" }), + ); + seedGitStatus(true); + h.settings = { + ...h.settings, + providerInstances: { + [antigravityInstanceId]: { + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + enabled: true, + config: { binaryPath: "custom-agy" }, + }, + }, + }; + vi.unstubAllGlobals(); + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + const menuContainer = document.createElement("div"); + document.body.append(menuContainer); + const menuRoot = createRoot(menuContainer); + try { + await act(async () => { + root.render( + , + ); + await Promise.resolve(); + }); + // ChatHeaderActions is mocked here, so the real menu renders from the props ChatView gave it. + const header = + capturedProps< + Pick< + ComponentProps, + | "providerStatuses" + | "settings" + | "canCreatePanel" + | "onCreateChatPanel" + | "onCreateSideChat" + | "sideChatUnavailableReason" + | "onReopenChatPanel" + | "onOpenTerminalPanel" + | "onOpenProviderTerminalPanel" + > + >("chatHeaderActions"); + await act(async () => + menuRoot.render( + undefined} + />, + ), + ); + const trigger = menuContainer.querySelector( + 'button[aria-label="New panel"]', + )!; + await act(async () => { + trigger.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true })); + trigger.click(); + }); + const items = await vi.waitFor(() => { + const found = Array.from(document.querySelectorAll("[role='menuitem']")); + expect(found.map((item) => item.textContent)).toEqual( + expect.arrayContaining(["Antigravity", "Antigravity Terminal"]), + ); + return found; + }); + await act(async () => + items.find((item) => item.textContent === "Antigravity Terminal")!.click(), + ); + await vi.waitFor(() => expect(commandCallsFor("terminal.open")).toHaveLength(1)); + const opened = commandCallsFor("terminal.open")[0]!.input as { + input: { cwd: string; command: unknown }; + }; + expect(opened.input.cwd).toBe("X:/demo-worktrees/feature"); + expect(opened.input.command).toEqual({ + executable: "custom-agy", + args: ["--dangerously-skip-permissions"], + label: "Antigravity Terminal", + activity: { + driverKind: ProviderDriverKind.make("antigravity"), + providerInstanceId: antigravityInstanceId, + }, + }); + expect(JSON.stringify(opened)).not.toMatch(/observer/i); + } finally { + await act(async () => menuRoot.unmount()); + await act(async () => root.unmount()); + container.remove(); + menuContainer.remove(); + } + }); + }); + describe("Review changes from Source Control (R90, R95, R97, R98)", () => { type ReviewProp = { readonly unavailableReason: string | null; diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 4959e97ad3..9a1caeb522 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -4,6 +4,8 @@ import { assert, describe, it } from "vite-plus/test"; import { buildGitActionProgressStages, buildMenuItems, + canShowPullRequestInPanel, + isPullRequestInOtherRepository, requiresDefaultBranchConfirmation, resolveAutoFeatureBranchName, resolveDefaultBranchActionDialogCopy, @@ -75,7 +77,58 @@ describe("when: ref is clean and has an open PR", () => { assert.deepInclude(quick, { kind: "open_pr", label: "View PR", disabled: false }); }); - it("buildMenuItems offers opening the PR in the thread's panel only when asked", () => { + it("resolveQuickAction opens the PR in the panel when the panel can show it", () => { + const pr = { + number: 10, + title: "Open PR", + url: "https://example.com/pr/10", + baseRef: "main", + headRef: "feature/test", + state: "open", + } as const; + assert.deepInclude(resolveQuickAction(status({ pr }), false, false, true, true), { + kind: "open_pr_panel", + label: "View PR", + disabled: false, + }); + assert.deepInclude(resolveQuickAction(status({ pr }), false, false, true, false), { + kind: "open_pr", + label: "View PR", + }); + const gitlab = status({ + pr, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + }); + assert.deepInclude(resolveQuickAction(gitlab, false, false, true, true), { + kind: "open_pr_panel", + label: "View MR", + }); + }); + + it("resolveQuickAction opens the PR in the panel when there is no upstream", () => { + const pr = { + number: 10, + title: "Open PR", + url: "https://example.com/pr/10", + baseRef: "main", + headRef: "feature/test", + state: "open", + } as const; + for (const hasPrimaryRemote of [true, false]) { + assert.deepInclude( + resolveQuickAction( + status({ hasUpstream: false, aheadCount: 0, pr }), + false, + false, + hasPrimaryRemote, + true, + ), + { kind: "open_pr_panel", label: "View PR" }, + ); + } + }); + + it("buildMenuItems puts View PR in the panel and keeps a browser item only when asked", () => { const withPr = status({ pr: { number: 11, @@ -86,24 +139,38 @@ describe("when: ref is clean and has an open PR", () => { state: "open", }, }); + assert.deepEqual( + buildMenuItems(withPr, false) + .filter((item) => item.icon === "pr") + .map(({ label, kind }) => ({ label, kind })), + [{ label: "View PR", kind: "open_pr" }], + ); + assert.deepEqual( + buildMenuItems(withPr, false, true, true) + .filter((item) => item.icon === "pr") + .map(({ label, kind, disabled }) => ({ label, kind, disabled })), + [ + { label: "View PR", kind: "open_pr_panel", disabled: false }, + { label: "Open PR in browser", kind: "open_pr", disabled: false }, + ], + ); assert.notInclude( - buildMenuItems(withPr, false).map((item) => item.id), - "pr_panel", + buildMenuItems(status(), false, true, true).map((item) => item.label), + "Open PR in browser", ); - assert.deepInclude(buildMenuItems(withPr, false, true, true).at(-1), { - id: "pr_panel", - label: "Open PR in panel", - disabled: false, - icon: "pr", - kind: "open_pr_panel", + const gitlab = status({ + pr: withPr.pr, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, }); - assert.notInclude( - buildMenuItems(status(), false, true, true).map((item) => item.id), - "pr_panel", + assert.deepEqual( + buildMenuItems(gitlab, false, true, true) + .filter((item) => item.icon === "pr") + .map((item) => item.label), + ["View MR", "Open MR in browser"], ); }); - it("buildMenuItems disables opening the PR in the panel while busy", () => { + it("buildMenuItems disables both PR items while busy", () => { const withPr = status({ pr: { number: 11, @@ -114,10 +181,11 @@ describe("when: ref is clean and has an open PR", () => { state: "open", }, }); - assert.deepInclude(buildMenuItems(withPr, true, true, true).at(-1), { - id: "pr_panel", - disabled: true, - }); + const prItems = buildMenuItems(withPr, true, true, true).filter((item) => item.icon === "pr"); + assert.deepEqual( + prItems.map((item) => item.disabled), + [true, true], + ); }); it("buildMenuItems disables commit/push and enables open PR", () => { @@ -1211,3 +1279,46 @@ describe("resolveAutoFeatureBranchName", () => { assert.equal(ref, "feature/update"); }); }); + +describe("canShowPullRequestInPanel", () => { + it("needs the setting, a supported host and the server's pullRequestsReads", () => { + const base = { enabled: true, pullRequestsReads: true, providerKind: "github" } as const; + assert.isTrue(canShowPullRequestInPanel(base)); + assert.isFalse(canShowPullRequestInPanel({ ...base, enabled: false })); + assert.isFalse(canShowPullRequestInPanel({ ...base, pullRequestsReads: false })); + assert.isFalse(canShowPullRequestInPanel({ ...base, providerKind: "bitbucket" })); + assert.isFalse(canShowPullRequestInPanel({ ...base, providerKind: "azure-devops" })); + }); +}); + +describe("isPullRequestInOtherRepository", () => { + it("is true only when the pull request URL names a different repository", () => { + assert.isFalse( + isPullRequestInOtherRepository("https://github.test/team/repo/pull/9", "team/repo"), + ); + assert.isFalse( + isPullRequestInOtherRepository("https://github.test/Team/Repo/pull/9", "team/repo"), + ); + assert.isTrue( + isPullRequestInOtherRepository("https://github.test/upstream/repo/pull/9", "fork/repo"), + ); + assert.isFalse( + isPullRequestInOtherRepository( + "https://gitlab.test/group/sub/proj/-/merge_requests/4", + "group/sub/proj", + ), + ); + assert.isTrue( + isPullRequestInOtherRepository( + "https://gitlab.test/group/other/-/merge_requests/4", + "group/sub/proj", + ), + ); + }); + + it("cannot tell, and says false, for an unknown repository or an unrecognised URL", () => { + assert.isFalse(isPullRequestInOtherRepository("https://github.test/team/repo/pull/9", null)); + assert.isFalse(isPullRequestInOtherRepository("not a url", "team/repo")); + assert.isFalse(isPullRequestInOtherRepository("https://host.test/x/y", "team/repo")); + }); +}); diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index ce82f7ab93..dedc7d0045 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -2,6 +2,7 @@ import { VcsActionRemoteFailureError } from "@bibcode/client-runtime/state/vcs"; import type { GitRunStackedActionResult, GitStackedAction, + SourceControlProviderKind, VcsStatusResult, } from "@bibcode/contracts"; import { isTemporaryWorktreeBranch } from "@bibcode/shared/git"; @@ -11,13 +12,14 @@ import { getChangeRequestTerminology, type ChangeRequestTerminology, } from "../sourceControlPresentation"; +import { canOpenPullRequestInPanel } from "./pullRequests/pullRequestsAvailability"; export type GitActionIconName = "commit" | "push" | "pr"; export type GitDialogAction = "commit" | "push" | "create_pr"; export interface GitActionMenuItem { - id: "commit" | "push" | "pr" | "pr_panel"; + id: "commit" | "push" | "pr" | "pr_browser"; label: string; disabled: boolean; icon: GitActionIconName; @@ -28,7 +30,7 @@ export interface GitActionMenuItem { export interface GitQuickAction { label: string; disabled: boolean; - kind: "run_action" | "run_pull" | "open_pr" | "open_publish" | "show_hint"; + kind: "run_action" | "run_pull" | "open_pr" | "open_pr_panel" | "open_publish" | "show_hint"; action?: GitStackedAction; hint?: string; } @@ -154,7 +156,7 @@ export function buildMenuItems( label: `View ${terminology.shortLabel}`, disabled: !canOpenPr, icon: "pr", - kind: "open_pr", + kind: canOpenInPanel ? "open_pr_panel" : "open_pr", } : { id: "pr", @@ -167,11 +169,11 @@ export function buildMenuItems( ]; if (canOpenInPanel && hasOpenPr) { items.push({ - id: "pr_panel", - label: `Open ${terminology.shortLabel} in panel`, + id: "pr_browser", + label: `Open ${terminology.shortLabel} in browser`, disabled: !canOpenPr, icon: "pr", - kind: "open_pr_panel", + kind: "open_pr", }); } return items; @@ -182,6 +184,7 @@ export function resolveQuickAction( isBusy: boolean, isDefaultRef = false, hasPrimaryRemote = true, + canOpenInPanel = false, ): GitQuickAction { if (isBusy) { return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." }; @@ -204,6 +207,7 @@ export function resolveQuickAction( const isBehind = gitStatus.behindCount > 0; const isDiverged = isAhead && isBehind; const terminology = resolveChangeRequestTerminology(gitStatus); + const viewKind = canOpenInPanel ? "open_pr_panel" : "open_pr"; if (!hasBranch) { return { @@ -232,7 +236,7 @@ export function resolveQuickAction( if (!gitStatus.hasUpstream) { if (!hasPrimaryRemote) { if (hasOpenPr && !isAhead) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } return { label: "Publish repository", @@ -242,7 +246,7 @@ export function resolveQuickAction( } if (!isAhead) { if (hasOpenPr) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } return { label: "Push", @@ -302,7 +306,7 @@ export function resolveQuickAction( } if (hasOpenPr && gitStatus.hasUpstream) { - return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" }; + return { label: `View ${terminology.shortLabel}`, disabled: false, kind: viewKind }; } if (hasDefaultBranchDelta && !isDefaultRef) { @@ -322,6 +326,45 @@ export function resolveQuickAction( }; } +/** + * Whether a request can be shown in the thread's right panel: the setting is on, the host has + * request details, and the server reads pull requests. A disconnect is not lack of support. + */ +export function canShowPullRequestInPanel(input: { + readonly enabled: boolean; + readonly pullRequestsReads: boolean; + readonly providerKind: SourceControlProviderKind; +}): boolean { + return ( + input.pullRequestsReads && + canOpenPullRequestInPanel({ enabled: input.enabled, providerKind: input.providerKind }) + ); +} + +const REQUEST_PATH_MARKER = /\/(?:-\/)?(?:pull|merge_requests)\/\d+/; + +/** + * True when a request URL names a repository other than `repository` (the checkout's origin, + * as the panel addresses it). Source Control finds a branch's request through the host CLI's + * default repository, which can be the parent of a copy. An unknown repository or an + * unrecognised URL is "cannot tell", reported as false. + */ +export function isPullRequestInOtherRepository( + requestUrl: string, + repository: string | null, +): boolean { + if (repository === null) return false; + let pathname: string; + try { + pathname = new URL(requestUrl).pathname; + } catch { + return false; + } + const marker = REQUEST_PATH_MARKER.exec(pathname); + if (marker === null) return false; + return pathname.slice(1, marker.index).toLowerCase() !== repository.toLowerCase(); +} + const isRemoteFailure = Schema.is(VcsActionRemoteFailureError); /** diff --git a/apps/web/src/components/SourceControlPanel.test.tsx b/apps/web/src/components/SourceControlPanel.test.tsx index 9b203a7f54..49e07d91a1 100644 --- a/apps/web/src/components/SourceControlPanel.test.tsx +++ b/apps/web/src/components/SourceControlPanel.test.tsx @@ -135,6 +135,8 @@ const testState = vi.hoisted(() => ({ rightPanelOpen: vi.fn(), openPullRequest: vi.fn(), pullRequestsEnabled: true, + pullRequestsReads: true, + pullRequestsContext: undefined as { status: string; repository?: string } | undefined, selectGitScope: vi.fn(), toast: { add: vi.fn(), update: vi.fn(), close: vi.fn() }, groupByFolder: true, @@ -342,6 +344,7 @@ vi.mock("~/state/entities", () => ({ gitManagerStashMergeOperations: testState.mergeCapabilities, gitManagerBranchSyncOperations: testState.mergeCapabilities, codeReviews: testState.codeReviews, + pullRequestsReads: testState.pullRequestsReads, }, }, }), @@ -423,6 +426,10 @@ vi.mock("~/hooks/useSettings", () => ({ selector({ pullRequestsEnabled: testState.pullRequestsEnabled }), })); +vi.mock("./pullRequests/usePullRequestsContextQuery", () => ({ + usePullRequestsContextQuery: () => ({ query: { data: testState.pullRequestsContext } }), +})); + vi.mock("~/rightPanelStore", () => ({ useRightPanelStore: { getState: () => ({ @@ -778,6 +785,8 @@ beforeEach(() => { testState.rightPanelOpen.mockReset(); testState.openPullRequest.mockReset(); testState.pullRequestsEnabled = true; + testState.pullRequestsReads = true; + testState.pullRequestsContext = undefined; testState.selectGitScope.mockReset(); testState.toast.add.mockReset(); testState.toast.add.mockReturnValue("toast-1"); @@ -824,6 +833,14 @@ describe("SourceControlPanel", () => { expect(testState.runAction).toHaveBeenCalledTimes(1); }); + // A clean tree walks the remote ladder: the staging-area ladder, and the legacy one (files + // without an area) with its quick action. + const CLEAN_LADDERS = [ + status, + (overrides: Partial) => + legacyStatus({ hasWorkingTreeChanges: false, ...overrides }), + ]; + const OPEN_MR = { number: 89, title: "Fix it", @@ -840,7 +857,7 @@ describe("SourceControlPanel", () => { }); const props = buildProps(); render(props); - menuItemByText("Open MR in panel")?.onClick?.(); + menuItemByText("View MR")?.onClick?.(); expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { number: 89, provider: "gitlab", @@ -848,6 +865,56 @@ describe("SourceControlPanel", () => { expect(testState.openPullRequestLink).not.toHaveBeenCalled(); }); + it("opens the open merge request in the panel from the View MR button, in both ladders", () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + pr: OPEN_MR, + }); + const props = buildProps(); + render(props); + const viewMr = buttonByExactText("View MR") ?? buttonsByText("View MR")[0]; + expect(viewMr).toBeDefined(); + viewMr?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { + number: 89, + provider: "gitlab", + }); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + } + }); + + it("opens the PR URL in the browser from the Open PR in browser menu item, in both ladders", async () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ pr: OPEN_MR }); + render(buildProps()); + menuItemByText("Open PR in browser")?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledWith( + (testState.localApi as { shell: unknown }).shell, + OPEN_MR.url, + ); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }); + + it("opens View PR in the browser when the server cannot read pull requests", async () => { + testState.pullRequestsReads = false; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ pr: OPEN_MR }); + render(buildProps()); + expect(menuItemByText("Open PR in browser")).toBeUndefined(); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledTimes(1); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }); + it("opens the open merge request in the thread's panel from the legacy menu", () => { testState.statusQuery.data = legacyStatus({ sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, @@ -855,38 +922,96 @@ describe("SourceControlPanel", () => { }); const props = buildProps(); render(props); - menuItemByText("Open MR in panel")?.onClick?.(); + menuItemByText("View MR")?.onClick?.(); expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { number: 89, provider: "gitlab", }); }); + it("opens a GitHub pull request from View PR in the panel, in both ladders", () => { + for (const build of CLEAN_LADDERS) { + testState.openPullRequest.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind: "github", name: "GitHub", baseUrl: "https://github.test" }, + pr: { ...OPEN_MR, url: "https://github.test/team/repo/pull/89" }, + }); + const props = buildProps(); + render(props); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledWith(props.threadRef, { + number: 89, + provider: "github", + }); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + } + }); + it.each([ - ["Pull Requests is turned off", false, "gitlab"], - ["the host is Bitbucket", true, "bitbucket"], - ["the host is Azure DevOps", true, "azure-devops"], - ] as const)("does not offer the in-panel action when %s", (_name, enabled, kind) => { - testState.pullRequestsEnabled = enabled; - for (const data of [ - status({ - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - pr: OPEN_MR, - }), - legacyStatus({ - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - pr: OPEN_MR, - }), - ]) { - testState.statusQuery.data = data; + ["Pull Requests is turned off", false, true, "gitlab"], + ["the host is Bitbucket", true, true, "bitbucket"], + ["the host is Azure DevOps", true, true, "azure-devops"], + ["the server cannot read pull requests", true, false, "gitlab"], + ] as const)( + "opens View in the browser and offers no browser item when %s", + async (_name, enabled, reads, kind) => { + testState.pullRequestsEnabled = enabled; + testState.pullRequestsReads = reads; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ + sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, + pr: OPEN_MR, + }); + render(buildProps()); + expect(menuItemByText("in browser")).toBeUndefined(); + (buttonsByText("View ")[0] ?? menuItemByText("View "))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledWith( + (testState.localApi as { shell: unknown }).shell, + OPEN_MR.url, + ); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + } + }, + ); + + it("still opens the panel when the connection is down and the repository is unknown", () => { + testState.pullRequestsContext = undefined; + testState.statusQuery.data = status({ pr: OPEN_MR }); + render(buildProps()); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledTimes(1); + expect(testState.openPullRequestLink).not.toHaveBeenCalled(); + }); + + it("opens View PR in the browser when the pull request belongs to another repository", async () => { + // origin is a fork; the status lookup found the parent's pull request. + testState.pullRequestsContext = { status: "available", repository: "fork/repo" }; + for (const build of CLEAN_LADDERS) { + testState.openPullRequestLink.mockClear(); + testState.statusQuery.data = build({ + pr: { ...OPEN_MR, url: "https://host.test/team/repo/pull/89" }, + }); render(buildProps()); - expect(captured.menuItems.map((item) => flattenText(item.children))).not.toContainEqual( - expect.stringContaining("in panel"), - ); - expect(menuItemByText("View")).toBeDefined(); + expect(menuItemByText("Open PR in browser")).toBeUndefined(); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + await flushPromises(); + expect(testState.openPullRequestLink).toHaveBeenCalledTimes(1); + expect(testState.openPullRequest).not.toHaveBeenCalled(); } }); + it("opens View PR in the panel when the pull request belongs to the addressed repository", () => { + testState.pullRequestsContext = { status: "available", repository: "team/repo" }; + testState.statusQuery.data = status({ + pr: { ...OPEN_MR, url: "https://host.test/team/repo/pull/89" }, + }); + render(buildProps()); + (buttonsByText("View PR")[0] ?? menuItemByText("View PR"))?.onClick?.(); + expect(testState.openPullRequest).toHaveBeenCalledTimes(1); + }); + it("opens the created merge request beside the thread on Done", async () => { testState.statusQuery.data = status({ refName: "feature/test", @@ -907,26 +1032,31 @@ describe("SourceControlPanel", () => { }); it.each([ - ["Pull Requests is turned off", false, "gitlab"], - ["the host is Bitbucket", true, "bitbucket"], - ["the host is Azure DevOps", true, "azure-devops"], - ] as const)("does not open the created request on Done when %s", async (_name, enabled, kind) => { - testState.pullRequestsEnabled = enabled; - testState.statusQuery.data = status({ - refName: "feature/test", - hasUpstream: false, - aheadCount: 1, - sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, - }); - const props = buildProps(); - render(props); - buttonsByText("Push & create")[0]?.onClick?.(); - await flushPromises(); - render(props); - expect(captured.createPullRequest).toMatchObject({ open: true }); - captured.createPullRequest?.onDone?.({ number: 89, provider: kind }); - expect(testState.openPullRequest).not.toHaveBeenCalled(); - }); + ["Pull Requests is turned off", false, "gitlab", true], + ["the host is Bitbucket", true, "bitbucket", true], + ["the host is Azure DevOps", true, "azure-devops", true], + ["the server cannot read pull requests", true, "gitlab", false], + ] as const)( + "does not open the created request on Done when %s", + async (_name, enabled, kind, reads) => { + testState.pullRequestsEnabled = enabled; + testState.pullRequestsReads = reads; + testState.statusQuery.data = status({ + refName: "feature/test", + hasUpstream: false, + aheadCount: 1, + sourceControlProvider: { kind, name: "Host", baseUrl: "https://host.test" }, + }); + const props = buildProps(); + render(props); + buttonsByText("Push & create")[0]?.onClick?.(); + await flushPromises(); + render(props); + expect(captured.createPullRequest).toMatchObject({ open: true }); + captured.createPullRequest?.onDone?.({ number: 89, provider: kind }); + expect(testState.openPullRequest).not.toHaveBeenCalled(); + }, + ); it.each([ ["a tracked branch", { hasUpstream: true, aheadCount: 1 }, true], @@ -1933,7 +2063,8 @@ describe("SourceControlPanel", () => { expect(testState.runAction.mock.calls[0]?.[0]).not.toHaveProperty("commitStagedIndexAsIs"); }); - it("opens an existing PR from the legacy quick action", async () => { + it("opens an existing PR from the legacy quick action in the browser without pull request reads", async () => { + testState.pullRequestsReads = false; testState.statusQuery.data = legacyStatus({ hasWorkingTreeChanges: false, workingTree: { files: [], insertions: 0, deletions: 0 }, diff --git a/apps/web/src/components/SourceControlPanel.tsx b/apps/web/src/components/SourceControlPanel.tsx index 82e8288571..7f81f19285 100644 --- a/apps/web/src/components/SourceControlPanel.tsx +++ b/apps/web/src/components/SourceControlPanel.tsx @@ -100,6 +100,8 @@ import { DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { joinWorkspacePath } from "./files/FileTreeContextMenu.logic"; import { buildMenuItems, + canShowPullRequestInPanel, + isPullRequestInOtherRepository, type DefaultBranchConfirmableAction, requiresDefaultBranchConfirmation, resolveDefaultBranchActionDialogCopy, @@ -139,7 +141,7 @@ import { GIT_MANAGER_STASH_MERGE_DISABLED_REASON } from "./gitManager/gitManager import { GitManagerInProgressStrip } from "./gitManager/GitManagerInProgressStrip"; import { GitManagerMergeDialog } from "./gitManager/merge/GitManagerMergeDialog"; import { GitManagerOperationBanner } from "./gitManager/toolbar/GitManagerOperationBanner"; -import { canOpenPullRequestInPanel } from "./pullRequests/pullRequestsAvailability"; +import { usePullRequestsContextQuery } from "./pullRequests/usePullRequestsContextQuery"; import { SourceControlMergeChanges } from "./SourceControlMergeChanges"; import { CodeReviewInstructionsDialog } from "./sourceControl/CodeReviewInstructionsDialog"; import { CodeReviewProjectPromptDialog } from "./sourceControl/CodeReviewProjectPromptDialog"; @@ -421,17 +423,33 @@ export default function SourceControlPanel({ [codeReviewMenuReviewers, codeReviewScope, status], ); + // The panel can show the request only on a host that has it, with the setting on and a server + // that reads pull requests. Otherwise View PR opens the browser. + const openPrUrl = status?.pr?.state === "open" ? status.pr.url : null; + const panelSupported = canShowPullRequestInPanel({ + enabled: pullRequestsEnabled, + pullRequestsReads: capabilities?.pullRequestsReads === true, + providerKind: status?.sourceControlProvider?.kind ?? "unknown", + }); + // The panel addresses the checkout's origin, while the request lookup may have used another + // repository. Until the context is known, the panel opens and explains itself. + const { query: pullRequestsContext } = usePullRequestsContextQuery({ + environmentId, + cwd: gitCwd, + enabled: panelSupported && openPrUrl !== null, + }); + const panelRepository = + pullRequestsContext.data?.status === "available" ? pullRequestsContext.data.repository : null; + const canOpenInPanel = + panelSupported && + !(openPrUrl !== null && isPullRequestInOtherRepository(openPrUrl, panelRepository)); // Legacy servers (no staging areas) keep the chat-header cascade // (commit_push-first, commit-by-filePaths). The primary button and dropdown // below fork on `hasAreas`: this pair drives the legacy branch unchanged. const quickAction = useMemo( - () => resolveQuickAction(status, isBusy, isDefaultRef, hasPrimaryRemote), - [status, isBusy, isDefaultRef, hasPrimaryRemote], + () => resolveQuickAction(status, isBusy, isDefaultRef, hasPrimaryRemote, canOpenInPanel), + [status, isBusy, isDefaultRef, hasPrimaryRemote, canOpenInPanel], ); - const canOpenInPanel = canOpenPullRequestInPanel({ - enabled: pullRequestsEnabled, - providerKind: status?.sourceControlProvider?.kind ?? "unknown", - }); const menuItems = useMemo( () => buildMenuItems(status, isBusy, hasPrimaryRemote, canOpenInPanel), [status, isBusy, hasPrimaryRemote, canOpenInPanel], @@ -1036,12 +1054,13 @@ export default function SourceControlPanel({ const onPrimaryAction = useCallback(() => { if (quickAction.kind === "open_pr") return openPr(); + if (quickAction.kind === "open_pr_panel") return openPrInPanel(); if (quickAction.kind === "run_pull") return void runPull(); if (quickAction.kind === "run_action" && quickAction.action) { return void runGitAction(quickAction.action); } // open_publish / show_hint: no-op here (surfaced as disabled below). - }, [openPr, quickAction, runGitAction, runPull]); + }, [openPr, openPrInPanel, quickAction, runGitAction, runPull]); // Commit-first ladder dispatch (staging-area servers). Commit-family actions // route through runGitAction, which holds the ledger guard (commit the staged @@ -1063,9 +1082,12 @@ export default function SourceControlPanel({ case "open_pr": openPr(); return; + case "open_pr_panel": + openPrInPanel(); + return; // publish / sync_hint / none: disabled below, no-op here. } - }, [primaryAction, runGitAction, runStage, runPull, openPr, groups]); + }, [primaryAction, runGitAction, runStage, runPull, openPr, openPrInPanel, groups]); const onScMenuItem = useCallback( (item: SourceControlMenuItem) => { @@ -1774,8 +1796,9 @@ export default function SourceControlPanel({ }} onDone={(request) => { if ( - canOpenPullRequestInPanel({ + canShowPullRequestInPanel({ enabled: pullRequestsEnabled, + pullRequestsReads: capabilities?.pullRequestsReads === true, providerKind: request.provider, }) ) diff --git a/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts b/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts index 2e28480b29..0978a573e3 100644 --- a/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts +++ b/apps/web/src/components/SourceControlPrimaryAction.logic.test.ts @@ -219,12 +219,36 @@ describe("resolveSourceControlPrimaryAction — commit-first ladder", () => { hasPrimaryRemote: false, }), ); - assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View PR", disabled: false }); }); - it("views an open PR when clean, synced, and a PR is open", () => { + it("views an open PR in the panel when clean, synced, and a PR is open", () => { const action = resolveSourceControlPrimaryAction(makeInput({ status: { pr: OPEN_PR } })); - assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View PR", disabled: false }); + }); + + it("views an open PR in the browser when the panel cannot show it", () => { + for (const statusOverrides of [ + { pr: OPEN_PR }, + { hasUpstream: false, aheadCount: 0, pr: OPEN_PR }, + ]) { + const action = resolveSourceControlPrimaryAction( + makeInput({ status: statusOverrides, hasPrimaryRemote: false, canOpenInPanel: false }), + ); + assert.deepEqual(action, { kind: "open_pr", label: "View PR", disabled: false }); + } + }); + + it("words the panel action View MR on GitLab", () => { + const action = resolveSourceControlPrimaryAction( + makeInput({ + status: { + pr: OPEN_PR, + sourceControlProvider: { kind: "gitlab", name: "GitLab", baseUrl: "https://gitlab.test" }, + }, + }), + ); + assert.deepEqual(action, { kind: "open_pr_panel", label: "View MR", disabled: false }); }); it("creates a PR when synced with upstream but ahead of the default ref", () => { @@ -408,20 +432,20 @@ describe("buildSourceControlMenuItems — always-rendered, disabled-with-reason" "push", "pull", "merge", - "open_pr", "open_pr_panel", + "open_pr", ]); - assert.deepInclude(menuItem(items, "open_pr"), { - label: "View PR", - disabled: false, - kind: "open_pr", - }); assert.deepInclude(menuItem(items, "open_pr_panel"), { - label: "Open PR in panel", + label: "View PR", disabled: false, kind: "open_pr_panel", group: "remote", }); + assert.deepInclude(menuItem(items, "open_pr"), { + label: "Open PR in browser", + disabled: false, + kind: "open_pr", + }); }); it("omits the in-panel action where the panel cannot show the request", () => { @@ -429,7 +453,7 @@ describe("buildSourceControlMenuItems — always-rendered, disabled-with-reason" makeInput({ status: { aheadCount: 2, pr: OPEN_PR }, canOpenInPanel: false }), ); assert.notInclude(menuIds(items), "open_pr_panel"); - assert.include(menuIds(items), "open_pr"); + assert.deepInclude(menuItem(items, "open_pr"), { label: "View PR", kind: "open_pr" }); }); it("offers no in-panel action without an open request", () => { diff --git a/apps/web/src/components/SourceControlPrimaryAction.logic.ts b/apps/web/src/components/SourceControlPrimaryAction.logic.ts index 10ee4dc02d..2a88cfa8c2 100644 --- a/apps/web/src/components/SourceControlPrimaryAction.logic.ts +++ b/apps/web/src/components/SourceControlPrimaryAction.logic.ts @@ -34,6 +34,7 @@ export type SourceControlPrimaryActionKind = | "publish" | "create_pr" | "open_pr" + | "open_pr_panel" | "none"; export interface SourceControlPrimaryAction { @@ -96,7 +97,7 @@ export interface SourceControlPrimaryActionInput { stageableCount: number; /** The environment runs Git Manager fetch and merge operations for this project. */ mergeAvailable: boolean; - /** The thread's right panel can show this branch's request (setting on, host supported). */ + /** The thread's right panel can show this branch's request (setting on, host and server support it). */ canOpenInPanel: boolean; } @@ -151,6 +152,7 @@ function resolvePrimaryActionForStatus( const terminology = resolveChangeRequestTerminology(gitStatus); const changeRequestsEnabled = supportsChangeRequests(gitStatus); const pushEnabledForRef = canPushFromCurrentRef(gitStatus); + const viewPrKind = input.canOpenInPanel ? "open_pr_panel" : "open_pr"; // Staged content always wins — commit the staged index as-is. Enabled even // with an empty message (auto-generate divergence); ordering intentionally @@ -196,7 +198,7 @@ function resolvePrimaryActionForStatus( if (!gitStatus.hasUpstream) { if (!hasPrimaryRemote) { if (changeRequestsEnabled && hasOpenPr && !isAhead) { - return { kind: "open_pr", label: `View ${terminology.shortLabel}`, disabled: false }; + return { kind: viewPrKind, label: `View ${terminology.shortLabel}`, disabled: false }; } return { kind: "publish", label: "Publish repository", disabled: false }; } @@ -265,7 +267,7 @@ function resolvePrimaryActionForStatus( } if (changeRequestsEnabled && hasOpenPr) { - return { kind: "open_pr", label: `View ${terminology.shortLabel}`, disabled: false }; + return { kind: viewPrKind, label: `View ${terminology.shortLabel}`, disabled: false }; } if (changeRequestsEnabled && pushEnabledForRef && hasDefaultBranchDelta && !isDefaultRef) { @@ -386,10 +388,10 @@ export function buildSourceControlMenuItems( }, changeRequestsEnabled && hasOpenPr ? { - id: "open_pr", + id: input.canOpenInPanel ? "open_pr_panel" : "open_pr", label: `View ${terminology.shortLabel}`, group: "remote", - kind: "open_pr", + kind: input.canOpenInPanel ? "open_pr_panel" : "open_pr", ...gate(undefined), } : changeRequestsEnabled @@ -417,10 +419,10 @@ export function buildSourceControlMenuItems( : null, changeRequestsEnabled && hasOpenPr && input.canOpenInPanel ? { - id: "open_pr_panel", - label: `Open ${terminology.shortLabel} in panel`, + id: "open_pr", + label: `Open ${terminology.shortLabel} in browser`, group: "remote", - kind: "open_pr_panel", + kind: "open_pr", ...gate(undefined), } : null, diff --git a/apps/web/src/components/activity/activityPresentation.test.ts b/apps/web/src/components/activity/activityPresentation.test.ts index a2f4386815..d179b54260 100644 --- a/apps/web/src/components/activity/activityPresentation.test.ts +++ b/apps/web/src/components/activity/activityPresentation.test.ts @@ -37,6 +37,9 @@ describe("activityRecordTimeLabel", () => { expect(activityStopUnavailableReason("claudeAgent")).toBe( "Claude doesn't offer a way to stop this subagent from BiBCode.", ); + expect(activityStopUnavailableReason("antigravity")).toBe( + "Antigravity doesn't offer a way to stop this subagent from BiBCode.", + ); expect(activityStopUnavailableReason("custom")).toBe( "The provider doesn't offer a way to stop this subagent from BiBCode.", ); diff --git a/apps/web/src/components/activity/activityPresentation.ts b/apps/web/src/components/activity/activityPresentation.ts index a3f2aba5f5..d6c61ee102 100644 --- a/apps/web/src/components/activity/activityPresentation.ts +++ b/apps/web/src/components/activity/activityPresentation.ts @@ -249,6 +249,7 @@ const PROVIDER_LABELS: Readonly> = { opencode: "OpenCode", cursor: "Cursor", grok: "Grok", + antigravity: "Antigravity", }; /** Why a running subagent has no Stop, without promising another way to end it. */ diff --git a/apps/web/src/components/chat/ChatComposer.test.tsx b/apps/web/src/components/chat/ChatComposer.test.tsx index 730217b5d3..adef33fccf 100644 --- a/apps/web/src/components/chat/ChatComposer.test.tsx +++ b/apps/web/src/components/chat/ChatComposer.test.tsx @@ -1413,6 +1413,57 @@ describe("ChatComposer rendering", () => { expect(activePlan["className"]).toContain("text-foreground"); }); + it("shows an Antigravity chat's advertised model, its thinking levels and Plan (R13)", () => { + const antigravityInstanceId = ProviderInstanceId.make("antigravity"); + const level = (ids: ReadonlyArray) => ({ + id: "reasoning", + label: "Thinking level", + type: "select" as const, + options: ids.map((id) => ({ id, label: `Level ${id}`, isDefault: id === "low" })), + }); + const antigravityProvider: ServerProvider = { + ...codexProvider, + instanceId: antigravityInstanceId, + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + slashCommands: [], + skills: [], + agents: [], + models: [ + { + slug: "model-alpha", + name: "Model Alpha", + isCustom: false, + capabilities: { optionDescriptors: [level(["low", "high"])] }, + }, + { + slug: "model-beta", + name: "Model Beta", + isCustom: false, + capabilities: { optionDescriptors: [level(["low", "high", "xhigh"])] }, + }, + ], + }; + const selection = { + instanceId: antigravityInstanceId, + model: "model-beta", + options: [{ id: "reasoning", value: "xhigh" }], + }; + + const { markup, spies } = renderComposer({ + providerStatuses: [codexProvider, antigravityProvider], + providerBindingInstanceId: antigravityInstanceId, + activeProjectDefaultModelSelection: selection, + activeThreadModelSelection: selection, + }); + + expect(markup).toContain('data-instance="antigravity"'); + expect(markup).toContain('data-model="model-beta"'); + expect(markup).toContain('aria-label="Reasoning effort: Level xhigh"'); + (captureByLabel("Button", "Enable plan mode")["onClick"] as () => void)(); + expect(spies.toggleInteractionMode).toHaveBeenCalledOnce(); + }); + it("keeps runtime controls icon-only at compact and regular widths", () => { const { spies } = renderComposer({ runtimeMode: "auto-accept-edits" }); diff --git a/apps/web/src/components/chat/TraitsPicker.test.tsx b/apps/web/src/components/chat/TraitsPicker.test.tsx index 33b919040f..9d4401b66b 100644 --- a/apps/web/src/components/chat/TraitsPicker.test.tsx +++ b/apps/web/src/components/chat/TraitsPicker.test.tsx @@ -918,6 +918,64 @@ describe("TraitsPicker", () => { expect(document.querySelector('button[aria-label^="Reasoning effort:"]')).toBeNull(); }); + it("shows each Antigravity model's own advertised thinking levels (R13)", async () => { + const level = (ids: ReadonlyArray) => + selectDescriptor( + "reasoning", + "Thinking level", + ids.map((id) => ({ + id, + label: id.toUpperCase(), + ...(id === "low" ? { isDefault: true } : {}), + })), + ); + const models: ReadonlyArray = [ + { + slug: "model-alpha", + name: "Model Alpha", + isCustom: false, + capabilities: { optionDescriptors: [level(["low", "medium", "high"])] }, + }, + { + slug: "model-beta", + name: "Model Beta", + isCustom: false, + capabilities: { optionDescriptors: [level(["low", "medium", "high", "xhigh"])] }, + }, + ]; + const antigravity = ProviderDriverKind.make("antigravity"); + + await mount( +
+ + +
, + ); + + const bars = (label: string) => + document + .querySelector(`button[aria-label="Reasoning effort: ${label}"]`) + ?.querySelector('[aria-hidden="true"]')?.children; + expect(bars("HIGH")).toHaveLength(3); + expect(bars("XHIGH")).toHaveLength(4); + }); + it("replaces composer controls when the provider instance and model change", async () => { const mounted = await mount( { expect(actions.map(({ value }) => value)).toEqual(["chat:codex", "terminal:codex"]); }); + it("lists Antigravity chat and Antigravity Terminal only once the instance is enabled (R11, R13)", () => { + const antigravity = provider({ + instanceId: "antigravity", + driver: "antigravity", + displayName: "Antigravity", + }); + const antigravityId = ProviderInstanceId.make("antigravity"); + + expect( + buildProviderAgentActions([readyCodex, antigravity], DEFAULT_SERVER_SETTINGS).map( + ({ value }) => value, + ), + ).toEqual(["chat:codex", "terminal:codex"]); + + const actions = buildProviderAgentActions([readyCodex, antigravity], { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [antigravityId]: { driver: ProviderDriverKind.make("antigravity"), enabled: true }, + }, + }); + expect( + actions + .filter((action) => action.entry.instanceId === antigravityId) + .map(({ value, label, disabled }) => ({ value, label, disabled })), + ).toEqual([ + { value: "chat:antigravity", label: "Antigravity", disabled: false }, + { value: "terminal:antigravity", label: "Antigravity Terminal", disabled: false }, + ]); + }); + it("keeps visible but unready providers disabled", () => { const [chat, terminal] = buildProviderAgentActions([unreadyCodex], settings); diff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts index 37ea10648e..5b1155cabd 100644 --- a/apps/web/src/components/chat/providerIconUtils.ts +++ b/apps/web/src/components/chat/providerIconUtils.ts @@ -1,5 +1,13 @@ import { ProviderDriverKind } from "@bibcode/contracts"; -import { ClaudeAI, CursorIcon, GrokIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { + AntigravityIcon, + ClaudeAI, + CursorIcon, + GrokIcon, + Icon, + OpenAI, + OpenCodeIcon, +} from "../Icons"; import { PROVIDER_OPTIONS } from "../../session-logic"; export const PROVIDER_ICON_BY_PROVIDER: Partial> = { @@ -8,6 +16,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial [ProviderDriverKind.make("opencode")]: OpenCodeIcon, [ProviderDriverKind.make("cursor")]: CursorIcon, [ProviderDriverKind.make("grok")]: GrokIcon, + [ProviderDriverKind.make("antigravity")]: AntigravityIcon, }; function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is { diff --git a/apps/web/src/components/chat/providerTerminalActions.test.ts b/apps/web/src/components/chat/providerTerminalActions.test.ts index a565429a52..c5a97921b0 100644 --- a/apps/web/src/components/chat/providerTerminalActions.test.ts +++ b/apps/web/src/components/chat/providerTerminalActions.test.ts @@ -8,6 +8,7 @@ import { TERMINAL_LAUNCH_EXECUTABLE_MAX_LENGTH, TERMINAL_LAUNCH_LABEL_MAX_LENGTH, type ProviderOptionDescriptor, + type ProviderSessionDefault, type ServerSettings, type ServerProviderModel, } from "@bibcode/contracts"; @@ -29,6 +30,7 @@ const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent"); const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); const GROK_DRIVER = ProviderDriverKind.make("grok"); const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); +const ANTIGRAVITY_DRIVER = ProviderDriverKind.make("antigravity"); function entry( driver: string, @@ -679,6 +681,7 @@ describe("resolveProviderTerminalAction", () => { it.each([ { driver: CURSOR_DRIVER, executable: "cursor-agent" }, { driver: GROK_DRIVER, executable: "grok" }, + { driver: ANTIGRAVITY_DRIVER, executable: "agy" }, ])("names the $driver provider so its status reads unavailable", ({ driver, executable }) => { const action = resolveProviderTerminalAction(entry(driver, driver), DEFAULT_SERVER_SETTINGS); @@ -769,6 +772,156 @@ describe("resolveProviderTerminalAction", () => { }); }); +describe("Antigravity Terminal (R12)", () => { + const ANTIGRAVITY_ID = ProviderInstanceId.make("antigravity"); + const thinkingLevel: ProviderOptionDescriptor = { + id: "reasoning", + label: "Thinking level", + type: "select", + options: [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium", isDefault: true }, + { id: "high", label: "High" }, + ], + currentValue: "medium", + }; + const catalog = [model("model-alpha", [thinkingLevel]), model("model-beta", [thinkingLevel])]; + + function withDefault( + configuredDefault: ProviderSessionDefault | undefined, + overrides: Partial = {}, + ): ServerSettings { + return { + ...DEFAULT_SERVER_SETTINGS, + ...overrides, + providerSessionDefaults: configuredDefault ? { [ANTIGRAVITY_DRIVER]: configuredDefault } : {}, + }; + } + + function launch( + settings: ServerSettings, + instanceId = "antigravity", + displayName = "Antigravity", + ) { + return resolveProviderTerminalAction( + entry("antigravity", instanceId, displayName, catalog), + settings, + ); + } + + it("starts plain agy with the bypass flag and no model when no default is saved", () => { + const action = launch(withDefault(undefined)); + + // The resolver would pick model-alpha from the catalog; the terminal must not (D-A6). + expect(action?.command).toEqual({ + executable: "agy", + args: ["--dangerously-skip-permissions"], + label: "Antigravity Terminal", + activity: { driverKind: ANTIGRAVITY_DRIVER, providerInstanceId: ANTIGRAVITY_ID }, + }); + expect(action).not.toHaveProperty("fallback"); + }); + + it("passes the saved model alone, without the catalog's default thinking level", () => { + expect(launch(withDefault({ model: "model-beta" }))?.command?.args).toEqual([ + "--dangerously-skip-permissions", + "--model", + "model-beta", + ]); + }); + + it("passes the saved model and thinking level as stored", () => { + expect( + launch(withDefault({ model: "model-beta", options: [{ id: "reasoning", value: "high" }] })) + ?.command?.args, + ).toEqual(["--dangerously-skip-permissions", "--model", "model-beta", "--effort", "high"]); + }); + + it("passes a saved model the catalog does not list, and no fallback", () => { + const action = launch(withDefault({ model: "model-gamma" })); + + expect(action?.command?.args).toEqual([ + "--dangerously-skip-permissions", + "--model", + "model-gamma", + ]); + expect(action).not.toHaveProperty("fallback"); + }); + + it("reads the thinking level only from the reasoning option", () => { + expect( + launch(withDefault({ model: "model-beta", options: [{ id: "effort", value: "high" }] })) + ?.command?.args, + ).toEqual(["--dangerously-skip-permissions", "--model", "model-beta"]); + }); + + it("never resumes a conversation", () => { + const args = + launch(withDefault({ model: "model-beta", options: [{ id: "reasoning", value: "high" }] })) + ?.command?.args ?? []; + + for (const flag of ["--continue", "-c", "--conversation"]) { + expect(args).not.toContain(flag); + } + }); + + it("starts a custom instance's binary and names that instance", () => { + const customId = ProviderInstanceId.make("antigravity_work"); + const settings = withDefault(undefined, { + providerInstances: { + [customId]: { + driver: ANTIGRAVITY_DRIVER, + displayName: "Work Antigravity", + enabled: true, + config: { binaryPath: " custom-agy " }, + }, + }, + }); + + expect(launch(settings, customId, "Work Antigravity")).toMatchObject({ + label: "Work Antigravity Terminal", + command: { + executable: "custom-agy", + args: ["--dangerously-skip-permissions"], + activity: { driverKind: ANTIGRAVITY_DRIVER, providerInstanceId: customId }, + }, + }); + }); + + it("starts the legacy binary path of the default instance", () => { + const settings = withDefault(undefined, { + providers: { + ...DEFAULT_SERVER_SETTINGS.providers, + antigravity: { ...DEFAULT_SERVER_SETTINGS.providers.antigravity, binaryPath: "legacy-agy" }, + }, + }); + + expect(launch(settings)?.command?.executable).toBe("legacy-agy"); + }); + + it("disables the action when the saved model exceeds command bounds", () => { + const action = launch( + withDefault({ model: "x".repeat(TERMINAL_LAUNCH_ARGUMENT_MAX_LENGTH + 1) }), + ); + + expect(action).toMatchObject({ + command: null, + disabledReason: + "Provider terminal command exceeds supported limits. Shorten the provider name or configured binary path.", + }); + }); + + it("offers no review terminal", () => { + expect( + resolveProviderReviewTerminalAction( + entry("antigravity", "antigravity", "Antigravity", catalog), + DEFAULT_SERVER_SETTINGS, + { prompt: "Review.", platformOs: "linux", modelSelection: null }, + ), + ).toBeNull(); + }); +}); + describe("resolveProviderReviewTerminalAction", () => { const PROMPT = "Code review requested from BiBCode. Do not edit files. Scope: the staged, unstaged and untracked changes in the working tree.\n\nReview."; diff --git a/apps/web/src/components/chat/providerTerminalActions.ts b/apps/web/src/components/chat/providerTerminalActions.ts index ace7d57d62..215d8c582a 100644 --- a/apps/web/src/components/chat/providerTerminalActions.ts +++ b/apps/web/src/components/chat/providerTerminalActions.ts @@ -3,6 +3,7 @@ import { ProviderDriverKind, TERMINAL_LAUNCH_ARGUMENT_MAX_LENGTH, type ModelSelection, + type ProviderSessionDefault, type ServerSettings, type TerminalLaunchCommand, } from "@bibcode/contracts"; @@ -56,6 +57,10 @@ const DEFINITIONS: Partial option.id === "reasoning")?.value; + return [ + "--model", + configuredDefault.model, + ...(typeof effort === "string" ? ["--effort", effort] : []), + ]; +} + function resolveTerminalLaunch( entry: ProviderInstanceEntry, settings: ProviderTerminalSettings, @@ -168,20 +187,25 @@ function resolveTerminalLaunch( ) { const instance = settings.providerInstances?.[entry.instanceId]; const legacy = (settings.providers as Readonly>)[entry.driverKind]; + const configuredDefault = settings.providerSessionDefaults[entry.driverKind] ?? null; const resolution = resolveProviderSessionDefault({ driver: entry.driverKind, instanceId: entry.instanceId, models: entry.models, - configuredDefault: settings.providerSessionDefaults[entry.driverKind] ?? null, + configuredDefault, explicitSelection, }); + const rawDefaultOnly = entry.driverKind === ProviderDriverKind.make("antigravity"); return { executable: binaryPath(instance?.config) ?? binaryPath(legacy) ?? definition.executable, // Every AI Terminal names its provider: the server observes the ones it can (Codex, Claude, // OpenCode on macOS and Linux) and reports the rest as status unavailable (#187). activity: { driverKind: entry.driverKind, providerInstanceId: entry.instanceId }, - resolution, - modelArguments: providerArguments(entry.driverKind, resolution, entry.models), + // No resolver fallback reaches Antigravity's argv, so none is reported either. + resolution: rawDefaultOnly ? { ...resolution, fallback: null } : resolution, + modelArguments: rawDefaultOnly + ? antigravityArguments(configuredDefault) + : providerArguments(entry.driverKind, resolution, entry.models), }; } diff --git a/apps/web/src/components/files/FileEditorToolbar.test.tsx b/apps/web/src/components/files/FileEditorToolbar.test.tsx index b234e772a4..a8429c7191 100644 --- a/apps/web/src/components/files/FileEditorToolbar.test.tsx +++ b/apps/web/src/components/files/FileEditorToolbar.test.tsx @@ -4,7 +4,8 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { FileEditorToolbar } from "./FileEditorToolbar"; +import { FileEditorToolbar, redoShortcutLabel } from "./FileEditorToolbar"; +import { isMacPlatform } from "../../lib/platform"; import { TooltipProvider } from "../ui/tooltip"; describe("FileEditorToolbar", () => { @@ -202,6 +203,18 @@ describe("FileEditorToolbar", () => { expect(container.textContent).not.toContain("Saved"); }); + it("names every redo chord that works on the platform and in the active view", () => { + for (const rendered of [false, true]) { + expect(redoShortcutLabel(false, rendered)).toContain("Shift+Ctrl+Z"); + expect(redoShortcutLabel(false, rendered)).toContain("Ctrl+Y"); + expect(redoShortcutLabel(true, rendered)).toContain("Shift+Cmd+Z"); + expect(redoShortcutLabel(true, rendered)).not.toContain("Ctrl+Y"); + } + // TipTap binds Mod-y in the rendered view; Pierre's source view binds no Cmd+Y. + expect(redoShortcutLabel(true, true)).toContain("Cmd+Y"); + expect(redoShortcutLabel(true, false)).not.toContain("Cmd+Y"); + }); + it("keeps native disabled buttons inside focusable hover tooltip triggers", async () => { act(() => { root.render( @@ -233,7 +246,7 @@ describe("FileEditorToolbar", () => { await Promise.resolve(); }); expect(document.body.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain( - "Redo (Shift+Ctrl/Cmd+Z)", + redoShortcutLabel(isMacPlatform(navigator.platform), false), ); await act(async () => { diff --git a/apps/web/src/components/files/FileEditorToolbar.tsx b/apps/web/src/components/files/FileEditorToolbar.tsx index 7f7caf34c1..b674bbb745 100644 --- a/apps/web/src/components/files/FileEditorToolbar.tsx +++ b/apps/web/src/components/files/FileEditorToolbar.tsx @@ -1,6 +1,7 @@ import { Code2, Eye, LoaderCircle, Redo2, Save, Undo2 } from "lucide-react"; import { type ReactNode, useEffect, useState } from "react"; +import { isMacPlatform } from "../../lib/platform"; import { Button } from "../ui/button"; import { Toggle } from "../ui/toggle"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -9,6 +10,15 @@ import type { FileSavePhase } from "./fileSaveCoordinator"; const SAVED_INDICATOR_DURATION_MS = 1_500; +/** + * The Redo tooltip: every redo chord that works on the platform in the active view. Ctrl+Y works + * only off macOS; on macOS the rendered editor also redoes with Cmd+Y and the source editor does not. + */ +export function redoShortcutLabel(isMac: boolean, rendered: boolean): string { + if (!isMac) return "Redo (Shift+Ctrl+Z or Ctrl+Y)"; + return rendered ? "Redo (Shift+Cmd+Z or Cmd+Y)" : "Redo (Shift+Cmd+Z)"; +} + /** A file shown either rendered (Markdown, SVG image) or as the source text in the editor. */ export interface FileEditorMarkdownView { readonly rendered: boolean; @@ -179,7 +189,10 @@ export function FileEditorToolbar({ } disabled={!canRedo} label="Redo" - tooltip="Redo (Shift+Ctrl/Cmd+Z)" + tooltip={redoShortcutLabel( + isMacPlatform(navigator.platform), + markdownView?.rendered ?? false, + )} onClick={onRedo} > diff --git a/apps/web/src/components/files/FilePreviewPanel.test.tsx b/apps/web/src/components/files/FilePreviewPanel.test.tsx index e0126d24da..e208a0c31a 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.test.tsx @@ -2172,7 +2172,7 @@ describe("disk watching wiring", () => { renderPanel(baseProps()); const session = testState.session as unknown as DiskSession; const surface = fakeSurface(); - harness.refs[1]!.current = surface.element; + harness.refs[2]!.current = surface.element; stubVisibleWindow(); const cleanups = harness.runEffects(); @@ -2242,7 +2242,7 @@ describe("effects wiring", () => { it("installs the editor dismissal handler on the surface", () => { renderWithEffects(); const surface = fakeSurface(); - harness.refs[1]!.current = surface.element; + harness.refs[2]!.current = surface.element; harness.runEffects(); expect(testState.installFileEditorDismissal).toHaveBeenCalledTimes(1); const input = testState.installFileEditorDismissal.mock.calls[0]![0] as { @@ -2260,7 +2260,7 @@ describe("effects wiring", () => { it("saves explicitly on the scoped mod+s chord", () => { renderWithEffects(); const surface = fakeSurface(); - harness.refs[1]!.current = surface.element; + harness.refs[2]!.current = surface.element; const cleanups = harness.runEffects(); const handler = surface.listeners.get("keydown"); expect(handler).toBeDefined(); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 596456ff58..33513a923d 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -83,6 +83,7 @@ import { useInsertImage } from "./richMarkdown/useInsertImage"; import type { RichMarkdownEditor } from "./richMarkdown/richMarkdownExtensions"; import { FileMediaPreview } from "./FileMediaPreview"; import { preloadRichMarkdownSurface, RichMarkdownView } from "./RichMarkdownView"; +import { type FilesEditHistory, useFilesEditRegion } from "./editMenuHistory"; import { explainUndeliveredEdit, saveFile, useFileSaveShortcut } from "./useFileSaveShortcut"; import { filePreviewKind, @@ -897,6 +898,15 @@ export default function FilePreviewPanel({ const richEditable = richMode?.editable === true && richEditor !== null; const activeRichEditor = renderMarkdown && richEditable ? (richEditor ?? null) : null; const [linkDialogOpen, setLinkDialogOpen] = useState(false); + // One history for the toolbar buttons and the desktop Edit menu. + const editHistory = useMemo(() => { + if (activeRichEditor) { + return { undo: () => activeRichEditor.undo(), redo: () => activeRichEditor.redo() }; + } + return session ? { undo: () => session.undo(), redo: () => session.redo() } : null; + }, [activeRichEditor, session]); + const editRegionRef = useRef(null); + useFilesEditRegion(editRegionRef, editHistory); const richMarkdownWorkspace = useMemo( () => ({ environmentId, @@ -1122,8 +1132,8 @@ export default function FilePreviewPanel({ onSave={() => { if (session) saveFile(session); }} - onUndo={() => (activeRichEditor ? activeRichEditor.undo() : session?.undo())} - onRedo={() => (activeRichEditor ? activeRichEditor.redo() : session?.redo())} + onUndo={() => editHistory?.undo()} + onRedo={() => editHistory?.redo()} /> ) : null} {activeRichEditor && linkDialogOpen ? ( @@ -1153,6 +1163,7 @@ export default function FilePreviewPanel({ ) : null}
void>(), redo: vi.fn<() => void>() }; +} + +function editable(parent: Node): HTMLDivElement { + const element = document.createElement("div"); + element.contentEditable = "true"; + element.tabIndex = 0; + parent.appendChild(element); + return element; +} + +describe("runEditMenuAction", () => { + let execCommand: ReturnType boolean>>; + const cleanups: (() => void)[] = []; + + beforeEach(() => { + execCommand = vi.fn<(command: string) => boolean>(() => true); + document.execCommand = execCommand as unknown as Document["execCommand"]; + }); + + afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup(); + document.body.replaceChildren(); + }); + + function region(target: FilesEditHistory): HTMLDivElement { + const element = document.createElement("div"); + document.body.append(element); + cleanups.push(registerFilesEditRegion(element, target)); + return element; + } + + it("moves only the focused Files history, one step, with no native undo", () => { + const first = history(); + const second = history(); + editable(region(first)); + editable(region(second)).focus(); + + runEditMenuAction("edit-undo", false); + + expect(second.undo).toHaveBeenCalledTimes(1); + expect(first.undo).not.toHaveBeenCalled(); + expect(execCommand).not.toHaveBeenCalled(); + }); + + it("redoes the focused Files history", () => { + const files = history(); + editable(region(files)).focus(); + + runEditMenuAction("edit-redo", false); + + expect(files.redo).toHaveBeenCalledTimes(1); + expect(files.undo).not.toHaveBeenCalled(); + expect(execCommand).not.toHaveBeenCalled(); + }); + + it("reaches the source editor's content inside a shadow root", () => { + const files = history(); + const host = document.createElement("div"); + region(files).append(host); + const content = editable(host.attachShadow({ mode: "open" })); + content.focus(); + + runEditMenuAction("edit-undo", false); + + expect(files.undo).toHaveBeenCalledTimes(1); + }); + + it("reaches a focusable node nested in the rendered editor, such as a table cell", () => { + const files = history(); + const cell = document.createElement("td"); + cell.tabIndex = 0; + editable(region(files)).append(cell); + cell.focus(); + + runEditMenuAction("edit-undo", false); + + expect(files.undo).toHaveBeenCalledTimes(1); + }); + + it("leaves a text field inside Files, like the comment textarea, to its native undo", () => { + const files = history(); + const comment = document.createElement("textarea"); + region(files).append(comment); + comment.focus(); + + runEditMenuAction("edit-undo", false); + + expect(files.undo).not.toHaveBeenCalled(); + expect(execCommand).toHaveBeenCalledWith("undo"); + }); + + it("leaves editable text outside Files, like the composer, to its native undo and redo", () => { + region(history()); + editable(document.body).focus(); + + runEditMenuAction("edit-undo", false); + runEditMenuAction("edit-redo", false); + + expect(execCommand.mock.calls).toEqual([["undo"], ["redo"]]); + }); + + it("keeps the native path during a composition in Files", () => { + const files = history(); + editable(region(files)).focus(); + + runEditMenuAction("edit-undo", true); + + expect(files.undo).not.toHaveBeenCalled(); + expect(execCommand).toHaveBeenCalledWith("undo"); + }); + + it("forgets a region once it is unregistered", () => { + const files = history(); + const element = document.createElement("div"); + document.body.append(element); + const unregister = registerFilesEditRegion(element, files); + editable(element).focus(); + unregister(); + + runEditMenuAction("edit-undo", false); + + expect(files.undo).not.toHaveBeenCalled(); + expect(execCommand).toHaveBeenCalledWith("undo"); + }); +}); + +describe("useEditMenuActions and useFilesEditRegion", () => { + afterEach(() => { + delete (window as { desktopBridge?: unknown }).desktopBridge; + document.body.replaceChildren(); + }); + + it("runs the menu actions while mounted, ignores other actions, and stops after unmount", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const execCommand = vi.fn<(command: string) => boolean>(() => true); + document.execCommand = execCommand as unknown as Document["execCommand"]; + let listener: ((action: string) => void) | null = null; + const unsubscribe = vi.fn(() => { + listener = null; + }); + Object.assign(window, { + desktopBridge: { + onMenuAction: (next: (action: string) => void) => { + listener = next; + return unsubscribe; + }, + }, + }); + const files = history(); + function Probe() { + useEditMenuActions([]); + const region = useRef(null); + useFilesEditRegion(region, files); + return ( +
+
+
+ ); + } + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => root.render()); + container.querySelector('[data-testid="text"]')!.focus(); + const send = (action: string) => (listener as ((action: string) => void) | null)?.(action); + + send("edit-undo"); + send("open-settings"); + expect(files.undo).toHaveBeenCalledTimes(1); + expect(execCommand).not.toHaveBeenCalled(); + + await act(async () => root.unmount()); + expect(unsubscribe).toHaveBeenCalledTimes(1); + send("edit-undo"); + expect(files.undo).toHaveBeenCalledTimes(1); + }); + + it("forgets a composition whose editor went away before it ended", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const execCommand = vi.fn<(command: string) => boolean>(() => true); + document.execCommand = execCommand as unknown as Document["execCommand"]; + let listener: ((action: string) => void) | null = null; + Object.assign(window, { + desktopBridge: { + onMenuAction: (next: (action: string) => void) => { + listener = next; + return () => {}; + }, + }, + }); + function Listener() { + useEditMenuActions([]); + return null; + } + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => root.render()); + const files = history(); + const regionElement = document.createElement("div"); + document.body.append(regionElement); + const unregister = registerFilesEditRegion(regionElement, files); + const first = editable(regionElement); + first.focus(); + first.dispatchEvent( + new CompositionEvent("compositionstart", { bubbles: true, composed: true }), + ); + first.remove(); + editable(regionElement).focus(); + + (listener as ((action: string) => void) | null)?.("edit-undo"); + + expect(files.undo).toHaveBeenCalledTimes(1); + expect(execCommand).not.toHaveBeenCalled(); + unregister(); + await act(async () => root.unmount()); + }); + + // WebKit may start a composition on the text node or child element holding the caret, or on the + // editing host while a focusable descendant such as a table cell has focus. + it("ignores a composition in a text field of the region once focus is in the editor", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const execCommand = vi.fn<(command: string) => boolean>(() => true); + document.execCommand = execCommand as unknown as Document["execCommand"]; + let listener: ((action: string) => void) | null = null; + Object.assign(window, { + desktopBridge: { + onMenuAction: (next: (action: string) => void) => { + listener = next; + return () => {}; + }, + }, + }); + function Listener() { + useEditMenuActions([]); + return null; + } + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => root.render()); + const files = history(); + const regionElement = document.createElement("div"); + document.body.append(regionElement); + const unregister = registerFilesEditRegion(regionElement, files); + const comment = document.createElement("textarea"); + regionElement.append(comment); + comment.dispatchEvent( + new CompositionEvent("compositionstart", { bubbles: true, composed: true }), + ); + // Its compositionend was lost; the comment form stays open. + editable(regionElement).focus(); + + (listener as ((action: string) => void) | null)?.("edit-undo"); + + expect(files.undo).toHaveBeenCalledTimes(1); + expect(execCommand).not.toHaveBeenCalled(); + unregister(); + await act(async () => root.unmount()); + }); + + for (const [name, arrange] of [ + [ + "a text node inside the editor", + (host: HTMLElement) => { + const paragraph = document.createElement("p"); + paragraph.append("marked"); + host.append(paragraph); + host.focus(); + return paragraph.firstChild!; + }, + ], + [ + "a child element of the editor", + (host: HTMLElement) => { + const paragraph = document.createElement("p"); + host.append(paragraph); + host.focus(); + return paragraph; + }, + ], + [ + "the editor while a table cell inside it has focus", + (host: HTMLElement) => { + const cell = document.createElement("td"); + cell.tabIndex = 0; + host.append(cell); + cell.focus(); + return host; + }, + ], + ] as const) { + it(`keeps the native path during a composition started on ${name}`, async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const execCommand = vi.fn<(command: string) => boolean>(() => true); + document.execCommand = execCommand as unknown as Document["execCommand"]; + let listener: ((action: string) => void) | null = null; + Object.assign(window, { + desktopBridge: { + onMenuAction: (next: (action: string) => void) => { + listener = next; + return () => {}; + }, + }, + }); + function Listener() { + useEditMenuActions([]); + return null; + } + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => root.render()); + const files = history(); + const regionElement = document.createElement("div"); + document.body.append(regionElement); + const unregister = registerFilesEditRegion(regionElement, files); + const target = arrange(editable(regionElement)); + target.dispatchEvent( + new CompositionEvent("compositionstart", { bubbles: true, composed: true }), + ); + + (listener as ((action: string) => void) | null)?.("edit-undo"); + + expect(files.undo).not.toHaveBeenCalled(); + expect(execCommand).toHaveBeenCalledWith("undo"); + unregister(); + await act(async () => root.unmount()); + }); + } +}); + +describe("Linux text-field undo chords (#408)", () => { + function keydown(target: EventTarget, init: KeyboardEventInit & { key: string }): KeyboardEvent { + const event = new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + composed: true, + ...init, + }); + target.dispatchEvent(event); + return event; + } + + it("maps Ctrl+Z, Shift+Ctrl+Z and Ctrl+Y in an input or a textarea", () => { + const area = document.createElement("textarea"); + const input = document.createElement("input"); + document.body.append(area, input); + const seen: (string | null)[] = []; + const record = (event: Event) => seen.push(textFieldHistoryChord(event as KeyboardEvent)); + document.addEventListener("keydown", record); + + keydown(area, { key: "z", ctrlKey: true }); + keydown(area, { key: "Z", ctrlKey: true, shiftKey: true }); + keydown(input, { key: "y", ctrlKey: true }); + + document.removeEventListener("keydown", record); + expect(seen).toEqual(["undo", "redo", "redo"]); + }); + + it("leaves editable text, cancelled chords and other modifiers alone", () => { + const area = document.createElement("textarea"); + const text = document.createElement("div"); + text.contentEditable = "true"; + document.body.append(area, text); + const seen: (string | null)[] = []; + const record = (event: Event) => seen.push(textFieldHistoryChord(event as KeyboardEvent)); + area.addEventListener("keydown", (event) => { + if (event.key === "y") event.preventDefault(); + }); + document.addEventListener("keydown", record); + + keydown(text, { key: "z", ctrlKey: true }); + keydown(area, { key: "y", ctrlKey: true }); + keydown(area, { key: "z", metaKey: true }); + keydown(area, { key: "z", ctrlKey: true, altKey: true }); + keydown(area, { key: "z" }); + + document.removeEventListener("keydown", record); + expect(seen).toEqual([null, null, null, null, null]); + }); + + it("leaves composing keystrokes and controls that hold no editable text alone", () => { + const area = document.createElement("textarea"); + const url = document.createElement("input"); + url.type = "url"; + const checkbox = document.createElement("input"); + checkbox.type = "checkbox"; + const button = document.createElement("input"); + button.type = "button"; + const readOnly = document.createElement("input"); + readOnly.readOnly = true; + const disabled = document.createElement("textarea"); + disabled.disabled = true; + document.body.append(area, url, checkbox, button, readOnly, disabled); + const seen: (string | null)[] = []; + const record = (event: Event) => seen.push(textFieldHistoryChord(event as KeyboardEvent)); + document.addEventListener("keydown", record); + + keydown(area, { key: "z", ctrlKey: true, isComposing: true }); + keydown(area, { key: "z", ctrlKey: true, keyCode: 229 }); + keydown(url, { key: "z", ctrlKey: true }); + const padded = document.createElement("input"); + padded.setAttribute("type", " Text "); + document.body.append(padded); + keydown(padded, { key: "z", ctrlKey: true }); + keydown(checkbox, { key: "z", ctrlKey: true }); + keydown(button, { key: "z", ctrlKey: true }); + keydown(readOnly, { key: "z", ctrlKey: true }); + keydown(disabled, { key: "z", ctrlKey: true }); + // The terminal's own input textarea: xterm leaves Shift+Ctrl+Z uncancelled, for the shell. + const terminal = document.createElement("div"); + terminal.className = "xterm"; + const terminalInput = document.createElement("textarea"); + terminalInput.className = "xterm-helper-textarea"; + terminal.append(terminalInput); + document.body.append(terminal); + keydown(terminalInput, { key: "Z", ctrlKey: true, shiftKey: true }); + + document.removeEventListener("keydown", record); + expect(seen).toEqual([null, null, "undo", "undo", null, null, null, null, null]); + }); + + // Mounts the listener on a given platform with a textarea, and returns it with its cleanup. + async function mountLinuxListener( + platformName: string, + keybindings: ResolvedKeybindingsConfig = [], + ): Promise<{ field: HTMLTextAreaElement; unmount: () => Promise }> { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + Object.assign(window, { desktopBridge: { onMenuAction: () => () => {} } }); + const platform = vi.spyOn(navigator, "platform", "get").mockReturnValue(platformName); + function Probe() { + useEditMenuActions(keybindings); + return