diff --git a/.github/workflows/desktop-ui-smoke.yml b/.github/workflows/desktop-ui-smoke.yml index 3380246619..44334e6e0f 100644 --- a/.github/workflows/desktop-ui-smoke.yml +++ b/.github/workflows/desktop-ui-smoke.yml @@ -203,7 +203,7 @@ jobs: BIBCODE_E2E_ARTIFACT_DIR: ${{ runner.temp }}/bibcode-desktop-ui-artifacts run: | if [[ "$BIBCODE_E2E_PLATFORM" == "linux" ]]; then - xvfb-run --auto-servernum vp run test:ui:desktop + xvfb-run --auto-servernum -s '-screen 0 1920x1080x24' vp run test:ui:desktop else vp run test:ui:desktop fi diff --git a/apps/desktop/e2e/specs/chat-activity-panel.e2e.ts b/apps/desktop/e2e/specs/chat-activity-panel.e2e.ts index e9cc27cb54..59b51b97b2 100644 --- a/apps/desktop/e2e/specs/chat-activity-panel.e2e.ts +++ b/apps/desktop/e2e/specs/chat-activity-panel.e2e.ts @@ -7,6 +7,7 @@ import * as NodePath from "node:path"; import { configureDesktopActivityCodexExecutable, materializeDesktopActivitySession, + waitForDesktopActivityCodexInventory, startDesktopActivityComposerFollowupTurn, startDesktopActivityFollowupTurn, stopDesktopActivitySession, @@ -127,6 +128,7 @@ async function openMaterializedFixtureChat(): Promise<{ readonly threadId: string; }> { await ensureMainSidebarOpen(); + const inventory = await waitForDesktopActivityCodexInventory(); const materialized = await materializeDesktopActivitySession(preparedProjectPath); await configureDesktopActivityCodexExecutable(preparedCodexExecutable); expect(materialized.threadId).toBe(desktopActivityFixture.thread.id); @@ -137,6 +139,7 @@ async function openMaterializedFixtureChat(): Promise<{ JSON.stringify( { ...materialized, + inventory, }, null, 2, diff --git a/apps/desktop/e2e/specs/composer-message-queue.e2e.ts b/apps/desktop/e2e/specs/composer-message-queue.e2e.ts index 81d0b8634f..9ae1df59f2 100644 --- a/apps/desktop/e2e/specs/composer-message-queue.e2e.ts +++ b/apps/desktop/e2e/specs/composer-message-queue.e2e.ts @@ -234,7 +234,7 @@ describe("packaged composer message queue", () => { await openInitialCodexDraft(); await setDesktopUiWindowSize(1_100, 900); await expect(composerForm().$('[data-chat-provider-model-picker="true"]')).toHaveText( - expect.stringContaining("GPT-5.4"), + expect.stringContaining("Codex default"), ); const baseline = readProviderInputLog(preparedProviderInputLogPath).length; const prompt = "first [[slow]]"; diff --git a/apps/desktop/e2e/specs/files-binary-preview.e2e.ts b/apps/desktop/e2e/specs/files-binary-preview.e2e.ts index 87639ae530..1ff76a133e 100644 --- a/apps/desktop/e2e/specs/files-binary-preview.e2e.ts +++ b/apps/desktop/e2e/specs/files-binary-preview.e2e.ts @@ -5,6 +5,7 @@ import * as NodePath from "node:path"; import { desktopUiFixture } from "../support/test-project.ts"; import { ensureMainSidebarOpen, + expectRightPanelBesideChat, mockDesktopUiFolderPicker, setDesktopUiWindowSize, } from "../support/ui-state.ts"; @@ -194,7 +195,9 @@ async function loadedImage(): Promise<{ width: number; height: number } | null> describe("packaged Files binary previews", () => { it("shows a PNG, an SVG without running its script, and a PDF from the Files tree", async () => { writeFixtureFiles(); - await setDesktopUiWindowSize(1_600, 1_000); + // The case needs only the Files panel beside the chat, and this size fits a laptop screen. + await setDesktopUiWindowSize(1_200, 720); + await expectRightPanelBesideChat(); await openFixtureWorkspace(); await openFilesSurface(); await watchSecurityPolicyViolations(); diff --git a/apps/desktop/e2e/specs/manual/claude-approval-real-provider.e2e.ts b/apps/desktop/e2e/specs/manual/claude-approval-real-provider.e2e.ts new file mode 100644 index 0000000000..93f5d3129a --- /dev/null +++ b/apps/desktop/e2e/specs/manual/claude-approval-real-provider.e2e.ts @@ -0,0 +1,410 @@ +// @effect-diagnostics nodeBuiltinImport:off - Manual real-provider run writes an evidence file and screenshots. +// @effect-diagnostics globalDate:off - Waits for the real Claude CLI against wall-clock deadlines. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { captureStuckConnectionState } from "../../support/connection-state.ts"; +import { ensureMainSidebarOpen, mockDesktopUiFolderPicker } from "../../support/ui-state.ts"; + +/** + * Claude approvals against the installed Claude Code (#383). Not in the default suite: it runs + * the machine's own `claude` and its sign-in, so it spends a little of that account. Set + * `BIBCODE_E2E_REAL_PROVIDERS=1` and `BIBCODE_E2E_REAL_PROJECT=`, then + * `BIBCODE_E2E_SPEC=./specs/manual/claude-approval-real-provider.e2e.ts`. + * + * It writes what it saw to `real-claude-approval-evidence.txt`: a Supervised Claude chat asks + * before a command, "Always allow this session" runs it, and the same command then runs again + * with no card and no settings file. + */ +const artifactDirectory = process.env.BIBCODE_E2E_ARTIFACT_DIR; +const realProject = process.env.BIBCODE_E2E_REAL_PROJECT; +if (!artifactDirectory || !realProject) { + throw new Error("BIBCODE_E2E_ARTIFACT_DIR and BIBCODE_E2E_REAL_PROJECT are required."); +} +const evidencePath = NodePath.join(artifactDirectory, "real-claude-approval-evidence.txt"); +const probeFile = NodePath.join(realProject, "bibcode-approval-probe.txt"); +const settingsFile = NodePath.join(realProject, ".claude", "settings.local.json"); +const COMMAND = "touch bibcode-approval-probe.txt"; +const PROMPT = `Run exactly this shell command with the Bash tool and nothing else: ${COMMAND}`; +const SESSION_BUTTON = '//button[normalize-space()="Always allow this session"]'; +let surface = '[data-center-surface-host][data-visible="true"]'; + +function note(line: string): void { + NodeFS.appendFileSync(evidencePath, `${line}\n`); +} + +async function shot(name: string): Promise { + await browser.saveScreenshot( + NodePath.join(artifactDirectory!, `real-claude-approval-${name}.png`), + ); +} + +/** The first script after a launch can time out while the webview is still starting. */ +async function awaitWebview(): Promise { + for (let attempt = 0; attempt < 6; attempt += 1) { + try { + await browser.execute(() => window.location.origin); + return; + } catch { + await browser.pause(5_000); + } + } +} + +async function importProject(): Promise { + await awaitWebview(); + const appOrigin = await browser.execute(() => window.location.origin); + await browser.url(`${appOrigin}/#/`); + await ensureMainSidebarOpen(); + const loading = browser.$("//*[normalize-space()='Project data is still loading']"); + await browser.pause(1_000); + if (await loading.isExisting()) { + try { + await loading.waitForDisplayed({ reverse: true, timeout: 60_000 }); + } catch (error) { + // #381: keep what the client held, for the next diagnosis. + const state = await captureStuckConnectionState().catch((reason: unknown) => String(reason)); + note(`project data never loaded; client state: ${JSON.stringify(state)}`); + throw error; + } + } + const addProject = browser.$('[data-testid="sidebar-add-project-trigger"]'); + await addProject.waitForDisplayed(); + await addProject.click(); + await browser.$('[role="dialog"]').waitForExist(); + const browseFolder = browser.$( + "//button[@data-add-project-action='true'][.//span[normalize-space()='Browse folder']]", + ); + await browseFolder.waitForDisplayed(); + await mockDesktopUiFolderPicker(realProject!); + await browseFolder.click(); + const thread = browser.$('//*[@data-thread-item="true"]'); + await thread.waitForDisplayed({ timeout: 60_000 }); + await thread.click(); + await browser.pause(2_000); +} + +async function selectedTabId(): Promise { + const id = await browser + .$('//*[@data-center-panel-tab-id][.//*[@role="tab"][@aria-selected="true"]]') + .getAttribute("data-center-panel-tab-id"); + if (!id) throw new Error("No selected center panel tab."); + return id; +} + +async function newClaudeChat(): Promise { + const before = await selectedTabId(); + const trigger = browser.$('button[aria-label="New panel"]'); + await trigger.waitForDisplayed(); + await trigger.click(); + const item = browser.$('//*[@role="menuitem"][.//span[normalize-space()="Claude"]]'); + await item.waitForDisplayed(); + await item.click(); + await browser.waitUntil(async () => (await selectedTabId()) !== before, { + timeout: 30_000, + timeoutMsg: "The Claude panel did not open.", + }); + surface = `[data-center-surface-host="${await selectedTabId()}"]`; +} + +const composerForm = () => browser.$(`${surface} [data-chat-composer-form="true"]`); + +/** Switches the chat to Supervised, where Claude asks before commands. */ +async function chooseSupervised(): Promise { + const form = composerForm(); + await form.waitForDisplayed({ timeout: 30_000 }); + if (await form.$('[aria-label="Supervised"]').isExisting()) return; + const trigger = form.$('[aria-label="Full access"], [aria-label="Auto-accept edits"]'); + await trigger.waitForDisplayed(); + await trigger.click(); + const option = browser.$('//*[@role="option"][.//*[normalize-space()="Supervised"]]'); + await option.waitForDisplayed(); + await option.click(); + await form.$('[aria-label="Supervised"]').waitForExist({ timeout: 10_000 }); +} + +async function submitPrompt(text: string): Promise { + const editor = composerForm().$('[data-testid="composer-editor"]'); + await editor.waitForDisplayed({ timeout: 30_000 }); + await editor.click(); + await editor.addValue(text); + await browser.keys("Enter"); + await browser.waitUntil(async () => (await editor.getText()).trim() === "", { + timeoutMsg: "The composer kept the prompt after Enter.", + }); +} + +/** Waits for the probe file, reporting whether an approval card showed while waiting. */ +async function waitForCommand(maxMs: number): Promise<{ ran: boolean; cardSeen: boolean }> { + const deadline = Date.now() + maxMs; + let cardSeen = false; + while (Date.now() < deadline) { + cardSeen ||= await browser.$(SESSION_BUTTON).isExisting(); + if (NodeFS.existsSync(probeFile)) return { ran: true, cardSeen }; + await browser.pause(2_000); + } + return { ran: false, cardSeen }; +} + +/** Claude's question opens the question card, and the chosen answer reaches Claude. */ +async function questionStep(): Promise { + await submitPrompt( + "Use the AskUserQuestion tool to ask me whether I prefer red or blue, with exactly those two options. Then tell me in one short sentence which one I chose.", + ); + const option = composerForm().$('//button[.//*[normalize-space()="Blue"]]'); + await option.waitForDisplayed({ + timeout: 180_000, + timeoutMsg: "No question card with a Blue option opened.", + }); + await shot("question-card"); + note(`question card: ${(await composerForm().getText()).replaceAll(/\s+/g, " ").slice(0, 200)}`); + await option.click(); + await option.waitForExist({ reverse: true, timeout: 30_000 }); + // Claude read the answer when its reply names the chosen option. The prompt names both + // colors, so the check reads what follows the last "Worked for" row. + await browser.waitUntil( + async () => { + const text = await browser.$(surface).getText(); + return /blue/i.test(text.slice(text.lastIndexOf("Worked for"))); + }, + { timeout: 120_000, timeoutMsg: "Claude's reply did not name the chosen answer." }, + ); + note("the question card closed and Claude's reply names the chosen answer"); + await shot("question-answered"); +} + +/** The text of the working row ("Waiting for 3s"), or null when no turn shows as running. */ +async function workingRowText(): Promise { + return browser.execute((selector) => { + const dots = document.querySelector(`${selector} [data-working-indicator]`); + return dots?.parentElement?.textContent ?? null; + }, surface); +} + +/** + * A background task that ends inside a turn (#389): Claude answers its notification in that + * turn, so the thread must be idle afterwards, and the next turn's timer starts from zero. + */ +async function backgroundTaskStep(): Promise { + await submitPrompt( + "Use the Bash tool to run `sleep 8` with run_in_background set to true. Then use the Bash tool to run `sleep 20` in the foreground. Then reply with exactly: background step finished", + ); + const stop = () => composerForm().$('button[aria-label="Stop generation"]'); + const turnDeadline = Date.now() + 300_000; + let replied = false; + while (Date.now() < turnDeadline) { + const sessionButton = browser.$(SESSION_BUTTON); + if (await sessionButton.isExisting()) await sessionButton.click(); + const text = await browser.$(surface).getText(); + // The prompt holds the phrase too, so the reply is the second occurrence. + replied = text.split("background step finished").length > 2; + if (replied && !(await stop().isExisting())) break; + await browser.pause(3_000); + } + note(`background step replied: ${replied}`); + expect(replied).toBe(true); + // Nothing may claim a running turn while Claude is silent. + const quietDeadline = Date.now() + 60_000; + let phantom: string | null = null; + while (Date.now() < quietDeadline && phantom === null) { + if (await stop().isExisting()) phantom = "stop button"; + else phantom = await workingRowText(); + await browser.pause(3_000); + } + await shot("background-task-idle"); + note(`after the background task's turn, a running turn showed: ${phantom ?? "no"}`); + expect(phantom).toBeNull(); + // The next turn counts from its own start. + await submitPrompt("Reply with exactly: timer check"); + let firstTimer: string | null = null; + await browser.waitUntil( + async () => { + firstTimer = await workingRowText(); + return firstTimer !== null && /\d+s/.test(firstTimer); + }, + { timeout: 60_000, interval: 250, timeoutMsg: "The next turn showed no working row." }, + ); + note(`next turn's first timer text: ${firstTimer}`); + expect(firstTimer).not.toMatch(/\dm /); + await browser.waitUntil(async () => !(await stop().isExisting()), { timeout: 180_000 }); +} + +/** + * A background task that outlives its turn: it finishes while no turn runs and Claude answers it + * by itself, with no replay (Claude Code 2.1.326). The answer's text shows and ends, the thread + * is idle afterwards, and the next message runs normally. + */ +async function idleAnswerStep(): Promise { + const marker = "idle answer arrived"; + // As before the plan step: a prompt sent the moment the previous turn ends can stay in the + // composer. + await browser.pause(20_000); + await submitPrompt( + `Use the Bash tool to run \`sleep 25\` with run_in_background set to true. Do not wait for it: reply at once with exactly: background started. Later, when that background command finishes, reply with exactly: ${marker}`, + ); + const stop = () => composerForm().$('button[aria-label="Stop generation"]'); + // The prompt holds each phrase once, so a reply is a second occurrence. + const replies = async (phrase: string) => + (await browser.$(surface).getText()).split(phrase).length - 2; + const turnDeadline = Date.now() + 180_000; + let started = false; + while (Date.now() < turnDeadline) { + const sessionButton = browser.$(SESSION_BUTTON); + if (await sessionButton.isExisting()) await sessionButton.click(); + started = (await replies("background started")) > 0; + if (started && !(await stop().isExisting())) break; + await browser.pause(1_000); + } + const turnEndedAt = Date.now(); + // The answer must come after the turn, from the task finishing while no turn runs. + const answeredInTurn = (await replies(marker)) > 0; + note( + `idle answer step: the turn ended with its reply: ${started}; marker already answered: ${answeredInTurn}`, + ); + expect(started).toBe(true); + expect(answeredInTurn).toBe(false); + const answerDeadline = Date.now() + 180_000; + let answered = false; + while (Date.now() < answerDeadline && !answered) { + answered = (await replies(marker)) > 0; + if (!answered) await browser.pause(1_000); + } + note( + `idle answer step: Claude answered by itself: ${answered}, ${Math.round((Date.now() - turnEndedAt) / 1000)}s after the turn ended`, + ); + expect(answered).toBe(true); + await browser.pause(30_000); + const phantom = (await stop().isExisting()) ? "stop button" : await workingRowText(); + // A streaming reply has no copy button; the last reply of a turn gets one once its text ends. + const ended = (phrase: string) => + browser.execute( + (selector, text) => { + const rows = [ + ...document.querySelectorAll(`${selector} [data-message-role="assistant"]`), + ].filter((row) => row.textContent?.includes(text)); + return rows.at(-1)?.querySelector('button[aria-label="Copy link"]') != null; + }, + surface, + phrase, + ); + const answerEnded = await ended(marker); + // Control: the finished reply of the previous step's turn shows the same button. + const controlEnded = await ended("timer check"); + await shot("idle-answer"); + note( + `30s after the idle answer: running turn shown: ${phantom ?? "no"}; answer ended: ${answerEnded}; control reply ended: ${controlEnded}`, + ); + expect(phantom).toBeNull(); + expect(answerEnded).toBe(true); + await submitPrompt("Reply with exactly: after the idle answer"); + await browser.waitUntil( + async () => (await replies("after the idle answer")) > 0 && !(await stop().isExisting()), + { timeout: 180_000, interval: 1_000, timeoutMsg: "The next message did not run normally." }, + ); + note("idle answer step: the next message ran and its turn ended"); +} + +/** Plan review stays in BiBCode: the plan shows, no approval card opens, the turn ends. */ +async function planStep(): Promise { + await browser.pause(20_000); + const planToggle = composerForm().$('[aria-label="Enable plan mode"]'); + await planToggle.waitForDisplayed({ timeout: 30_000 }); + await planToggle.click(); + await composerForm().$('[aria-label="Disable plan mode"]').waitForExist({ timeout: 10_000 }); + await submitPrompt( + "Plan how to create a file named hello.txt with one line of text. Keep the plan to two steps and do not ask questions.", + ); + let cardSeen = false; + const deadline = Date.now() + 240_000; + let settled = false; + while (Date.now() < deadline) { + cardSeen ||= await browser.$(SESSION_BUTTON).isExisting(); + const text = await browser.$(surface).getText(); + const running = await composerForm().$('button[aria-label="Stop generation"]').isExisting(); + if (/hello\.txt/.test(text.slice(-1_500)) && !running && Date.now() > deadline - 200_000) { + settled = true; + break; + } + await browser.pause(5_000); + } + await shot("plan"); + note(`plan turn settled: ${settled}; approval card seen: ${cardSeen}`); + note( + `plan text tail: ${(await browser.$(surface).getText()).replaceAll(/\s+/g, " ").slice(-400)}`, + ); + expect(cardSeen).toBe(false); + expect(settled).toBe(true); + expect(NodeFS.existsSync(NodePath.join(realProject!, "hello.txt"))).toBe(false); +} + +describe("real Claude approvals (#383)", function () { + this.timeout(1_500_000); + + it("asks once, honors the session approval, shows a question and keeps plan review", async function () { + NodeFS.writeFileSync(evidencePath, ""); + NodeFS.rmSync(probeFile, { force: true }); + const settingsBefore = NodeFS.existsSync(settingsFile); + for (let attempt = 1; ; attempt += 1) { + try { + await importProject(); + break; + } catch (error) { + note(`import attempt ${attempt} failed: ${String(error).split("\n")[0]}`); + if (attempt >= 3) throw error; + await browser.pause(10_000); + } + } + await newClaudeChat(); + await chooseSupervised(); + await shot("supervised"); + + // No warm-up turn: the approval is given during the chat's first message. The second message + // names the default agent the first one left out, which must not restart the Claude process, + // because a session approval ends with its process. + // First command: Claude asks, and the card names the command. + await submitPrompt(PROMPT); + const sessionButton = browser.$(SESSION_BUTTON); + await sessionButton.waitForDisplayed({ + timeout: 180_000, + timeoutMsg: "No approval card opened for the first command.", + }); + const cardText = (await composerForm().getText()).replaceAll(/\s+/g, " "); + const placeholder = await composerForm() + .$('[data-testid="composer-editor"]') + .getAttribute("aria-placeholder"); + note(`card opened; composer text: ${cardText.slice(0, 300)}`); + note(`card detail: ${placeholder ?? "(none)"}`); + await shot("card-open"); + expect(NodeFS.existsSync(probeFile)).toBe(false); + await sessionButton.click(); + const first = await waitForCommand(120_000); + note(`first command ran after the session approval: ${first.ran}`); + expect(first.ran).toBe(true); + await sessionButton.waitForExist({ reverse: true, timeout: 30_000 }); + note("the card closed after the approval"); + await shot("after-approval"); + + // Let the turn finish, then repeat the same command: no card this time. + await browser.pause(30_000); + NodeFS.rmSync(probeFile, { force: true }); + await submitPrompt(PROMPT); + const second = await waitForCommand(180_000); + note(`second command ran: ${second.ran}; approval card seen: ${second.cardSeen}`); + await shot("second-command"); + expect(second.ran).toBe(true); + expect(second.cardSeen).toBe(false); + + const settingsAfter = NodeFS.existsSync(settingsFile); + note(`settings.local.json existed before: ${settingsBefore}; after: ${settingsAfter}`); + expect(settingsAfter).toBe(settingsBefore); + NodeFS.rmSync(probeFile, { force: true }); + + // The harness reloads the document between tests, so the question and the plan run here, + // in the same chat. + await browser.pause(20_000); + await questionStep(); + await backgroundTaskStep(); + await idleAnswerStep(); + await planStep(); + }); +}); diff --git a/apps/desktop/e2e/specs/manual/send-to-agent-real-providers.e2e.ts b/apps/desktop/e2e/specs/manual/send-to-agent-real-providers.e2e.ts index ba2b6220c0..5b3322fbb5 100644 --- a/apps/desktop/e2e/specs/manual/send-to-agent-real-providers.e2e.ts +++ b/apps/desktop/e2e/specs/manual/send-to-agent-real-providers.e2e.ts @@ -1,8 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off - Manual real-provider run writes an evidence file and screenshots. // @effect-diagnostics globalDate:off - Waits for real provider CLIs against wall-clock deadlines. +import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; +import { DESKTOP_UI_BUNDLE_IDENTIFIER } from "../../support/app-lifecycle.ts"; +import { captureStuckConnectionState } from "../../support/connection-state.ts"; import { ensureMainSidebarOpen, mockDesktopUiFolderPicker } from "../../support/ui-state.ts"; /** @@ -39,6 +42,31 @@ function note(line: string): void { NodeFS.appendFileSync(evidencePath, `${line}\n`); } +/** + * Submits what was typed into the focused terminal. Codex's input reads the packaged driver's + * Enter and Return as a new line, so macOS sends a trusted Return through System Events, which + * needs the process that runs the suite to be allowed to control System Events. The other + * platforms keep the driver's key. + */ +async function submitTerminalInput(): Promise { + if (process.env.BIBCODE_E2E_PLATFORM !== "mac") { + await browser.keys("Return"); + return; + } + NodeChildProcess.execFileSync("osascript", [ + "-e", + [ + 'tell application "System Events"', + ` tell (first application process whose bundle identifier is "${DESKTOP_UI_BUNDLE_IDENTIFIER}")`, + " set frontmost to true", + " end tell", + " delay 0.5", + " key code 36", + "end tell", + ].join("\n"), + ]); +} + async function shot(name: string): Promise { await browser.saveScreenshot(NodePath.join(artifactDirectory!, `real-${provider}-${name}.png`)); } @@ -63,7 +91,14 @@ async function importProject(): Promise { const loading = browser.$("//*[normalize-space()='Project data is still loading']"); await browser.pause(1_000); if (await loading.isExisting()) { - await loading.waitForDisplayed({ reverse: true, timeout: 60_000 }); + try { + await loading.waitForDisplayed({ reverse: true, timeout: 60_000 }); + } catch (error) { + // #381: keep what the client held, for the next diagnosis. + const state = await captureStuckConnectionState().catch((reason: unknown) => String(reason)); + note(`project data never loaded; client state: ${JSON.stringify(state)}`); + throw error; + } } const addProject = browser.$('[data-testid="sidebar-add-project-trigger"]'); await addProject.waitForDisplayed(); @@ -251,8 +286,7 @@ describe(`real ${provider}`, function () { // A fresh agent is not ready for a pointer before its first end-of-turn signal, so the person // gives it one tiny prompt first. await browser.$(`${visibleSurface} .xterm-helper-textarea`).addValue("Reply with the word ok."); - // Codex's input takes the driver's Enter as a new line; Return submits in every CLI. - await browser.keys("Return"); + await submitTerminalInput(); await browser.pause(provider === "claude" ? 60_000 : 45_000); await shot("first-turn"); note( diff --git a/apps/desktop/e2e/specs/mermaid-diagrams.e2e.ts b/apps/desktop/e2e/specs/mermaid-diagrams.e2e.ts index ed74647872..5b7105be94 100644 --- a/apps/desktop/e2e/specs/mermaid-diagrams.e2e.ts +++ b/apps/desktop/e2e/specs/mermaid-diagrams.e2e.ts @@ -15,6 +15,7 @@ import { startKeyboardSamples, type KeyboardSample } from "../support/timeline-k import { desktopUiFixture } from "../support/test-project.ts"; import { ensureMainSidebarOpen, + expectRightPanelBesideChat, mockDesktopUiFolderPicker, setDesktopUiWindowSize, } from "../support/ui-state.ts"; @@ -722,7 +723,9 @@ async function scrollTimelineToEnd(lastLine: string): Promise { describe("packaged Mermaid diagrams", () => { it("draws, refuses and sanitizes diagrams in the rendered Markdown view", async () => { prepareMermaidFixtureFiles(preparedProjectPath); - await setDesktopUiWindowSize(1_600, 1_000); + // The case needs only the Files panel beside the chat, and this size fits a laptop screen. + await setDesktopUiWindowSize(1_200, 720); + await expectRightPanelBesideChat(); await watchSecurityPolicyViolations(); await openFixtureWorkspace(); await openFilesSurface(); @@ -733,6 +736,19 @@ describe("packaged Mermaid diagrams", () => { expect.stringContaining("Fixture draw"), ); await saveEvidence("mermaid-file-valid"); + // The file view can draw the diagram again right after the first draw, so the svg seen above + // may be one whose nodes are not drawn yet. + await browser.waitUntil( + () => + browser.execute( + (viewQuery: string) => + !!document + .querySelector(`${viewQuery} .chat-markdown-mermaid svg`) + ?.querySelector(".pele-node rect, .pele-node polygon, .pele-node path"), + fileViewSelector, + ), + { timeout: 10_000, timeoutMsg: "The drawn fixture diagram never showed a node shape." }, + ); // A theme switch recolors the drawn diagram without drawing or replacing it. Timers, not // animation frames, wait for React: frames can stop in an occluded macOS webview. @@ -1388,6 +1404,32 @@ describe("packaged Mermaid diagrams", () => { ); await expectPaintingWebview(); await waitForRowsReplyUnmount({ width: 1_400, height: 900 }, "Fixture draw"); + // The remounted row would draw within a task of mounting, often before the line being read + // scrolls into view. Draws that miss the cache are held until that line is chosen, so every + // run sees the row's source with the line chosen, then the draw. + const held = await browser.execute(() => { + const page = window as Window & { + __bibcodeHoldMermaidDraws?: () => () => void; + __bibcodeReleaseMermaidDraws?: () => void; + }; + if (!page.__bibcodeHoldMermaidDraws) return false; + page.__bibcodeReleaseMermaidDraws = page.__bibcodeHoldMermaidDraws(); + return true; + }); + expect(held).toBe(true); + try { + await holdLineThenDrawCold(); + } finally { + await browser.execute(() => + ( + window as Window & { __bibcodeReleaseMermaidDraws?: () => void } + ).__bibcodeReleaseMermaidDraws?.(), + ); + } + }).timeout(900_000); + + /** The cold-draw case from the held draw on: scroll to the line, release, check the line. */ + async function holdLineThenDrawCold(): Promise { // The step-by-step scroll up takes over a minute on a slow runner (Linux arm64), so the // samples run until the row has drawn rather than stopping at the usual minute. await startReadingLineSamples( @@ -1403,10 +1445,26 @@ describe("packaged Mermaid diagrams", () => { const reachedBlock = [ ...document.querySelectorAll(`${surface} .chat-markdown-codeblock`), ].some((element) => element.textContent?.includes(diagramLabel)); - if (reachedBlock) return true; const scroller = document.querySelector( `${surface} [class*='overflow-anchor']`, ); + // The list can mount the rows reply well above the view, before the reply below it, + // whose paragraph is the line being read, is in view; scrolling on brings that line + // in. The test is the sampler's own choice of line. + const viewport = scroller?.parentElement?.getBoundingClientRect(); + const lineInView = + !!viewport && + [...document.querySelectorAll(`${surface} .chat-markdown p`)].some( + (element) => { + const box = element.getBoundingClientRect(); + return ( + element.textContent?.startsWith("Following reply paragraph ") && + box.top >= viewport.top + 16 && + box.bottom <= viewport.bottom - 16 + ); + }, + ); + if (reachedBlock && lineInView) return true; if (scroller) scroller.scrollTop -= 300; return false; }, @@ -1416,6 +1474,15 @@ describe("packaged Mermaid diagrams", () => { if (reached) break; await browser.pause(250); } + await browser.waitUntil( + async () => (await readReadingLineSamples()).painted.some((entry) => entry.target !== null), + { timeoutMsg: "The sampler never chose a reading line while the draw was held." }, + ); + await browser.execute(() => + ( + window as Window & { __bibcodeReleaseMermaidDraws?: () => void } + ).__bibcodeReleaseMermaidDraws?.(), + ); await browser.pause(1_500); const coldDraw = await readReadingLineSamples(); await browser.execute(() => @@ -1444,10 +1511,11 @@ describe("packaged Mermaid diagrams", () => { const drew = coldDraw.painted.findIndex( (entry, index) => index >= appeared && entry.diagramDrawn, ); - // A row remounted in the buffer can draw from the cache before its first painted frame, so - // the check needs the diagram drawn by the end, not a frame of its source first. + // With the draw held, a painted frame shows the row's source and the chosen line before + // the diagram draws. expect(appeared).toBeGreaterThanOrEqual(0); - expect(drew).toBeGreaterThanOrEqual(appeared); + expect(coldDraw.painted[appeared]!.diagramDrawn).toBe(false); + expect(drew).toBeGreaterThan(appeared); const readingLine = coldDraw.painted[appeared]!.target!; // The diagram's row ends where the read row begins. A display scaled 200% lays the two out // a fraction of a pixel apart, so the row counts as above within the same 1 px as below. @@ -1463,7 +1531,7 @@ describe("packaged Mermaid diagrams", () => { ), ).toBe(true); await saveEvidence("mermaid-timeline-cold-draw"); - }).timeout(900_000); + } it("follows the end while a streamed reply's diagram draws", async () => { await setDesktopUiWindowSize(1_400, 900); @@ -1743,7 +1811,16 @@ describe("packaged Mermaid diagrams", () => { ); if (above) { above.dataset.bibcodeKeyboardGrown = "true"; - above.style.paddingTop = "160px"; + // A style rule, not an inline style: the list can unmount the row before the key and + // mount it again, and the growth must come back with it as a real row's would. + const row = above.closest("[data-message-id]")?.dataset.messageId; + const nth = [...above.parentElement!.children] + .filter((element) => element.tagName === "P") + .indexOf(above); + const grown = document.createElement("style"); + grown.dataset.bibcodeKeyboardGrown = "true"; + grown.textContent = `[data-message-id="${CSS.escape(row ?? "")}"] p:nth-of-type(${nth + 1}) { padding-top: 160px; }`; + document.head.append(grown); } frames(2, () => { const button = [ @@ -1995,8 +2072,8 @@ describe("packaged Mermaid diagrams", () => { for (const element of document.querySelectorAll( "[data-bibcode-keyboard-grown]", )) { - element.style.paddingTop = ""; - element.removeAttribute("data-bibcode-keyboard-grown"); + if (element instanceof HTMLStyleElement) element.remove(); + else element.removeAttribute("data-bibcode-keyboard-grown"); } }); const endAt = (await readKeyboardSamples()).samples.at(-1)!.at; @@ -2375,7 +2452,16 @@ async function pressNativePageUpDuringGlide( ); if (above) { above.dataset.bibcodeKeyboardGrown = "true"; - above.style.paddingTop = "160px"; + // A style rule, not an inline style: the list can unmount the row before the key and + // mount it again, and the growth must come back with it as a real row's would. + const row = above.closest("[data-message-id]")?.dataset.messageId; + const nth = [...above.parentElement!.children] + .filter((element) => element.tagName === "P") + .indexOf(above); + const grown = document.createElement("style"); + grown.dataset.bibcodeKeyboardGrown = "true"; + grown.textContent = `[data-message-id="${CSS.escape(row ?? "")}"] p:nth-of-type(${nth + 1}) { padding-top: 160px; }`; + document.head.append(grown); } requestAnimationFrame(() => requestAnimationFrame(() => { diff --git a/apps/desktop/e2e/specs/project-session-terminal.e2e.ts b/apps/desktop/e2e/specs/project-session-terminal.e2e.ts index 9657d406c8..9997de3fd7 100644 --- a/apps/desktop/e2e/specs/project-session-terminal.e2e.ts +++ b/apps/desktop/e2e/specs/project-session-terminal.e2e.ts @@ -63,7 +63,7 @@ describe("packaged project session and terminal", () => { const providerModelPicker = browser.$('[data-chat-provider-model-picker="true"]'); await expect(providerModelPicker).toBeEnabled(); - await expect(providerModelPicker).toHaveText(expect.stringContaining("GPT-5.4")); + await expect(providerModelPicker).toHaveText(expect.stringContaining("Codex default")); const composer = browser.$('[data-testid="composer-editor"]'); await expect(composer).toBeDisplayed(); diff --git a/apps/desktop/e2e/specs/send-to-agent.e2e.ts b/apps/desktop/e2e/specs/send-to-agent.e2e.ts index 5b9f2d2284..c2a8dce4f7 100644 --- a/apps/desktop/e2e/specs/send-to-agent.e2e.ts +++ b/apps/desktop/e2e/specs/send-to-agent.e2e.ts @@ -400,6 +400,21 @@ describe("packaged send to agent", () => { await openFixtureCodexTerminal(); terminalTabId = await selectedTabId(); + // The terminal's control is easy to find: at least 28 px square and painted in the primary color. + const control = await browser.$(sendControlSelector); + const size = await control.getSize(); + expect(size.width).toBeGreaterThanOrEqual(28); + expect(size.height).toBeGreaterThanOrEqual(28); + const colors = await browser.execute((element: HTMLElement) => { + const probe = document.createElement("span"); + probe.style.backgroundColor = "var(--primary)"; + document.body.append(probe); + const primary = getComputedStyle(probe).backgroundColor; + probe.remove(); + return { control: getComputedStyle(element).backgroundColor, primary }; + }, control); + expect(colors.control).toBe(colors.primary); + await chooseSendTarget("Message", codexPanelTitle); await sendFromPreview(terminalNote); const requests = browser.$(`${visibleSurfaceSelector} button[aria-label^="Send requests"]`); diff --git a/apps/desktop/e2e/specs/server-commands.e2e.ts b/apps/desktop/e2e/specs/server-commands.e2e.ts new file mode 100644 index 0000000000..a4491c7026 --- /dev/null +++ b/apps/desktop/e2e/specs/server-commands.e2e.ts @@ -0,0 +1,252 @@ +// @effect-diagnostics nodeBuiltinImport:off - The spec reads what the server shell wrote. +// Issue 378: Open terminal and Dashboard for a server, from the rail menu and the Repositories +// card. The packaged suite has only this device and no second, remote environment, and the +// Environments view's server card is hidden for this device, so that card's buttons are +// covered by EnvironmentContextCard.test.tsx and the shared command's history by +// serverCommands.history.test.tsx. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { desktopUiPlatform } from "../support/app-lifecycle.ts"; +import { refreshDesktopUiDocument } from "../support/document-navigation.ts"; +import { installDesktopUiMotionGuard } from "../support/motion-guard.ts"; +import { desktopUiFixture } from "../support/test-project.ts"; +import { sendTerminalCommand } from "../support/terminal-input.ts"; +import { ensureMainSidebarOpen, mockDesktopUiFolderPicker } from "../support/ui-state.ts"; + +const stateRoot = process.env.BIBCODE_HOME; +if (!stateRoot) throw new Error("BIBCODE_HOME is required."); +const projectPath = process.env.BIBCODE_E2E_PROJECT_PATH; +if (!projectPath) throw new Error("BIBCODE_E2E_PROJECT_PATH is required."); + +const dashboardPanel = '[data-testid="host-dashboard-panel"]'; +const terminalPanel = '[data-testid="server-terminal-panel"]'; +const markerPath = (name: string) => NodePath.join(stateRoot, `server-terminal-${name}.txt`); +// The default shell is PowerShell on Windows and a POSIX shell elsewhere. +const windows = desktopUiPlatform() === "win"; +const recordFoldersCommand = windows + ? // The server's `~` follows USERPROFILE, which the harness points at the fixture home; the + // shell inherits it from the server. + `(Get-Location).ProviderPath | Set-Content '${markerPath("pwd")}'; $env:USERPROFILE | Set-Content '${markerPath("home")}'; $env:BIBCODE_E2E_SERVER_SESSION = 'kept'` + : `pwd -P > '${markerPath("pwd")}'; (cd ~ && pwd -P) > '${markerPath("home")}'; export BIBCODE_E2E_SERVER_SESSION=kept`; +const recordSessionCommand = windows + ? `$env:BIBCODE_E2E_SERVER_SESSION | Set-Content '${markerPath("session")}'` + : `echo "$BIBCODE_E2E_SERVER_SESSION" > '${markerPath("session")}'`; + +const localRailIcon = '[data-testid="environment-rail-local"]'; +const MENU_LABELS = { terminal: "Open terminal", dashboard: "Dashboard" } as const; + +/** + * The native context menu cannot be driven by WebDriver: the next one records the items it + * was given and answers `choice`. Windows has no native menu (WebView2 renders it in the DOM). + */ +async function answerNextContextMenu(choice: "terminal" | "dashboard"): Promise { + const menu = await browser.tauri.mock("desktop_bridge_show_context_menu"); + await menu.mockReturnValue(choice); + const installed = await browser.execute((answer: string) => { + const host = window as Window & { + __wdio_mocks__?: Record; + __serverCommandMenuItems?: unknown; + }; + const mocks = (host.__wdio_mocks__ ??= {}); + mocks.desktop_bridge_show_context_menu = async (args: { items?: unknown }) => { + host.__serverCommandMenuItems = args?.items; + return answer; + }; + return typeof mocks.desktop_bridge_show_context_menu === "function"; + }, choice); + if (!installed) throw new Error("The context-menu mock could not be installed in the page."); +} + +async function recordedMenuLabels(): Promise { + return browser.execute(() => { + const items = (window as Window & { __serverCommandMenuItems?: unknown }) + .__serverCommandMenuItems; + return Array.isArray(items) ? items.map((item: { label?: string }) => item.label ?? "") : []; + }); +} + +async function showView(label: "Environments view" | "Repositories view"): Promise { + const toggle = browser.$(`button[aria-label="${label}"]`); + await toggle.waitForDisplayed(); + await toggle.click(); +} + +/** Picks `choice` from the Local icon's menu and returns the menu's labels, in order. */ +async function openFromLocalRail(choice: "terminal" | "dashboard"): Promise { + await showView("Environments view"); + if (!windows) await answerNextContextMenu(choice); + const local = browser.$(localRailIcon); + await local.waitForDisplayed(); + // The packaged drivers' right click dispatches untrusted mousedown and mouseup only, and a + // page gets no contextmenu event from untrusted input, so the spec sends the one a real + // right click ends with. + await browser.execute((selector: string) => { + const element = document.querySelector(selector)!; + const box = element.getBoundingClientRect(); + element.dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + button: 2, + clientX: box.left + box.width / 2, + clientY: box.top + box.height / 2, + }), + ); + }, localRailIcon); + if (!windows) { + await browser.waitUntil(async () => (await recordedMenuLabels()).length > 0, { + timeoutMsg: "The rail icon did not open its menu.", + }); + return recordedMenuLabels(); + } + const item = browser.$( + `//*[@role="menu"]//*[@role="menuitem"][.//span[normalize-space()="${MENU_LABELS[choice]}"]]`, + ); + await item.waitForDisplayed(); + const labels: string[] = []; + for (const row of await browser.$$('//*[@role="menu"]//*[@role="menuitem"]')) { + labels.push((await row.getText()).trim()); + } + await item.click(); + return labels; +} + +async function ensureFixtureProject(): Promise { + const project = browser.$( + `//button[.//span[normalize-space()="${desktopUiFixture.projectName}"]]`, + ); + if (await project.isDisplayed()) return; + 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(projectPath!); + await browseFolder.click(); + await expect(project).toBeDisplayed(); +} + +async function waitForCpuFigure(): Promise { + const cpu = browser.$(`${dashboardPanel} [data-testid="host-dashboard-cpu"]`); + await browser.waitUntil(async () => /^\d+(\.\d)?%$/.test((await cpu.getText()).trim()), { + timeoutMsg: "The center dashboard never showed a CPU percentage.", + }); +} + +/** Open terminal focuses the shell itself; the click after the check only keeps it there. */ +async function focusTerminal(): Promise { + const screen = browser.$(`${terminalPanel} .xterm-screen`); + await expect(screen).toBeDisplayed(); + await browser.waitUntil( + () => + browser.execute( + (panel: string) => + document.activeElement?.closest(panel) !== null && + document.activeElement?.classList.contains("xterm-helper-textarea") === true, + terminalPanel, + ), + { timeoutMsg: "Open terminal did not focus the terminal." }, + ); + await screen.click(); +} + +async function terminalRoute(): Promise { + return /^#\/environment\/[^/]+\/terminal/.test(await browser.execute(() => window.location.hash)); +} + +/** + * The server canonicalises the folder it opens, while USERPROFILE may name a temporary folder in + * 8.3 short form and Windows paths ignore case: compare the long path the file system reports. + */ +function canonicalFolder(path: string): string { + const long = NodeFS.realpathSync.native(path); + return windows ? long.toLowerCase() : long; +} + +async function waitForMarker(name: string): Promise { + const path = markerPath(name); + await browser.waitUntil( + () => NodeFS.existsSync(path) && NodeFS.readFileSync(path, "utf8").trim().length > 0, + { timeout: 10_000, timeoutMsg: `The server shell did not write ${name}.` }, + ); + return NodeFS.readFileSync(path, "utf8").trim(); +} + +describe("packaged server commands", () => { + it("opens the dashboard and the home-folder terminal from the rail and the card", async () => { + for (const name of ["pwd", "home", "session"]) NodeFS.rmSync(markerPath(name), { force: true }); + await ensureMainSidebarOpen(); + + // Rail menu: both commands, in order, then Dashboard for this device. + const labels = await openFromLocalRail("dashboard"); + await browser.$(dashboardPanel).waitForDisplayed(); + expect(labels).toEqual(["Open terminal", "Dashboard"]); + expect(await browser.$(`${dashboardPanel} h1`).getText()).toBe("Local"); + await waitForCpuFigure(); + + // A reload restores the panel from its URL, after this device registers again. + await refreshDesktopUiDocument(); + await installDesktopUiMotionGuard(); + await browser.$(dashboardPanel).waitForDisplayed(); + expect(await browser.execute(() => window.location.hash)).toMatch( + /^#\/environment\/[^/]+\/dashboard/, + ); + await waitForCpuFigure(); + + // Rail menu: Open terminal starts a shell in the server user's home folder. + await ensureMainSidebarOpen(); + await openFromLocalRail("terminal"); + await browser.$(terminalPanel).waitForDisplayed(); + await focusTerminal(); + await sendTerminalCommand(recordFoldersCommand); + expect(canonicalFolder(await waitForMarker("pwd"))).toBe( + canonicalFolder(await waitForMarker("home")), + ); + + // Repositories card: the same commands, and Open terminal reuses the running session. + await showView("Repositories view"); + await ensureFixtureProject(); + const cardDashboard = browser.$('button[aria-label="Dashboard for Local"]'); + await cardDashboard.waitForDisplayed(); + await cardDashboard.click(); + await browser.$(dashboardPanel).waitForDisplayed(); + await waitForCpuFigure(); + + const cardTerminal = browser.$('button[aria-label="Open terminal on Local"]'); + await cardTerminal.waitForDisplayed(); + await cardTerminal.click(); + await browser.$(terminalPanel).waitForDisplayed(); + await focusTerminal(); + await sendTerminalCommand(recordSessionCommand); + expect(await waitForMarker("session")).toBe("kept"); + + // A reload restores the terminal panel and its session. + await refreshDesktopUiDocument(); + await installDesktopUiMotionGuard(); + await browser.$(terminalPanel).waitForDisplayed(); + NodeFS.rmSync(markerPath("session"), { force: true }); + await focusTerminal(); + await sendTerminalCommand(recordSessionCommand); + expect(await waitForMarker("session")).toBe("kept"); + + // Open terminal on the terminal shown refocuses it in place: when the shell exits, the + // panel goes Back to the view before it (the card's Local dashboard), not into another + // copy of the terminal that would open it again. + await ensureMainSidebarOpen(); + await showView("Repositories view"); + await cardTerminal.waitForDisplayed(); + await cardTerminal.click(); + await focusTerminal(); + await sendTerminalCommand("exit"); + await browser.$(dashboardPanel).waitForDisplayed({ + timeoutMsg: "The exited terminal did not go back to the Local dashboard.", + }); + expect(await browser.$(`${dashboardPanel} h1`).getText()).toBe("Local"); + await browser.pause(1_000); + expect(await terminalRoute()).toBe(false); + await expect(browser.$(dashboardPanel)).toBeDisplayed(); + }); +}); diff --git a/apps/desktop/e2e/specs/source-control-review.e2e.ts b/apps/desktop/e2e/specs/source-control-review.e2e.ts index 7b84ea4f99..d412909fd2 100644 --- a/apps/desktop/e2e/specs/source-control-review.e2e.ts +++ b/apps/desktop/e2e/specs/source-control-review.e2e.ts @@ -248,6 +248,33 @@ describe("packaged Source Control review", () => { modifyTrackedFile(); await openSourceControl(); + // #375: at a narrow window the button keeps its whole "Review" label and is as tall as + // Stage All. + await setDesktopUiWindowSize(960, 900); + const reviewLayout = await browser.execute(() => { + const review = document.querySelector('button[aria-label="Review changes"]'); + const stageAll = [...document.querySelectorAll("button")].find((button) => + button.textContent?.startsWith("Stage All Changes"), + ); + const header = review?.parentElement; + if (!review || !stageAll || !header) return null; + const bounds = review.getBoundingClientRect(); + return { + text: review.textContent?.trim(), + clipped: review.scrollWidth > review.clientWidth, + insideHeader: + bounds.right <= header.getBoundingClientRect().right && bounds.right <= window.innerWidth, + height: bounds.height, + stageAllHeight: stageAll.getBoundingClientRect().height, + }; + }); + expect(reviewLayout).toMatchObject({ text: "Review", clipped: false, insideHeader: true }); + expect(reviewLayout!.height).toBeGreaterThanOrEqual(reviewLayout!.stageAllHeight); + await browser.saveScreenshot( + NodePath.join(preparedArtifactDirectory, "review-button-narrow.png"), + ); + await setDesktopUiWindowSize(1_280, 900); + const baseline = readProviderInputLog(preparedProviderInputLogPath).length; // The saved reviewer is the default, chat Codex. await browser.$('button[aria-label="Review changes"]').click(); @@ -256,9 +283,32 @@ describe("packaged Source Control review", () => { const prompt = await waitForReviewStart("codex", baseline); expect(prompt).toContain(UNCOMMITTED_SCOPE); - // The review starts supervised (approval required), the Codex read-only sandbox. + // Codex runs the review in its own read-only sandbox, so the composer shows a disabled lock + // with the reason instead of a mode picker (#376). await waitForComposerDisplayed(); - await expect(composerForm().$('[aria-label="Supervised"]')).toExist(); + const reviewLock = composerForm().$('button[aria-label="Read-only review"]'); + await expect(reviewLock).toBeDisplayed(); + await expect(reviewLock).toHaveAttribute("aria-disabled", "true"); + await expect(composerForm().$('[aria-label="Supervised"]')).not.toExist(); + // The embedded driver's pointer move does not reach the page, so the hover the tooltip + // opens on is dispatched to the lock itself. + await browser.execute((form: string) => { + const lock = document.querySelector(`${form} button[aria-label="Read-only review"]`); + if (!lock) throw new Error("The read-only review lock is missing."); + const init = { bubbles: true, pointerType: "mouse" }; + lock.dispatchEvent(new PointerEvent("pointerover", init)); + lock.dispatchEvent(new PointerEvent("pointerenter", { ...init, bubbles: false })); + lock.dispatchEvent(new MouseEvent("mouseover", { bubbles: true })); + lock.dispatchEvent(new MouseEvent("mouseenter")); + lock.dispatchEvent(new PointerEvent("pointermove", init)); + lock.dispatchEvent(new MouseEvent("mousemove", { bubbles: true })); + }, visibleComposerFormSelector); + // Another trigger's tooltip can still be in the page, so the lock's is found by its text. + await expect( + browser.$( + '//*[@data-slot="tooltip-popup" and normalize-space()="Codex runs reviews on their own in its read-only sandbox, so the mode does not apply."]', + ), + ).toBeDisplayed(); await browser.saveScreenshot( NodePath.join(preparedArtifactDirectory, "review-codex-panel.png"), ); diff --git a/apps/desktop/e2e/support/activity-session.ts b/apps/desktop/e2e/support/activity-session.ts index e383ab3a1e..e7eeb9b8a4 100644 --- a/apps/desktop/e2e/support/activity-session.ts +++ b/apps/desktop/e2e/support/activity-session.ts @@ -22,6 +22,11 @@ interface DesktopActivityBridge { }>; } +interface DesktopActivityDispatchResult extends DesktopActivitySessionMaterialization { + /** What each setup request answered, in order. */ + readonly setupResults: ReadonlyArray>; +} + interface DesktopActivityRpcRequest { readonly payload: Record; readonly tag: string; @@ -31,7 +36,7 @@ async function dispatchDesktopActivityCommands( commands: ReadonlyArray>, requestedProjectId: string | null, setupRequests: ReadonlyArray = [], -): Promise { +): Promise { return browser.execute( async (input: { readonly commands: ReadonlyArray>; @@ -250,8 +255,9 @@ async function dispatchDesktopActivityCommands( ); }); + const setupResults: Record[] = []; for (const setupRequest of input.setupRequests) { - await request(setupRequest.tag, setupRequest.payload); + setupResults.push(await request(setupRequest.tag, setupRequest.payload)); } let resolvedProjectId = input.requestedProjectId; @@ -266,7 +272,7 @@ async function dispatchDesktopActivityCommands( } } if (!input.commands.some((command) => command.type === "thread.create")) { - return { projectId: "", providerInstanceId: "", threadId: "" }; + return { projectId: "", providerInstanceId: "", threadId: "", setupResults }; } const envelope = await request( "orchestration.subscribeThread", @@ -302,6 +308,7 @@ async function dispatchDesktopActivityCommands( projectId: snapshot.projectId, providerInstanceId: session.providerInstanceId, threadId: snapshot.id, + setupResults, }; } finally { disposeSocketListeners(); @@ -324,10 +331,65 @@ async function dispatchDesktopActivityCommands( export async function materializeDesktopActivitySession( projectPath: string, ): Promise { - return dispatchDesktopActivityCommands( + // The setup replies stay with the inventory helper; this returns the three identifiers. + const { projectId, providerInstanceId, threadId } = await dispatchDesktopActivityCommands( desktopActivitySessionCommands(projectPath), desktopActivityFixture.project.id, ); + return { projectId, providerInstanceId, threadId }; +} + +/** The fixture Codex snapshot's sign-in type and models, from what the server published. */ +function codexInventory(config: Record): { + readonly authType: string | null; + readonly models: ReadonlyArray; +} { + const providers = Array.isArray(config.providers) ? config.providers : []; + const codex = providers.find( + (provider): provider is Record => + provider !== null && + typeof provider === "object" && + (provider as Record).instanceId === "codex", + ); + const auth = codex?.auth as Record | undefined; + const models = Array.isArray(codex?.models) ? codex.models : []; + return { + authType: typeof auth?.type === "string" ? auth.type : null, + models: models.flatMap((model) => + model !== null && typeof model === "object" && typeof model.slug === "string" + ? [model.slug] + : [], + ), + }; +} + +/** + * Waits until the server has published the fixture Codex's ChatGPT sign-in and model list. A + * launch before that cannot know the stored model is retired under that sign-in, so it starts + * with the model, and the composer's later send of Codex's default restarts the session, ending + * the fixture's activity. Returns what the first read showed, for the run's evidence. + */ +export async function waitForDesktopActivityCodexInventory(): Promise<{ + readonly firstAuthType: string | null; + readonly refreshes: number; +}> { + const read = async (tag: string, payload: Record) => + codexInventory( + (await dispatchDesktopActivityCommands([], null, [{ tag, payload }])).setupResults[0] ?? {}, + ); + const first = await read("server.getConfig", {}); + let current = first; + let refreshes = 0; + while (current.authType !== "chatgpt" || current.models.length === 0) { + if (refreshes >= 5) { + throw new Error( + `The fixture Codex inventory never published its sign-in: ${JSON.stringify(current)}`, + ); + } + refreshes += 1; + current = await read("server.refreshProviders", { instanceId: "codex" }); + } + return { firstAuthType: first.authType, refreshes }; } export async function startDesktopActivityFollowupTurn(): Promise { diff --git a/apps/desktop/e2e/support/app-lifecycle.test.ts b/apps/desktop/e2e/support/app-lifecycle.test.ts index 1e4f5726cc..5901528aff 100644 --- a/apps/desktop/e2e/support/app-lifecycle.test.ts +++ b/apps/desktop/e2e/support/app-lifecycle.test.ts @@ -12,6 +12,7 @@ import { type RecoveryDeadline, dispatchDesktopUiApplicationExit, isDeadDesktopUiWebviewError, + isEndedApplicationSessionDelete, isFinalDesktopUiSpec, prepareRelaunchedDesktopUiSession, recoverDeadDesktopUiWebview, @@ -88,6 +89,26 @@ describe("isDeadDesktopUiWebviewError", () => { }); }); +describe("isEndedApplicationSessionDelete", () => { + const refused = new Error( + 'WebDriverError: Request failed with error code ECONNREFUSED when running "http://127.0.0.1:4445/session/s" with method "DELETE"', + ); + + it("accepts a refused DELETE once the app no longer runs", async () => { + expect(await isEndedApplicationSessionDelete(refused, async () => false)).toBe(true); + }); + + it("keeps a refused DELETE while the app still runs a failure", async () => { + expect(await isEndedApplicationSessionDelete(refused, async () => true)).toBe(false); + }); + + it("keeps any other DELETE error a failure", async () => { + expect( + await isEndedApplicationSessionDelete(new Error("unknown error: boom"), async () => false), + ).toBe(false); + }); +}); + describe("recoverDeadDesktopUiWebview", () => { const deps = (probe: () => Promise, running: boolean) => ({ probe: vi.fn(probe), diff --git a/apps/desktop/e2e/support/app-lifecycle.ts b/apps/desktop/e2e/support/app-lifecycle.ts index 27e8d7c317..b415d245f9 100644 --- a/apps/desktop/e2e/support/app-lifecycle.ts +++ b/apps/desktop/e2e/support/app-lifecycle.ts @@ -434,6 +434,40 @@ export async function prepareRelaunchedDesktopUiSession( await withinRecoveryDeadline(deadline, "plugin wait", steps.waitForPlugin); } +/** + * Whether the runner's closing DELETE failed only because teardown already ended the app on + * purpose: a dead-session error while no embedded driver answers any more. + */ +export async function isEndedApplicationSessionDelete( + error: unknown, + isRunning: () => Promise = isDesktopUiApplicationRunning, +): Promise { + return isDeadDesktopUiWebviewError(error) && !(await isRunning()); +} + +/** + * After teardown ends the app, the runner still deletes the session and the refused request + * fails the worker. Only that one DELETE, in that one worker, is accepted as a clean end. + */ +export function acceptEndedApplicationSessionDelete(): void { + // WebdriverIO overwrites protocol commands too, but its types list only browser commands. + const overwrite = browser.overwriteCommand as unknown as ( + name: "deleteSession", + command: ( + original: (...args: unknown[]) => Promise, + ...args: unknown[] + ) => Promise, + ) => void; + overwrite.call(browser, "deleteSession", async (deleteSession, ...args) => { + try { + return await deleteSession(...args); + } catch (error) { + if (await isEndedApplicationSessionDelete(error)) return undefined; + throw error; + } + }); +} + /** Ends an app this helper relaunched, if it still runs: only a process this helper started. */ export async function stopRelaunchedDesktopUiApplication(): Promise { const child = relaunched; diff --git a/apps/desktop/e2e/support/connection-state.ts b/apps/desktop/e2e/support/connection-state.ts new file mode 100644 index 0000000000..4310317b0b --- /dev/null +++ b/apps/desktop/e2e/support/connection-state.ts @@ -0,0 +1,58 @@ +// @effect-diagnostics globalTimers:off - The timer runs inside the page under test, not in an Effect. +/** + * What the web client holds when the app stays at "Project data is still loading" (#381): the + * sidebar text, the requests it made that are not scripts or styles, and the connection + * catalog in IndexedDB. A spec writes it to its evidence when the project never loads, so an + * intermittent hang leaves a record instead of only a timeout. + */ +export async function captureStuckConnectionState(): Promise { + return browser.executeAsync((done: (value: unknown) => void) => { + const result: Record = { + sidebar: document.body.innerText.replaceAll(/\s+/g, " ").slice(0, 300), + resources: performance + .getEntriesByType("resource") + .map((entry) => { + const resource = entry as PerformanceResourceTiming; + return `${resource.name.replace(/\?.*/, "")} start=${Math.round(resource.startTime)} end=${Math.round(resource.responseEnd)} status=${(resource as unknown as { responseStatus?: number }).responseStatus ?? "?"}`; + }) + .filter((line) => !/\.(js|css|woff2?|png|svg)\b/.test(line)), + now: Math.round(performance.now()), + }; + const timer = setTimeout(() => { + result.indexedDb = "open did not settle in 8 s"; + done(result); + }, 8_000); + const request = indexedDB.open("bibcode:connection-runtime"); + request.addEventListener("blocked", () => (result.indexedDbBlocked = true)); + request.addEventListener("error", () => { + clearTimeout(timer); + result.indexedDb = `error ${String(request.error)}`; + done(result); + }); + request.addEventListener("success", () => { + const database = request.result; + const stores = [...database.objectStoreNames]; + result.indexedDb = `version ${database.version} stores ${stores.join(",")}`; + if (stores.length === 0) { + clearTimeout(timer); + database.close(); + done(result); + return; + } + const transaction = database.transaction(stores, "readonly"); + const counts: string[] = []; + for (const store of stores) { + const keys = transaction.objectStore(store).getAllKeys(); + keys.addEventListener("success", () => + counts.push(`${store}: ${keys.result.map(String).join("|").slice(0, 200)}`), + ); + } + transaction.addEventListener("complete", () => { + clearTimeout(timer); + result.indexedDbKeys = counts; + database.close(); + done(result); + }); + }); + }); +} diff --git a/apps/desktop/e2e/support/tauri-service-compat.test.ts b/apps/desktop/e2e/support/tauri-service-compat.test.ts index 8957f2b77d..2968713ab5 100644 --- a/apps/desktop/e2e/support/tauri-service-compat.test.ts +++ b/apps/desktop/e2e/support/tauri-service-compat.test.ts @@ -66,6 +66,14 @@ describe("@wdio/tauri-service compatibility", () => { "[desktopUiSpecFiles.filter((spec) => spec !== closingSpec), closingSpec]", ); expect(wdioConfig).toContain("connectionRetryCount: 0"); + // Only the final spec's teardown, after it ends the app, accepts the runner's refused DELETE. + expect(wdioConfig).toContain( + "await stopRelaunchedDesktopUiApplication();\n acceptEndedApplicationSessionDelete();", + ); + expect(wdioConfig.match(/acceptEndedApplicationSessionDelete\(\)/g)).toHaveLength(1); + expect(wdioConfig.indexOf("isFinalDesktopUiSpec(currentSpecs")).toBeLessThan( + wdioConfig.indexOf("acceptEndedApplicationSessionDelete();"), + ); expect(wdioConfig).toContain("commandTimeout: 60_000"); expect(wdioConfig).toContain("beforeTest: async () =>"); expect(wdioConfig).toContain("await refreshDesktopUiDocument()"); diff --git a/apps/desktop/e2e/support/ui-state.ts b/apps/desktop/e2e/support/ui-state.ts index 8a8b1f9a8e..fc0b96d00a 100644 --- a/apps/desktop/e2e/support/ui-state.ts +++ b/apps/desktop/e2e/support/ui-state.ts @@ -1,3 +1,4 @@ +import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../../../web/src/rightPanelLayout.ts"; import { correctDesktopUiOuterSize } from "./window-size.ts"; /** @@ -66,6 +67,15 @@ export async function setDesktopUiWindowSize(width: number, height: number): Pro ); } +/** Fails unless the window is wide enough for the right panel to sit beside the chat. */ +export async function expectRightPanelBesideChat(): Promise { + const sheet = await browser.execute( + (query: string) => window.matchMedia(query).matches, + RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY, + ); + expect(sheet).toBe(false); +} + export async function ensureMainSidebarOpen(): Promise { await setDesktopUiWindowSize(1_000, 720); const wrapper = browser.$('[data-slot="sidebar-wrapper"]'); diff --git a/apps/desktop/e2e/wdio.conf.ts b/apps/desktop/e2e/wdio.conf.ts index fc35f06d5c..c1ecda2ab5 100644 --- a/apps/desktop/e2e/wdio.conf.ts +++ b/apps/desktop/e2e/wdio.conf.ts @@ -9,6 +9,7 @@ import { refreshDesktopUiDocument } from "./support/document-navigation.ts"; import { resolveDesktopAppPath, type DesktopUiPlatform } from "./support/app-path.ts"; import { + acceptEndedApplicationSessionDelete, DESKTOP_UI_TEST_TIMEOUT_MS, ensureLiveDesktopUiWebview, isDesktopUiApplicationRunning, @@ -71,6 +72,7 @@ const desktopUiSpecFiles = "./specs/appearance-themes.e2e.ts", "./specs/source-control-review.e2e.ts", "./specs/host-dashboard.e2e.ts", + "./specs/server-commands.e2e.ts", closingSpec, ]; // The default specs share one app session. The closing spec ends the app, so it runs last in a @@ -94,7 +96,31 @@ const screenshotPath = (title: string): string => .toLowerCase()}.png`, ); +/** + * Waits for the app's readiness signal, `data-connection-store` on ``, to say the + * connection store finished opening. Destroying the document while its IndexedDB requests + * are in flight is what left a later open pending in WebKit (#381). A new document has no + * attribute until the app sets it, which reads as pending. + */ +async function waitForDesktopUiConnectionStoreIdle(stage: string): Promise { + // A plain loop: this file keeps to plain driver commands (tauri-service-compat.test.ts). + let lastState: string | null = null; + // 120 polls of 250 ms: 30 s. + for (let poll = 0; poll < 120; poll += 1) { + lastState = await browser.execute(() => + document.documentElement.getAttribute("data-connection-store"), + ); + if (lastState === "failed") { + throw new Error(`The app's connection store failed ${stage}.`); + } + if (lastState === "ready") return; + await browser.pause(250); + } + throw new Error(`The app's connection store was not ready ${stage} (${lastState ?? "pending"}).`); +} + async function resetDesktopUiConnectionCache(): Promise { + await waitForDesktopUiConnectionStoreIdle("before the connection reset"); const resetResult = await browser.executeAsync( (done: (result: { readonly error: string | null }) => void) => { window.localStorage.clear(); @@ -106,11 +132,23 @@ async function resetDesktopUiConnectionCache(): Promise { done({ error }); }; const openRequest = indexedDB.open("bibcode:connection-runtime", 2); + // Set by an upgrade: null for a new database, which has nothing to clear. + let upgradeOutcome: string | null | undefined; openRequest.addEventListener("error", () => { - finish(String(openRequest.error ?? "Could not open the E2E connection catalog.")); + finish( + upgradeOutcome !== undefined + ? upgradeOutcome + : String(openRequest.error ?? "Could not open the E2E connection catalog."), + ); }); - openRequest.addEventListener("upgradeneeded", () => { - finish("The E2E connection catalog schema was unexpectedly missing."); + openRequest.addEventListener("upgradeneeded", (event) => { + // Abort, so the app's own open creates the stores. The abort ends this request with + // an error event, and that event ends the reset. + openRequest.transaction?.abort(); + upgradeOutcome = + event.oldVersion === 0 + ? null + : "The E2E connection catalog schema was unexpectedly missing."; }); openRequest.addEventListener("success", () => { const database = openRequest.result; @@ -134,6 +172,7 @@ async function resetDesktopUiConnectionCache(): Promise { throw new Error(resetResult.error); } await refreshDesktopUiDocument(); + await waitForDesktopUiConnectionStoreIdle("after the connection reset"); } export const config = { @@ -236,6 +275,7 @@ export const config = { await requestDesktopUiApplicationExit(); // The service stops only the app it started; an app a closing case relaunched is stopped here. await stopRelaunchedDesktopUiApplication(); + acceptEndedApplicationSessionDelete(); }, onComplete: () => { // Keep the app's own logs (native page loads, webview process failures, server errors) diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs index 76ef1a46f0..35ef462c30 100644 --- a/apps/desktop/src-tauri/src/bridge.rs +++ b/apps/desktop/src-tauri/src/bridge.rs @@ -4559,9 +4559,22 @@ mod tests { .expect("mock Tauri app"); #[cfg(target_os = "linux")] app.manage(crate::linux_theme::LinuxThemeState::default()); + // Tauri on Windows and Linux otherwise puts webview data in the identifier's local app-data + // folder, which outlives the test process. + // A folder an earlier run with this process id left behind is the test's own. + let local_app_data = app + .path() + .app_local_data_dir() + .expect("local app-data folder"); + let _ = std::fs::remove_dir_all(&local_app_data); let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .data_directory(temp.path().join("webview-data")) .build() .expect("mock webview"); + assert!( + !local_app_data.exists(), + "the test leaves nothing in the local app-data folder" + ); let invoke = |cmd: &str, body: Value| { get_ipc_response( &webview, diff --git a/apps/desktop/src-tauri/src/remote_update_delegate.rs b/apps/desktop/src-tauri/src/remote_update_delegate.rs index 3f1f3659f1..f51fd9b70a 100644 --- a/apps/desktop/src-tauri/src/remote_update_delegate.rs +++ b/apps/desktop/src-tauri/src/remote_update_delegate.rs @@ -385,11 +385,14 @@ mod tests { assert!(window_allows_install(app.handle()).await); // With a main window the install waits for the web: Stay refuses it, Allow lets it run. + // Its webview data stays in a temporary folder, not the local app-data folder. + let webview_data = tempfile::tempdir().expect("webview data folder"); let _window = tauri::WebviewWindowBuilder::new( &app, crate::window::MAIN_WINDOW_LABEL, Default::default(), ) + .data_directory(webview_data.path().to_path_buf()) .build() .expect("mock webview"); let guard = app.state::(); diff --git a/apps/desktop/src-tauri/src/window.rs b/apps/desktop/src-tauri/src/window.rs index 2a582da915..619217f80e 100644 --- a/apps/desktop/src-tauri/src/window.rs +++ b/apps/desktop/src-tauri/src/window.rs @@ -1053,9 +1053,22 @@ mod tests { .build(context) .expect("mock Tauri app"); let handle = app.handle(); + // Tauri on Windows and Linux otherwise puts webview data in the identifier's local app-data + // folder, which outlives the test process. + // A folder an earlier run with this process id left behind is the test's own. + let local_app_data = handle + .path() + .app_local_data_dir() + .expect("local app-data folder"); + let _ = std::fs::remove_dir_all(&local_app_data); let window = tauri::WebviewWindowBuilder::new(&app, MAIN_WINDOW_LABEL, Default::default()) + .data_directory(temp.path().join("webview-data")) .build() .expect("mock webview"); + assert!( + !local_app_data.exists(), + "the test leaves nothing in the local app-data folder" + ); let state_path = window_state_path(handle).expect("window state path should resolve"); persist_main_window_state(handle).expect("empty mock state should be ignored"); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 0174e5cbcd..26be019ba2 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -25,8 +25,8 @@ } ], "security": { - "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* http: ws: https: wss:; img-src 'self' asset: http://asset.localhost http://127.0.0.1:* http://localhost:* data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self' data:; object-src blob:; frame-src 'self' blob:; base-uri 'self'; frame-ancestors 'none'; form-action 'self'", - "devCsp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* http: ws: https: wss:; img-src 'self' asset: http://asset.localhost http://127.0.0.1:* http://localhost:* data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval'; font-src 'self' data:; object-src blob:; frame-src 'self' blob:; base-uri 'self'; frame-ancestors 'none'; form-action 'self'", + "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* http: ws: https: wss: blob:; img-src 'self' asset: http://asset.localhost http://127.0.0.1:* http://localhost:* data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self' data:; object-src blob:; frame-src 'self' blob:; base-uri 'self'; frame-ancestors 'none'; form-action 'self'", + "devCsp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* http: ws: https: wss: blob:; img-src 'self' asset: http://asset.localhost http://127.0.0.1:* http://localhost:* data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval'; font-src 'self' data:; object-src blob:; frame-src 'self' blob:; base-uri 'self'; frame-ancestors 'none'; form-action 'self'", "dangerousDisableAssetCspModification": ["style-src"] } }, diff --git a/apps/server/src/agent_messaging/pointer.rs b/apps/server/src/agent_messaging/pointer.rs index 1be0054a51..62a8bae821 100644 --- a/apps/server/src/agent_messaging/pointer.rs +++ b/apps/server/src/agent_messaging/pointer.rs @@ -117,9 +117,9 @@ impl PointerTerminals for TerminalManager { } /// The only text the server ever types into a terminal (R17): it names no message, title or -/// sender. -pub const POINTER_LINE: &str = - "BiBCode: you have new messages. Run `bibcode agent inbox` to read them."; +/// sender. It asks for the answer too: an agent told only to read its inbox reads it and stops, +/// because it treats what a message asks as data, not as its user's request. +pub const POINTER_LINE: &str = "BiBCode: you have new messages. Run `bibcode agent inbox` to read them, and answer each one that asks for a reply."; pub const POINTER_PASTE_OPEN: &str = "\u{1b}[200~"; pub const POINTER_PASTE_CLOSE: &str = "\u{1b}[201~"; pub const POINTER_SUBMIT: &str = "\r"; @@ -1547,7 +1547,7 @@ pub(crate) mod tests { assert_eq!(fixture.terminals.writes("t", "term-1"), [pointer_bytes()]); assert_eq!( pointer_bytes(), - "\u{1b}[200~BiBCode: you have new messages. Run `bibcode agent inbox` to read them.\u{1b}[201~\r" + "\u{1b}[200~BiBCode: you have new messages. Run `bibcode agent inbox` to read them, and answer each one that asks for a reply.\u{1b}[201~\r" ); fixture.shutdown().await; } diff --git a/apps/server/src/auth/service.rs b/apps/server/src/auth/service.rs index ad060cf1f9..02c98d0c7e 100644 --- a/apps/server/src/auth/service.rs +++ b/apps/server/src/auth/service.rs @@ -142,6 +142,8 @@ pub(crate) struct AuthTestHooks { pub(crate) before_session_upsert_event: std::sync::Mutex>, /// Gives `mcp-client` sessions random ids, as a server before #281 did. pub(crate) random_mcp_session_ids: AtomicBool, + /// Makes the authority watcher skip its ticks, so a test sees what a prune alone sends. + pub(crate) pause_watcher: AtomicBool, } #[cfg(test)] @@ -857,6 +859,8 @@ impl AuthService { let access_events = Arc::downgrade(&self.access_events); let access_revision = Arc::downgrade(&self.access_revision); let watcher_running = Arc::downgrade(&self.authority_watcher_running); + #[cfg(test)] + let hooks = Arc::downgrade(&self.test_hooks); tokio::spawn(async move { let mut interval = tokio::time::interval(AUTHORITY_CONVERGENCE_INTERVAL); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); @@ -867,6 +871,13 @@ impl AuthService { let mut next_expiry_ms = None; 'watcher: loop { interval.tick().await; + #[cfg(test)] + if hooks + .upgrade() + .is_some_and(|hooks| hooks.pause_watcher.load(Ordering::Acquire)) + { + continue; + } let ( Some(state), Some(access_events), @@ -1435,6 +1446,32 @@ impl AuthService { Ok(()) } + /// Drops expired or revoked sessions from the cache and sends their `ClientRemoved` under + /// the same lock, so the watcher's later diff cannot miss them (#374). An expired remote + /// grant stays for the watcher: a refresh rotation commits its new expiry before the cache + /// follows, so only the store knows whether the grant is still valid. + fn prune_dead_sessions(&self, state: &mut AuthState, now: i64) { + let renewable = self.repositories.is_some(); + let dead = state + .sessions + .iter() + .filter(|(_, session)| { + session.revoked_at_ms.is_some() + || (session.expires_at_ms <= now + && !(renewable && session.mcp_resource.is_some())) + }) + .map(|(session_id, _)| session_id.clone()) + .collect::>(); + if dead.is_empty() { + return; + } + for session_id in dead { + state.sessions.remove(&session_id); + self.emit_access_change(state, AuthAccessChange::ClientRemoved { session_id }); + } + state.bump_authority_generation(); + } + async fn remove_cached_session(&self, session_id: &str) { let mut state = self.state.lock().await; let removed = state.sessions.remove(session_id).is_some(); @@ -2095,9 +2132,7 @@ impl AuthService { pub async fn list_clients(&self, current_session_id: &str) -> Vec { let now = now_ms(); let mut state = self.state.lock().await; - state - .sessions - .retain(|_, session| session.revoked_at_ms.is_none() && session.expires_at_ms > now); + self.prune_dead_sessions(&mut state, now); let mut sessions = state .sessions .values() @@ -2217,9 +2252,7 @@ impl AuthService { let issued_at = now_ms(); { let mut state = self.state.lock().await; - state.sessions.retain(|_, session| { - session.revoked_at_ms.is_none() && session.expires_at_ms > issued_at - }); + self.prune_dead_sessions(&mut state, issued_at); if state.sessions.len() >= MAX_ACTIVE_SESSIONS { return Err(AuthError::Internal( "active session capacity exceeded".to_owned(), @@ -2935,9 +2968,7 @@ impl AuthService { }; { let mut state = self.state.lock().await; - state.sessions.retain(|_, session| { - session.revoked_at_ms.is_none() && session.expires_at_ms > issued_at - }); + self.prune_dead_sessions(&mut state, issued_at); // Sessions the desktop bootstrap is about to supersede do not hold // capacity against the session that replaces them. let occupied = if desktop_bootstrap { @@ -8264,6 +8295,154 @@ mod tests { ); } + enum Prune { + ListClients, + IssueSession, + MintGrant, + } + + /// #374: a session that expired and was revoked before the watcher reconciled must + /// reach an access-stream consumer as a `ClientRemoved` from the prune itself. The + /// watcher is held, so it cannot send the removal in the prune's place. + async fn assert_pruned_expired_revoked_client_is_removed(prune: Prune) { + let (service, repositories, _secrets) = mcp_test_service().await; + service + .test_hooks() + .pause_watcher + .store(true, std::sync::atomic::Ordering::Release); + let gone = run(&service, &repositories, "builder").await; + let mut events = service.access_events.subscribe(); + assert!( + service + .access_snapshot("") + .await + .2 + .iter() + .any(|client| client.session_id == gone), + "the consumer's snapshot holds the live client" + ); + let past = now_ms() - 1; + service + .state + .lock() + .await + .sessions + .get_mut(&gone) + .expect("the run is cached") + .expires_at_ms = past; + repositories + .revoke_auth_session(gone.clone(), format_iso(now_ms())) + .await + .unwrap(); + let expired = format_iso(past); + let id = gone.clone(); + repositories + .database() + .call(move |connection| { + connection.execute( + "UPDATE auth_sessions SET expires_at = ? WHERE session_id = ?", + rusqlite::params![expired, id], + )?; + Ok(()) + }) + .await + .unwrap(); + + match prune { + Prune::ListClients => { + service.list_clients("").await; + } + Prune::IssueSession => { + run(&service, &repositories, "reviewer").await; + } + Prune::MintGrant => { + super::minted_remote_grant(&service, &repositories, "refresh-1").await; + } + } + assert!( + !service.state.lock().await.sessions.contains_key(&gone), + "the prune dropped the cached row" + ); + let mut removed = false; + while let Ok(event) = events.try_recv() { + removed |= matches!(&event.change, + AuthAccessChange::ClientRemoved { session_id } if *session_id == gone); + } + service + .test_hooks() + .pause_watcher + .store(false, std::sync::atomic::Ordering::Release); + assert!( + removed, + "a stream consumer never hears that the pruned client is gone" + ); + } + + #[tokio::test] + async fn listing_clients_sends_the_removal_of_an_expired_revoked_one() { + assert_pruned_expired_revoked_client_is_removed(Prune::ListClients).await; + } + + #[tokio::test] + async fn issuing_a_session_sends_the_removal_of_an_expired_revoked_one() { + assert_pruned_expired_revoked_client_is_removed(Prune::IssueSession).await; + } + + #[tokio::test] + async fn minting_a_grant_sends_the_removal_of_an_expired_revoked_one() { + assert_pruned_expired_revoked_client_is_removed(Prune::MintGrant).await; + } + + /// A rotation commits the moved expiry before it updates the cache. A prune in that gap + /// must not announce the removal of a grant that is still valid. + #[tokio::test] + async fn a_prune_between_a_rotation_commit_and_its_cache_update_keeps_the_grant() { + let (service, repositories, _secrets) = mcp_test_service().await; + service + .test_hooks() + .pause_watcher + .store(true, std::sync::atomic::Ordering::Release); + let tokens = super::minted_remote_grant(&service, &repositories, "refresh-1").await; + let session_id = service + .authenticate_mcp_client(&tokens.access_token) + .await + .unwrap() + .principal + .session_id; + let mut events = service.access_events.subscribe(); + // The database holds the grant's new expiry; the cache still has the old, passed one. + service + .state + .lock() + .await + .sessions + .get_mut(&session_id) + .expect("the grant is cached") + .expires_at_ms = now_ms() - 1; + + service.list_clients("").await; + service + .refresh_session_from_repository(&session_id, now_ms()) + .await + .unwrap(); + + while let Ok(event) = events.try_recv() { + assert!( + !matches!(&event.change, AuthAccessChange::ClientRemoved { .. }), + "the consumer saw a valid grant disappear: {:?}", + event.change + ); + } + assert!( + service + .list_clients("") + .await + .iter() + .any(|client| client.session_id == session_id), + "the grant is listed again once the cache follows the database" + ); + } + #[tokio::test] async fn a_relay_revoke_never_ends_its_named_client() { let (service, repositories, _secrets) = mcp_test_service().await; diff --git a/apps/server/src/diagnostics/native.rs b/apps/server/src/diagnostics/native.rs index 066289be85..5178d0218b 100644 --- a/apps/server/src/diagnostics/native.rs +++ b/apps/server/src/diagnostics/native.rs @@ -283,16 +283,34 @@ fn cleanup_runtime_process_identities( mut signal: impl FnMut(ProcessIdentity) -> Result<(), SignalError>, ) -> ProcessCleanupReport { let mut report = ProcessCleanupReport::default(); + let mut unsupported = 0_usize; + let mut unsupported_pids = Vec::new(); for identity in identities { match signal(*identity) { Ok(()) | Err(SignalError::NotFound(_) | SignalError::StaleIdentity(_)) => { report.record_success(); } + // macOS has no identity-bound signal, so nothing was attempted. The sample also + // lists processes that shutdown already killed and that have not been reaped yet, + // which is why this is no failure. + Err(SignalError::Unsupported) => { + unsupported += 1; + if unsupported_pids.len() < 8 { + unsupported_pids.push(identity.pid); + } + } Err(error) => { report.record_failure(format!("process {}: {error}", identity.pid)); } } } + if unsupported > 0 { + tracing::debug!( + unsupported, + pids = ?unsupported_pids, + "left runtime-owned processes to exit: this platform has no identity-bound signal" + ); + } report } @@ -1306,6 +1324,17 @@ mod tests { )); } + #[test] + fn cleanup_reports_no_failure_where_the_platform_cannot_signal() { + let identities = [1, 2].map(|pid| ProcessIdentity { + pid, + started_at: 100, + }); + let report = + cleanup_runtime_process_identities(&identities, |_| Err(SignalError::Unsupported)); + assert_eq!(report, ProcessCleanupReport::default()); + } + #[test] fn cleanup_fallback_continues_after_failures_and_bounds_its_report() { let identities = (1..=20) diff --git a/apps/server/src/git/manager/graph.rs b/apps/server/src/git/manager/graph.rs index bf4903548c..47cc07b87e 100644 --- a/apps/server/src/git/manager/graph.rs +++ b/apps/server/src/git/manager/graph.rs @@ -22,9 +22,15 @@ pub const MAX_REASONABLE_DIFF_SIZE: usize = MAX_DIFF_BUFFER_SIZE / 16; pub const MAX_DIFF_LINE_CHARACTERS: usize = 5_000; const COMMIT_TEXT_LIMIT: usize = 100 * 1024; const RECORD_SEPARATOR: char = '\u{1e}'; -/// History pages target 1 MiB of serialized commit JSON. Always retain one -/// commit so an unusually large entry cannot stop pagination. +/// History pages hold at most 1 MiB of serialized commit JSON. A page always +/// keeps one commit so pagination never stalls, and that commit is cut down to +/// fit the target on its own (see `fit_first_commit`). pub const COMMIT_PAGE_TARGET_BYTES: usize = 1024 * 1024; +/// Room left for `,"changedFilesOmitted":` when changed files are cut. +const OMITTED_MARKER_BYTES: usize = 48; +/// A first commit cut to fit leaves this much of the target for the page around it (pinned +/// tips, offsets) and the RPC envelope, under the 1 MiB logical message a remote client accepts. +const FIRST_COMMIT_HEADROOM_BYTES: usize = 64 * 1024; /// The entry's exact JSON size, escaping, field names and numbers included. /// It is counted, not built, so the response encoding is the only place the @@ -35,6 +41,20 @@ fn encoded_entry_bytes(entry: &GitManagerCommitEntry) -> usize { encoded_json_len(entry).unwrap_or(usize::MAX) } +#[cfg(test)] +thread_local! { + /// Bytes the first-commit fitter measured on this thread, for its cost test. + static FIT_BYTES_MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// `encoded_json_len` for the first-commit fitter, counted in tests. +fn fit_measure(value: &T) -> usize { + let bytes = encoded_json_len(value).unwrap_or(usize::MAX); + #[cfg(test)] + FIT_BYTES_MEASURED.with(|measured| measured.set(measured.get().saturating_add(bytes))); + bytes +} + /// How many leading commits fit the page target; always at least one. fn commits_within_target(commits: &[GitManagerCommitEntry], target: usize) -> usize { let mut total = 2_usize; // JSON array brackets @@ -49,6 +69,87 @@ fn commits_within_target(commits: &[GitManagerCommitEntry], target: usize) -> us commits.len() } +/// How many leading commits the page keeps. With `fit_first` (a client that shows +/// `changedFilesOmitted`) its first commit is cut to fit, and the whole page, cut or not, keeps +/// the headroom free for the page wrapper. Without it the first commit is sent whole and the page +/// uses the full target, as older clients expect. +fn fit_page(commits: &mut [GitManagerCommitEntry], fit_first: bool) -> usize { + if !fit_first { + return commits_within_target(commits, COMMIT_PAGE_TARGET_BYTES); + } + if let Some(first) = commits.first_mut() { + fit_first_commit(first, COMMIT_PAGE_TARGET_BYTES); + } + commits_within_target( + commits, + COMMIT_PAGE_TARGET_BYTES - FIRST_COMMIT_HEADROOM_BYTES, + ) +} + +/// Cuts `entry` until it fits `target` less `FIRST_COMMIT_HEADROOM_BYTES` (#390), and says +/// whether it cut anything. Changed files go first, from the end, and are counted in +/// `changed_files_omitted`; then text fields, longest first; then decorations, from the end. The +/// cut is computed from the sizes of the parts it removes, so the entry is measured whole once. +/// Only the SHAs and parents, which the graph needs, are never cut. +fn fit_first_commit(entry: &mut GitManagerCommitEntry, target: usize) -> bool { + let budget = target.saturating_sub(FIRST_COMMIT_HEADROOM_BYTES); + let size = fit_measure(entry); + if size <= budget { + return false; + } + // Each removed array item also frees its comma; the marker room covers the one fewer comma + // than items an emptied array frees. + let mut excess = size + .saturating_sub(budget) + .saturating_add(OMITTED_MARKER_BYTES); + while excess > 0 { + let Some(path) = entry.changed_files.pop() else { + break; + }; + excess = excess.saturating_sub(fit_measure(&path).saturating_add(1)); + entry.changed_files_omitted += 1; + } + let mut texts = [ + &mut entry.body, + &mut entry.subject, + &mut entry.author_name, + &mut entry.author_email, + &mut entry.committer_name, + &mut entry.committer_email, + ]; + texts.sort_by_key(|text| std::cmp::Reverse(text.len())); + for text in texts { + if excess == 0 { + break; + } + // The text's encoded size without its quotes. + let bytes = fit_measure(text.as_str()).saturating_sub(2); + if bytes <= excess { + excess -= bytes; + text.clear(); + continue; + } + let keep = bytes - excess; + let boundaries = text + .char_indices() + .map(|(index, _)| index) + .chain([text.len()]) + .collect::>(); + let fitting = + boundaries.partition_point(|&end| fit_measure(&text[..end]).saturating_sub(2) <= keep); + let end = boundaries[fitting.saturating_sub(1)]; + text.truncate(end); + excess = 0; + } + while excess > 0 { + let Some(decoration) = entry.decorations.pop() else { + break; + }; + excess = excess.saturating_sub(fit_measure(&decoration).saturating_add(1)); + } + true +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct GitManagerCommitEntry { @@ -65,6 +166,13 @@ pub struct GitManagerCommitEntry { pub committer_email: String, pub committed_at_ms: u64, pub changed_files: Vec, + /// How many changed files `changed_files` leaves out to keep the entry within a page. + #[serde(skip_serializing_if = "is_zero")] + pub changed_files_omitted: usize, +} + +fn is_zero(value: &usize) -> bool { + *value == 0 } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -120,6 +228,7 @@ pub fn parse_commit_record(record: &str) -> Option { .map(str::to_owned) .collect(), changed_files: Vec::new(), + changed_files_omitted: 0, }; fields.next().is_none().then_some(entry) } @@ -169,6 +278,7 @@ pub async fn page( pinned_tips: Option<&[String]>, offset: usize, limit: usize, + fit_first: bool, cancellation: &CancellationToken, ) -> Result { let (selection, generation) = match pinned_tips { @@ -245,7 +355,7 @@ pub async fn page( } let has_more = commits.len() > limit; commits.truncate(limit); - let kept = commits_within_target(&commits, COMMIT_PAGE_TARGET_BYTES); + let kept = fit_page(&mut commits, fit_first); let trimmed = kept < commits.len(); commits.truncate(kept); let returned = commits.len(); @@ -376,6 +486,7 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; None, 1, 100, + true, &CancellationToken::new(), ) .await @@ -396,6 +507,7 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; Some(&[missing]), 0, 100, + true, &CancellationToken::new(), ) .await @@ -439,6 +551,7 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; None, 0, 1, + true, &CancellationToken::new(), ) .await @@ -453,6 +566,7 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; Some(&first.pinned_tips), 1, 1, + true, &CancellationToken::new(), ) .await @@ -476,6 +590,7 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; committer_email: "cara@example.test".to_owned(), committed_at_ms: 0, changed_files: Vec::new(), + changed_files_omitted: 0, } } @@ -489,6 +604,106 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; assert_eq!(commits_within_target(&small, COMMIT_PAGE_TARGET_BYTES), 100); } + /// After a cut first commit, the rest of the page shares its budget, so the whole page with + /// its wrapper stays within the target (#390 review). + #[test] + fn a_page_after_a_cut_first_commit_stays_within_the_target() { + let mut first = entry_with_body(0); + first.changed_files = (0..27_000) + .map(|index| format!("generated/path/{index:05}/file-name.txt")) + .collect(); + // Whole, it fits 1 MiB alone but not the 960 KiB a cut leaves, as in the review. + let whole = encoded_entry_bytes(&first); + assert!(whole > COMMIT_PAGE_TARGET_BYTES - FIRST_COMMIT_HEADROOM_BYTES); + assert!(whole < COMMIT_PAGE_TARGET_BYTES); + let mut alone = first.clone(); + assert!(fit_first_commit(&mut alone, COMMIT_PAGE_TARGET_BYTES)); + let first_bytes = encoded_entry_bytes(&alone); + // A second commit that would just fit the full target after the cut first one. + let base = encoded_entry_bytes(&entry_with_body(0)); + let room = COMMIT_PAGE_TARGET_BYTES - 2 - first_bytes - 1 - 20; + let second = entry_with_body(room - base); + assert_eq!(encoded_entry_bytes(&second), room); + let mut commits = vec![first, second]; + let kept = fit_page(&mut commits, true); + let page = GitManagerCommitPage { + generation: 1, + pinned_tips: vec!["c".repeat(40)], + commits: commits[..kept].to_vec(), + next_offset: Some(kept), + exhausted: false, + degraded_to_all_paging: false, + }; + let bytes = serde_json::to_vec(&page).expect("page JSON").len(); + assert!(bytes <= COMMIT_PAGE_TARGET_BYTES, "{bytes} bytes"); + } + + /// With the flag the page keeps the headroom for its wrapper even when no commit needs a + /// cut: two commits that each fit leave the serialized page within the target. + #[test] + fn an_opted_in_page_without_a_cut_stays_within_the_target() { + let base = encoded_entry_bytes(&entry_with_body(0)); + let half = entry_with_body(524_284 - base); + assert_eq!(encoded_entry_bytes(&half), 524_284); + let mut commits = vec![half.clone(), half]; + let kept = fit_page(&mut commits, true); + let page = GitManagerCommitPage { + generation: 1, + pinned_tips: vec!["c".repeat(40)], + commits: commits[..kept].to_vec(), + next_offset: Some(kept), + exhausted: false, + degraded_to_all_paging: false, + }; + let bytes = serde_json::to_vec(&page).expect("page JSON").len(); + assert!(bytes <= COMMIT_PAGE_TARGET_BYTES, "{bytes} bytes"); + // A client without the flag keeps the base behaviour: both commits, the full target. + let mut base_commits = vec![entry_with_body(524_284 - base); 2]; + assert_eq!(fit_page(&mut base_commits, false), 2); + } + + /// Fitting a commit with 20,000 decorations measures a bounded number of bytes instead of + /// re-encoding the entry once per dropped decoration (#390 review). + #[test] + fn fitting_a_heavily_decorated_commit_measures_a_bounded_number_of_bytes() { + let mut entry = entry_with_body(0); + entry.decorations = (0..20_000) + .map(|index| format!("tag: refs/tags/release-{index:05}-{}", "x".repeat(50))) + .collect(); + assert!(encoded_entry_bytes(&entry) > COMMIT_PAGE_TARGET_BYTES); + FIT_BYTES_MEASURED.with(|measured| measured.set(0)); + fit_first_commit(&mut entry, COMMIT_PAGE_TARGET_BYTES); + let measured = FIT_BYTES_MEASURED.with(std::cell::Cell::get); + assert!(measured < 64 * 1024 * 1024, "measured {measured} bytes"); + assert!( + encoded_entry_bytes(&entry) <= COMMIT_PAGE_TARGET_BYTES - FIRST_COMMIT_HEADROOM_BYTES + ); + } + + /// Text that only fits after escaping is cut too, and the SHA and parents stay (#390). + #[test] + fn a_first_commit_over_the_target_without_files_cuts_its_text() { + let mut entry = entry_with_body(0); + entry.body = "\u{0001}".repeat(COMMIT_TEXT_LIMIT); + entry.subject = "\u{0001}".repeat(COMMIT_TEXT_LIMIT); + entry.parents = vec!["b".repeat(40)]; + assert!(encoded_entry_bytes(&entry) > COMMIT_PAGE_TARGET_BYTES); + let sha = entry.sha.clone(); + fit_first_commit(&mut entry, COMMIT_PAGE_TARGET_BYTES); + let bytes = serde_json::to_vec(std::slice::from_ref(&entry)) + .expect("page JSON") + .len(); + assert!(bytes <= COMMIT_PAGE_TARGET_BYTES, "{bytes} bytes"); + assert_eq!(entry.sha, sha); + assert_eq!(entry.parents, vec!["b".repeat(40)]); + assert_eq!(entry.changed_files_omitted, 0); + // A commit within the target is left as it was. + let small = entry_with_body(100); + let mut fitted = small.clone(); + fit_first_commit(&mut fitted, COMMIT_PAGE_TARGET_BYTES); + assert_eq!(fitted, small); + } + #[test] fn history_budget_counts_json_escaping_instead_of_raw_string_lengths() { let mut entry = entry_with_body(0); @@ -569,6 +784,79 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; assert_eq!(pages, vec![5, 3, 4, 3, 4, 3, 1, 1, 3, 4, 3, 4, 2]); } + /// A first commit whose changed files alone pass the page target still fits it, and says how + /// many files it leaves out (#390). + #[tokio::test] + async fn a_first_commit_with_a_huge_file_list_stays_within_the_page_target() { + let repository = repository_with_one_commit(); + const FILES: usize = 8_000; + // The paths go straight into the index, so no file on disk meets a path length limit. + let blob = git_stdout(repository.path(), &["hash-object", "-w", "README.md"]); + let index_info = (0..FILES) + .map(|index| { + format!( + "100644 {} 0\tgenerated/module-{:03}/{}file-{index:05}.txt\n", + blob.trim(), + index / 100, + "nested-directory-name/".repeat(24) + ) + }) + .collect::(); + let mut update = Command::new("git") + .args(["update-index", "--index-info"]) + .current_dir(repository.path()) + .stdin(std::process::Stdio::piped()) + .spawn() + .expect("git update-index starts"); + std::io::Write::write_all( + update.stdin.as_mut().expect("update-index stdin"), + index_info.as_bytes(), + ) + .expect("index info written"); + assert!(update.wait().expect("update-index ends").success()); + git(repository.path(), &["commit", "-q", "-m", "many files"]); + // A client that does not ask for a fitted first commit gets it whole, as before. + let whole = page( + &GitRepository::default(), + repository.path(), + None, + 0, + COMMIT_PAGE_SIZE, + false, + &CancellationToken::new(), + ) + .await + .expect("whole history page"); + assert_eq!(whole.commits[0].changed_files.len(), FILES); + assert_eq!(whole.commits[0].changed_files_omitted, 0); + let first = page( + &GitRepository::default(), + repository.path(), + None, + 0, + COMMIT_PAGE_SIZE, + true, + &CancellationToken::new(), + ) + .await + .expect("first history page"); + let commits_bytes = serde_json::to_vec(&first.commits).expect("page JSON").len(); + let page_bytes = serde_json::to_vec(&first).expect("page JSON").len(); + let listed = first.commits[0].changed_files.len(); + eprintln!( + "getCommits first page: {} commits, commits {commits_bytes} bytes, page {page_bytes} bytes, {listed} of {FILES} files listed", + first.commits.len() + ); + assert!( + commits_bytes <= COMMIT_PAGE_TARGET_BYTES, + "{commits_bytes} bytes" + ); + assert!(page_bytes <= COMMIT_PAGE_TARGET_BYTES, "{page_bytes} bytes"); + assert_eq!(listed + first.commits[0].changed_files_omitted, FILES); + assert!(first.commits[0].changed_files_omitted > 0); + assert!(listed > 0, "the files that fit stay listed"); + } + #[tokio::test] async fn a_page_of_large_commits_stops_near_one_mebibyte_and_pages_on() { let repository = repository_with_one_commit(); @@ -593,27 +881,30 @@ parent1\u{1f}HEAD -> main\0\nfirst.txt\0nested/second.txt\0"; None, 0, COMMIT_PAGE_SIZE, + true, &CancellationToken::new(), ) .await .expect("first history page"); - assert_eq!(first.commits.len(), 11, "eleven 90 KiB commits fit 1 MiB"); - assert_eq!(first.next_offset, Some(11)); + // The client opted in, so the page keeps the wrapper's headroom: 960 KiB. + assert_eq!(first.commits.len(), 10, "ten 90 KiB commits fit 960 KiB"); + assert_eq!(first.next_offset, Some(10)); assert!(!first.exhausted); let second = page( &GitRepository::default(), repository.path(), Some(first.pinned_tips.as_slice()), - 11, + 10, COMMIT_PAGE_SIZE, + true, &CancellationToken::new(), ) .await .expect("second history page"); assert_eq!( second.commits.len(), - 4, - "three large commits and the first one" + 5, + "four large commits and the first one" ); assert!(second.exhausted); } diff --git a/apps/server/src/git/manager/merge.rs b/apps/server/src/git/manager/merge.rs index c5e32df49e..bd7862c7c8 100644 --- a/apps/server/src/git/manager/merge.rs +++ b/apps/server/src/git/manager/merge.rs @@ -97,6 +97,19 @@ pub async fn ensure_merge_tree_supported( } } +/// Whether merge-into can be offered: false only when Git is known to be older than 2.38. +/// A failed or unparseable read keeps it on; the operation itself reports any real failure. +pub async fn git_supports_merge_into( + repository: &GitRepository, + cwd: &Path, + cancellation: &CancellationToken, +) -> bool { + !matches!( + ensure_merge_tree_supported(repository, cwd, cancellation).await, + Err(GitManagerMergeError::GitTooOld { .. }) + ) +} + fn valid_revision(value: &str) -> bool { !value.is_empty() && value.trim() == value && !value.starts_with('-') } @@ -417,7 +430,7 @@ fn parse_ahead_behind(stdout: &str) -> Result<(u64, u64), GitManagerMergeError> } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, @@ -427,11 +440,17 @@ mod tests { use crate::git::{BoxGitProcessFuture, GitProcessRunner, ProcessRequest}; /// Answers every Git invocation with a fixed `git --version` line and counts the calls. - struct VersionRunner { + pub(crate) struct VersionRunner { stdout: &'static str, - calls: AtomicUsize, + pub(crate) calls: AtomicUsize, } + /// The Git every unit-test `NativeServerControl` reads its startup version from. + pub(crate) static UNIT_TEST_STARTUP_GIT: std::sync::LazyLock<( + Arc, + GitRepository, + )> = std::sync::LazyLock::new(|| version_runner("git version 2.38.0\n")); + impl GitProcessRunner for VersionRunner { fn run<'a>( &'a self, @@ -452,7 +471,7 @@ mod tests { } } - fn version_runner(stdout: &'static str) -> (Arc, GitRepository) { + pub(crate) fn version_runner(stdout: &'static str) -> (Arc, GitRepository) { let runner = Arc::new(VersionRunner { stdout, calls: AtomicUsize::new(0), @@ -475,6 +494,23 @@ mod tests { )); } + #[tokio::test] + async fn merge_into_is_offered_only_on_git_2_38_or_later() { + let cancellation = CancellationToken::new(); + for (version, supported) in [ + ("git version 2.37.9\n", false), + ("git version 2.38.0\n", true), + ("not a git version\n", true), + ] { + let (_, repository) = version_runner(version); + assert_eq!( + git_supports_merge_into(&repository, Path::new("."), &cancellation).await, + supported, + "{version}" + ); + } + } + #[tokio::test] async fn supported_versions_are_read_once_per_repository() { let (runner, repository) = version_runner("git version 2.38.0\n"); diff --git a/apps/server/src/git/manager/refs.rs b/apps/server/src/git/manager/refs.rs index 04ce402752..7007867338 100644 --- a/apps/server/src/git/manager/refs.rs +++ b/apps/server/src/git/manager/refs.rs @@ -869,6 +869,59 @@ mod tests { } } + #[tokio::test] + async fn head_ref_names_the_branch_when_a_tag_shares_its_name() { + let repository = repository_with_one_commit(); + let branch = + String::from_utf8(git_output(repository.path(), &["branch", "--show-current"]).stdout) + .expect("UTF-8 branch") + .trim() + .to_owned(); + // `symbolic-ref --short` would say `heads/` once the tag exists. + git(repository.path(), &["tag", &branch]); + + let snapshot = snapshot(&repository).await; + assert_eq!(snapshot.head_ref.as_deref(), Some(branch.as_str())); + assert!( + snapshot + .local_branches + .iter() + .any(|entry| entry.current && entry.name == branch) + ); + } + + /// What the New branch dialog relies on before the first commit: no start point, + /// and Git can start the branch only by switching to it. + #[tokio::test] + async fn an_unborn_branch_starts_a_new_branch_only_by_switching() { + let repository = TempDir::new().expect("temporary repository"); + git(repository.path(), &["init", "-q", "-b", "main"]); + let before = snapshot(&repository).await; + assert_eq!(before.head_ref.as_deref(), Some("main")); + assert!(before.local_branches.is_empty()); + assert_eq!(before.detached_sha, None); + + let git_repository = GitRepository::default(); + let cancellation = CancellationToken::new(); + for (checkout, succeeds) in [(false, false), (true, true)] { + let result = git_repository + .git_manager_create_branch( + repository.path(), + "topic", + None, + checkout, + &cancellation, + ) + .await; + let created = matches!(&result, Ok(output) if output.exit_code == 0); + assert_eq!(created, succeeds, "checkout {checkout}: {result:?}"); + } + assert_eq!( + snapshot(&repository).await.head_ref.as_deref(), + Some("topic") + ); + } + #[tokio::test] async fn detached_head_sets_sha_without_a_head_ref() { let repository = repository_with_one_commit(); diff --git a/apps/server/src/git/repository.rs b/apps/server/src/git/repository.rs index 5013ecf1c4..a47588c584 100644 --- a/apps/server/src/git/repository.rs +++ b/apps/server/src/git/repository.rs @@ -872,15 +872,22 @@ impl GitRepository { cwd: &Path, cancellation: &CancellationToken, ) -> Result { - self.git_manager_bounded_read( - "GitManager.getRefs.headRef", - cwd, - &strings(&["symbolic-ref", "--quiet", "--short", "HEAD"]), - true, - 64 * 1024, - cancellation, - ) - .await + // `--short` would say `heads/main` when a tag `main` exists: read the full ref and + // drop the branch prefix, so the name always matches the branch's own entry. + let mut output = self + .git_manager_bounded_read( + "GitManager.getRefs.headRef", + cwd, + &strings(&["symbolic-ref", "--quiet", "HEAD"]), + true, + 64 * 1024, + cancellation, + ) + .await?; + if let Some(branch) = output.stdout.trim().strip_prefix("refs/heads/") { + output.stdout = format!("{branch}\n"); + } + Ok(output) } pub(crate) async fn git_manager_head_sha( diff --git a/apps/server/src/lifecycle.rs b/apps/server/src/lifecycle.rs index 06f15b9c33..992091f641 100644 --- a/apps/server/src/lifecycle.rs +++ b/apps/server/src/lifecycle.rs @@ -90,6 +90,7 @@ fn connect_environment_descriptor(config: &ServerConfig) -> serde_json::Value { "codeReviews": true, "hostMetrics": true, "sendRequests": true, + "readOnlyCodexReviews": true, "conversationOnlyRewind": true, "threadDeleteOnlyIfUnused": true, }, @@ -1416,6 +1417,7 @@ mod tests { assert_eq!(descriptor["capabilities"]["codeReviews"], true); assert_eq!(descriptor["capabilities"]["hostMetrics"], true); assert_eq!(descriptor["capabilities"]["sendRequests"], true); + assert_eq!(descriptor["capabilities"]["readOnlyCodexReviews"], true); assert_eq!(descriptor["capabilities"]["threadDeleteOnlyIfUnused"], true); assert_eq!(descriptor["capabilities"]["attachmentStaging"], true); assert_eq!(descriptor["capabilities"]["profiler"], true); diff --git a/apps/server/src/orchestration/engine.rs b/apps/server/src/orchestration/engine.rs index 56e0e9dee0..e5808f5a5d 100644 --- a/apps/server/src/orchestration/engine.rs +++ b/apps/server/src/orchestration/engine.rs @@ -639,6 +639,21 @@ pub enum OrchestrationCommand { )] worktree_path: OptionalNullable, }, + /// Server only (#380 R4): stores Codex's default in place of the retired model a session + /// dropped, decided on the thread's selection when the command runs, so a selection another + /// client committed meanwhile is kept. + #[serde(rename = "thread.retired-model.clear")] + ThreadRetiredModelClear { + #[serde(rename = "commandId")] + command_id: String, + #[serde(rename = "threadId")] + thread_id: String, + /// The provider instance whose session dropped the model. + #[serde(rename = "instanceId")] + instance_id: String, + /// The canonical retired model the session dropped. + retired: String, + }, #[serde(rename = "thread.runtime-mode.set")] ThreadRuntimeModeSet { #[serde(rename = "commandId")] @@ -1271,6 +1286,9 @@ impl TestHooks { } } +/// Why a retired-model clear changes nothing: the thread no longer names that model. +pub const RETIRED_MODEL_ALREADY_REPLACED: &str = "the thread no longer names the retired model"; + #[derive(Debug, Error, Clone)] pub enum OrchestrationError { #[error("orchestration command invariant failed ({command_type}): {detail}")] @@ -4561,7 +4579,7 @@ async fn plan_command( let selection = default_model_selection .as_ref() .and_then(|value| value.cloned()) - .unwrap_or_else(|| json!({"instanceId":"codex","model":"gpt-5.4"})); + .unwrap_or_else(|| json!({"instanceId":"codex","model":"auto"})); Ok(vec![ make_event( "project.created", @@ -4976,6 +4994,7 @@ async fn plan_command( created_at, } => { require_project(model, command, project_id)?; + refuse_reserved_thread_id(command, thread_id)?; if *side_chat && (kind.as_deref() != Some("panel") || host_thread_id.is_none()) { return invariant( command, @@ -5160,6 +5179,51 @@ async fn plan_command( json!({"threadId":thread_id,"updatedAt":occurred_at}), )]) } + OrchestrationCommand::ThreadRetiredModelClear { + command_id, + thread_id, + instance_id, + retired, + } => { + require_thread(model, command, thread_id)?; + let mut selection = repositories + .get_thread(thread_id.clone()) + .await + .map_err(wrap_persistence)? + .map(|thread| thread.model_selection) + .unwrap_or(Value::Null); + // Only while the thread still names the dropped model on the instance that dropped + // it: a selection committed since the session launched, the same model on another + // instance included, stays as it is, and the command is refused as a no-op. + let selected_instance = selection + .get("instanceId") + .and_then(Value::as_str) + .filter(|instance| !instance.trim().is_empty()) + .unwrap_or("codex"); + if selected_instance != instance_id + || !selection + .get("model") + .and_then(Value::as_str) + .is_some_and(|selected| { + crate::provider::codex::model::same_model(selected, retired) + }) + { + return Err(OrchestrationError::Invariant { + command_type: command.command_type().to_owned(), + detail: RETIRED_MODEL_ALREADY_REPLACED.to_owned(), + }); + } + selection["model"] = json!("auto"); + Ok(vec![make_event( + "thread.meta-updated", + "thread", + thread_id, + occurred_at, + command_id, + metadata, + json!({"threadId":thread_id,"modelSelection":selection,"updatedAt":occurred_at}), + )]) + } OrchestrationCommand::ThreadMetaUpdate { command_id, thread_id, @@ -5281,6 +5345,7 @@ async fn plan_command( ); }; require_project(model, command, &create.project_id)?; + refuse_reserved_thread_id(command, thread_id)?; if create .purpose .as_deref() @@ -6117,6 +6182,21 @@ async fn compact_policy_baseline( Ok(()) } +/// The server terminal's thread id (#378) names no thread, so its session never mixes with a +/// thread's terminals or their cleanup. +fn refuse_reserved_thread_id( + command: &OrchestrationCommand, + thread_id: &str, +) -> Result<(), OrchestrationError> { + if thread_id == crate::terminal::SERVER_TERMINAL_THREAD_ID { + return invariant( + command, + format!("Thread id '{thread_id}' is reserved for the server terminal."), + ); + } + Ok(()) +} + fn invariant(command: &OrchestrationCommand, detail: String) -> Result { Err(OrchestrationError::Invariant { command_type: command.command_type().to_owned(), @@ -9295,6 +9375,7 @@ impl OrchestrationCommand { Self::ThreadArchive { .. } => "thread.archive", Self::ThreadUnarchive { .. } => "thread.unarchive", Self::ThreadMetaUpdate { .. } => "thread.meta.update", + Self::ThreadRetiredModelClear { .. } => "thread.retired-model.clear", Self::ThreadRuntimeModeSet { .. } => "thread.runtime-mode.set", Self::ThreadInteractionModeSet { .. } => "thread.interaction-mode.set", Self::ThreadTurnStart { .. } => "thread.turn.start", @@ -9335,6 +9416,7 @@ impl OrchestrationCommand { | Self::ThreadArchive { command_id, .. } | Self::ThreadUnarchive { command_id, .. } | Self::ThreadMetaUpdate { command_id, .. } + | Self::ThreadRetiredModelClear { command_id, .. } | Self::ThreadRuntimeModeSet { command_id, .. } | Self::ThreadInteractionModeSet { command_id, .. } | Self::ThreadTurnStart { command_id, .. } @@ -9372,7 +9454,8 @@ impl OrchestrationCommand { | Self::ThreadDelete { .. } | Self::ThreadArchive { .. } | Self::ThreadUnarchive { .. } - | Self::ThreadMetaUpdate { .. } => None, + | Self::ThreadMetaUpdate { .. } + | Self::ThreadRetiredModelClear { .. } => None, Self::ProjectCreate { created_at, .. } | Self::ThreadCreate { created_at, .. } | Self::ThreadRuntimeModeSet { created_at, .. } @@ -9415,6 +9498,7 @@ impl OrchestrationCommand { | Self::ThreadArchive { thread_id, .. } | Self::ThreadUnarchive { thread_id, .. } | Self::ThreadMetaUpdate { thread_id, .. } + | Self::ThreadRetiredModelClear { thread_id, .. } | Self::ThreadRuntimeModeSet { thread_id, .. } | Self::ThreadInteractionModeSet { thread_id, .. } | Self::ThreadTurnStart { thread_id, .. } @@ -9450,6 +9534,7 @@ impl OrchestrationCommand { | Self::WorktreeBranchReconcileResolved { .. } | Self::ThreadHistoryImport { .. } | Self::ThreadCompactionSettle { .. } + | Self::ThreadRetiredModelClear { .. } ) || matches!( self, Self::ThreadCompact { @@ -11602,6 +11687,42 @@ mod tests { } } + #[tokio::test] + async fn a_thread_cannot_take_the_server_terminal_thread_id() { + let (engine, _host_id) = delivery_engine(TestHooks::default()).await; + let mut create = side_chat_create("reserved", "server-terminal", None, None); + if let OrchestrationCommand::ThreadCreate { side_chat, .. } = &mut create { + *side_chat = false; + } + let turn = serde_json::from_value::(json!({ + "type":"thread.turn.start", "commandId":"reserved-turn", + "threadId":"server-terminal", + "message":{"messageId":"reserved-message","role":"user","text":"hi","attachments":[]}, + "bootstrap":{"createThread":{ + "projectId":"delivery-project", "title":"Reserved", + "modelSelection":{"instanceId":"codex","model":"gpt-5"}, + "runtimeMode":"full-access", "interactionMode":"default", + "branch":null, "worktreePath":null, "createdAt":"2026-11-02T00:00:01Z" + }}, + "createdAt":"2026-11-02T00:00:01Z" + })) + .expect("bootstrap command"); + for command in [create, turn] { + assert_eq!( + invariant_detail(engine.dispatch(command).await), + "Thread id 'server-terminal' is reserved for the server terminal." + ); + } + assert!( + engine + .repositories() + .get_thread("server-terminal".to_owned()) + .await + .expect("thread read") + .is_none() + ); + } + #[tokio::test] async fn side_chat_marker_requires_a_panel_with_a_host() { let (engine, host_id) = delivery_engine(TestHooks::default()).await; @@ -14653,7 +14774,7 @@ mod tests { .expect("default thread"); assert_eq!( default_thread.model_selection, - json!({"instanceId":"codex","model":"gpt-5.4"}) + json!({"instanceId":"codex","model":"auto"}) ); assert_eq!( result.thread_id.as_deref(), diff --git a/apps/server/src/orchestration/mod.rs b/apps/server/src/orchestration/mod.rs index 7f67f64994..af7b5d5b9b 100644 --- a/apps/server/src/orchestration/mod.rs +++ b/apps/server/src/orchestration/mod.rs @@ -9,9 +9,9 @@ pub use delivery::{ }; pub(crate) use engine::{AskRecoveryHold, EXTERNALLY_RESUMABLE_PROVIDERS}; pub use engine::{ - EngineOptions, OrchestrationCommand, OrchestrationEngine, OrchestrationError, Snapshot, - load_capped_shell_snapshot, load_shell_snapshot, load_snapshot, load_thread_snapshot, - shell_rows_snapshot, + EngineOptions, OrchestrationCommand, OrchestrationEngine, OrchestrationError, + RETIRED_MODEL_ALREADY_REPLACED, Snapshot, load_capped_shell_snapshot, load_shell_snapshot, + load_snapshot, load_thread_snapshot, shell_rows_snapshot, }; pub use process_ownership::StartupProcessOwnership; diff --git a/apps/server/src/production/agent_sessions_rpc.rs b/apps/server/src/production/agent_sessions_rpc.rs index 932daf963e..30be86bc22 100644 --- a/apps/server/src/production/agent_sessions_rpc.rs +++ b/apps/server/src/production/agent_sessions_rpc.rs @@ -48,7 +48,8 @@ const SOURCES: [(AgentSessionProvider, &str); 2] = [ ]; /// Mirrors `DEFAULT_MODEL_BY_PROVIDER` in `packages/contracts/src/model.ts`. const CLAUDE_DEFAULT_MODEL: &str = "claude-sonnet-5"; -const CODEX_DEFAULT_MODEL: &str = "gpt-5.4"; +/// No chosen model: Codex runs its own recommended one. +const CODEX_DEFAULT_MODEL: &str = crate::provider::codex::model::AUTO_MODEL; const IMPORTED_RUNTIME_MODE: &str = "full-access"; const USED_BEFORE_IMPORT: &str = "This session's thread was used before its import finished, so it keeps its own conversation."; diff --git a/apps/server/src/production/control.rs b/apps/server/src/production/control.rs index 32fa034bf1..f4d8d8c836 100644 --- a/apps/server/src/production/control.rs +++ b/apps/server/src/production/control.rs @@ -36,6 +36,9 @@ use crate::{ }; const MAX_KEYBINDINGS: usize = 256; +/// Internal to the config event channel: each `subscribeServerConfig` stream replaces it +/// with a snapshot built in its own order, so no client ever receives it. +const CONFIG_SNAPSHOT_REFRESH_EVENT: &str = "internal.configSnapshotRefresh"; const PROVIDER_REFRESH_TTL: Duration = Duration::from_secs(5 * 60); const PROVIDER_PROBE_TIMESTAMP_PATHS: &[&[&str]] = &[&["checkedAt"], &["versionAdvisory", "checkedAt"]]; @@ -324,6 +327,10 @@ pub struct NativeServerControl { mcp_server: watch::Sender, settings_update_lock: Arc>, settings_generation: Arc, + /// Bumped under the provider list's write lock whenever the list changes. + providers_version: Arc, + /// Bumped under the keybinding rules' write lock at each keybindings write. + keybindings_version: Arc, agent_activity_handler: AgentActivityHandlerSlot, next_provider_probe_sequence: Arc, latest_committed_provider_probe_sequence: Arc, @@ -362,6 +369,8 @@ pub struct NativeServerControl { full_provider_refresh_running: Arc, provider_refresh_state: Arc>, activity_protocol_registered: Arc, + /// Cleared by the startup Git version read when Git is older than 2.38. + merge_into_git_supported: Arc, config_events: broadcast::Sender, trace_diagnostics: TraceDiagnosticsStore, } @@ -391,6 +400,22 @@ impl NativeServerControl { config: ServerConfig, auth_descriptor: Value, trace_diagnostics: TraceDiagnosticsStore, + ) -> Self { + // Unit tests never read the host's Git version: it decides a capability they assert. + #[cfg(test)] + let git = crate::git::manager::merge::tests::UNIT_TEST_STARTUP_GIT + .1 + .clone(); + #[cfg(not(test))] + let git = crate::git::GitRepository::default(); + Self::with_merge_into_git_probe(config, auth_descriptor, trace_diagnostics, git).await + } + + async fn with_merge_into_git_probe( + config: ServerConfig, + auth_descriptor: Value, + trace_diagnostics: TraceDiagnosticsStore, + git: crate::git::GitRepository, ) -> Self { let state_directory = config.state_dir(); let settings_path = state_directory.join("settings.json"); @@ -437,7 +462,7 @@ impl NativeServerControl { // Nothing subscribes yet, so the tools' publish during startup reaches no one. *providers.write().await = probe_startup_inventory(&settings, &cwd, &provider_maintenance, &tools).await; - Self { + let control = Self { config, auth_descriptor, state_directory, @@ -452,6 +477,8 @@ impl NativeServerControl { mcp_server, settings_update_lock: Arc::new(Mutex::new(())), settings_generation: Arc::new(AtomicU64::new(0)), + providers_version: Arc::new(AtomicU64::new(0)), + keybindings_version: Arc::new(AtomicU64::new(0)), agent_activity_handler: AgentActivityHandlerSlot::default(), next_provider_probe_sequence: Arc::new(AtomicU64::new(0)), latest_committed_provider_probe_sequence: Arc::new(AtomicU64::new(0)), @@ -492,9 +519,36 @@ impl NativeServerControl { std::sync::Mutex::new(ProviderRefreshState::default()), ), activity_protocol_registered: Arc::new(AtomicBool::new(false)), + merge_into_git_supported: Arc::new(AtomicBool::new(true)), config_events, trace_diagnostics, - } + }; + control.spawn_merge_into_git_probe(git); + control + } + + /// Reads the Git version once, off the startup path, so the descriptor can stop + /// advertising merge-into on a Git too old for it. Until it answers, merge-into stays on. + fn spawn_merge_into_git_probe(&self, repository: crate::git::GitRepository) { + let control = self.clone(); + let cwd = PathBuf::from(current_directory(&self.config)); + self.capability_tasks.spawn(async move { + let result = crate::git::manager::merge::git_supports_merge_into( + &repository, + &cwd, + &control.capability_shutdown, + ) + .await; + let previous = control + .merge_into_git_supported + .swap(result, Ordering::AcqRel); + // A client that subscribed before the probe answered holds the old descriptor. + // A snapshot built here could carry settings older than a `settingsUpdated` + // published while it was built, so each subscriber builds it in stream order. + if previous != result { + control.publish(json!({ "type": CONFIG_SNAPSHOT_REFRESH_EVENT })); + } + }); } /// Marks the structured activity protocol ready after the production registry @@ -504,29 +558,71 @@ impl NativeServerControl { .store(true, Ordering::Release); } + fn environment(&self) -> Value { + environment_descriptor( + &self.config, + self.activity_protocol_registered.load(Ordering::Acquire), + self.merge_into_git_supported.load(Ordering::Acquire), + ) + } + pub async fn config_snapshot(&self) -> Value { let settings = self.settings.read().await.clone(); - let rules = self.keybinding_rules.read().await.clone(); - let issues = self.keybinding_issues.read().await.clone(); - let providers = self.providers.read().await.clone(); + self.config_snapshot_with(settings, 0).await.0 + } + + /// A snapshot with the version of each part it holds, for a config stream to skip every + /// later event that the snapshot already holds or that is older than it. + async fn versioned_config_snapshot(&self) -> (Value, ConfigVersions) { + let (generation, settings) = self.settings_snapshot().await; + self.config_snapshot_with(settings, generation).await + } + + /// Each part is read with its version under the lock its writers bump that version in. + async fn config_snapshot_with( + &self, + settings: Value, + generation: u64, + ) -> (Value, ConfigVersions) { + let (rules, issues, keybindings) = { + let rules = self.keybinding_rules.read().await; + let issues = self.keybinding_issues.read().await.clone(); + ( + rules.clone(), + issues, + self.keybindings_version.load(Ordering::Acquire), + ) + }; + let (providers, provider_version) = { + let providers = self.providers.read().await; + ( + providers.clone(), + self.providers_version.load(Ordering::Acquire), + ) + }; + let (tools, tool_version) = self.tools.snapshots_with_version(); let cwd = current_directory(&self.config); - json!({ - "environment": environment_descriptor( - &self.config, - self.activity_protocol_registered.load(Ordering::Acquire), - ), + let snapshot = json!({ + "environment": self.environment(), "auth": self.auth_descriptor, "cwd": cwd, "keybindingsConfigPath": self.keybindings_path.to_string_lossy(), "keybindings": keybindings::resolve(&rules), "issues": issues, "providers": providers, - "tools": self.tools.snapshots(), + "tools": tools, "availableEditors": available_editors(), "observability": observability_snapshot(&self.state_directory), "settings": settings, "mcpLaunch": mcp_launch(&self.config), - }) + }); + let versions = ConfigVersions { + settings: generation, + keybindings, + providers: provider_version, + tools: tool_version, + }; + (snapshot, versions) } pub(crate) fn automatic_git_fetch_interval_signal(&self) -> watch::Sender { @@ -634,6 +730,33 @@ impl NativeServerControl { agent_activity_enabled(¤t, AgentActivitySource::Terminal), ), ]; + // A write that owns some providers' session defaults sets or removes only those, so a + // default another window committed meanwhile survives a map built from an older copy. + if let (Some(owned), Some(written)) = ( + payload + .get("ownedProviderSessionDefaults") + .and_then(Value::as_array), + patch + .get("providerSessionDefaults") + .and_then(Value::as_object), + ) { + let mut merged = current + .get("providerSessionDefaults") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + for provider in owned.iter().filter_map(Value::as_str) { + match written.get(provider) { + Some(default) => { + merged.insert(provider.to_owned(), default.clone()); + } + None => { + merged.remove(provider); + } + } + } + patch["providerSessionDefaults"] = Value::Object(merged); + } let mut next = current; apply_settings_patch(&mut next, patch); validate_settings_document(&next) @@ -776,6 +899,8 @@ impl NativeServerControl { "version": 1, "type": "settingsUpdated", "payload": { "settings": next.clone() }, + // Read and removed by each config stream before it sends the event. + "sectionVersion": generation, })); drop(update_guard); // Once settings are committed, their inventory refresh must also survive @@ -1034,6 +1159,9 @@ impl NativeServerControl { self.provider_maintenance.overlay_update_state(provider); changed |= provider.get("updateState") != previous.as_ref(); } + if changed { + self.providers_version.fetch_add(1, Ordering::AcqRel); + } let snapshot = providers.clone(); drop(providers); if changed { @@ -1657,15 +1785,21 @@ impl NativeServerControl { .iter() .zip(&merged) .any(|(current, next)| !provider_snapshot_content_eq(current, next)); + // Every write is a new version, timestamps included: a manual refresh publishes them. + self.providers_version.fetch_add(1, Ordering::AcqRel); *current = merged; (current.clone(), changed) } + /// Callers hold `settings_update_lock` across the write and this publication, so the + /// version read here is the one that write made. fn publish_provider_snapshots(&self, providers: &[Value]) { self.publish(json!({ "version": 1, "type": "providerStatuses", "payload": { "providers": providers }, + // Read and removed by each config stream before it sends the event. + "sectionVersion": self.providers_version.load(Ordering::Acquire), })); } @@ -1791,10 +1925,13 @@ impl NativeServerControl { .map_err(|error| keybindings_error(&self.keybindings_path, &error.to_string()))?; self.keybinding_issues.write().await.clear(); let result = json!({ "keybindings": keybindings::resolve(&rules), "issues": [] }); + let version = self.keybindings_version.fetch_add(1, Ordering::AcqRel) + 1; self.publish(json!({ "version": 1, "type": "keybindingsUpdated", "payload": result.clone(), + // Read and removed by each config stream before it sends the event. + "sectionVersion": version, })); Ok(result) } @@ -1969,10 +2106,11 @@ impl NativeServerControl { .discover_provider_capabilities(payload, CancellationToken::new()) .await { - let reason = error.get("reason").and_then(Value::as_str); + // The reason can carry provider error text that names skills. + let tag = error.get("_tag").and_then(Value::as_str); tracing::warn!( instance_id = %key.0, - reason = reason.unwrap_or_default(), + tag = tag.unwrap_or_default(), "background provider capability refresh failed" ); } @@ -2099,12 +2237,16 @@ impl ProductionServerControl for NativeServerControl { FullProviderRefreshTrigger::Subscription, ); let mut updates = control.config_events.subscribe(); + // The config as this stream's client holds it, so a capability change + // can be sent without moving any other part of it, and the version of + // each part it holds, so no event older than it is sent after it. + let (mut sent, mut held) = control.versioned_config_snapshot().await; if send_event( &sender, json!({ "version": 1, "type": "snapshot", - "config": control.config_snapshot().await, + "config": sent.clone(), }), ) .await @@ -2116,12 +2258,82 @@ impl ProductionServerControl for NativeServerControl { tokio::select! { () = cancellation.cancelled() => return, event = updates.recv() => match event { - Ok(event) => { + Ok(mut event) => { + if !held.advance(&mut event) { + continue; + } + // The tools publisher copies the provider list outside the + // lock provider writers publish under, so that copy can be + // older than the list already sent. + if event["type"] == "providerStatuses" + && event["payload"].get("tools").is_some() + { + event["payload"]["providers"] = sent["providers"].clone(); + } + // Only the environment changed: everything else is what + // this stream already sent, so a settingsUpdated still + // queued behind the marker never lands on newer settings. + let event = if event["type"] == CONFIG_SNAPSHOT_REFRESH_EVENT { + let environment = control.environment(); + // Already sent, as when the probe answered before this + // stream's first snapshot was built. + if sent["environment"] == environment { + continue; + } + sent["environment"] = environment; + json!({ + "version": 1, + "type": "snapshot", + "config": sent.clone(), + }) + } else { + // A manual provider refresh republishes the whole provider + // list even when nothing in it changed. + if !config_stream_event_changes(&sent, &event) { + continue; + } + apply_config_stream_event(&mut sent, &event); + event + }; if send_event(&sender, event).await.is_err() { return; } } - Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Lagged(_)) => { + // Dropped events can include a capability marker: send the + // whole config again. Resubscribing first skips the retained + // events older than it, and anything after it is newer. + updates = updates.resubscribe(); + let (current, versions) = + control.versioned_config_snapshot().await; + // A dropped settingsUpdated can hold a rotated secret, which + // redacts to the same settings. The client refreshes provider + // capabilities on that event, never on equal settings. + let settings_hidden = versions.settings != held.settings + && sent["settings"] == current["settings"]; + held = versions; + if !config_content_eq(&sent, ¤t) { + sent = current; + let snapshot = json!({ + "version": 1, + "type": "snapshot", + "config": sent.clone(), + }); + if send_event(&sender, snapshot).await.is_err() { + return; + } + } + if settings_hidden { + let event = json!({ + "version": 1, + "type": "settingsUpdated", + "payload": { "settings": sent["settings"].clone() }, + }); + if send_event(&sender, event).await.is_err() { + return; + } + } + } Err(broadcast::error::RecvError::Closed) => return, } } @@ -2136,8 +2348,13 @@ impl ProductionServerControl for NativeServerControl { .unwrap_or("BiBCode"); let activity_protocol_registered = control.activity_protocol_registered.load(Ordering::Acquire); - let environment = - environment_descriptor(&control.config, activity_protocol_registered); + let merge_into_git_supported = + control.merge_into_git_supported.load(Ordering::Acquire); + let environment = environment_descriptor( + &control.config, + activity_protocol_registered, + merge_into_git_supported, + ); if send_event( &sender, json!({ @@ -2167,6 +2384,7 @@ impl ProductionServerControl for NativeServerControl { "environment": environment_descriptor( &control.config, activity_protocol_registered, + merge_into_git_supported, ), }, }), @@ -2185,6 +2403,95 @@ impl ProductionServerControl for NativeServerControl { } } +/// The version of each config part a stream's client holds. Every versioned event carries its +/// part's version in `sectionVersion`, taken where its writer bumped it. +#[derive(Clone, Copy, Debug)] +struct ConfigVersions { + settings: u64, + keybindings: u64, + providers: u64, + tools: u64, +} + +impl ConfigVersions { + /// Removes the event's version and records it; false when the client already holds that + /// part at this version or a newer one, so the event must not be sent. + fn advance(&mut self, event: &mut Value) -> bool { + let Some(version) = event + .as_object_mut() + .and_then(|event| event.remove("sectionVersion")) + .and_then(|version| version.as_u64()) + else { + return true; + }; + let held = match event["type"].as_str() { + Some("settingsUpdated") => &mut self.settings, + Some("keybindingsUpdated") => &mut self.keybindings, + Some("providerStatuses") if event["payload"].get("tools").is_some() => &mut self.tools, + Some("providerStatuses") => &mut self.providers, + _ => return true, + }; + if version <= *held { + return false; + } + *held = version; + true + } +} + +/// Applies a config stream event the way a client does: a snapshot replaces the config, and +/// each update replaces the part it names. +fn apply_config_stream_event(config: &mut Value, event: &Value) { + let payload = &event["payload"]; + match event["type"].as_str() { + Some("snapshot") => *config = event["config"].clone(), + Some("settingsUpdated") => config["settings"] = payload["settings"].clone(), + Some("keybindingsUpdated") => { + config["keybindings"] = payload["keybindings"].clone(); + config["issues"] = payload["issues"].clone(); + } + Some("providerStatuses") => { + config["providers"] = payload["providers"].clone(); + if let Some(tools) = payload.get("tools") { + config["tools"] = tools.clone(); + } + } + _ => {} + } +} + +/// Whether two configs differ only in provider probe timestamps, which are never published on +/// their own either. +fn config_content_eq(sent: &Value, current: &Value) -> bool { + let (Value::Object(sent), Value::Object(current)) = (sent, current) else { + return sent == current; + }; + sent.len() == current.len() + && sent + .iter() + .all(|(key, value)| match (key.as_str(), current.get(key)) { + ("providers", Some(Value::Array(next))) => value.as_array().is_some_and(|held| { + held.len() == next.len() + && held + .iter() + .zip(next) + .all(|(held, next)| provider_snapshot_content_eq(held, next)) + }), + (_, next) => next == Some(value), + }) +} + +/// Whether a provider list event would change the config a client holds. Every other event is +/// sent as published. +fn config_stream_event_changes(config: &Value, event: &Value) -> bool { + let payload = &event["payload"]; + event["type"] != "providerStatuses" + || config["providers"] != payload["providers"] + || payload + .get("tools") + .is_some_and(|tools| config["tools"] != *tools) +} + async fn send_event( sender: &mpsc::Sender, Value>>, event: Value, @@ -2699,7 +3006,7 @@ fn apply_settings_defaults(settings: &mut Value) { "addProjectBaseDirectory": "", "textGenerationModelSelection": { "instanceId": "codex", - "model": "gpt-5.4-mini", + "model": "auto", }, "providers": crate::server_settings::built_in_provider_defaults(), "providerInstances": {}, @@ -2890,7 +3197,11 @@ fn current_directory(config: &ServerConfig) -> String { .into_owned() } -fn environment_descriptor(config: &ServerConfig, activity_protocol_registered: bool) -> Value { +fn environment_descriptor( + config: &ServerConfig, + activity_protocol_registered: bool, + merge_into_git_supported: bool, +) -> Value { // Built apart from the descriptor: one literal holding both exceeds `json!`'s recursion limit. let mut capabilities = json!({ "repositoryIdentity": true, @@ -2901,7 +3212,7 @@ fn environment_descriptor(config: &ServerConfig, activity_protocol_registered: b "gitManagerCommitOperations": true, "gitManagerBranchSyncOperations": true, "gitManagerStashMergeOperations": true, - "gitManagerMergeIntoOperations": true, + "gitManagerMergeIntoOperations": merge_into_git_supported, "gitManagerPartialStaging": true, "gitManagerRewriteOperations": true, "gitManagerTagOperations": true, @@ -2939,6 +3250,7 @@ fn environment_descriptor(config: &ServerConfig, activity_protocol_registered: b capabilities["terminalUserInputClaim"] = json!(true); capabilities["agentMessaging"] = json!(true); capabilities["sendRequests"] = json!(true); + capabilities["readOnlyCodexReviews"] = json!(true); capabilities["terminalSizeHandOver"] = json!(true); // A flag is advertised only when every method it promises is registered. capabilities["pipelinesReads"] = @@ -3376,6 +3688,15 @@ mod tests { } async fn scheduler_control(temp: &tempfile::TempDir) -> NativeServerControl { + let (_, git) = crate::git::manager::merge::tests::version_runner("git version 2.38.0\n"); + scheduler_control_with_git(temp, git).await + } + + /// `scheduler_control` with the Git the startup version probe reads. + async fn scheduler_control_with_git( + temp: &tempfile::TempDir, + git: crate::git::GitRepository, + ) -> NativeServerControl { let config = running_test_config(temp.path()); let settings_path = config.state_dir().join("settings.json"); let missing_binary = missing_provider_executable(temp); @@ -3411,7 +3732,15 @@ mod tests { ) .await .expect("write settings"); - NativeServerControl::new(config, json!({"policy":"test"})).await + let trace_diagnostics = + TraceDiagnosticsStore::new(config.state_dir().join("logs/server.trace.ndjson")); + NativeServerControl::with_merge_into_git_probe( + config, + json!({"policy":"test"}), + trace_diagnostics, + git, + ) + .await } async fn control_with_stub_tool( @@ -3871,6 +4200,111 @@ mod tests { assert!(error["reason"].as_str().unwrap().contains("shutting down")); } + /// In a process of its own, so no sibling test can turn a callsite off for this capture. + #[cfg(unix)] + #[tokio::test] + async fn a_failed_background_capability_refresh_keeps_catalog_content_out_of_the_log() { + let Some(child) = crate::test_support::in_own_process( + "production::control::tests::a_failed_background_capability_refresh_keeps_catalog_content_out_of_the_log", + ) else { + return; + }; + #[derive(Clone, Default)] + struct Captured(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(()) + } + } + const SENTINEL: &str = "sentinel-skill-name"; + 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 temp = tempfile::tempdir().unwrap(); + let control = scheduler_control(&temp).await; + let sandbox = crate::test_support::TestSandbox::new("capability-refresh-log"); + let binary = sandbox.executable_script( + "codex", + &format!( + r#" +while IFS= read -r request; do + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$request" in + *'"method":"initialized"'*) ;; + *'"method":"skills/list"'*) printf '{{"id":%s,"error":{{"code":-32000,"message":"cannot load {SENTINEL}"}}}}\n' "$id" ;; + *) printf '{{"id":%s,"result":{{}}}}\n' "$id" ;; + esac +done +"# + ), + "", + ); + let mut settings = control.settings.read().await.clone(); + settings["providerInstances"]["codex"]["config"]["binaryPath"] = json!(binary); + settings["providerInstances"]["codex"]["environment"] = + json!([{"name":"HOME","value":sandbox.root()}]); + tokio::fs::write( + &control.settings_path, + serde_json::to_vec(&settings).unwrap(), + ) + .await + .unwrap(); + let payload = json!({"instanceId":"codex","cwd":sandbox.root()}); + let key = CapabilityCache::key(&payload).unwrap(); + // A stale cached catalog answers at once and starts the refresh that fails. + control.capability_cache.lock().unwrap().store( + key, + control.settings_generation.load(Ordering::Acquire), + json!({"slashCommands":[],"skills":[],"agents":[],"issues":[]}), + ); + for entry in control + .capability_cache + .lock() + .unwrap() + .entries + .values_mut() + { + entry.stored_at = std::time::Instant::now() + .checked_sub(CAPABILITY_CACHE_FRESH * 2) + .unwrap(); + } + control + .call( + "server.getProviderCapabilities", + payload, + CancellationToken::new(), + ) + .await + .expect("the cached catalog answers"); + let text = || String::from_utf8(log.0.lock().unwrap().clone()).unwrap(); + tokio::time::timeout(Duration::from_secs(20), async { + while !text().contains("background provider capability refresh failed") { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("the refresh failure was logged:\n{}", text())); + control.shutdown_capability_discovery().await; + assert!( + !text().contains(SENTINEL), + "catalog content reached the log:\n{}", + text() + ); + child.complete(); + } + async fn mutable_provider_registry( version: &str, ) -> (Url, Arc>, Arc) { @@ -7542,6 +7976,51 @@ mod tests { assert_eq!(settings["automaticGitFetchInterval"], json!(0.1)); } + #[tokio::test] + async fn a_write_that_owns_one_session_default_keeps_another_windows_save() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let codex = json!({ "model": "gpt-5.4", "options": [] }); + let claude = json!({ "model": "claude-sonnet-4-6", "options": [] }); + let auto = json!({ "model": "auto", "options": [] }); + let update = async |request: Value| { + control + .call("server.updateSettings", request, CancellationToken::new()) + .await + .expect("settings update")["providerSessionDefaults"] + .clone() + }; + update(json!({ "patch": { "providerSessionDefaults": { "codex": codex } } })).await; + // Window B saves a Claude default. + update(json!({ + "patch": { "providerSessionDefaults": { "codex": codex, "claudeAgent": claude } }, + })) + .await; + + // Window A has not seen B's save yet and rewrites only its Codex default. + let saved = update(json!({ + "patch": { "providerSessionDefaults": { "codex": auto } }, + "ownedProviderSessionDefaults": ["codex"], + })) + .await; + assert_eq!(saved, json!({ "codex": auto, "claudeAgent": claude })); + + // An owned provider the map leaves out is removed; the rest stays. + let saved = update(json!({ + "patch": { "providerSessionDefaults": {} }, + "ownedProviderSessionDefaults": ["codex"], + })) + .await; + assert_eq!(saved, json!({ "claudeAgent": claude })); + + // Without the field the map still replaces the whole saved map, as older clients expect. + let saved = + update(json!({ "patch": { "providerSessionDefaults": { "codex": auto } } })).await; + assert_eq!(saved, json!({ "codex": auto })); + } + #[tokio::test] async fn settings_validation_preserves_open_unknown_keys_and_legacy_options() { #[cfg(feature = "hermetic-test-guard")] @@ -7598,11 +8077,601 @@ mod tests { ); } + #[tokio::test] + async fn the_git_probe_corrects_merge_into_without_rolling_back_a_newer_setting() { + let temp = tempfile::tempdir().expect("state directory"); + let (_, startup_git) = + crate::git::manager::merge::tests::version_runner("git version 2.38.0\n"); + let control = scheduler_control_with_git(&temp, startup_git).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = stream + .recv() + .await + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + let merge_into = |config: &Value| { + config["environment"]["capabilities"]["gitManagerMergeIntoOperations"].clone() + }; + assert_eq!(merge_into(&client), true); + + for (version, expected, setting) in [ + ("git version 2.37.9\n", false, false), + ("git version 2.38.0\n", true, true), + ] { + // Any snapshot built now waits on the keybindings after reading the settings. + let keybindings = control.keybinding_rules.write().await; + let (_, repository) = crate::git::manager::merge::tests::version_runner(version); + control.spawn_merge_into_git_probe(repository); + tokio::time::timeout(Duration::from_secs(5), async { + while control.merge_into_git_supported.load(Ordering::Acquire) != expected { + tokio::task::yield_now().await; + } + }) + .await + .expect("the probe answers"); + control + .update_settings(json!({"patch": {"enableChatAgentActivity": setting}})) + .await + .expect("settings update"); + drop(keybindings); + control.capability_tasks.wait().await; + + let server = control.config_snapshot().await; + assert_eq!(merge_into(&server), expected, "{version}"); + tokio::time::timeout(Duration::from_secs(5), async { + while client["settings"] != server["settings"] || merge_into(&client) != expected { + for event in stream.recv().await.expect("config stream").expect("events") { + apply_config_stream_event(&mut client, &event); + } + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "{version}: the client settled on enableChatAgentActivity {} and merge-into {}", + client["settings"]["enableChatAgentActivity"], + merge_into(&client) + ) + }); + } + cancellation.cancel(); + } + + #[tokio::test] + async fn a_delayed_config_stream_never_moves_settings_backward_on_a_capability_change() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = stream + .recv() + .await + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + // Fill the stream's output so it stops reading: everything after queues behind. + for _ in 0..12 { + control.publish(json!({ "type": "unit" })); + } + let (_, repository) = + crate::git::manager::merge::tests::version_runner("git version 2.37.9\n"); + control.spawn_merge_into_git_probe(repository); + control.capability_tasks.wait().await; + for prompt in ["first", "second"] { + control + .update_settings(json!({"patch": {"codeReviewPrompt": prompt}})) + .await + .expect("settings update"); + } + + let server = control.config_snapshot().await; + // Read everything the stream sends, until it has been quiet for a while. + let mut prompts = Vec::new(); + while let Ok(Some(chunk)) = + tokio::time::timeout(Duration::from_millis(500), stream.recv()).await + { + for event in chunk.expect("events") { + apply_config_stream_event(&mut client, &event); + prompts.push(client["settings"]["codeReviewPrompt"].clone()); + } + } + assert_eq!(client["settings"], server["settings"]); + assert_eq!(client["environment"], server["environment"]); + let second = prompts + .iter() + .position(|prompt| prompt == "second") + .expect("the second prompt arrives"); + assert!( + !prompts[second..].contains(&json!("first")), + "the prompt moved back: {prompts:?}" + ); + cancellation.cancel(); + } + + #[tokio::test] + async fn a_config_stream_that_lags_past_its_buffer_resynchronises_its_client() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = stream + .recv() + .await + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + // Fill the stream's output so it stops reading: everything after queues behind. + for _ in 0..12 { + control.publish(json!({ "type": "unit" })); + } + let (_, repository) = + crate::git::manager::merge::tests::version_runner("git version 2.37.9\n"); + control.spawn_merge_into_git_probe(repository); + control.capability_tasks.wait().await; + control + .update_settings(json!({"patch": {"codeReviewPrompt": "lagged"}})) + .await + .expect("settings update"); + // More than the broadcast holds: the marker and the settings update are dropped. + for _ in 0..64 { + control.publish(json!({ "type": "unit" })); + } + // Retained behind the lag, and older than any snapshot built after it. + for prompt in ["first", "second"] { + control + .update_settings(json!({"patch": {"codeReviewPrompt": prompt}})) + .await + .expect("settings update"); + } + + let server = control.config_snapshot().await; + let mut prompts = Vec::new(); + while let Ok(Some(chunk)) = + tokio::time::timeout(Duration::from_millis(500), stream.recv()).await + { + for event in chunk.expect("events") { + apply_config_stream_event(&mut client, &event); + prompts.push(client["settings"]["codeReviewPrompt"].clone()); + } + } + let second = prompts + .iter() + .position(|prompt| prompt == "second") + .expect("the second prompt arrives"); + assert!( + !prompts[second..].contains(&json!("first")), + "the prompt moved back: {prompts:?}" + ); + assert_eq!( + client["environment"]["capabilities"]["gitManagerMergeIntoOperations"], + false + ); + assert_eq!(client["environment"], server["environment"]); + assert_eq!(client["settings"], server["settings"]); + cancellation.cancel(); + } + + /// Reads everything a config stream sends until it has been quiet for a while, applying each + /// event to `client`, and returns the events. + async fn drain_config_stream(stream: &mut JsonStream, client: &mut Value) -> Vec { + let mut events = Vec::new(); + while let Ok(Some(chunk)) = + tokio::time::timeout(Duration::from_millis(500), stream.recv()).await + { + for event in chunk.expect("events") { + apply_config_stream_event(client, &event); + events.push(event); + } + } + events + } + + /// A subscribed stream past its first snapshot and its own provider refresh. + async fn settled_config_stream( + control: &NativeServerControl, + cancellation: &CancellationToken, + ) -> (JsonStream, Value) { + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = stream + .recv() + .await + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + tokio::time::timeout(Duration::from_secs(10), async { + while control + .full_provider_refresh_running + .load(Ordering::Acquire) + { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the subscription's provider refresh settles"); + drain_config_stream(&mut stream, &mut client).await; + (stream, client) + } + + #[tokio::test] + async fn a_config_resync_never_replays_an_inventory_older_than_its_snapshot() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let (mut stream, mut client) = settled_config_stream(&control, &cancellation).await; + let publish_inventory = async |mark: &str| { + let (providers, _) = control + .merge_provider_snapshots( + vec![provider_inventory::ProviderProbeResult { + snapshot: json!({ + "instanceId": "resync-probe", + "driver": "codex", + "message": mark, + }), + rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, + models_authoritative: false, + }], + true, + ) + .await; + control.publish_provider_snapshots(&providers); + }; + let mark = |config: &Value| { + config["providers"] + .as_array() + .and_then(|providers| { + providers + .iter() + .find(|provider| provider["instanceId"] == "resync-probe") + }) + .map(|provider| provider["message"].clone()) + .unwrap_or(Value::Null) + }; + + // Fill the stream's output so it stops reading, then lag it past the broadcast. + for _ in 0..12 { + control.publish(json!({ "type": "unit" })); + } + // The resync's snapshot reads the settings, then waits here before the providers. + let keybindings = control.keybinding_rules.write().await; + for _ in 0..64 { + control.publish(json!({ "type": "unit" })); + } + drain_config_stream(&mut stream, &mut client).await; + publish_inventory("A").await; + publish_inventory("B").await; + drop(keybindings); + + let mut marks = Vec::new(); + for event in drain_config_stream(&mut stream, &mut Value::Null).await { + apply_config_stream_event(&mut client, &event); + marks.push(mark(&client)); + } + let latest = marks + .iter() + .position(|mark| mark == "B") + .expect("the newer inventory arrives"); + assert!( + !marks[latest..].contains(&json!("A")), + "the inventory moved back: {marks:?}" + ); + assert_eq!(mark(&client), "B"); + cancellation.cancel(); + } + + /// Publishes an inventory whose `ordered-probe` row carries `mark`, as a provider writer does. + async fn publish_marked_inventory(control: &NativeServerControl, mark: u64) { + let (providers, _) = control + .merge_provider_snapshots( + vec![provider_inventory::ProviderProbeResult { + snapshot: json!({ + "instanceId": "ordered-probe", + "driver": "codex", + "message": mark, + }), + rich_metadata: provider_inventory::RichMetadataOutcome::NotRequested, + models_authoritative: false, + }], + true, + ) + .await; + control.publish_provider_snapshots(&providers); + } + + fn inventory_mark(config: &Value) -> Option { + config["providers"] + .as_array()? + .iter() + .find(|provider| provider["instanceId"] == "ordered-probe")?["message"] + .as_u64() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_config_stream_gets_its_snapshot_while_publications_never_stop() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let publishing = CancellationToken::new(); + let publisher = tokio::spawn({ + let control = control.clone(); + let publishing = publishing.clone(); + async move { + let mut mark = 0; + while !publishing.is_cancelled() { + mark += 1; + publish_marked_inventory(&control, mark).await; + tokio::task::yield_now().await; + } + } + }); + // Other events never pause either, so no snapshot build ever sees a quiet moment. + let spamming = Arc::new(AtomicBool::new(true)); + let spammer = std::thread::spawn({ + let events = control.config_events.clone(); + let spamming = spamming.clone(); + move || { + while spamming.load(Ordering::Acquire) { + let _ = events.send(json!({ "type": "unit" })); + std::thread::sleep(Duration::from_micros(100)); + } + } + }); + // Publications are under way before the subscription and never pause. + loop { + let providers = control.providers.read().await.clone(); + if inventory_mark(&json!({ "providers": providers })).is_some() { + break; + } + tokio::task::yield_now().await; + } + let cancellation = CancellationToken::new(); + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = tokio::time::timeout(Duration::from_secs(5), stream.recv()) + .await + .expect("the snapshot arrives while publications go on") + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + let mut marks = Vec::from_iter(inventory_mark(&client)); + let deadline = tokio::time::Instant::now() + Duration::from_millis(500); + while let Ok(Some(chunk)) = tokio::time::timeout_at(deadline, stream.recv()).await { + for event in chunk.expect("events") { + apply_config_stream_event(&mut client, &event); + marks.extend(inventory_mark(&client)); + } + } + publishing.cancel(); + publisher.await.expect("publisher joins"); + spamming.store(false, Ordering::Release); + spammer.join().expect("spammer joins"); + assert!( + marks.windows(2).all(|pair| pair[0] <= pair[1]), + "the inventory moved back: {marks:?}" + ); + cancellation.cancel(); + } + + #[tokio::test] + async fn a_config_resync_never_replays_tools_older_than_its_snapshot() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let (mut stream, mut client) = settled_config_stream(&control, &cancellation).await; + let publish_tools = async |mark: &str| { + control + .tools + .publish_snapshots_for_tests(vec![ + json!({ "toolId": "ordered-tool", "message": mark }), + ]) + .await; + }; + let mark = |config: &Value| config["tools"][0]["message"].clone(); + + // Fill the stream's output so it stops reading, then lag it past the broadcast. + for _ in 0..12 { + control.publish(json!({ "type": "unit" })); + } + // The resync's snapshot reads the settings, then waits here before the tools. + let keybindings = control.keybinding_rules.write().await; + for _ in 0..64 { + control.publish(json!({ "type": "unit" })); + } + drain_config_stream(&mut stream, &mut client).await; + publish_tools("A").await; + publish_tools("B").await; + drop(keybindings); + + let mut marks = Vec::new(); + for event in drain_config_stream(&mut stream, &mut Value::Null).await { + apply_config_stream_event(&mut client, &event); + marks.push(mark(&client)); + } + let latest = marks + .iter() + .position(|mark| mark == "B") + .expect("the newer tools arrive"); + assert!( + !marks[latest..].contains(&json!("A")), + "the tools moved back: {marks:?}" + ); + assert_eq!(mark(&client), "B"); + cancellation.cancel(); + } + + #[tokio::test] + async fn a_config_resync_keeps_a_rotated_secret_as_a_capability_change() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let rotate = async |value: &str| { + let mut instances = control.settings.read().await["providerInstances"].clone(); + instances["codex"]["environment"] = + json!([{ "name": "TOKEN", "value": value, "sensitive": true }]); + control + .update_settings(json!({ "patch": { "providerInstances": instances } })) + .await + .expect("settings update"); + }; + rotate("first").await; + let cancellation = CancellationToken::new(); + let (mut stream, mut client) = settled_config_stream(&control, &cancellation).await; + + // Fill the stream's output so it stops reading; the rotation is then dropped by a lag. + for _ in 0..12 { + control.publish(json!({ "type": "unit" })); + } + rotate("second").await; + for _ in 0..64 { + control.publish(json!({ "type": "unit" })); + } + + // The client refreshes provider capabilities when one of these reaches it + // (`capabilitiesMayHaveChanged` in packages/client-runtime/src/state/server.ts). + let mut capabilities_may_have_changed = false; + for event in drain_config_stream(&mut stream, &mut Value::Null).await { + capabilities_may_have_changed |= match event["type"].as_str() { + Some("settingsUpdated" | "providerStatuses") => true, + Some("snapshot") => { + event["config"]["providers"] != client["providers"] + || event["config"]["settings"] != client["settings"] + } + _ => false, + }; + apply_config_stream_event(&mut client, &event); + } + assert!( + capabilities_may_have_changed, + "the rotated secret never reached the client as a capability change" + ); + cancellation.cancel(); + } + + #[tokio::test] + async fn a_config_stream_sends_nothing_for_a_refresh_its_client_already_holds() { + let temp = tempfile::tempdir().expect("state directory"); + let control = scheduler_control(&temp).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + let cancellation = CancellationToken::new(); + let mut stream = control.subscribe("subscribeServerConfig", cancellation.clone()); + let mut client = stream + .recv() + .await + .expect("config stream") + .expect("snapshot")[0]["config"] + .clone(); + let mut sent = Vec::new(); + let mut drain = async |client: &mut Value, sent: &mut Vec| { + while let Ok(Some(chunk)) = + tokio::time::timeout(Duration::from_millis(500), stream.recv()).await + { + for event in chunk.expect("events") { + if event["type"] == "unit" { + continue; + } + let before = client.clone(); + apply_config_stream_event(client, &event); + assert_ne!( + *client, before, + "an event changed nothing: {}", + event["type"] + ); + sent.push(event["type"].clone()); + } + } + }; + // A capability marker and a provider list that change nothing, then a real change. + control.publish(json!({ "type": CONFIG_SNAPSHOT_REFRESH_EVENT })); + control.publish_provider_snapshots(&control.providers.read().await.clone()); + control + .update_settings(json!({"patch": {"codeReviewPrompt": "visible"}})) + .await + .expect("settings update"); + drain(&mut client, &mut sent).await; + assert!( + sent.contains(&json!("settingsUpdated")), + "the real change arrives: {sent:?}" + ); + // The subscription's own provider refresh is a real change: let it land first. + tokio::time::timeout(Duration::from_secs(10), async { + while control + .full_provider_refresh_running + .load(Ordering::Acquire) + { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the subscription's provider refresh settles"); + drain(&mut client, &mut sent).await; + // A lag past the buffer that dropped nothing the client lacks resynchronises silently. + sent.clear(); + for _ in 0..76 { + control.publish(json!({ "type": "unit" })); + } + drain(&mut client, &mut sent).await; + assert!(sent.is_empty(), "an unchanged resync was sent: {sent:?}"); + assert_eq!( + client["settings"], + control.config_snapshot().await["settings"] + ); + cancellation.cancel(); + } + + #[tokio::test] + async fn unit_tests_never_read_the_host_git_version_for_merge_into() { + let temp = tempfile::tempdir().expect("state directory"); + let calls = || { + crate::git::manager::merge::tests::UNIT_TEST_STARTUP_GIT + .0 + .calls + .load(std::sync::atomic::Ordering::SeqCst) + }; + let config = running_test_config(temp.path()); + hermetic_providers::write_hermetic_settings(&config.state_dir(), json!({})); + let control = NativeServerControl::new(config, json!({})).await; + control.capability_tasks.close(); + control.capability_tasks.wait().await; + // The constructor every unit test uses reads the unit-test Git, never the host's. + // The version is read once per repository, so earlier tests may have made the call. + assert!(calls() > 0, "the startup probe read another Git"); + assert_eq!( + control.config_snapshot().await["environment"]["capabilities"]["gitManagerMergeIntoOperations"], + true + ); + } + + #[test] + fn environment_descriptor_withdraws_merge_into_on_old_git() { + let temp = tempfile::tempdir().expect("state directory"); + let config = running_test_config(temp.path()); + for supported in [true, false] { + let descriptor = environment_descriptor(&config, false, supported); + assert_eq!( + descriptor["capabilities"]["gitManagerMergeIntoOperations"], + supported + ); + } + } + #[test] fn environment_descriptor_advertises_complete_worktree_catalog_surface() { let temp = tempfile::tempdir().expect("state directory"); let config = running_test_config(temp.path()); - let descriptor = environment_descriptor(&config, false); + let descriptor = environment_descriptor(&config, false, true); assert_eq!(descriptor["capabilities"]["repositoryIdentity"], true); assert_eq!(descriptor["capabilities"]["worktreeCatalog"], true); assert_eq!( @@ -7648,7 +8717,7 @@ mod tests { let temp = tempfile::tempdir().expect("state directory"); let mut config = running_test_config(temp.path()); config.boot_id = Some(uuid::Uuid::nil()); - let descriptor = environment_descriptor(&config, false); + let descriptor = environment_descriptor(&config, false, true); assert_eq!(descriptor["bootId"], "00000000-0000-0000-0000-000000000000"); assert_eq!(descriptor["capabilities"]["remoteUpdateControl"], true); assert_eq!(descriptor["capabilities"]["remoteUpdateProgress"], true); @@ -7668,6 +8737,8 @@ mod tests { assert_eq!(descriptor["capabilities"]["sendRequests"], true); assert_eq!(descriptor["capabilities"]["sideChats"], true); assert_eq!(descriptor["capabilities"]["codeReviews"], true); + // The web client words the Codex review guard line by this flag (#376). + assert_eq!(descriptor["capabilities"]["readOnlyCodexReviews"], true); assert_eq!(descriptor["capabilities"]["hostMetrics"], true); assert_eq!(descriptor["capabilities"]["threadDeleteOnlyIfUnused"], true); // `server.getConfig` carries this descriptor; a client downloads a remote @@ -7688,7 +8759,7 @@ mod tests { fn environment_descriptor_advertises_the_protocol_compatibility_window() { let temp = tempfile::tempdir().expect("state directory"); let config = running_test_config(temp.path()); - let descriptor = environment_descriptor(&config, false); + let descriptor = environment_descriptor(&config, false, true); assert_eq!(descriptor["remoteProtocolVersion"], 1); assert_eq!(descriptor["minCompatibleRemoteProtocol"], 1); } @@ -7711,7 +8782,7 @@ mod tests { let expected = prepared.storage_instance_id.to_string(); config.storage_instance_id = Some(prepared.storage_instance_id); - let descriptor = environment_descriptor(&config, true); + let descriptor = environment_descriptor(&config, true, true); assert_eq!(descriptor["storageInstanceId"], expected); let encoded = descriptor.to_string(); @@ -7752,14 +8823,15 @@ mod tests { assert!(!platform_os().is_empty()); assert!(!platform_arch().is_empty()); assert!( - environment_descriptor(&config, false)["capabilities"]["repositoryIdentity"] == true + environment_descriptor(&config, false, true)["capabilities"]["repositoryIdentity"] + == true ); assert_eq!( - environment_descriptor(&config, false)["capabilities"]["worktreeCatalog"], + environment_descriptor(&config, false, true)["capabilities"]["worktreeCatalog"], true ); assert_eq!( - environment_descriptor(&config, false)["capabilities"]["worktreeCatalogRefreshReason"], + environment_descriptor(&config, false, true)["capabilities"]["worktreeCatalogRefreshReason"], true ); let editors = available_editors(); diff --git a/apps/server/src/production/git_manager_rpc.rs b/apps/server/src/production/git_manager_rpc.rs index f0ba6467f9..fbe1104325 100644 --- a/apps/server/src/production/git_manager_rpc.rs +++ b/apps/server/src/production/git_manager_rpc.rs @@ -606,6 +606,7 @@ impl ConfiguredGitManagerRpcServices { input.pinned_tips.as_deref(), input.offset.unwrap_or(0), input.limit.unwrap_or(100), + input.fit_first_commit == Some(true), &cancellation, ) .await @@ -1372,6 +1373,8 @@ struct GitManagerGetCommitsInput { pinned_tips: Option>, offset: Option, limit: Option, + /// The client shows `changedFilesOmitted`, so a huge first commit may be cut (#390). + fit_first_commit: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] diff --git a/apps/server/src/production/orchestration_rpc.rs b/apps/server/src/production/orchestration_rpc.rs index a14fdc58d7..bf89d81a1f 100644 --- a/apps/server/src/production/orchestration_rpc.rs +++ b/apps/server/src/production/orchestration_rpc.rs @@ -6577,6 +6577,7 @@ mod tests { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, }) .await .expect("provider launches"); @@ -6703,6 +6704,7 @@ mod tests { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, }) .await .expect("provider launches"); diff --git a/apps/server/src/production/provider_inventory.rs b/apps/server/src/production/provider_inventory.rs index ae2b31d83a..f5c2263a7f 100644 --- a/apps/server/src/production/provider_inventory.rs +++ b/apps/server/src/production/provider_inventory.rs @@ -757,6 +757,7 @@ async fn probe_one_snapshot( "codex" => { if include_slow_capabilities && let Some(inventory) = probe_codex( + &definition.instance_id, &executable, cwd, &definition.custom_models, @@ -1179,7 +1180,7 @@ fn copy_non_empty_string(source: &Value, target: &mut Value, key: &str) { fn apply_agent_options(models: &mut [Value], agents: &[Value]) { let default_agent = agents .iter() - .find(|agent| agent["name"] == "claude") + .find(|agent| agent["name"] == crate::provider::claude::model::DEFAULT_AGENT) .or_else(|| agents.first()) .and_then(|agent| agent.get("name")) .and_then(Value::as_str); @@ -1391,7 +1392,37 @@ async fn run_command( }) } +/// Logs why a Codex inventory probe learned no sign-in type: the step and the kind of failure, +/// never the reply, the account or its email. A launch then cannot tell whether a stored model +/// is retired under a ChatGPT sign-in. +fn warn_codex_sign_in_unknown(instance_id: &str, step: &str, failure: &str) { + tracing::warn!( + instance_id, + step, + failure, + "the Codex inventory probe learned no sign-in type" + ); +} + +/// The step a Codex inventory probe failed at and the kind of failure, without the reply. +fn codex_probe_failure(error: &codex::runtime::RuntimeError) -> (String, String) { + use codex::ProtocolError; + use codex::runtime::RuntimeError; + match error { + RuntimeError::Protocol(ProtocolError::RemoteRequest { method, code, .. }) => { + (method.clone(), format!("error {code}")) + } + RuntimeError::Protocol(ProtocolError::Closed { .. }) => { + ("probe".to_owned(), "connection closed".to_owned()) + } + RuntimeError::Protocol(_) => ("probe".to_owned(), "protocol failure".to_owned()), + RuntimeError::InvalidPayload { .. } => ("probe".to_owned(), "invalid reply".to_owned()), + _ => ("probe".to_owned(), "failed".to_owned()), + } +} + async fn probe_codex( + instance_id: &str, executable: &Path, cwd: &Path, custom_models: &[String], @@ -1406,20 +1437,45 @@ async fn probe_codex( .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); - let mut child = supervised_command(command).spawn().ok()?; + // The launch error names local paths, so only the kind of failure is logged. + let Ok(mut child) = supervised_command(command).spawn() else { + warn_codex_sign_in_unknown(instance_id, "launch", "could not start"); + return None; + }; let stdout = child.stdout().take()?; let stdin = child.stdin().take()?; let stderr = child.stderr().take()?; let (connection, _incoming) = codex::JsonRpcConnection::spawn(stdout, stdin, stderr, codex::ConnectionConfig::default()); let cwd = cwd.to_string_lossy().into_owned(); - let result = timeout( + let result = match timeout( PROBE_TIMEOUT, codex::probe_provider(&connection, env!("CARGO_PKG_VERSION"), &cwd, custom_models), ) .await - .ok() - .and_then(Result::ok); + { + Ok(Ok(snapshot)) => { + let auth = codex_auth(&snapshot.account); + if auth.get("type").is_none() { + let failure = if auth["status"] == "authenticated" { + "no sign-in type in the reply" + } else { + "no account in the reply" + }; + warn_codex_sign_in_unknown(instance_id, "account/read", failure); + } + Some(snapshot) + } + Ok(Err(error)) => { + let (step, failure) = codex_probe_failure(&error); + warn_codex_sign_in_unknown(instance_id, &step, &failure); + None + } + Err(_) => { + warn_codex_sign_in_unknown(instance_id, "probe", "timed out"); + None + } + }; connection.close().await; stop_supervised_child(&mut *child).await; result @@ -2096,13 +2152,130 @@ mod tests { ); } + /// In a process of its own, so no sibling test can turn the callsite off for this capture. + #[cfg(unix)] + #[tokio::test] + async fn a_codex_probe_that_learns_no_sign_in_logs_why_without_the_account() { + let Some(child) = crate::test_support::in_own_process( + "production::provider_inventory::tests::a_codex_probe_that_learns_no_sign_in_logs_why_without_the_account", + ) 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::WARN) + .with_writer({ + let log = log.clone(); + move || log.clone() + }) + .finish(), + ); + const EMAIL: &str = "secret-person@example.test"; + let sandbox = crate::test_support::TestSandbox::new("codex-sign-in-log"); + // `account/read` answers with `$1`: an error, nothing at all, or a reply without account. + let fake = |name: &str, account_reply: &str| { + sandbox.executable_script( + name, + &format!( + r#" +while IFS= read -r request; do + id=$(printf '%s' "$request" | sed -n 's/.*"id":\([0-9]*\).*/\1/p') + case "$request" in + *'"method":"initialized"'*) ;; + *'"method":"account/read"'*) {account_reply} ;; + *'"method":"model/list"'*) printf '{{"id":%s,"result":{{"data":[{{"model":"gpt-6.2-sol","displayName":"gpt-6.2-sol","supportedReasoningEfforts":[{{"reasoningEffort":"medium"}}],"defaultReasoningEffort":"medium"}}],"nextCursor":null}}}}\n' "$id" ;; + *'"method":"skills/list"'*) printf '{{"id":%s,"result":{{"data":[]}}}}\n' "$id" ;; + *) printf '{{"id":%s,"result":{{}}}}\n' "$id" ;; + esac +done +"# + ), + "", + ) + }; + let refused = fake( + "codex-refused", + &format!( + r#"printf '{{"id":%s,"error":{{"code":-32001,"message":"cannot read {EMAIL}"}}}}\n' "$id""# + ), + ); + let silent = fake("codex-silent", ":"); + let no_account = fake( + "codex-no-account", + r#"printf '{"id":%s,"result":{"account":null,"requiresOpenaiAuth":false}}\n' "$id""#, + ); + // Resolves and is executable, but its interpreter does not exist, so it cannot start. + let unstartable = sandbox.path("codex-unstartable"); + crate::test_support::TestSandbox::write_executable( + &unstartable, + "#!/nonexistent/interpreter\n", + ); + let cwd = sandbox.root().to_path_buf(); + assert!( + probe_codex("codex-unstartable", &unstartable, &cwd, &[], &[]) + .await + .is_none() + ); + assert!( + probe_codex("codex-refused", &refused, &cwd, &[], &[]) + .await + .is_none() + ); + assert!( + probe_codex("codex-silent", &silent, &cwd, &[], &[]) + .await + .is_none() + ); + let answered = probe_codex("codex-no-account", &no_account, &cwd, &[], &[]) + .await + .is_some(); + let text = String::from_utf8(log.0.lock().unwrap().clone()).unwrap(); + assert!(answered, "{text}"); + + for (instance, step, failure) in [ + ("codex-unstartable", "launch", "could not start"), + ("codex-refused", "account/read", "error -32001"), + ("codex-silent", "probe", "timed out"), + ( + "codex-no-account", + "account/read", + "no account in the reply", + ), + ] { + assert!( + text.lines() + .any(|line| line.contains("learned no sign-in type") + && line.contains(&format!("instance_id=\"{instance}\"")) + && line.contains(&format!("step=\"{step}\"")) + && line.contains(&format!("failure=\"{failure}\""))), + "{instance}: {text}" + ); + } + assert!(!text.contains(EMAIL), "{text}"); + assert!(!text.contains("cannot read"), "{text}"); + child.complete(); + } + #[cfg(target_os = "linux")] #[test] fn codex_inventory_probe_ignores_appimage_environment() { check_inventory_probe_appimage_environment( "production::provider_inventory::tests::codex_inventory_probe_ignores_appimage_environment", |executable, cwd, environment| async move { - probe_codex(&executable, &cwd, &[], &environment) + probe_codex("codex", &executable, &cwd, &[], &environment) .await .is_some() }, diff --git a/apps/server/src/production/provider_runtime.rs b/apps/server/src/production/provider_runtime.rs index d6c8a7e254..6355caf8ba 100644 --- a/apps/server/src/production/provider_runtime.rs +++ b/apps/server/src/production/provider_runtime.rs @@ -185,6 +185,9 @@ pub struct ProviderLaunchRequest { /// The host of a side chat (#265), whose messages the side chat's first delivered turn /// carries. `None` for any other thread. pub side_chat_host_thread_id: Option, + /// The thread is a code review panel (#376), from the thread row. Read by Codex only, which + /// then never asks and stays in its read-only sandbox, whatever `runtime_mode` says. + pub code_review: bool, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -401,6 +404,11 @@ pub trait ProviderDriver: Send + Sync { fn startup_activity_capabilities_are_final(&self) -> bool { false } + /// The retired model this driver dropped from its launch (#380 R4): it starts with the + /// provider's default instead, and the thread stops naming the retired model. + fn retired_model(&self) -> Option<&'static str> { + None + } fn send( &self, text: String, @@ -948,6 +956,9 @@ type SessionPublicationFence = Arc>; struct SessionEntry { launch: ProviderLaunchRequest, + /// 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, driver: Arc, /// Holds queued messages while a resumed session reads the asks its provider kept (#187); /// released by that read finishing or by the session ending. @@ -6642,6 +6653,7 @@ async fn build_launch_request( open_url: None, host_thread_id: thread.host_thread_id.clone(), side_chat_host_thread_id: thread.host_thread_id.clone().filter(|_| thread.side_chat), + code_review: thread.code_review, }) } @@ -6911,6 +6923,28 @@ fn frozen_delivery_route_fingerprint( }) } +/// Whether `request` is the route a delivery was admitted for. The default Claude agent named or +/// left out is one route: a chat's first message leaves it out and later ones name it. +fn delivery_route_matches( + expected: &str, + request: &ProviderLaunchRequest, +) -> Result { + if expected == delivery_route_fingerprint(request)? { + return Ok(true); + } + if !matches!(request.provider.as_str(), "claude" | "claudeAgent") + || claude_agent_changed(request.agent.as_deref(), None) + { + return Ok(false); + } + let mut other_spelling = request.clone(); + other_spelling.agent = match request.agent { + Some(_) => None, + None => Some(crate::provider::claude::model::DEFAULT_AGENT.to_owned()), + }; + Ok(expected == delivery_route_fingerprint(&other_spelling)?) +} + fn validate_frozen_delivery_route( row: &ProviderTurnDelivery, request: &ProviderLaunchRequest, @@ -6928,8 +6962,7 @@ fn validate_frozen_delivery_route( }); } let expected = frozen_delivery_route_fingerprint(row)?; - let actual = delivery_route_fingerprint(request)?; - if expected == actual { + if delivery_route_matches(expected, request)? { return Ok(()); } Err(ProviderRuntimeError::Provider { @@ -7442,6 +7475,7 @@ async fn run_supervisor( thread_id, selection, operational_log.as_ref(), + true, ) .await?; } @@ -8017,7 +8051,23 @@ fn validate_active_delivery_identity( ), }); } - validate_frozen_delivery_route(row, &entry.launch)?; + match &entry.dropped_model { + // The session dropped the retired model a turn was admitted naming (#380 R4); that turn + // still matches the launch as it was requested. Its route holds the spelling it was + // admitted with, which may be another spelling of the same model. + Some(dropped) => { + let mut admitted = entry.launch.clone(); + admitted.model = row + .payload + .get("modelSelection") + .and_then(model_from_selection) + .filter(|model| crate::provider::codex::model::same_model(model, dropped)) + .or_else(|| Some(dropped.clone())); + validate_frozen_delivery_route(row, &entry.launch) + .or_else(|_| validate_frozen_delivery_route(row, &admitted))?; + } + None => validate_frozen_delivery_route(row, &entry.launch)?, + } if row.provider_session_id.is_none() { return Ok(()); } @@ -9743,6 +9793,10 @@ async fn launch_session( .map_err(|error| ProviderRuntimeError::Persistence(error.to_string()))? .is_some_and(|runtime| saved_context_handoff(runtime.runtime_payload.as_ref())); let driver = factory.create(request.clone()).await?; + let retired_model = driver.retired_model(); + // The session runs Codex's default, so the thread's "auto" below is no model change to + // restart for. + let dropped_model = retired_model.and_then(|_| request.model.take()); persist_runtime( &engine.repositories(), &request, @@ -9931,10 +9985,24 @@ async fn launch_session( #[cfg(test)] idle_deadline_test_observer.clone(), ); + if let Some(retired) = retired_model { + clear_retired_codex_selection( + engine.clone(), + retired_codex_selection_clear( + &request.thread_id, + request + .provider_instance_id + .as_deref() + .unwrap_or(request.provider.as_str()), + retired, + ), + ); + } sessions.insert( request.thread_id.clone(), SessionEntry { launch: request, + dropped_model, driver, _ask_recovery: ask_recovery, engine: engine.clone(), @@ -9974,6 +10042,40 @@ async fn launch_session( Ok(released) } +/// #380 R4: once a session started without a model Codex retired, the thread stops naming it, +/// so its warning shows once. Off the supervisor's turn, as an ordinary orchestration command; +/// a failure leaves the warning to show again at the next start. +fn clear_retired_codex_selection(engine: OrchestrationEngine, command: OrchestrationCommand) { + tokio::spawn(async move { + let thread_id = command.aggregate_ref().1.to_owned(); + match engine.dispatch(command).await { + Ok(_) => {} + // Another client chose a model meanwhile; there is nothing left to clear. + Err(crate::orchestration::OrchestrationError::Invariant { detail, .. }) + if detail == crate::orchestration::RETIRED_MODEL_ALREADY_REPLACED => {} + Err(error) => { + tracing::warn!(%thread_id, %error, "could not clear a thread's retired Codex model"); + } + } + }); +} + +/// The command that stops `thread_id` naming `retired` on `instance_id`. The engine decides on +/// the thread's selection when the command runs and keeps the rest of it, so a selection another +/// client committed meanwhile is not overwritten. +fn retired_codex_selection_clear( + thread_id: &str, + instance_id: &str, + retired: &'static str, +) -> OrchestrationCommand { + OrchestrationCommand::ThreadRetiredModelClear { + command_id: format!("retired-codex-model:{}", Uuid::new_v4()), + thread_id: thread_id.to_owned(), + instance_id: instance_id.to_owned(), + retired: retired.to_owned(), + } +} + /// Moves a frozen start whose conversation the provider no longer has to the replacement, before /// the replacement's cursor is saved: the saved cursor is cleared first, so the existing guarded /// unfreeze accepts the row, and a crash at any step leaves a state a retry recovers from. `None` @@ -10077,6 +10179,9 @@ async fn handle_command( &thread_id, selection, operational_log, + // 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 { .. }), ) .await?; } @@ -11027,6 +11132,7 @@ async fn retire_compaction_session( retired } +#[allow(clippy::too_many_arguments)] async fn reconcile_model_selection( engine: &OrchestrationEngine, factory: &Arc, @@ -11035,6 +11141,7 @@ async fn reconcile_model_selection( thread_id: &str, selection: &Value, operational_log: Option<&ProviderOperationalLog>, + starting_turn: bool, ) -> Result<(), ProviderRuntimeError> { let target_model = model_from_selection(selection); let selection_options = selection_options(selection); @@ -11060,21 +11167,38 @@ async fn reconcile_model_selection( let target_agent = selection_string_option_from(&selection_options, "agent"); let launch_only_changed = match entry.launch.provider.as_str() { "claude" | "claudeAgent" => { - entry.launch.effort != target_effort || entry.launch.agent != target_agent + entry.launch.effort != target_effort + || claude_agent_changed(entry.launch.agent.as_deref(), target_agent.as_deref()) } "opencode" => entry.launch.agent != target_agent, _ => false, }; - let model_changed = target_model - .as_ref() - .is_some_and(|model| entry.launch.model.as_ref() != Some(model)); + // A turn still naming the retired model this session dropped at launch (#380 R4) asks + // for no change: switching to it would restart into a route the turn was not admitted for. + let retired = entry.driver.retired_model(); + let model_changed = target_model.as_ref().is_some_and(|model| { + entry.launch.model.as_ref() != Some(model) + && !retired.is_some_and(|retired| { + crate::provider::codex::model::same_model(model, retired) + }) + }); let options_changed = entry.launch.options != target_options; - if !model_changed && !options_changed && !launch_only_changed { + let model_cleared = codex_model_cleared( + &entry.launch.provider, + entry.launch.model.as_deref(), + target_model.as_deref(), + ); + if model_cleared && !starting_turn { + // Saved for a queued message while a turn may still run. The options belong to the + // default model, so they wait with the switch for that message's own start. return Ok(()); } - if launch_only_changed { + if !model_changed && !options_changed && !launch_only_changed && !model_cleared { + return Ok(()); + } + if launch_only_changed || model_cleared { let mut launch = entry.launch.clone(); - if model_changed { + if model_changed || model_cleared { launch.model.clone_from(&target_model); } launch.options = target_options; @@ -11411,6 +11535,34 @@ fn command_thread_id(command: &OrchestrationCommand) -> Option<&str> { } } +/// Whether a Claude session must restart to run another agent. +/// +/// The agent named `claude` is Claude Code's own default: `--agent claude` starts the same +/// session as no `--agent` (measured on Claude Code 2.1.326: the same tools and the same prompt +/// size). A chat's first message can leave before the agent list has loaded and so names no +/// agent, and the second names the default. Restarting for that would end the Claude process and +/// everything that lives in it, a session approval included, for no change. +fn claude_agent_changed(running: Option<&str>, target: Option<&str>) -> bool { + let named = |agent: Option<&str>| { + agent + .map(str::trim) + .filter(|agent| { + !agent.is_empty() && *agent != crate::provider::claude::model::DEFAULT_AGENT + }) + .map(str::to_owned) + }; + named(running) != named(target) +} + +/// Whether a Codex session that names a model was switched to "Codex default" (`auto`). +/// +/// A running Codex session cannot be told to forget its model, so it restarts without one. +/// Without the restart the session keeps the named model while the next message's route names +/// none, and that message is refused. +fn codex_model_cleared(provider: &str, running: Option<&str>, target: Option<&str>) -> bool { + provider == "codex" && running.is_some() && target.is_none() +} + fn model_from_selection(selection: &Value) -> Option { selection .get("model") @@ -14598,15 +14750,32 @@ impl ProviderDriverFactory for NativeProviderDriverFactory { Box::pin(async move { let activity_enabled = self.activity_controller.snapshot().enabled; match request.provider.as_str() { - "codex" => Ok(Arc::new( - CodexDriver::spawn( + "codex" => { + let mut request = request; + let retired_model = match &self.published_inventory { + Some(inventory) => retired_codex_model_for_chatgpt( + &inventory.read().await, + request + .provider_instance_id + .as_deref() + .unwrap_or(&request.provider), + request.model.as_deref(), + ), + None => None, + }; + if retired_model.is_some() { + request.model = None; + } + let mut driver = CodexDriver::spawn( request, self.attachments.clone(), self.attribution.clone(), activity_enabled, ) - .await?, - ) as Arc), + .await?; + driver.retired_model = retired_model; + Ok(Arc::new(driver) as Arc) + } "cursor" => Ok(Arc::new( CursorDriver::spawn( request, @@ -14985,7 +15154,15 @@ fn runtime_mode(value: &str) -> CodexRuntimeMode { match value { "approval-required" => CodexRuntimeMode::ApprovalRequired, "auto-accept-edits" => CodexRuntimeMode::AutoAcceptEdits, - _ => CodexRuntimeMode::FullAccess, + "full-access" => CodexRuntimeMode::FullAccess, + unknown => { + // Fail closed (#376): a mode this server does not know asks before acting. + tracing::warn!( + runtime_mode = unknown, + "unknown runtime mode for Codex; starting it Supervised" + ); + CodexRuntimeMode::ApprovalRequired + } } } @@ -14999,6 +15176,8 @@ struct CodexDriver { custom_models: Vec, /// The `config.toml` this Codex reads, named when Codex refuses it. config_path: String, + /// The retired model the thread stored, which this session was started without. + retired_model: Option<&'static str>, } fn codex_activity_target_ids( @@ -15124,7 +15303,11 @@ impl CodexDriver { version: env!("CARGO_PKG_VERSION").to_owned(), thread_id: request.thread_id, cwd: request.cwd.to_string_lossy().into_owned(), - runtime_mode: runtime_mode(&request.runtime_mode), + runtime_mode: if request.code_review { + CodexRuntimeMode::CodeReview + } else { + runtime_mode(&request.runtime_mode) + }, model: request.model, service_tier: None, effort: None, @@ -15141,6 +15324,7 @@ impl CodexDriver { provider_label: request.provider_label, custom_models: request.custom_models, config_path, + retired_model: None, }) } @@ -15238,6 +15422,9 @@ fn is_codex_compaction(text: &str, attachments: &[Value]) -> bool { } impl ProviderDriver for CodexDriver { + fn retired_model(&self) -> Option<&'static str> { + self.retired_model + } /// `thread/compact/start`: Codex answers, then reports the compaction as a root turn of its /// own with a `contextCompaction` item, which the runtime tags with the compaction id. fn compact(&self, compaction_id: String) -> BoxRuntimeFuture<'_, ProviderCompactionStart> { @@ -15271,6 +15458,9 @@ impl ProviderDriver for CodexDriver { .start() .await .map_err(|error| codex_start_error(error, &self.config_path))?; + if let Some(model) = self.retired_model { + self.runtime.warn(&retired_codex_model_notice(model)).await; + } Ok(StartedSession { resume_cursor: session .resume_cursor @@ -16696,6 +16886,10 @@ fn claude_replayed_user_text(value: &Value) -> Option<&str> { if value.get("type").and_then(Value::as_str) != Some("user") { return None; } + // Claude's own notification replay is never a delivered message's echo, whatever its text. + if value.pointer("/origin/kind").and_then(Value::as_str) == Some("task-notification") { + return None; + } match value.pointer("/message/content")? { Value::String(text) => Some(text), Value::Array(blocks) => { @@ -16981,9 +17175,15 @@ async fn query_claude_control( } } +/// The turn whose context reading Claude is asked for: a completed turn, or the last turn when +/// an answer Claude gave with no turn open ends (the Claude runtime emits +/// `assistant.message.completed` only then, its last text unmarked). The answer is dropped if +/// another turn started before it arrived. fn claude_completion_query_turn_id(event: &ProviderEvent) -> Option<&str> { if event.event_type == "turn.completed" && event.payload.get("state").and_then(Value::as_str) == Some("completed") + || event.event_type == "assistant.message.completed" + && event.payload.get("answerContinues").is_none() { event.turn_id.as_deref() } else { @@ -17658,6 +17858,14 @@ mod claude_context_query_tests { let mut non_completion = completion("completed"); non_completion.event_type = "item.completed".to_owned(); assert_eq!(claude_completion_query_turn_id(&non_completion), None); + // Claude emits this only when an answer it gave with no turn open ends (its text). + let mut idle_answer = completion("completed"); + idle_answer.event_type = "assistant.message.completed".to_owned(); + idle_answer.payload = json!({}); + assert_eq!( + claude_completion_query_turn_id(&idle_answer), + Some("turn-1") + ); } #[test] @@ -17862,9 +18070,14 @@ struct ClaudeDriver { /// The instance's label, which delivery details name the provider by. provider_label: String, runtime: Arc>, - writer: Mutex>, + writer: ClaudeWriter, events: Mutex>, + /// For the events of a request this driver settles. Weak, so the driver does not keep the + /// event stream open after Claude's output ended. + events_tx: mpsc::WeakSender, deferred_events: Mutex>, + /// The turn whose context reading to ask for once an idle answer's text completion is out. + idle_context_query: Mutex>, control_responses: ClaudeControlResponseRouter, child: SharedChild, session_id: String, @@ -17945,6 +18158,10 @@ pub struct ClaudeActivitySupport { /// The CLI accepts `--thinking-display summarized` (#173). From Claude Opus 4.7 on, the /// API omits thinking text unless asked; without the flag those models send none. pub thinking_display: bool, + /// The CLI's `--help` lists `--permission-prompts`, so it sends a tool that needs approval + /// to its host when started with `--permission-prompt-tool stdio`. Without it Claude Code + /// denies such a tool by itself and no approval card can open. + pub permission_prompts: bool, } /// A value `--thinking-display` rejects: a CLI that knows the flag lists its allowed values, @@ -18691,6 +18908,7 @@ async fn probe_claude_activity_support_uncached( fork_session_id, probe_finished: true, thinking_display, + permission_prompts: has_exact_flag("--permission-prompts"), }, }) } @@ -18922,6 +19140,10 @@ fn build_claude_launch_arguments( if support.thinking_display { args.extend(["--thinking-display".to_owned(), "summarized".to_owned()]); } + // Approvals and questions come to BiBCode over the stream instead of being denied (#383). + if support.permission_prompts { + args.extend(["--permission-prompt-tool".to_owned(), "stdio".to_owned()]); + } args.extend([ "--verbose".to_owned(), "--setting-sources=user,project,local".to_owned(), @@ -18945,7 +19167,13 @@ fn build_claude_launch_arguments( if let Some(effort) = request.effort.as_ref() { args.extend(["--effort".to_owned(), effort.clone()]); } - if let Some(agent) = request.agent.as_ref() { + // The default agent takes no flag: Claude then runs its own default, which its settings + // can name, and a selection that names the default launches like one that names none. + if let Some(agent) = request + .agent + .as_ref() + .filter(|agent| agent.as_str() != crate::provider::claude::model::DEFAULT_AGENT) + { args.extend(["--agent".to_owned(), agent.clone()]); } if let Some(settings) = claude_session_settings(request, hook_settings) { @@ -19019,6 +19247,30 @@ fn model_offers_boolean_option(model: &Value, option: &str) -> bool { }) } +/// The retired model a Codex launch names, when the inventory published for `instance_id` says +/// that Codex is signed in with ChatGPT. An API-key session still runs these models, and with no +/// published sign-in the model is passed through, so Codex's own answer is shown. +fn retired_codex_model_for_chatgpt( + inventory: &[Value], + instance_id: &str, + model: Option<&str>, +) -> Option<&'static str> { + let retired = crate::provider::codex::model::retired_model(model?)?; + let auth_type = inventory + .iter() + .find(|snapshot| snapshot.get("instanceId").and_then(Value::as_str) == Some(instance_id))? + .get("auth")? + .get("type")? + .as_str()?; + (auth_type == "chatgpt").then_some(retired) +} + +fn retired_codex_model_notice(model: &str) -> String { + format!( + "Codex retired {model} for ChatGPT sign-in, so this session uses Codex's default model. Choose a model in the model picker to use another one." + ) +} + /// Whether `model` offers the boolean `option` in the inventory published for `instance_id`, or /// `None` when that inventory does not list the model. fn published_model_offers_option( @@ -19407,6 +19659,8 @@ impl ClaudeDriver { }; let pending_acknowledgement = ClaudeAcknowledgements::default(); let control_responses = ClaudeControlResponseRouter::default(); + let writer: ClaudeWriter = Arc::new(Mutex::new(Box::new(stdin))); + let weak_events_tx = events_tx.downgrade(); let output = spawn_claude_output( runtime.clone(), request.thread_id.clone(), @@ -19417,14 +19671,17 @@ impl ClaudeDriver { events_tx, pending_acknowledgement.clone(), control_responses.clone(), + writer.clone(), ); Ok(Self { provider: request.provider, provider_label: request.provider_label, runtime, - writer: Mutex::new(Box::new(stdin)), + writer, events: Mutex::new(events_rx), + events_tx: weak_events_tx, deferred_events: Mutex::new(VecDeque::new()), + idle_context_query: Mutex::new(None), control_responses, child: Arc::new(Mutex::new(child)), session_id, @@ -19500,6 +19757,43 @@ impl ClaudeDriver { refused.then_some(CLAUDE_RESUME_REFUSED) } + /// Answers Claude's request `request_id` with `response`. + async fn reply_to_request( + &self, + request_id: &str, + response: &Value, + ) -> Result<(), ProviderRuntimeError> { + let written = write_claude_control_reply( + &self.writer, + &crate::provider::claude::runtime::control_response(request_id, response), + ) + .await; + if written.is_err() { + // Claude may hold part of the frame and still waits for its answer, which nothing + // can deliver now. Ending its output ends the session, so the turn does not hang. + self.output.cancellation.cancel(); + } + written.map_err(provider_error(&self.provider)) + } + + /// Hands the supervisor the events of requests this driver settled, which close their cards. + async fn publish_request_events(&self, events: Vec) { + let Some(sender) = self.events_tx.upgrade() else { + return; + }; + for event in events { + if !send_claude_output( + &sender, + &self.output.cancellation, + claude_provider_event(event, None, Vec::new()), + ) + .await + { + return; + } + } + } + fn encode_json_line(&self, value: Value) -> Result, ProviderRuntimeError> { let mut bytes = serde_json::to_vec(&value).map_err(provider_error(&self.provider))?; bytes.push(b'\n'); @@ -20022,10 +20316,19 @@ impl ProviderDriver for ClaudeDriver { _: Option, ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { - self.runtime.lock().await.stop_turn_input(); + // An interrupted turn leaves nobody to answer its requests. Claude withdraws them + // too, which then finds nothing pending. + let cancelled = { + let mut runtime = self.runtime.lock().await; + runtime.stop_turn_input(); + runtime.cancel_pending_requests() + }; let control = ClaudeControlRequest::interrupt(self.next_sequence().await); - self.write_json(serde_json::to_value(control).map_err(provider_error(&self.provider))?) - .await + let written = self + .write_json(serde_json::to_value(control).map_err(provider_error(&self.provider))?) + .await; + self.publish_request_events(cancelled).await; + written }) } fn approve( @@ -20034,16 +20337,28 @@ impl ProviderDriver for ClaudeDriver { decision: String, ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { - let accepted = matches!(decision.as_str(), "accept" | "acceptForSession"); - self.runtime.lock().await.resolve_permission_request( - &request_id, - if accepted { - Decision::Accept - } else { - Decision::Deny - }, - ); - self.write_json(json!({"type":"control_response","response":{"request_id":request_id,"subtype":"success","response":{"behavior":if accepted {"allow"} else {"deny"}}}})).await + let decision = match decision.as_str() { + "accept" => Decision::Accept, + "acceptForSession" => Decision::AcceptForSession, + "cancel" => Decision::Cancel, + _ => Decision::Decline, + }; + // Claiming the request is what lets exactly one answer or cancellation win. + let Some(resolved) = self + .runtime + .lock() + .await + .resolve_permission_request(&request_id, decision) + else { + return Err(ProviderRuntimeError::Provider { + provider: self.provider.clone(), + detail: format!("Unknown pending approval request: {request_id}"), + }); + }; + self.reply_to_request(&request_id, &resolved.response) + .await?; + self.publish_request_events(resolved.events).await; + Ok(()) }) } fn answer( @@ -20052,11 +20367,25 @@ impl ProviderDriver for ClaudeDriver { answers: Value, ) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { - self.runtime + let Some(resolved) = self + .runtime .lock() .await - .resolve_user_input_request(&request_id, answers.clone()); - self.write_json(json!({"type":"control_response","response":{"request_id":request_id,"subtype":"success","response":answers}})).await + .resolve_user_input_request(&request_id, answers) + else { + return Err(ProviderRuntimeError::Provider { + provider: self.provider.clone(), + detail: format!("Unknown pending user-input request: {request_id}"), + }); + }; + // The answers go back as the tool's input, which is how Claude reads them. + self.reply_to_request( + &request_id, + &json!({ "behavior": "allow", "updatedInput": resolved.updated_input }), + ) + .await?; + self.publish_request_events(resolved.events).await; + Ok(()) }) } fn set_mode(&self, mode: String) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { @@ -20175,14 +20504,26 @@ impl ProviderDriver for ClaudeDriver { if let Some(event) = deferred_events.pop_front() { return Some(event); } - let Some(completion) = self.events.lock().await.recv().await else { - // Decided before the pump sees the end, so it can record a refused resume. - let _ = self.launch_refusal().await; - return None; - }; - let Some(turn_id) = claude_completion_query_turn_id(&completion).map(str::to_owned) - else { - return Some(completion); + // An idle answer's text completion went out first: no turn holds the idle deadline + // off, so a query it waited on could outlive the session and lose it. + let idle_query = self.idle_context_query.lock().await.take(); + let (turn_id, completion) = if let Some(turn_id) = idle_query { + (turn_id, None) + } else { + let Some(completion) = self.events.lock().await.recv().await else { + // Decided before the pump sees the end, so it can record a refused resume. + let _ = self.launch_refusal().await; + return None; + }; + let Some(turn_id) = claude_completion_query_turn_id(&completion).map(str::to_owned) + else { + return Some(completion); + }; + if completion.event_type == "assistant.message.completed" { + *self.idle_context_query.lock().await = Some(turn_id); + return Some(completion); + } + (turn_id, Some(completion)) }; let response = query_claude_context_usage( &self.provider, @@ -20214,12 +20555,15 @@ impl ProviderDriver for ClaudeDriver { updates.push_back(claude_provider_event(status, None, Vec::new())); } drop(runtime); - let Some(first) = updates.pop_front() else { - return Some(completion); - }; deferred_events.extend(updates); - deferred_events.push_back(completion); - Some(first) + deferred_events.extend(completion); + match deferred_events.pop_front() { + Some(first) => Some(first), + None => { + drop(deferred_events); + self.next_event().await + } + } }) } fn exited_process(&self) -> BoxRuntimeFuture<'_, Option<(u32, std::process::ExitStatus)>> { @@ -20233,6 +20577,15 @@ impl ProviderDriver for ClaudeDriver { fn shutdown(&self) -> BoxRuntimeFuture<'_, Result<(), ProviderRuntimeError>> { Box::pin(async move { self.control_responses.close(); + // The process that asked is going away, so its open requests close with it. + // Not awaited: the supervisor stops reading events before it shuts a driver down, so + // a full queue would never drain. + let cancelled = self.runtime.lock().await.cancel_pending_requests(); + if let Some(sender) = self.events_tx.upgrade() { + for event in cancelled { + let _ = sender.try_send(claude_provider_event(event, None, Vec::new())); + } + } // Kill first: a write Claude stopped reading holds the writer until the pipe breaks. kill_child(&self.child).await; let _ = self.writer.lock().await.shutdown().await; @@ -20335,6 +20688,7 @@ fn spawn_claude_output( sender: mpsc::Sender, pending_acknowledgement: ClaudeAcknowledgements, control_responses: ClaudeControlResponseRouter, + writer: ClaudeWriter, ) -> Arc { let cancellation = CancellationToken::new(); let (recovery_sender, recovery_receiver) = @@ -20354,6 +20708,8 @@ fn spawn_claude_output( let stdout_cancellation = cancellation.clone(); let stdout_pending_acknowledgement = pending_acknowledgement.clone(); let stdout_control_responses = control_responses.clone(); + let stdout_writer = writer.clone(); + let hook_writer = writer; let stdout_task = tokio::spawn(async move { let mut lines = BufReader::new(stdout).lines(); loop { @@ -20380,6 +20736,7 @@ fn spawn_claude_output( &stdout_recovery_sender, &stdout_cancellation, &stdout_pending_acknowledgement, + &stdout_writer, ) .await { @@ -20414,6 +20771,7 @@ fn spawn_claude_output( &hook_recovery_sender, &hook_cancellation, &pending_acknowledgement, + &hook_writer, ) .await { @@ -20503,6 +20861,7 @@ pub async fn claude_output_shutdown_with_open_stream_for_test() -> bool { sender, ClaudeAcknowledgements::default(), ClaudeControlResponseRouter::default(), + Arc::new(Mutex::new(Box::new(tokio::io::sink()))), ); let completed = tokio::time::timeout(Duration::from_millis(150), output.shutdown()) .await @@ -20811,6 +21170,42 @@ mod claude_recovery_worker_tests { } } +/// Claude's stdin, shared by the driver and by the output loop, which answers some of Claude's +/// requests itself. +type ClaudeWriter = Arc>>; + +#[cfg(test)] +fn claude_test_writer() -> ClaudeWriter { + Arc::new(Mutex::new(Box::new(tokio::io::sink()))) +} + +/// How long an answer to Claude's request may wait for Claude to read it. The single supervisor +/// actor awaits an approval for every session, so the write is bounded like an interrupt. +const CLAUDE_CONTROL_REPLY_TIMEOUT: Duration = PROVIDER_INTERRUPT_SETTLEMENT_TIMEOUT; + +/// Writes one `control_response` frame. A timeout or a failed write is an error: the caller +/// then knows the answer may not have reached Claude. +async fn write_claude_control_reply( + writer: &ClaudeWriter, + response: &Value, +) -> Result<(), std::io::Error> { + let mut bytes = serde_json::to_vec(response)?; + bytes.push(b'\n'); + let write = async { + let mut writer = writer.lock().await; + writer.write_all(&bytes).await?; + writer.flush().await + }; + tokio::time::timeout(CLAUDE_CONTROL_REPLY_TIMEOUT, write) + .await + .map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::TimedOut, + "Claude did not read the answer in time", + ) + })? +} + fn claude_provider_event( event: ClaudeCanonicalEvent, native_event_id: Option, @@ -20839,6 +21234,7 @@ async fn emit_claude_value( recovery_sender: &mpsc::Sender, cancellation: &CancellationToken, pending_acknowledgement: &ClaudeAcknowledgements, + writer: &ClaudeWriter, ) -> bool { let emitted_at_ms = u64::try_from( OffsetDateTime::now_utc() @@ -20880,6 +21276,25 @@ async fn emit_claude_value( runtime.handle_raw_value(&value, emitted_at_ms) } }; + // Answers the runtime gives by itself to a request from Claude. Written off this loop, so + // a slow stdin cannot hold back Claude's output. + let control_responses = std::mem::take(&mut output.control_responses); + if !control_responses.is_empty() { + let writer = writer.clone(); + let cancellation = cancellation.clone(); + tokio::spawn(async move { + for response in control_responses { + if write_claude_control_reply(&writer, &response) + .await + .is_err() + { + // Claude waits for this answer and cannot get it: end the session. + cancellation.cancel(); + return; + } + } + }); + } if let Some(live_tasks) = output.background_tasks.take() && !send_claude_output( sender, @@ -21400,6 +21815,7 @@ mod tests { set_mode_unsupported: bool, interaction_modes: Vec, models: Vec, + retired_model: Option<&'static str>, rollbacks: Vec, exited: Option<(u32, std::process::ExitStatus)>, shutdowns: usize, @@ -21662,6 +22078,9 @@ mod tests { } impl ProviderDriver for SupervisorDriver { + fn retired_model(&self) -> Option<&'static str> { + self.state.lock().unwrap().retired_model + } fn holds_unsettled_work(&self) -> super::BoxRuntimeFuture<'_, bool> { Box::pin(std::future::ready( self.state.lock().unwrap().unsettled_work, @@ -22052,6 +22471,7 @@ mod tests { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, } } @@ -23166,6 +23586,25 @@ done #[cfg(windows)] const CLAUDE_REPLAY_FIXTURE: &str = "claude-replay"; + // Claude Code 2.1's frames for a tool that needs approval (#383): a `can_use_tool` request + // after each user message, and a request to leave plan mode once the first one is answered. + #[cfg(unix)] + const CLAUDE_APPROVAL_FIXTURE: &str = r#"#!/bin/sh +while IFS= read -r line; do + printf '%s\n' "$line" >> "$BIBCODE_TEST_REQUEST_CAPTURE" + case "$line" in + *'"type":"user"'*) + printf '%s\n' "$line" + printf '%s\n' '{"type":"control_request","request_id":"cli-request-1","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"touch made.txt"},"permission_suggestions":[{"type":"addRules","rules":[{"toolName":"Bash","ruleContent":"touch made.txt"}],"behavior":"allow","destination":"localSettings"},{"type":"setMode","mode":"acceptEdits","destination":"session"}],"tool_use_id":"tool-1"}}' + ;; + *'"request_id":"cli-request-1"'*) + printf '%s\n' '{"type":"control_request","request_id":"cli-plan-1","request":{"subtype":"can_use_tool","tool_name":"ExitPlanMode","input":{"plan":"Create hello.txt"},"tool_use_id":"tool-2"}}' + printf '%s\n' '{"type":"control_request","request_id":"cli-request-2","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"rm made.txt"},"tool_use_id":"tool-3"}}' + ;; + esac +done +"#; + // Replays each message only after a delay longer than the test's acknowledgement wait. #[cfg(unix)] const CLAUDE_LATE_REPLAY_FIXTURE: &str = r#"#!/bin/sh @@ -23251,6 +23690,184 @@ while IFS= read -r line; do done "#; + /// The context fixture, then an answer Claude gives with no turn open (Claude Code 2.1.326 + /// answering a finished background task): it starts once the turn's queries are answered, + /// and the context reading Claude reports afterwards is larger. + #[cfg(unix)] + const CLAUDE_IDLE_ANSWER_CONTEXT_FIXTURE: &str = r#"#!/bin/sh +while IFS= read -r line; do + printf '%s\n' "$line" >> "$BIBCODE_TEST_REQUEST_CAPTURE" + case "$line" in + *'"type":"user"'*) + printf '%s\n' "$line" + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"errors":[],"stop_reason":"end_turn","session_id":"fixture-session","uuid":"result-1"}' + ;; + *'"subtype":"get_context_usage"'*) + request_id=$(printf '%s\n' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + tokens=31251 + [ "$request_id" = "bibcode-1" ] || tokens=42000 + printf '{"type":"control_response","response":{"subtype":"success","request_id":"%s","response":{"totalTokens":%s,"maxTokens":200000,"isAutoCompactEnabled":true}}}\n' "$request_id" "$tokens" + ;; + *'"subtype":"mcp_status"'*) + request_id=$(printf '%s\n' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + printf '{"type":"control_response","response":{"subtype":"success","request_id":"%s","response":{"mcpServers":[]}}}\n' "$request_id" + if [ "$request_id" = "bibcode-2" ]; then + printf '%s\n' '{"type":"system","subtype":"init","session_id":"fixture-session","uuid":"idle-init"}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"idle-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background task finished."}}}' + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"errors":[],"stop_reason":"end_turn","origin":{"kind":"task-notification"},"session_id":"fixture-session","uuid":"idle-result"}' + fi + ;; + esac +done +"#; + + /// After an answer Claude gives with no turn open, the context reading is refreshed by the + /// same query a completed turn runs, after the answer's text completes (so a session + /// suspended meanwhile never loses that completion), and no turn completes for it. + #[cfg(unix)] + #[tokio::test] + async fn claude_idle_answer_refreshes_the_context_reading() { + let temp = TempDir::new().expect("provider fixture directory"); + let capture_path = temp.path().join("claude-idle-context-query.jsonl"); + let driver = claude_delivery_fixture( + &temp, + "claude-idle-context-query", + CLAUDE_IDLE_ANSWER_CONTEXT_FIXTURE, + &capture_path, + None, + None, + ) + .await; + driver.start().await.expect("Claude fixture should start"); + let deadline = ProviderFixtureDeadline::integration(); + let outcome = deadline + .observe(driver.deliver( + "measure context".to_owned(), + Vec::new(), + "default".to_owned(), + "unused-no-id-key".to_owned(), + )) + .await + .expect("delivery outcome"); + assert!(matches!( + outcome, + super::ProviderDeliveryOutcome::Accepted { .. } + )); + let mut events: Vec = Vec::new(); + let answer_ended = |events: &[ProviderEvent]| { + events + .iter() + .position(|event| event.event_type == "assistant.message.completed") + }; + while answer_ended(&events).is_none_or(|ended| { + !events[ended..] + .iter() + .any(|event| event.event_type == "thread.token-usage.updated") + }) { + let event = deadline + .observe(driver.next_event()) + .await + .expect("next event") + .expect("an event"); + events.push(event); + } + driver.shutdown().await.expect("Claude fixture shutdown"); + + let completions = events + .iter() + .filter(|event| event.event_type == "turn.completed") + .count(); + assert_eq!(completions, 1, "only the delivered turn completes"); + let readings: Vec<_> = events + .iter() + .filter(|event| event.event_type == "thread.token-usage.updated") + .map(|event| event.payload["usage"]["usedTokens"].clone()) + .collect(); + assert_eq!( + readings.last(), + Some(&json!(42_000)), + "the idle answer's context reading: {readings:?}" + ); + } + + /// An idle answer that streams text, calls a tool, and streams more text under a second + /// message: both texts complete, and the context reading is asked for once, after both. + #[cfg(unix)] + #[tokio::test] + async fn claude_idle_answer_in_two_messages_completes_both_and_queries_once() { + let two_messages = CLAUDE_IDLE_ANSWER_CONTEXT_FIXTURE.replace( + r#" printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"idle-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background task finished."}}}'"#, + r#" printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"start-a","parent_tool_use_id":null,"event":{"type":"message_start","message":{"id":"answer-a"}}}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"delta-a","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Checking the output."}}}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"tool-start","parent_tool_use_id":null,"event":{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tool-1","name":"Bash","input":{}}}}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"tool-stop","parent_tool_use_id":null,"event":{"type":"content_block_stop","index":1}}' + printf '%s\n' '{"type":"user","parent_tool_use_id":null,"session_id":"fixture-session","uuid":"tool-result","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"ok"}]}}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"start-b","parent_tool_use_id":null,"event":{"type":"message_start","message":{"id":"answer-b"}}}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"delta-b","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background task finished."}}}'"#, + ); + assert!(two_messages.contains("answer-b")); + let temp = TempDir::new().expect("provider fixture directory"); + let capture_path = temp.path().join("claude-idle-two-messages.jsonl"); + let driver = claude_delivery_fixture( + &temp, + "claude-idle-two-messages", + &two_messages, + &capture_path, + None, + None, + ) + .await; + driver.start().await.expect("Claude fixture should start"); + let deadline = ProviderFixtureDeadline::integration(); + deadline + .observe(driver.deliver( + "measure context".to_owned(), + Vec::new(), + "default".to_owned(), + "unused-no-id-key".to_owned(), + )) + .await + .expect("delivery outcome"); + let mut events: Vec = Vec::new(); + let last_completion = |events: &[ProviderEvent]| { + events + .iter() + .filter(|event| event.event_type == "assistant.message.completed") + .count() + == 2 + }; + while !last_completion(&events) + || !events + .iter() + .rev() + .take_while(|event| event.event_type != "assistant.message.completed") + .any(|event| event.event_type == "thread.token-usage.updated") + { + let event = deadline + .observe(driver.next_event()) + .await + .expect("next event") + .expect("an event"); + events.push(event); + } + driver.shutdown().await.expect("Claude fixture shutdown"); + + let completed: Vec<_> = events + .iter() + .filter(|event| event.event_type == "assistant.message.completed") + .map(|event| event.item_id.clone()) + .collect(); + assert_eq!( + completed, + [Some("answer-a".to_owned()), Some("answer-b".to_owned())] + ); + let queries = std::fs::read_to_string(&capture_path) + .unwrap() + .matches("\"subtype\":\"get_context_usage\"") + .count(); + assert_eq!(queries, 2, "one for the delivered turn, one for the answer"); + } + async fn claude_delivery_fixture( temp: &TempDir, name: &str, @@ -24278,6 +24895,272 @@ done } } + /// #380 R4: a message from outside the app (an agent message, an MCP client) launches a + /// thread that names a retired Codex model. The session starts without it, the thread then + /// stores Codex's default so the warning shows once, and the next turn does not restart. + #[tokio::test] + async fn a_session_started_without_a_retired_codex_model_stops_the_thread_naming_it() { + let engine = supervisor_engine().await; + engine + .dispatch( + serde_json::from_value(json!({ + "type":"thread.meta.update","commandId":"retired","threadId":"t1", + "modelSelection":{"instanceId":"codex","model":"gpt-5.4"} + })) + .unwrap(), + ) + .await + .unwrap(); + let activity = super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )); + let state = Arc::new(StdMutex::new(SupervisorDriverState { + retired_model: Some("gpt-5.4"), + ..SupervisorDriverState::default() + })); + let (_events_tx, events_rx) = mpsc::channel(1); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(SupervisorFactory { + state: state.clone(), + events: StdMutex::new(Some(events_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.model = Some("gpt-5.4".to_owned()); + supervisor.launch(launch).await.expect("launch runtime"); + + let stored_model = || async { + engine + .repositories() + .get_thread("t1".to_owned()) + .await + .expect("read thread") + .expect("thread") + .model_selection["model"] + .clone() + }; + timeout(Duration::from_secs(5), async { + while stored_model().await != json!("auto") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the thread stores Codex's default"); + + let next: OrchestrationCommand = serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":"next", "threadId":"t1", + "message":{"messageId":"user-next","role":"user","text":"next","attachments":[]}, + "modelSelection":{"instanceId":"codex","model":"auto"}, + "runtimeMode":"full-access", "interactionMode":"default", + "createdAt":"2026-07-16T00:00:01Z" + })) + .unwrap(); + supervisor.handle_orchestration(next).await.unwrap(); + let (launches, shutdowns) = { + let state = state.lock().unwrap(); + (state.launches, state.shutdowns) + }; + assert_eq!(launches, 1, "the session already runs Codex's default"); + assert_eq!(shutdowns, 0); + engine.shutdown().await; + } + + /// #380 R4: the turn that launched the session, or one queued before the thread stored + /// Codex's default, still names the retired model. The session already dropped it, so the + /// turn is no model change: it is sent on that session, not on a restart. + #[tokio::test] + async fn a_turn_naming_the_retired_codex_model_is_sent_without_a_restart() { + let engine = supervisor_engine().await; + let activity = super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )); + let state = Arc::new(StdMutex::new(SupervisorDriverState { + retired_model: Some("gpt-5.4"), + ..SupervisorDriverState::default() + })); + let (_events_tx, events_rx) = mpsc::channel(1); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(SupervisorFactory { + state: state.clone(), + events: StdMutex::new(Some(events_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.model = Some("gpt-5.4".to_owned()); + supervisor.launch(launch).await.expect("launch runtime"); + + let turn: OrchestrationCommand = serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":"retired-turn", "threadId":"t1", + "message":{"messageId":"user-retired","role":"user","text":"hello","attachments":[]}, + "modelSelection":{"instanceId":"codex","model":"gpt-5.4"}, + "runtimeMode":"full-access", "interactionMode":"default", + "createdAt":"2026-07-16T00:00:01Z" + })) + .unwrap(); + supervisor.handle_orchestration(turn).await.unwrap(); + let (launches, shutdowns, models, sends) = { + let state = state.lock().unwrap(); + ( + state.launches, + state.shutdowns, + state.models.clone(), + state.sends.len(), + ) + }; + assert_eq!( + launches, 1, + "the session already runs without the retired model" + ); + assert_eq!(shutdowns, 0); + assert_eq!(sends, 1, "the turn is sent on the running session"); + assert!( + models.is_empty(), + "no live switch back to the retired model: {models:?}" + ); + engine.shutdown().await; + } + + /// #380 R4: the durable turn that launched the session was admitted naming the retired + /// model, and the session runs without it. That is the route the turn was admitted for, so + /// the turn is not blocked as a changed route. + #[tokio::test] + async fn a_turn_admitted_for_a_retired_codex_model_keeps_its_route_on_the_session() { + // The route fingerprints the spelling the turn was admitted with, an alias included, and + // the session may have launched from another spelling of the same model. + let spellings = ["gpt-5.4", "5.4", "gpt-5-codex"]; + for launched in spellings { + for admitted in spellings { + assert_retired_codex_route_kept(launched, admitted).await; + } + } + } + + async fn assert_retired_codex_route_kept(launched: &str, admitted: &str) { + let engine = supervisor_engine().await; + let state = Arc::new(StdMutex::new(SupervisorDriverState { + retired_model: Some("gpt-5.4"), + ..SupervisorDriverState::default() + })); + let (_events_tx, events_rx) = mpsc::channel(1); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(SupervisorFactory { + state, + events: StdMutex::new(Some(events_rx)), + }), + super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )), + super::SupervisorOptions::default(), + ); + let temp = TempDir::new().expect("launch directory"); + let mut launch = native_launch(&temp, "codex"); + launch.thread_id = "t1".to_owned(); + launch.model = Some(admitted.to_owned()); + let mut payload = json!({"modelSelection":{"instanceId":"codex","model":admitted}}); + payload[super::DELIVERY_ROUTE_FINGERPRINT_FIELD] = + Value::String(super::delivery_route_fingerprint(&launch).unwrap()); + launch.model = Some(launched.to_owned()); + supervisor.launch(launch).await.expect("launch runtime"); + + let reconciled = supervisor + .reconcile_turn(crate::orchestration::ProviderTurnDelivery { + mode: crate::orchestration::TurnDeliveryMode::Start, + held: false, + command_id: "retired-turn".to_owned(), + thread_id: "t1".to_owned(), + message_id: "user-retired".to_owned(), + provider_instance_id: "codex".to_owned(), + provider_kind: "codex".to_owned(), + provider_session_id: None, + delivery_key: "retired-delivery".to_owned(), + payload, + state: crate::orchestration::TurnDeliveryState::Sending, + attempts: 1, + last_error: None, + created_at: "2026-07-16T00:00:00Z".to_owned(), + updated_at: "2026-07-16T00:00:00Z".to_owned(), + }) + .await; + assert!( + reconciled.is_ok(), + "{launched} then {admitted}: {reconciled:?}" + ); + supervisor.shutdown().await.unwrap(); + engine.shutdown().await; + } + + /// #380 R4: a selection another client commits after the cleanup was decided is kept: the + /// cleanup must not write back the selection it read with the model replaced. The same model + /// chosen on another Codex instance, where it may still run, is another selection. + #[tokio::test] + async fn the_retired_codex_model_cleanup_keeps_a_selection_committed_meanwhile() { + for chosen in [ + json!({ + "instanceId":"codex","model":"gpt-6.2-sol", + "options":[{"id":"reasoningEffort","value":"high"}] + }), + json!({ + "instanceId":"codex-api-key","model":"gpt-5.4", + "options":[{"id":"reasoningEffort","value":"high"}] + }), + ] { + let engine = supervisor_engine().await; + let select = |command_id: &str, model_selection: Value| { + serde_json::from_value::(json!({ + "type":"thread.meta.update","commandId":command_id,"threadId":"t1", + "modelSelection":model_selection + })) + .unwrap() + }; + engine + .dispatch(select( + "retired", + json!({"instanceId":"codex","model":"5.4"}), + )) + .await + .unwrap(); + // As a session on the "codex" instance that dropped `5.4` builds it. + let cleanup = serde_json::from_value::(json!({ + "type":"thread.retired-model.clear","commandId":"cleanup","threadId":"t1", + "instanceId":"codex","retired":"gpt-5.4" + })) + .unwrap(); + engine + .dispatch(select("chosen", chosen.clone())) + .await + .unwrap(); + let refused = engine.dispatch(cleanup).await; + assert!( + matches!( + &refused, + Err(crate::orchestration::OrchestrationError::Invariant { detail, .. }) + if detail == crate::orchestration::RETIRED_MODEL_ALREADY_REPLACED + ), + "{chosen}: {refused:?}" + ); + let stored = engine + .repositories() + .get_thread("t1".to_owned()) + .await + .unwrap() + .unwrap() + .model_selection; + assert_eq!(stored, chosen); + engine.shutdown().await; + } + } + /// The session stays registered after its stream ends, and a shutdown writes its runtime row /// again: the refusal must survive that, so History keeps offering a copy. #[tokio::test] @@ -24431,6 +25314,9 @@ while IFS= read -r line; do *'"fixtureAction":"unrelated"'*) printf '%s\n' '{"type":"user","message":{"role":"user","content":"another input"}}' ;; + *'"fixtureAction":"notification"'*) + printf '%s\n' '{"type":"user","message":{"role":"user","content":"follow up"},"origin":{"kind":"task-notification"}}' + ;; *'"fixtureAction":"multiple-text-blocks"'*) printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"other"},{"type":"text","text":"follow up"}]}}' ;; @@ -24478,6 +25364,8 @@ done let echo = json!({"type":"user","message":{"role":"user","content":content}}); assert_eq!(super::claude_replayed_user_text(&echo), expected, "{echo}"); } + let notification = json!({"type":"user","message":{"role":"user","content":"prompt"},"origin":{"kind":"task-notification"}}); + assert_eq!(super::claude_replayed_user_text(¬ification), None); } #[cfg(unix)] @@ -25073,6 +25961,8 @@ done "mixed-result", "unrelated", "multiple-text-blocks", + // A notification replay with the steer's text is Claude's own turn, not the echo. + "notification", ] { let (_temp, driver, active, mut steer) = claude_pending_steer_fixture().await; claude_fixture_action(&driver, noise).await; @@ -25863,6 +26753,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -25936,6 +26827,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -27001,6 +27893,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -27054,6 +27947,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -27229,6 +28123,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -27274,6 +28169,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ) .await ); @@ -27431,7 +28327,8 @@ done authenticated, &recovery_sender, &cancellation, - &slot + &slot, + &super::claude_test_writer(), ) .await ); @@ -27445,6 +28342,7 @@ done &recovery_sender, &cancellation, &slot, + &super::claude_test_writer(), ).await); } let scope = ActivityScopeRef::Thread { @@ -32278,6 +33176,48 @@ while IFS= read -r line; do ;; esac done +"#; + + /// The same agent as Claude Code 2.1.326 answers it while idle (recorded, see + /// docs/providers/claude.md): `task_notification`, then a turn Claude starts by itself with + /// `system` `init`, its main-thread answer and a `result` whose `origin.kind` is + /// `task-notification`, and no `user` record first. The older fixture keeps the documented + /// replay shape, which BiBCode still handles for a CLI that sends it. + #[cfg(unix)] + const CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE: &str = r#"#!/bin/sh +case "$1" in + --version) printf '%s\n' '2.1.326 (Claude Code)'; exit 0;; + --help) printf '%s\n' '__HELP__'; exit 0;; +esac +printf '%s\n' "$@" > "$BIBCODE_TEST_ARGS" +while IFS= read -r line; do + case "$line" in + *'"type":"user"'*) + printf '%s\n' "$line" + printf '%s\n' '{"type":"system","subtype":"task_started","task_id":"task-bg","tool_use_id":"tool-agent-bg","description":"Background agent","task_type":"local_agent","is_backgrounded":true,"uuid":"task-started","session_id":"fixture-session"}' + printf '%s\n' '{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"task-bg","task_type":"local_agent","description":"Background agent"}],"uuid":"tasks-changed-1","session_id":"fixture-session"}' + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","session_id":"fixture-session","uuid":"result-1"}' + ( + while [ ! -f "$BIBCODE_TEST_RELEASE" ]; do sleep 0.05; done + printf '%s\n' '{"type":"system","subtype":"task_notification","task_id":"task-bg","status":"completed","output_file":"/tmp/task-bg.output","summary":"Done.","uuid":"task-notified","session_id":"fixture-session"}' + printf '%s\n' '{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"tasks-changed-2","session_id":"fixture-session"}' + sleep 0.6 + printf '%s\n' '{"type":"system","subtype":"init","session_id":"fixture-session","uuid":"follow-up-init"}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"follow-up-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background agent finished."}}}' + printf '%s\n' '{"type":"assistant","session_id":"fixture-session","uuid":"follow-up-answer","parent_tool_use_id":null,"message":{"id":"follow-up-message","role":"assistant","content":[{"type":"text","text":"The background agent finished."}]}}' + sleep 0.6 + : > "$BIBCODE_TEST_FOLLOW_UP" + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","origin":{"kind":"task-notification"},"session_id":"fixture-session","uuid":"follow-up-result"}' + ) & + ;; + *'"subtype":"get_context_usage"'*|*'"subtype":"mcp_status"'*) + # Claude answers the queries BiBCode sends after the answer ends. Without this case the + # fixture is the late-answer case, which the unanswered-query test below covers. + request_id=$(printf '%s\n' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + printf '{"type":"control_response","response":{"subtype":"success","request_id":"%s","response":{"totalTokens":1000,"maxTokens":200000,"mcpServers":[]}}}\n' "$request_id" + ;; + esac +done "#; /// Tests (b) and (c), end to end: a real Claude driver whose turn ended while a background @@ -32287,6 +33227,24 @@ done help: &str, launched_with_hook_events: bool, chat_activity: bool, + ) { + assert_claude_background_agent_fixture_outlives_the_idle_deadline( + CLAUDE_BACKGROUND_AGENT_FIXTURE, + help, + launched_with_hook_events, + chat_activity, + true, + ) + .await; + } + + #[cfg(unix)] + async fn assert_claude_background_agent_fixture_outlives_the_idle_deadline( + fixture: &str, + help: &str, + launched_with_hook_events: bool, + chat_activity: bool, + answer_has_its_own_turn: bool, ) { const IDLE_TIMEOUT: Duration = Duration::from_millis(300); let temp = TempDir::new().unwrap(); @@ -32296,7 +33254,7 @@ done let executable = executable_fixture( &temp, "claude-background-agent", - &CLAUDE_BACKGROUND_AGENT_FIXTURE.replace("__HELP__", help), + &fixture.replace("__HELP__", help), ); let engine = supervisor_engine().await; let (deadline_tx, mut deadlines) = mpsc::unbounded_channel(); @@ -32417,14 +33375,29 @@ done .unwrap() .is_none() ); - // Claude's answer is a turn of its own, after the delivered one. + // Claude's answer is stored complete. With a replay first it is a turn of its own, + // after the delivered one; without one BiBCode opens no turn for it. let snapshot = load_snapshot(&engine.repositories()).await.unwrap(); let answer = snapshot .messages .iter() .find(|message| message.text == "The background agent finished.") .expect("Claude's answer to its finished agent is in the thread"); - assert!(!answer.is_streaming); + assert!(!answer.is_streaming, "Claude's answer was left streaming"); + if !answer_has_its_own_turn { + // No turn of its own, and the delivered turn stays completed: the thread reads ready. + let session = engine + .repositories() + .get_thread_session("t1".into()) + .await + .unwrap() + .expect("thread session"); + assert_ne!(session.status, "running", "{session:?}"); + assert_eq!(session.active_turn_id, None); + supervisor.shutdown().await.unwrap(); + engine.shutdown().await; + return; + } assert!(answer.turn_id.is_some()); let delivered_turn = snapshot .messages @@ -32473,6 +33446,183 @@ done .await; } + /// Tests (b) and (c) with the sequence Claude Code 2.1.326 sends while idle: no `user` + /// replay before Claude's own answer. The idle deadline waits for that answer's `result`, + /// which ends the answer's text: it is stored complete, not left streaming. BiBCode opens no + /// turn for it (a known limit in docs/providers/claude.md), so the test claims none. + #[cfg(unix)] + #[tokio::test] + async fn claude_2_1_326_keeps_a_background_agent_past_the_idle_deadline() { + for (help, hook_events) in [ + ("Usage: claude [options]", false), + ("--include-hook-events --forward-subagent-text", true), + ] { + assert_claude_background_agent_fixture_outlives_the_idle_deadline( + CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE, + help, + hook_events, + true, + false, + ) + .await; + } + } + + /// The same, with a Claude that never answers the context query BiBCode sends after the + /// answer ends, while the idle deadline is about to fire: the answer is still stored + /// complete, and the session still suspends. + #[cfg(unix)] + #[tokio::test] + async fn claude_2_1_326_idle_answer_survives_an_unanswered_context_query() { + let query_case = CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE + .find(" *'\"subtype\":\"get_context_usage\"'*") + .expect("the fixture answers queries"); + let end = query_case + + CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE[query_case..] + .find(";;\n") + .expect("the query case ends") + + 3; + let silent = format!( + "{}{}", + &CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE[..query_case], + &CLAUDE_BACKGROUND_AGENT_2_1_326_FIXTURE[end..] + ); + assert!(!silent.contains("get_context_usage")); + assert_claude_background_agent_fixture_outlives_the_idle_deadline( + &silent, + "--include-hook-events --forward-subagent-text", + true, + true, + false, + ) + .await; + } + + /// Claude Code 2.1.326 when the agent finishes while the turn writes its last answer + /// (recorded, see docs/providers/claude.md): `task_notification` inside the turn, no replay, + /// the turn's own `result`, then a turn Claude starts by itself. It answers BiBCode's queries + /// at once, so they cannot delay the idle deadline, and starts its answer only when the test + /// creates `$BIBCODE_TEST_RELEASE`, after the first deadline evaluation. + #[cfg(unix)] + const CLAUDE_AGENT_DONE_DURING_LAST_ANSWER_FIXTURE: &str = r#"#!/bin/sh +case "$1" in + --version) printf '%s\n' '2.1.326 (Claude Code)'; exit 0;; + --help) printf '%s\n' 'Usage: claude [options]'; exit 0;; +esac +while IFS= read -r line; do + case "$line" in + *'"type":"user"'*) + printf '%s\n' "$line" + printf '%s\n' '{"type":"system","subtype":"task_started","task_id":"task-bg","tool_use_id":"tool-agent-bg","description":"Background agent","task_type":"local_agent","is_backgrounded":true,"uuid":"task-started","session_id":"fixture-session"}' + printf '%s\n' '{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"task-bg","task_type":"local_agent","description":"Background agent"}],"uuid":"tasks-changed-1","session_id":"fixture-session"}' + ( + sleep 0.2 + printf '%s\n' '{"type":"system","subtype":"task_notification","task_id":"task-bg","status":"completed","output_file":"/tmp/task-bg.output","summary":"Done.","uuid":"task-notified","session_id":"fixture-session"}' + printf '%s\n' '{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"tasks-changed-2","session_id":"fixture-session"}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"last-answer-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Started the agent."}}}' + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","session_id":"fixture-session","uuid":"result-1"}' + while [ ! -f "$BIBCODE_TEST_RELEASE" ]; do sleep 0.05; done + printf '%s\n' '{"type":"system","subtype":"init","session_id":"fixture-session","uuid":"follow-up-init"}' + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"follow-up-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background agent finished."}}}' + : > "$BIBCODE_TEST_FOLLOW_UP" + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","origin":{"kind":"task-notification"},"session_id":"fixture-session","uuid":"follow-up-result"}' + ) & + ;; + *'"subtype":"get_context_usage"'*) + request_id=$(printf '%s\n' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + printf '{"type":"control_response","response":{"subtype":"success","request_id":"%s","response":{"totalTokens":31251,"maxTokens":200000,"isAutoCompactEnabled":true}}}\n' "$request_id" + ;; + *'"subtype":"mcp_status"'*) + request_id=$(printf '%s\n' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + printf '{"type":"control_response","response":{"subtype":"success","request_id":"%s","response":{"mcpServers":[]}}}\n' "$request_id" + ;; + esac +done +"#; + + /// Known limit, not a goal: an agent that finishes during the turn's last answer, with no + /// replay, leaves nothing BiBCode counts, so once the turn's context queries are answered the + /// idle deadline suspends Claude before the answer it starts by itself arrives. In the + /// recorded sequence that answer started 0.4 to 1.1 seconds after the turn's `result`, well + /// inside the 60-second production timeout; this fixture holds it past the first evaluation. + #[cfg(unix)] + #[tokio::test] + async fn claude_2_1_326_agent_done_during_the_last_answer_is_suspended_when_its_answer_is_late() + { + const IDLE_TIMEOUT: Duration = Duration::from_millis(300); + let temp = TempDir::new().unwrap(); + let follow_up = temp.path().join("follow-up"); + let release = temp.path().join("release"); + let executable = executable_fixture( + &temp, + "claude-agent-done-during-last-answer", + CLAUDE_AGENT_DONE_DURING_LAST_ANSWER_FIXTURE, + ); + let engine = supervisor_engine().await; + let (deadline_tx, mut deadlines) = mpsc::unbounded_channel(); + let activity = super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(super::NativeProviderDriverFactory::new( + temp.path().join("attachments"), + )), + activity, + super::SupervisorOptions { + session_idle_timeout: IDLE_TIMEOUT, + idle_deadline_test_observer: Some(deadline_tx), + ..super::SupervisorOptions::default() + }, + ); + let mut request = native_launch(&temp, "claudeAgent"); + request.thread_id = "t1".to_owned(); + request.binary_path = executable.to_string_lossy().into_owned(); + request.environment.insert( + "BIBCODE_TEST_FOLLOW_UP".to_owned(), + follow_up.to_string_lossy().into_owned(), + ); + request.environment.insert( + "BIBCODE_TEST_RELEASE".to_owned(), + release.to_string_lossy().into_owned(), + ); + supervisor.launch(request).await.unwrap(); + supervisor + .deliver_turn( + IdleDeadlineFixture::turn_command("first"), + "first".to_owned(), + ) + .await + .expect("turn admitted"); + timeout(Duration::from_secs(10), async { + loop { + match deadlines.recv().await.expect("deadline observer") { + super::IdleDeadlineTestEvent::Evaluated { + outcome: super::IdleDeadlineEvaluation::Suspended, + .. + } => { + assert!( + !follow_up.exists(), + "the fixture holds Claude's answer until after the first evaluation" + ); + return; + } + super::IdleDeadlineTestEvent::Evaluated { + outcome: super::IdleDeadlineEvaluation::Failed, + .. + } => panic!("idle suspension failed"), + _ => {} + } + } + }) + .await + .expect("the session is suspended before Claude's late answer"); + // Lets the fixture's background writer finish. + std::fs::write(&release, b"").unwrap(); + supervisor.shutdown().await.unwrap(); + engine.shutdown().await; + } + /// #165: a Claude whose background task finishes during a slow delivered turn (`/compact`). /// Claude replays the task notification just before that turn's `result`, then answers it in /// a turn of its own. Each pause in the answer outlasts the test's idle timeout. @@ -32565,6 +33715,131 @@ done .await; } + /// #389, as Claude Code 2.1.326 emits it: background tasks finish during a delivered turn, + /// Claude replays each notification into that turn and answers them there, under the turn's + /// one `result`, then stays silent. + #[cfg(unix)] + const CLAUDE_NOTIFICATION_ANSWERED_IN_ITS_TURN_FIXTURE: &str = r#"#!/bin/sh +case "$1" in + --version) printf '%s\n' '2.1.326 (Claude Code)'; exit 0;; + --help) printf '%s\n' 'Usage: claude [options]'; exit 0;; +esac +while IFS= read -r line; do + case "$line" in + *'"type":"user"'*) + printf '%s\n' "$line" + for task in $BIBCODE_TEST_TASKS; do + printf '{"type":"system","subtype":"task_started","task_id":"%s","tool_use_id":"tool-%s","description":"Background command","task_type":"local_bash","is_backgrounded":true,"uuid":"started-%s","session_id":"fixture-session"}\n' "$task" "$task" "$task" + done + for task in $BIBCODE_TEST_TASKS; do + printf '{"type":"system","subtype":"task_notification","task_id":"%s","status":"completed","output_file":"/tmp/%s.output","summary":"Done.","uuid":"notified-%s","session_id":"fixture-session"}\n' "$task" "$task" "$task" + done + printf '%s\n' '{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"tasks-changed","session_id":"fixture-session"}' + for task in $BIBCODE_TEST_TASKS; do + printf '{"type":"user","message":{"role":"user","content":"%scompleted"},"origin":{"kind":"task-notification"},"parent_tool_use_id":null,"isReplay":true,"session_id":"fixture-session","uuid":"replayed-%s"}\n' "$task" "$task" + done + printf '%s\n' '{"type":"stream_event","session_id":"fixture-session","uuid":"answer-delta","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The background commands finished."}}}' + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","session_id":"fixture-session","uuid":"turn-result"}' + ;; + esac +done +"#; + + /// #389 (a): one notification answered in its turn. The session suspends at the idle + /// deadline with that one turn completed and no other opened. + #[cfg(unix)] + #[tokio::test] + async fn claude_notification_answered_in_its_turn_leaves_the_thread_ready() { + assert_claude_notification_answered_in_its_turn("task-bg").await; + } + + /// #389 (b): two notifications answered by the turn's one `result`. + #[cfg(unix)] + #[tokio::test] + async fn claude_two_notifications_answered_by_one_result_leave_the_thread_ready() { + assert_claude_notification_answered_in_its_turn("task-a task-b").await; + } + + #[cfg(unix)] + async fn assert_claude_notification_answered_in_its_turn(tasks: &str) { + const IDLE_TIMEOUT: Duration = Duration::from_millis(300); + let temp = TempDir::new().unwrap(); + let executable = executable_fixture( + &temp, + "claude-notification-answered-in-its-turn", + CLAUDE_NOTIFICATION_ANSWERED_IN_ITS_TURN_FIXTURE, + ); + let engine = supervisor_engine().await; + let (deadline_tx, mut deadlines) = mpsc::unbounded_channel(); + let activity = super::ActivityProjection::new(ActivityRepository::new( + engine.repositories().database().clone(), + )); + let supervisor = super::ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(super::NativeProviderDriverFactory::new( + temp.path().join("attachments"), + )), + activity, + super::SupervisorOptions { + session_idle_timeout: IDLE_TIMEOUT, + idle_deadline_test_observer: Some(deadline_tx), + ..super::SupervisorOptions::default() + }, + ); + let mut request = native_launch(&temp, "claudeAgent"); + request.thread_id = "t1".to_owned(); + request.binary_path = executable.to_string_lossy().into_owned(); + request + .environment + .insert("BIBCODE_TEST_TASKS".to_owned(), tasks.to_owned()); + supervisor.launch(request).await.unwrap(); + let command = serde_json::from_value(json!({ + "type":"thread.turn.start", "commandId":"answered-turn", "threadId":"t1", + "message":{"messageId":"user-answered-turn","role":"user","text":"start background commands","attachments":[]}, + "runtimeMode":"full-access", "interactionMode":"default", + "createdAt":"2026-07-16T00:00:01Z" + })) + .unwrap(); + let handle = supervisor + .deliver_turn(command, "answered-turn".to_owned()) + .await + .expect("turn admitted"); + let outcome = timeout(Duration::from_secs(10), handle.completion()) + .await + .expect("Claude acknowledges the turn"); + assert!( + matches!(outcome, super::ProviderDeliveryOutcome::Accepted { .. }), + "{outcome:?}" + ); + timeout(Duration::from_secs(10), async { + loop { + match deadlines.recv().await.expect("deadline observer") { + super::IdleDeadlineTestEvent::Evaluated { + outcome: super::IdleDeadlineEvaluation::Suspended, + .. + } => return, + super::IdleDeadlineTestEvent::Evaluated { + outcome: super::IdleDeadlineEvaluation::Failed, + .. + } => panic!("idle suspension failed"), + _ => {} + } + } + }) + .await + .expect("the session suspends: no turn stays open after the answered notification"); + let snapshot = load_snapshot(&engine.repositories()).await.unwrap(); + let turns = snapshot + .turns + .iter() + .filter(|turn| turn.thread_id == "t1") + .map(|turn| turn.state.as_str()) + .collect::>(); + assert_eq!(turns, ["completed"], "{:?}", snapshot.turns); + supervisor.shutdown().await.unwrap(); + engine.shutdown().await; + } + #[cfg(unix)] async fn assert_claude_follow_up_outlives_the_idle_deadline( name: &str, @@ -34457,6 +35732,138 @@ done )); } + /// #383, through the real driver: a tool that needs approval opens a card, "Always allow + /// this session" answers Claude with session-only rules and closes the card, leaving plan + /// mode is denied without a card, and an interrupt closes what is still open. + #[cfg(unix)] + #[tokio::test] + async fn claude_tool_approval_round_trips_through_the_driver() { + let temp = TempDir::new().expect("provider fixture directory"); + let deadline = ProviderFixtureDeadline::integration(); + let factory = super::NativeProviderDriverFactory::new(temp.path().join("attachments")); + let capture_path = temp.path().join("provider-requests.jsonl"); + let fixture = executable_fixture(&temp, "claude-approval", CLAUDE_APPROVAL_FIXTURE); + let mut request = native_launch(&temp, "claudeAgent"); + request.binary_path = fixture.to_string_lossy().into_owned(); + request.runtime_mode = "approval-required".to_owned(); + request.environment.insert( + "BIBCODE_TEST_REQUEST_CAPTURE".to_owned(), + capture_path.to_string_lossy().into_owned(), + ); + let claude = super::ClaudeDriver::spawn( + request, + factory.attachments.clone(), + factory.attribution.clone(), + true, + factory.claude_probe_cache.clone(), + factory.claude_probe_launch_policy, + false, + ) + .await + .expect("Claude driver should create"); + claude.start().await.expect("Claude should start"); + claude + .send("run it".to_owned(), Vec::new(), "default".to_owned()) + .await + .expect("Claude turn should send"); + + // The next event of the given type, skipping the rest of Claude's output. + let next = |event_type: &'static str| { + let claude = &claude; + async move { + deadline + .observe(async { + loop { + let event = claude.next_event().await.expect("Claude event stream"); + if event.event_type == event_type { + return event; + } + } + }) + .await + .unwrap_or_else(|_| panic!("no {event_type} event before the deadline")) + } + }; + let reply_to = |request_id: &'static str| { + let capture_path = capture_path.clone(); + async move { + captured_request(deadline, &capture_path, move |frame| { + frame["type"] == "control_response" + && frame["response"]["request_id"] == request_id + }) + .await + .unwrap_or_else(|_| panic!("no reply to {request_id} before the deadline")) + } + }; + + let opened = next("request.opened").await; + assert_eq!(opened.request_id.as_deref(), Some("cli-request-1")); + assert_eq!(opened.payload["detail"], "touch made.txt"); + + claude + .approve("cli-request-1".to_owned(), "acceptForSession".to_owned()) + .await + .expect("the session approval is written"); + assert_eq!( + reply_to("cli-request-1").await["response"], + json!({ + "request_id": "cli-request-1", + "subtype": "success", + "response": { + "behavior": "allow", + "updatedInput": { "command": "touch made.txt" }, + // The settings-file destination became the session, and the mode change + // is gone. + "updatedPermissions": [{ + "type": "addRules", + "rules": [{ "toolName": "Bash", "ruleContent": "touch made.txt" }], + "behavior": "allow", + "destination": "session" + }] + } + }) + ); + let resolved = next("request.resolved").await; + assert_eq!(resolved.request_id.as_deref(), Some("cli-request-1")); + assert_eq!(resolved.payload["decision"], "acceptForSession"); + // The same request cannot be answered twice. + assert!( + claude + .approve("cli-request-1".to_owned(), "accept".to_owned()) + .await + .is_err() + ); + + // Leaving plan mode is denied by BiBCode itself, and no card opens for it: the next + // card is the second command's. + let plan_reply = reply_to("cli-plan-1").await; + assert_eq!(plan_reply["response"]["response"]["behavior"], "deny"); + let second = next("request.opened").await; + assert_eq!(second.request_id.as_deref(), Some("cli-request-2")); + assert_eq!(second.payload["detail"], "rm made.txt"); + + // An interrupt leaves nobody to answer the open card, so it closes. + claude + .interrupt(None) + .await + .expect("Claude should interrupt"); + let cancelled = next("request.resolved").await; + assert_eq!(cancelled.request_id.as_deref(), Some("cli-request-2")); + assert_eq!(cancelled.payload["decision"], "cancel"); + assert!( + claude + .approve("cli-request-2".to_owned(), "accept".to_owned()) + .await + .is_err() + ); + let written = std::fs::read_to_string(&capture_path).unwrap_or_default(); + assert!( + !written.contains(r#""request_id":"cli-request-2""#), + "nothing is written for a request that was cancelled" + ); + claude.shutdown().await.expect("Claude should shut down"); + } + #[tokio::test] async fn literal_delivery_cursor() { literal_delivery_acp("cursor", "cursor-session").await; @@ -34565,14 +35972,28 @@ done .interrupt(None) .await .expect("Claude should interrupt"); - claude - .approve("approval-1".to_owned(), "acceptForSession".to_owned()) - .await - .expect("Claude approval should resolve"); - claude - .approve("approval-2".to_owned(), "deny".to_owned()) - .await - .expect("Claude denial should resolve"); + // An approval for a request Claude never made is refused before anything is written, + // in the words the client reads as "this card is stale". + for decision in ["acceptForSession", "decline"] { + let error = claude + .approve("approval-1".to_owned(), decision.to_owned()) + .await + .expect_err("an unknown approval is refused"); + assert!( + error + .to_string() + .contains("Unknown pending approval request"), + "{error}" + ); + } + assert!( + claude + .answer("question-0".to_owned(), json!({"answer":"yes"})) + .await + .expect_err("an unknown question is refused") + .to_string() + .contains("Unknown pending user-input request") + ); claude.runtime.lock().await.open_user_input_request( crate::provider::claude::UserInputRequestInput { tool_name: "AskUserQuestion".to_owned(), @@ -35384,6 +36805,110 @@ done server.abort(); } + #[test] + fn naming_the_default_claude_agent_does_not_restart_the_session() { + // The second message of a new chat names the default agent the first one left out. + assert!(!super::claude_agent_changed(None, Some("claude"))); + assert!(!super::claude_agent_changed(Some("claude"), None)); + assert!(!super::claude_agent_changed(None, None)); + assert!(!super::claude_agent_changed( + Some("reviewer"), + Some("reviewer") + )); + // Another agent is a real change, in both directions. + assert!(super::claude_agent_changed(None, Some("reviewer"))); + assert!(super::claude_agent_changed(Some("reviewer"), None)); + assert!(super::claude_agent_changed( + Some("reviewer"), + Some("claude") + )); + assert!(super::claude_agent_changed( + Some("reviewer"), + Some("planner") + )); + } + + /// A message admitted with the default agent named reaches a session launched without it, + /// on every path that checks the route: a turn start, a steer and a reconciliation. + #[tokio::test] + async fn a_named_default_claude_agent_keeps_the_delivery_route() { + let launch = |options| { + launch_request_for_provider_with_options("claudeAgent", "claude-opus-4-8", options) + }; + let unnamed = launch(vec![]).await; + let named = launch(vec![json!({ "id":"agent", "value":"claude" })]).await; + let reviewer = launch(vec![json!({ "id":"agent", "value":"reviewer" })]).await; + let route = |request: &super::ProviderLaunchRequest| { + super::delivery_route_fingerprint(request).expect("route fingerprint") + }; + let matches = |expected: &super::ProviderLaunchRequest, + running: &super::ProviderLaunchRequest| { + super::delivery_route_matches(&route(expected), running).expect("route match") + }; + assert_ne!(route(&unnamed), route(&named)); + assert!(matches(&named, &unnamed)); + assert!(matches(&unnamed, &named)); + assert!(matches(&named, &named)); + // Another agent is another route, in both directions. + assert!(!matches(&reviewer, &unnamed)); + assert!(!matches(&reviewer, &named)); + assert!(!matches(&unnamed, &reviewer)); + assert!(!matches(&named, &reviewer)); + } + + #[test] + fn switching_a_named_codex_model_to_the_default_restarts_the_session() { + assert!(super::codex_model_cleared( + "codex", + Some("gpt-6.2-sol"), + None + )); + // Nothing to clear, a model change, and providers whose "auto" is a real model. + assert!(!super::codex_model_cleared("codex", None, None)); + assert!(!super::codex_model_cleared("codex", Some("a"), Some("b"))); + assert!(!super::codex_model_cleared( + "cursor", + Some("composer-2"), + None + )); + } + + #[test] + fn a_retired_codex_model_is_dropped_only_for_chatgpt_sign_in() { + let inventory = |auth: Value| vec![json!({ "instanceId": "codex", "auth": auth })]; + let chatgpt = inventory(json!({ "status": "authenticated", "type": "chatgpt" })); + for (stored, retired) in [("gpt-5.4", "gpt-5.4"), ("gpt-5.4-mini", "gpt-5.4-mini")] { + assert_eq!( + super::retired_codex_model_for_chatgpt(&chatgpt, "codex", Some(stored)), + Some(retired) + ); + } + // A model Codex still runs, or none at all, is left alone. + for kept in [Some("gpt-6.2-sol"), None] { + assert_eq!( + super::retired_codex_model_for_chatgpt(&chatgpt, "codex", kept), + None + ); + } + // An API-key session still runs the model, and an unknown sign-in is not guessed. + for auth in [ + json!({ "status": "authenticated", "type": "apiKey" }), + json!({ "status": "authenticated" }), + json!({ "status": "unauthenticated" }), + ] { + assert_eq!( + super::retired_codex_model_for_chatgpt(&inventory(auth), "codex", Some("gpt-5.4")), + None + ); + } + // Another instance's sign-in does not count. + assert_eq!( + super::retired_codex_model_for_chatgpt(&chatgpt, "codex-work", Some("gpt-5.4")), + None + ); + assert!(super::retired_codex_model_notice("gpt-5.4").contains("gpt-5.4")); + } + #[test] fn automatic_model_selection_uses_the_provider_default() { assert_eq!(super::model_from_selection(&json!({"model":"auto"})), None); @@ -36225,6 +37750,66 @@ done } } + #[test] + fn unknown_codex_runtime_mode_starts_supervised() { + for unknown in ["", "bypass", "FULL-ACCESS", "code-review"] { + assert_eq!( + super::runtime_mode(unknown), + crate::provider::codex::CodexRuntimeMode::ApprovalRequired, + "{unknown:?}" + ); + } + } + + /// A review panel switched to Claude launches Claude from the stored modes, as before #376; + /// only Codex reads the marker. + #[tokio::test] + async fn code_review_panel_switched_to_claude_launches_claude_from_its_stored_modes() { + let engine = supervisor_engine().await; + engine + .dispatch(serde_json::from_value(json!({ + "type":"thread.create","commandId":"review","threadId":"review","projectId":"p1", + "title":"Code review","kind":"panel","hostThreadId":"t1","codeReview":true, + "modelSelection":{"instanceId":"codex","model":"gpt-5"}, + "runtimeMode":"approval-required","interactionMode":"plan","branch":null, + "worktreePath":null,"createdAt":"2026-07-16T00:00:00Z" + })).unwrap()) + .await + .unwrap(); + let settings = TempDir::new().expect("provider settings directory"); + for (thread_id, code_review) in [("review", true), ("t1", false)] { + let command = serde_json::from_value(json!({ + "type":"thread.turn.start","commandId":format!("turn-{thread_id}"), + "threadId":thread_id, + "message":{"messageId":format!("m-{thread_id}"),"role":"user","text":"review","attachments":[]}, + "modelSelection":{"instanceId":"claudeAgent","model":"claude-sonnet-4-6"}, + "runtimeMode":"approval-required","interactionMode":"plan", + "createdAt":"2026-07-16T00:00:00Z" + })) + .unwrap(); + let request = super::launch_request_for_command( + &engine, + &settings.path().to_path_buf(), + &command, + None, + ) + .await + .expect("launch request"); + assert_eq!(request.provider, "claudeAgent"); + assert_eq!(request.code_review, code_review); + assert_eq!(request.runtime_mode, "approval-required"); + assert_eq!(request.interaction_mode, "plan"); + assert_eq!( + super::claude_permission_arg(super::claude_mode( + &request.runtime_mode, + &request.interaction_mode + )), + "plan" + ); + } + engine.shutdown().await; + } + #[cfg(target_os = "linux")] #[test] fn provider_chat_launch_ignores_appimage_environment() { diff --git a/apps/server/src/production/server_terminal.rs b/apps/server/src/production/server_terminal.rs index a9baa0b69e..5ee0e447bc 100644 --- a/apps/server/src/production/server_terminal.rs +++ b/apps/server/src/production/server_terminal.rs @@ -35,9 +35,10 @@ use crate::{ }, rpc::{RpcRegistry, RpcResult, RpcStreamChunk}, terminal::{ - AttachmentItem, InputReadmissionScope, TerminalAttachInput, TerminalError, TerminalEvent, - TerminalInputAdmission, TerminalInputOrigin, TerminalLaunchCommand, TerminalManager, - TerminalMetadataEvent, TerminalOpenInput, TerminalSessionIdentity, + AttachmentItem, InputReadmissionScope, SERVER_TERMINAL_THREAD_ID, TerminalAttachInput, + TerminalError, TerminalEvent, TerminalInputAdmission, TerminalInputOrigin, + TerminalLaunchCommand, TerminalManager, TerminalMetadataEvent, TerminalOpenInput, + TerminalSessionIdentity, }, worktree_catalog::{ WorkspaceAdmissionCancellation, WorkspaceAdmissionLease, WorkspaceAvailabilityRegistry, @@ -325,6 +326,10 @@ impl ServerTerminalServices { } pub async fn close_thread_terminals(&self, thread_id: &str) { + // No thread owns the server terminal, so no thread's cleanup ends it. + if thread_id == SERVER_TERMINAL_THREAD_ID { + return; + } let _ = self.terminal.close(thread_id, None).await; } @@ -1115,12 +1120,21 @@ fn register_terminal_rpcs(registry: &mut RpcRegistry, services: &ServerTerminalS }); } +/// The server terminal (#378) has no thread and no workspace: a thread row with its id, left +/// by an older server, must neither lend it a workspace nor block it. +fn workspace_admission_for<'a>( + admission: Option<&'a WorkspaceAdmissionController>, + thread_id: &str, +) -> Option<&'a WorkspaceAdmissionController> { + admission.filter(|_| thread_id != SERVER_TERMINAL_THREAD_ID) +} + async fn acquire_terminal_start( admission: Option<&WorkspaceAdmissionController>, thread_id: &str, cwd: &str, ) -> Result, Value> { - let Some(admission) = admission else { + let Some(admission) = workspace_admission_for(admission, thread_id) else { return Ok(None); }; admission @@ -1134,7 +1148,7 @@ async fn acquire_terminal_attach( admission: Option<&WorkspaceAdmissionController>, input: &TerminalAttachPayload, ) -> Result, Value> { - let Some(admission) = admission else { + let Some(admission) = workspace_admission_for(admission, &input.thread_id) else { return Ok(None); }; if let Some(cwd) = input.cwd.as_deref() { @@ -1325,7 +1339,7 @@ async fn acquire_terminal_thread( admission: Option<&WorkspaceAdmissionController>, thread_id: &str, ) -> Result, Value> { - let Some(admission) = admission else { + let Some(admission) = workspace_admission_for(admission, thread_id) else { return Ok(None); }; admission @@ -1370,7 +1384,7 @@ async fn acquire_terminal_input( admission: Option<&WorkspaceAdmissionController>, thread_id: &str, ) -> Result)>, Value> { - let Some(admission) = admission else { + let Some(admission) = workspace_admission_for(admission, thread_id) else { return Ok(None); }; admission diff --git a/apps/server/src/production/server_terminal_input_tests.rs b/apps/server/src/production/server_terminal_input_tests.rs index 73eb8bf1db..c8394c1c54 100644 --- a/apps/server/src/production/server_terminal_input_tests.rs +++ b/apps/server/src/production/server_terminal_input_tests.rs @@ -939,6 +939,147 @@ async fn begin_thread_input(fixture: &mut Fixture, thread_id: &str, cwd: &Path) .to_owned() } +fn server_terminal_open(cwd: &Path) -> Value { + json!({"threadId": "server-terminal", "terminalId": "server-terminal", "cwd": cwd, "env": {}, "centerPanel": true}) +} + +fn latest_process(fixture: &Fixture) -> Arc { + fixture + .backend + .process + .lock() + .expect("process") + .clone() + .expect("a spawned process") +} + +async fn wait_for_live_sessions(fixture: &Fixture, count: usize) { + tokio::time::timeout(DEADLINE, async { + while fixture.services.terminal.live_session_count().await != count { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("live session count"); +} + +/// A thread row with the server terminal's id (#378), live or deleted, left by an older server +/// that accepted it, neither lends the server terminal a workspace nor stops it opening, even +/// when that row's workspace is unavailable and ordinary admission refuses it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_server_terminal_opens_past_a_thread_row_with_its_id() { + let mut fixture = Fixture::start().await; + let baseline = fixture.services.terminal.live_session_count().await; + let home = fixture.root.join("home"); + std::fs::create_dir_all(&home).expect("home"); + let worktree = fixture.worktree.to_string_lossy().into_owned(); + let _removal = fixture + .registry + .mark_removing("thread-other", &fixture.worktree) + .await + .expect("physical identity resolves"); + let mut deleted = thread_row_in("server-terminal", "project-input", Some(worktree.clone())); + deleted.deleted_at = Some("2026-10-13T00:00:00Z".to_owned()); + for row in [ + thread_row_in("server-terminal", "project-input", Some(worktree.clone())), + deleted, + ] { + fixture + .repositories + .upsert_thread(row) + .await + .expect("thread"); + let opened = success( + fixture + .request("terminal.open", server_terminal_open(&home)) + .await, + ); + assert_eq!(opened["status"], "running", "{opened}"); + } + assert_eq!( + fixture.services.terminal.live_session_count().await, + baseline + 1 + ); + fixture.shutdown().await; +} + +/// Thread-wide cleanup, as a thread's deletion runs it, never reaches the server terminal. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn thread_cleanup_leaves_the_server_terminal_running() { + let mut fixture = Fixture::start().await; + let home = fixture.root.join("home"); + std::fs::create_dir_all(&home).expect("home"); + success( + fixture + .request("terminal.open", server_terminal_open(&home)) + .await, + ); + let shell = latest_process(&fixture); + fixture + .services + .close_thread_terminals("server-terminal") + .await; + assert!(shell.exit.borrow().is_none(), "the server shell was closed"); + fixture.shutdown().await; +} + +/// Two windows (#378): A's shell exits, B opens the terminal again, then everything A can +/// still send arrives late. Only `terminal.open` starts a shell and no client closes one, so +/// B's shell is still the session's and still running at the end. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_late_window_cannot_end_or_replace_the_reopened_server_shell() { + let mut fixture = Fixture::start().await; + let baseline = fixture.services.terminal.live_session_count().await; + let home = fixture.root.join("home"); + std::fs::create_dir_all(&home).expect("home"); + let first = success( + fixture + .request("terminal.open", server_terminal_open(&home)) + .await, + ); + latest_process(&fixture).exit.send_replace(Some(PtyExit { + exit_code: Some(0), + signal: None, + })); + wait_for_live_sessions(&fixture, baseline).await; + + let second = success( + fixture + .request("terminal.open", server_terminal_open(&home)) + .await, + ); + assert_ne!(first["generation"], second["generation"]); + let shell = latest_process(&fixture); + + // A's late traffic: its attach (no working directory), its input and its size, and a + // thread-wide cleanup of the reserved id. None of them starts, restarts or closes a shell. + let key = json!({"threadId": "server-terminal", "terminalId": "server-terminal"}); + fixture.send("terminal.attach", key.clone()).await; + let _ = fixture.reply().await; + let mut write = key.clone(); + write["data"] = json!("late"); + let _ = fixture.request("terminal.write", write).await; + let mut resize = key; + resize["cols"] = json!(100); + resize["rows"] = json!(30); + let _ = fixture.request("terminal.resize", resize).await; + fixture + .services + .close_thread_terminals("server-terminal") + .await; + + assert!(shell.exit.borrow().is_none(), "B's shell was ended"); + assert!( + Arc::ptr_eq(&shell, &latest_process(&fixture)), + "a late message started another shell" + ); + assert_eq!( + fixture.services.terminal.live_session_count().await, + baseline + 1 + ); + fixture.shutdown().await; +} + fn project_moved(project_id: &str, workspace_root: &Path) -> OrchestrationEvent { let mut event = orchestration_event( "project.meta-updated", diff --git a/apps/server/src/production/tool_maintenance.rs b/apps/server/src/production/tool_maintenance.rs index 1c7a41627c..4ba6da3f51 100644 --- a/apps/server/src/production/tool_maintenance.rs +++ b/apps/server/src/production/tool_maintenance.rs @@ -157,6 +157,9 @@ struct State { running: HashMap, update_states: HashMap, next_run: u64, + /// Counts publications, each taking its number with the tools it reads, so a config stream + /// can tell a tools event older than its snapshot. + publications: u64, } struct Inner { @@ -276,8 +279,14 @@ impl ToolMaintenance { /// The published tools: the last probe of each, with any update state on top. pub(crate) fn snapshots(&self) -> Vec { + self.snapshots_with_version().0 + } + + /// The published tools and the number of the last publication that read them: a tools + /// event numbered at or below it holds these tools or older ones. + pub(crate) fn snapshots_with_version(&self) -> (Vec, u64) { let state = self.lock(); - Self::overlay(&state) + (Self::overlay(&state), state.publications) } fn lock(&self) -> std::sync::MutexGuard<'_, State> { @@ -305,13 +314,26 @@ impl ToolMaintenance { .collect() } + /// Replaces the probed tools with `snapshots` and publishes them, as a probe does. + #[cfg(test)] + pub(crate) async fn publish_snapshots_for_tests(&self, snapshots: Vec) { + self.lock().snapshots = snapshots; + self.publish().await; + } + async fn publish(&self) { - let tools = self.snapshots(); + let (tools, version) = { + let mut state = self.lock(); + state.publications += 1; + (Self::overlay(&state), state.publications) + }; let providers = self.inner.publisher.providers.read().await.clone(); let _ = self.inner.publisher.events.send(json!({ "version": 1, "type": "providerStatuses", "payload": { "providers": providers, "tools": tools }, + // Read and removed by each config stream before it sends the event. + "sectionVersion": version, })); } diff --git a/apps/server/src/production/worktree_catalog_rpc.rs b/apps/server/src/production/worktree_catalog_rpc.rs index 574f5bd36d..3a41ac9118 100644 --- a/apps/server/src/production/worktree_catalog_rpc.rs +++ b/apps/server/src/production/worktree_catalog_rpc.rs @@ -1922,6 +1922,10 @@ struct WorktreeRemovalError { message: String, #[serde(skip_serializing_if = "Option::is_none")] current_generation: Option, + /// Set on `thread-not-found` when the thread's removal already finished. An optional field, + /// not a reason, so a client that predates it still decodes the failure (#391). + #[serde(skip_serializing_if = "Option::is_none")] + already_removed: Option, } async fn get_removal_plan( @@ -1943,7 +1947,14 @@ async fn get_removal_plan( // The plan is advisory: execution plans again under the lock and compares the token. let epoch = catalog.mutation_epoch(project_id); let plan = - build_removal_plan(services, project_id, thread_id, None, true, &cancellation).await; + match build_removal_plan(services, project_id, thread_id, None, true, &cancellation) + .await + { + Err(error) if error["reason"] == "thread-not-found" => { + Err(distinguish_removed(services, project_id, thread_id, error).await) + } + other => other, + }; // The lock waits out a mutation in flight, then confirms that nothing moved. let (unchanged, generation) = catalog .with_project_mutation_lock_cancellation(project_id, &cancellation, || async { @@ -1967,11 +1978,44 @@ async fn get_removal_plan( } current_generation = generation; } - Err(encode(removal_error( + let stale = encode(removal_error( WorktreeRemovalErrorReason::StaleGeneration, "The worktree changed while its removal details loaded. Load them again.", current_generation, - ))) + )); + // A detach during the last read moves the catalog too; the target is gone, not stale. + Err(distinguish_removed(services, project_id, thread_id, stale).await) +} + +/// Answers `thread-not-found` with `alreadyRemoved` when the thread's row survives with a +/// deletion mark (a removal finished while the plan loaded, #391), so a client can tell that +/// from a thread that never existed. Otherwise `error` stands. +async fn distinguish_removed( + services: &WorktreeCatalogRpcServices, + project_id: &str, + thread_id: &str, + error: Value, +) -> Value { + let removed = services + .orchestration + .repositories() + .get_thread(thread_id.to_owned()) + .await + .ok() + .flatten() + .is_some_and(|thread| { + thread.project_id == project_id + && thread.kind == "workspace" + && thread.deleted_at.is_some() + }); + if removed { + encode(WorktreeRemovalError { + already_removed: Some(true), + ..removal_not_found() + }) + } else { + error + } } async fn remove_from_bibcode( @@ -2604,10 +2648,25 @@ async fn resolve_removal_thread( }) } +/// Answers `thread-not-found` with `alreadyRemoved` when another removal or detach finished +/// first, as the plan does (#391). async fn resolve_removal_thread_with_ownership( services: &WorktreeCatalogRpcServices, project_id: &str, thread_id: &str, +) -> Result<(WorkspaceOwnershipLease, ResolvedRemovalThread), Value> { + match resolve_removal_thread_owned(services, project_id, thread_id).await { + Err(error) if error["reason"] == "thread-not-found" => { + Err(distinguish_removed(services, project_id, thread_id, error).await) + } + other => other, + } +} + +async fn resolve_removal_thread_owned( + services: &WorktreeCatalogRpcServices, + project_id: &str, + thread_id: &str, ) -> Result<(WorkspaceOwnershipLease, ResolvedRemovalThread), Value> { // The first read discovers a server-owned normalized key. The second read is the // authoritative ownership preflight and remains protected through Git and detach. @@ -3214,6 +3273,7 @@ fn removal_error( reason, message: crate::worktree_catalog::bounded_message(message.into()), current_generation, + already_removed: None, } } @@ -4988,6 +5048,78 @@ mod mutation_invalidation_tests { fixture.handler.shutdown().await; } + #[tokio::test] + async fn plan_for_a_removed_thread_reports_already_removed_not_missing() { + let fixture = RemovalFixture::new().await; + fixture + .remove(fixture.payload().await) + .await + .expect("removal succeeds"); + let plan = |thread_id: &'static str| { + get_removal_plan( + &fixture.handler.services, + request( + "worktree.getRemovalPlan", + json!({"projectId":"project-1", "threadId":thread_id}), + ), + CancellationToken::new(), + ) + }; + let removed = plan("removed-thread") + .await + .expect_err("a removed thread has no plan"); + assert_eq!(removed["reason"], "thread-not-found"); + assert_eq!(removed["alreadyRemoved"], true); + let unknown = plan("never-existed") + .await + .expect_err("an unknown thread has no plan"); + assert_eq!(unknown["reason"], "thread-not-found"); + assert!(unknown.get("alreadyRemoved").is_none()); + fixture.handler.shutdown().await; + } + + /// A detach or a removal that reaches a thread another client already removed reports that + /// outcome, as the plan does, and an unknown thread stays plainly missing. + #[tokio::test] + async fn detach_or_remove_of_a_removed_thread_reports_already_removed_not_missing() { + let fixture = RemovalFixture::new().await; + let payload = fixture.payload().await; + fixture + .remove(payload.clone()) + .await + .expect("removal succeeds"); + let detach = |command_id: &'static str, thread_id: &'static str| { + remove_from_bibcode( + &fixture.handler.services, + request( + "worktree.removeFromBibCode", + json!({"commandId":command_id, "projectId":"project-1", "threadId":thread_id}), + ), + CancellationToken::new(), + ) + }; + let removed = detach("late-detach", "removed-thread") + .await + .expect_err("a removed thread cannot be detached again"); + assert_eq!(removed["reason"], "thread-not-found"); + assert_eq!(removed["alreadyRemoved"], true); + let unknown = detach("unknown-detach", "never-existed") + .await + .expect_err("an unknown thread cannot be detached"); + assert_eq!(unknown["reason"], "thread-not-found"); + assert!(unknown.get("alreadyRemoved").is_none()); + // A second client's removal with the plan it loaded before the first finished. + let mut late_remove = payload; + late_remove["commandId"] = json!("late-remove"); + let removed = fixture + .remove(late_remove) + .await + .expect_err("a removed thread cannot be removed again"); + assert_eq!(removed["reason"], "thread-not-found"); + assert_eq!(removed["alreadyRemoved"], true); + fixture.handler.shutdown().await; + } + #[tokio::test] async fn removal_waits_for_admitted_work_before_checking_the_session() { let mut fixture = RemovalFixture::new().await; @@ -5286,6 +5418,7 @@ mod mutation_invalidation_tests { .expect("plan joins") .expect_err("a plan that raced a detach reads the result again"); assert_eq!(error["reason"], "thread-not-found"); + assert_eq!(error["alreadyRemoved"], true); fixture.handler.shutdown().await; } @@ -5386,6 +5519,47 @@ mod mutation_invalidation_tests { assert_eq!(gate.inventories.load(Ordering::SeqCst), 2); fixture.handler.shutdown().await; } + + #[tokio::test] + async fn plan_answers_already_removed_when_a_detach_lands_during_its_second_read() { + let (fixture, gate) = gated_fixture().await; + let plan = plan_in_flight(&fixture, &gate).await; + fixture + .handler + .catalog + .refresh("project-1", CatalogRefreshTrigger::Explicit) + .await + .expect("refresh during the first read"); + gate.armed.store(true, Ordering::SeqCst); + gate.release.add_permits(1); + tokio::time::timeout(Duration::from_secs(30), gate.entered.acquire()) + .await + .expect("the plan reads again") + .expect("gate open") + .forget(); + remove_from_bibcode( + &fixture.handler.services, + request( + "worktree.removeFromBibCode", + json!({ + "commandId":"detach-command", + "projectId":"project-1", + "threadId":"removed-thread" + }), + ), + CancellationToken::new(), + ) + .await + .expect("detach succeeds"); + gate.release.add_permits(1); + let error = plan + .await + .expect("plan joins") + .expect_err("the target is gone"); + assert_eq!(error["reason"], "thread-not-found"); + assert_eq!(error["alreadyRemoved"], true); + fixture.handler.shutdown().await; + } } #[tokio::test] diff --git a/apps/server/src/production/worktree_runtime.rs b/apps/server/src/production/worktree_runtime.rs index 5cf7af6309..fa84b40143 100644 --- a/apps/server/src/production/worktree_runtime.rs +++ b/apps/server/src/production/worktree_runtime.rs @@ -1130,9 +1130,7 @@ impl WorktreeRuntimeActions for ProductionWorktreeRuntimeActions { if !registry.removal_is_current(&identity) { return Ok(()); } - let terminals_to_close = terminals - .capture_thread_terminal_identities(&thread_id) - .await; + let terminals_to_close = workspace_terminal_identities(&terminals, &thread_id).await; let Some(_signal) = registry.begin_removal_terminal_signal(&identity).await else { return Ok(()); }; @@ -1143,6 +1141,20 @@ impl WorktreeRuntimeActions for ProductionWorktreeRuntimeActions { } } +/// The terminals a workspace's loss or removal stops for `thread_id`. The server terminal +/// (#378) has no workspace, so a thread row left with its id by an older server never reaches it. +async fn workspace_terminal_identities( + terminals: &ServerTerminalServices, + thread_id: &str, +) -> Vec { + if thread_id == crate::terminal::SERVER_TERMINAL_THREAD_ID { + return Vec::new(); + } + terminals + .capture_thread_terminal_identities(thread_id) + .await +} + async fn quiesce_terminals_for_transition( terminals: &ServerTerminalServices, registry: &WorkspaceAvailabilityRegistry, @@ -1152,9 +1164,7 @@ async fn quiesce_terminals_for_transition( if !registry.transition_is_current(transition) { return Ok(()); } - let identities = terminals - .capture_thread_terminal_identities(thread_id) - .await; + let identities = workspace_terminal_identities(terminals, thread_id).await; let Some(_signal_permit) = registry.begin_terminal_signal(transition).await else { return Ok(()); }; @@ -1755,6 +1765,7 @@ mod tests { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, }) .await .expect("provider launches"); @@ -1878,6 +1889,90 @@ mod tests { engine.shutdown().await; } + /// A workspace thread row with the server terminal's id, left by an older server, is + /// detached: the removal's terminal cleanup collects that thread's terminals and must leave + /// the server's home shell running. + #[tokio::test] + async fn production_workspace_removal_leaves_the_server_terminal_running() { + let root = tempfile::tempdir().unwrap(); + let database = Database::open_in_memory().await.unwrap(); + database + .call(|connection| { + run_migrations(connection, None)?; + Ok(()) + }) + .await + .unwrap(); + let activity = ActivityProjection::new(ActivityRepository::new(database.clone())); + let engine = OrchestrationEngine::start(database, EngineOptions::default()) + .await + .unwrap(); + let provider = Arc::new(ProviderRuntimeSupervisor::start( + engine.clone(), + Arc::new(RuntimeTestProvider), + activity, + SupervisorOptions::default(), + )); + let backend = Arc::new(RuntimeTestPtyBackend::default()); + let terminals = TerminalManager::new(backend.clone(), TerminalManagerOptions::default()); + terminals + .open(TerminalOpenInput::new( + crate::terminal::SERVER_TERMINAL_THREAD_ID, + crate::terminal::SERVER_TERMINAL_THREAD_ID, + root.path().to_path_buf(), + 80, + 24, + )) + .await + .expect("server terminal opens"); + let shell = backend.processes()[0].clone(); + let registry = WorkspaceAvailabilityRegistry::new(); + let removal = registry + .mark_removing(crate::terminal::SERVER_TERMINAL_THREAD_ID, root.path()) + .await + .expect("physical identity resolves"); + let actions = super::ProductionWorktreeRuntimeActions { + orchestration: engine.clone(), + provider: provider.clone(), + terminals: runtime_terminal_services(terminals.clone()), + registry, + }; + + actions + .close_terminals_for_removal( + crate::terminal::SERVER_TERMINAL_THREAD_ID.into(), + removal.identity(), + ) + .await + .unwrap(); + + assert!(!shell.is_killed(), "the removal killed the server shell"); + drop(removal); + + // The same row's workspace going missing does not reach it either. + let loss = WorkspaceLossTransition { + thread_id: crate::terminal::SERVER_TERMINAL_THREAD_ID.to_owned(), + path: std::fs::canonicalize(root.path()).unwrap(), + ..transition(1) + }; + actions + .registry + .mark_unavailable(loss.clone()) + .await + .unwrap(); + actions + .close_terminals(crate::terminal::SERVER_TERMINAL_THREAD_ID.into(), loss) + .await + .unwrap(); + assert!( + !shell.is_killed(), + "the workspace loss killed the server shell" + ); + provider.shutdown().await.unwrap(); + terminals.shutdown().await; + engine.shutdown().await; + } + #[derive(Debug)] struct RuntimeTestPty { pid: u32, @@ -4120,6 +4215,7 @@ pub(super) mod removal_test_support { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, } } diff --git a/apps/server/src/provider/claude/follow_up_turn_tests.rs b/apps/server/src/provider/claude/follow_up_turn_tests.rs new file mode 100644 index 0000000000..58bd5b2fa0 --- /dev/null +++ b/apps/server/src/provider/claude/follow_up_turn_tests.rs @@ -0,0 +1,483 @@ +//! A task notification Claude replays into the running turn and answers there (#389). Frame order +//! as Claude Code 2.1.326 emits it in stream-JSON mode with `--replay-user-messages`: the replay +//! comes mid-turn, Claude writes its answer, and the turn's one `result` follows. No other turn +//! follows it, so none may open. + +use serde_json::{Value, json}; + +use super::{CanonicalEvent, ClaudeProviderRuntime, Decision, TurnInput}; + +fn runtime() -> ClaudeProviderRuntime { + let mut runtime = ClaudeProviderRuntime::new("thread".to_owned(), "session".to_owned()); + runtime.start_turn(TurnInput { + turn_id: "delivered".to_owned(), + input: "start a background task".to_owned(), + }); + runtime +} + +fn kinds(runtime: &mut ClaudeProviderRuntime, value: &Value) -> Vec<(String, Option)> { + runtime + .handle_raw_value(value, 1_000) + .events + .into_iter() + .map(|event| (event.event_type, event.turn_id)) + .collect() +} + +fn task(subtype: &str, task_id: &str) -> Value { + let mut value = json!({"type":"system","subtype":subtype,"task_id":task_id,"session_id":"session","uuid":format!("{subtype}-{task_id}")}); + if subtype == "task_started" { + value["task_type"] = json!("local_bash"); + value["is_backgrounded"] = json!(true); + } else { + value["status"] = json!("completed"); + } + value +} + +fn notification() -> Value { + json!({"type":"user","message":{"role":"user","content":""},"origin":{"kind":"task-notification"},"parent_tool_use_id":null,"isReplay":true,"session_id":"session","uuid":"notification"}) +} + +fn text_delta() -> Value { + json!({"type":"stream_event","parent_tool_use_id":null,"session_id":"session","uuid":"delta","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}}) +} + +fn result() -> Value { + json!({"type":"result","subtype":"success","is_error":false,"stop_reason":"end_turn","session_id":"session","uuid":"result"}) +} + +fn assert_answered_in_its_turn(tasks: &[&str]) { + let mut runtime = runtime(); + let mut frames = Vec::new(); + frames.extend(tasks.iter().map(|id| task("task_started", id))); + frames.extend(tasks.iter().map(|id| task("task_notification", id))); + frames.extend(tasks.iter().map(|_| notification())); + frames.push(text_delta()); + for frame in frames { + let output = kinds(&mut runtime, &frame); + assert!( + output.iter().all(|(kind, _)| kind != "turn.started"), + "{output:?}" + ); + } + assert_eq!( + kinds(&mut runtime, &result()), + [("turn.completed".to_owned(), Some("delivered".to_owned()))], + "the turn answered its notifications, so no other turn opens" + ); +} + +/// (a) One notification answered in its turn. +#[test] +fn a_notification_answered_in_its_turn_opens_no_other() { + assert_answered_in_its_turn(&["bg"]); +} + +/// (b) Two notifications answered by the turn's one `result`. +#[test] +fn two_notifications_answered_by_one_result_open_no_turn() { + assert_answered_in_its_turn(&["a", "b"]); +} + +/// Two notifications the turn did not answer each keep their own turn: output in the first +/// follow-up answers only that one. +#[test] +fn two_unanswered_notifications_each_get_a_turn() { + let mut runtime = runtime(); + for frame in [ + task("task_started", "a"), + task("task_started", "b"), + text_delta(), + task("task_notification", "a"), + task("task_notification", "b"), + notification(), + notification(), + ] { + kinds(&mut runtime, &frame); + } + let started = |output: Vec<(String, Option)>| { + output + .iter() + .filter(|(kind, _)| kind == "turn.started") + .count() + }; + assert_eq!( + started(kinds(&mut runtime, &result())), + 1, + "the first answer's turn" + ); + kinds(&mut runtime, &text_delta()); + assert_eq!( + started(kinds(&mut runtime, &result())), + 1, + "the second answer's turn" + ); + kinds(&mut runtime, &text_delta()); + assert_eq!( + started(kinds(&mut runtime, &result())), + 0, + "nothing is owed after both" + ); +} + +/// A carried count does not outlive a stream failure: afterwards an answered notification +/// opens no turn. +#[test] +fn a_stream_failure_forgets_the_carried_follow_ups() { + let mut runtime = runtime(); + for frame in [text_delta(), notification(), notification()] { + kinds(&mut runtime, &frame); + } + kinds(&mut runtime, &result()); + runtime.handle_stream_failure("the stream ended"); + runtime.start_turn(TurnInput { + turn_id: "next".to_owned(), + input: "again".to_owned(), + }); + kinds(&mut runtime, ¬ification()); + kinds(&mut runtime, &text_delta()); + let output = kinds(&mut runtime, &result()); + assert!( + output.iter().all(|(kind, _)| kind != "turn.started"), + "{output:?}" + ); +} + +fn assistant_text() -> Value { + json!({"type":"assistant","parent_tool_use_id":null,"session_id":"session","uuid":"answer","message":{"id":"answer-message","role":"assistant","content":[{"type":"text","text":"Done."}]}}) +} + +fn init() -> Value { + json!({"type":"system","subtype":"init","session_id":"session","uuid":"init"}) +} + +fn idle_result(is_error: bool) -> Value { + json!({"type":"result","subtype":if is_error {"error_during_execution"} else {"success"},"is_error":is_error,"stop_reason":"end_turn","origin":{"kind":"task-notification"},"session_id":"session","uuid":"idle-result"}) +} + +/// Claude Code 2.1.326 answering a background agent that finished while no turn ran: no +/// replay, so no turn opens. The answer's `result` still ends its text, and completes no turn: +/// the delivered turn already ended. +#[test] +fn an_answer_with_no_turn_ends_its_text_and_completes_no_turn() { + let mut runtime = runtime(); + kinds(&mut runtime, &task("task_started", "bg")); + kinds(&mut runtime, &result()); + let mut events = Vec::new(); + for frame in [ + task("task_notification", "bg"), + init(), + text_delta(), + assistant_text(), + idle_result(false), + ] { + events.extend(runtime.handle_raw_value(&frame, 1_000).events); + } + let names: Vec<_> = events + .iter() + .map(|event| event.event_type.as_str()) + .collect(); + assert!(!names.contains(&"turn.started"), "{names:?}"); + assert!(!names.contains(&"turn.completed"), "{names:?}"); + let delta = events + .iter() + .find(|event| event.event_type == "content.delta") + .expect("the answer's text"); + let completed = events + .iter() + .find(|event| event.event_type == "assistant.message.completed") + .unwrap_or_else(|| panic!("the answer's text ends: {names:?}")); + assert_eq!(completed.item_id, delta.item_id); + assert_eq!(completed.turn_id, delta.turn_id); +} + +/// An answer with no turn that streams text, calls a tool, then streams more text under a second +/// message: its `result` ends both texts under the ids each was stored with, and only the last +/// completion ends the answer, so one context query follows it. +#[test] +fn an_answer_with_no_turn_ends_every_text_it_streamed() { + let mut runtime = runtime(); + let message_start = |id: &str| stream(json!({"type":"message_start","message":{"id":id}})); + let events = idle_answer_events( + &mut runtime, + vec![ + message_start("answer-a"), + text_delta(), + tool_start(), + tool_stop(), + tool_result(), + message_start("answer-b"), + text_delta(), + idle_result(false), + ], + ); + let streamed: Vec<_> = events + .iter() + .filter(|event| event.event_type == "content.delta") + .map(|event| (event.turn_id.clone(), event.item_id.clone())) + .collect(); + let completed: Vec<_> = events + .iter() + .filter(|event| event.event_type == "assistant.message.completed") + .collect(); + assert_eq!( + completed + .iter() + .map(|event| (event.turn_id.clone(), event.item_id.clone())) + .collect::>(), + streamed, + "each streamed text completes under its own ids" + ); + assert_eq!(completed[0].payload["answerContinues"], true); + assert_eq!(completed[1].payload, json!({}), "the last ends the answer"); +} + +/// The same answer failing before any output completes nothing and names no turn. +#[test] +fn a_failed_answer_with_no_turn_completes_nothing() { + let mut runtime = runtime(); + kinds(&mut runtime, &task("task_started", "bg")); + kinds(&mut runtime, &result()); + let mut events = Vec::new(); + for frame in [task("task_notification", "bg"), init(), idle_result(true)] { + events.extend(runtime.handle_raw_value(&frame, 1_000).events); + } + let named: Vec<_> = events + .iter() + .map(|event| (event.event_type.clone(), event.turn_id.clone())) + .collect(); + assert!( + named + .iter() + .all(|(kind, turn)| turn.is_none() && !kind.ends_with(".completed")), + "{named:?}" + ); +} + +fn tool_start() -> Value { + json!({"type":"stream_event","parent_tool_use_id":null,"session_id":"session","uuid":"tool-start","event":{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tool-1","name":"Bash","input":{}}}}) +} + +fn tool_stop() -> Value { + json!({"type":"stream_event","parent_tool_use_id":null,"session_id":"session","uuid":"tool-stop","event":{"type":"content_block_stop","index":1}}) +} + +fn tool_result() -> Value { + json!({"type":"user","parent_tool_use_id":null,"session_id":"session","uuid":"tool-result","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"ok"}]}}) +} + +/// The tool items an answer with no turn started, and those it completed. +fn idle_answer_tools(frames: Vec) -> (Vec, Vec) { + let mut runtime = runtime(); + kinds(&mut runtime, &task("task_started", "bg")); + kinds(&mut runtime, &result()); + let mut events = Vec::new(); + for frame in [task("task_notification", "bg"), init()] + .into_iter() + .chain(frames) + { + events.extend(runtime.handle_raw_value(&frame, 1_000).events); + } + assert!( + events.iter().all(|event| event.event_type != "turn.started" + && event.event_type != "turn.completed"), + "no turn opens or completes" + ); + let items = |kind: &str| { + events + .iter() + .filter(|event| event.event_type == kind) + .filter_map(|event| { + event + .provider_refs + .as_ref()? + .get("providerItemId")? + .as_str() + }) + .map(str::to_owned) + .collect::>() + }; + (items("item.started"), items("item.completed")) +} + +/// A tool the answer called completes from its own result, with no turn open. +#[test] +fn a_tool_in_an_answer_with_no_turn_completes_from_its_result() { + let (started, completed) = idle_answer_tools(vec![ + tool_start(), + tool_stop(), + tool_result(), + text_delta(), + idle_result(false), + ]); + assert_eq!(started, ["tool-1"]); + assert_eq!(completed, ["tool-1"]); +} + +/// A result that ends the answer while a tool is still open completes that tool, as a turn's +/// result does. +#[test] +fn a_result_mid_tool_in_an_answer_with_no_turn_completes_the_tool() { + let (started, completed) = + idle_answer_tools(vec![tool_start(), tool_stop(), idle_result(true)]); + assert_eq!(started, ["tool-1"]); + assert_eq!(completed, ["tool-1"]); +} + +/// Every event an answer with no turn produced after the delivered turn ended. +fn idle_answer_events( + runtime: &mut ClaudeProviderRuntime, + frames: Vec, +) -> Vec { + kinds(runtime, &task("task_started", "bg")); + kinds(runtime, &result()); + let mut events = Vec::new(); + for frame in [task("task_notification", "bg"), init()] + .into_iter() + .chain(frames) + { + events.extend(runtime.handle_raw_value(&frame, 1_000).events); + } + assert!( + events.iter().all(|event| event.event_type != "turn.started" + && event.event_type != "turn.completed"), + "no turn opens or completes" + ); + events +} + +fn stream(event: Value) -> Value { + json!({"type":"stream_event","parent_tool_use_id":null,"session_id":"session","uuid":"stream","event":event}) +} + +/// Thinking the answer was still streaming when its result came is completed by that result, +/// as its block's own stop would. +#[test] +fn a_result_mid_thinking_in_an_answer_with_no_turn_completes_the_reasoning() { + let mut runtime = runtime(); + let events = idle_answer_events( + &mut runtime, + vec![ + stream(json!({"type":"message_start","message":{"id":"answer-message"}})), + stream( + json!({"type":"content_block_start","index":0,"content_block":{"type":"thinking"}}), + ), + stream( + json!({"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Checking."}}), + ), + idle_result(true), + ], + ); + let reasoning = events + .iter() + .find(|event| event.payload["streamKind"] == "reasoning_text") + .expect("the reasoning streamed"); + assert!( + events + .iter() + .any(|event| event.event_type == "item.completed" + && event.payload["itemType"] == "reasoning" + && event.item_id == reasoning.item_id + && event.turn_id == reasoning.turn_id), + "{:?}", + events + .iter() + .map(|event| &event.event_type) + .collect::>() + ); +} + +fn can_use_tool() -> Value { + json!({"type":"control_request","request_id":"approval-1","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"ls"},"tool_use_id":"tool-1"}}) +} + +/// An approval the answer asked for and abandoned at its result is withdrawn, as a turn's +/// result withdraws one. +#[test] +fn an_approval_left_pending_at_an_idle_result_is_withdrawn() { + let mut runtime = runtime(); + let events = idle_answer_events(&mut runtime, vec![can_use_tool(), idle_result(true)]); + let opened = events + .iter() + .find(|event| event.event_type == "request.opened") + .expect("the answer asks for approval"); + assert!( + events + .iter() + .any(|event| event.event_type == "request.resolved" + && event.request_id.as_deref() == Some("approval-1") + && event.turn_id == opened.turn_id), + "{:?}", + events + .iter() + .map(|event| &event.event_type) + .collect::>() + ); +} + +/// An approval answered during an answer with no turn resolves as in a turn. +#[test] +fn an_approval_answered_in_an_idle_answer_resolves() { + let mut runtime = runtime(); + idle_answer_events(&mut runtime, vec![can_use_tool()]); + let resolved = runtime + .resolve_permission_request("approval-1", Decision::Accept) + .expect("the approval is pending"); + assert_eq!(resolved.events[0].event_type, "request.resolved"); + let after = idle_answer_tail(&mut runtime); + assert!( + after.iter().all(|event| event != "request.resolved"), + "an answered approval is not withdrawn again: {after:?}" + ); +} + +fn idle_answer_tail(runtime: &mut ClaudeProviderRuntime) -> Vec { + runtime + .handle_raw_value(&idle_result(false), 1_000) + .events + .into_iter() + .map(|event| event.event_type) + .collect() +} + +/// After the answer's result nothing reads busy: no background task and no answer owed. +#[test] +fn an_idle_answer_result_leaves_no_background_work() { + let mut runtime = runtime(); + idle_answer_events(&mut runtime, vec![text_delta()]); + let output = runtime.handle_raw_value(&idle_result(false), 1_000); + assert_eq!(output.background_tasks, Some(0)); +} + +/// A compaction still reported at the answer's result ends there, as at a turn's end, so the +/// session stops reading as compacting. +#[test] +fn a_compaction_open_at_an_idle_answer_result_ends_there() { + let mut runtime = runtime(); + let compacting = runtime.compaction_watch(); + let events = idle_answer_events( + &mut runtime, + vec![ + json!({"type":"system","subtype":"status","status":"compacting","session_id":"session","uuid":"compacting"}), + idle_result(true), + ], + ); + let started = events + .iter() + .find(|event| event.payload["itemType"] == "context_compaction") + .expect("the compaction shows"); + assert!( + events + .iter() + .any(|event| event.event_type == "item.completed" + && event.provider_refs == started.provider_refs), + "{:?}", + events + .iter() + .map(|event| &event.event_type) + .collect::>() + ); + assert!(!*compacting.borrow()); +} diff --git a/apps/server/src/provider/claude/mod.rs b/apps/server/src/provider/claude/mod.rs index 4daa373991..34a3af16fe 100644 --- a/apps/server/src/provider/claude/mod.rs +++ b/apps/server/src/provider/claude/mod.rs @@ -18,8 +18,8 @@ pub(crate) use protocol::ClaudeControlResponseFrame; pub use protocol::{AssistantMessage, ClaudeMessage}; pub use runtime::{ ClaudeControlRequest, ClaudePermissionMode, ClaudeProviderRuntime, Decision, LaunchRequest, - LaunchRequestInput, PermissionRequestInput, ReconnectSnapshot, ResolvedUserInput, RuntimeMode, - TurnInput, UserInputRequestInput, + LaunchRequestInput, PermissionRequestInput, ReconnectSnapshot, ResolvedPermission, + ResolvedUserInput, RuntimeMode, TurnInput, UserInputRequestInput, }; #[doc(hidden)] pub use transcript::{ClaudeTranscriptFixtureAdapter, ClaudeTranscriptFixtureOutput}; diff --git a/apps/server/src/provider/claude/model.rs b/apps/server/src/provider/claude/model.rs index f447f89ac4..f343cf4245 100644 --- a/apps/server/src/provider/claude/model.rs +++ b/apps/server/src/provider/claude/model.rs @@ -5,6 +5,10 @@ use serde_json::{Value, json}; /// How the Fast Mode option is named everywhere a user sees it, including a refusal. pub(crate) const FAST_MODE_LABEL: &str = "Fast Mode"; +/// The agent Claude Code runs when none is named. Starting with `--agent claude` is the same +/// session as starting with no `--agent`. +pub const DEFAULT_AGENT: &str = "claude"; + const MINIMUM_FABLE_5_VERSION: [u64; 3] = [2, 1, 169]; const MINIMUM_OPUS_4_8_VERSION: [u64; 3] = [2, 1, 154]; const MINIMUM_OPUS_4_7_VERSION: [u64; 3] = [2, 1, 111]; diff --git a/apps/server/src/provider/claude/protocol.rs b/apps/server/src/provider/claude/protocol.rs index e46f94cea4..5e040e4eb0 100644 --- a/apps/server/src/provider/claude/protocol.rs +++ b/apps/server/src/provider/claude/protocol.rs @@ -156,10 +156,19 @@ pub struct ResultMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub local_command: Option, pub stop_reason: Option, + /// `task-notification` on the result of a turn Claude started by itself to answer a + /// background task that finished. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub origin: Option, pub session_id: String, pub uuid: String, } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ResultOrigin { + pub kind: String, +} + #[derive(Clone, PartialEq, Deserialize)] pub(crate) struct ClaudeControlResponseFrame { pub response: ClaudeControlResponse, diff --git a/apps/server/src/provider/claude/runtime.rs b/apps/server/src/provider/claude/runtime.rs index 1f694e2be8..66dcce90b2 100644 --- a/apps/server/src/provider/claude/runtime.rs +++ b/apps/server/src/provider/claude/runtime.rs @@ -201,10 +201,14 @@ mod tests { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] +#[serde(rename_all = "camelCase")] pub enum Decision { Accept, - Deny, + AcceptForSession, + /// Refuses this tool use; the turn goes on. + Decline, + /// Refuses this tool use and stops the turn. + Cancel, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -231,6 +235,13 @@ pub struct UserInputRequestInput { pub tool_use_id: String, } +/// What a resolved approval tells Claude: the body of the `control_response`. +#[derive(Debug, Clone, PartialEq)] +pub struct ResolvedPermission { + pub response: Value, + pub events: Vec, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ResolvedUserInput { @@ -272,12 +283,15 @@ struct InFlightTool { #[derive(Debug, Clone)] struct PendingApproval { provider_item_id: String, + /// The turn that asked, which may have ended by the time the request is settled. + turn_id: Option, raw: Value, } #[derive(Debug, Clone)] struct PendingUserInput { provider_item_id: String, + turn_id: Option, original_input: Value, raw: Value, } @@ -1571,6 +1585,9 @@ impl ClaudeBackgroundTasks { #[derive(Debug, Default)] pub struct ClaudeRuntimeOutput { pub events: Vec, + /// `control_response` frames the driver must write to Claude: answers the runtime gives by + /// itself to a request Claude sent. + pub control_responses: Vec, pub activity: Vec, pub native_event_id: Option, /// How much work Claude runs outside a turn (live background tasks, answers it owes), when @@ -1604,6 +1621,9 @@ pub struct ClaudeProviderRuntime { /// open: it can replay the task notification just before that turn's `result` (#165). Each /// opens when the turn before it ends, so idle suspension waits for its own `result`. follow_ups_after_turn: usize, + /// Follow-ups still owed when the open follow-up turn began; its own output answers none of + /// them. + follow_ups_carried: usize, /// Task notifications replayed while a delivered write still awaits its replay. A result /// ignored in that window answered one of them; the rest follow the turn once the write is /// replayed or acknowledged, as a `/compact` is from its `result` alone. @@ -1657,6 +1677,10 @@ pub struct ClaudeProviderRuntime { /// The open turn produced assistant text, a tool call or a compaction. A context-limit /// failure before any is one compacting can fix by sending the message again. turn_produced_output: bool, + /// Claude streamed main-thread text while no turn was open: an answer to a background task + /// it started by itself with no replay (Claude Code 2.1.326). Each text by the turn and item + /// it was stored under, oldest first; its `result` ends them all. + texts_outside_turn: Vec<(Option, Option)>, } /// A copy whose first `system/init` names a session ID BiBCode did not assign: Claude would @@ -1684,6 +1708,7 @@ impl ClaudeProviderRuntime { turn_open: false, turn_input_awaiting_replay: None, follow_ups_after_turn: 0, + follow_ups_carried: 0, follow_ups_awaiting_replay: 0, turn_input_cancellation: CancellationToken::new(), delivery_acknowledgement_cancellation: CancellationToken::new(), @@ -1712,6 +1737,7 @@ impl ClaudeProviderRuntime { turn_compaction_id: None, pending_turn_started: None, turn_produced_output: false, + texts_outside_turn: Vec::new(), } } @@ -1763,6 +1789,7 @@ impl ClaudeProviderRuntime { json!({ "reason": "copy_session_id_mismatch" }), )); ClaudeRuntimeOutput { + control_responses: Vec::new(), events, ..ClaudeRuntimeOutput::default() } @@ -1817,6 +1844,7 @@ impl ClaudeProviderRuntime { self.stop_turn_input(); self.reset_delivery_acknowledgements(); self.follow_ups_after_turn = 0; + self.follow_ups_carried = 0; self.follow_ups_awaiting_replay = 0; self.runtime_mode = Some(runtime_mode); vec![ @@ -1985,6 +2013,9 @@ impl ClaudeProviderRuntime { if self.halted.is_some() { return ClaudeRuntimeOutput::default(); } + if !authenticated_hook && let Some(output) = self.handle_host_request(value) { + return output; + } if !authenticated_hook && value.get("type").and_then(Value::as_str) == Some("system") && value.get("subtype").and_then(Value::as_str) == Some("init") @@ -2010,8 +2041,10 @@ impl ClaudeProviderRuntime { let turn_was_open = self.turn_open; let mut output = self.handle_non_usage_raw_value(value, emitted_at_ms, authenticated_hook); output.background_tasks = background_tasks; - if turn_was_open - && !self.turn_open + // A turn's end, or the end of an answer Claude gave with no turn open. + let idle_answer_ended = !turn_was_open + && value.pointer("/origin/kind").and_then(Value::as_str) == Some("task-notification"); + if (turn_was_open && !self.turn_open || idle_answer_ended) && !authenticated_hook && value.get("type").and_then(Value::as_str) == Some("result") { @@ -2049,10 +2082,19 @@ impl ClaudeProviderRuntime { /// acknowledged. A replay that arrives while another turn is still open starts its turn when /// that one ends. fn start_provider_turn(&mut self, value: &Value) -> Vec { - let follow_up = value.get("type").and_then(Value::as_str) == Some("user") + let kind = value.get("type").and_then(Value::as_str); + let main_thread = value.get("parent_tool_use_id").is_none_or(Value::is_null); + let follow_up = kind == Some("user") && value.pointer("/origin/kind").and_then(Value::as_str) == Some("task-notification") - && value.get("parent_tool_use_id").is_none_or(Value::is_null); + && main_thread; if !follow_up { + // Model output after replays in the open turn: that turn answers them, under its + // one `result`, so no turn follows for them (#389). + // Notifications counted before this turn opened keep their turns. + if self.turn_open && main_thread && matches!(kind, Some("stream_event" | "assistant")) { + self.follow_ups_after_turn = + self.follow_ups_after_turn.min(self.follow_ups_carried); + } return Vec::new(); } if self.turn_input_awaiting_replay.is_some() { @@ -2143,6 +2185,7 @@ impl ClaudeProviderRuntime { self.correlated_activity_enabled = true; } return ClaudeRuntimeOutput { + control_responses: Vec::new(), events: Vec::new(), activity, native_event_id: has_control_effects @@ -2191,6 +2234,7 @@ impl ClaudeProviderRuntime { _ => Vec::new(), }; return ClaudeRuntimeOutput { + control_responses: Vec::new(), events, activity, native_event_id: has_control_effects @@ -2247,6 +2291,7 @@ impl ClaudeProviderRuntime { ClaudeMessageRoute::SuppressedChildText => Vec::new(), }; ClaudeRuntimeOutput { + control_responses: Vec::new(), events, activity, native_event_id: has_control_effects @@ -2506,6 +2551,7 @@ impl ClaudeProviderRuntime { observation_state: ActivityObservationState::Live, }); ClaudeRuntimeOutput { + control_responses: Vec::new(), events: Vec::new(), activity, native_event_id: Some(recovered.native_event_id), @@ -2545,6 +2591,73 @@ impl ClaudeProviderRuntime { events } + /// Handles a request Claude sent to its host over the stream: a tool that needs the person's + /// approval or answer (`can_use_tool`), or the withdrawal of one (`control_cancel_request`). + /// Claude sends these only when it was started with `--permission-prompt-tool stdio`. + /// `None` when `value` is neither. + fn handle_host_request(&mut self, value: &Value) -> Option { + let request_id = value.get("request_id").and_then(Value::as_str)?; + match value.get("type").and_then(Value::as_str)? { + "control_cancel_request" => Some(ClaudeRuntimeOutput { + events: self.cancel_request(request_id), + ..ClaudeRuntimeOutput::default() + }), + "control_request" => { + let request = value.get("request")?; + if request.get("subtype").and_then(Value::as_str) != Some("can_use_tool") { + return None; + } + let tool_name = request + .get("tool_name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let input = request.get("input").cloned().unwrap_or(Value::Null); + let tool_use_id = request + .get("tool_use_id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let mut output = ClaudeRuntimeOutput::default(); + match tool_name.as_str() { + // The plan is read from the tool call and reviewed in BiBCode, so Claude's + // own approval of it is never given here. + "ExitPlanMode" => output.control_responses.push(control_response( + request_id, + &json!({ "behavior": "deny", "message": EXIT_PLAN_MODE_DENIAL }), + )), + "AskUserQuestion" => { + output.events = self.open_user_input_request( + UserInputRequestInput { + tool_name, + input, + tool_use_id, + }, + request_id, + ); + } + _ => { + output.events = self.open_permission_request( + PermissionRequestInput { + tool_name, + input, + tool_use_id, + suggestions: request + .get("permission_suggestions") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + }, + request_id, + ); + } + } + Some(output) + } + _ => None, + } + } + pub fn open_permission_request( &mut self, input: PermissionRequestInput, @@ -2558,6 +2671,7 @@ impl ClaudeProviderRuntime { request_id.to_owned(), PendingApproval { provider_item_id: provider_item_id.clone(), + turn_id: self.current_turn_id.clone(), raw: json!({ "requestId": request_id, "providerItemId": provider_item_id, @@ -2567,35 +2681,86 @@ impl ClaudeProviderRuntime { }), }, ); + let mut payload = json!({ + "requestType": classify_request_type(&input.tool_name), + "toolName": input.tool_name, + "input": input.input, + "suggestions": input.suggestions, + }); + // What the approval card shows: the command, the file or the tool being approved. + if let Some(detail) = permission_request_detail(&input.tool_name, &input.input) { + payload["detail"] = json!(detail); + } vec![self.event( "request.opened", self.current_turn_id.clone(), Some(request_id.to_owned()), Some(json!({ "providerItemId": input.tool_use_id })), - json!({ - "requestType": classify_request_type(&input.tool_name), - "toolName": input.tool_name, - "input": input.input, - "suggestions": input.suggestions, - }), + payload, )] } + /// Settles a pending approval: the reply for Claude and the event that closes the card. + /// `None` when the request is not pending (already answered, cancelled, or never opened), so + /// exactly one decision or cancellation wins. pub fn resolve_permission_request( &mut self, request_id: &str, decision: Decision, - ) -> Vec { - let Some(pending) = self.pending_approvals.remove(request_id) else { - return Vec::new(); + ) -> Option { + let pending = self.pending_approvals.remove(request_id)?; + let session_rules = match decision { + Decision::AcceptForSession => session_permission_updates(&pending.raw["suggestions"]), + Decision::Accept | Decision::Decline | Decision::Cancel => Vec::new(), }; - vec![self.event( + // Claude Code before 2.1.207 rejects an allow without `updatedInput`, so the reply echoes + // the input Claude asked about. + let allow = |session_rules: Option<&[Value]>| { + let mut response = json!({ "behavior": "allow" }); + let input = &pending.raw["input"]; + if !input.is_null() { + response["updatedInput"] = input.clone(); + } + if let Some(rules) = session_rules { + response["updatedPermissions"] = json!(rules); + } + response + }; + let (response, payload) = match decision { + Decision::Decline => ( + json!({ "behavior": "deny", "message": "The user denied this tool use." }), + json!({ "decision": decision }), + ), + Decision::Cancel => ( + json!({ + "behavior": "deny", + "message": "The user stopped the turn.", + "interrupt": true, + }), + json!({ "decision": decision }), + ), + Decision::AcceptForSession if !session_rules.is_empty() => { + (allow(Some(&session_rules)), json!({ "decision": decision })) + } + // No rule to apply: a one-time allow, recorded as one, with the reason. + Decision::AcceptForSession => ( + allow(None), + // `detail` is the line the thread shows on the resolved row. + json!({ + "decision": Decision::Accept, + "detail": "Claude offered no session rule for this request, so it was approved once.", + }), + ), + Decision::Accept => (allow(None), json!({ "decision": decision })), + }; + let events = vec![self.event( "request.resolved", - self.current_turn_id.clone(), + pending.turn_id, Some(request_id.to_owned()), Some(json!({ "providerItemId": pending.provider_item_id })), - json!({ "decision": decision }), - )] + payload, + )]; + Some(ResolvedPermission { response, events }) } pub fn open_user_input_request( @@ -2609,6 +2774,7 @@ impl ClaudeProviderRuntime { request_id.to_owned(), PendingUserInput { provider_item_id: provider_item_id.clone(), + turn_id: self.current_turn_id.clone(), original_input: input.input.clone(), raw: json!({ "requestId": request_id, @@ -2626,15 +2792,13 @@ impl ClaudeProviderRuntime { )] } + /// Settles a pending question. `None` when it is not pending, as for an approval. pub fn resolve_user_input_request( &mut self, request_id: &str, answers: Value, - ) -> ResolvedUserInput { - let pending = self - .pending_user_inputs - .remove(request_id) - .expect("pending user input request"); + ) -> Option { + let pending = self.pending_user_inputs.remove(request_id)?; let updated_input = json!({ "questions": pending .original_input @@ -2645,21 +2809,61 @@ impl ClaudeProviderRuntime { }); let events = vec![self.event( "user-input.resolved", - self.current_turn_id.clone(), + pending.turn_id, Some(request_id.to_owned()), Some(json!({ "providerItemId": pending.provider_item_id })), json!({ "answers": answers }), )]; - ResolvedUserInput { + Some(ResolvedUserInput { updated_input, events, - } + }) + } + + /// Closes a request Claude withdrew, or that its owner (the turn or the process) left + /// behind. Nothing is written to Claude for it. Empty when the request is not pending. + pub fn cancel_request(&mut self, request_id: &str) -> Vec { + if let Some(pending) = self.pending_approvals.remove(request_id) { + return vec![self.event( + "request.resolved", + pending.turn_id, + Some(request_id.to_owned()), + Some(json!({ "providerItemId": pending.provider_item_id })), + json!({ "decision": Decision::Cancel }), + )]; + } + if let Some(pending) = self.pending_user_inputs.remove(request_id) { + return vec![self.event( + "user-input.resolved", + pending.turn_id, + Some(request_id.to_owned()), + Some(json!({ "providerItemId": pending.provider_item_id })), + json!({ "answers": {}, "cancelled": true }), + )]; + } + Vec::new() + } + + /// Closes every pending request. A request belongs to the Claude process and the turn that + /// asked, so an interrupt or the end of the process leaves nobody to answer it. + pub fn cancel_pending_requests(&mut self) -> Vec { + let request_ids = self + .pending_approvals + .keys() + .chain(self.pending_user_inputs.keys()) + .cloned() + .collect::>(); + request_ids + .iter() + .flat_map(|request_id| self.cancel_request(request_id)) + .collect() } pub fn handle_stream_failure(&mut self, error: &str) -> Vec { self.stop_turn_input(); self.delivery_acknowledgement_cancellation.cancel(); self.follow_ups_after_turn = 0; + self.follow_ups_carried = 0; self.follow_ups_awaiting_replay = 0; let error_message = if is_interrupted_error(error) { "Claude runtime interrupted.".to_owned() @@ -2714,6 +2918,7 @@ impl ClaudeProviderRuntime { self.current_turn_id = snapshot.turn_id; self.turn_open = self.current_turn_id.is_some(); self.follow_ups_after_turn = 0; + self.follow_ups_carried = 0; self.follow_ups_awaiting_replay = 0; self.runtime_mode = Some(snapshot.runtime_mode); self.pending_approvals = snapshot @@ -2726,6 +2931,7 @@ impl ClaudeProviderRuntime { request_id, PendingApproval { provider_item_id, + turn_id: None, raw: value, }, )) @@ -2741,6 +2947,7 @@ impl ClaudeProviderRuntime { request_id, PendingUserInput { provider_item_id, + turn_id: None, original_input: json!({ "questions": value.get("questions").cloned().unwrap_or_else(|| json!([])), }), @@ -2844,17 +3051,28 @@ impl ClaudeProviderRuntime { StreamEvent::ContentBlockDelta { index: _, delta: ContentBlockDelta::TextDelta { text }, - } => vec![self.item_event( - "content.delta", - self.current_turn_id.clone(), - None, - None, - json!({ - "streamKind": "assistant_text", - "delta": text, - }), - self.active_assistant_item_id.clone(), - )], + } => { + if !self.turn_open && parent_tool_use_id.is_none() { + let text = ( + self.current_turn_id.clone(), + self.active_assistant_item_id.clone(), + ); + if !self.texts_outside_turn.contains(&text) { + self.texts_outside_turn.push(text); + } + } + vec![self.item_event( + "content.delta", + self.current_turn_id.clone(), + None, + None, + json!({ + "streamKind": "assistant_text", + "delta": text, + }), + self.active_assistant_item_id.clone(), + )] + } // A fragment of the tool's input is not a step of its own: recording each one as an // update made them most of a thread's activity (#167). The input is reported once, // complete, when its block stops. @@ -2970,9 +3188,55 @@ impl ClaudeProviderRuntime { ); return Vec::new(); } + // A turn Claude started by itself with no replay opened no turn here, so its `result` + // completes none: the last turn already ended. It still ends the text it streamed, + // under the turn and item that text was stored with, completes a tool, thinking block or + // compaction it left open and withdraws a request it abandoned, as a turn's end does. + if !self.turn_open + && message + .origin + .as_ref() + .is_some_and(|origin| origin.kind == "task-notification") + { + let mut events = self.flush_incomplete_tools(); + events.extend(self.cancel_pending_requests()); + events.extend(self.end_compaction(None)); + for (message_id, index) in std::mem::take(&mut self.open_reasoning_blocks) { + events.push(self.item_event( + "item.completed", + self.current_turn_id.clone(), + None, + None, + json!({ "itemType": "reasoning" }), + message_id.map(|message_id| format!("{message_id}:{index}")), + )); + } + let texts = std::mem::take(&mut self.texts_outside_turn); + let last = texts.len().saturating_sub(1); + for (index, (turn_id, item_id)) in texts.into_iter().enumerate() { + // Only the last completion ends the answer, so one context query follows it. + let payload = if index < last { + json!({ "answerContinues": true }) + } else { + json!({}) + }; + events.push(self.item_event( + "assistant.message.completed", + turn_id, + None, + None, + payload, + item_id, + )); + } + return events; + } self.stop_turn_input(); self.turn_open = false; let mut events = self.flush_incomplete_tools(); + // A request belongs to the turn that asked. Claude withdraws it before the turn ends; + // one it did not withdraw has nobody left to read an answer. + events.extend(self.cancel_pending_requests()); events.extend(self.end_compaction(None)); let interrupted = is_interrupted_result(&message); let failed = message.is_error && !interrupted; @@ -3043,6 +3307,7 @@ impl ClaudeProviderRuntime { self.follow_ups_after_turn -= 1; events.extend(self.start_follow_up_turn()); } + self.follow_ups_carried = self.follow_ups_after_turn; events } @@ -3512,6 +3777,99 @@ fn claude_hook_native_event_id(value: &Value) -> Option { Some(format!("claude:hook:{encoded}")) } +/// What Claude is told when it asks to leave plan mode. Without a host, Claude Code has no +/// `ExitPlanMode` tool at all and the turn ends with the plan as text. This keeps that outcome. +const EXIT_PLAN_MODE_DENIAL: &str = "The plan is shown to the user in BiBCode, who reviews it there. Do not carry out the plan. End your turn now and wait for the user's decision."; + +/// The `control_response` frame that answers Claude's request `request_id`. +#[must_use] +pub fn control_response(request_id: &str, response: &Value) -> Value { + json!({ + "type": "control_response", + "response": { "request_id": request_id, "subtype": "success", "response": response }, + }) +} + +/// One line for the approval card: the command, else the file or target, else the tool. +fn permission_request_detail(tool_name: &str, input: &Value) -> Option { + let field = [ + "command", + "file_path", + "notebook_path", + "path", + "url", + "pattern", + "query", + ] + .into_iter() + .find_map(|key| input.get(key).and_then(Value::as_str)) + .map(str::trim) + .filter(|value| !value.is_empty()); + let detail = match field { + Some(value) if classify_request_type(tool_name) == "command_execution_approval" => { + value.to_owned() + } + Some(value) => format!("{tool_name}: {value}"), + None => tool_name.trim().to_owned(), + }; + (!detail.is_empty()).then_some(detail) +} + +/// The rules Claude suggested for "always allow", limited to this session. +/// +/// Claude may suggest saving a rule to a settings file, which would outlive the session, so every +/// destination becomes `session`. A suggested mode change is dropped: it would move the session +/// to another permission mode while the thread still shows the one the person chose. +fn session_permission_updates(suggestions: &Value) -> Vec { + // Only what "always allow" means: more allow rules and more readable folders. Anything else, + // a malformed entry included, is not a rule to apply. + let items = |update: &Value, key: &str| update[key].as_array().cloned().unwrap_or_default(); + let is_rule = |rule: &Value| { + rule["toolName"] + .as_str() + .is_some_and(|name| !name.trim().is_empty()) + && (rule.get("ruleContent").is_none() || rule["ruleContent"].is_string()) + }; + let is_directory = |directory: &Value| { + directory + .as_str() + .is_some_and(|path| !path.trim().is_empty()) + }; + suggestions + .as_array() + .into_iter() + .flatten() + .filter_map(|suggestion| { + let mut update = suggestion.as_object()?.clone(); + match suggestion["type"].as_str()? { + "addRules" if suggestion["behavior"] == "allow" => { + let rules = items(suggestion, "rules") + .into_iter() + .filter(is_rule) + .collect::>(); + if rules.is_empty() { + return None; + } + update.insert("rules".to_owned(), json!(rules)); + } + "addDirectories" => { + let directories = items(suggestion, "directories") + .into_iter() + .filter(is_directory) + .collect::>(); + if directories.is_empty() { + return None; + } + update.insert("directories".to_owned(), json!(directories)); + } + _ => return None, + } + update.insert("destination".to_owned(), json!("session")); + Some(Value::Object(update)) + }) + .collect() +} + fn claude_control_fact_native_event_id(value: &Value) -> Option { let mut fields = Vec::with_capacity(12); if value.get("type").and_then(Value::as_str) == Some("system") { @@ -3876,10 +4234,23 @@ fn normalize_questions(input: &Value) -> Vec { .and_then(Value::as_str) .map(str::to_owned) .unwrap_or_else(|| format!("Question {}", index + 1)); + // The question card shows only options with a label and a description, and + // Claude may omit the description. let options = question .get("options") .and_then(Value::as_array) - .cloned() + .map(|options| { + options + .iter() + .map(|option| { + let mut option = option.clone(); + if option.is_object() && !option["description"].is_string() { + option["description"] = json!(""); + } + option + }) + .collect::>() + }) .unwrap_or_default(); Some(json!({ "id": id, @@ -7173,3 +7544,7 @@ mod compaction_turn_tests; #[cfg(test)] #[path = "turn_end_activity_tests.rs"] mod turn_end_activity_tests; + +#[cfg(test)] +#[path = "follow_up_turn_tests.rs"] +mod follow_up_turn_tests; diff --git a/apps/server/src/provider/claude/turn_end_activity_tests.rs b/apps/server/src/provider/claude/turn_end_activity_tests.rs index 1f46f3bcf3..d5531ac8e7 100644 --- a/apps/server/src/provider/claude/turn_end_activity_tests.rs +++ b/apps/server/src/provider/claude/turn_end_activity_tests.rs @@ -209,3 +209,18 @@ fn a_stopped_notification_before_the_task_mapping_applies_once_the_mapping_arriv outputs.extend(launch_mapped_subagent(&mut runtime)); assert_eq!(last_status(&outputs), Some(ActivityLifecycle::Cancelled)); } + +/// A subagent started in an answer Claude gives with no turn open (Claude Code 2.1.326 answering +/// a finished background task) closes at that answer's result as it would at a turn's end. +#[test] +fn a_subagent_absent_at_an_idle_answer_result_closes_there() { + let mut runtime = runtime(); + runtime.handle_raw_value(&result(), 500); + let mut outputs = launch_mapped_subagent(&mut runtime); + assert_eq!(last_status(&outputs), Some(ActivityLifecycle::Running)); + outputs.push(runtime.handle_raw_value(&tasks_changed(json!([])), 2_000)); + let mut idle_result = result(); + idle_result["origin"] = json!({"kind": "task-notification"}); + outputs.push(runtime.handle_raw_value(&idle_result, 2_001)); + assert_eq!(last_status(&outputs), Some(ActivityLifecycle::Interrupted)); +} diff --git a/apps/server/src/provider/codex/model.rs b/apps/server/src/provider/codex/model.rs index 0bcb72527b..8ef05b2097 100644 --- a/apps/server/src/provider/codex/model.rs +++ b/apps/server/src/provider/codex/model.rs @@ -1,7 +1,12 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -const DEFAULT_MODEL: &str = "gpt-5.4"; +/// The slug of "no model chosen": Codex then runs its own recommended model. +pub const AUTO_MODEL: &str = "auto"; +/// Used only where Codex requires a model name and has reported none. A retired model stops a +/// session at Codex's own question, so the name a person did not choose comes from Codex. +const FALLBACK_MODEL: &str = "gpt-6.1-sol"; +const AUTO_MODEL_NAME: &str = "Codex default"; const BIBCODE_BROWSER_TOOL_INSTRUCTIONS: &str = r#" @@ -164,6 +169,9 @@ pub enum CodexRuntimeMode { ApprovalRequired, AutoAcceptEdits, FullAccess, + /// A code review panel's session (#376): never asks, in the read-only sandbox, whatever mode + /// the thread stores. Internal to the server; never a thread's runtime mode on the wire. + CodeReview, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] @@ -670,8 +678,12 @@ pub struct BuildTurnStartInput { pub prompt: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub attachments: Vec, + /// The model the person chose. `None` or `auto` sends no model. #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, + /// The model Codex reported for the thread, for fields that require a name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reported_model: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub service_tier: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -728,6 +740,7 @@ pub fn build_turn_start_params(input: &BuildTurnStartInput) -> Value { CodexRuntimeMode::ApprovalRequired => ("untrusted", json!({ "type": "readOnly" })), CodexRuntimeMode::AutoAcceptEdits => ("on-request", json!({ "type": "workspaceWrite" })), CodexRuntimeMode::FullAccess => ("never", json!({ "type": "dangerFullAccess" })), + CodexRuntimeMode::CodeReview => ("never", json!({ "type": "readOnly" })), }; let mut payload = json!({ @@ -741,7 +754,8 @@ pub fn build_turn_start_params(input: &BuildTurnStartInput) -> Value { payload["clientUserMessageId"] = json!(client_user_message_id); } - if let Some(model) = input.model.as_ref().map(|value| resolve_turn_model(value)) { + let chosen_model = input.model.as_deref().and_then(chosen_turn_model); + if let Some(model) = chosen_model.as_ref() { payload["model"] = json!(model); } if let Some(service_tier) = input.service_tier.as_ref() { @@ -751,11 +765,11 @@ pub fn build_turn_start_params(input: &BuildTurnStartInput) -> Value { payload["effort"] = json!(effort); } if let Some(mode) = input.interaction_mode.as_ref() { - let model = input - .model - .as_ref() - .map(|value| resolve_turn_model(value)) - .unwrap_or_else(|| DEFAULT_MODEL.to_owned()); + // The collaboration mode requires a name: the chosen model, else the one Codex reported + // for this thread. + let model = chosen_model + .or_else(|| input.reported_model.clone()) + .unwrap_or_else(|| FALLBACK_MODEL.to_owned()); payload["collaborationMode"] = json!({ "mode": mode, "settings": { @@ -795,17 +809,66 @@ pub fn is_recoverable_thread_resume_error(message: &str) -> bool { pub fn parse_model_list_response( response: &Value, custom_models: &[String], +) -> Result, String> { + parse_model_list_with_default(response, custom_models, None) +} + +/// As [`parse_model_list_response`], with the model Codex's own configuration names +/// (`config/read`). A configured model is what Codex runs when a request names none, so it wins +/// over the model the list marks with `isDefault`. +pub fn parse_model_list_with_default( + response: &Value, + custom_models: &[String], + configured_default: Option<&str>, ) -> Result, String> { let data = response .get("data") .and_then(Value::as_array) .ok_or_else(|| "model/list response missing data array".to_owned())?; - let mut models = Vec::with_capacity(data.len() + custom_models.len()); + let mut models = Vec::with_capacity(data.len() + custom_models.len() + 1); + // "No model chosen" is the first entry, named after the default Codex reports, so the picker + // shows what Codex will run and the request names no model. + let configured_default = configured_default + .map(str::trim) + .filter(|model| !model.is_empty()); + let default_model = match configured_default { + Some(configured) => data + .iter() + .find(|model| model.get("model").and_then(Value::as_str) == Some(configured)), + None => data + .iter() + .find(|model| model.get("isDefault").and_then(Value::as_bool) == Some(true)), + }; + models.push(CodexProviderModel { + slug: AUTO_MODEL.to_owned(), + name: default_model + .and_then(|model| { + model + .get("displayName") + .or_else(|| model.get("model")) + .and_then(Value::as_str) + }) + // A configured model the list does not offer is still what Codex runs. + .or(configured_default) + .map_or_else( + || AUTO_MODEL_NAME.to_owned(), + |name| format!("{AUTO_MODEL_NAME} ({})", to_display_name(name)), + ), + is_custom: false, + capabilities: default_model + .or_else(|| data.first()) + .map_or(Value::Null, map_model_capabilities), + }); for model in data { let slug = model .get("model") .and_then(Value::as_str) .ok_or_else(|| "model entry missing model".to_owned())?; + // `auto` is reserved for the entry above: a second row with that slug would give the + // picker two choices with one value. + if slug.trim().eq_ignore_ascii_case(AUTO_MODEL) { + continue; + } let display_name = model .get("displayName") .and_then(Value::as_str) @@ -824,12 +887,14 @@ pub fn parse_model_list_response( .collect::>(); let fallback_capabilities = models .iter() + .skip(1) .find(|model| !model.capabilities.is_null()) .map(|model| model.capabilities.clone()) .unwrap_or(Value::Null); for custom in custom_models { let slug = custom.trim(); - if slug.is_empty() || seen.contains(slug) { + // Dispatch reads every casing of `auto` as "no model", so none may be a second entry. + if slug.is_empty() || seen.contains(slug) || slug.eq_ignore_ascii_case(AUTO_MODEL) { continue; } seen.insert(slug.to_owned()); @@ -856,7 +921,7 @@ pub fn fallback_models( let model = configured_model .map(str::trim) .filter(|value| !value.is_empty()) - .unwrap_or(DEFAULT_MODEL); + .unwrap_or(AUTO_MODEL); let selected_effort = configured_effort .map(str::trim) .filter(|value| !value.is_empty()) @@ -880,7 +945,11 @@ pub fn fallback_models( .collect::>(); let mut models = vec![json!({ "slug": model, - "name": to_display_name(model), + "name": if model == AUTO_MODEL { + AUTO_MODEL_NAME.to_owned() + } else { + to_display_name(model) + }, "isCustom": false, "capabilities": { "optionDescriptors": [ @@ -897,14 +966,15 @@ pub fn fallback_models( let mut seen = std::collections::HashSet::from([model.to_owned()]); models.extend(custom_models.iter().filter_map(|custom| { let slug = custom.trim(); - (!slug.is_empty() && seen.insert(slug.to_owned())).then(|| { - json!({ - "slug": slug, - "name": slug, - "isCustom": true, - "capabilities": null, + (!slug.is_empty() && !slug.eq_ignore_ascii_case(AUTO_MODEL) && seen.insert(slug.to_owned())) + .then(|| { + json!({ + "slug": slug, + "name": slug, + "isCustom": true, + "capabilities": null, + }) }) - }) })); models } @@ -1167,14 +1237,56 @@ fn normalize_model_slug(model: &str, preferred_id: Option<&str>) -> String { normalized } -fn resolve_turn_model(model: &str) -> String { - if model.trim().eq_ignore_ascii_case("auto") { - DEFAULT_MODEL.to_owned() - } else { - normalize_model_slug(model, None) +/// The model Codex's own configuration names, from a `config/read` response. Codex runs it when +/// a request names no model, whatever `model/list` marks as default. +#[must_use] +pub fn configured_model(config_response: &Value) -> Option { + config_response + .get("config")? + .get("model")? + .as_str() + .map(str::trim) + .filter(|model| !model.is_empty()) + .map(str::to_owned) +} + +/// The model Codex's `model/list` marks as its default, from one page of that list. +#[must_use] +pub fn reported_default_model(data: &[Value]) -> Option { + data.iter() + .find(|model| model.get("isDefault").and_then(Value::as_bool) == Some(true)) + .and_then(|model| model.get("model")) + .and_then(Value::as_str) + .map(str::to_owned) +} + +/// The retired model that `model` names, directly or through an alias. +/// +/// Codex retired these for sessions signed in with ChatGPT on 31 August 2026. A session that +/// names one stops at Codex's own "no longer available" question. API-key sessions still run them. +#[must_use] +pub fn retired_model(model: &str) -> Option<&'static str> { + match model.trim().to_ascii_lowercase().as_str() { + "gpt-5.4" | "5.4" | "gpt-5-codex" => Some("gpt-5.4"), + "gpt-5.4-mini" => Some("gpt-5.4-mini"), + _ => None, } } +/// Whether two model strings name the same Codex model: the same string, or one retired model +/// under any of its spellings. The one equality a dropped retired model is compared with. +#[must_use] +pub fn same_model(left: &str, right: &str) -> bool { + left == right + || retired_model(left).is_some_and(|retired| retired_model(right) == Some(retired)) +} + +fn chosen_turn_model(model: &str) -> Option { + let model = model.trim(); + (!model.is_empty() && !model.eq_ignore_ascii_case(AUTO_MODEL)) + .then(|| normalize_model_slug(model, None)) +} + fn to_display_name(display_name: &str) -> String { let mut result = display_name.replacen("gpt", "GPT", 1); let mut chars = result.chars().peekable(); @@ -1578,9 +1690,10 @@ mod tests { &[" ".to_owned(), "gpt-test".to_owned(), "custom".to_owned()], ) .expect("fallback model payload should parse"); - assert_eq!(models.len(), 2); - assert_eq!(models[0].name, "GPT-Test"); - assert!(models[1].is_custom); + assert_eq!(models.len(), 3); + assert_eq!(models[0].slug, "auto"); + assert_eq!(models[1].name, "GPT-Test"); + assert!(models[2].is_custom); assert!(parse_skills_list_response(&json!({}), "/workspace").is_err()); assert!( @@ -1616,14 +1729,177 @@ mod tests { prompt: Some(String::new()), attachments: Vec::new(), model: None, + reported_model: None, service_tier: None, effort: None, interaction_mode: Some("plan".to_owned()), }); assert_eq!( turn["collaborationMode"]["settings"]["model"], - DEFAULT_MODEL + FALLBACK_MODEL ); + assert!(turn.get("model").is_none()); + } + + fn plan_turn(model: Option<&str>, reported_model: Option<&str>) -> Value { + build_turn_start_params(&BuildTurnStartInput { + thread_id: "thread".to_owned(), + runtime_mode: CodexRuntimeMode::ApprovalRequired, + client_user_message_id: None, + prompt: Some(String::new()), + attachments: Vec::new(), + model: model.map(str::to_owned), + reported_model: reported_model.map(str::to_owned), + service_tier: None, + effort: None, + interaction_mode: Some("plan".to_owned()), + }) + } + + #[test] + fn a_turn_names_no_model_when_none_was_chosen() { + for unchosen in [None, Some("auto"), Some(" AUTO "), Some("")] { + let turn = plan_turn(unchosen, Some("gpt-reported")); + assert!(turn.get("model").is_none(), "{unchosen:?}"); + // The collaboration mode requires a name: the one Codex reported for the thread. + assert_eq!( + turn["collaborationMode"]["settings"]["model"], + "gpt-reported" + ); + } + } + + #[test] + fn retired_models_are_recognized_by_name_and_alias() { + for (stored, retired) in [ + ("gpt-5.4", "gpt-5.4"), + (" GPT-5.4 ", "gpt-5.4"), + ("5.4", "gpt-5.4"), + ("gpt-5-codex", "gpt-5.4"), + ("gpt-5.4-mini", "gpt-5.4-mini"), + ] { + assert_eq!(retired_model(stored), Some(retired), "{stored}"); + } + for current in ["auto", "gpt-6.2-sol", "gpt-5.3-codex", "gpt-5.6-sol", ""] { + assert_eq!(retired_model(current), None, "{current}"); + } + } + + #[test] + fn a_turn_names_the_chosen_model() { + let turn = plan_turn(Some("gpt-6-astra"), Some("gpt-reported")); + assert_eq!(turn["model"], "gpt-6-astra"); + assert_eq!( + turn["collaborationMode"]["settings"]["model"], + "gpt-6-astra" + ); + } + + #[test] + fn the_built_in_fallback_is_never_a_retired_model() { + let turn = plan_turn(None, None); + let fallback = turn["collaborationMode"]["settings"]["model"] + .as_str() + .expect("fallback model"); + assert_eq!(fallback, "gpt-6.1-sol"); + assert!(!["gpt-5.4", "gpt-5.4-mini"].contains(&fallback)); + } + + #[test] + fn the_model_list_starts_with_the_default_codex_reports() { + let models = parse_model_list_response( + &json!({ "data": [ + { "model": "gpt-other", "displayName": "GPT Other" }, + { "model": "gpt-6.2-sol", "displayName": "GPT-6.2-Sol", "isDefault": true }, + ]}), + &[], + ) + .expect("model list"); + assert_eq!(models[0].slug, "auto"); + assert_eq!(models[0].name, "Codex default (GPT-6.2-Sol)"); + assert!(!models[0].is_custom); + assert_eq!(models[0].capabilities, models[2].capabilities); + assert_eq!( + models.iter().map(|model| &model.slug).collect::>(), + ["auto", "gpt-other", "gpt-6.2-sol"] + ); + } + + #[test] + fn a_configured_model_names_the_default_entry_before_the_listed_default() { + let list = json!({ "data": [ + { "model": "gpt-6.2-sol", "displayName": "GPT-6.2-Sol", "isDefault": true }, + { "model": "gpt-6-sol", "displayName": "GPT-6-Sol" }, + ]}); + // Codex's config.toml names gpt-6-sol: that is what a request with no model runs. + let configured = + parse_model_list_with_default(&list, &[], Some("gpt-6-sol")).expect("model list"); + assert_eq!(configured[0].name, "Codex default (GPT-6-Sol)"); + assert_eq!(configured[0].capabilities, configured[2].capabilities); + // A configured model the list does not offer is still named. + let unlisted = + parse_model_list_with_default(&list, &[], Some("gpt-private")).expect("model list"); + assert_eq!(unlisted[0].name, "Codex default (GPT-Private)"); + // No configured model: the listed default. + let listed = parse_model_list_with_default(&list, &[], Some(" ")).expect("model list"); + assert_eq!(listed[0].name, "Codex default (GPT-6.2-Sol)"); + + assert_eq!( + configured_model(&json!({ "config": { "model": " gpt-6-sol " } })), + Some("gpt-6-sol".to_owned()) + ); + assert_eq!( + configured_model(&json!({ "config": { "model": null } })), + None + ); + assert_eq!(configured_model(&json!({ "config": {} })), None); + assert_eq!(configured_model(&json!({})), None); + } + + #[test] + fn the_reported_default_is_the_model_marked_is_default() { + let data = [ + json!({ "model": "gpt-other" }), + json!({ "model": "gpt-6.2-sol", "isDefault": true }), + ]; + assert_eq!( + reported_default_model(&data), + Some("gpt-6.2-sol".to_owned()) + ); + assert_eq!(reported_default_model(&data[..1]), None); + assert_eq!(reported_default_model(&[]), None); + } + + #[test] + fn a_reported_model_named_auto_does_not_duplicate_the_default_entry() { + let models = parse_model_list_response( + &json!({ "data": [{ "model": "Auto", "isDefault": true }, { "model": "gpt-other" }] }), + &["auto".to_owned(), "AUTO".to_owned()], + ) + .expect("model list"); + assert_eq!( + models.iter().map(|model| &model.slug).collect::>(), + ["auto", "gpt-other"] + ); + } + + #[test] + fn the_default_entry_names_no_model_when_codex_reports_no_default() { + let models = parse_model_list_response( + &json!({ "data": [{ "model": "gpt-other", "displayName": "GPT Other" }] }), + &[], + ) + .expect("model list"); + assert_eq!(models[0].slug, "auto"); + assert_eq!(models[0].name, "Codex default"); + + // The list could not be read at all: the same entry, and no retired name. + let fallback = fallback_models(None, None, None, &[]); + assert_eq!(fallback[0]["slug"], "auto"); + assert_eq!(fallback[0]["name"], "Codex default"); + assert!(!fallback.iter().any(|model| { + ["gpt-5.4", "gpt-5.4-mini"].contains(&model["slug"].as_str().unwrap_or_default()) + })); } #[test] diff --git a/apps/server/src/provider/codex/protocol.rs b/apps/server/src/provider/codex/protocol.rs index 7afc8b96ad..af6f508663 100644 --- a/apps/server/src/provider/codex/protocol.rs +++ b/apps/server/src/provider/codex/protocol.rs @@ -474,10 +474,11 @@ impl JsonRpcConnection { } pub async fn close(&self) { + // Sent even after a failure closed the connection, so the writer releases stdin. + let _ = self.inner.writer.send(WriterMessage::Close); if self.inner.closed.swap(true, Ordering::SeqCst) { return; } - let _ = self.inner.writer.send(WriterMessage::Close); let mut reason = self.inner.close_reason.lock().await; if reason.is_none() { *reason = Some("closed by runtime".to_owned()); @@ -1394,4 +1395,35 @@ mod tests { }) )); } + + #[tokio::test] + async fn close_after_the_peer_exited_releases_stdin_and_the_incoming_channel() { + let (stdout, stdout_peer) = duplex(4096); + let (mut stdin_peer, stdin) = duplex(4096); + let (stderr, stderr_peer) = duplex(4096); + let (connection, mut incoming) = + JsonRpcConnection::spawn(stdout, stdin, stderr, ConnectionConfig::default()); + drop((stdout_peer, stderr_peer)); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while !connection.inner.closed.load(Ordering::SeqCst) { + tokio::task::yield_now().await; + } + }) + .await + .expect("EOF closes the connection"); + connection.close().await; + let mut buffer = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + tokio::io::AsyncReadExt::read_to_end(&mut stdin_peer, &mut buffer), + ) + .await + .expect("stdin is released") + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while incoming.recv().await.is_some() {} + }) + .await + .expect("every task holding the incoming channel ended"); + } } diff --git a/apps/server/src/provider/codex/runtime.rs b/apps/server/src/provider/codex/runtime.rs index 6d355d1c29..609700463b 100644 --- a/apps/server/src/provider/codex/runtime.rs +++ b/apps/server/src/provider/codex/runtime.rs @@ -35,11 +35,11 @@ use super::{ CodexProviderSnapshot, CodexRuntimeMode, ReconciliationThread, ThreadBackgroundTerminalsListParams, ThreadListParams, ThreadReadParams, ThreadReadResponse, TurnsPager, build_initialize_params, build_turn_start_params, - build_turn_steer_params, decode_background_terminals_list_response, + build_turn_steer_params, configured_model, decode_background_terminals_list_response, decode_thread_list_response, decode_thread_read_response, decode_turns_page, delivery_key_in_turns, is_recoverable_thread_resume_error, parse_model_list_response, - parse_skills_list_response, parse_thread_snapshot, reasoning_effort_label, - turn_option_label, + parse_model_list_with_default, parse_skills_list_response, parse_thread_snapshot, + reasoning_effort_label, reported_default_model, turn_option_label, }, protocol::{IncomingEvent, JsonRpcConnection, ProtocolError}, }; @@ -642,6 +642,35 @@ struct PendingRequest { turn_id: Option, } +/// The model Codex runs for a request that names none: the one its configuration names, else +/// the one `model/list` marks as default. `None` when Codex reports neither. +async fn effective_default_model(connection: &JsonRpcConnection) -> Option { + if let Some(model) = bounded_lookup(connection, "config/read") + .await + .as_ref() + .and_then(configured_model) + { + return Some(model); + } + let list = bounded_lookup(connection, "model/list").await?; + reported_default_model(list.get("data")?.as_array()?) +} + +/// How long a lookup made while a session opens may take. The provider supervisor awaits the +/// open for every session, so a Codex that does not answer must not hold it. +const DEFAULT_MODEL_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5); + +/// One request whose failure or silence means "unknown", never a failed launch. +async fn bounded_lookup(connection: &JsonRpcConnection, method: &str) -> Option { + tokio::time::timeout( + DEFAULT_MODEL_LOOKUP_TIMEOUT, + connection.request(method, json!({})), + ) + .await + .ok()? + .ok() +} + pub async fn probe_provider( connection: &JsonRpcConnection, version: &str, @@ -678,8 +707,18 @@ pub async fn probe_provider( break; } } - let models = parse_model_list_response(&json!({ "data": raw_models }), custom_models) - .map_err(|message| RuntimeError::InvalidPayload { message })?; + // What the "Codex default" entry is named after. A Codex without `config/read` names the + // listed default. + let configured = bounded_lookup(connection, "config/read") + .await + .as_ref() + .and_then(configured_model); + let models = parse_model_list_with_default( + &json!({ "data": raw_models }), + custom_models, + configured.as_deref(), + ) + .map_err(|message| RuntimeError::InvalidPayload { message })?; let skills_response = connection .request("skills/list", json!({ "cwds": [cwd] })) @@ -1114,11 +1153,13 @@ impl CodexSessionRuntime { CodexRuntimeMode::ApprovalRequired => "untrusted", CodexRuntimeMode::AutoAcceptEdits => "on-request", CodexRuntimeMode::FullAccess => "never", + CodexRuntimeMode::CodeReview => "never", }, "sandbox": match self.inner.options.runtime_mode { CodexRuntimeMode::ApprovalRequired => "read-only", CodexRuntimeMode::AutoAcceptEdits => "workspace-write", CodexRuntimeMode::FullAccess => "danger-full-access", + CodexRuntimeMode::CodeReview => "read-only", }, "model": self.inner.options.model, "serviceTier": self.inner.options.service_tier, @@ -1144,6 +1185,13 @@ impl CodexSessionRuntime { self.publish_initialize_response_ready(); connection.notify_without_params("initialized").await?; let opened = if let Some(resume_thread_id) = resume_thread_id { + // A thread resumed without a model keeps the one it ran before (measured on + // codex-cli 0.169.0). "No model chosen" means Codex's default, so a resume + // names the model a new thread would run. When Codex reports none, it names none. + let resume_model = match self.inner.options.model.clone() { + Some(model) => Some(model), + None => effective_default_model(&connection).await, + }; match connection .request( "thread/resume", @@ -1154,13 +1202,15 @@ impl CodexSessionRuntime { CodexRuntimeMode::ApprovalRequired => "untrusted", CodexRuntimeMode::AutoAcceptEdits => "on-request", CodexRuntimeMode::FullAccess => "never", + CodexRuntimeMode::CodeReview => "never", }, "sandbox": match self.inner.options.runtime_mode { CodexRuntimeMode::ApprovalRequired => "read-only", CodexRuntimeMode::AutoAcceptEdits => "workspace-write", CodexRuntimeMode::FullAccess => "danger-full-access", + CodexRuntimeMode::CodeReview => "read-only", }, - "model": self.inner.options.model, + "model": resume_model, "serviceTier": self.inner.options.service_tier, }), ) @@ -1229,6 +1279,12 @@ impl CodexSessionRuntime { Ok(self.inner.session.lock().await.clone()) } + /// Shows the person one warning line in the thread. + pub async fn warn(&self, message: &str) { + self.emit("runtime.warning", None, None, json!({ "message": message })) + .await; + } + pub async fn refresh_mcp_status(&self) { let completion = match self.inner.mcp_status.refresh().await { Ok(completion) => completion, @@ -1292,7 +1348,8 @@ impl CodexSessionRuntime { client_user_message_id, prompt: input, attachments, - model: session.model.clone(), + model: self.inner.options.model.clone(), + reported_model: session.model.clone(), service_tier: turn_options.service_tier, effort: turn_options.effort, interaction_mode, @@ -2955,6 +3012,26 @@ impl CodexSessionRuntime { params: Value, ) -> Result<(), RuntimeError> { match method.as_str() { + // A code review runs on its own (#376): nobody answers a card, so it is declined at + // once and never recorded as pending, and the turn goes on. + "item/commandExecution/requestApproval" + | "item/fileChange/requestApproval" + | "item/tool/requestUserInput" + if self.inner.options.runtime_mode == CodexRuntimeMode::CodeReview => + { + let reply = if method == "item/tool/requestUserInput" { + json!({ "answers": {} }) + } else { + json!({ "decision": "decline" }) + }; + tracing::info!( + provider = PROVIDER, + method = method.as_str(), + "declined a Codex request in a code review" + ); + connection.respond(wire_id, reply).await?; + Ok(()) + } "item/commandExecution/requestApproval" => { let request_id = request_scope.approval_id(&correlation_id); let turn_id = params @@ -5337,6 +5414,69 @@ mod tests { assert_ne!(first.request_id, second.request_id); } + #[tokio::test] + async fn code_review_session_declines_codex_requests_without_a_pending_card() { + let requests = [ + ("1", "item/commandExecution/requestApproval"), + ("2", "item/fileChange/requestApproval"), + ("3", "item/tool/requestUserInput"), + ]; + for code_review in [true, false] { + let (connection, _protocol, _peer_stdout, peer_stdin, _peer_stderr) = + runtime_test_connection(); + let (sender, incoming) = mpsc::unbounded_channel(); + let mut options = reconciliation_test_options(); + if code_review { + options.runtime_mode = CodexRuntimeMode::CodeReview; + } + let runtime = CodexSessionRuntime::new(options, connection, incoming); + for (id, method) in requests { + sender + .send(IncomingEvent::Request { + correlation_id: id.to_owned(), + wire_id: json!(id.parse::().unwrap()), + method: method.to_owned(), + params: json!({"turnId":"turn-1","reason":"Approve","questions":[]}), + }) + .expect("request"); + } + if code_review { + let mut reader = BufReader::new(peer_stdin); + let mut replies = Vec::new(); + for _ in requests { + let reply = read_runtime_test_json(&mut reader).await; + replies.push((reply["id"].as_u64().unwrap(), reply["result"].clone())); + } + replies.sort_by_key(|(id, _)| *id); + assert_eq!( + replies, + [ + (1, json!({"decision":"decline"})), + (2, json!({"decision":"decline"})), + (3, json!({"answers":{}})), + ] + ); + assert!(runtime.inner.pending_requests.lock().await.is_empty()); + assert!( + tokio::time::timeout(Duration::from_millis(50), runtime.next_event()) + .await + .is_err(), + "a declined request publishes no request.opened" + ); + } else { + let mut kinds = Vec::new(); + for _ in requests { + kinds.push(runtime.next_event().await.expect("event").event_type); + } + assert_eq!( + kinds, + ["request.opened", "request.opened", "user-input.requested"] + ); + assert_eq!(runtime.inner.pending_requests.lock().await.len(), 3); + } + } + } + #[tokio::test] async fn mcp_catalogue_oversize_thread_resumes_and_completes_followup_turns() { // The peer would kill this transport if asked for its synthetic tool catalogue. diff --git a/apps/server/src/provider/opencode/v2_runtime_tests.rs b/apps/server/src/provider/opencode/v2_runtime_tests.rs index aba31a7839..474bfb7285 100644 --- a/apps/server/src/provider/opencode/v2_runtime_tests.rs +++ b/apps/server/src/provider/opencode/v2_runtime_tests.rs @@ -1170,6 +1170,7 @@ async fn the_driver_speaks_v2_to_an_opencode_2_server_url() { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, }) .await .unwrap_or_else(|error| panic!("driver: {error}")); diff --git a/apps/server/src/pull_requests/gitlab/mod.rs b/apps/server/src/pull_requests/gitlab/mod.rs index 627e50b7af..bcf9323c3a 100644 --- a/apps/server/src/pull_requests/gitlab/mod.rs +++ b/apps/server/src/pull_requests/gitlab/mod.rs @@ -1052,7 +1052,9 @@ mod tests { let s = TestSandbox::new("pr-gitlab-pipeline-cancel"); let script = s.executable_script( "glab", - "printf '%s\\n' \"$*\" >> calls\nsleep 20\necho '{}'", + // Opens the record before writing it, so the race with cancellation is the same + // every run, not only under load. + "exec 3>>calls\nsleep 0.2\nprintf '%s\\n' \"$*\" >&3\nsleep 20\necho '{}'", "", ); let host = GitLabHost::new(Arc::new( @@ -1065,9 +1067,11 @@ mod tests { let c = CancellationToken::new(); let started = std::time::Instant::now(); let read = host.pipeline_graph(&scope, 42, &c); - // Cancel once the read is out on the host, as a leaving subscriber would. + // Cancel once the read is out on the host, as a leaving subscriber would. `>>` creates + // the file before `printf` writes, so wait for the whole recorded line, not the file. let cancel = async { - while !s.path("calls").exists() { + while !std::fs::read_to_string(s.path("calls")).is_ok_and(|calls| calls.ends_with('\n')) + { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } c.cancel(); diff --git a/apps/server/src/source_control/discovery.rs b/apps/server/src/source_control/discovery.rs index bc49302674..f167b8e907 100644 --- a/apps/server/src/source_control/discovery.rs +++ b/apps/server/src/source_control/discovery.rs @@ -229,13 +229,14 @@ impl SourceControlDiscovery { cwd: PathBuf, cancellation: &CancellationToken, ) -> SourceControlDiscoveryResult { - let mut version_control_systems = Vec::with_capacity(VCS_PROBES.len()); - for spec in VCS_PROBES { + // Every tool is probed at once: a missing, signed-out or offline CLI that waits out + // PROBE_TIMEOUT delays the answer by its own bound, not by the sum of all of them. + let vcs = futures_util::future::join_all(VCS_PROBES.iter().map(|spec| async { let result = self .probe(&cwd, spec.executable, spec.version_args, None, cancellation) .await; let available = result.as_ref().is_some_and(|output| output.exit_code == 0); - version_control_systems.push(VcsDiscoveryItem { + VcsDiscoveryItem { kind: spec.kind, label: spec.label.into(), executable: spec.executable.into(), @@ -252,11 +253,9 @@ impl SourceControlDiscovery { } else { WireOption::none() }, - }); - } - - let mut source_control_providers = Vec::with_capacity(PROVIDER_PROBES.len() + 1); - for spec in PROVIDER_PROBES { + } + })); + let providers = futures_util::future::join_all(PROVIDER_PROBES.iter().map(|spec| async { let version = self .probe( &cwd, @@ -281,7 +280,7 @@ impl SourceControlDiscovery { } else { unknown_auth("Hosting integration command was not found on the server PATH.") }; - source_control_providers.push(SourceControlProviderDiscoveryItem { + SourceControlProviderDiscoveryItem { kind: spec.kind, label: spec.label.into(), executable: Some(spec.executable.into()), @@ -298,8 +297,10 @@ impl SourceControlDiscovery { WireOption::none() }, auth, - }); - } + } + })); + let (version_control_systems, mut source_control_providers) = + futures_util::future::join(vcs, providers).await; source_control_providers.push(SourceControlProviderDiscoveryItem { kind: ProviderKind::Bitbucket, label: "Bitbucket".into(), @@ -525,6 +526,53 @@ mod tests { assert_eq!(jj.status, DiscoveryStatus::Missing); } + #[cfg(unix)] + #[tokio::test] + async fn discovery_probes_every_tool_at_once_and_keeps_the_order() { + let sandbox = crate::test_support::TestSandbox::new("discovery-concurrent"); + let directory = sandbox.path("bin"); + std::fs::create_dir(&directory).unwrap(); + for executable in ["jj", "gh", "glab", "az"] { + crate::test_support::TestSandbox::write_executable( + &directory.join(executable), + "#!/bin/sh\nsleep 1\necho 'tool 1.0'\n", + ); + } + let discovery = SourceControlDiscovery::with_executable_dir_for_integration_test(directory); + let started = std::time::Instant::now(); + let result = discovery + .discover(sandbox.root().to_path_buf(), &CancellationToken::new()) + .await; + let elapsed = started.elapsed(); + // One after another this takes at least 7 s: jj once, gh, glab and az twice each + // (version, then sign-in). Together it is the longest chain, about 2 s. + assert!( + elapsed < Duration::from_secs(5), + "discovery took {elapsed:?}" + ); + assert_eq!( + result + .version_control_systems + .iter() + .map(|item| item.kind) + .collect::>(), + [VcsDiscoveryKind::Git, VcsDiscoveryKind::Jj] + ); + assert_eq!( + result + .source_control_providers + .iter() + .map(|item| (item.kind, item.status)) + .collect::>(), + [ + (ProviderKind::Github, DiscoveryStatus::Available), + (ProviderKind::Gitlab, DiscoveryStatus::Available), + (ProviderKind::AzureDevops, DiscoveryStatus::Available), + (ProviderKind::Bitbucket, DiscoveryStatus::Missing), + ] + ); + } + #[cfg(unix)] #[tokio::test] async fn discovery_runs_glab_with_telemetry_off() { diff --git a/apps/server/src/terminal/mod.rs b/apps/server/src/terminal/mod.rs index a53d6c91bb..43d0934acf 100644 --- a/apps/server/src/terminal/mod.rs +++ b/apps/server/src/terminal/mod.rs @@ -28,3 +28,7 @@ pub use pty::{ ExhaustedResize, PortablePtyBackend, PtyBackend, PtyExit, PtyProcess, PtySpawnInput, }; pub use writer::WriteGuard; + +/// The thread id of the terminal each server owns in its user's home folder (#378). The +/// engine refuses to create a thread with it, so no thread terminal shares that session. +pub const SERVER_TERMINAL_THREAD_ID: &str = "server-terminal"; diff --git a/apps/server/src/workspace/entries.rs b/apps/server/src/workspace/entries.rs index 4848f110a7..58fc8ebb5c 100644 --- a/apps/server/src/workspace/entries.rs +++ b/apps/server/src/workspace/entries.rs @@ -193,13 +193,39 @@ pub async fn browse_directory( } fn expand_home(input: &str) -> PathBuf { + if !input.starts_with('~') { + return PathBuf::from(input); + } + let home = + environment_home(cfg!(windows), &|name| std::env::var_os(name)).or_else(dirs::home_dir); + expand_home_from(input, home) +} + +/// The home the environment names, in the order Cursor capability discovery reads it: +/// USERPROFILE then HOME on Windows, HOME elsewhere. `dirs::home_dir` ignores both on Windows. +fn environment_home( + windows: bool, + variable: &dyn Fn(&str) -> Option, +) -> Option { + let names: &[&str] = if windows { + &["USERPROFILE", "HOME"] + } else { + &["HOME"] + }; + names + .iter() + .find_map(|name| variable(name).filter(|value| !value.is_empty())) + .map(PathBuf::from) +} + +fn expand_home_from(input: &str, home: Option) -> PathBuf { if input == "~" { - return dirs::home_dir().unwrap_or_else(|| PathBuf::from(input)); + return home.unwrap_or_else(|| PathBuf::from(input)); } if let Some(rest) = input .strip_prefix("~/") .or_else(|| input.strip_prefix("~\\")) - && let Some(home) = dirs::home_dir() + && let Some(home) = home { return home.join(rest); } @@ -219,6 +245,56 @@ fn looks_like_windows_absolute(input: &str) -> bool { mod tests { use super::*; + /// `~` follows the home the environment names, as a shell does, before the platform's own + /// lookup: USERPROFILE then HOME on Windows, HOME elsewhere. An empty value is unset. + #[test] + fn home_follows_the_environment_before_the_platform_lookup() { + let environment = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| { + pairs + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| std::ffi::OsString::from(value)) + } + }; + let both = environment(&[ + ("USERPROFILE", "/fixture/profile"), + ("HOME", "/fixture/home"), + ]); + assert_eq!( + environment_home(true, &both), + Some(PathBuf::from("/fixture/profile")) + ); + assert_eq!( + environment_home(false, &both), + Some(PathBuf::from("/fixture/home")) + ); + let home_only = environment(&[("USERPROFILE", ""), ("HOME", "/fixture/home")]); + assert_eq!( + environment_home(true, &home_only), + Some(PathBuf::from("/fixture/home")) + ); + let profile_only = environment(&[("USERPROFILE", "/fixture/profile")]); + assert_eq!(environment_home(false, &profile_only), None); + assert_eq!(environment_home(true, &environment(&[])), None); + + let home = Some(PathBuf::from("/fixture/home")); + assert_eq!( + expand_home_from("~", home.clone()), + PathBuf::from("/fixture/home") + ); + assert_eq!( + expand_home_from("~/code", home.clone()), + PathBuf::from("/fixture/home").join("code") + ); + assert_eq!( + expand_home_from("~\\code", home.clone()), + PathBuf::from("/fixture/home").join("code") + ); + assert_eq!(expand_home_from("~other", home), PathBuf::from("~other")); + assert_eq!(expand_home_from("~/code", None), PathBuf::from("~/code")); + } + #[tokio::test] async fn browse_covers_relative_hidden_sorted_and_missing_directories() { let root = tempfile::tempdir().unwrap(); diff --git a/apps/server/src/workspace/mod.rs b/apps/server/src/workspace/mod.rs index 5b4163a8fe..74bc30a6d4 100644 --- a/apps/server/src/workspace/mod.rs +++ b/apps/server/src/workspace/mod.rs @@ -15,7 +15,10 @@ pub use rpc::{ WorkspaceMutationObserver, WorkspaceRpc, WorkspaceRpcDependencies, }; #[allow(unused_imports)] -pub use search::{EntryKind, SearchLimits, SearchResult, WorkspaceEntry, WorkspaceSearchIndex}; +pub use search::{ + EntryKind, ListPage, SearchLimits, SearchResult, StaleCursor, WorkspaceEntry, + WorkspaceSearchIndex, +}; #[allow(unused_imports)] pub(crate) use service::PathLocks; pub use service::{ReadFileResult, WorkspaceService}; diff --git a/apps/server/src/workspace/rpc.rs b/apps/server/src/workspace/rpc.rs index 8bc7113fa7..5cb24296be 100644 --- a/apps/server/src/workspace/rpc.rs +++ b/apps/server/src/workspace/rpc.rs @@ -33,6 +33,9 @@ use super::watcher::{WatchScope, WatchScopeFuture, WatchSubscription, WorkspaceW use super::{EntryKind, SearchLimits, WorkspaceError, WorkspaceSearchIndex, WorkspaceService}; const PROJECT_ENTRIES_MAX_LIMIT: usize = 200; +/// The most one page of a paged list encodes to (#390). It leaves room for the RPC envelope under +/// the 1 MiB logical message a remote client accepts. +const PROJECT_ENTRIES_PAGE_TARGET_BYTES: usize = 1024 * 1024 - 64 * 1024; pub const TASK_SIX_RPC_METHODS: [&str; 18] = [ "projects.searchEntries", @@ -556,13 +559,24 @@ impl WorkspaceRpc { let input: ListInput = decode(payload)?; let _admission = self.acquire_path(&input.cwd).await?; // Out-of-band filesystem changes are invisible to the cached snapshot, so a - // request must opt in before paying for a full rebuild. - if input.refresh == Some(true) { + // request must opt in before paying for a full rebuild. A later page never + // rebuilds: that would end the snapshot it pages. + if input.refresh == Some(true) && input.cursor.is_none() { self.refresh_index(Path::new(&input.cwd)).await; } let index = self.index(&input.cwd).await.map_err(|error| { entries_wire_error("ProjectListEntriesError", &input.cwd, &error) })?; + // `limit` wins over paging; neither keeps the whole-list reply older clients read. + if input.limit.is_none() && (input.paged == Some(true) || input.cursor.is_some()) { + let page = index + .page(input.cursor.as_deref(), PROJECT_ENTRIES_PAGE_TARGET_BYTES) + .await + .map_err(|_| stale_cursor_wire_error(&input.cwd))?; + return encode(page).map_err(|error| { + entries_wire_error("ProjectListEntriesError", &input.cwd, &error) + }); + } let limit = input .limit .map(|limit| limit.clamp(1, PROJECT_ENTRIES_MAX_LIMIT)); @@ -1567,6 +1581,16 @@ fn entries_wire_error(tag: &str, cwd: &str, error: &WorkspaceError) -> Value { }) } +/// The page cursor names a list the index no longer holds; the client lists again from the start. +fn stale_cursor_wire_error(cwd: &str) -> Value { + json!({ + "_tag": "ProjectListEntriesError", + "cwd": cwd, + "failure": "search_index_cursor_stale", + "message": "The workspace file list changed while it was being read.", + }) +} + fn filesystem_wire_error(input: &BrowseInput, error: &WorkspaceError) -> Value { json!({ "_tag": "FilesystemBrowseError", @@ -1746,6 +1770,10 @@ struct ListInput { cwd: String, limit: Option, refresh: Option, + /// Asks for the first page of a paged list (#390). + paged: Option, + /// The previous page's `nextCursor`. + cursor: Option, } #[derive(Deserialize)] @@ -1906,6 +1934,94 @@ mod tests { root } + /// 260 folders of `components` files each, with paths of about 80 bytes (#390): 95 makes + /// 24,991 entries, just under the 25,000-entry snapshot cap; 100 passes it. + fn large_entry_workspace(components: usize) -> tempfile::TempDir { + let root = tempfile::tempdir().expect("large workspace root"); + for package in 0..10 { + for feature in 0..26 { + let directory = root.path().join(format!( + "packages/package-name-{package:02}/src/components/feature-area-{feature:03}" + )); + std::fs::create_dir_all(&directory).expect("fixture directory"); + for component in 0..components { + std::fs::write( + directory.join(format!("ComponentName{component:03}.test.tsx")), + "", + ) + .expect("fixture file"); + } + } + } + root + } + + /// A paged list keeps each page within the budget and concatenates to the whole list; an + /// omitted `limit` and cursor still answer the whole list at once, which older clients read; + /// a cursor from an older snapshot is refused; `limit` keeps its 200 cap (#390). + #[tokio::test] + async fn a_paged_list_stays_within_the_page_budget_and_matches_the_whole_list() { + let root = large_entry_workspace(95); + let cwd = root.path().to_string_lossy().into_owned(); + let rpc = WorkspaceRpc::new(WorkspaceService::default()); + let whole = rpc + .handle("projects.listEntries", json!({ "cwd": cwd })) + .await + .expect("whole list"); + let whole_bytes = serde_json::to_vec(&whole).expect("reply JSON").len(); + assert_eq!(whole["entries"].as_array().expect("entries").len(), 24_991); + assert_eq!(whole["truncated"], false); + assert!(whole.get("nextCursor").is_none()); + + let mut request = json!({ "cwd": cwd, "paged": true }); + let (mut entries, mut sizes, mut second_cursor) = (Vec::new(), Vec::new(), None); + loop { + let page = rpc + .handle("projects.listEntries", request.clone()) + .await + .expect("page"); + let bytes = serde_json::to_vec(&page).expect("page JSON").len(); + assert!( + bytes <= PROJECT_ENTRIES_PAGE_TARGET_BYTES, + "page is {bytes} bytes" + ); + assert_eq!(page["truncated"], false); + sizes.push(bytes); + entries.extend(page["entries"].as_array().expect("entries").iter().cloned()); + let Some(cursor) = page["nextCursor"].as_str() else { + break; + }; + second_cursor.get_or_insert_with(|| cursor.to_owned()); + request = json!({ "cwd": cwd, "cursor": cursor }); + } + eprintln!( + "listEntries: whole {whole_bytes} bytes; {} pages of {sizes:?} bytes", + sizes.len() + ); + assert!(sizes.len() > 1); + assert_eq!(Value::Array(entries), whole["entries"]); + + rpc.refresh_index(root.path()).await; + let stale = rpc + .handle( + "projects.listEntries", + json!({ "cwd": cwd, "cursor": second_cursor.expect("second page") }), + ) + .await + .expect_err("stale cursor"); + assert_eq!(stale["failure"], "search_index_cursor_stale"); + + let limited = rpc + .handle( + "projects.listEntries", + json!({ "cwd": cwd, "limit": 1000, "paged": true }), + ) + .await + .expect("limited list"); + assert_eq!(limited["entries"].as_array().expect("entries").len(), 200); + assert_eq!(limited["truncated"], true); + } + fn index_benchmark_workspace() -> tempfile::TempDir { let root = tempfile::tempdir().expect("benchmark workspace root"); initialize_index_git_workspace(root.path()); diff --git a/apps/server/src/workspace/search.rs b/apps/server/src/workspace/search.rs index 0fcc2881d7..6f04056738 100644 --- a/apps/server/src/workspace/search.rs +++ b/apps/server/src/workspace/search.rs @@ -4,6 +4,7 @@ use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; @@ -85,6 +86,21 @@ pub struct SearchResult { pub truncated: bool, } +/// One page of a paged list (#390): `next_cursor` names the next page of the same snapshot and is +/// absent on the last page. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListPage { + pub entries: Vec, + pub truncated: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, +} + +/// A page cursor that names another snapshot than the current one, or no snapshot at all. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StaleCursor; + #[derive(Debug, Clone, Copy)] pub struct SearchLimits { pub max_entries: usize, @@ -104,6 +120,8 @@ impl Default for SearchLimits { #[derive(Default)] struct SearchSnapshot { + /// Zero until the first build; a page cursor names it. + generation: u64, entries: Vec, memory_bytes: usize, truncated: bool, @@ -210,6 +228,12 @@ pub struct WorkspaceSearchIndex { root: PathBuf, limits: SearchLimits, snapshot: Arc>, + /// Every build of this index gets the next generation, so a cursor can tell when the list it + /// pages moved. + generations: Arc, + /// A random value per index, in every cursor, so a cursor from another index (one a server ran + /// before it restarted, whose generations also start at 1) is refused. + instance: u64, #[cfg(test)] phase_sink: Option, } @@ -220,6 +244,11 @@ impl WorkspaceSearchIndex { root, limits, snapshot: Arc::new(RwLock::new(SearchSnapshot::default())), + generations: Arc::new(AtomicU64::new(1)), + instance: std::hash::BuildHasher::hash_one( + &std::collections::hash_map::RandomState::new(), + (), + ), #[cfg(test)] phase_sink: None, } @@ -282,6 +311,8 @@ impl WorkspaceSearchIndex { if cancellation.is_cancelled() { return Err(WorkspaceError::Cancelled); } + let mut scanned = scanned; + scanned.generation = self.generations.fetch_add(1, Ordering::Relaxed); *self.snapshot.write().await = scanned; Ok(()) } @@ -300,6 +331,53 @@ impl WorkspaceSearchIndex { } } + /// One page of the snapshot that encodes to at most `budget` bytes, and always at least one + /// entry (#390). `cursor` is `None` for the first page, otherwise the previous page's + /// `next_cursor`; a cursor from another snapshot is refused, so pages are never mixed. + pub async fn page(&self, cursor: Option<&str>, budget: usize) -> Result { + let snapshot = self.snapshot.read().await; + let offset = match cursor { + None => 0, + Some(cursor) => { + let mut parts = cursor.split('.'); + let (Some(instance), Some(generation), Some(offset), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(StaleCursor); + }; + let instance = u64::from_str_radix(instance, 16).map_err(|_| StaleCursor)?; + let generation = generation.parse::().map_err(|_| StaleCursor)?; + let offset = offset.parse::().map_err(|_| StaleCursor)?; + if instance != self.instance + || generation != snapshot.generation + || offset > snapshot.entries.len() + { + return Err(StaleCursor); + } + offset + } + }; + // `{"entries":[],"truncated":false,"nextCursor":".."}` at its longest. + let mut total = 112_usize; + let mut end = offset; + for entry in &snapshot.entries[offset..] { + let bytes = crate::json_size::encoded_json_len(entry) + .unwrap_or(usize::MAX) + .saturating_add(1); + if end > offset && total.saturating_add(bytes) > budget { + break; + } + total = total.saturating_add(bytes); + end += 1; + } + Ok(ListPage { + entries: snapshot.entries[offset..end].to_vec(), + truncated: snapshot.truncated, + next_cursor: (end < snapshot.entries.len()) + .then(|| format!("{:x}.{}.{end}", self.instance, snapshot.generation)), + }) + } + /// Whether `other` lists exactly what this index lists: the same entries in the same order, and /// the same truncation. pub async fn same_entries(&self, other: &Self) -> bool { @@ -899,6 +977,7 @@ impl BoundedEntries { }); directories.extend(self.listed_directories); SearchSnapshot { + generation: 0, entries: self.entries.into_values().collect(), memory_bytes, truncated: self.truncated, @@ -1912,6 +1991,59 @@ mod tests { assert!(snapshot_truncated.truncated); } + /// Pages fit their budget, concatenate to the full list, and refuse a cursor from another + /// snapshot or a malformed one (#390). + #[tokio::test] + async fn pages_fit_the_budget_concatenate_to_the_list_and_refuse_a_stale_cursor() { + let root = tempfile::tempdir().unwrap(); + for index in 0..40 { + std::fs::write(root.path().join(format!("file-{index:02}.txt")), "").unwrap(); + } + let index = WorkspaceSearchIndex::new(root.path().to_path_buf(), SearchLimits::default()); + index.refresh(CancellationToken::new()).await.unwrap(); + let full = index.list(None).await; + let (mut paged, mut cursor, mut pages) = (Vec::new(), None::, 0); + loop { + let page = index.page(cursor.as_deref(), 300).await.unwrap(); + assert!(serde_json::to_vec(&page).unwrap().len() <= 300); + assert!(!page.entries.is_empty()); + pages += 1; + paged.extend(page.entries); + match page.next_cursor { + Some(next) => cursor = Some(next), + None => break, + } + } + assert!(pages > 1); + assert_eq!(paged, full.entries); + // One entry larger than the budget still makes progress. + assert_eq!(index.page(None, 1).await.unwrap().entries.len(), 1); + + let second = index.page(None, 300).await.unwrap().next_cursor.unwrap(); + index.refresh(CancellationToken::new()).await.unwrap(); + assert_eq!(index.page(Some(&second), 300).await, Err(StaleCursor)); + for malformed in ["", "x", "1", "1.x", "x.1"] { + assert_eq!(index.page(Some(malformed), 300).await, Err(StaleCursor)); + } + } + + /// A cursor from another index, such as the one a server ran before it restarted, is refused + /// even when that index reached the same generation (#390 review). + #[tokio::test] + async fn a_cursor_from_another_index_with_the_same_generation_is_refused() { + let root = tempfile::tempdir().unwrap(); + for index in 0..40 { + std::fs::write(root.path().join(format!("file-{index:02}.txt")), "").unwrap(); + } + let before = WorkspaceSearchIndex::new(root.path().to_path_buf(), SearchLimits::default()); + before.refresh(CancellationToken::new()).await.unwrap(); + let cursor = before.page(None, 300).await.unwrap().next_cursor.unwrap(); + let after = WorkspaceSearchIndex::new(root.path().to_path_buf(), SearchLimits::default()); + after.refresh(CancellationToken::new()).await.unwrap(); + assert_eq!(after.page(Some(&cursor), 300).await, Err(StaleCursor)); + assert!(before.page(Some(&cursor), 300).await.is_ok()); + } + /// No `.git` (a nested repository's included, in any letter case) is listed or searched; /// `.github` and `.gitignore` are (#139 X5 review round 6). #[tokio::test] diff --git a/apps/server/tests/fixtures/claude-provider/permission-flow.json b/apps/server/tests/fixtures/claude-provider/permission-flow.json index efc6d1af1b..15c9a02b85 100644 --- a/apps/server/tests/fixtures/claude-provider/permission-flow.json +++ b/apps/server/tests/fixtures/claude-provider/permission-flow.json @@ -53,6 +53,7 @@ "providerItemId": "tool-use-1" }, "payload": { + "detail": "pwd", "requestType": "command_execution_approval", "toolName": "Bash", "input": { diff --git a/apps/server/tests/git_manager_reads.rs b/apps/server/tests/git_manager_reads.rs index 3c9b937993..af623f7777 100644 --- a/apps/server/tests/git_manager_reads.rs +++ b/apps/server/tests/git_manager_reads.rs @@ -56,15 +56,24 @@ async fn unchanged_pinned_page_reads_keep_the_same_generation() { let repository = GitRepository::default(); let cancellation = CancellationToken::new(); - let first = page(&repository, fixture.path(), None, 0, 1, &cancellation) - .await - .expect("first commit page"); + let first = page( + &repository, + fixture.path(), + None, + 0, + 1, + false, + &cancellation, + ) + .await + .expect("first commit page"); let second = page( &repository, fixture.path(), Some(&first.pinned_tips), 1, 1, + false, &cancellation, ) .await @@ -83,9 +92,17 @@ async fn refs_and_page_reads_agree_on_generation() { let refs = build_refs_snapshot(&repository, fixture.path(), &cancellation) .await .expect("refs snapshot"); - let commits = page(&repository, fixture.path(), None, 0, 1, &cancellation) - .await - .expect("commit page"); + let commits = page( + &repository, + fixture.path(), + None, + 0, + 1, + false, + &cancellation, + ) + .await + .expect("commit page"); assert_eq!(commits.generation, refs.generation); } diff --git a/apps/server/tests/production_control.rs b/apps/server/tests/production_control.rs index 6550bcc876..7428aead96 100644 --- a/apps/server/tests/production_control.rs +++ b/apps/server/tests/production_control.rs @@ -424,10 +424,7 @@ async fn config_and_settings_match_the_typescript_contract_without_faking_provid assert_eq!(settings["enableAssistantStreaming"], false); assert_eq!(settings["enableProviderUpdateChecks"], false); assert_eq!(settings["automaticGitFetchInterval"], 180_000); - assert_eq!( - settings["textGenerationModelSelection"]["model"], - "gpt-5.4-mini" - ); + assert_eq!(settings["textGenerationModelSelection"]["model"], "auto"); assert_eq!( settings["providers"]["codex"]["binaryPath"], hermetic_providers::missing_provider_executable(&test_config(directory.path()).state_dir()) diff --git a/apps/server/tests/production_provider_runtime.rs b/apps/server/tests/production_provider_runtime.rs index 0200cef1ff..28774f9268 100644 --- a/apps/server/tests/production_provider_runtime.rs +++ b/apps/server/tests/production_provider_runtime.rs @@ -859,6 +859,7 @@ fn launch() -> ProviderLaunchRequest { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, } } @@ -15186,14 +15187,14 @@ async fn native_claude_driver_supports_the_complete_live_command_surface() { .is_some() ); driver.interrupt(None).await.unwrap(); - driver - .approve("approval-1".to_owned(), "acceptForSession".to_owned()) - .await - .unwrap(); - driver - .approve("approval-2".to_owned(), "deny".to_owned()) - .await - .unwrap(); + // An approval for a request Claude never made is refused before anything is written (#383). + for decision in ["acceptForSession", "decline"] { + assert!(matches!( + driver.approve("approval-1".to_owned(), decision.to_owned()).await, + Err(ProviderRuntimeError::Provider { detail, .. }) + if detail.contains("Unknown pending approval request") + )); + } driver .set_mode("auto-accept-edits".to_owned()) .await @@ -15688,6 +15689,26 @@ cat >/dev/null ); } +/// The default agent takes no flag, so Claude's own settings can name its default and a selection +/// that names `claude` launches like one that names no agent. +#[test] +fn claude_launch_arguments_leave_the_default_agent_to_claude() { + let mut request = launch(); + request.provider = "claudeAgent".to_owned(); + for agent in [None, Some("claude")] { + request.agent = agent.map(str::to_owned); + let arguments = build_claude_launch_arguments_for_test( + &request, + "session", + ClaudeActivitySupport::default(), + ); + assert!( + !arguments.iter().any(|argument| argument == "--agent"), + "{agent:?}: {arguments:?}" + ); + } +} + #[test] fn claude_launch_arguments_preserve_controls_and_gate_activity_flags() { let mut request = launch(); @@ -15714,6 +15735,7 @@ fn claude_launch_arguments_preserve_controls_and_gate_activity_flags() { fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, }, ); for required in [ @@ -15844,6 +15866,7 @@ async fn claude_activity_probe_is_cached_by_executable_identity() { fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, } ); assert_eq!(second, first); @@ -16720,6 +16743,7 @@ async fn claude_activity_probe_singleflights_concurrent_misses() { fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, } ); } @@ -16839,6 +16863,7 @@ async fn claude_activity_probe_test_contexts_isolate_concurrent_cache_mutation() fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, } ); } @@ -16895,6 +16920,7 @@ async fn claude_activity_probe_retries_transient_failures_without_poisoning_cach fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, } ); assert_eq!( @@ -16916,6 +16942,7 @@ fn claude_launch_arguments_ask_for_summarized_thinking_only_when_supported() { "session", ClaudeActivitySupport { thinking_display: true, + permission_prompts: false, ..ClaudeActivitySupport::default() }, ); @@ -16938,6 +16965,40 @@ fn claude_launch_arguments_ask_for_summarized_thinking_only_when_supported() { ); } +/// #383: a tool that needs approval reaches BiBCode only when Claude is started with +/// `--permission-prompt-tool stdio`. The flag is passed only to a CLI whose `--help` lists +/// `--permission-prompts`; an older one keeps denying such tools by itself. +#[test] +fn claude_launch_arguments_ask_for_host_permission_prompts_only_when_supported() { + let mut request = launch(); + request.provider = "claudeAgent".to_owned(); + let with_flag = build_claude_launch_arguments_for_test( + &request, + "session", + ClaudeActivitySupport { + permission_prompts: true, + ..ClaudeActivitySupport::default() + }, + ); + assert!( + with_flag + .windows(2) + .any(|window| window == ["--permission-prompt-tool", "stdio"]), + "{with_flag:?}" + ); + let without_flag = build_claude_launch_arguments_for_test( + &request, + "session", + ClaudeActivitySupport::default(), + ); + assert!( + !without_flag + .iter() + .any(|argument| argument == "--permission-prompt-tool"), + "{without_flag:?}" + ); +} + /// A CLI that knows `--thinking-display` rejects the probe's invalid value and lists the /// allowed ones; one that does not either ignores it under `--version` or rejects it as unknown. #[cfg(unix)] @@ -16979,6 +17040,7 @@ async fn claude_thinking_display_probe_reads_the_allowed_values() { fork_session_id: false, probe_finished: true, thinking_display: expected, + permission_prompts: false, }, "{case}" ); @@ -17024,6 +17086,7 @@ async fn claude_thinking_display_probe_timeout_is_not_cached() { fork_session_id: false, probe_finished: true, thinking_display: true, + permission_prompts: false, } ); } @@ -17165,6 +17228,7 @@ async fn assert_claude_probe_recovers_after_one_bad_help(case: &str, first_help: fork_session_id: false, probe_finished: true, thinking_display: false, + permission_prompts: false, }, "{case}: a later launch of the same working Claude gets the activity flags" ); @@ -20274,3 +20338,396 @@ async fn checkpoint_revert_refuses_while_the_session_runs_background_work() { engine.shutdown().await; } } + +/// A fake `codex app-server` for the code review panel tests (#376). It captures every line it +/// reads. With `@REQUESTS@` set to 1 it asks for a command approval, a file-change approval and +/// an answer on the first turn, and completes that turn once the last of them is answered. +#[cfg(unix)] +const CODE_REVIEW_CODEX_FIXTURE: &str = r#"#!/bin/sh +capture='@CAPTURE@' +send_requests='@REQUESTS@' +while IFS= read -r line; do + printf '%s\n' "$line" >> "$capture" + id=$(printf '%s\n' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p') + case "$line" in + *'"method":"initialize"'*) printf '{"id":%s,"result":{"userAgent":"fixture"}}\n' "$id" ;; + *'"method":"thread/start"'*|*'"method":"thread/resume"'*) printf '{"id":%s,"result":{"cwd":"/tmp","model":"gpt-5","thread":{"id":"review-native"}}}\n' "$id" ;; + *'"method":"thread/read"'*) printf '{"id":%s,"result":{"thread":{"id":"review-native","createdAt":1,"updatedAt":1,"status":{"type":"idle"},"turns":[]}}}\n' "$id" ;; + *'"method":"thread/turns/list"'*|*'"method":"thread/list"'*) printf '{"id":%s,"result":{"data":[],"nextCursor":null,"backwardsCursor":null}}\n' "$id" ;; + *'"method":"thread/backgroundTerminals/list"'*|*'"method":"mcpServerStatus/list"'*) printf '{"id":%s,"result":{"data":[],"nextCursor":null}}\n' "$id" ;; + *'"method":"turn/start"'*) + # Counted across processes, so a restarted session's turn gets a new id. + turns=$(($(cat "$capture.turns" 2>/dev/null || echo 0) + 1)) + printf '%s\n' "$turns" > "$capture.turns" + printf '{"id":%s,"result":{"turn":{"id":"review-turn-%s"}}}\n' "$id" "$turns" + if [ "$send_requests" = 1 ] && [ "$turns" = 1 ]; then + printf '%s\n' '{"id":9001,"method":"item/commandExecution/requestApproval","params":{"threadId":"review-native","turnId":"review-turn-1","itemId":"command-1","command":"node --test"}}' + printf '%s\n' '{"id":9002,"method":"item/fileChange/requestApproval","params":{"threadId":"review-native","turnId":"review-turn-1","itemId":"change-1","reason":"write a file"}}' + printf '%s\n' '{"id":9003,"method":"item/tool/requestUserInput","params":{"threadId":"review-native","turnId":"review-turn-1","itemId":"question-1","questions":[{"id":"q1","header":"Scope","question":"Which files?","options":[{"label":"All","description":"Every file"}]}]}}' + else + # After BiBCode has accepted the turn, as a real turn ends. + (sleep 0.3; printf '{"method":"turn/completed","params":{"threadId":"review-native","turn":{"id":"review-turn-%s","status":"completed","completedAt":3}}}\n' "$turns") & + fi ;; + *'"id":9003'*) printf '%s\n' '{"method":"turn/completed","params":{"threadId":"review-native","turn":{"id":"review-turn-1","status":"completed","completedAt":3}}}' ;; + *'"method":"turn/interrupt"'*) printf '{"id":%s,"result":{}}\n' "$id" ;; + *'"method":"shutdown"'*) printf '{"id":%s,"result":null}\n' "$id" ;; + esac +done +"#; + +/// A server with one Codex host thread and one chat panel on it, created the way the Source +/// Control review creates its panel (`worktree.createPanel`), with `stored_mode` as the panel's +/// runtime mode. +#[cfg(unix)] +struct CodexPanelRun { + _state: TempDir, + capture: PathBuf, + handle: bibcode_server::ServerHandle, + socket: WebSocketStream>, + next_id: u64, +} + +#[cfg(unix)] +impl CodexPanelRun { + async fn start(code_review: bool, stored_mode: &str, send_requests: bool) -> Self { + let state = TempDir::new().expect("state"); + let capture = state.path().join("codex-review-requests.ndjson"); + let script = CODE_REVIEW_CODEX_FIXTURE + .replace("@CAPTURE@", &capture.display().to_string()) + .replace("@REQUESTS@", if send_requests { "1" } else { "0" }); + let executable = executable_fixture(&state, "codex-review", &script, ""); + let config = test_config(&state); + hermetic_providers::write_hermetic_settings( + &config.state_dir(), + json!({ + "providerInstances": { + "codex-review": { + "driver": "codex", + "enabled": true, + "config": { "binaryPath": executable } + } + } + }), + ); + let workspace = state.path().join("workspace"); + std::fs::create_dir(&workspace).expect("workspace"); + let handle = ServerRuntime::start(config) + .await + .expect("production RPC server"); + let (socket, _) = connect_async(format!("ws://{}/ws", handle.local_addr())) + .await + .expect("WebSocket"); + let mut run = Self { + _state: state, + capture, + handle, + socket, + next_id: 1000, + }; + let selection = json!({"instanceId":"codex-review","model":"gpt-5"}); + run.rpc( + "orchestration.dispatchCommand", + json!({ + "type":"project.create","commandId":"review-project","projectId":"review-project", + "title":"Review","workspaceRoot":workspace,"defaultModelSelection":null,"createdAt":NOW + }), + ) + .await + .expect("project created"); + run.rpc( + "orchestration.dispatchCommand", + json!({ + "type":"thread.create","commandId":"review-host","threadId":"review-host", + "projectId":"review-project","title":"Host","modelSelection":selection, + "runtimeMode":"full-access","interactionMode":"default","branch":null, + "worktreePath":null,"createdAt":NOW + }), + ) + .await + .expect("host thread created"); + let mut panel = json!({ + "commandId":"review-panel","hostThreadId":"review-host","threadId":"review-thread", + "title":"Code review", + "threadDefaults":{ + "modelSelection":selection,"runtimeMode":stored_mode,"interactionMode":"default" + } + }); + if code_review { + panel["codeReview"] = json!(true); + } + run.rpc("worktree.createPanel", panel) + .await + .expect("panel created"); + run + } + + async fn rpc(&mut self, tag: &str, payload: Value) -> Result { + self.next_id += 1; + tagged_rpc_request(&mut self.socket, &self.next_id.to_string(), tag, payload).await + } + + async fn turn(&mut self, message_id: &str, text: &str, runtime_mode: &str) { + self.rpc( + "orchestration.dispatchCommand", + json!({ + "type":"thread.turn.start","commandId":format!("command-{message_id}"), + "threadId":"review-thread", + "message":{"messageId":message_id,"role":"user","text":text,"attachments":[]}, + "modelSelection":{"instanceId":"codex-review","model":"gpt-5"}, + "runtimeMode":runtime_mode,"interactionMode":"default","createdAt":NOW + }), + ) + .await + .expect("turn admitted"); + } + + async fn shell_until(&mut self, what: &str, done: impl Fn(&Value) -> bool) -> Value { + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + loop { + let shells = self + .rpc( + "orchestration.getThreadShells", + json!({"threadIds":["review-thread"]}), + ) + .await + .expect("thread shells"); + let shell = shells["threads"][0].clone(); + if done(&shell) { + return shell; + } + assert!( + tokio::time::Instant::now() < deadline, + "{what}: shell={shell}; capture={:?}", + std::fs::read_to_string(&self.capture).unwrap_or_default() + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + + async fn turn_completed_after(&mut self, previous: Option<&Value>) -> Value { + self.shell_until("turn completes", |shell| { + shell["latestTurn"]["state"] == "completed" + && previous.is_none_or(|turn_id| &shell["latestTurn"]["turnId"] != turn_id) + && shell["session"]["activeTurnId"].is_null() + }) + .await["latestTurn"]["turnId"] + .clone() + } + + fn captured(&self) -> Vec { + std::fs::read_to_string(&self.capture) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .collect() + } + + async fn wait_for_method(&self, method: &str) { + timeout(Duration::from_secs(20), async { + while !self.captured().iter().any(|line| line["method"] == method) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("Codex never received {method}: {:?}", self.captured())); + } + + /// First turn, a runtime-mode change that restarts and resumes the session, second turn. + async fn two_turns_across_a_restart(&mut self, stored_mode: &str, next_mode: &str) { + self.turn("review-message-1", "first review turn", stored_mode) + .await; + let first = self.turn_completed_after(None).await; + self.rpc( + "orchestration.dispatchCommand", + json!({ + "type":"thread.runtime-mode.set","commandId":"review-mode-change", + "threadId":"review-thread","runtimeMode":next_mode,"createdAt":NOW + }), + ) + .await + .expect("mode change admitted"); + self.wait_for_method("thread/resume").await; + self.turn("review-message-2", "second review turn", next_mode) + .await; + self.turn_completed_after(Some(&first)).await; + } + + async fn finish(mut self) { + self.socket.close(None).await.expect("close WebSocket"); + self.handle.shutdown(); + self.handle.join().await.expect("RPC server joins"); + } +} + +#[cfg(unix)] +fn codex_wire_policy(mode: &str) -> (&'static str, &'static str, &'static str) { + match mode { + "approval-required" => ("untrusted", "read-only", "readOnly"), + "auto-accept-edits" => ("on-request", "workspace-write", "workspaceWrite"), + "full-access" => ("never", "danger-full-access", "dangerFullAccess"), + other => panic!("unexpected runtime mode {other}"), + } +} + +/// The policy each Codex request of the two-turn sequence carries, in order: `thread/start`, +/// `thread/resume`, the first `turn/start` and the second, each turn found by its own text. +#[cfg(unix)] +fn codex_policies(captured: &[Value]) -> [(String, Value); 4] { + let only = |method: &str| { + let matching = captured + .iter() + .filter(|line| line["method"] == method) + .collect::>(); + assert_eq!(matching.len(), 1, "one {method}: {captured:?}"); + matching[0].clone() + }; + let turn = |text: &str| { + let matching = captured + .iter() + .filter(|line| { + line["method"] == "turn/start" + && line["params"]["input"] + .as_array() + .is_some_and(|input| input.iter().any(|part| part["text"] == text)) + }) + .collect::>(); + assert_eq!( + matching.len(), + 1, + "one turn/start for {text:?}: {captured:?}" + ); + matching[0].clone() + }; + assert_eq!( + captured + .iter() + .filter(|line| line["method"] == "turn/start") + .count(), + 2, + "exactly two turns: {captured:?}" + ); + let policy = |request: Value, sandbox: &str| { + ( + request["params"]["approvalPolicy"] + .as_str() + .unwrap_or_default() + .to_owned(), + request["params"] + .pointer(sandbox) + .cloned() + .unwrap_or_default(), + ) + }; + [ + policy(only("thread/start"), "/sandbox"), + policy(only("thread/resume"), "/sandbox"), + policy(turn("first review turn"), "/sandboxPolicy/type"), + policy(turn("second review turn"), "/sandboxPolicy/type"), + ] +} + +#[cfg(unix)] +const RUNTIME_MODE_CYCLE: [(&str, &str); 3] = [ + ("approval-required", "auto-accept-edits"), + ("auto-accept-edits", "full-access"), + // A review row stored as Full access, as a person could switch one before #376. + ("full-access", "approval-required"), +]; + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn code_review_codex_panel_never_asks_in_the_read_only_sandbox_across_restart_and_resume() { + for (stored_mode, next_mode) in RUNTIME_MODE_CYCLE { + let mut run = CodexPanelRun::start(true, stored_mode, false).await; + run.two_turns_across_a_restart(stored_mode, next_mode).await; + assert_eq!( + codex_policies(&run.captured()), + [ + ("never".to_owned(), json!("read-only")), + ("never".to_owned(), json!("read-only")), + ("never".to_owned(), json!("readOnly")), + ("never".to_owned(), json!("readOnly")), + ], + "stored mode {stored_mode}" + ); + run.finish().await; + } +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn plain_codex_panel_keeps_the_wire_policy_of_each_runtime_mode() { + for (stored_mode, next_mode) in RUNTIME_MODE_CYCLE { + let mut run = CodexPanelRun::start(false, stored_mode, false).await; + run.two_turns_across_a_restart(stored_mode, next_mode).await; + let (first_approval, first_sandbox, first_turn_sandbox) = codex_wire_policy(stored_mode); + let (next_approval, next_sandbox, next_turn_sandbox) = codex_wire_policy(next_mode); + assert_eq!( + codex_policies(&run.captured()), + [ + (first_approval.to_owned(), json!(first_sandbox)), + (next_approval.to_owned(), json!(next_sandbox)), + (first_approval.to_owned(), json!(first_turn_sandbox)), + (next_approval.to_owned(), json!(next_turn_sandbox)), + ], + "stored mode {stored_mode}" + ); + run.finish().await; + } +} + +/// The replies BiBCode sent to the fixture's three requests, by request id. +#[cfg(unix)] +fn replies_to_fixture_requests(captured: &[Value]) -> Vec<(Value, Value)> { + captured + .iter() + .filter(|line| { + line.get("method").is_none() + && [json!(9001), json!(9002), json!(9003)].contains(&line["id"]) + }) + .map(|line| (line["id"].clone(), line["result"].clone())) + .collect() +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn code_review_codex_panel_declines_approvals_and_questions_at_once() { + let mut run = CodexPanelRun::start(true, "approval-required", true).await; + run.turn("review-message-1", "first review turn", "approval-required") + .await; + let shell = run + .shell_until("the turn completes with no card", |shell| { + shell["latestTurn"]["state"] == "completed" + }) + .await; + assert_eq!(shell["hasPendingApprovals"], false, "{shell}"); + assert_eq!(shell["hasPendingUserInput"], false, "{shell}"); + assert_eq!( + replies_to_fixture_requests(&run.captured()), + [ + (json!(9001), json!({"decision":"decline"})), + (json!(9002), json!({"decision":"decline"})), + (json!(9003), json!({"answers":{}})), + ] + ); + run.finish().await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn plain_codex_panel_still_opens_cards_for_approvals_and_questions() { + let mut run = CodexPanelRun::start(false, "approval-required", true).await; + run.turn("review-message-1", "first review turn", "approval-required") + .await; + let shell = run + .shell_until("the cards open", |shell| { + shell["hasPendingApprovals"] == true && shell["hasPendingUserInput"] == true + }) + .await; + assert_ne!(shell["latestTurn"]["state"], "completed", "{shell}"); + assert!( + replies_to_fixture_requests(&run.captured()).is_empty(), + "nothing answers a card before the person does" + ); + run.finish().await; +} diff --git a/apps/server/tests/provider_claude.rs b/apps/server/tests/provider_claude.rs index 1face838a4..cf39ddd9b3 100644 --- a/apps/server/tests/provider_claude.rs +++ b/apps/server/tests/provider_claude.rs @@ -2656,15 +2656,507 @@ fn permission_requests_round_trip_through_open_and_resolved_events() { runtime.open_permission_request(fixture.request, &fixture.resolution.request_id); events.extend(request_event); events.extend( - runtime.resolve_permission_request( - &fixture.resolution.request_id, - fixture.resolution.decision, - ), + runtime + .resolve_permission_request(&fixture.resolution.request_id, fixture.resolution.decision) + .expect("pending approval") + .events, ); assert_trace_eq(&events, &fixture.expected_events); } +fn runtime_with_bash_approval(suggestions: Value) -> ClaudeProviderRuntime { + let mut runtime = ClaudeProviderRuntime::new("thread-1".to_owned(), "session-1".to_owned()); + runtime.start_session(RuntimeMode::ApprovalRequired, None); + runtime.start_turn(TurnInput { + turn_id: "turn-1".to_owned(), + input: "run a command".to_owned(), + }); + runtime.open_permission_request( + serde_json::from_value(json!({ + "toolName": "Bash", + "input": { "command": "touch made.txt" }, + "toolUseId": "tool-use-1", + "suggestions": suggestions, + })) + .expect("permission request"), + "request-1", + ); + runtime +} + +/// The shape Claude 2.1 sends for a Bash command: one rule it would save to a settings file, the +/// working folder, and a mode change. +fn bash_suggestions() -> Value { + json!([ + { + "type": "addRules", + "rules": [{ "toolName": "Bash", "ruleContent": "touch made.txt" }], + "behavior": "allow", + "destination": "localSettings" + }, + { "type": "addDirectories", "directories": ["/work"], "destination": "session" }, + { "type": "setMode", "mode": "acceptEdits", "destination": "session" } + ]) +} + +#[test] +fn accept_for_session_applies_the_suggested_rules_to_the_session_only() { + let mut runtime = runtime_with_bash_approval(bash_suggestions()); + let resolved = runtime + .resolve_permission_request("request-1", Decision::AcceptForSession) + .expect("pending approval"); + + // Every rule goes to the session, never to a settings file, and the mode stays as the + // thread shows it. + assert_eq!( + resolved.response, + json!({ + "behavior": "allow", + "updatedInput": { "command": "touch made.txt" }, + "updatedPermissions": [ + { + "type": "addRules", + "rules": [{ "toolName": "Bash", "ruleContent": "touch made.txt" }], + "behavior": "allow", + "destination": "session" + }, + { "type": "addDirectories", "directories": ["/work"], "destination": "session" } + ] + }) + ); + assert_eq!(resolved.events.len(), 1); + assert_eq!( + resolved.events[0].payload, + json!({ "decision": "acceptForSession" }) + ); +} + +#[test] +fn accept_allows_once_and_adds_no_session_rule() { + let mut runtime = runtime_with_bash_approval(bash_suggestions()); + let resolved = runtime + .resolve_permission_request("request-1", Decision::Accept) + .expect("pending approval"); + + assert_eq!( + resolved.response, + json!({ "behavior": "allow", "updatedInput": { "command": "touch made.txt" } }) + ); + assert_eq!(resolved.events[0].payload, json!({ "decision": "accept" })); +} + +#[test] +fn accept_for_session_without_a_usable_rule_allows_once_and_says_so() { + for suggestions in [ + json!([]), + json!([{ "type": "setMode", "mode": "acceptEdits", "destination": "session" }]), + // Malformed or not an allow: none of these is a rule to apply. + json!([{}]), + json!([{ "type": "addRules", "rules": [], "behavior": "allow" }]), + json!([{ "type": "addRules", "rules": [{ "toolName": "Bash" }], "behavior": "deny" }]), + json!([{ "type": "removeRules", "rules": [{ "toolName": "Bash" }], "behavior": "deny" }]), + // Entries that are not rules or folders. + json!([{ "type": "addRules", "rules": [{}], "behavior": "allow" }]), + json!([{ "type": "addDirectories", "directories": [null, ""] }]), + ] { + let mut runtime = runtime_with_bash_approval(suggestions); + let resolved = runtime + .resolve_permission_request("request-1", Decision::AcceptForSession) + .expect("pending approval"); + + assert_eq!( + resolved.response, + json!({ "behavior": "allow", "updatedInput": { "command": "touch made.txt" } }) + ); + assert_eq!( + resolved.events[0].payload, + json!({ + "decision": "accept", + "detail": "Claude offered no session rule for this request, so it was approved once." + }) + ); + } +} + +#[test] +fn deny_refuses_the_tool() { + let mut runtime = runtime_with_bash_approval(bash_suggestions()); + let resolved = runtime + .resolve_permission_request("request-1", Decision::Decline) + .expect("pending approval"); + + assert_eq!( + resolved.response, + json!({ "behavior": "deny", "message": "The user denied this tool use." }) + ); + assert_eq!(resolved.events[0].payload, json!({ "decision": "decline" })); +} + +/// A started runtime in a turn, as when Claude asks its host about a tool. +fn runtime_in_turn() -> ClaudeProviderRuntime { + let mut runtime = ClaudeProviderRuntime::new("thread-1".to_owned(), "session-1".to_owned()); + runtime.start_session(RuntimeMode::ApprovalRequired, None); + runtime.start_turn(TurnInput { + turn_id: "turn-1".to_owned(), + input: "do the work".to_owned(), + }); + runtime +} + +/// The frame Claude Code 2.1 writes when a tool needs its host's answer. +fn can_use_tool(request_id: &str, tool_name: &str, input: Value) -> Value { + json!({ + "type": "control_request", + "request_id": request_id, + "request": { + "subtype": "can_use_tool", + "tool_name": tool_name, + "input": input, + "permission_suggestions": [{ + "type": "addRules", + "rules": [{ "toolName": tool_name, "ruleContent": "touch made.txt" }], + "behavior": "allow", + "destination": "localSettings" + }], + "tool_use_id": "tool-use-1" + } + }) +} + +#[test] +fn a_tool_that_needs_approval_opens_a_card_that_names_the_command() { + let mut runtime = runtime_in_turn(); + let output = runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + + assert!( + output.control_responses.is_empty(), + "the person answers, not BiBCode" + ); + assert_eq!(output.events.len(), 1); + let opened = &output.events[0]; + assert_eq!(opened.event_type, "request.opened"); + // The card's id is Claude's own request id, so the reply needs no mapping. + assert_eq!(opened.request_id.as_deref(), Some("cli-request-1")); + assert_eq!(opened.turn_id.as_deref(), Some("turn-1")); + assert_eq!(opened.payload["requestType"], "command_execution_approval"); + assert_eq!(opened.payload["detail"], "touch made.txt"); + + // The session approval answers that request with a rule for this session only. + let resolved = runtime + .resolve_permission_request("cli-request-1", Decision::AcceptForSession) + .expect("pending approval"); + assert_eq!( + resolved.response["updatedPermissions"][0]["destination"], + "session" + ); + assert_eq!(resolved.events[0].turn_id.as_deref(), Some("turn-1")); +} + +#[test] +fn a_file_tool_card_names_the_tool_and_the_file() { + let mut runtime = runtime_in_turn(); + let output = runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Edit", + json!({ "file_path": "/work/src/main.rs" }), + ), + 0, + ); + assert_eq!( + output.events[0].payload["requestType"], + "file_change_approval" + ); + assert_eq!( + output.events[0].payload["detail"], + "Edit: /work/src/main.rs" + ); +} + +#[test] +fn a_request_is_settled_once() { + let mut runtime = runtime_in_turn(); + runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + + assert!( + runtime + .resolve_permission_request("cli-request-1", Decision::Accept) + .is_some() + ); + // A second answer, from another client or after a cancellation, finds nothing to answer. + assert!( + runtime + .resolve_permission_request("cli-request-1", Decision::Accept) + .is_none() + ); + assert!(runtime.cancel_request("cli-request-1").is_empty()); + assert!( + runtime + .resolve_permission_request("never-opened", Decision::Accept) + .is_none() + ); + assert!( + runtime + .resolve_user_input_request("never-opened", json!({})) + .is_none() + ); +} + +#[test] +fn cancel_denies_the_tool_and_stops_the_turn() { + let mut runtime = runtime_in_turn(); + runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + let resolved = runtime + .resolve_permission_request("cli-request-1", Decision::Cancel) + .expect("pending approval"); + assert_eq!(resolved.response["behavior"], "deny"); + assert_eq!(resolved.response["interrupt"], true); + assert_eq!(resolved.events[0].payload, json!({ "decision": "cancel" })); +} + +#[test] +fn a_request_claude_withdraws_closes_its_card_and_takes_no_answer() { + let mut runtime = runtime_in_turn(); + runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + let output = runtime.handle_raw_value( + &json!({ "type": "control_cancel_request", "request_id": "cli-request-1" }), + 0, + ); + + assert!(output.control_responses.is_empty()); + assert_eq!(output.events.len(), 1); + assert_eq!(output.events[0].event_type, "request.resolved"); + assert_eq!( + output.events[0].request_id.as_deref(), + Some("cli-request-1") + ); + assert_eq!(output.events[0].payload, json!({ "decision": "cancel" })); + assert!( + runtime + .resolve_permission_request("cli-request-1", Decision::Accept) + .is_none(), + "an answer that races the withdrawal loses" + ); + // A withdrawal of something that is not pending does nothing. + let again = runtime.handle_raw_value( + &json!({ "type": "control_cancel_request", "request_id": "cli-request-1" }), + 0, + ); + assert!(again.events.is_empty()); +} + +#[test] +fn a_question_opens_the_question_card_and_is_answered_as_the_tool_input() { + let mut runtime = runtime_in_turn(); + let questions = json!([{ + "question": "Red or blue?", + "header": "Color", + "options": [{ "label": "Red" }, { "label": "Blue" }] + }]); + let output = runtime.handle_raw_value( + &can_use_tool( + "cli-question-1", + "AskUserQuestion", + json!({ "questions": questions }), + ), + 0, + ); + assert!(output.control_responses.is_empty()); + assert_eq!(output.events[0].event_type, "user-input.requested"); + assert_eq!( + output.events[0].request_id.as_deref(), + Some("cli-question-1") + ); + // The question card requires a description on every option, which Claude may omit. + assert_eq!( + output.events[0].payload["questions"][0]["options"], + json!([ + { "label": "Red", "description": "" }, + { "label": "Blue", "description": "" } + ]) + ); + + let resolved = runtime + .resolve_user_input_request("cli-question-1", json!({ "Red or blue?": "Blue" })) + .expect("pending question"); + assert_eq!( + resolved.updated_input, + json!({ "questions": questions, "answers": { "Red or blue?": "Blue" } }) + ); + assert_eq!(resolved.events[0].event_type, "user-input.resolved"); +} + +#[test] +fn leaving_plan_mode_is_denied_at_once_and_opens_no_card() { + let mut runtime = runtime_in_turn(); + let output = runtime.handle_raw_value( + &can_use_tool( + "cli-plan-1", + "ExitPlanMode", + json!({ "plan": "Create hello.txt" }), + ), + 0, + ); + + // The plan is reviewed in BiBCode, which reads it from the tool call, so no card opens. + assert!(output.events.is_empty()); + assert_eq!(output.control_responses.len(), 1); + let reply = &output.control_responses[0]; + assert_eq!(reply["type"], "control_response"); + assert_eq!(reply["response"]["request_id"], "cli-plan-1"); + assert_eq!(reply["response"]["subtype"], "success"); + assert_eq!(reply["response"]["response"]["behavior"], "deny"); + assert!( + reply["response"]["response"]["message"] + .as_str() + .is_some_and(|message| message.contains("End your turn")) + ); +} + +#[test] +fn an_interrupt_or_a_stopped_process_closes_every_open_request() { + let mut runtime = runtime_in_turn(); + runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + runtime.handle_raw_value( + &can_use_tool( + "cli-question-1", + "AskUserQuestion", + json!({ "questions": [{ "question": "Go on?" }] }), + ), + 0, + ); + + let events = runtime.cancel_pending_requests(); + let mut closed = events + .iter() + .map(|event| (event.event_type.as_str(), event.request_id.as_deref())) + .collect::>(); + closed.sort_unstable(); + assert_eq!( + closed, + [ + ("request.resolved", Some("cli-request-1")), + ("user-input.resolved", Some("cli-question-1")), + ] + ); + assert!(runtime.cancel_pending_requests().is_empty()); +} + +#[test] +fn a_turn_that_ends_closes_the_requests_it_left_open() { + let mut runtime = runtime_in_turn(); + runtime.handle_raw_value( + &can_use_tool( + "cli-request-1", + "Bash", + json!({ "command": "touch made.txt" }), + ), + 0, + ); + let output = runtime.handle_raw_value( + &json!({ + "type": "result", + "subtype": "success", + "is_error": false, + "stop_reason": "end_turn", + "session_id": "session-1", + "uuid": "result-1" + }), + 0, + ); + let types = output + .events + .iter() + .map(|event| event.event_type.as_str()) + .collect::>(); + let closed = types.iter().position(|kind| *kind == "request.resolved"); + let completed = types.iter().position(|kind| *kind == "turn.completed"); + assert!(closed.is_some() && closed < completed, "{types:?}"); + // An answer from another client after the turn ended is refused. + assert!( + runtime + .resolve_permission_request("cli-request-1", Decision::Accept) + .is_none() + ); +} + +#[test] +fn a_session_rule_keeps_only_its_valid_entries() { + let mut runtime = runtime_with_bash_approval(json!([{ + "type": "addRules", + "rules": [ + {}, + { "toolName": "Bash", "ruleContent": 42 }, + { "toolName": "Bash", "ruleContent": "touch made.txt" } + ], + "behavior": "allow", + "destination": "userSettings" + }])); + let resolved = runtime + .resolve_permission_request("request-1", Decision::AcceptForSession) + .expect("pending approval"); + assert_eq!( + resolved.response["updatedPermissions"], + json!([{ + "type": "addRules", + "rules": [{ "toolName": "Bash", "ruleContent": "touch made.txt" }], + "behavior": "allow", + "destination": "session" + }]) + ); +} + +#[test] +fn other_control_requests_are_not_treated_as_tool_requests() { + let mut runtime = runtime_in_turn(); + let output = runtime.handle_raw_value( + &json!({ + "type": "control_request", + "request_id": "cli-other-1", + "request": { "subtype": "something_else" } + }), + 0, + ); + assert!(output.events.is_empty()); + assert!(output.control_responses.is_empty()); +} + #[test] fn ask_user_question_round_trips_structured_answers() { let fixture: UserInputFixture = load_fixture("user-input-flow.json"); @@ -2678,10 +3170,12 @@ fn ask_user_question_round_trips_structured_answers() { let mut events = runtime.handle_message(fixture.message); let opened = runtime.open_user_input_request(fixture.request, &fixture.resolution.request_id); events.extend(opened); - let resolved = runtime.resolve_user_input_request( - &fixture.resolution.request_id, - fixture.resolution.answers.clone(), - ); + let resolved = runtime + .resolve_user_input_request( + &fixture.resolution.request_id, + fixture.resolution.answers.clone(), + ) + .expect("pending question"); assert_eq!(resolved.updated_input, fixture.expected_updated_input); events.extend(resolved.events); diff --git a/apps/server/tests/provider_codex.rs b/apps/server/tests/provider_codex.rs index a31ff13e12..018bb8601e 100644 --- a/apps/server/tests/provider_codex.rs +++ b/apps/server/tests/provider_codex.rs @@ -91,7 +91,7 @@ fn missing_codex_rollout_is_a_recoverable_resume_failure() { } #[test] -fn automatic_codex_model_resolves_to_the_supported_default() { +fn automatic_codex_model_names_no_model() { let payload = build_turn_start_params(&BuildTurnStartInput { thread_id: "provider-thread-1".to_owned(), runtime_mode: CodexRuntimeMode::FullAccess, @@ -99,12 +99,18 @@ fn automatic_codex_model_resolves_to_the_supported_default() { prompt: Some("hello".to_owned()), attachments: vec![], model: Some("auto".to_owned()), + reported_model: Some("gpt-6.2-sol".to_owned()), service_tier: None, effort: None, interaction_mode: Some("default".to_owned()), }); - assert_eq!(payload["model"], "gpt-5.4"); - assert_eq!(payload["collaborationMode"]["settings"]["model"], "gpt-5.4"); + // "auto" is no chosen model: the turn names none, and the collaboration mode, which requires + // a name, takes the one Codex reported for the thread. + assert!(payload.get("model").is_none()); + assert_eq!( + payload["collaborationMode"]["settings"]["model"], + "gpt-6.2-sol" + ); } #[derive(Debug, Deserialize)] @@ -2572,6 +2578,7 @@ async fn helper_outputs_match_canonical_codex_fixtures() { "url": "data:image/png;base64,abc", })], model: Some("gpt-5.3-codex".to_owned()), + reported_model: None, service_tier: None, effort: None, interaction_mode: Some("default".to_owned()), @@ -2588,6 +2595,7 @@ async fn helper_outputs_match_canonical_codex_fixtures() { prompt: Some("Make a plan".to_owned()), attachments: vec![], model: Some("gpt-5.3-codex".to_owned()), + reported_model: None, service_tier: None, effort: Some("medium".to_owned()), interaction_mode: Some("plan".to_owned()), @@ -2631,6 +2639,9 @@ async fn probe_matches_fixture_corpus() { .respond(scenario["modelListFirst"].clone()); peer.expect_request("model/list", json!({ "cursor": "cursor-2" })) .respond(scenario["modelListSecond"].clone()); + // No configured model: the "Codex default" entry is named after the listed default. + peer.expect_request("config/read", json!({})) + .respond(json!({ "config": { "model": null } })); peer.expect_request( "skills/list", json!({ "cwds": [scenario["cwd"].as_str().expect("cwd")] }), @@ -10178,6 +10189,10 @@ async fn codex_runtime_covers_auto_edit_resume_requests_and_stream_edges() { peer.expect_request("initialize", build_initialize_params("0.1.1")) .respond(json!({})); peer.expect_notification("initialized"); + // A resume names the model Codex's configuration names, because a thread resumed without a + // model keeps its old one. + peer.expect_request("config/read", json!({})) + .respond(json!({ "config": { "model": "gpt-default" } })); peer.expect_request( "thread/resume", json!({ @@ -10185,7 +10200,7 @@ async fn codex_runtime_covers_auto_edit_resume_requests_and_stream_edges() { "cwd": "/tmp/codex-edge", "approvalPolicy": "on-request", "sandbox": "workspace-write", - "model": null, + "model": "gpt-default", "serviceTier": "fast", }), ) @@ -10577,6 +10592,11 @@ async fn codex_runtime_and_probe_reject_invalid_provider_payloads() { .expect_request("initialize", build_initialize_params("0.1.1")) .respond(json!({})); resume_peer.expect_notification("initialized"); + // A resume names the model Codex's configuration names, because a thread resumed without a + // model keeps its old one. + resume_peer + .expect_request("config/read", json!({})) + .respond(json!({ "config": { "model": "gpt-default" } })); resume_peer .expect_request( "thread/resume", @@ -10585,7 +10605,7 @@ async fn codex_runtime_and_probe_reject_invalid_provider_payloads() { "cwd": "/tmp/codex-invalid", "approvalPolicy": "untrusted", "sandbox": "read-only", - "model": null, + "model": "gpt-default", "serviceTier": null, }), ) @@ -10892,6 +10912,7 @@ fn codex_edge_turn_params(provider_thread_id: &str, prompt: &str) -> Value { prompt: Some(prompt.to_owned()), attachments: Vec::new(), model: None, + reported_model: None, service_tier: Some("fast".to_owned()), effort: Some("high".to_owned()), interaction_mode: None, diff --git a/apps/server/tests/turn_delivery_recovery.rs b/apps/server/tests/turn_delivery_recovery.rs index 09a8de0773..796b773cab 100644 --- a/apps/server/tests/turn_delivery_recovery.rs +++ b/apps/server/tests/turn_delivery_recovery.rs @@ -734,6 +734,7 @@ fn crash_launch(provider: &str, state: &Path) -> ProviderLaunchRequest { open_url: None, host_thread_id: None, side_chat_host_thread_id: None, + code_review: false, } } diff --git a/apps/web/src/AppRoot.lifecycle.test.tsx b/apps/web/src/AppRoot.lifecycle.test.tsx index cbbf1c7046..25fd6fd4bc 100644 --- a/apps/web/src/AppRoot.lifecycle.test.tsx +++ b/apps/web/src/AppRoot.lifecycle.test.tsx @@ -60,6 +60,10 @@ vi.mock("./rpc/atomRegistry", () => ({ AppAtomRegistryProvider: ({ children }: { readonly children?: React.ReactNode }) => children, })); +vi.mock("./connection/connectionStoreReadiness", () => ({ + useConnectionStoreReadinessAttribute: () => undefined, +})); + vi.mock("./diagnostics/DiagnosticLogsRelayHost", () => ({ DiagnosticLogsRelayHost: () => null, })); diff --git a/apps/web/src/cloud/dpop.test.ts b/apps/web/src/cloud/dpop.test.ts index 1f36758d61..3c82ccf95b 100644 --- a/apps/web/src/cloud/dpop.test.ts +++ b/apps/web/src/cloud/dpop.test.ts @@ -1,6 +1,7 @@ import { verifyDpopProof } from "@bibcode/shared/dpop"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import { decodeJwt } from "jose"; import { afterEach, vi } from "vite-plus/test"; @@ -30,7 +31,15 @@ class FakeRequest { } } -type IndexedDbFault = "none" | "open" | "read" | "write"; +// A "silent-" fault leaves that request without any event. +type IndexedDbFault = + | "none" + | "open" + | "read" + | "write" + | "silent-open" + | "silent-read" + | "silent-write"; function installFakeIndexedDb( options: { @@ -58,9 +67,11 @@ function installFakeIndexedDb( transaction: () => { const transaction = new FakeRequest(); return Object.assign(transaction, { + abort: () => undefined, objectStore: () => ({ get: (key: IDBValidKey) => { const request = new FakeRequest(); + if (options.fault === "silent-read") return request; queueMicrotask(() => { if (options.fault === "read") { request.error = new Error("read-denied"); @@ -73,6 +84,7 @@ function installFakeIndexedDb( return request; }, put: (value: unknown, key: IDBValidKey) => { + if (options.fault === "silent-write") return; queueMicrotask(() => { if (options.fault === "write") { transaction.error = new Error("write-denied"); @@ -94,6 +106,7 @@ function installFakeIndexedDb( vi.stubGlobal("indexedDB", { open: (name: string) => { const request = new FakeRequest(); + if (options.fault === "silent-open") return request; queueMicrotask(() => { if (options.fault === "open") { request.error = new Error("open-denied"); @@ -266,3 +279,30 @@ describe("browser DPoP proofs", () => { }), ); }); + +describe("DPoP key storage that does not answer", () => { + const stalls = [ + ["an open", "silent-open", () => readStoredBrowserDpopKey()], + ["a read", "silent-read", () => readStoredBrowserDpopKey()], + ["a write", "silent-write", () => writeStoredBrowserDpopKey({} as BrowserDpopKey)], + ] as const; + + for (const [name, fault, operation] of stalls) { + it.effect(`fails ${name} that never settles with a clear error`, () => + Effect.gen(function* () { + installFakeIndexedDb({ fault }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const fiber = yield* Effect.forkDetach(Effect.flip(operation()), { + startImmediately: true, + }); + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(10_000)); + + const exit = fiber.pollUnsafe(); + expect(exit, `${name} was still waiting`).toBeDefined(); + const error = Exit.isSuccess(exit!) ? exit.value : null; + expect(error).toBeInstanceOf(BrowserDpopError); + expect(error?.message).toContain("DPoP key storage did not answer"); + }).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers()))), + ); + } +}); diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.ts index 2620e2a21c..058c4e5b09 100644 --- a/apps/web/src/cloud/dpop.ts +++ b/apps/web/src/cloud/dpop.ts @@ -26,6 +26,10 @@ const DPOP_DATABASE_VERSION = 1; const DPOP_KEY_STORE_NAME = "keys"; const DPOP_KEY_ID = "relay-dpop-proof-key"; const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk); +/** How long one DPoP key storage request may stay silent before it fails. */ +const DPOP_STORAGE_DEADLINE_MS = 10_000; +const DPOP_STORAGE_SILENT_MESSAGE = + "DPoP key storage did not answer in time, so the relay request was not signed. Quit BiBCode and open it again."; export const browserCryptoLayer = Layer.succeed( Crypto.Crypto, @@ -44,8 +48,44 @@ function dpopError(message: string, cause?: unknown) { return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) }); } +/** + * Settles one DPoP storage request once and fails it when IndexedDB stays + * silent. A timeout never substitutes weaker key storage. `resume` returns + * false once the deadline settled the request. + */ +function withDpopDeadline( + register: ( + resume: (effect: Effect.Effect) => boolean, + ) => IDBTransaction | void, +): Effect.Effect { + return Effect.callback((resume) => { + let settled = false; + let deadline: ReturnType | undefined; + const transaction = register((effect) => { + if (settled) return false; + settled = true; + clearTimeout(deadline); + resume(effect); + return true; + }); + if (settled) return; + // @effect-diagnostics-next-line globalTimersInEffect:off + deadline = setTimeout(() => { + if (settled) return; + settled = true; + try { + // A key write that lands later could race the next key the relay generates. + transaction?.abort(); + } catch { + // The transaction already committed or finished. + } + resume(Effect.fail(dpopError(DPOP_STORAGE_SILENT_MESSAGE))); + }, DPOP_STORAGE_DEADLINE_MS); + }); +} + function openDpopDatabase(name = DPOP_DATABASE_NAME): Effect.Effect { - return Effect.callback((resume) => { + return withDpopDeadline((resume) => { const request = indexedDB.open(name, DPOP_DATABASE_VERSION); request.addEventListener("error", () => resume( @@ -57,7 +97,10 @@ function openDpopDatabase(name = DPOP_DATABASE_NAME): Effect.Effect resume(Effect.succeed(request.result))); + request.addEventListener("success", () => { + // An open that answers after its deadline is closed, because nobody uses it. + if (!resume(Effect.succeed(request.result))) request.result.close(); + }); }); } @@ -67,7 +110,7 @@ function readStoredBrowserDpopKeyFrom( return Effect.acquireUseRelease( openDpopDatabase(databaseName), (database) => - Effect.callback((resume) => { + withDpopDeadline((resume) => { const request = database .transaction(DPOP_KEY_STORE_NAME, "readonly") .objectStore(DPOP_KEY_STORE_NAME) @@ -90,7 +133,7 @@ function writeStoredBrowserDpopKeyTo( return Effect.acquireUseRelease( openDpopDatabase(databaseName), (database) => - Effect.callback((resume) => { + withDpopDeadline((resume) => { const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite"); transaction.addEventListener("error", () => resume( @@ -99,6 +142,7 @@ function writeStoredBrowserDpopKeyTo( ); transaction.addEventListener("complete", () => resume(Effect.void)); transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID); + return transaction; }), (database) => Effect.sync(() => database.close()), ); diff --git a/apps/web/src/codeReview.test.ts b/apps/web/src/codeReview.test.ts index 4ccb3d08f1..81119e6e88 100644 --- a/apps/web/src/codeReview.test.ts +++ b/apps/web/src/codeReview.test.ts @@ -154,6 +154,27 @@ describe("codeReviewGuardLine", () => { expect(line("terminal", "codex")).toBe("Runs in Codex's read-only sandbox."); }); + 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( + "Runs on its own in Codex's read-only sandbox, like the Codex terminal review.", + ); + // An older server still asks before commands, so the line keeps today's wording. + expect(codeReviewGuardLine({ kind: "chat", driver: codex, readOnlyCodexReviews: false })).toBe( + "Runs in Codex's read-only sandbox. Writes ask for your approval.", + ); + expect( + codeReviewGuardLine({ kind: "terminal", driver: codex, readOnlyCodexReviews: true }), + ).toBe("Runs in Codex's read-only sandbox."); + expect( + codeReviewGuardLine({ + kind: "chat", + driver: ProviderDriverKind.make("claudeAgent"), + readOnlyCodexReviews: true, + }), + ).toBe("Starts in Claude's plan mode."); + }); + it("never promises that a review cannot edit", () => { for (const kind of ["chat", "terminal"] as const) { for (const driver of ["claudeAgent", "codex", "opencode", "cursor", "grok", "other"]) { diff --git a/apps/web/src/codeReview.ts b/apps/web/src/codeReview.ts index f878c57355..7867351e84 100644 --- a/apps/web/src/codeReview.ts +++ b/apps/web/src/codeReview.ts @@ -62,11 +62,14 @@ const INSTRUCTED_GUARD_LINE = "Told not to edit. BiBCode cannot block edits for export function codeReviewGuardLine(reviewer: { readonly kind: "chat" | "terminal"; readonly driver: ProviderDriverKind; + /** The server's `readOnlyCodexReviews` capability (#376); absent on an older server. */ + readonly readOnlyCodexReviews?: boolean; }): string { if (reviewer.driver === "claudeAgent") return "Starts in Claude's plan mode."; if (reviewer.driver === "codex") { - return reviewer.kind === "terminal" - ? "Runs in Codex's read-only sandbox." + if (reviewer.kind === "terminal") return "Runs in Codex's read-only sandbox."; + return reviewer.readOnlyCodexReviews === true + ? "Runs on its own in Codex's read-only sandbox, like the Codex terminal review." : "Runs in Codex's read-only sandbox. Writes ask for your approval."; } if (reviewer.driver === "opencode" && reviewer.kind === "chat") { @@ -132,12 +135,17 @@ export interface CodeReviewMenuReviewer { export function buildCodeReviewMenuReviewers( actions: ReadonlyArray, reasonFor: (action: ProviderAgentAction) => string | null, + readOnlyCodexReviews = false, ): ReadonlyArray { return codeReviewerActions(actions).map((action) => ({ value: action.value, label: action.label, selection: action.selection, - guardLine: codeReviewGuardLine({ kind: action.kind, driver: action.entry.driverKind }), + guardLine: codeReviewGuardLine({ + kind: action.kind, + driver: action.entry.driverKind, + readOnlyCodexReviews, + }), disabledReason: reasonFor(action), })); } diff --git a/apps/web/src/components/CenterTerminalPanel.test.tsx b/apps/web/src/components/CenterTerminalPanel.test.tsx index d229a5e8c2..dcd0ecc86a 100644 --- a/apps/web/src/components/CenterTerminalPanel.test.tsx +++ b/apps/web/src/components/CenterTerminalPanel.test.tsx @@ -95,6 +95,8 @@ describe("CenterTerminalPanel", () => { expect(h.panelProps?.["onSplitTerminal"]).toBeUndefined(); expect(h.panelProps?.["onSplitTerminalVertical"]).toBeUndefined(); expect(h.panelProps?.["onCloseTerminal"]).toBe(onClose); + expect(h.panelProps?.["chatThread"]).toBe(true); + expect(h.panelProps?.["attachOnly"]).toBe(false); expect( (h.panelProps!["terminalCommandsById"] as ReadonlyMap).get("term-1"), ).toEqual(surface.command); diff --git a/apps/web/src/components/CenterTerminalPanel.tsx b/apps/web/src/components/CenterTerminalPanel.tsx index 05c5f75356..2f903d8c5d 100644 --- a/apps/web/src/components/CenterTerminalPanel.tsx +++ b/apps/web/src/components/CenterTerminalPanel.tsx @@ -22,9 +22,13 @@ interface CenterTerminalPanelProps { focusRequestId: number; focusEligible: boolean; onAddTerminalContext: (selection: TerminalContextSelection) => void; - /** Invoked when the terminal is closed from within its own chrome. */ + /** Invoked when the terminal is closed from within its own chrome, or its process exits. */ onClose: () => void; workspaceUnavailable?: string | null; + /** False when no chat owns the terminal: no Add to chat, and links open without one. */ + chatThread?: boolean; + /** The session exists already: attach to it and never start one. */ + attachOnly?: boolean; } const noop = () => undefined; @@ -49,6 +53,8 @@ export function CenterTerminalPanel({ onAddTerminalContext, onClose, workspaceUnavailable = null, + chatThread = true, + attachOnly = false, }: CenterTerminalPanelProps) { const { terminalId, command, label } = surface; const knownTerminalSessions = useKnownTerminalSessions({ @@ -90,6 +96,8 @@ export function CenterTerminalPanel({ onActiveTerminalChange={noop} onCloseTerminal={onClose} onAddTerminalContext={onAddTerminalContext} + chatThread={chatThread} + attachOnly={attachOnly} terminalLabelsById={terminalLabelsById} {...(terminalCommandsById ? { terminalCommandsById } : {})} keybindings={keybindings} diff --git a/apps/web/src/components/ChatMarkdown.mermaid.test.tsx b/apps/web/src/components/ChatMarkdown.mermaid.test.tsx index 369cc04457..64800f5dcd 100644 --- a/apps/web/src/components/ChatMarkdown.mermaid.test.tsx +++ b/apps/web/src/components/ChatMarkdown.mermaid.test.tsx @@ -17,6 +17,7 @@ import { projectFindSource, } from "./chat/threadFind/threadFindText"; import { + __holdMermaidDrawsForTests, __resetMermaidDiagramsForTests, __setMermaidRendererLoaderForTests, } from "./markdown/MarkdownMermaidBlock"; @@ -118,9 +119,16 @@ async function flushMicrotasks(): Promise { }); } +/** + * Waits by the clock, not by a number of polls: the first diagram waits for the renderer and a + * diagram chunk to be imported, which takes seconds when the whole suite loads the machine. + */ +const WAIT_FOR_MS = 20_000; + async function waitFor(condition: () => boolean, message: string): Promise { - for (let attempt = 0; !condition(); attempt += 1) { - if (attempt > 400) throw new Error(message); + const deadline = performance.now() + WAIT_FOR_MS; + while (!condition()) { + if (performance.now() > deadline) throw new Error(message); await settle(1); } } @@ -236,6 +244,38 @@ describe("Mermaid diagrams in chat Markdown", () => { expect(renderedSources).toEqual([FLOWCHART]); }); + it("keeps a cold diagram's source while draws are held, and draws it on release", async () => { + const release = __holdMermaidDrawsForTests(); + const view = await mount(fence(FLOWCHART)); + // Long enough for the renderer import and the queue to run were the draw not held. + await waitFor(() => rendererLoads > 0, "the renderer never loaded"); + await settle(20); + expect(hasDiagram(view.container)).toBe(false); + expect(view.container.querySelector("pre")?.textContent).toContain("Write --> Draw"); + expect(renderedSources).toEqual([]); + + act(() => release()); + await waitFor(() => hasDiagram(view.container), "the released diagram never drew"); + expect(renderedSources).toEqual([FLOWCHART]); + }); + + it("exposes no draw hold to the page outside the packaged UI build", () => { + expect("__bibcodeHoldMermaidDraws" in window).toBe(false); + }); + + it("holds no draw when called outside unit tests and the packaged UI build", async () => { + // An ordinary development build, where any page script can import the module. + vi.stubEnv("MODE", "development"); + try { + const release = __holdMermaidDrawsForTests(); + const view = await mount(fence(FLOWCHART)); + await waitFor(() => hasDiagram(view.container), "the held diagram never drew"); + release(); + } finally { + vi.unstubAllEnvs(); + } + }); + it("keeps raw-HTML language-mermaid as source", async () => { const view = await mount(`
${FLOWCHART}\n
`); await settle(); diff --git a/apps/web/src/components/ChatView.hooks.test.tsx b/apps/web/src/components/ChatView.hooks.test.tsx index 35f600e009..abafb17b80 100644 --- a/apps/web/src/components/ChatView.hooks.test.tsx +++ b/apps/web/src/components/ChatView.hooks.test.tsx @@ -309,7 +309,12 @@ vi.mock("../state/terminalSessions", () => ({ useThreadRunningTerminalIds: () => h.runningTerminalIds, })); +const updateEnvironmentSettingsMock = vi.hoisted(() => + vi.fn(async (_patch: unknown) => ({ _tag: "Success" as const })), +); vi.mock("../hooks/useSettings", () => ({ + useUpdateEnvironmentSettings: () => updateEnvironmentSettingsMock, + readEnvironmentServerSettings: () => h.settings, useEnvironmentSettings: (_environmentId: string, selector?: (settings: unknown) => unknown) => selector ? selector(h.settings) : h.settings, })); diff --git a/apps/web/src/components/ChatView.test.tsx b/apps/web/src/components/ChatView.test.tsx index 1c04c11048..67f7b3ac73 100644 --- a/apps/web/src/components/ChatView.test.tsx +++ b/apps/web/src/components/ChatView.test.tsx @@ -397,7 +397,13 @@ vi.mock("../state/terminalSessions", () => ({ useThreadRunningTerminalIds: () => h.runningTerminalIds, })); +const updateEnvironmentSettingsMock = vi.hoisted(() => + vi.fn(async (_patch: unknown) => ({ _tag: "Success" as const })), +); vi.mock("../hooks/useSettings", () => ({ + useUpdateEnvironmentSettings: () => updateEnvironmentSettingsMock, + readEnvironmentServerSettings: (environmentId: string) => + h.environmentSettingsById.get(environmentId) ?? h.settings, useEnvironmentSettings: ( environmentId: string, selector?: (settings: Record) => unknown, @@ -8233,6 +8239,235 @@ describe("ChatView send snapshot", () => { }); }); + it("saves Codex's default over a saved default that names a retired model (#380)", async () => { + updateEnvironmentSettingsMock.mockClear(); + h.settings = { + ...h.settings, + providerSessionDefaults: { codex: { model: "gpt-5.4", options: [] } }, + }; + seedEnvironment(makeEnvironmentPresentation()); + seedProject(makeProject()); + seedServerThread(makeThread()); + seedGitStatus(true); + const add = vi.spyOn(toastManager, "add").mockReturnValue("retired-toast"); + const send = async (offered: { slug: string }[]) => { + renderServerRoute(); + const composer = capturedProps>("chatComposer"); + (composer["composerAttachmentsRef"] as RefObject).current = []; + (composer["composerRef"] as RefObject).current = { + focusAtEnd: () => undefined, + resetCursorState: () => undefined, + addTerminalContext: () => false, + getSendContext: () => ({ + attachments: [], + terminalContexts: [], + elementContexts: [], + previewAnnotations: [], + reviewComments: [], + selectedProvider: ProviderDriverKind.make("codex"), + selectedModel: "auto", + selectedProviderModels: offered, + selectedPromptEffort: null, + selectedModelSelection: { instanceId: codexInstanceId, model: "auto" }, + }), + } as unknown as ChatComposerHandle; + (composer["promptRef"] as RefObject).current = "hello"; + await (composer["onSend"] as () => Promise)(); + }; + + // API-key sign-in: Codex still offers the model, so the saved default stays. + await send([{ slug: "auto" }, { slug: "gpt-5.4" }]); + expect(updateEnvironmentSettingsMock).not.toHaveBeenCalled(); + + // ChatGPT sign-in: the list leaves it out, so the default is saved again, then announced. + await send([{ slug: "auto" }, { slug: "gpt-6.2-sol" }]); + expect(updateEnvironmentSettingsMock).toHaveBeenCalledWith( + { providerSessionDefaults: { codex: { model: "auto", options: [] } } }, + { ownedProviderSessionDefaults: ["codex"] }, + ); + await vi.waitFor(() => + expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Codex retired gpt-5.4" })), + ); + }); + + const sendCodexAuto = async () => { + renderServerRoute(); + const composer = capturedProps>("chatComposer"); + (composer["composerAttachmentsRef"] as RefObject).current = []; + (composer["composerRef"] as RefObject).current = { + focusAtEnd: () => undefined, + resetCursorState: () => undefined, + addTerminalContext: () => false, + getSendContext: () => ({ + attachments: [], + terminalContexts: [], + elementContexts: [], + previewAnnotations: [], + reviewComments: [], + selectedProvider: ProviderDriverKind.make("codex"), + selectedModel: "auto", + selectedProviderModels: [{ slug: "auto" }, { slug: "gpt-6.2-sol" }], + selectedPromptEffort: null, + selectedModelSelection: { instanceId: codexInstanceId, model: "auto" }, + }), + } as unknown as ChatComposerHandle; + (composer["promptRef"] as RefObject).current = "hello"; + await (composer["onSend"] as () => Promise)(); + }; + + it("keeps another window's saved default when a send clears a retired Codex default (#380)", async () => { + updateEnvironmentSettingsMock.mockClear(); + h.settings = { + ...h.settings, + providerSessionDefaults: { codex: { model: "gpt-5.4", options: [] } }, + }; + seedEnvironment(makeEnvironmentPresentation()); + seedProject(makeProject()); + seedServerThread(makeThread()); + seedGitStatus(true); + const claudeDefault = { model: "claude-sonnet-4-6", options: [] }; + // Another window saves a Claude default while this send is in flight. + h.commandResults["thread.updateMetadata"] = (input) => { + const defaults = h.settings["providerSessionDefaults"] as Record; + h.settings = { + ...h.settings, + providerSessionDefaults: { ...defaults, claudeAgent: claudeDefault }, + }; + return h.defaultCommandResult(input); + }; + + await sendCodexAuto(); + + expect(updateEnvironmentSettingsMock).toHaveBeenCalledWith( + { + providerSessionDefaults: { + codex: { model: "auto", options: [] }, + claudeAgent: claudeDefault, + }, + }, + { ownedProviderSessionDefaults: ["codex"] }, + ); + }); + + it("owns only the Codex default when another window's save has not reached this one (#380)", async () => { + updateEnvironmentSettingsMock.mockClear(); + // Window B saved a Claude default on the server; its config event has not arrived here. + h.settings = { + ...h.settings, + providerSessionDefaults: { codex: { model: "gpt-5.4", options: [] } }, + }; + seedEnvironment(makeEnvironmentPresentation()); + seedProject(makeProject()); + seedServerThread(makeThread()); + seedGitStatus(true); + + await sendCodexAuto(); + + // The server merges an owned provider into its own map, so B's default survives. + expect(updateEnvironmentSettingsMock).toHaveBeenCalledWith( + { providerSessionDefaults: { codex: { model: "auto", options: [] } } }, + { ownedProviderSessionDefaults: ["codex"] }, + ); + }); + + it("shows one notice when the thread and the saved default name the same retired model (#380)", async () => { + updateEnvironmentSettingsMock.mockClear(); + h.settings = { + ...h.settings, + providerSessionDefaults: { codex: { model: "gpt-5.4", options: [] } }, + }; + seedEnvironment(makeEnvironmentPresentation()); + seedProject(makeProject()); + seedServerThread(makeThread()); + seedGitStatus(true); + const add = vi.spyOn(toastManager, "add").mockReturnValue("retired-toast"); + add.mockClear(); + try { + await sendCodexAuto(); + await vi.waitFor(() => expect(updateEnvironmentSettingsMock).toHaveBeenCalledTimes(1)); + await Promise.resolve(); + const notices = add.mock.calls.filter(([toast]) => + String(toast.title).startsWith("Codex retired"), + ); + expect(notices).toHaveLength(1); + expect(notices[0]![0]).toMatchObject({ + title: "Codex retired gpt-5.4", + description: "This thread and your saved Codex default now use Codex's default model.", + }); + } finally { + add.mockRestore(); + } + }); + + it("saves Codex's default over a retired saved default on a new chat's first send (#380)", async () => { + updateEnvironmentSettingsMock.mockClear(); + h.settings = { + ...h.settings, + providerSessionDefaults: { codex: { model: "gpt-5.4", options: [] } }, + }; + seedEnvironment(makeEnvironmentPresentation()); + seedProject(makeProject()); + seedGitStatus(true); + const draftId = newDraftId(); + useComposerDraftStore + .getState() + .setLogicalProjectDraftThreadId( + "logical-project-1", + scopeProjectRef(environmentId, projectId), + draftId, + { threadId, createdAt: now, envMode: "local" }, + ); + publishSeededStoreState(useComposerDraftStore); + const add = vi.spyOn(toastManager, "add").mockReturnValue("retired-toast"); + // An earlier case's spy may still hold its notices. + add.mockClear(); + try { + renderToStaticMarkup( + , + ); + const composer = capturedProps>("chatComposer"); + (composer["composerAttachmentsRef"] as RefObject).current = []; + (composer["composerRef"] as RefObject).current = { + focusAtEnd: () => undefined, + resetCursorState: () => undefined, + addTerminalContext: () => false, + getSendContext: () => ({ + attachments: [], + terminalContexts: [], + elementContexts: [], + previewAnnotations: [], + reviewComments: [], + selectedProvider: ProviderDriverKind.make("codex"), + selectedModel: "auto", + selectedProviderModels: [{ slug: "auto" }, { slug: "gpt-6.2-sol" }], + selectedPromptEffort: null, + selectedModelSelection: { instanceId: codexInstanceId, model: "auto" }, + }), + } as unknown as ChatComposerHandle; + (composer["promptRef"] as RefObject).current = "hello"; + await (composer["onSend"] as () => Promise)(); + + expect(h.commandCalls.filter((call) => call.key === "thread.startTurn")).toHaveLength(1); + expect(updateEnvironmentSettingsMock).toHaveBeenCalledTimes(1); + expect(updateEnvironmentSettingsMock).toHaveBeenCalledWith( + { providerSessionDefaults: { codex: { model: "auto", options: [] } } }, + { ownedProviderSessionDefaults: ["codex"] }, + ); + await vi.waitFor(() => + expect( + add.mock.calls.filter(([toast]) => toast.title === "Codex retired gpt-5.4"), + ).toHaveLength(1), + ); + } finally { + add.mockRestore(); + } + }); + it("restores a send whose staging fails when the connection drops, and never resends it", async () => { seedEnvironment(makeEnvironmentPresentation()); seedProject(makeProject()); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index cc89426ba7..feade9ff01 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -24,6 +24,7 @@ import { type OrchestrationReasoning, OrchestrationThreadActivity, ProviderInteractionMode, + CODEX_AUTO_MODEL, ProviderDriverKind, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, RuntimeMode, @@ -71,7 +72,12 @@ import { scopeProjectRef, scopeThreadRef, } from "@bibcode/client-runtime/environment"; -import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@bibcode/shared/model"; +import { + applyClaudePromptEffortPrefix, + replacedRetiredCodexModel, + retiredCodexSessionDefault, + resolvePromptInjectedEffort, +} from "@bibcode/shared/model"; import { canonicalizeLegacyComposerFileReferences } from "@bibcode/shared/composerReferences"; import { resolveProviderSessionDefault } from "@bibcode/shared/providerSessionDefaults"; import { CHAT_LIST_ANCHOR_OFFSET } from "@bibcode/shared/chatList"; @@ -278,7 +284,11 @@ import { } from "~/projectScripts"; import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels"; -import { useEnvironmentSettings } from "../hooks/useSettings"; +import { + readEnvironmentServerSettings, + useEnvironmentSettings, + useUpdateEnvironmentSettings, +} from "../hooks/useSettings"; import { readTerminalFittedSize } from "./terminalSizing"; import { worktreeEnvironment } from "../state/worktrees"; import { resolveAppModelSelectionForInstance } from "../modelSelection"; @@ -1267,6 +1277,7 @@ function ChatViewContent(props: ChatViewProps) { routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined, ); const settings = useEnvironmentSettings(environmentId); + const updateEnvironmentSettings = useUpdateEnvironmentSettings(environmentId); const enableChatAgentActivity = settings.enableChatAgentActivity; const enableTerminalAgentActivity = settings.enableTerminalAgentActivity; const setStickyComposerModelSelection = useComposerDraftStore( @@ -5016,6 +5027,8 @@ function ChatViewContent(props: ChatViewProps) { ); const codeReviewPlatformOs = serverConfig?.environment.platform.os ?? null; const codeReviewsSupported = serverConfig?.environment.capabilities?.codeReviews === true; + const readOnlyCodexReviews = + serverConfig?.environment.capabilities?.readOnlyCodexReviews === true; const hasCodeReviewLaunchContext = isServerThread && centerPanelLaunchContext !== null; // Reasons that hold for every reviewer on this thread and environment. const codeReviewEnvironmentReason = !codeReviewsSupported @@ -5053,13 +5066,15 @@ function ChatViewContent(props: ChatViewProps) { (action.disabled ? (action.disabledReason ?? `${action.label} is not available.`) : codeReviewerReason({ action, reason: null })), + readOnlyCodexReviews, ), - [codeReviewAgentActions, codeReviewEnvironmentReason, codeReviewerReason], + [codeReviewAgentActions, codeReviewEnvironmentReason, codeReviewerReason, readOnlyCodexReviews], ); const codeReviewGuard = savedCodeReviewer.action ? codeReviewGuardLine({ kind: savedCodeReviewer.action.kind, driver: savedCodeReviewer.action.entry.driverKind, + readOnlyCodexReviews, }) : null; // `selection` is a one-off reviewer from the menu; the saved reviewer stays as saved (R103). @@ -6811,6 +6826,7 @@ function ChatViewContent(props: ChatViewProps) { } } + let retiredThreadModel: string | null = null; if (failure === null && isServerThread) { const settingsResult = await persistThreadSettingsForNextTurn({ threadId: threadIdForSend, @@ -6821,6 +6837,69 @@ function ChatViewContent(props: ChatViewProps) { }); if (settingsResult._tag === "Failure") { failure = settingsResult; + } else { + // #380: the thread stored a model Codex retired, and this send replaced it with + // Codex's default. The thread now stores that choice, so this shows once. + retiredThreadModel = ctxSelectedModel + ? replacedRetiredCodexModel({ + driver: ctxSelectedProvider, + stored: activeThread?.modelSelection, + sent: ctxSelectedModelSelection, + offered: ctxSelectedProviderModels, + }) + : null; + } + } + + // #380 R4: a saved default that names the retired model is cleared when it is used, + // a new chat's first send included. + if (failure === null) { + const announceRetired = (models: ReadonlyArray, description: string) => + toastManager.add( + stackedThreadToast({ + type: "warning", + title: `Codex retired ${[...new Set(models.filter(Boolean))].join(" and ")}`, + description, + }), + ); + const threadNotice = "This thread now uses Codex's default model."; + // Read now, not from the render: another window may have saved a default meanwhile. + const savedDefaults = readEnvironmentServerSettings(environmentId).providerSessionDefaults; + const savedCodexDefault = savedDefaults[ctxSelectedProvider]; + const retiredDefault = + ctxSelectedProvider === ProviderDriverKind.make("codex") + ? retiredCodexSessionDefault({ + saved: savedCodexDefault, + offered: ctxSelectedProviderModels, + }) + : null; + if (retiredDefault !== null && savedCodexDefault) { + // The notice says the default was saved, so it waits for the save; one notice + // covers the thread too. + // Owning only this provider's default keeps one another window saved meanwhile; an + // older server ignores the option and replaces the map, as before. + void updateEnvironmentSettings( + { + providerSessionDefaults: { + ...savedDefaults, + [ctxSelectedProvider]: { ...savedCodexDefault, model: CODEX_AUTO_MODEL }, + }, + }, + { ownedProviderSessionDefaults: [ctxSelectedProvider] }, + ).then((result) => { + if (result._tag !== "Success") { + if (retiredThreadModel !== null) announceRetired([retiredThreadModel], threadNotice); + return; + } + announceRetired( + [retiredThreadModel, retiredDefault], + retiredThreadModel !== null + ? "This thread and your saved Codex default now use Codex's default model." + : "Your saved Codex default now uses Codex's default model.", + ); + }); + } else if (retiredThreadModel !== null) { + announceRetired([retiredThreadModel], threadNotice); } } @@ -8252,6 +8331,7 @@ function ChatViewContent(props: ChatViewProps) { planSidebarOpen={planSidebarOpen} runtimeMode={runtimeMode} interactionMode={interactionMode} + readOnlyCodexReviews={readOnlyCodexReviews} lockedProvider={lockedProvider} providerBindingInstanceId={providerBinding.instanceId} lockProviderPickerToActiveInstance={lockProviderPickerToActiveInstance} diff --git a/apps/web/src/components/ConnectionDatabaseRecoveryDialog.test.tsx b/apps/web/src/components/ConnectionDatabaseRecoveryDialog.test.tsx index 881cd798b2..885086c41a 100644 --- a/apps/web/src/components/ConnectionDatabaseRecoveryDialog.test.tsx +++ b/apps/web/src/components/ConnectionDatabaseRecoveryDialog.test.tsx @@ -22,12 +22,17 @@ vi.mock("./ui/dialog", () => { DialogTitle: passthrough, }; }); +// The readiness attribute reads the live connection runtime, which these tests do not build. +vi.mock("../connection/connectionStoreReadiness", () => ({ + useConnectionStoreReadinessAttribute: () => undefined, +})); vi.mock("./ui/button", () => ({ Button: (props: React.ButtonHTMLAttributes) => ) : null} - + {timedOut ? null : } diff --git a/apps/web/src/components/RemoteUpdateRequestNotifier.install.test.tsx b/apps/web/src/components/RemoteUpdateRequestNotifier.install.test.tsx index e345397e6c..c884cfd00d 100644 --- a/apps/web/src/components/RemoteUpdateRequestNotifier.install.test.tsx +++ b/apps/web/src/components/RemoteUpdateRequestNotifier.install.test.tsx @@ -2,7 +2,7 @@ import type { DesktopBridge } from "@bibcode/contracts"; import { act, Children, isValidElement, type ReactElement, type ReactNode } from "react"; import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test"; vi.mock("../env", async (importOriginal) => ({ ...(await importOriginal()), @@ -61,6 +61,12 @@ const manageDevices = () => const toastText = () => document.querySelector('[data-slot="toast-portal"]')?.textContent ?? ""; const dialogText = () => document.querySelector('[data-slot="alert-dialog-popup"]')?.textContent; +// The first import of the whole app graph is a cold transform that takes tens of seconds on a +// loaded machine; it belongs in a hook with its own budget, not in the first test's 30 s. +beforeAll(async () => { + await import("../AppRoot"); +}, 120_000); + let container: HTMLDivElement; let root: Root; diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 988020023f..83252cf8d7 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -585,6 +585,44 @@ describe("SidebarThreadRow browser interactions", () => { }, ); + it("hides the open chat's card when its project is collapsed and shows it again (#382)", async () => { + baseScenario(); + h.state.routeParams = { environmentId: ENV_MAIN, threadId: "thread-default" }; + const key = derivePhysicalProjectKey(projectA); + h.uiStore.setState({ projectExpandedById: { [key]: true } }); + const { container, root } = await mount(); + const header = () => + container.querySelector('[data-mock="SidebarMenuButton"][aria-expanded]')!; + const cards = () => + container.querySelectorAll('[data-testid^="primary-card-"], [data-testid^="thread-row-"]'); + // The harness store does not notify subscribers, so the new state needs a render. + const setExpanded = (expanded: boolean) => + React.act(async () => { + h.uiStore.setState({ projectExpandedById: { [key]: expanded } }); + root.render(); + }); + try { + await React.act(async () => flush()); + expect(header().getAttribute("aria-expanded")).toBe("true"); + expect(cards().length).toBeGreaterThan(1); + + await dispatch(header(), new MouseEvent("click", { bubbles: true })); + expect(h.spies.setProjectExpanded).toHaveBeenCalledWith(expect.anything(), false); + await setExpanded(false); + expect(header().getAttribute("aria-expanded")).toBe("false"); + expect(cards()).toHaveLength(0); + // The open chat is hidden, so the collapsed header says it holds the current page. + expect(header().getAttribute("aria-current")).toBe("true"); + + await setExpanded(true); + expect(header().getAttribute("aria-expanded")).toBe("true"); + expect(header().getAttribute("aria-current")).toBeNull(); + expect(cards().length).toBeGreaterThan(1); + } finally { + await unmount(root, container); + } + }); + it.each([ { expanded: true, label: "Show Hidden Worktrees (1)" }, { expanded: false, label: "Show Hidden Worktrees" }, diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 6c79c9eb66..c478b94e5b 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -4,6 +4,7 @@ import { findDefaultThread, getSidebarThreadIdsToPrewarm, getVisibleSidebarThreadIds, + resolveVisibleProjectThreads, orderRowsWithPins, resolveAdjacentThreadId, getFallbackThreadIdAfterDelete, @@ -610,6 +611,85 @@ describe("resolveAdjacentThreadId", () => { }); }); +describe("resolveVisibleProjectThreads", () => { + const thread = (id: string, kind: "default" | "worktree" | "panel" = "worktree") => ({ + id, + kind, + }); + const resolve = ( + threads: ReturnType[], + overrides: { + pinnedKeys?: string[]; + isListExpanded?: boolean; + previewCount?: number; + sort?: (ids: string[]) => string[]; + } = {}, + ) => { + const result = resolveVisibleProjectThreads({ + threads: threads as never, + sort: (items) => { + const order = overrides.sort?.(items.map((item) => (item as { id: string }).id)); + return order + ? order.map((id) => items.find((item) => (item as { id: string }).id === id)!) + : items; + }, + pinnedKeys: overrides.pinnedKeys ?? [], + keyOf: (item) => (item as unknown as { id: string }).id, + isListExpanded: overrides.isListExpanded ?? false, + previewCount: overrides.previewCount ?? 6, + }); + return { + primary: (result.primaryThread as { id: string } | null)?.id ?? null, + rows: (result.rows as { id: string }[]).map((row) => row.id), + }; + }; + + it("gives a panel chat no row, even when it is the most recent thread", () => { + // A center-panel chat is not a sidebar row, so a jump shortcut must not reach it. + expect(resolve([thread("panel-chat", "panel"), thread("a"), thread("b")]).rows).toEqual([ + "a", + "b", + ]); + }); + + it("keeps a grouped card's first default thread as the primary, whatever the sort order", () => { + // Two member projects, one default thread each: the card shows the first as its primary + // and the second as a row, so the second takes a jump number even when it sorts first. + const threads = [thread("main-a", "default"), thread("main-b", "default"), thread("w")]; + expect(resolve(threads, { sort: (ids) => ids.toReversed() })).toEqual({ + primary: "main-a", + rows: ["w", "main-b"], + }); + }); + + it("keeps the primary thread out of the rows", () => { + expect(resolve([thread("a"), thread("main", "default"), thread("b")])).toEqual({ + primary: "main", + rows: ["a", "b"], + }); + }); + + it("puts pinned rows first, as the card renders them", () => { + expect(resolve([thread("a"), thread("b"), thread("c")], { pinnedKeys: ["c"] }).rows).toEqual([ + "c", + "a", + "b", + ]); + }); + + it("shows only the preview while the list is folded", () => { + const threads = [thread("a"), thread("b"), thread("c")]; + expect(resolve(threads, { previewCount: 2 }).rows).toEqual(["a", "b"]); + expect(resolve(threads, { previewCount: 2, isListExpanded: true }).rows).toEqual([ + "a", + "b", + "c", + ]); + // A pinned row past the fold is shown before an unpinned one inside it. + expect(resolve(threads, { previewCount: 2, pinnedKeys: ["c"] }).rows).toEqual(["c", "a"]); + }); +}); + describe("getVisibleSidebarThreadIds", () => { it("returns only the rendered visible thread order across projects", () => { expect( @@ -1948,3 +2028,16 @@ describe("keyboard context menu helpers", () => { expect(isKeyboardContextMenuEcho(Number.NEGATIVE_INFINITY, 5)).toBe(false); }); }); + +describe("resolveSidebarProjectAvailability when the connection runtime failed", () => { + it("reports the failure instead of loading forever", () => { + expect( + resolveSidebarProjectAvailability({ + projectCount: 0, + catalogReady: false, + catalogFailed: true, + environments: [], + }), + ).toEqual({ kind: "runtime-failed", environmentId: null, error: null }); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index abffa43105..784f91c9c4 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -30,7 +30,7 @@ export type SidebarNewThreadEnvMode = "local" | "worktree"; export type SidebarProjectAvailabilityView = | { - readonly kind: "available" | "empty-confirmed" | "loading"; + readonly kind: "available" | "empty-confirmed" | "loading" | "runtime-failed"; readonly environmentId: null; readonly error: null; } @@ -59,6 +59,8 @@ const SIDEBAR_PROJECT_AVAILABILITY_PRIORITY = [ export function resolveSidebarProjectAvailability(input: { readonly projectCount: number; readonly catalogReady: boolean; + /** The connection runtime failed to build, so the catalog never becomes ready. */ + readonly catalogFailed?: boolean | undefined; readonly catalogHealth?: ConnectionCatalogHealth; readonly environments: ReadonlyArray; }): SidebarProjectAvailabilityView { @@ -71,7 +73,11 @@ export function resolveSidebarProjectAvailability(input: { }; } if (!input.catalogReady) { - return { kind: "loading", environmentId: null, error: null }; + return { + kind: input.catalogFailed === true ? "runtime-failed" : "loading", + environmentId: null, + error: null, + }; } const everyEnvironmentIsAuthoritative = @@ -1189,6 +1195,33 @@ export function splitPrimaryAndWorkspaceThreads(input: { + /** The project's unarchived threads, in the order the card receives them. */ + readonly threads: readonly T[]; + /** The sidebar's sort order for the rows. */ + readonly sort: (threads: T[]) => readonly T[]; + readonly pinnedKeys: ReadonlySet | readonly string[]; + readonly keyOf: (thread: T) => string; + readonly isListExpanded: boolean; + readonly previewCount: number; +}): { primaryThread: T | null; rows: T[] } { + // The primary is chosen before sorting, as the card does: a grouped card can hold several + // default threads, and the first in member order is the primary whatever the sort order. + const { primaryThread, workspaceThreads } = splitPrimaryAndWorkspaceThreads(input.threads); + const ordered = orderRowsWithPins(input.sort(workspaceThreads), input.pinnedKeys, input.keyOf); + const rows = + input.isListExpanded || ordered.length <= input.previewCount + ? ordered + : ordered.slice(0, input.previewCount); + return { primaryThread, rows }; +} + export function orderRowsWithPins( items: readonly T[], pinnedKeys: ReadonlySet | readonly string[], diff --git a/apps/web/src/components/Sidebar.test.tsx b/apps/web/src/components/Sidebar.test.tsx index c2c0a0af43..ee83fe0eff 100644 --- a/apps/web/src/components/Sidebar.test.tsx +++ b/apps/web/src/components/Sidebar.test.tsx @@ -44,7 +44,7 @@ import { classOf, levelTextTags, textColorUtilities } from "./sidebar/sidebarLev import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import * as React from "react"; -import { beforeEach, expect, it, vi } from "vite-plus/test"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { DEFAULT_SERVER_SETTINGS, ProjectId, @@ -202,11 +202,50 @@ staticDescribe("Sidebar global event helpers", () => { expect(padding(PROJECT_HEADER_ACTION_PADDING[count].badge)).toBeGreaterThanOrEqual(strip + 22); }); - it("counts the always-shown actions plus Pull Requests and Pipelines", () => { - expect(projectHeaderActionCount({ showsPullRequests: false, showsPipelines: false })).toBe(3); - expect(projectHeaderActionCount({ showsPullRequests: true, showsPipelines: false })).toBe(4); - expect(projectHeaderActionCount({ showsPullRequests: false, showsPipelines: true })).toBe(4); - expect(projectHeaderActionCount({ showsPullRequests: true, showsPipelines: true })).toBe(5); + it("counts the always-shown actions plus Pull Requests, Pipelines and the server commands", () => { + const count = ( + showsPullRequests: boolean, + showsPipelines: boolean, + showsServerCommands = false, + ) => projectHeaderActionCount({ showsPullRequests, showsPipelines, showsServerCommands }); + expect(count(false, false)).toBe(3); + expect(count(true, false)).toBe(4); + expect(count(false, true)).toBe(4); + expect(count(true, true)).toBe(5); + // A Repositories server card: the three icons plus Open terminal and Dashboard. + expect(count(false, false, true)).toBe(5); + }); + + // #382: a collapsed card hides the open chat, so that chat is not in the ordered list. + it("traverses from the edge when the open chat is not listed", () => { + const first = makeThread("first"); + const second = makeThread("second"); + const hidden = makeThread("hidden"); + const navigateToThread = vi.fn(); + const base = { + orderedThreadKeys: [threadKeyOf(first), threadKeyOf(second)], + currentThreadKey: threadKeyOf(hidden), + jumpThreadKeys: [], + threadByKey: new Map([ + [threadKeyOf(first), first], + [threadKeyOf(second), second], + ]), + navigateToThread, + }; + expect( + handleSidebarNavigationKeyDown({ + ...base, + event: navigationEvent(), + resolveCommand: () => "thread.next", + }), + ).toBe(true); + expect(navigateToThread).toHaveBeenLastCalledWith(scopeThreadRef(ENV_MAIN, first.id)); + handleSidebarNavigationKeyDown({ + ...base, + event: navigationEvent(), + resolveCommand: () => "thread.previous", + }); + expect(navigateToThread).toHaveBeenLastCalledWith(scopeThreadRef(ENV_MAIN, second.id)); }); it("handles traversal and numbered jump shortcuts across every guard", () => { @@ -560,6 +599,13 @@ staticDescribe("Sidebar full render", () => { expect(markup).not.toContain("No projects yet"); }); + it("renders the failed connection runtime instead of loading forever", () => { + h.state.shellSummary = { ...h.state.shellSummary, catalogFailed: true }; + const markup = render(); + expect(markup).toContain("Connections could not start"); + expect(markup).not.toContain("Project data is still loading"); + }); + it("keeps a saved remote project row while hiding desktop remote recovery controls", () => { h.state.presentationPolicy = createEnvironmentPresentationPolicy({ surface: "desktop", @@ -734,17 +780,44 @@ staticDescribe("Sidebar full render", () => { expect(markup).not.toContain("No threads yet"); }); - it("collapses a project but keeps the active thread row visible", () => { - baseScenario(); - h.uiStore.setState({ - projectExpandedById: { [derivePhysicalProjectKey(projectA)]: false }, - }); - const markup = render(); - // Active thread peeks through even while collapsed; the inactive primary card does not. - expect(markup).toContain("thread-row-thread-active"); - expect(markup).not.toContain("thread-row-thread-idle"); - expect(markup).not.toContain('data-testid="primary-card-project-a"'); - }); + // #382: an explicit collapse hides every descendant, the open chat's card included. + staticDescribe.each(["environments", "repositories"] as const)( + "a collapsed card in %s", + (view) => { + const collapse = () => + h.uiStore.setState({ + sidebarView: view, + projectExpandedById: { [derivePhysicalProjectKey(projectA)]: false }, + }); + + it("hides the open worktree row and every other card", () => { + baseScenario(); + collapse(); + const markup = render(); + expect(markup).not.toContain("thread-row-thread-active"); + expect(markup).not.toContain("thread-row-thread-idle"); + expect(markup).not.toContain('data-testid="primary-card-project-a"'); + }); + + it("hides the primary card when its chat is the open one", () => { + baseScenario(); + h.state.routeParams = { environmentId: ENV_MAIN, threadId: threadDefault.id }; + collapse(); + const markup = render(); + expect(markup).not.toContain('data-testid="primary-card-project-a"'); + expect(markup).not.toContain("more chat"); + }); + + it("shows the cards again when expanded", () => { + baseScenario(); + h.state.routeParams = { environmentId: ENV_MAIN, threadId: threadDefault.id }; + h.uiStore.setState({ sidebarView: view }); + const markup = render(); + expect(markup).toContain('data-testid="primary-card-project-a"'); + expect(markup).toContain("thread-row-thread-active"); + }); + }, + ); it("writes only an environment card's own expansion keys, not the repository row's", () => { groupedScenario(); @@ -3870,6 +3943,95 @@ staticDescribe("grouped and remote projects", () => { expect(strip).not.toContain("opacity-0"); }); + describe("server card commands (#378)", () => { + it("puts Open terminal and Dashboard on each server card, named for its server", () => { + groupedScenario(); + h.uiStore.setState({ sidebarView: "repositories" }); + const markup = render(); + for (const label of ["Main", "Remote Box"]) { + const terminal = mustFindProps(byAriaLabel(`Open terminal on ${label}`), label); + const dashboard = mustFindProps(byAriaLabel(`Dashboard for ${label}`), label); + expect(terminal["data-testid"]).toBe("server-command-terminal"); + expect(dashboard["data-testid"]).toBe("server-command-dashboard"); + expect(terminal["aria-disabled"]).toBeUndefined(); + } + // The strip keeps its three icons, then the two server commands. + const strip = markup.slice(markup.indexOf('data-testid="project-actions-strip"')); + const order = [ + "project-actions-button", + "new-worktree-button", + "git-manager-button", + "server-command-terminal", + "server-command-dashboard", + ].map((id) => strip.indexOf(`data-testid="${id}"`)); + expect(order.every((index) => index >= 0)).toBe(true); + expect(order).toEqual([...order].toSorted((left, right) => left - right)); + // Five icons: the card title stops short of them. + const header = captured("SidebarMenuButton").find( + (entry) => typeof entry.props["onPointerDownCapture"] === "function", + )!; + expect(header.props["className"]).toContain(PROJECT_HEADER_ACTION_PADDING[5].plain); + }); + + it("opens that server's center panel from each icon", () => { + groupedScenario(); + h.uiStore.setState({ sidebarView: "repositories" }); + render(); + const click = mouseEvent(); + invoke(mustFindProps(byAriaLabel("Dashboard for Remote Box"), "Dashboard"), "onClick", click); + expect(click.stopPropagation, "the card must not toggle").toHaveBeenCalled(); + expect(h.spies.navigate).toHaveBeenLastCalledWith({ + to: "/environment/$environmentId/dashboard", + params: { environmentId: ENV_REMOTE }, + }); + invoke( + mustFindProps(byAriaLabel("Open terminal on Main"), "Terminal"), + "onClick", + mouseEvent(), + ); + expect(h.spies.navigate).toHaveBeenLastCalledWith({ + to: "/environment/$environmentId/terminal", + params: { environmentId: ENV_MAIN }, + search: { open: expect.any(Number) }, + }); + expect(h.spies.navigate).toHaveBeenCalledTimes(2); + }); + + it("explains and refuses the commands on a server that is not connected", () => { + groupedScenario(); + h.state.environments = [ + environmentFixture({ environmentId: ENV_MAIN, label: "Main", connectionId: "primary" }), + environmentFixture({ + environmentId: ENV_REMOTE, + label: "Remote Box", + connectionId: "remote", + phase: "error", + error: "Remote host is offline.", + }), + ]; + h.uiStore.setState({ sidebarView: "repositories" }); + render(); + for (const name of ["Open terminal on Remote Box", "Dashboard for Remote Box"]) { + const button = mustFindProps(byAriaLabel(name), name); + expect(button["aria-disabled"]).toBe(true); + expect(button["aria-description"]).toBe("Remote Box is not connected."); + invoke(button, "onClick", mouseEvent()); + } + expect(h.spies.navigate).not.toHaveBeenCalled(); + }); + + it("shows no server commands on a project row outside a server card", () => { + groupedScenario(); + h.uiStore.setState({ sidebarView: "environments" }); + render(); + expect(findProps(byTestId("server-command-terminal"))).toBeNull(); + expect(findProps(byTestId("server-command-dashboard"))).toBeNull(); + expect(findProps(byTestId("git-manager-button"))).not.toBeNull(); + expect(findProps(byTestId("new-worktree-button"))).not.toBeNull(); + expect(findProps(byTestId("project-actions-button"))).not.toBeNull(); + }); + }); + it("puts Pipelines after Pull Requests on the repository row, not its environment rows", () => { groupedScenario(); h.uiStore.setState({ sidebarView: "repositories" }); diff --git a/apps/web/src/components/Sidebar.testHarness.tsx b/apps/web/src/components/Sidebar.testHarness.tsx index 5067cd28c1..f1e5ccafb6 100644 --- a/apps/web/src/components/Sidebar.testHarness.tsx +++ b/apps/web/src/components/Sidebar.testHarness.tsx @@ -112,6 +112,7 @@ const h = vi.hoisted(() => { const domProps = new Set([ "aria-current", "aria-describedby", + "aria-expanded", "aria-label", "aria-labelledby", "autoFocus", @@ -304,7 +305,11 @@ const h = vi.hoisted(() => { vi.mock("@tanstack/react-router", () => ({ Link: h.mk("Link", "a"), useNavigate: () => h.spies.navigate, - useRouter: () => ({ navigate: h.spies.routerNavigate }), + useRouter: () => ({ + navigate: h.spies.routerNavigate, + buildLocation: ({ to }: { to: string }) => ({ pathname: to }), + state: { location: { pathname: h.state.pathname } }, + }), useLocation: (opts?: { select?: (loc: { pathname: string }) => unknown }) => opts?.select ? opts.select({ pathname: h.state.pathname }) : { pathname: h.state.pathname }, useParams: (opts?: { select?: (params: Record) => unknown }) => diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8968a3f399..1a73b096ff 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -187,6 +187,7 @@ import { import { AgentsNavRow } from "./sidebar/AgentsNavRow"; import { AgentsUnreadTracker } from "./sidebar/AgentsUnreadTracker"; import { SendRequestsUnreadTracker } from "./sendToAgent/SendRequestsUnreadTracker"; +import { ServerCommandButtons } from "./serverCommands/ServerCommandButtons"; import { EnvironmentCardHeader } from "./sidebar/EnvironmentCardHeader"; import { EnvironmentContextCard } from "./sidebar/EnvironmentContextCard"; import { @@ -268,6 +269,7 @@ import { getSidebarThreadIdsToPrewarm, orderRowsWithPins, resolveAdjacentThreadId, + resolveVisibleProjectThreads, isContextMenuPointerDown, isTrailingDoubleClick, resolveSidebarProjectAvailability, @@ -485,6 +487,7 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = { easing: "ease-out", } as const; const EMPTY_THREAD_JUMP_LABELS = new Map(); +const EMPTY_RENDERED_THREADS: readonly SidebarThreadSummary[] = []; const EMPTY_EDITOR_IDS: ReadonlyArray = []; const PROJECT_GROUPING_MODE_LABELS: Record = { repository: "Group by repository", @@ -516,7 +519,12 @@ export function handleSidebarNavigationKeyDown(input: { traversalDirection !== null ? resolveAdjacentThreadId({ threadIds: input.orderedThreadKeys, - currentThreadId: input.currentThreadKey, + // The open chat is not listed while its card is collapsed: traverse from the edge. + currentThreadId: + input.currentThreadKey !== null && + input.orderedThreadKeys.includes(input.currentThreadKey) + ? input.currentThreadKey + : null, direction: traversalDirection, }) : (() => { @@ -668,14 +676,19 @@ export const PROJECT_HEADER_ACTION_PADDING = { export type ProjectHeaderActionCount = keyof typeof PROJECT_HEADER_ACTION_PADDING; -/** Project actions, New worktree and Git Manager always show; Pull Requests and Pipelines may. */ +/** + * Project actions, New worktree and Git Manager always show; Pull Requests and Pipelines may. + * A server card adds Open terminal and Dashboard (two icons) and never shows the other two. + */ export function projectHeaderActionCount(input: { readonly showsPullRequests: boolean; readonly showsPipelines: boolean; + readonly showsServerCommands: boolean; }): ProjectHeaderActionCount { return (3 + Number(input.showsPullRequests) + - Number(input.showsPipelines)) as ProjectHeaderActionCount; + Number(input.showsPipelines) + + 2 * Number(input.showsServerCommands)) as ProjectHeaderActionCount; } export function projectHeaderButtonClassName(input: { @@ -1335,7 +1348,6 @@ interface SidebarProjectThreadListProps { hiddenThreadStatus: WorkspaceCardStatus | null; orderedProjectThreadKeys: readonly string[]; renderedThreads: readonly SidebarThreadSummary[]; - shouldShowThreadPanel: boolean; isThreadListExpanded: boolean; activeRouteThreadKey: string | null; threadJumpLabelByKey: ReadonlyMap; @@ -1638,7 +1650,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList( hiddenThreadStatus, orderedProjectThreadKeys, renderedThreads, - shouldShowThreadPanel, isThreadListExpanded, activeRouteThreadKey, threadJumpLabelByKey, @@ -1684,7 +1695,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList( const cardLookups = useWorkspaceCardLookups({ project, serverConfigs, - active: shouldShowThreadPanel, + active: projectExpanded, threads: lookupThreads, pinnedKeys, unreadKeys, @@ -1721,7 +1732,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList( onHiddenCountChange={onDiscoveryHiddenCountChange} /> ) : null} - {projectExpanded || primaryThreadActive ? ( + {projectExpanded ? ( ) : null} - {shouldShowThreadPanel && + {projectExpanded && renderedThreads.map((thread) => { const keyInfo = cardLookups.keys.get(thread)!; const threadKey = keyInfo.key; @@ -2158,89 +2169,31 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec threadSortOrder, workspaceStatuses, ]); - const pinnedCollapsedThread = useMemo(() => { - const activeThreadKey = activeRouteThreadKey ?? undefined; - if (!activeThreadKey || projectExpanded) { - return null; - } - return ( - visibleProjectThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey, - ) ?? null - ); - }, [activeRouteThreadKey, projectExpanded, visibleProjectThreads]); - // The primary row's thread was - // split out of `visibleProjectThreads`, so `pinnedCollapsedThread` (which - // only searches that array) never matched it — collapsing a project while - // routed to its own default thread hid the primary row entirely, unlike - // regular threads which peek through when collapsed+active. Tracked - // separately (not folded into `pinnedCollapsedThread` itself) because that - // value also drives which threads `SidebarProjectThreadList` renders, and - // the primary thread must stay rendered via `SidebarPrimaryRow`, not - // `SidebarThreadRow`. - const isPrimaryThreadActiveWhileCollapsed = useMemo(() => { - if (!primaryThread || projectExpanded || !activeRouteThreadKey) { - return false; - } - return ( - scopedThreadKey(scopeThreadRef(primaryThread.environmentId, primaryThread.id)) === - activeRouteThreadKey - ); - }, [activeRouteThreadKey, primaryThread, projectExpanded]); - - const { hasOverflowingThreads, hiddenThreadStatus, renderedThreads, shouldShowThreadPanel } = - useMemo(() => { - const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount; - const previewThreads = - isThreadListExpanded || !hasOverflowingThreads - ? visibleProjectThreads - : visibleProjectThreads.slice(0, sidebarThreadPreviewCount); - const visibleThreadKeys = new Set( - [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map( - (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ); - // Collapsed + routed to the primary (default) thread: `pinnedCollapsedThread` - // stays null (it only searches workspace threads, see - // `isPrimaryThreadActiveWhileCollapsed` above) and `shouldShowThreadPanel` - // is true so the primary row can peek through -- but that must NOT fall - // into the `previewThreads` branch below, or every workspace row's - // preview slice would render alongside it. Only render workspace rows - // here when actually expanded or peeking a specific pinned/active one. - const renderedThreads = pinnedCollapsedThread - ? [pinnedCollapsedThread] - : projectExpanded - ? visibleProjectThreads.filter((thread) => - visibleThreadKeys.has( - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ) - : []; - const hiddenThreads = visibleProjectThreads.filter( - (thread) => - !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), - ); - return { - hasOverflowingThreads, - hiddenThreadStatus: resolveHighestWorkspaceCardStatus( - hiddenThreads.map(workspaceStatuses.statusOf), - ), - renderedThreads, - shouldShowThreadPanel: - projectExpanded || pinnedCollapsedThread !== null || isPrimaryThreadActiveWhileCollapsed, - }; - }, [ - isPrimaryThreadActiveWhileCollapsed, - isThreadListExpanded, - pinnedCollapsedThread, - projectExpanded, - sidebarThreadPreviewCount, - visibleProjectThreads, - workspaceStatuses, - ]); + // A collapsed card hides every descendant, the open chat's card included (#382). + const { hasOverflowingThreads, hiddenThreadStatus, renderedThreads } = useMemo(() => { + const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount; + const previewThreads = + isThreadListExpanded || !hasOverflowingThreads + ? visibleProjectThreads + : visibleProjectThreads.slice(0, sidebarThreadPreviewCount); + return { + hasOverflowingThreads, + hiddenThreadStatus: resolveHighestWorkspaceCardStatus( + visibleProjectThreads.slice(previewThreads.length).map(workspaceStatuses.statusOf), + ), + renderedThreads: projectExpanded ? previewThreads : EMPTY_RENDERED_THREADS, + }; + }, [ + isThreadListExpanded, + projectExpanded, + sidebarThreadPreviewCount, + visibleProjectThreads, + workspaceStatuses, + ]); const projectSelected = selectedProjectKey === project.projectKey; + // The open chat's card is hidden while collapsed, so the header marks where it is. + const holdsOpenChatWhileCollapsed = !projectExpanded && activeRouteThreadKey !== null; const handleProjectButtonClick = useCallback( (event: React.MouseEvent) => { @@ -3414,9 +3367,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec Git Manager + {environmentCard ? ( + + ) : null} {showsPullRequestsAction ? ( { if (projectAvailability.environmentId === null) { @@ -5298,56 +5267,59 @@ export default function Sidebar() { [repositoryGroupExpandedById, repositoryGroups, sortedProjects], ); const isManualProjectSorting = sidebarProjectSortOrder === "manual"; - const visibleSidebarThreadKeys = useMemo( + const pinnedSidebarThreadKeys = useSidebarWorkspaceMetaStore((state) => state.pinnedThreadKeys); + // What each expanded project card shows, in card order: the same rows the card renders, so a + // jump shortcut or thread traversal never reaches a thread that has no row. + const visibleSidebarThreads = useMemo( () => visibleProjectsInOrder.flatMap((project) => { - const projectThreads = sortThreads( - (threadsByProjectKey.get(project.projectKey) ?? []).filter( - (thread) => thread.archivedAt === null, - ), - sidebarThreadSortOrder, - ); const projectExpanded = resolveProjectExpanded( projectExpandedById, projectExpansionPreferenceKeys(project), ); - const activeThreadKey = routeThreadKey ?? undefined; - const pinnedCollapsedThread = - !projectExpanded && activeThreadKey - ? (projectThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === - activeThreadKey, - ) ?? null) - : null; - const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null; - if (!shouldShowThreadPanel) { + if (!projectExpanded) { return []; } - const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey); - const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount; - const previewThreads = - isThreadListExpanded || !hasOverflowingThreads - ? projectThreads - : projectThreads.slice(0, sidebarThreadPreviewCount); - const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads; - return renderedThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ); + const keyOf = (thread: SidebarThreadSummary) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const { primaryThread, rows } = resolveVisibleProjectThreads({ + threads: (threadsByProjectKey.get(project.projectKey) ?? []).filter( + (thread) => thread.archivedAt === null, + ), + sort: (threads) => sortThreads(threads, sidebarThreadSortOrder), + pinnedKeys: pinnedSidebarThreadKeys, + keyOf, + isListExpanded: expandedThreadListsByProject.has(project.projectKey), + previewCount: sidebarThreadPreviewCount, + }); + return [ + ...(primaryThread ? [{ key: keyOf(primaryThread), row: false }] : []), + ...rows.map((thread) => ({ key: keyOf(thread), row: true })), + ]; }), [ sidebarThreadSortOrder, sidebarThreadPreviewCount, expandedThreadListsByProject, + pinnedSidebarThreadKeys, projectExpandedById, - routeThreadKey, threadsByProjectKey, visibleProjectsInOrder, ], ); + // Traversal and prewarming cover every thread a card shows, the primary card's included. + const visibleSidebarThreadKeys = useMemo( + () => visibleSidebarThreads.map((thread) => thread.key), + [visibleSidebarThreads], + ); + // Jump labels are drawn on rows only, so only rows take a jump number. + const jumpableSidebarThreadKeys = useMemo( + () => visibleSidebarThreads.filter((thread) => thread.row).map((thread) => thread.key), + [visibleSidebarThreads], + ); const threadJumpCommandByKey = useMemo(() => { const mapping = new Map>>(); - for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) { + for (const [visibleThreadIndex, threadKey] of jumpableSidebarThreadKeys.entries()) { const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); if (!jumpCommand) { return mapping; @@ -5356,7 +5328,7 @@ export default function Sidebar() { } return mapping; - }, [visibleSidebarThreadKeys]); + }, [jumpableSidebarThreadKeys]); const threadJumpThreadKeys = useMemo( () => [...threadJumpCommandByKey.keys()], [threadJumpCommandByKey], diff --git a/apps/web/src/components/SourceControlPanel.test.tsx b/apps/web/src/components/SourceControlPanel.test.tsx index 0abe752eab..9b203a7f54 100644 --- a/apps/web/src/components/SourceControlPanel.test.tsx +++ b/apps/web/src/components/SourceControlPanel.test.tsx @@ -150,6 +150,8 @@ interface CapturedButtonProps { "aria-label"?: string; "aria-pressed"?: boolean; className?: string; + size?: string; + variant?: string; } interface CapturedMenuItemProps { @@ -1147,6 +1149,38 @@ describe("SourceControlPanel", () => { match[1]!.replaceAll("'", "'"), ); + it("is a labelled button with Stage All's size and color and a bot icon (#375)", () => { + testState.statusQuery.data = stagingStatus({ + refName: "main", + isDefaultRef: true, + defaultRefName: "main", + aheadOfDefaultCount: 0, + hasWorkingTreeChanges: true, + workingTree: { files: [UNSTAGED_FILE], insertions: 1, deletions: 0 }, + }); + const onStart = vi.fn(); + const markup = render(reviewProps(null, onStart)); + const review = reviewButton()!; + const stageAll = buttonsByText("Stage All Changes (1)")[0]!; + + expect(flattenText(review.children)).toBe("Review"); + expect(review.size).toBe("sm"); + expect(review.size).toBe(stageAll.size); + expect(review.variant).toBe(stageAll.variant); + expect(markup).toMatch(/]*lucide-bot[^>]*aria-hidden="true"/); + + review.onClick!(); + expect(onStart).toHaveBeenCalledTimes(1); + expect(testState.runStage).not.toHaveBeenCalled(); + }); + + it("stays dimmed while disabled, so it does not look like an enabled Stage All (#375)", () => { + testState.statusQuery.data = status(); + render(reviewProps()); + expect((reviewButton() as Record)["aria-disabled"]).toBe(true); + expect(reviewButton()!.className).toContain("opacity-64"); + }); + it("is absent without a review handler", () => { render(buildProps()); expect(reviewButton()).toBeUndefined(); diff --git a/apps/web/src/components/SourceControlPanel.tsx b/apps/web/src/components/SourceControlPanel.tsx index d38336dccf..82e8288571 100644 --- a/apps/web/src/components/SourceControlPanel.tsx +++ b/apps/web/src/components/SourceControlPanel.tsx @@ -23,6 +23,7 @@ import { useAtomValue } from "@effect/atom-react"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { + BotIcon, ChevronDownIcon, CloudUploadIcon, DownloadIcon, @@ -30,7 +31,6 @@ import { GitCommitIcon, ListChecksIcon, ListIcon, - ScanSearchIcon, SparklesIcon, SquareIcon, Undo2Icon, @@ -1142,7 +1142,8 @@ export default function SourceControlPanel({
{status?.refName ?? "Source Control"} {vsBaseLabel ? ( - {vsBaseLabel} + // Truncates before it can push Review out of a narrow panel. + {vsBaseLabel} ) : null} {status?.pr?.state === "open" ? ( + + {reasonShown ? ( + + {disabledReason} + + ) : null} + + ); +} diff --git a/apps/web/src/components/gitManager/GitManagerInProgressStrip.test.tsx b/apps/web/src/components/gitManager/GitManagerInProgressStrip.test.tsx index 633b72ed1b..bbceb5dff7 100644 --- a/apps/web/src/components/gitManager/GitManagerInProgressStrip.test.tsx +++ b/apps/web/src/components/gitManager/GitManagerInProgressStrip.test.tsx @@ -57,10 +57,10 @@ describe("GitManagerInProgressStrip", () => { ), ); - expect(buttonWithText("Commit merge")).toMatchObject({ - disabled: true, - title: "Resolve and stage every conflicted file first.", - }); + expect(buttonWithText("Commit merge").disabled).toBe(true); + expect(buttonWithText("Commit merge").parentElement?.title).toBe( + "Resolve and stage every conflicted file first.", + ); expect(buttonWithText("Abort").disabled).toBe(false); expect(container.textContent).toContain("Resolve and stage every conflicted file first."); }); @@ -79,13 +79,9 @@ describe("GitManagerInProgressStrip", () => { ), ); - expect(buttonWithText("Continue")).toMatchObject({ - disabled: true, - title: "A merge is running.", - }); - expect(buttonWithText("Abort")).toMatchObject({ - disabled: true, - title: "A merge is running.", - }); + for (const label of ["Continue", "Abort"]) { + expect(buttonWithText(label).disabled).toBe(true); + expect(buttonWithText(label).parentElement?.title).toBe("A merge is running."); + } }); }); diff --git a/apps/web/src/components/gitManager/GitManagerInProgressStrip.tsx b/apps/web/src/components/gitManager/GitManagerInProgressStrip.tsx index 60e5d0a701..616d0c6c6f 100644 --- a/apps/web/src/components/gitManager/GitManagerInProgressStrip.tsx +++ b/apps/web/src/components/gitManager/GitManagerInProgressStrip.tsx @@ -3,6 +3,7 @@ import { AlertTriangleIcon } from "lucide-react"; import { memo, useCallback, useState } from "react"; import { Button } from "~/components/ui/button"; +import { GitManagerDisabledReasonButton } from "./GitManagerDisabledReasonButton"; import { Dialog, DialogDescription, @@ -42,8 +43,6 @@ export const GitManagerInProgressStrip = memo(function GitManagerInProgressStrip const presentation = describeInProgressOperation(operation); const continueReason = disabledReason ?? continueDisabledReason; const blockedReason = continueReason ?? resolveInProgressBlockedReason(blocked); - const disabledReasonId = - continueReason === null ? undefined : "git-manager-in-progress-disabled-reason"; const requestAbort = useCallback(() => setAbortConfirmationOpen(true), []); const confirmAbort = useCallback(() => { setAbortConfirmationOpen(false); @@ -68,31 +67,25 @@ export const GitManagerInProgressStrip = memo(function GitManagerInProgressStrip )} - - +
{blockedReason === null ? null : ( -

- {blockedReason} -

+

{blockedReason}

)} diff --git a/apps/web/src/components/gitManager/GitManagerPanel.historyChangesVisibility.test.tsx b/apps/web/src/components/gitManager/GitManagerPanel.historyChangesVisibility.test.tsx index 0cd897718e..a203d31b43 100644 --- a/apps/web/src/components/gitManager/GitManagerPanel.historyChangesVisibility.test.tsx +++ b/apps/web/src/components/gitManager/GitManagerPanel.historyChangesVisibility.test.tsx @@ -348,10 +348,10 @@ it("returns from real History PNG selection to exactly one visible working-tree expect(retainedImage).not.toBeNull(); // The list and the diff share one split under the filters; the commit form sits in its own // pane below it. Both panes resize, so the list is not a direct child of the section. - const split = list.parentElement!.parentElement!; const diffSlot = retainedImage.parentElement!; + const split = diffSlot.parentElement!; expect(split.parentElement).toBe(changes); - expect(diffSlot.parentElement).toBe(split); + expect(split.contains(list)).toBe(true); expect(retainedCommit.parentElement!.parentElement).toBe(changes); expect( retainedCommit.querySelector('input[name="git-manager-summary"]')?.value, diff --git a/apps/web/src/components/gitManager/GitManagerPanel.repositoryUnavailable.test.tsx b/apps/web/src/components/gitManager/GitManagerPanel.repositoryUnavailable.test.tsx index 6ecf951a74..0ef1089551 100644 --- a/apps/web/src/components/gitManager/GitManagerPanel.repositoryUnavailable.test.tsx +++ b/apps/web/src/components/gitManager/GitManagerPanel.repositoryUnavailable.test.tsx @@ -291,10 +291,19 @@ const UNREADABLE_MESSAGE = const HEDGED_MESSAGE = "Git can't read this folder as a repository. Run git init to create one, or check its .git folder if it already is one."; +const NATIVE_BUTTONS: ReadonlySet = new Set(["Choose branch", "Sync unavailable"]); + function expectDisabled(label: string, message: string): void { const action = button(label); expect(action.disabled).toBe(true); - expect(action.title).toBe(message); + if (NATIVE_BUTTONS.has(label)) { + // Plain ` - {pullRequestsDisabledReason === null ? null : ( - - {pullRequestsDisabledReason} - - )} - - {stashMergeDisabledReason === null ? null : ( - - {stashMergeDisabledReason} - - )} - - {mergeDisabledReason === null ? null : ( - - {mergeDisabledReason} - - )} - - {rebaseDisabledReason === null ? null : ( - - {rebaseDisabledReason} - - )} + {historyActionMessage === null ? null : (

); @@ -1424,7 +1455,12 @@ export const GitManagerPanel = memo(function GitManagerPanel({ projectRef }: Git ); if (availability.kind !== "ready") { - return ; + // Pending is a transient wait, not a failure: say what is awaited without the error card. + return availability.kind === "pending" ? ( + + ) : ( + + ); } if (project === null || mainCheckoutCwd === null || activeCwd === null) { return ; @@ -1462,7 +1498,7 @@ export const GitManagerPanel = memo(function GitManagerPanel({ projectRef }: Git signalGeneration={signalGeneration} signalPending={signalPending} stashMergeDisabledReason={effectiveDisabledReasons.stashMerge} - mergeIntoAvailable={capabilityDisabledReasons.mergeInto === null} + mergeIntoDisabledReason={capabilityDisabledReasons.mergeInto} tagDisabledReason={effectiveDisabledReasons.tag} tabTransitionBaselineRef={tabTransitionBaselineRef} onTabChange={handleTabChange} diff --git a/apps/web/src/components/gitManager/GitManagerToolbar.tsx b/apps/web/src/components/gitManager/GitManagerToolbar.tsx index c9c3607d3c..0aced608a2 100644 --- a/apps/web/src/components/gitManager/GitManagerToolbar.tsx +++ b/apps/web/src/components/gitManager/GitManagerToolbar.tsx @@ -28,7 +28,7 @@ import { type GitManagerBranchDialogSubmission, } from "./dialogs/GitManagerBranchDialogs"; import { GitManagerSwitchWithChangesDialog } from "./dialogs/GitManagerSwitchWithChangesDialog"; -import { resolveBranchCreateBase } from "./toolbar/branchCreateBase"; +import { newBranchDialog } from "./toolbar/branchCreateBase"; import { GitManagerBranchDropdown } from "./toolbar/GitManagerBranchDropdown"; import { GitManagerOperationBanner } from "./toolbar/GitManagerOperationBanner"; import { @@ -453,18 +453,7 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ }, [checkoutBranch, snapshot?.isDirty], ); - const createBranch = useCallback( - () => - setBranchDialog({ - kind: "create", - baseBranch: resolveBranchCreateBase({ - currentBranchName, - defaultBranch: snapshot?.defaultBranch ?? null, - }), - baseCommit: null, - }), - [currentBranchName, snapshot?.defaultBranch], - ); + const createBranch = useCallback(() => setBranchDialog(newBranchDialog(snapshot)), [snapshot]); const renameBranch = useCallback( (branch: GitManagerRefEntry) => setBranchDialog({ kind: "rename", branch }), [], @@ -703,17 +692,20 @@ export const GitManagerToolbar = memo(function GitManagerToolbar({ onSwitchWorktree={onSelectedWorktreeChange} />

- - + {/* The disabled trigger has pointer-events-none, so its reason sits on a wrapper. */} + + + + ({ statusError: null as string | null, statusEmission: null as AsyncResult.AsyncResult | null, refsError: null as string | null, + // A refs read runs while the last snapshot stays. + refsRefreshing: false, refsEmission: null as AsyncResult.AsyncResult | null, refreshStatusQuery: vi.fn(), revalidateStatusQuery: vi.fn(), @@ -91,6 +93,7 @@ function readActionsFor(kind: string | undefined) { function pendingFor(kind: string | undefined, data: unknown): boolean { if (kind === "status" && h.statusEmission !== null) return h.statusEmission.waiting; if (kind === "refs" && h.refsError !== null) return false; + if (kind === "refs" && h.refsRefreshing) return true; if (kind === "commits" && h.commitsEmission !== null) return h.commitsEmission.waiting; return data === null; } @@ -192,6 +195,7 @@ vi.mock("./GitManagerChangesList", () => ({ })); import { GitManagerChangesView } from "./GitManagerChangesView"; +import { expectLoadingModel } from "~/components/ui/loading-state.testing"; import { GitManagerChangeRow } from "./GitManagerChangeRow"; const projectRef = { environmentId: "environment-1", projectId: "project-1" } as never; @@ -307,6 +311,7 @@ beforeEach(() => { h.statusError = null; h.statusEmission = null; h.refsError = null; + h.refsRefreshing = false; h.refsEmission = null; h.refreshStatusQuery.mockClear(); h.revalidateStatusQuery.mockClear(); @@ -462,9 +467,21 @@ describe("GitManagerChangesView", () => { expect(container.textContent).toContain("src/manual-refresh.ts"); }); + it("keeps the changes beside a refresh label while the refs reread", async () => { + h.status = statusWith("src/kept.ts"); + await renderView(); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.refsRefreshing = true; + await renderView(); + expect(container.textContent).toContain("src/kept.ts"); + expectLoadingModel(container, ["Refreshing changes…"]); + }); + it("repopulates from the status subscription after a reconnect", async () => { await renderView(); expect(container.textContent).toContain("Connecting to changes"); + expectLoadingModel(container, ["Connecting to changes…"]); + expect(container.querySelector('[role="status"] svg.animate-spin')).not.toBeNull(); h.status = statusWith("src/before.ts"); await renderView(); diff --git a/apps/web/src/components/gitManager/changes/GitManagerChangesView.tsx b/apps/web/src/components/gitManager/changes/GitManagerChangesView.tsx index 47c730a787..40307b0dd4 100644 --- a/apps/web/src/components/gitManager/changes/GitManagerChangesView.tsx +++ b/apps/web/src/components/gitManager/changes/GitManagerChangesView.tsx @@ -29,6 +29,7 @@ import { } from "react"; import { Button } from "~/components/ui/button"; +import { LoadingState, RefreshRegion } from "~/components/ui/loading-state"; import { RetryButton, type RetryButtonProps } from "~/components/ui/retry-button"; import { Checkbox } from "~/components/ui/checkbox"; import { useOpenInPreferredEditor } from "~/editorPreferences"; @@ -72,6 +73,7 @@ import { type ChangeFilters, type ChangeRow, } from "./changesList.logic"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; export interface GitManagerChangesViewProps { readonly scope: { readonly environmentId: EnvironmentId; readonly cwd: string }; @@ -94,6 +96,7 @@ type ChangeContextAction = | "reveal" | "open-editor"; +const REFRESH_STATUS = "Refreshing changes…"; const EMPTY_PATHS: ReadonlyArray = Object.freeze([]); const EMPTY_EDITORS: ReadonlyArray = Object.freeze([]); const EMPTY_FILES: VcsStatusResult["workingTree"]["files"] = Object.freeze([]); @@ -720,19 +723,15 @@ export const GitManagerChangesView = memo(function GitManagerChangesView({ : errorPanel("Could not load changes", message, retry); } if (statusQuery.data === null || refsQuery.data === null || refsRecovering) { - return ( -
- Connecting to changes… -
- ); + return ; } const filterActive = rows.filterActive; const noLocalChanges = rows.totalCount === 0; const mainCheckoutCwd = project?.workspaceRoot ?? cwd; + // Status is a stream that waits between emissions; only the refs read is a reread. It + // names the changed files; the diff pane's own read keeps its own status. + const refreshing = refsQuery.isPending; return (
@@ -770,21 +769,15 @@ export const GitManagerChangesView = memo(function GitManagerChangesView({ cwd={cwd} mainCheckoutCwd={mainCheckoutCwd} /> - - {commitOperationsAvailable ? null : ( - - {commitDisabledReason} - - )} +
{FILTER_NAMES.map((name) => ( @@ -802,16 +795,24 @@ export const GitManagerChangesView = memo(function GitManagerChangesView({ ))}
{noLocalChanges ? ( -
+

No local changes

-
+ ) : rows.length === 0 && filterActive ? ( -
+

No changed files match these filters.

-
+ ) : ( <>
@@ -856,14 +857,20 @@ export const GitManagerChangesView = memo(function GitManagerChangesView({ ) } list={ - + + + } onKeyDown={handleNavigationKeyDown} /> diff --git a/apps/web/src/components/gitManager/changes/GitManagerCommitBox.tsx b/apps/web/src/components/gitManager/changes/GitManagerCommitBox.tsx index 06e02f6be9..5043d952e4 100644 --- a/apps/web/src/components/gitManager/changes/GitManagerCommitBox.tsx +++ b/apps/web/src/components/gitManager/changes/GitManagerCommitBox.tsx @@ -29,6 +29,7 @@ import { isSummaryOverIdealLength, } from "./commitBox.logic"; import { GitManagerUndoCommitStrip } from "./GitManagerUndoCommitStrip"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; export interface GitManagerCommitSubmission { readonly message: string; @@ -111,7 +112,6 @@ export const GitManagerCommitBox = memo(function GitManagerCommitBox({ isAmending, isBusy: busy, }); - const disabledDescriptionId = disabledReason === null ? undefined : "git-manager-commit-disabled"; const handleSummaryChange = useCallback( (event: ChangeEvent) => { @@ -348,20 +348,18 @@ export const GitManagerCommitBox = memo(function GitManagerCommitBox({
- + {disabledReason === null ? null : ( -

- {disabledReason} -

+

{disabledReason}

)} {latestCommit === null || onUndo === undefined ? null : ( diff --git a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx index 91c56b3525..83b5667319 100644 --- a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx +++ b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.test.tsx @@ -50,7 +50,11 @@ const LOCAL_REFS = [branch("main", { current: true }), branch("feature")]; const REMOTE_REFS = [branch("origin/main"), branch("origin/release")]; async function renderCreate( - base: { readonly baseBranch: string | null; readonly baseCommit: string | null }, + base: { + readonly baseBranch: string | null; + readonly baseCommit: string | null; + readonly unborn?: boolean; + }, refs: ReadonlyArray = LOCAL_REFS, ) { const submissions: GitManagerBranchDialogSubmission[] = []; @@ -169,7 +173,7 @@ describe("GitManagerBranchDialogs", () => { expect(document.body.textContent).toContain(message); expect(buttonWithText("Rename").disabled).toBe(true); - expect(buttonWithText("Rename").title).toBe(message); + expect(buttonWithText("Rename").parentElement?.title).toBe(message); }); it("creates and checks out from the active branch by default", async () => { @@ -244,6 +248,46 @@ describe("GitManagerBranchDialogs", () => { ]); }); + it("on an unborn HEAD, lets a branch from an existing start point skip checkout", async () => { + // An orphan checkout beside a committed `main`: Git creates from `main` without switching. + const submissions = await renderCreate({ baseBranch: null, baseCommit: null, unborn: true }, [ + branch("main"), + ]); + await chooseSource("main"); + await toggleCheckout(); + expect(checkoutBox().checked).toBe(false); + await typeName("topic"); + await act(async () => buttonWithText("Create branch").click()); + + expect(submissions).toEqual([ + { kind: "create", name: "topic", startPoint: "refs/heads/main", checkout: false }, + ]); + }); + + it("before the first commit, switches to the new branch from the current HEAD", async () => { + // Git can only start a branch on an unborn HEAD by switching to it. + const submissions = await renderCreate( + { baseBranch: null, baseCommit: null, unborn: true }, + [], + ); + + expect(sourceInput().value).toBe("Current HEAD"); + expect(checkoutBox().checked).toBe(true); + expect( + checkoutBox().getAttribute("aria-disabled") ?? + String(checkoutBox().hasAttribute("data-disabled")), + ).toBe("true"); + expect(document.body.textContent).toContain("No commit exists yet"); + await toggleCheckout(); + expect(checkoutBox().checked).toBe(true); + await typeName("topic"); + await act(async () => buttonWithText("Create and check out").click()); + + expect(submissions).toEqual([ + { kind: "create", name: "topic", startPoint: null, checkout: true }, + ]); + }); + it("requires explicit confirmation before deleting a branch", async () => { const submissions: GitManagerBranchDialogSubmission[] = []; await act(async () => diff --git a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx index bd721216de..2e0cb0f25e 100644 --- a/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx +++ b/apps/web/src/components/gitManager/dialogs/GitManagerBranchDialogs.tsx @@ -23,6 +23,7 @@ import { DialogTitle, } from "~/components/ui/dialog"; import { Input } from "~/components/ui/input"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; export type GitManagerBranchDialog = | { @@ -31,6 +32,8 @@ export type GitManagerBranchDialog = readonly baseBranch: string | null; /** A commit chosen in History; it becomes the default source. */ readonly baseCommit: string | null; + /** HEAD names a branch with no commit yet, so Git can create a branch only by switching. */ + readonly unborn?: boolean; } | { readonly kind: "rename"; readonly branch: GitManagerRefEntry } | { @@ -127,6 +130,7 @@ function initialBranchSource(baseBranch: string | null, baseCommit: string | nul function CreateBranchDialog({ baseBranch, baseCommit, + unborn, refs, remoteRefs, busy, @@ -137,11 +141,15 @@ function CreateBranchDialog({ }: SharedDialogProps & { readonly baseBranch: string | null; readonly baseCommit: string | null; + readonly unborn: boolean; readonly remoteRefs: ReadonlyArray; }) { const [name, setName] = useState(""); const [source, setSource] = useState(() => initialBranchSource(baseBranch, baseCommit)); - const [checkout, setCheckout] = useState(true); + const [checkoutChoice, setCheckout] = useState(true); + // Only the unborn HEAD itself has no ref to start from, so only it must be switched to. + const checkoutForced = unborn && source.startPoint === null; + const checkout = checkoutForced || checkoutChoice; const [debouncedRulesMessage, setDebouncedRulesMessage] = useState(null); const checkoutHintId = useId(); const trimmedName = name.trim(); @@ -257,17 +265,19 @@ function CreateBranchDialog({ aria-describedby={checkoutHintId} checked={checkout} data-testid="git-manager-create-branch-checkout" - disabled={busy} + disabled={busy || checkoutForced} onCheckedChange={setCheckout} /> Check out after creating

- {checkout - ? "Switches this checkout to the new branch." - : currentBranch === null - ? "You stay on the current commit." - : `You stay on ${currentBranch}.`} + {checkoutForced + ? "No commit exists yet, so the new branch can only start by switching to it." + : checkout + ? "Switches this checkout to the new branch." + : currentBranch === null + ? "You stay on the current commit." + : `You stay on ${currentBranch}.`}

@@ -276,14 +286,15 @@ function CreateBranchDialog({ - +
@@ -355,14 +366,16 @@ function RenameBranchDialog({ - + @@ -385,8 +398,6 @@ function DeleteBranchDialog({ const [deleteRemote, setDeleteRemote] = useState(false); const serverBlock = branch.blocked.find((reason) => reason.operation === "branch-delete") ?? null; const disabledReason = capabilityDisabledReason ?? serverBlock?.message ?? null; - const descriptionId = - disabledReason === null ? undefined : "git-manager-delete-branch-disabled-reason"; const submit = useCallback(() => { if (!confirmed || disabledReason !== null) return; void onSubmit({ kind: "delete", name: branch.name, deleteRemote }); @@ -403,11 +414,7 @@ function DeleteBranchDialog({
- {disabledReason === null ? null : ( -

- {disabledReason} -

- )} + {disabledReason === null ? null :

{disabledReason}

}
- - {leaveChangesDisabledReason === null ? null : ( - - {leaveChangesDisabledReason} - - )} - - {branchDisabledReason === null ? null : ( - - {branchDisabledReason} - - )} + diff --git a/apps/web/src/components/gitManager/gitManagerAvailability.ts b/apps/web/src/components/gitManager/gitManagerAvailability.ts index 76fa7feddb..9d9bef42bc 100644 --- a/apps/web/src/components/gitManager/gitManagerAvailability.ts +++ b/apps/web/src/components/gitManager/gitManagerAvailability.ts @@ -18,7 +18,7 @@ export const GIT_MANAGER_TAG_DISABLED_REASON = export const GIT_MANAGER_PULL_REQUESTS_DISABLED_REASON = "This environment does not support Git Manager pull request operations."; export const GIT_MANAGER_MERGE_INTO_DISABLED_REASON = - "This environment does not support merging into a branch that is not checked out."; + "Merging into a branch that is not checked out needs Git 2.38 or later and a current server on this environment."; export const GIT_MANAGER_LIVE_SIGNAL_DISABLED_REASON = "This environment does not support Git Manager live updates. Use Refresh to load new repository data."; diff --git a/apps/web/src/components/gitManager/history/GitManagerCommitDetail.test.tsx b/apps/web/src/components/gitManager/history/GitManagerCommitDetail.test.tsx index 12e7af9fcc..0951c9b335 100644 --- a/apps/web/src/components/gitManager/history/GitManagerCommitDetail.test.tsx +++ b/apps/web/src/components/gitManager/history/GitManagerCommitDetail.test.tsx @@ -157,4 +157,38 @@ describe("GitManagerCommitDetail", () => { expect(container.querySelectorAll("img")).toHaveLength(2); expect(fetchSpy).not.toHaveBeenCalled(); }); + + it("says how many changed files the server left out of a huge commit", async () => { + await act(async () => + root?.render( + undefined} + />, + ), + ); + + expect(container.textContent).toContain("4,321 more files not listed"); + // The note sits outside the listbox, so it is not read as a file. + expect(container.querySelector('[role="listbox"]')?.textContent).not.toContain("more files"); + }); + + it("shows no omitted-files note for a commit that lists every file", async () => { + await act(async () => + root?.render( + undefined} + />, + ), + ); + + expect(container.textContent).not.toContain("more files"); + }); }); diff --git a/apps/web/src/components/gitManager/history/GitManagerCommitDetail.tsx b/apps/web/src/components/gitManager/history/GitManagerCommitDetail.tsx index 6ce2d0e366..68499c1608 100644 --- a/apps/web/src/components/gitManager/history/GitManagerCommitDetail.tsx +++ b/apps/web/src/components/gitManager/history/GitManagerCommitDetail.tsx @@ -205,7 +205,7 @@ const ChangedFileList = memo(function ChangedFileList({
@@ -358,17 +358,22 @@ export const GitManagerCommitDetail = memo(function GitManagerCommitDetail({
- {commit.changedFiles.length > 0 ? ( - - ) : ( -
+
+ {commit.changedFiles.length > 0 ? ( + + ) : commit.changedFilesOmitted ? null : (

No changed files.

-
- )} + )} + {commit.changedFilesOmitted ? ( +

+ {commit.changedFilesOmitted.toLocaleString()} more files not listed +

+ ) : null} +
{selectedFilePath === null ? ( diff --git a/apps/web/src/components/gitManager/history/GitManagerHistoryView.test.tsx b/apps/web/src/components/gitManager/history/GitManagerHistoryView.test.tsx index 63b15c3c3a..9f0cfa0d5a 100644 --- a/apps/web/src/components/gitManager/history/GitManagerHistoryView.test.tsx +++ b/apps/web/src/components/gitManager/history/GitManagerHistoryView.test.tsx @@ -41,6 +41,7 @@ const h = vi.hoisted(() => ({ retainedInputs: [] as unknown[], firstPageInputs: [] as Array<{ input: { refreshCacheKey: string } }>, firstPageWaiting: false, + firstPagePending: false, firstPageError: null as string | null, retainedError: null as string | null, retainedWaiting: false, @@ -51,6 +52,7 @@ const h = vi.hoisted(() => ({ revalidateFirstPage: vi.fn(), scrollNode: null as HTMLElement | null, nextPageRequests: [] as number[], + nextPageFitFlags: [] as Array, nextPageResult: (_request: NextPageRequest): NextPageResult => PENDING_NEXT_PAGE, retryNextPage: vi.fn(), })); @@ -86,9 +88,10 @@ vi.mock("../../../localApi", () => ({ vi.mock("../../../state/gitManager", () => ({ gitManagerEnvironment: { - getCommits: vi.fn((request: { input: { offset: number } }) => { + getCommits: vi.fn((request: { input: { offset: number; fitFirstCommit?: boolean } }) => { const offset = request.input.offset; h.nextPageRequests.push(offset); + h.nextPageFitFlags.push(request.input.fitFirstCommit); const attempt = h.nextPageRequests.filter((requested) => requested === offset).length; return { kind: "next", offset, attempt }; }), @@ -134,7 +137,12 @@ vi.mock("../../../state/query", () => ({ : atom?.kind === "commits" ? h.firstPageError : (next?.error ?? null), - isPending: false, + isPending: + atom?.kind === "commits" + ? h.firstPagePending + : atom?.kind === "retained" + ? h.retainedWaiting + : false, refresh: atom?.kind === "commits" ? h.refreshCommits @@ -164,6 +172,7 @@ vi.mock("../rewrite/gitManagerCommitDrag", () => ({ import { GitManagerCommitList } from "./GitManagerCommitList"; import { GitManagerHistoryView } from "./GitManagerHistoryView"; +import { expectLoadingModel } from "../../ui/loading-state.testing"; let container: HTMLDivElement; let root: Root | null; @@ -196,6 +205,7 @@ beforeEach(() => { h.retainedInputs.length = 0; h.firstPageInputs.length = 0; h.firstPageWaiting = false; + h.firstPagePending = false; h.firstPageError = null; h.retainedError = null; h.retainedWaiting = false; @@ -205,6 +215,7 @@ beforeEach(() => { h.refreshCommits.mockReset(); h.revalidateFirstPage.mockReset(); h.nextPageRequests.length = 0; + h.nextPageFitFlags.length = 0; h.nextPageResult = () => PENDING_NEXT_PAGE; h.retryNextPage.mockReset(); container = document.createElement("div"); @@ -801,6 +812,39 @@ describe("GitManagerHistoryView repository generation tracking", () => { expect(firstPageReads()).toHaveLength(2); }); + it("labels the first load, then keeps the commits beside a refresh label", async () => { + h.firstPagePending = true; + await renderHistory(null, null, true); + expectLoadingModel(container, ["Loading commit history…"]); + h.commitPage = page(4, [commit(50)]); + h.firstPagePending = false; + await renderHistory(4, 1); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.firstPagePending = true; + await act(async () => + container.querySelector('[aria-label="Refresh history"]')?.click(), + ); + expect(h.refreshCommits).toHaveBeenCalledOnce(); + await renderHistory(4, 1); + expect(renderedShas()).toEqual([commit(50).sha]); + expectLoadingModel(container, ["Refreshing history…"]); + }); + + it("keeps a settled empty history on screen while Refresh rereads it", async () => { + h.commitPage = page(4, []); + await renderHistory(4, 1); + expect(container.textContent).toContain("This repository has no commits yet."); + h.firstPagePending = true; + await act(async () => + container.querySelector('[aria-label="Refresh history"]')?.click(), + ); + await renderHistory(4, 1); + expect(container.textContent).toContain("This repository has no commits yet."); + expect(container.querySelector('[aria-label="Refresh history"]')).not.toBeNull(); + expect(container.textContent).not.toContain("Loading commit history…"); + expectLoadingModel(container, ["Refreshing history…"]); + }); + it("waits for an in-flight first-page read instead of starting another", async () => { h.commitPage = page(4, [commit(50)]); await renderHistory(4, 1); @@ -1122,6 +1166,16 @@ describe("GitManagerHistoryView repository generation tracking", () => { expect(retryButton()).toBeUndefined(); }); + it("keeps the refresh line while the retained pages reread after the first page settled", async () => { + await loadWithRetainedBatch(); + h.retainedWaiting = true; + await renderHistory(2, 2); + expectLoadingModel(container, ["Refreshing history…"]); + h.retainedWaiting = false; + await renderHistory(2, 2); + expect(container.querySelector('[role="status"]')).toBeNull(); + }); + it("ends a cause without final punctuation before the banner's next sentence", async () => { h.commitPage = page(1, [commit(80)]); await renderHistory(1, 1); @@ -1301,6 +1355,14 @@ describe("GitManagerHistoryView paging", () => { ); expect(h.refreshCommits).toHaveBeenCalledOnce(); + // The read is still out: the loaded pages and their cursors stay until it succeeds. + h.firstPagePending = true; + await renderPagedHistory(); + expect(container.textContent).toContain("The next page could not load."); + expect(loadedCursors()).toEqual([0, 3]); + h.firstPagePending = false; + h.commitPage = historyPage([commit(1), commit(2), commit(3)], 3); + await renderPagedHistory(); expect(container.textContent).not.toContain("The next page could not load."); expect(container.textContent).toContain("3 commits loaded"); expect(h.nextPageRequests).toEqual([3]); @@ -1320,6 +1382,8 @@ describe("GitManagerHistoryView paging", () => { await renderPagedHistory(); expect(h.nextPageRequests).toEqual([3, 6]); + // The commit detail shows changedFilesOmitted, so every page asks for a fitted first commit. + expect(h.nextPageFitFlags).toEqual([true, true]); expect(container.textContent).toContain("7 commits loaded"); expect(container.textContent).not.toContain("Loading more commits…"); expect(loadedCursors()).toEqual([0, 3, 6]); diff --git a/apps/web/src/components/gitManager/history/GitManagerHistoryView.tsx b/apps/web/src/components/gitManager/history/GitManagerHistoryView.tsx index e9d5529212..997a2ce443 100644 --- a/apps/web/src/components/gitManager/history/GitManagerHistoryView.tsx +++ b/apps/web/src/components/gitManager/history/GitManagerHistoryView.tsx @@ -37,8 +37,12 @@ import { GitManagerCommitDetail } from "./GitManagerCommitDetail"; import { GitManagerCommitList } from "./GitManagerCommitList"; import { Button } from "../../ui/button"; import { RetryButton } from "../../ui/retry-button"; +import { LoadingState, RefreshRegion } from "../../ui/loading-state"; +import { Skeleton } from "../../ui/skeleton"; +import { cn } from "../../../lib/utils"; const HISTORY_PAGE_SIZE = 100; +const REFRESH_STATUS = "Refreshing history…"; const COMMIT_LOOKUP_MAX_ENTRIES = 1_000; const COMMIT_LOOKUP_MAX_MEMORY_BYTES = 32 * 1024 * 1024; const EMPTY_COMMITS: ReadonlyArray = Object.freeze([]); @@ -372,6 +376,8 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ cwd, offset: pageLoadOffset, limit: HISTORY_PAGE_SIZE, + // The commit detail shows changedFilesOmitted, so a huge first commit may be cut. + fitFirstCommit: true, ...(pinnedTips.length > 0 ? { pinnedTips } : {}), }, }); @@ -839,7 +845,7 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ if (current.exhausted || current.nextOffset === null) return; setLoadingOffset(current.nextOffset); }, [loadMoreError, pageLoadOffset, retryNextPage]); - const handleRefresh = useCallback(() => { + const resetForRefresh = useCallback(() => { commitLookup.clear(); const reset = emptyHistoryPages(); pagesRef.current = reset; @@ -858,10 +864,8 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ setLoadedPageCursors(currentProjectRef, []); setLoadedPageCount(currentProjectRef, 0); setRefreshEpoch((epoch) => epoch + 1); - refreshFirstPage(); }, [ commitLookup, - refreshFirstPage, projectEnvironmentId, projectId, setLoadedPageCount, @@ -870,12 +874,30 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ setSelectedCommit, setSelectedFile, ]); + // A manual Refresh keeps the loaded commits, selection and scroll until its read + // succeeds; a failed read leaves them, and the reset waits for the next success. + const refreshFromRef = useRef<{ readonly page: unknown } | null>(null); + const handleRefresh = useCallback(() => { + refreshFromRef.current = { page: firstPage }; + refreshFirstPage(); + }, [firstPage, refreshFirstPage]); + useEffect(() => { + const from = refreshFromRef.current; + if (from === null || firstPageQuery.isPending || firstPageQuery.error !== null) return; + if (firstPage === from.page) return; + refreshFromRef.current = null; + resetForRefresh(); + }, [firstPage, firstPageQuery.error, firstPageQuery.isPending, resetForRefresh]); - if ((firstPageAtom === null || firstPageQuery.isPending) && pages.commits.length === 0) { + // A settled empty history is a result, not a first load: Refresh keeps it on screen. + const firstLoad = pages.commits.length === 0 && pages.processedFirstPage === null; + if ((firstPageAtom === null || firstPageQuery.isPending) && firstLoad) { return ( -

- Loading commit history… -

+ + + + + ); } if (firstPageQuery.error !== null && pages.commits.length === 0) { @@ -889,6 +911,8 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ ); } + // The retained pages are reread too: the line stays until both reads settle. + const rereading = firstPageQuery.isPending || retainedQuery.isPending; return (
@@ -904,7 +928,10 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({ className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring" onClick={handleRefresh} > -
{pages.degradedToAllPaging ? ( @@ -945,21 +972,32 @@ export const GitManagerHistoryView = memo(function GitManagerHistoryView({

)} {pages.commits.length === 0 ? ( -

This repository has no commits yet.

+ +

This repository has no commits yet.

+
) : (
- + {/* The commit list is what the reread replaces; the detail pane has its own read. */} +
+ + + +
{selectedCommit === null ? (

Select a commit to inspect it.

) : ( diff --git a/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.test.tsx b/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.test.tsx index 5428914e63..abb841b1cc 100644 --- a/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.test.tsx +++ b/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.test.tsx @@ -192,7 +192,9 @@ describe("GitManagerMergeDialog", () => { const confirm = buttonWithText("Merge"); expect(confirm.disabled).toBe(true); - expect(confirm.title).toBe("Nothing to merge: `feature` has no commits that `main` lacks."); + expect(confirm.parentElement?.title).toBe( + "Nothing to merge: `feature` has no commits that `main` lacks.", + ); expect(container.textContent).toContain("Nothing to merge"); }); @@ -206,8 +208,9 @@ describe("GitManagerMergeDialog", () => { const confirm = buttonWithText("Merge"); expect(confirm.disabled).toBe(true); - expect(confirm.title).toBe(message); - expect(confirm.getAttribute("aria-describedby")).toBe("git-manager-merge-disabled-reason"); + expect(confirm.parentElement?.title).toBe(message); + const describedBy = confirm.getAttribute("aria-describedby"); + expect(document.getElementById(describedBy ?? "")?.textContent).toBe(message); expect(container.textContent).toContain(message); }); @@ -216,7 +219,8 @@ describe("GitManagerMergeDialog", () => { await renderDialog([branch("main", true), branch("feature")], vi.fn(), reason); expect(h.previewMerge).not.toHaveBeenCalled(); - expect(buttonWithText("Merge")).toMatchObject({ disabled: true, title: reason }); + expect(buttonWithText("Merge").disabled).toBe(true); + expect(buttonWithText("Merge").parentElement?.title).toBe(reason); expect(container.textContent).toContain(reason); expect(buttonWithText("Cancel").disabled).toBe(false); expect(container.textContent).toContain("feature"); @@ -235,7 +239,8 @@ describe("GitManagerMergeDialog", () => { expect(h.previewMerge).toHaveBeenLastCalledWith( expect.objectContaining({ input: { cwd: "/repo", source: "refs/remotes/origin/topic" } }), ); - expect(buttonWithText("Merge")).toMatchObject({ disabled: true, title: message }); + expect(buttonWithText("Merge").disabled).toBe(true); + expect(buttonWithText("Merge").parentElement?.title).toBe(message); }); it("merges the checked-out branch into another branch with merge-into", async () => { @@ -264,6 +269,77 @@ describe("GitManagerMergeDialog", () => { ); }); + it("fixes the source to the selected branch and waits for an Into choice", async () => { + await renderDialog([branch("main", true), branch("release")], vi.fn(), null, [], { + mergeIntoAvailable: true, + sourceBranch: "main", + }); + expect(container.textContent).toContain("Source: main"); + expect(container.querySelector('[aria-label="Source branches"]')).toBeNull(); + expect(buttonWithText("Merge").disabled).toBe(true); + expect(buttonWithText("Merge").parentElement?.title).toBe("Choose a branch to merge into."); + expect(h.previewMerge).not.toHaveBeenCalled(); + }); + + it("offers every other branch as Into and merges the fixed source into the choice", async () => { + h.preview = { ...cleanPreview, source: "refs/heads/main", current: "release" }; + await renderDialog([branch("main", true), branch("release")], vi.fn(), null, [], { + mergeIntoAvailable: true, + sourceBranch: "main", + }); + await act(async () => { + targetInput().focus(); + targetInput() + .closest('[data-slot="input-control"]') + ?.parentElement?.querySelector('[data-slot="combobox-trigger"]') + ?.click(); + }); + const options = [...document.querySelectorAll('[role="option"]')].map((o) => o.textContent); + expect(options).toEqual(["release"]); + await chooseTarget("release"); + await act(async () => buttonWithText("Merge").click()); + expect(h.runOperation).toHaveBeenLastCalledWith( + expect.anything(), + { + environmentId: "env-a", + input: { + _tag: "merge-into", + cwd: "/repo", + projectId: "project-a", + source: "refs/heads/main", + target: "release", + }, + }, + expect.any(Function), + ); + }); + + it("shows a target-neutral title and no Squash until a target is chosen from a fixed source", async () => { + await renderDialog([branch("main", true), branch("release")], vi.fn(), null, [], { + mergeIntoAvailable: true, + sourceBranch: "main", + }); + expect(container.querySelector("h2")?.textContent).toBe("Merge main into another branch"); + expect(buttonWithText("Squash merge", { optional: true })).toBeNull(); + }); + + it("never falls back to an ordinary merge when the chosen target becomes checked out", async () => { + h.preview = { ...cleanPreview, source: "refs/heads/main", current: "release" }; + const extra = { mergeIntoAvailable: true, sourceBranch: "main" }; + await renderDialog([branch("main", true), branch("release")], vi.fn(), null, [], extra); + await chooseTarget("release"); + await renderDialog([branch("main"), branch("release", true)], vi.fn(), null, [], extra); + const merge = buttonWithText("Merge"); + expect(merge.disabled).toBe(true); + // The reason sits on a wrapper that still receives hover; the disabled button ignores the pointer. + expect(merge.title).toBe(""); + expect(merge.parentElement?.title).toBe( + "release is now checked out. Use Merge… to merge into the checked-out branch.", + ); + await act(async () => merge.click()); + expect(h.runOperation).not.toHaveBeenCalled(); + }); + it("keeps Merge disabled until the preview matches the chosen target", async () => { h.preview = { ...cleanPreview, current: "main" }; await renderDialog( @@ -457,10 +533,10 @@ describe("GitManagerMergeDialog", () => { h.preview = null; h.error = "The current HEAD could not be resolved for merge preview."; await renderDialog([branch("main", true), branch("feature")]); - expect(buttonWithText("Merge")).toMatchObject({ - disabled: true, - title: "The current HEAD could not be resolved for merge preview.", - }); + expect(buttonWithText("Merge").disabled).toBe(true); + expect(buttonWithText("Merge").parentElement?.title).toBe( + "The current HEAD could not be resolved for merge preview.", + ); }); it("closes on a conflicted current-branch merge so the panel strip shows", async () => { diff --git a/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.tsx b/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.tsx index 0aab7b31ff..6a02d8c2a1 100644 --- a/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.tsx +++ b/apps/web/src/components/gitManager/merge/GitManagerMergeDialog.tsx @@ -21,6 +21,7 @@ import { } from "react"; import { Button } from "~/components/ui/button"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; import { Combobox, ComboboxEmpty, @@ -91,6 +92,8 @@ export interface GitManagerMergeDialogProps { readonly mergeIntoAvailable?: boolean; /** "current-branch" merges only into the checked-out branch and hides the Into picker. */ readonly targetMode?: "any-target" | "current-branch"; + /** Fixes the source to this local branch; the person only picks the Into branch. */ + readonly sourceBranch?: string | null; /** Remotes the Fetch button refreshes; no Fetch button when empty. */ readonly remotes?: ReadonlyArray; /** Why the owner's refs failed to load; shown with Retry (`onRefsStale`) when no source is listed. */ @@ -138,6 +141,7 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ disabledReason: capabilityDisabledReason = null, mergeIntoAvailable = false, targetMode = "any-target", + sourceBranch = null, remotes = NO_REMOTES, refsError = null, onOpenChange, @@ -172,10 +176,18 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ // `entry`, not `ref`: the compiler's refs lint would read `ref.current` as a React ref. const currentName = useMemo(() => refs.find((entry) => entry.current)?.name ?? null, [refs]); - const targetNames = useMemo(() => refs.map((ref) => ref.name), [refs]); + const targetNames = useMemo( + () => refs.map((ref) => ref.name).filter((name) => name !== sourceBranch), + [refs, sourceBranch], + ); const showTargetPicker = mergeIntoAvailable && targetMode !== "current-branch"; - const target = (showTargetPicker ? targetName : null) ?? currentName; - const intoOtherBranch = showTargetPicker && target !== null && target !== currentName; + // A fixed source never defaults Into to the checked-out branch: that is the source itself. + const target = + (showTargetPicker ? targetName : null) ?? (sourceBranch === null ? currentName : null); + // A fixed source always merges into the chosen branch, even if that branch becomes the + // checked-out one after the choice; confirmation is then blocked instead. + const intoOtherBranch = + showTargetPicker && target !== null && (sourceBranch !== null || target !== currentName); const deferredFilter = useDeferredValue(filter); const grouped = useMemo( @@ -186,7 +198,10 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ (): ReadonlyArray => // The target cannot be its own source; the checked-out branch is a source for // another target. - [...grouped.default, ...grouped.recent, ...grouped.other] + (sourceBranch === null + ? [...grouped.default, ...grouped.recent, ...grouped.other] + : refs.filter((branch) => branch.name === sourceBranch) + ) .filter((branch) => branch.name !== target) .map((entry) => ({ ref: `refs/heads/${entry.name}`, @@ -194,17 +209,17 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ entry, remote: false, })), - [grouped.default, grouped.other, grouped.recent, target], + [grouped.default, grouped.other, grouped.recent, refs, sourceBranch, target], ); const remoteSourceOptions = useMemo( (): ReadonlyArray => - grouped.remote.map((entry) => ({ + (sourceBranch === null ? grouped.remote : []).map((entry) => ({ ref: `refs/remotes/${entry.name}`, label: entry.name, entry, remote: true, })), - [grouped.remote], + [grouped.remote, sourceBranch], ); const selectedOption = localSourceOptions.find((option) => option.ref === selectedSourceRef) ?? @@ -214,7 +229,8 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ null; const selectedSource = selectedOption?.ref ?? null; // Merge into another branch, and the Source Control entry, record a merge commit only. - const mergeCommitOnly = intoOtherBranch || targetMode === "current-branch"; + const mergeCommitOnly = + intoOtherBranch || sourceBranch !== null || targetMode === "current-branch"; const effectiveMode = mergeCommitOnly ? "merge" : mode; const operationTag = intoOtherBranch ? "merge-into" @@ -230,20 +246,23 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ ) ?? null, [operationTag, refs], ); - const blockedReason = intoOtherBranch - ? (refs - .find((ref) => ref.name === target) - ?.blocked.find((reason) => reason.operation === "merge-into") ?? null) - : selectedOption === null - ? null - : selectedOption.remote - ? repositoryBlockedReason - : (selectedOption.entry.blocked.find((reason) => reason.operation === operationTag) ?? - null); + const awaitingTarget = sourceBranch !== null && target === null; + const blockedReason = awaitingTarget + ? null + : intoOtherBranch + ? (refs + .find((ref) => ref.name === target) + ?.blocked.find((reason) => reason.operation === "merge-into") ?? null) + : selectedOption === null + ? null + : selectedOption.remote + ? repositoryBlockedReason + : (selectedOption.entry.blocked.find((reason) => reason.operation === operationTag) ?? + null); const previewAtom = useMemo( () => - !open || selectedSource === null || capabilityDisabledReason !== null + !open || selectedSource === null || awaitingTarget || capabilityDisabledReason !== null ? null : gitManagerEnvironment.previewMerge({ environmentId, @@ -253,7 +272,16 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ ...(intoOtherBranch && target !== null ? { target } : {}), }, }), - [capabilityDisabledReason, cwd, environmentId, intoOtherBranch, open, selectedSource, target], + [ + awaitingTarget, + capabilityDisabledReason, + cwd, + environmentId, + intoOtherBranch, + open, + selectedSource, + target, + ], ); const previewQuery = useEnvironmentQuery(previewAtom); const refreshPreview = previewQuery.refresh; @@ -265,29 +293,43 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ ? previewQuery.data : null; const summary = preview === null ? null : summarizeMergePreview(preview, { intoOtherBranch }); - const copy = resolveMergeConfirmCopy(effectiveMode, intoOtherBranch ? target : null); + const copy = + sourceBranch !== null && target === null + ? { title: `Merge ${sourceBranch} into another branch`, confirmLabel: "Merge" } + : resolveMergeConfirmCopy(effectiveMode, intoOtherBranch ? target : null); + const fixedSourceInvalidReason = + sourceBranch === null || target === null + ? null + : !refs.some((ref) => ref.name === sourceBranch) + ? `${sourceBranch} no longer exists.` + : !refs.some((ref) => ref.name === target) + ? `${target} no longer exists.` + : target === currentName + ? `${target} is now checked out. Use Merge… to merge into the checked-out branch.` + : null; // Below Git 2.38 there is no preview, but merging into the checked-out branch still works. const previewUnsupported = !intoOtherBranch && previewQuery.error?.startsWith(MERGE_PREVIEW_GIT_TOO_OLD_PREFIX) === true; const disabledReason = capabilityDisabledReason ?? + fixedSourceInvalidReason ?? blockedReason?.message ?? (operationRunning ? "The selected Git operation is running." : selectedSource === null ? "Choose a source branch." - : previewUnsupported - ? null - : preview === null && previewQuery.error !== null - ? previewQuery.error - : previewQuery.isPending || preview === null - ? "Loading merge preview." - : summary?.mergeEnabled === false - ? summary.message - : null); + : awaitingTarget + ? "Choose a branch to merge into." + : previewUnsupported + ? null + : preview === null && previewQuery.error !== null + ? previewQuery.error + : previewQuery.isPending || preview === null + ? "Loading merge preview." + : summary?.mergeEnabled === false + ? summary.message + : null); const confirmDisabled = disabledReason !== null; - const disabledReasonId = - disabledReason === null ? undefined : "git-manager-merge-disabled-reason"; const changeFilter = useCallback( (event: ChangeEvent) => setFilter(event.currentTarget.value), @@ -445,7 +487,9 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ {copy.title} - Select a source branch and review the server-computed merge preview. + {sourceBranch === null + ? "Select a source branch and review the server-computed merge preview." + : `Choose the branch to merge ${sourceBranch} into and review the server-computed merge preview.`}
@@ -506,68 +550,57 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({ )}
-
- - {remotes.length === 0 ? null : ( - - )} -
-
- {localSourceOptions.length === 0 && - remoteSourceOptions.length === 0 && - refsError !== null ? ( -
-

{refsError}

- -
- ) : localSourceOptions.length === 0 && remoteSourceOptions.length === 0 ? ( -

No source branches found.

- ) : ( - <> - {localSourceOptions.map((option) => ( - +
+ + {remotes.length === 0 ? null : ( + + Fetch + + )} +
+
+ {localSourceOptions.length === 0 && + remoteSourceOptions.length === 0 && + refsError !== null ? ( +
+

{refsError}

+ +
+ ) : localSourceOptions.length === 0 && remoteSourceOptions.length === 0 ? ( +

No source branches found.

+ ) : ( <> -

- Remote -

- {remoteSourceOptions.map((option) => ( + {localSourceOptions.map((option) => ( ))} + {remoteSourceOptions.length === 0 ? null : ( + <> +

+ Remote +

+ {remoteSourceOptions.map((option) => ( + + ))} + + )} )} - - )} -
+
+ + ) : ( +

+ Source: {sourceBranch} +

+ )}
{previewQuery.error !== null && preview === null ? (

{previewQuery.error}

) : summary === null ? ( -

Loading merge preview…

+

+ {awaitingTarget ? "Choose a branch to merge into." : "Loading merge preview…"} +

) : ( <>

{summary.message}

@@ -604,24 +659,14 @@ export const GitManagerMergeDialog = memo(function GitManagerMergeDialog({

)} - {disabledReason === null ? null : ( - - {disabledReason} - - )}
- + diff --git a/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.test.tsx b/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.test.tsx index 6c05350b61..a4db390bf4 100644 --- a/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.test.tsx +++ b/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.test.tsx @@ -1371,9 +1371,13 @@ describe("GitManagerCreatePullRequestDialog", () => { await act(async () => button("Publish and create pull request").click()); expect(text("create-pr-status")).toBe("Publishing feature/reviewed…"); + // The progress status is heard as it changes, not held back by a busy dialog. + expect( + document.querySelector('[data-testid="create-pr-status"]')?.closest('[aria-busy="true"]'), + ).toBeNull(); const cancel = button("Cancel"); expect(cancel.disabled).toBe(true); - expect(cancel.title).toBe("Wait for the pull request to finish."); + expect(cancel.parentElement?.title).toBe("Wait for the pull request to finish."); expect(button("Working…").disabled).toBe(true); expect(input("git-manager-create-pr-title").disabled).toBe(true); await act(async () => cancel.click()); diff --git a/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.tsx b/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.tsx index ce3676ee5b..2bfbd18950 100644 --- a/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.tsx +++ b/apps/web/src/components/gitManager/provider/GitManagerCreatePullRequestDialog.tsx @@ -78,6 +78,7 @@ import { type CreatePullRequestProgress, type CreatePullRequestProviderHint, } from "./GitManagerPullRequestPanel.logic"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; function safeExternalUrl(value: string | null): string | null { if (value === null) return null; @@ -428,11 +429,7 @@ function CreatePullRequestReviewDialog({ return ( - + Create {noun} @@ -661,14 +658,13 @@ function CreatePullRequestReviewDialog({ ) : ( <> - + { expect(container.textContent).toContain("Pull requests and checks"); expect(container.textContent).toContain(reason); - expect(button("Create pull request")).toMatchObject({ disabled: true, title: reason }); - expect(button("Refresh")).toMatchObject({ disabled: true, title: reason }); + expect(button("Create pull request").disabled).toBe(true); + expect(button("Create pull request").parentElement?.title).toBe(reason); + expect(button("Refresh").disabled).toBe(true); + expect(button("Refresh").parentElement?.title).toBe(reason); expect(h.listRequests).not.toHaveBeenCalled(); expect(h.createPr).not.toHaveBeenCalled(); expect(onRefresh).not.toHaveBeenCalled(); diff --git a/apps/web/src/components/gitManager/provider/GitManagerPullRequestPanel.tsx b/apps/web/src/components/gitManager/provider/GitManagerPullRequestPanel.tsx index ade7c1ad0b..13632f204a 100644 --- a/apps/web/src/components/gitManager/provider/GitManagerPullRequestPanel.tsx +++ b/apps/web/src/components/gitManager/provider/GitManagerPullRequestPanel.tsx @@ -16,12 +16,12 @@ import { memo, useCallback, useMemo, useState } from "react"; import { usePullRequestsStore } from "../../../pullRequestsStore"; import { gitManagerEnvironment } from "../../../state/gitManager"; import { useEnvironmentQuery } from "../../../state/query"; -import { Button } from "../../ui/button"; import { GitManagerCreatePullRequestDialog } from "./GitManagerCreatePullRequestDialog"; import { resolveProviderPanePresentation, resolveStatusChangeRequestPresentation, } from "./GitManagerPullRequestPanel.logic"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; const EMPTY_PULL_REQUESTS: ReadonlyArray = Object.freeze([]); const EMPTY_CHECKS: ReadonlyArray = Object.freeze([]); @@ -185,8 +185,6 @@ export const GitManagerPullRequestPanel = memo(function GitManagerPullRequestPan if (disabledReason !== null) return; setCreateDialogOpen(true); }, [disabledReason]); - const disabledReasonId = - disabledReason === null ? undefined : "git-manager-pull-request-panel-disabled-reason"; return (
@@ -196,29 +194,26 @@ export const GitManagerPullRequestPanel = memo(function GitManagerPullRequestPan

Provider data refreshes only on demand.

- - +

{disabledReason ?? presentation.message} diff --git a/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.logic.test.ts b/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.logic.test.ts index a6d4dd4ca4..5ed7fd3a65 100644 --- a/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.logic.test.ts +++ b/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.logic.test.ts @@ -104,10 +104,11 @@ describe("GitManagerConflictList", () => { const continueButton = container.querySelector( '[aria-label="Continue operation"]', ); - expect(continueButton).toMatchObject({ disabled: true, title: blocked.message }); - expect(continueButton?.getAttribute("aria-describedby")).toBe( - "git-manager-conflicts-continue-reason", - ); + expect(continueButton?.disabled).toBe(true); + expect(continueButton?.parentElement?.title).toBe(blocked.message); + expect( + document.getElementById(continueButton?.getAttribute("aria-describedby") ?? "")?.textContent, + ).toBe(blocked.message); expect(container.textContent).toContain(blocked.message); await act(async () => diff --git a/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.tsx b/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.tsx index e2ab87fe43..ce60d9f34b 100644 --- a/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.tsx +++ b/apps/web/src/components/gitManager/rewrite/GitManagerConflictList.tsx @@ -3,6 +3,7 @@ import { AlertTriangleIcon, CheckCircle2Icon, ChevronDownIcon, Undo2Icon } from import { memo, useCallback, useState } from "react"; import { Button } from "~/components/ui/button"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; import { Dialog, DialogDescription, @@ -88,18 +89,16 @@ const GitManagerConflictRow = memo(function GitManagerConflictRow({ : `${conflictCount} ${conflictCount === 1 ? "conflict" : "conflicts"}`} {resolved ? ( - + ) : conflict.kind === "binary" || conflict.kind === "submodule" ? (

- - +
) : null} @@ -171,8 +168,6 @@ export const GitManagerConflictList = memo(function GitManagerConflictList({ }, [onCommit]); const closeCommitWarning = useCallback(() => setCommitWarningOpen(false), []); const effectiveContinueReason = disabledReason ?? continueBlocked?.message ?? null; - const continueReasonId = - effectiveContinueReason === null ? undefined : "git-manager-conflicts-continue-reason"; return (
@@ -193,20 +188,13 @@ export const GitManagerConflictList = memo(function GitManagerConflictList({ Commit Resolved Files )} - - {effectiveContinueReason === null ? null : ( - - {effectiveContinueReason} - - )} +
diff --git a/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.test.tsx b/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.test.tsx index df2e9c6b72..8688f4ae8f 100644 --- a/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.test.tsx +++ b/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.test.tsx @@ -90,7 +90,8 @@ describe("GitManagerMultiCommitOperationDialog", () => { const cancel = [...document.body.querySelectorAll("button")].find( (button) => button.textContent === "Cancel", ); - expect(confirm).toMatchObject({ disabled: true, title: reason }); + expect(confirm?.disabled).toBe(true); + expect(confirm?.parentElement?.title).toBe(reason); expect(document.body.textContent).toContain(reason); expect(cancel?.disabled).toBe(false); await act(async () => cancel?.click()); @@ -256,10 +257,11 @@ describe("GitManagerMultiCommitOperationDialog", () => { const branch = document.body.querySelector( '[aria-label="Choose branch held/rewrite"]', ); - expect(branch).toMatchObject({ disabled: true, title: message }); - expect(branch?.getAttribute("aria-describedby")).toBe( - "git-manager-branch-choice-tip-held-reason", - ); + expect(branch?.disabled).toBe(true); + expect(branch?.parentElement?.title).toBe(message); + expect( + document.getElementById(branch?.getAttribute("aria-describedby") ?? "")?.textContent, + ).toBe(message); expect(document.body.textContent).toContain(message); }); }); diff --git a/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.tsx b/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.tsx index 5003f76900..ac929fa97e 100644 --- a/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.tsx +++ b/apps/web/src/components/gitManager/rewrite/GitManagerMultiCommitOperationDialog.tsx @@ -3,6 +3,7 @@ import type { GitManagerRefEntry } from "@bibcode/contracts"; import { memo, useCallback, useMemo } from "react"; import { Button } from "~/components/ui/button"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; import { Dialog, DialogDescription, @@ -40,32 +41,20 @@ const BranchChoice = memo(function BranchChoice({ const choose = useCallback(() => onChoose(branch.name), [branch.name, onChoose]); const blocked = branch.blocked.find((reason) => reason.operation === operation) ?? null; const effectiveDisabledReason = disabledReason ?? blocked?.message ?? null; - const reasonId = - effectiveDisabledReason === null - ? undefined - : `git-manager-branch-choice-${branch.tipSha}-reason`; return ( - <> - - {effectiveDisabledReason === null ? null : ( - - {effectiveDisabledReason} - - )} - + + + {branch.name} + + ); }); @@ -200,8 +189,6 @@ export const GitManagerMultiCommitOperationDialog = memo( progress?.current === null || progress?.current === undefined || progress.total === null ? null : `Commit ${progress.current} of ${progress.total}`; - const disabledReasonId = - disabledReason === null ? undefined : "git-manager-multi-commit-disabled-reason"; if (state.step === null) return null; if (state.step === "hide-conflicts") { @@ -235,9 +222,7 @@ export const GitManagerMultiCommitOperationDialog = memo(
{disabledReason === null ? null : ( -

- {disabledReason} -

+

{disabledReason}

)} {state.step === "warn-force-push" ? (
@@ -311,25 +296,21 @@ export const GitManagerMultiCommitOperationDialog = memo( - + ) : state.step === "confirm-abort" ? ( <> - + ) : state.step === "show-conflicts" ? ( - - - +
diff --git a/apps/web/src/components/gitManager/stash/GitManagerStashList.test.tsx b/apps/web/src/components/gitManager/stash/GitManagerStashList.test.tsx index 77e5859c9e..1875ae010c 100644 --- a/apps/web/src/components/gitManager/stash/GitManagerStashList.test.tsx +++ b/apps/web/src/components/gitManager/stash/GitManagerStashList.test.tsx @@ -178,11 +178,13 @@ describe("GitManagerStashList", () => { for (const label of ["Apply stash@{0}", "Pop stash@{0}", "Drop stash@{0}"]) { const action = h.buttons.find((props) => props["aria-label"] === label); - expect(action).toMatchObject({ - disabled: true, - title: blocked.message, - }); - expect(action?.["aria-describedby"]).toBe("git-manager-stash-stash-sha-blocked"); + expect(action?.disabled).toBe(true); + // The reason sits on the wrapper: the disabled Button itself receives no pointer events. + expect(markup).toContain(`title="${blocked.message}"`); + const host = document.createElement("div"); + host.innerHTML = markup; + const described = host.querySelector(`[id="${String(action?.["aria-describedby"])}"]`); + expect(described?.textContent).toBe(blocked.message); } expect(markup).toContain(blocked.message); }); @@ -196,12 +198,9 @@ describe("GitManagerStashList", () => { }); for (const label of ["Apply stash@{0}", "Pop stash@{0}", "Drop stash@{0}"]) { - expect(h.buttons.find((props) => props["aria-label"] === label)).toMatchObject({ - disabled: true, - title: reason, - }); + expect(h.buttons.find((props) => props["aria-label"] === label)?.disabled).toBe(true); } - expect(markup).toContain(reason); + expect(markup).toContain(`title="${reason}"`); const select = h.buttons.find((props) => props["aria-label"] === "Select stash stash@{0}"); expect(select?.disabled).not.toBe(true); (select?.onClick as (() => void) | undefined)?.(); diff --git a/apps/web/src/components/gitManager/stash/GitManagerStashList.tsx b/apps/web/src/components/gitManager/stash/GitManagerStashList.tsx index f66f9bd6a8..821d7210b1 100644 --- a/apps/web/src/components/gitManager/stash/GitManagerStashList.tsx +++ b/apps/web/src/components/gitManager/stash/GitManagerStashList.tsx @@ -10,6 +10,7 @@ import { ArchiveRestoreIcon, PackageOpenIcon, Trash2Icon } from "lucide-react"; import { memo, useCallback, useMemo, useState } from "react"; import { Button } from "~/components/ui/button"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; import { Dialog, DialogDescription, @@ -110,9 +111,6 @@ const GitManagerStashRowView = memo(function GitManagerStashRowView({ onRequestDrop, }: GitManagerStashRowViewProps) { const selector = `stash@{${row.index}}`; - const actionDisabledReason = disabledReason ?? row.blocked?.message ?? null; - const descriptionId = - actionDisabledReason === null ? undefined : `git-manager-stash-${row.sha}-blocked`; const actions = resolveStashActionState(row, { operationInFlight }); const select = useCallback(() => onSelectStash(row.sha), [onSelectStash, row.sha]); const apply = useCallback(() => void onApply(row.sha), [onApply, row.sha]); @@ -143,45 +141,40 @@ const GitManagerStashRowView = memo(function GitManagerStashRowView({ {row.files.length} {row.files.length === 1 ? "file" : "files"} - - - - {actionDisabledReason === null ? null : ( - - {actionDisabledReason} - - )} +
); }, stashRowViewPropsEqual); diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagDialog.test.tsx b/apps/web/src/components/gitManager/tags/GitManagerTagDialog.test.tsx index 8d4053dd99..80cd0b1a51 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagDialog.test.tsx +++ b/apps/web/src/components/gitManager/tags/GitManagerTagDialog.test.tsx @@ -164,7 +164,8 @@ describe("GitManagerTagDialog", () => { const reason = "This environment does not support Git Manager tag operations."; await renderDialog({ action: "delete", disabledReason: reason, tag: "release/v1" }); - expect(button("Delete Tag")).toMatchObject({ disabled: true, title: reason }); + expect(button("Delete Tag").disabled).toBe(true); + expect(button("Delete Tag").parentElement?.title).toBe(reason); expect(container.textContent).toContain(reason); expect(button("Cancel").disabled).toBe(false); await act(async () => button("Delete Tag").click()); diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagDialog.tsx b/apps/web/src/components/gitManager/tags/GitManagerTagDialog.tsx index f014c007e5..7a528c322b 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagDialog.tsx +++ b/apps/web/src/components/gitManager/tags/GitManagerTagDialog.tsx @@ -33,6 +33,7 @@ import { runGitManagerOperation, type GitManagerOperationHandle } from "~/state/ import { GitManagerOperationBanner } from "../toolbar/GitManagerOperationBanner"; import { resolveTagDeleteDialogCopy, validateTagName } from "./GitManagerTagDialog.logic"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; const noop = () => undefined; @@ -273,15 +274,13 @@ export const GitManagerTagDialog = memo(function GitManagerTagDialog({ - + diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.test.ts b/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.test.ts index 6a55f19c1d..b686724cdc 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.test.ts +++ b/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.test.ts @@ -81,6 +81,6 @@ describe("summarizeRemoteTagsQuery", () => { tags: [{ name: "v1", targetSha: "a" }], }, }), - ).toEqual({ kind: "ready", message: "Refreshing…" }); + ).toEqual({ kind: "ready", message: null }); }); }); diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.ts b/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.ts index 4050bc5daa..1b1fdcdabd 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.ts +++ b/apps/web/src/components/gitManager/tags/GitManagerTagsView.logic.ts @@ -104,5 +104,5 @@ export function summarizeRemoteTagsQuery(input: { if (input.result.tags.length === 0) { return { kind: "empty", message: `No tags on ${input.remote}.` }; } - return { kind: "ready", message: input.pending ? "Refreshing…" : null }; + return { kind: "ready", message: null }; } diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagsView.test.tsx b/apps/web/src/components/gitManager/tags/GitManagerTagsView.test.tsx index a954a1ed07..e173a1fd5b 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagsView.test.tsx +++ b/apps/web/src/components/gitManager/tags/GitManagerTagsView.test.tsx @@ -53,6 +53,7 @@ vi.mock("~/components/ui/collapsible", () => ({ })); import { GitManagerTagsView } from "./GitManagerTagsView"; +import { expectLoadingModel } from "~/components/ui/loading-state.testing"; const SHA_A = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const SHA_B = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; @@ -179,6 +180,71 @@ describe("GitManagerTagsView", () => { expect(onSectionCollapsedChange).toHaveBeenCalledWith("local", true); }); + it("shows a loading state, not empty-tag copy, while the refs snapshot is pending", async () => { + await renderView({ refsPending: true, tags: [], remotes: [] }); + expectLoadingModel(container, ["Loading tags…"]); + expect(container.textContent).not.toContain("No local tags"); + expect(container.textContent).not.toContain("No remote configured"); + expect(h.getRemoteTags).not.toHaveBeenCalled(); + }); + + it("says a failed first refs read failed, offers Retry, and lists no tags or remotes", async () => { + const onRetryRefs = vi.fn(); + await renderView({ + refsLoaded: false, + refsError: "Could not read refs.", + onRetryRefs, + tags: [], + remotes: [], + }); + expect(container.querySelector('[role="alert"]')?.textContent).toContain( + "Could not read refs.", + ); + expect(container.textContent).not.toContain("No local tags"); + expect(container.textContent).not.toContain("No remote configured"); + await act(async () => container.querySelector("button")!.click()); + expect(onRetryRefs).toHaveBeenCalledOnce(); + }); + + it("keeps the last tags beside a refresh label while the refs reread", async () => { + await renderView({ refsRefreshing: true }); + // Two reads, each named once: the refs reread and the remote's first listing. + expectLoadingModel(container, ["Refreshing tags…", "Loading tags from origin…"]); + expect(container.querySelector('[data-testid="git-manager-local-tag-v1"]')).not.toBeNull(); + }); + + it("shows refresh feedback for a remote that has no tags", async () => { + h.remoteTags = { remote: "origin", status: "available", reason: null, tags: [] }; + await renderView(); + expect(container.textContent).toContain("No tags on origin."); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.pending = true; + await renderView(); + expectLoadingModel(container, ["Refreshing tags from origin…"]); + }); + + it("keeps a disabled tag action's reason on a wrapper that still receives hover", async () => { + await renderView({ tagDisabledReason: "Tag actions need a newer server." }); + const del = container.querySelector('[aria-label="Delete tag v1"]'); + expect(del?.disabled).toBe(true); + expect(del?.parentElement?.title).toBe("Tag actions need a newer server."); + const push = container.querySelector('[aria-label="Push tag v1"]'); + expect(push?.parentElement?.title).toBe("Tag actions need a newer server."); + // Assistive technology reads the same reason as the button's description. + for (const button of [del, push]) { + const id = button?.getAttribute("aria-describedby") ?? ""; + expect(document.getElementById(id)?.textContent).toBe("Tag actions need a newer server."); + } + }); + + it("stops the remote refresh icon spinning under reduced motion", async () => { + h.pending = true; + await renderView(); + const icon = container.querySelector('[aria-label="Refresh tags from origin"] svg'); + expect(icon?.getAttribute("class")).toContain("motion-safe:animate-spin"); + expect(icon?.getAttribute("class")).not.toMatch(/(^|\s)animate-spin/); + }); + it("explains the absence of remotes and hides push actions", async () => { await renderView({ remotes: [] }); expect(container.textContent).toContain("No remote configured"); diff --git a/apps/web/src/components/gitManager/tags/GitManagerTagsView.tsx b/apps/web/src/components/gitManager/tags/GitManagerTagsView.tsx index 04543f106e..d4acc9bf5b 100644 --- a/apps/web/src/components/gitManager/tags/GitManagerTagsView.tsx +++ b/apps/web/src/components/gitManager/tags/GitManagerTagsView.tsx @@ -10,10 +10,12 @@ import { memo, useCallback, useMemo, type ReactNode } from "react"; import { Button } from "~/components/ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "~/components/ui/collapsible"; +import { LoadingState, RefreshRegion } from "~/components/ui/loading-state"; import { cn } from "~/lib/utils"; import { gitManagerEnvironment } from "../../../state/gitManager"; import { useEnvironmentQuery } from "../../../state/query"; +import { GitManagerDisabledReasonButton } from "../GitManagerDisabledReasonButton"; import { LOCAL_TAG_SECTION, buildLocalTagRows, @@ -34,6 +36,14 @@ export interface GitManagerTagsViewProps { readonly collapsedSections: ReadonlyArray; readonly onSectionCollapsedChange: (section: string, collapsed: boolean) => void; readonly onTagAction: (action: GitManagerTagRowAction, tag: string) => void; + /** The refs snapshot has not arrived: `tags` and `remotes` are placeholders, not answers. */ + readonly refsPending?: boolean; + /** The refs read failed; with no earlier snapshot (`refsLoaded` false) the tags are unknown. */ + readonly refsError?: string | null; + readonly refsLoaded?: boolean; + /** A reread runs while the last snapshot stays on screen. */ + readonly refsRefreshing?: boolean; + readonly onRetryRefs?: () => void; } const ROW_CLASS = @@ -116,27 +126,27 @@ function LocalTagRows({ {row.shortSha} {canPush ? ( - + ) : null} - + ))} @@ -193,55 +203,66 @@ function RemoteTagsSection({ variant="ghost" onClick={retry} > -
- - - {branchDisabledReason === null ? null : ( - - {branchDisabledReason} - - )} - {mergeDisabledReason === null && currentBranchName !== null ? null : ( - - {mergeDisabledReason ?? "Check out a branch before merging."} - - )} +
diff --git a/apps/web/src/components/gitManager/toolbar/branchCreateBase.test.ts b/apps/web/src/components/gitManager/toolbar/branchCreateBase.test.ts index 51a427f1b6..4be9c4b6dc 100644 --- a/apps/web/src/components/gitManager/toolbar/branchCreateBase.test.ts +++ b/apps/web/src/components/gitManager/toolbar/branchCreateBase.test.ts @@ -1,17 +1,76 @@ +import type { GitManagerRefEntry, GitManagerRefsSnapshot } from "@bibcode/contracts"; import { expect, it } from "vite-plus/test"; -import { resolveBranchCreateBase } from "./branchCreateBase"; +import { newBranchDialog } from "./branchCreateBase"; + +function branch(name: string, current: boolean): GitManagerRefEntry { + return { + name, + tipSha: "a".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + current, + isDefault: false, + worktreePath: null, + blocked: [], + }; +} + +function snapshot(overrides: Partial): GitManagerRefsSnapshot { + return { + generation: 1, + headRef: "alpha", + detachedSha: null, + isDirty: false, + defaultBranch: "master", + remotes: [], + localBranches: [branch("alpha", true), branch("master", false)], + remoteBranches: [], + tags: [], + worktrees: [], + inProgressOperation: null, + conflictedPaths: [], + ...overrides, + }; +} it("creates from the checked-out branch, never from the repository default", () => { - expect(resolveBranchCreateBase({ currentBranchName: "alpha", defaultBranch: "master" })).toBe( - "alpha", - ); - expect(resolveBranchCreateBase({ currentBranchName: "master", defaultBranch: "master" })).toBe( - "master", - ); + expect(newBranchDialog(snapshot({}))).toEqual({ + kind: "create", + baseBranch: "alpha", + baseCommit: null, + unborn: false, + }); +}); + +it("starts from the current HEAD (no start point) when HEAD is detached", () => { + const detached = snapshot({ + headRef: null, + detachedSha: "b".repeat(40), + localBranches: [branch("alpha", false)], + }); + expect(newBranchDialog(detached)).toEqual({ + kind: "create", + baseBranch: null, + baseCommit: null, + unborn: false, + }); +}); + +it("starts from no start point on an unborn branch, whose name is not a ref yet", () => { + // `refs/heads/main` does not exist before the first commit, so naming it would fail. + const unborn = snapshot({ headRef: "main", localBranches: [] }); + expect(newBranchDialog(unborn)).toEqual({ + kind: "create", + baseBranch: null, + baseCommit: null, + unborn: true, + }); }); -it("falls back to the current HEAD (no start point) when HEAD is detached", () => { - expect(resolveBranchCreateBase({ currentBranchName: null, defaultBranch: "master" })).toBeNull(); - expect(resolveBranchCreateBase({ currentBranchName: null, defaultBranch: null })).toBeNull(); +it("names the branch entry, not HEAD's short name, when a tag shares the branch name", () => { + // `symbolic-ref --short` says `heads/main` when a tag `main` exists. + const shadowed = snapshot({ headRef: "heads/main", localBranches: [branch("main", true)] }); + expect(newBranchDialog(shadowed).baseBranch).toBe("main"); }); diff --git a/apps/web/src/components/gitManager/toolbar/branchCreateBase.ts b/apps/web/src/components/gitManager/toolbar/branchCreateBase.ts index c2a0ebca8c..f4c33d5b64 100644 --- a/apps/web/src/components/gitManager/toolbar/branchCreateBase.ts +++ b/apps/web/src/components/gitManager/toolbar/branchCreateBase.ts @@ -1,13 +1,24 @@ +import type { GitManagerRefsSnapshot } from "@bibcode/contracts"; + +import type { GitManagerBranchDialog } from "../dialogs/GitManagerBranchDialogs"; + /** - * The start point for "New Branch": always the branch the user has checked - * out, or the current HEAD commit (no explicit start point) when HEAD is - * detached. The repository's default branch is deliberately not a fallback: - * a user working on `alpha` expects a new branch to fork from `alpha`, and - * the dialog names the base so the choice is visible before confirming. + * The "New branch" dialog every entry point opens. It starts from the checked-out + * branch's own entry, whose name comes from its full ref, never from HEAD's short + * name (`heads/main` when a tag `main` exists). The repository's default branch is + * deliberately not a fallback: a user on `alpha` expects a branch forked from `alpha`. + * A detached HEAD starts from the current commit (no start point). An unborn branch + * has no ref yet, so it also has no start point, and Git can only create the branch + * by switching to it. */ -export function resolveBranchCreateBase(input: { - readonly currentBranchName: string | null; - readonly defaultBranch: string | null; -}): string | null { - return input.currentBranchName; +export function newBranchDialog( + snapshot: GitManagerRefsSnapshot | null, +): Extract { + const current = snapshot?.localBranches.find((branch) => branch.current) ?? null; + return { + kind: "create", + baseBranch: current?.name ?? null, + baseCommit: null, + unborn: snapshot !== null && current === null && snapshot.detachedSha === null, + }; } diff --git a/apps/web/src/components/hostDashboard/HostDashboardPanel.test.tsx b/apps/web/src/components/hostDashboard/HostDashboardPanel.test.tsx new file mode 100644 index 0000000000..e5d1048661 --- /dev/null +++ b/apps/web/src/components/hostDashboard/HostDashboardPanel.test.tsx @@ -0,0 +1,219 @@ +// @vitest-environment happy-dom +// The Dashboard center panel (#378) over the real `serverEnvironment.hostMetrics` atom: a fake +// server stream counts opens and closes per environment, so a leaked subscription fails. +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, type ServerHostMetricsEvent, WS_METHODS } from "@bibcode/contracts"; +import { act, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { AtomRegistry } from "effect/reactivity"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +const h = vi.hoisted(() => ({ + opened: new Map(), + closed: new Map(), + visibility: "visible" as DocumentVisibilityState, + phase: new Map(), + hostMetrics: new Map(), + navigate: vi.fn(), +})); + +vi.mock("@tanstack/react-router", () => ({ useNavigate: () => h.navigate })); +vi.mock("../ui/tooltip", () => ({ + Tooltip: ({ children }: { children?: ReactNode }) => <>{children}, + TooltipTrigger: ({ render }: { render: ReactNode }) => render, + TooltipPopup: () => null, +})); +vi.mock("~/hooks/useSettings", () => ({ useClientSettings: () => "locale" })); +vi.mock("~/state/environments", () => { + const environment = (environmentId: string) => ({ + environmentId, + label: `Server ${environmentId}`, + entry: { target: { _tag: "BearerConnectionTarget", connectionId: environmentId } }, + connection: { phase: h.phase.get(environmentId) ?? "connected", error: null, traceId: null }, + serverConfig: { + environment: { capabilities: { hostMetrics: h.hostMetrics.get(environmentId) ?? true } }, + }, + }); + return { + useEnvironment: environment, + useEnvironments: () => ({ environments: [], isReady: true }), + }; +}); +vi.mock("~/state/server", async () => { + const Effect = await import("effect/Effect"); + const Layer = await import("effect/Layer"); + const Option = await import("effect/Option"); + const Stream = await import("effect/Stream"); + const SubscriptionRef = await import("effect/SubscriptionRef"); + const { Atom } = await import("effect/reactivity"); + const { createServerEnvironmentAtoms } = await import("@bibcode/client-runtime/state/server"); + const { EnvironmentRegistry, EnvironmentSupervisor } = + await import("@bibcode/client-runtime/connection"); + const bump = (counts: Map, id: string) => + counts.set(id, (counts.get(id) ?? 0) + 1); + const snapshot = (environmentId: string): ServerHostMetricsEvent => ({ + _tag: "Snapshot", + host: { os: "linux", arch: "x86_64", cpuCount: 12, memoryTotalBytes: 1_000 }, + bootId: "boot-1", + startedAt: "2026-11-11T19:00:00.000Z", + statisticsSince: "2026-11-11T19:00:00.000Z", + sample: { + sampledAt: "2026-11-11T19:00:01.000Z", + // Each server reads differently, so a reading shown under the wrong server is visible. + cpuPercent: environmentId === "server-a" ? 23.5 : 61.5, + memoryTotalBytes: 1_000, + memoryUsedBytes: 250, + memoryAvailableBytes: 750, + volumes: [], + volumesPaused: false, + }, + cpu: null, + memory: null, + recent: [], + uptime: [], + hiddenVolumes: [], + volumeStatistics: [], + }); + const fakeStream = (environmentId: string) => + Stream.unwrap( + Effect.sync(() => { + bump(h.opened, environmentId); + return Stream.make(snapshot(environmentId)).pipe(Stream.concat(Stream.never)); + }), + ).pipe(Stream.ensuring(Effect.sync(() => bump(h.closed, environmentId)))); + const registry = EnvironmentRegistry.of({ + followStream: (environmentId: string, stream: unknown) => + Stream.unwrap( + Effect.map( + SubscriptionRef.make( + Option.some({ + client: { [WS_METHODS.serverSubscribeHostMetrics]: () => fakeStream(environmentId) }, + }), + ), + (session) => + (stream as Parameters[0]).pipe( + Stream.provideService( + EnvironmentSupervisor, + EnvironmentSupervisor.of({ target: { environmentId }, session } as never), + ), + ), + ), + ), + } as never); + return { + serverEnvironment: createServerEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, registry)), + { initialConfigValueAtom: () => Atom.make(null) }, + ), + }; +}); + +import { HostDashboardPanel } from "./HostDashboardPanel"; + +const SERVER_A = EnvironmentId.make("server-a"); +const SERVER_B = EnvironmentId.make("server-b"); + +let root: Root; +let container: HTMLDivElement; +let registry: AtomRegistry.AtomRegistry; + +beforeEach(() => { + h.opened.clear(); + h.closed.clear(); + h.phase.clear(); + h.hostMetrics.clear(); + h.navigate.mockReset(); + h.visibility = "visible"; + Object.defineProperty(document, "visibilityState", { + configurable: true, + get: () => h.visibility, + }); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + registry = AtomRegistry.make(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + registry.dispose(); +}); + +/** Lets the atom registry run its idle disposal and the stream's finalizers. */ +async function settle() { + for (let turn = 0; turn < 5; turn += 1) { + await act(async () => new Promise((resolve) => setTimeout(resolve, 0))); + } +} + +/** Renders the panel the way its route does: keyed by the server it shows. */ +async function show(environmentId: EnvironmentId | null) { + await act(async () => + root.render( + + {environmentId === null ? null : ( + + )} + , + ), + ); + await settle(); +} + +describe("Dashboard center panel", () => { + it("shows the server's live dashboard and ends its stream when the panel closes", async () => { + await show(SERVER_A); + const panel = container.querySelector('[data-testid="host-dashboard-panel"]'); + expect(panel?.querySelector("h1")?.textContent).toBe("Server server-a"); + expect(panel?.textContent).toContain("Dashboard"); + expect(h.opened.get(SERVER_A)).toBe(1); + expect(container.querySelector('[data-testid="host-dashboard-cpu"]')?.textContent).toBe( + "23.5%", + ); + expect(container.textContent).toContain("Volumes"); + await show(null); + expect(h.closed.get(SERVER_A)).toBe(1); + }); + + it("stops the stream while the document is hidden and subscribes again after", async () => { + await show(SERVER_A); + h.visibility = "hidden"; + await act(async () => document.dispatchEvent(new Event("visibilitychange"))); + await settle(); + expect(h.closed.get(SERVER_A)).toBe(1); + h.visibility = "visible"; + await act(async () => document.dispatchEvent(new Event("visibilitychange"))); + await settle(); + expect(h.opened.get(SERVER_A)).toBe(2); + }); + + it("releases the first server's stream and never shows its values for another", async () => { + await show(SERVER_A); + await show(SERVER_B); + expect(h.closed.get(SERVER_A)).toBe(1); + expect(h.opened.get(SERVER_B)).toBe(1); + expect(container.querySelector('[data-testid="host-dashboard-cpu"]')?.textContent).toBe( + "61.5%", + ); + }); + + it("explains an unsupported server without sending a host-metrics request", async () => { + h.hostMetrics.set(SERVER_A, false); + await show(SERVER_A); + expect(h.opened.get(SERVER_A)).toBeUndefined(); + const openRemoteServers = [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Open Remote Servers", + ); + expect(openRemoteServers).toBeDefined(); + await act(async () => openRemoteServers!.click()); + expect(h.navigate).toHaveBeenCalledExactlyOnceWith({ to: "/settings/remote-servers" }); + }); + + it("opens no stream on a server that is not connected", async () => { + h.phase.set(SERVER_A, "disconnected"); + await show(SERVER_A); + expect(h.opened.get(SERVER_A)).toBeUndefined(); + }); +}); diff --git a/apps/web/src/components/hostDashboard/HostDashboardPanel.tsx b/apps/web/src/components/hostDashboard/HostDashboardPanel.tsx new file mode 100644 index 0000000000..0f292f8c08 --- /dev/null +++ b/apps/web/src/components/hostDashboard/HostDashboardPanel.tsx @@ -0,0 +1,31 @@ +import type { EnvironmentId } from "@bibcode/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useCallback } from "react"; + +import { useEnvironment } from "~/state/environments"; + +import { ServerPanelFrame } from "../serverCommands/ServerPanelFrame"; +import { HostDashboardBody, useHostDashboard } from "./HostDashboardSheet"; + +/** The host dashboard as a server's center panel; leaving the route ends its stream. */ +export function HostDashboardPanel({ environmentId }: { readonly environmentId: EnvironmentId }) { + const navigate = useNavigate(); + const environment = useEnvironment(environmentId); + const dashboard = useHostDashboard(environmentId, environment); + const openRemoteServers = useCallback( + () => void navigate({ to: "/settings/remote-servers" }), + [navigate], + ); + return ( + +
+
+ +
+
+
+ ); +} diff --git a/apps/web/src/components/hostDashboard/HostDashboardSheet.tsx b/apps/web/src/components/hostDashboard/HostDashboardSheet.tsx index 55238c856f..f54a58839d 100644 --- a/apps/web/src/components/hostDashboard/HostDashboardSheet.tsx +++ b/apps/web/src/components/hostDashboard/HostDashboardSheet.tsx @@ -17,7 +17,7 @@ import { import { useClientSettings } from "~/hooks/useSettings"; import { cn } from "~/lib/utils"; -import { useEnvironment } from "~/state/environments"; +import { type EnvironmentPresentation, useEnvironment } from "~/state/environments"; import { hostDashboardRequest } from "~/state/hostDashboard"; import { useEnvironmentQuery } from "~/state/query"; import { serverEnvironment } from "~/state/server"; @@ -110,6 +110,37 @@ export function HostDashboardSheet({ readonly onOpenRemoteServers: () => void; }) { const environment = useEnvironment(environmentId); + const dashboard = useHostDashboard(environmentId, environment); + return ( + { + if (!open) onClose(); + }} + > + + + {environment?.label ?? "Host dashboard"} + Host dashboard + + +
+ +
+
+
+
+ ); +} + +/** + * The dashboard's subscription, notices and values, shared by the sheet and the center panel. + * The caller keys it by `environmentId`, so one server's baseline never shows under another. + */ +export function useHostDashboard( + environmentId: EnvironmentId, + environment: EnvironmentPresentation | null, +) { const visible = useDocumentVisible(); const timestampFormat = useClientSettings(selectTimestampFormat); const nowMs = useVisibleSecondTick(visible); @@ -144,59 +175,50 @@ export function HostDashboardSheet({ timestampFormat, }); const chartView = view ?? shown.baseline; + return { presentation, chartView, timestampFormat, query }; +} +/** The notices and values of `useHostDashboard`, for the sheet and the center panel. */ +export function HostDashboardBody({ + dashboard: { presentation, chartView, timestampFormat, query }, + onOpenRemoteServers, +}: { + readonly dashboard: ReturnType; + readonly onOpenRemoteServers: () => void; +}) { return ( - { - if (!open) onClose(); - }} - > - - - {environment?.label ?? "Host dashboard"} - Host dashboard - - -
- {presentation.notice === null ? null : ( -
- - {presentation.notice} - - {presentation.state === "error" ? ( - - ) : null} - {presentation.state === "unsupported" ? ( - - ) : null} -
- )} - {presentation.values === null ? ( - presentation.state === "loading" ? ( - - ) : null - ) : ( -
- - - -
- )} -
-
-
-
+ <> + {presentation.notice === null ? null : ( +
+ + {presentation.notice} + + {presentation.state === "error" ? ( + + ) : null} + {presentation.state === "unsupported" ? ( + + ) : null} +
+ )} + {presentation.values === null ? ( + presentation.state === "loading" ? ( + + ) : null + ) : ( +
+ + + +
+ )} + ); } diff --git a/apps/web/src/components/markdown/MarkdownMermaidBlock.e2e.test.ts b/apps/web/src/components/markdown/MarkdownMermaidBlock.e2e.test.ts new file mode 100644 index 0000000000..9db6c83214 --- /dev/null +++ b/apps/web/src/components/markdown/MarkdownMermaidBlock.e2e.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment happy-dom +import { expect, it, vi } from "vite-plus/test"; + +// The packaged UI build sets this flag; it must be in place before the module loads. +vi.hoisted(() => vi.stubEnv("VITE_BIBCODE_DESKTOP_E2E", "1")); + +import { __holdMermaidDrawsForTests } from "./MarkdownMermaidBlock"; + +it("gives the packaged UI build's page the draw hold", () => { + expect( + (window as Window & { __bibcodeHoldMermaidDraws?: unknown }).__bibcodeHoldMermaidDraws, + ).toBe(__holdMermaidDrawsForTests); +}); diff --git a/apps/web/src/components/markdown/MarkdownMermaidBlock.tsx b/apps/web/src/components/markdown/MarkdownMermaidBlock.tsx index a1d45d22d2..b77df59185 100644 --- a/apps/web/src/components/markdown/MarkdownMermaidBlock.tsx +++ b/apps/web/src/components/markdown/MarkdownMermaidBlock.tsx @@ -82,18 +82,49 @@ function loadMermaidRenderer(): Promise { return rendererModule; } -/** Test seam: replaces the renderer import, or restores it when given nothing. */ +/** + * Test seam: replaces the renderer import, or restores it when given nothing. The typography + * gallery build calls it for its "renderer unavailable" state, so it works in every build. + */ export function __setMermaidRendererLoaderForTests(loader?: () => Promise): void { rendererLoader = loader ?? importMermaidRenderer; rendererModule = null; } -/** Test seam: forgets every drawn diagram, pending job and the measured fonts. */ +/** Draws queued while a test holds them, started in order on release; null when not held. */ +let heldDraws: Array<() => void> | null = null; + +/** + * Test seam: holds every diagram draw that is not already cached until the returned release + * runs, so a test can act between a block showing its source and its diagram drawing. Inert + * outside unit tests and the packaged UI suite's build, whose page uses it below. + */ +export function __holdMermaidDrawsForTests(): () => void { + if (import.meta.env.MODE !== "test" && import.meta.env.VITE_BIBCODE_DESKTOP_E2E !== "1") { + return () => {}; + } + heldDraws ??= []; + return () => { + const held = heldDraws ?? []; + heldDraws = null; + for (const start of held) start(); + }; +} + +// The packaged UI suite holds draws from the page; other builds drop this branch. +if (import.meta.env.VITE_BIBCODE_DESKTOP_E2E === "1" && typeof window !== "undefined") { + (window as Window & { __bibcodeHoldMermaidDraws?: () => () => void }).__bibcodeHoldMermaidDraws = + __holdMermaidDrawsForTests; +} + +/** Test seam: forgets every drawn diagram, pending job and the measured fonts. Inert outside unit tests. */ export function __resetMermaidDiagramsForTests(): void { + if (import.meta.env.MODE !== "test") return; diagramCache.clear(); drawnDiagramHeights.clear(); for (const job of pendingDiagramJobs.values()) job.cancel(); pendingDiagramJobs.clear(); + heldDraws = null; diagramFonts = null; rendererModule = null; } @@ -165,18 +196,29 @@ function subscribeToDiagramJob( diagramIdCounter += 1; const idPrefix = `bibcode-mmd-${diagramIdCounter}`; const created: PendingDiagramJob = { subscribers: new Set(), cancel: () => undefined }; - created.cancel = scheduleRender( - () => renderer.renderMermaidDiagram(source, fonts, idPrefix), - (diagram) => finishDiagramJob(key, created, { kind: "diagram", diagram, idPrefix }), - (error) => { - const problem = renderer.describeMermaidProblem(error); - // Pele's messages can quote the source: log the failure's class only. - if (problem.kind === "failed") { - reportMarkdownActionFailure({ operation: "render-diagram", code: problem.code }); - } - finishDiagramJob(key, created, { kind: "problem", problem }); - }, - ); + let cancelled = false; + let cancelRender: () => void = () => {}; + const start = () => { + if (cancelled) return; + cancelRender = scheduleRender( + () => renderer.renderMermaidDiagram(source, fonts, idPrefix), + (diagram) => finishDiagramJob(key, created, { kind: "diagram", diagram, idPrefix }), + (error) => { + const problem = renderer.describeMermaidProblem(error); + // Pele's messages can quote the source: log the failure's class only. + if (problem.kind === "failed") { + reportMarkdownActionFailure({ operation: "render-diagram", code: problem.code }); + } + finishDiagramJob(key, created, { kind: "problem", problem }); + }, + ); + }; + created.cancel = () => { + cancelled = true; + cancelRender(); + }; + if (heldDraws) heldDraws.push(start); + else start(); pendingDiagramJobs.set(key, created); job = created; } diff --git a/apps/web/src/components/pipelines/PipelinesPanel.test.tsx b/apps/web/src/components/pipelines/PipelinesPanel.test.tsx index 7161c9c94e..99d020da00 100644 --- a/apps/web/src/components/pipelines/PipelinesPanel.test.tsx +++ b/apps/web/src/components/pipelines/PipelinesPanel.test.tsx @@ -134,6 +134,14 @@ afterEach(async () => { }); describe("PipelinesPanel", () => { + it("shows a pending environment as loading, not unavailable", async () => { + h.connection = null; + await render(); + const status = container.querySelector('[role="status"]'); + expect(status?.textContent).toContain("Waiting for the environment connection state."); + expect(container.querySelector('[aria-label="Pipelines unavailable"]')).toBeNull(); + }); + it("follows its own setting, not the Pull Requests one", async () => { h.settings = { pullRequestsEnabled: true, pipelinesEnabled: false }; await render(); diff --git a/apps/web/src/components/pipelines/detail/PipelinesDetailView.test.tsx b/apps/web/src/components/pipelines/detail/PipelinesDetailView.test.tsx index 38643fe021..ae4aa283e0 100644 --- a/apps/web/src/components/pipelines/detail/PipelinesDetailView.test.tsx +++ b/apps/web/src/components/pipelines/detail/PipelinesDetailView.test.tsx @@ -20,6 +20,8 @@ import { RepositoryModule, type RepositoryModuleValue, } from "../../repositoryModule/RepositoryModule"; +import { clearResourceRefusals } from "../../repositoryModule/resourceRefusal"; +import { expectLoadingModel } from "../../ui/loading-state.testing"; import { buildPipelinesListInput } from "../list/pipelinesList.logic"; import { pipelinesModule } from "../pipelinesModule"; import { pipelineJobDetail } from "../job/testFixtures"; @@ -32,6 +34,8 @@ const h = vi.hoisted(() => ({ onAnswer: null as ((detail: PipelinesDetail) => PipelinesDetail) | null, error: null as PullRequestsOperationError | null, pending: false, + // The stored copy's read is in flight, as after a change event. + snapshotPending: false, failures: new Map(), snapshot: null as PipelinesSnapshot | null, // What the latest attempt's stored copy holds, for an earlier attempt's page. @@ -94,7 +98,7 @@ vi.mock("../../../state/query", () => ({ data: value, emission, error: null, - isPending: false, + isPending: atom.kind === "readSnapshot" && h.snapshotPending, refresh: read, revalidate: read, requiresRetry: false, @@ -265,11 +269,14 @@ async function render( wrap?: (node: ReactNode) => ReactNode; /** The server serves `pipelines.runAction`. */ actions?: boolean; + /** The repository the checkout points at. */ + repository?: string; } = {}, ) { const view = ; + const base = options.provider === "github" ? githubContext : gitlabContext; const value = moduleValue( - options.provider === "github" ? githubContext : gitlabContext, + options.repository === undefined ? base : { ...base, repository: options.repository }, options.actions ? null : SERVER_TOO_OLD, ); await act(async () => @@ -321,11 +328,13 @@ beforeEach(() => { document.body.append(container); root = createRoot(container); usePipelinesStore.setState({ byProjectKey: {} }); + clearResourceRefusals(); localStorage.clear(); h.detail = pipelineDetail(); h.onAnswer = null; h.error = null; h.pending = false; + h.snapshotPending = false; h.failures.clear(); h.snapshot = null; h.latestSnapshot = null; @@ -775,6 +784,130 @@ describe("PipelinesDetailView errors", () => { expect(refreshContext).not.toHaveBeenCalled(); }); + it("keeps the refusal in force while a Refresh runs, and lifts it only on a successful read", async () => { + await render(); + h.changed = { list: false, pipeline: true, refused: "forbidden" }; + h.nextSnapshot = { list: null, detail: null, job: null }; + await render(); + expect(container.querySelector("header")).toBeNull(); + await act(async () => handle.current!.refresh()); + // The read is in flight: the retained detail and its actions stay hidden. + expect(container.querySelector("header")).toBeNull(); + expect(container.textContent).not.toContain("Retry rspec"); + expect(container.querySelector('[role="alert"]')?.textContent).toContain( + "You can't view this pipeline.", + ); + await settle(); + expect(container.querySelector("header")).not.toBeNull(); + }); + + it("does not bring a lifted refusal back on the next refresh", async () => { + await render(); + h.changed = { list: false, pipeline: true, refused: "forbidden" }; + h.nextSnapshot = { list: null, detail: null, job: null }; + await render(); + await act(async () => handle.current!.refresh()); + await settle(); + expect(container.querySelector("header")).not.toBeNull(); + await act(async () => handle.current!.refresh()); + // The second read is in flight: the authorized detail stays, with no old refusal. + expect(container.querySelector("header")).not.toBeNull(); + expect(container.querySelector('[role="alert"]')).toBeNull(); + }); + + describe("a refusal stays in force until a later read of the pipeline succeeds", () => { + const steps = { + refusal: async () => { + h.error = operationError("forbidden", "No access."); + await render(); + }, + // The poller's read was refused and its stored row dropped. + pollerRefusal: async () => { + h.changed = { list: false, pipeline: true, refused: "forbidden" }; + h.nextSnapshot = { list: null, detail: null, job: null }; + await render(); + }, + timeout: async () => { + h.error = operationError("provider_error", "Host timed out"); + await render(); + }, + // The list filter re-keys the stored copy this page reads. + filterChange: async () => { + usePipelinesStore + .getState() + .setFilters(projectRef, { ...DEFAULT_PIPELINES_FILTERS, ref: "release" }); + await render(); + }, + pendingRefresh: async () => { + h.error = null; + await act(async () => handle.current!.refresh()); + }, + reopen: async () => { + await act(async () => root.unmount()); + root = createRoot(container); + await render(); + }, + }; + it.each<[string, (keyof typeof steps)[]]>([ + ["refusal, then a timeout", ["refusal", "timeout"]], + ["timeout, then refusal, then timeout", ["timeout", "refusal", "timeout"]], + ["the poller's refusal, then a timeout", ["pollerRefusal", "timeout"]], + ["refusal, then a timeout, then a filter change", ["refusal", "timeout", "filterChange"]], + ["refusal, then a refresh still in flight", ["refusal", "pendingRefresh"]], + ["refusal, then a timeout, then reopening the page", ["refusal", "timeout", "reopen"]], + ])("%s", async (_name, order) => { + await render(); + expect(container.querySelector("header")).not.toBeNull(); + for (const step of order) await steps[step](); + expect(container.querySelector("header")).toBeNull(); + expect(container.textContent).not.toContain("Retry rspec"); + // Only a read the host answers lifts it. + h.error = null; + await act(async () => handle.current!.refresh()); + await settle(); + expect(container.querySelector("header")).not.toBeNull(); + }); + }); + + it("does not carry a refusal into another repository at the same checkout path", async () => { + h.detail = null; + h.error = operationError("not_found", "Gone."); + await render({ repository: "example-group/sample-project" }); + expect(container.textContent).toContain("This pipeline no longer exists."); + // The remote now points at another repository: its pipeline 4821 has not answered yet. + await act(async () => root.unmount()); + root = createRoot(container); + h.error = null; + h.pending = true; + await render({ repository: "example-group/other-project" }); + expect(container.textContent).not.toContain("This pipeline no longer exists."); + expectLoadingModel(container, ["Loading pipeline…"]); + }); + + it("names the pending read when a refused pipeline is opened again", async () => { + h.detail = null; + h.error = operationError("not_found", "Gone."); + await render(); + await act(async () => root.unmount()); + root = createRoot(container); + h.error = null; + h.pending = true; + await render(); + // The refusal stays in force, and the read that may lift it is announced. + expect(container.textContent).toContain("This pipeline no longer exists."); + expectLoadingModel(container, ["Loading pipeline…"]); + }); + + it("shows the refresh label while a change event's stored read is pending", async () => { + await render(); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.snapshotPending = true; + await render(); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Refreshing pipeline…", + ); + }); + it("says a pipeline the poller found gone no longer exists", async () => { await render(); h.changed = { list: false, pipeline: true, refused: "not_found" }; @@ -787,6 +920,22 @@ describe("PipelinesDetailView errors", () => { }); }); +describe("PipelinesDetailView loading feedback", () => { + it("labels a first load, then keeps the detail beside a refresh label", async () => { + h.detail = null; + h.pending = true; + await render(); + expectLoadingModel(container, ["Loading pipeline…"]); + h.detail = pipelineDetail({ pipeline: { title: "Loaded title" } }); + await render(); + expect(container.querySelector("header h2")?.textContent).toBe("Loaded title"); + expectLoadingModel(container, ["Refreshing pipeline…"]); + h.pending = false; + await render(); + expect(container.querySelector('[role="status"]')).toBeNull(); + }); +}); + describe("PipelinesDetailView paint", () => { it("paints the stored pipeline before its live read answers", async () => { h.detail = null; diff --git a/apps/web/src/components/pipelines/detail/PipelinesDetailView.tsx b/apps/web/src/components/pipelines/detail/PipelinesDetailView.tsx index 15ebb0d926..7ee209a43e 100644 --- a/apps/web/src/components/pipelines/detail/PipelinesDetailView.tsx +++ b/apps/web/src/components/pipelines/detail/PipelinesDetailView.tsx @@ -1,5 +1,5 @@ import { projectKey } from "@bibcode/client-runtime/state/entities"; -import { squashAtomCommandFailure } from "@bibcode/client-runtime/state/runtime"; +import { environmentRpcKey, squashAtomCommandFailure } from "@bibcode/client-runtime/state/runtime"; import { PullRequestsOperationError, type PipelinesDetail, @@ -30,10 +30,12 @@ import { usePullRequestsQuery } from "../../pullRequests/shared/usePullRequestsQ import { useDocumentVisible } from "../../pullRequests/useDocumentVisible"; import { useRepositoryModule } from "../../repositoryModule/RepositoryModule"; import { RepositoryModuleExternalLink } from "../../repositoryModule/RepositoryModuleExternalLink"; +import { useResourceRefusal } from "../../repositoryModule/resourceRefusal"; import { keepNewestCopy, type KeptCopy } from "../../repositoryModule/snapshotDisplay.logic"; import { useVisibleModuleRefresh } from "../../repositoryModule/useVisibleModuleRefresh"; import { PermissionButton } from "../../ui/permission-button"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../../ui/select"; +import { LoadingState, RefreshRegion } from "../../ui/loading-state"; import { Skeleton } from "../../ui/skeleton"; import { PipelineActions, type PipelineActionOutcome } from "../actions/PipelineActions"; import { pipelineActionDestination } from "../actions/pipelineActions.logic"; @@ -277,19 +279,17 @@ export function PipelinesDetailView({ // Any success on the stream, even its first all-false event, stands the timer down // until the stream fails or waits again. const paused = isGitlab && subscribeQuery.emission._tag === "Success"; - // The poller's read of this pipeline was refused and its stored row dropped: the - // refusal replaces the copy on screen until a Refresh reads the host again. - const [refusal, setRefusal] = useState<{ - readonly request: typeof request; - readonly code: PipelinesRefusal; - } | null>(null); - // Each event is a new object: a refusal is taken from the event that carries it. - const [seenChange, setSeenChange] = useState(null); - if (subscribeQuery.data !== seenChange) { - setSeenChange(subscribeQuery.data); - if (subscribeQuery.data?.refused) setRefusal({ request, code: subscribeQuery.data.refused }); - } - const refused = refusal !== null && refusal.request === request ? refusal.code : null; + // A refusal, by this read or by the poller's (which also dropped the stored row), hides + // every copy of this pipeline until a later read of it succeeds. + const error = operationError(detailQuery); + const liveRefusal: PipelinesRefusal | null = + error?.code === "forbidden" || error?.code === "not_found" ? error.code : null; + const refused = useResourceRefusal( + `pipelines.get:${context.host}/${context.repository}:${environmentRpcKey(request)}`, + detailQuery, + liveRefusal, + subscribeQuery.data, + ); const applySubscribedChange = useEffectEvent( (changed: NonNullable) => { // The poller already stored the new detail: paint it, never read the host again. @@ -332,7 +332,6 @@ export function PipelinesDetailView({ revalidate: timerRead, }); - const error = operationError(detailQuery); const refreshContext = use(PullRequestsContextRefresh); useEffect(() => { if (error?.code === "not_authenticated") refreshContext?.(); @@ -343,10 +342,8 @@ export function PipelinesDetailView({ onBackoffChange(backedOff); }, [backedOff, onBackoffChange]); const refreshDetail = detailQuery.refresh; - const refresh = useCallback(() => { - setRefusal(null); - refreshDetail(); - }, [refreshDetail]); + // A refusal stays in force until the read this starts succeeds. + const refresh = refreshDetail; useImperativeHandle(ref, () => ({ refresh }), [refresh]); // A GitLab job retry opens the new job; a GitHub re-run of an earlier attempt opens @@ -400,7 +397,7 @@ export function PipelinesDetailView({ detail.pipeline.reason, ); const announcement = useFinishedAnnouncement( - detail === null + detail === null || refused !== null ? null : { id: detail.pipeline.id, @@ -413,8 +410,8 @@ export function PipelinesDetailView({ // A refused or missing pipeline is about this resource only: say so here, and keep // the shared sign-in state for a lost login. - const resourceCode = - error?.code === "forbidden" || error?.code === "not_found" ? error.code : refused; + // A later failure of another kind, such as a timeout on Retry, is said as itself. + const resourceCode = liveRefusal ?? (detailQuery.error === null ? refused : null); const resourceError = resourceCode !== null; const message = resourceCode === "forbidden" @@ -462,7 +459,7 @@ export function PipelinesDetailView({ )} ); - const shown = resourceError ? null : detail; + const shown = refused !== null ? null : detail; const attemptOptions = provider === "github" && shown !== null ? pipelineAttemptOptions( @@ -493,6 +490,8 @@ export function PipelinesDetailView({ onJobChange(null); }, [onJobChange]); const logShown = selectedJobId !== null && shown !== null; + // The stored copy's read is what a change event updates the screen from. + const refreshing = detailQuery.isPending || snapshotQuery.isPending; return ( {alert} {shown !== null ? ( - <> + - - ) : message === null ? ( -
- Loading pipeline… + + ) : message === null || refreshing ? ( + // A held refusal or failure keeps its alert; the read that may answer it is named. + + -
+ ) : null} {logShown ? ( diff --git a/apps/web/src/components/pipelines/list/PipelinesListView.test.tsx b/apps/web/src/components/pipelines/list/PipelinesListView.test.tsx index ccc727f5bd..16f97d7a36 100644 --- a/apps/web/src/components/pipelines/list/PipelinesListView.test.tsx +++ b/apps/web/src/components/pipelines/list/PipelinesListView.test.tsx @@ -23,6 +23,8 @@ import { RepositoryModule, type RepositoryModuleValue, } from "../../repositoryModule/RepositoryModule"; +import { clearResourceRefusals } from "../../repositoryModule/resourceRefusal"; +import { expectLoadingModel } from "../../ui/loading-state.testing"; import { pipelinesModule } from "../pipelinesModule"; import { pipelineRow, pipelinesPage } from "../testFixtures"; import { buildPipelinesListInput } from "./pipelinesList.logic"; @@ -32,6 +34,14 @@ const h = vi.hoisted(() => ({ second: null as PipelinesListPage | null, error: null as PullRequestsOperationError | null, pending: false, + // The stored copy's read is in flight, as after a change event. + snapshotPending: false, + // The error answers the first page's read only; later pages stay settled. + firstOnlyError: false, + // The error answers a later page's read only; the first page stays settled. + laterOnlyError: false, + // Only the first page's read is in flight, as a timer refresh leaves page two alone. + firstOnly: false, failures: new Map(), snapshot: null as PipelinesSnapshot | null, nextSnapshot: null as PipelinesSnapshot | null, @@ -98,7 +108,7 @@ vi.mock("../../../state/query", () => ({ data: value, emission, error: null, - isPending: false, + isPending: atom.kind === "readSnapshot" && h.snapshotPending, refresh: read, revalidate: read, requiresRetry: false, @@ -115,7 +125,11 @@ vi.mock("../../../state/query", () => ({ requiresRetry: false, }; const data = atom.input.cursor === null ? h.first : h.second; - const error = h.error; + const error = + (h.firstOnlyError && atom.input.cursor !== null) || + (h.laterOnlyError && atom.input.cursor === null) + ? null + : h.error; if (error && !h.failures.has(error)) h.failures.set(error, { _tag: "Failure", cause: Cause.fail(error) }); // A read stays pending until `settle`, then answers with a new copy of the page. @@ -135,7 +149,7 @@ vi.mock("../../../state/query", () => ({ data, emission: error ? h.failures.get(error) : { _tag: "Success", value: data }, error: error?.message ?? null, - isPending: h.pending, + isPending: h.pending && (!h.firstOnly || atom.input.cursor === null), refresh: read, revalidate: read, requiresRetry: false, @@ -171,6 +185,7 @@ let container: HTMLDivElement; let root: Root; const handle = createRef(); const onFiltersChange = vi.fn(); +const onBackoffChange = vi.fn(); function moduleValue( repositoryContext: typeof context, @@ -219,7 +234,7 @@ async function render( ref={handle} filters={options.filters ?? DEFAULT_PIPELINES_FILTERS} onFiltersChange={onFiltersChange} - onBackoffChange={vi.fn()} + onBackoffChange={onBackoffChange} /> , ), @@ -251,11 +266,16 @@ beforeEach(() => { document.body.append(container); root = createRoot(container); usePipelinesStore.setState({ byProjectKey: {} }); + clearResourceRefusals(); localStorage.clear(); h.first = pipelinesPage([pipelineRow], { nextCursor: "c2" }); h.second = pipelinesPage([{ ...pipelineRow, id: 4700, label: "#4700", title: "Second page" }]); h.error = null; h.pending = false; + h.snapshotPending = false; + h.firstOnlyError = false; + h.laterOnlyError = false; + h.firstOnly = false; h.failures.clear(); h.snapshot = null; h.nextSnapshot = null; @@ -269,6 +289,7 @@ beforeEach(() => { h.reads.mockClear(); h.inflight = []; onFiltersChange.mockClear(); + onBackoffChange.mockClear(); setVisibility("visible"); }); afterEach(async () => { @@ -298,6 +319,101 @@ describe("PipelinesListView", () => { ); }); + it("hides retained rows and actions when a refresh is refused, and keeps them for a recoverable failure", async () => { + await render(); + expect(container.textContent).toContain("Fix connection recovery"); + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "provider_error", + message: "GitLab timed out.", + hostDetail: null, + retryable: true, + }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("timed out"); + expect(container.textContent).toContain("Fix connection recovery"); + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "forbidden", + message: "You can't view these pipelines.", + hostDetail: null, + retryable: false, + }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("can't view"); + expect(container.textContent).not.toContain("Fix connection recovery"); + expect(container.querySelector('[role="table"]')).toBeNull(); + expect(container.textContent).not.toContain("Load more"); + }); + + it("keeps later pages, and the rows, until a Refresh read succeeds", async () => { + await render(); + await act(async () => button("Load more").click()); + await settle(); + expect(container.textContent).toContain("Second page"); + await act(async () => handle.current!.refresh()); + expect(container.textContent).toContain("Second page"); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Refreshing pipelines…", + ); + await settle(); + expect(container.textContent).not.toContain("Second page"); + expect(container.textContent).toContain("Fix connection recovery"); + }); + + it("shows the refresh label for the first page's read while page two is shown", async () => { + await render(); + await act(async () => button("Load more").click()); + await settle(); + h.pending = true; + h.firstOnly = true; + await render(); + expect(container.textContent).toContain("Second page"); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Refreshing pipelines…", + ); + }); + + it("shows the refresh label while a stored first page waits for the live one", async () => { + h.first = null; + h.pending = true; + h.snapshot = stored("Stored title", 1_000); + await render(); + expect(container.textContent).toContain("Stored title"); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Refreshing pipelines…", + ); + }); + + it("keeps the empty message and Clear filter while a settled empty list refreshes", async () => { + h.first = pipelinesPage([]); + const filters = { ...DEFAULT_PIPELINES_FILTERS, ref: "release" }; + await render({ filters }); + expect(container.textContent).toContain("Clear filter"); + h.pending = true; + await render({ filters }); + expect(container.textContent).toContain("Clear filter"); + const status = container.querySelector('[role="status"]'); + expect(status?.textContent).toContain("Refreshing pipelines…"); + expect(container.textContent).not.toContain("Loading pipelines…"); + }); + + it("labels a first load, then keeps the rows beside a refresh label", async () => { + h.first = null; + h.pending = true; + await render(); + expectLoadingModel(container, ["Loading pipelines…"]); + expect(container.querySelector('[role="status"] svg.animate-spin')).not.toBeNull(); + h.pending = false; + h.first = pipelinesPage([{ ...pipelineRow, title: "Live title" }], { revision: 1 }); + await render(); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.pending = true; + await render(); + expect(container.textContent).toContain("Live title"); + expectLoadingModel(container, ["Refreshing pipelines…"]); + }); + it("paints the stored first page before the live read answers, then the live one", async () => { h.first = null; h.pending = true; @@ -439,6 +555,167 @@ describe("PipelinesListView", () => { expect(h.reads).not.toHaveBeenCalled(); }); + describe("a refusal stays in force until a later read of the same list succeeds", () => { + const refused = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "forbidden", + message: "You can't view these", + hostDetail: null, + retryable: false, + }); + const timedOut = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "provider_error", + message: "Host timed out", + hostDetail: null, + retryable: true, + }); + const filtered = { ...DEFAULT_PIPELINES_FILTERS, ref: "release" }; + const steps = { + refusal: async () => { + h.error = refused; + await render({ filters: filtered }); + }, + timeout: async () => { + h.error = timedOut; + await render({ filters: filtered }); + }, + // Clearing the filter shows another list; setting it again re-keys this one's pages. + filterRoundTrip: async () => { + await render(); + await render({ filters: filtered }); + }, + pendingRefresh: async () => { + h.error = null; + await act(async () => handle.current!.refresh()); + }, + // The stored copy paints the refused rows again unless the refusal outlives the view. + reopen: async () => { + h.snapshot = stored("Fix connection recovery", 1); + await act(async () => root.unmount()); + root = createRoot(container); + await render({ filters: filtered }); + }, + }; + it.each<[string, (keyof typeof steps)[]]>([ + ["refusal, then a timeout", ["refusal", "timeout"]], + ["timeout, then refusal, then timeout", ["timeout", "refusal", "timeout"]], + [ + "refusal, then a timeout, then a filter round trip", + ["refusal", "timeout", "filterRoundTrip"], + ], + ["refusal, then a refresh still in flight", ["refusal", "pendingRefresh"]], + ["refusal, then a timeout, then reopening the list", ["refusal", "timeout", "reopen"]], + ])("%s", async (_name, order) => { + await render({ filters: filtered }); + expect(container.textContent).toContain("Fix connection recovery"); + expect(button("All 1")).toBeDefined(); + for (const step of order) await steps[step](); + expect(container.textContent).not.toContain("Fix connection recovery"); + expect(container.querySelector('[aria-label="Retry pipeline #4821"]')).toBeNull(); + // The tab count came from the refused list too. + expect(button("All")).toBeDefined(); + // Only a read the host answers lifts it. + h.error = null; + await act(async () => handle.current!.refresh()); + await settle(); + expect(container.textContent).toContain("Fix connection recovery"); + }); + }); + it("hides later pages when only the first page's refresh is refused", async () => { + await render(); + await act(async () => button("Load more").click()); + await settle(); + expect(container.textContent).toContain("Second page"); + h.firstOnlyError = true; + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "forbidden", + message: "You can't view these pipelines.", + hostDetail: null, + retryable: false, + }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("can't view"); + expect(container.textContent).not.toContain("Second page"); + expect(container.querySelector('[role="table"]')).toBeNull(); + }); + + it("hides every page and the count when only the Load more read is refused", async () => { + await render(); + expect(button("All 1")).toBeDefined(); + h.laterOnlyError = true; + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "forbidden", + message: "You can't view these pipelines.", + hostDetail: null, + retryable: false, + }); + await act(async () => button("Load more").click()); + await settle(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("can't view"); + expect(container.textContent).not.toContain("Second page"); + expect(container.querySelector('[role="table"]')).toBeNull(); + // The tab count came from the refused list too. + expect(button("All")).toBeDefined(); + // Retry reads the list again from its first page; the host's answer lifts the refusal. + h.error = null; + h.laterOnlyError = false; + h.reads.mockClear(); + await act(async () => button("Retry").click()); + await settle(); + expect(h.reads).toHaveBeenCalledWith(null); + expect(container.textContent).toContain("Fix connection recovery"); + expect(container.querySelector('[role="alert"]')).toBeNull(); + }); + + it("counts down a first-page rate limit while page two is shown", async () => { + await render(); + await act(async () => button("Load more").click()); + await settle(); + h.firstOnlyError = true; + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "rate_limited", + message: "GitLab's rate limit was reached.", + hostDetail: null, + retryable: true, + retryAfterSeconds: 3, + }); + await render(); + expect(container.textContent).toContain("Trying again in 3 s."); + expect(button("Retry").disabled).toBe(true); + expect(onBackoffChange).toHaveBeenLastCalledWith(true); + }); + + it("shows a first-page failure that is not a refusal while page two is shown", async () => { + await render(); + await act(async () => button("Load more").click()); + await settle(); + h.firstOnlyError = true; + h.error = new PullRequestsOperationError({ + operation: "pipelines.list", + code: "provider_error", + message: "GitLab timed out.", + hostDetail: null, + retryable: true, + }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("timed out"); + expect(container.textContent).toContain("Second page"); + }); + + it("shows the refresh label while a change event's stored read is pending", async () => { + await render(); + expect(container.querySelector('[role="status"]')).toBeNull(); + h.snapshotPending = true; + await render(); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Refreshing pipelines…", + ); + }); + it("counts down a rate limit and reads again when it passes", async () => { vi.useFakeTimers(); h.first = null; diff --git a/apps/web/src/components/pipelines/list/PipelinesListView.tsx b/apps/web/src/components/pipelines/list/PipelinesListView.tsx index 7a786c8915..8ee4d49b80 100644 --- a/apps/web/src/components/pipelines/list/PipelinesListView.tsx +++ b/apps/web/src/components/pipelines/list/PipelinesListView.tsx @@ -29,9 +29,11 @@ import { usePullRequestsQuery } from "../../pullRequests/shared/usePullRequestsQ import { useDocumentVisible } from "../../pullRequests/useDocumentVisible"; import { useRepositoryModule } from "../../repositoryModule/RepositoryModule"; import { shownCopy, type ShownCopy } from "../../repositoryModule/snapshotDisplay.logic"; +import { type ResourceRefusal, useResourceRefusal } from "../../repositoryModule/resourceRefusal"; import { useVisibleModuleRefresh } from "../../repositoryModule/useVisibleModuleRefresh"; import { Button } from "../../ui/button"; import { PermissionButton } from "../../ui/permission-button"; +import { LoadingState, RefreshRegion } from "../../ui/loading-state"; import { Skeleton } from "../../ui/skeleton"; import { Tabs, TabsList, TabsTab } from "../../ui/tabs"; import { useRateLimitCountdown } from "../shared/useRateLimitCountdown"; @@ -64,7 +66,7 @@ const EMPTY_PAGES: readonly PipelinesLoadedPage[] = []; const getRowSize = () => PIPELINES_ROW_HEIGHT; const rowKey = (row: PipelinesRow) => String(row.id); -function operationError(query: EnvironmentQueryView) { +function operationError(query: Pick, "emission">) { const failure = query.emission._tag === "Failure" ? squashAtomCommandFailure(query.emission) : null; return isOperationError(failure) ? failure : null; @@ -78,6 +80,8 @@ function PipelinesPages({ firstQuery, emptyCopy, hasFilter, + firstRefused, + onPageRefused, onClearFilters, onTimerRetry, onBackoffChange, @@ -87,6 +91,10 @@ function PipelinesPages({ projectRef: ScopedProjectRef; input: PipelinesListInput; firstQuery: EnvironmentQueryView; + /** The host refused this list: every page loaded here, rows and actions, stays hidden. */ + firstRefused: boolean; + /** A later page was refused: the whole list is, as for a first-page refusal. */ + onPageRefused: (event: { readonly refused: ResourceRefusal }) => void; /** What the list says when it has no rows. */ emptyCopy: string; /** A branch or workflow filter is set, so an empty list offers to clear it. */ @@ -114,15 +122,26 @@ function PipelinesPages({ [cursor, input, scope.environmentId], ); const nextQuery = usePullRequestsQuery(nextAtom); - const query = cursor === null ? firstQuery : nextQuery; + // One report per failed read: a Retry the host refuses again is a new refusal. + const nextEmission = nextQuery.emission; + useEffect(() => { + const failure = operationError({ emission: nextEmission }); + if (failure?.code === "forbidden" || failure?.code === "not_found") + onPageRefused({ refused: failure.code }); + }, [nextEmission, onPageRefused]); + // Any first-page failure owns the alert, the countdown and Retry. + const query = cursor === null || firstQuery.error !== null ? firstQuery : nextQuery; + const firstData = firstRefused ? null : firstQuery.data; const rows = useMemo( () => - mergePipelineRows([ - ...(firstQuery.data ? [firstQuery.data] : EMPTY_PAGES), - ...(cursor === null ? EMPTY_PAGES : laterPages), - ...(cursor !== null && nextQuery.data ? [nextQuery.data] : EMPTY_PAGES), - ]), - [cursor, firstQuery.data, laterPages, nextQuery.data], + firstRefused + ? EMPTY_ROWS + : mergePipelineRows([ + ...(firstData ? [firstData] : EMPTY_PAGES), + ...(cursor === null ? EMPTY_PAGES : laterPages), + ...(cursor !== null && nextQuery.data ? [nextQuery.data] : EMPTY_PAGES), + ]), + [cursor, firstData, firstRefused, laterPages, nextQuery.data], ); const savedScrollTop = usePipelinesStore((state) => state.selectViewState(projectRef).scrollTop); const scrollTopRef = useRef(savedScrollTop); @@ -132,13 +151,27 @@ function PipelinesPages({ [projectRef], ); const refreshFirstPage = firstQuery.refresh; - const refresh = useCallback(() => { + // A manual Refresh keeps the loaded pages, selection and scroll until its read succeeds. + const resetFromRef = useRef<{ readonly data: unknown } | null>(null); + const resetPages = useCallback(() => { setCursors([null]); setLaterPages(EMPTY_PAGES); scrollTopRef.current = 0; scrollRef.current?.scrollToOffset({ offset: 0, animated: false }); + }, []); + const refresh = useCallback(() => { + resetFromRef.current = { data: firstQuery.data }; refreshFirstPage(); - }, [refreshFirstPage]); + }, [firstQuery.data, refreshFirstPage]); + useEffect(() => { + // The same data means the read has not answered yet; a failed read leaves the reset + // waiting for the next successful one. + const from = resetFromRef.current; + if (from === null || firstQuery.isPending || firstQuery.error !== null) return; + if (firstQuery.data === from.data) return; + resetFromRef.current = null; + resetPages(); + }, [firstQuery.data, firstQuery.error, firstQuery.isPending, resetPages]); useImperativeHandle(ref, () => ({ refresh }), [refresh]); const error = operationError(query); const refreshContext = useContext(PullRequestsContextRefresh); @@ -147,7 +180,7 @@ function PipelinesPages({ }, [error, refreshContext]); const waitSeconds = useRateLimitCountdown( error, - cursor === null ? onTimerRetry : query.revalidate, + query === firstQuery ? onTimerRetry : query.revalidate, ); const backedOff = waitSeconds !== null; useEffect(() => { @@ -186,13 +219,15 @@ function PipelinesPages({ revalidateFirstPage(); if (cursor !== null) revalidatePage(); }, [cursor, revalidateFirstPage, revalidatePage]); - const total = firstQuery.data?.total ?? null; - const loaded = query.data !== null && !query.isPending; + const total = firstData?.total ?? null; + // A zero-row page is a resolved page: only the absence of one is a first load. + const resolved = firstData !== null; + const rereading = firstQuery.isPending || nextQuery.isPending; return ( ) : null} - {rows.length > 0 ? ( -
- - - ref={scrollRef} - className="min-h-0 flex-1 overflow-x-hidden" - role="rowgroup" - data={rows} - estimatedItemSize={PIPELINES_ROW_HEIGHT} - getFixedItemSize={getRowSize} - keyExtractor={rowKey} - initialScrollOffset={savedScrollTop} - renderItem={renderRow} - onScroll={(event) => { - scrollTopRef.current = event.nativeEvent.contentOffset.y; - }} - /> -
- ) : null} - {query.isPending && rows.length === 0 ? ( -
- Loading pipelines… + {rereading && !resolved ? ( + -
+ ) : null} - {rows.length === 0 && loaded && message === null ? ( -
-

{emptyCopy}

- {hasFilter ? ( - - ) : null} -
- ) : null} - {nextCursor !== null && !cursors.includes(nextCursor) && message === null ? ( -
- + {rows.length > 0 ? ( +
- Load more - -
- ) : null} - {/* GitHub stops a filtered list at 1,000 runs; GitLab pages to the end. */} - {context.provider === "github" && - nextCursor === null && - rows.length > 0 && - total?.capped ? ( -

- GitHub returns at most 1,000 filtered runs. -

- ) : null} + + + ref={scrollRef} + className="min-h-0 flex-1 overflow-x-hidden" + role="rowgroup" + data={rows} + estimatedItemSize={PIPELINES_ROW_HEIGHT} + getFixedItemSize={getRowSize} + keyExtractor={rowKey} + initialScrollOffset={savedScrollTop} + renderItem={renderRow} + onScroll={(event) => { + scrollTopRef.current = event.nativeEvent.contentOffset.y; + }} + /> +
+ ) : null} + {rows.length === 0 && resolved && message === null ? ( +
+

{emptyCopy}

+ {hasFilter ? ( + + ) : null} +
+ ) : null} + {nextCursor !== null && !cursors.includes(nextCursor) && message === null ? ( +
+ + Load more + +
+ ) : null} + {/* GitHub stops a filtered list at 1,000 runs; GitLab pages to the end. */} + {context.provider === "github" && + nextCursor === null && + rows.length > 0 && + total?.capped ? ( +

+ GitHub returns at most 1,000 filtered runs. +

+ ) : null} +
); @@ -382,21 +423,32 @@ export function PipelinesListView({ pipelinesEnvironment.requestTimerRead(firstTarget); revalidateFirstPage(); }, [firstTarget, revalidateFirstPage]); - const displayedFirstPage = nextShownList?.payload ?? null; + // A refusal hides every copy of this list, the stored one, the count and the workflow + // choices included, until the host answers a later read of the same list. + const [pageRefusal, setPageRefusal] = useState<{ readonly refused: ResourceRefusal } | null>( + null, + ); + const liveError = operationError(firstQuery); + const refused = + useResourceRefusal( + `pipelines.list:${context.host}/${context.repository}:${environmentRpcKey(firstTarget)}`, + firstQuery, + liveError?.code === "forbidden" || liveError?.code === "not_found" ? liveError.code : null, + pageRefusal, + ) !== null; + const displayedFirstPage = refused ? null : (nextShownList?.payload ?? null); useVisibleModuleRefresh({ enabled: listTimerEnabled(context.provider, displayedFirstPage?.rows ?? EMPTY_ROWS), succeeded: firstQuery.data !== null && firstQuery.error === null && !firstQuery.isPending, paused, revalidate: timerRead, }); - const displayedFirstQuery: EnvironmentQueryView = - displayedFirstPage === null - ? firstQuery - : { - ...firstQuery, - data: displayedFirstPage, - isPending: firstQuery.data === null ? false : firstQuery.isPending, - }; + // The stored copy's read is what a change event updates the screen from. + const displayedFirstQuery: EnvironmentQueryView = { + ...firstQuery, + data: refused ? null : (displayedFirstPage ?? firstQuery.data), + isPending: firstQuery.isPending || snapshotQuery.isPending, + }; useEffect(() => { if (freshPageKey !== null) consumeFreshPage(freshPageKey); }, [consumeFreshPage, freshPageKey]); @@ -404,8 +456,9 @@ export function PipelinesListView({ // GitHub's Workflow choices ride on its first page; the last ones stay while // another filter's page loads. const pageWorkflows = displayedFirstPage?.workflows ?? null; - const [workflows, setWorkflows] = useState(pageWorkflows); - if (pageWorkflows !== null && pageWorkflows !== workflows) setWorkflows(pageWorkflows); + const [keptWorkflows, setWorkflows] = useState(pageWorkflows); + if (pageWorkflows !== null && pageWorkflows !== keptWorkflows) setWorkflows(pageWorkflows); + const workflows = refused ? null : keptWorkflows; const hasFilter = filters.ref !== null || filters.workflowId !== null; const clearFilters = () => onFiltersChange({ ...filters, ref: null, workflowId: null }); return ( @@ -451,6 +504,8 @@ export function PipelinesListView({ firstQuery={displayedFirstQuery} emptyCopy={emptyListCopy({ provider: context.provider, filters, workflows })} hasFilter={hasFilter} + firstRefused={refused} + onPageRefused={setPageRefusal} onClearFilters={clearFilters} onTimerRetry={timerRead} onBackoffChange={onBackoffChange} diff --git a/apps/web/src/components/pullRequests/PullRequestsPanel.test.tsx b/apps/web/src/components/pullRequests/PullRequestsPanel.test.tsx index 23ecf5c010..25a95ffa45 100644 --- a/apps/web/src/components/pullRequests/PullRequestsPanel.test.tsx +++ b/apps/web/src/components/pullRequests/PullRequestsPanel.test.tsx @@ -164,6 +164,14 @@ afterEach(async () => { container.remove(); }); describe("PullRequestsPanel", () => { + it("shows a pending environment as loading, not unavailable", async () => { + h.connection = null; + await act(async () => root.render()); + expect(container.querySelector('[role="status"]')?.textContent).toContain( + "Waiting for the environment connection state.", + ); + expect(container.querySelector('[aria-label="Pull Requests unavailable"]')).toBeNull(); + }); it("stops the worktree loading status after the live catalog emits", async () => { h.catalogPending = true; h.catalogData = null; diff --git a/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.test.tsx b/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.test.tsx index c7038db909..3305628709 100644 --- a/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.test.tsx +++ b/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.test.tsx @@ -13,6 +13,7 @@ import { recordPrefetch, resetPrefetchGates } from "../hoverPrefetch.logic"; import { PullRequestsContextRefresh } from "../pullRequestsContextRefresh"; import { context, detail, fakeNavigation, gitlabContext } from "./testFixtures"; import { click, allowed } from "../review/testHelpers"; +import { clearResourceRefusals } from "../../repositoryModule/resourceRefusal"; const h = vi.hoisted(() => ({ command: vi.fn(), data: {} as Record, @@ -92,6 +93,7 @@ vi.mock("@tanstack/react-router", () => ({ Link: ({ children }: { children: React.ReactNode }) =>
{children}, })); import { PullRequestsDetailView } from "./PullRequestsDetailView"; +import { expectLoadingModel } from "../../ui/loading-state.testing"; import { PullRequestsFileAnchorContext, PullRequestsNavigationContext, @@ -182,12 +184,50 @@ beforeEach(() => { vi.clearAllMocks(); h.command.mockResolvedValue({ _tag: "Success", value: { kind: "done" } }); usePullRequestsStore.setState({ byProjectKey: {} }); + clearResourceRefusals(); }); afterEach(async () => { await act(async () => root.unmount()); container.remove(); }); describe("PullRequestsDetailView", () => { + it("hides the detail beside a refusal until a later read of it succeeds", async () => { + await render(); + expect(container.textContent).toContain(detail.title); + h.errors.get = new PullRequestsOperationError({ + operation: "pullRequests.get", + code: "forbidden", + message: "You can't view this request.", + hostDetail: null, + retryable: false, + }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain( + "You can't view this request.", + ); + expect(container.textContent).not.toContain(detail.title); + // A failure of another kind while the refusal is held never shows the old detail. + h.errors.get = new PullRequestsOperationError({ + operation: "pullRequests.get", + code: "host_unreachable", + message: "Could not refresh request details. Try again.", + hostDetail: null, + retryable: true, + }); + await render(); + expect(container.textContent).not.toContain(detail.title); + // Held with no live failure and the same value: it still says why nothing is shown. + delete h.errors.get; + await render(); + expect(container.textContent).not.toContain(detail.title); + expect(container.querySelector('[role="alert"]')?.textContent).toContain( + "You can't view this pull request.", + ); + h.data.get = { ...detail }; + await render(); + expect(container.textContent).toContain(detail.title); + }); + it("uses the loaded GitLab vocabulary in the action owner's stale-head toast", async () => { h.data.get = { ...detail, permissions: { ...detail.permissions, comment: allowed } }; usePullRequestsStore.getState().setCommentDraft(projectRef, 14, "Keep this draft"); @@ -316,6 +356,51 @@ describe("PullRequestsDetailView", () => { }); }); + it("shows refresh feedback while a change event's stored read is pending", async () => { + await render("conversation"); + expect(document.querySelector('[role="status"][aria-label^="Refreshing"]')).toBeNull(); + h.pendingQueries.add("readSnapshot"); + await render("conversation"); + expect(document.querySelector('[role="status"][aria-label^="Refreshing"]')).not.toBeNull(); + }); + + it("leaves a cold tab's first-load feedback to the tab, not the outer refresh line", async () => { + delete h.data.getTimeline; + h.pendingQueries.add("getTimeline"); + await render("conversation"); + expectLoadingModel(document, ["Loading Conversation…"]); + }); + + it("names a cold tab's first load once when opening it also rereads the stored copy", async () => { + await render("conversation"); + // Opening Commits starts its own read and a stored-copy read keyed by the tab. + delete h.data.getCommits; + h.pendingQueries.add("getCommits"); + h.pendingQueries.add("readSnapshot"); + await render("commits"); + expectLoadingModel(document, ["Loading Commits…"]); + }); + + it("names a detail reread once, outside every busy region, while the tab stays exposed", async () => { + await render("conversation"); + h.pendingQueries.add("get"); + await render("conversation"); + expectLoadingModel(document, ["Refreshing pull request #14…"]); + // The shown tab is one of the regions being refreshed. + expect(document.querySelector('[role="tabpanel"] [aria-busy="true"]')).not.toBeNull(); + }); + + it("keeps refresh feedback while the Files tab's review threads are the last read running", async () => { + await render("files"); + expect(document.querySelector('[role="status"][aria-label^="Refreshing"]')).toBeNull(); + h.pendingQueries.add("getTimeline"); + await render("files"); + expectLoadingModel(document, ["Refreshing pull request #14…"], ["Preparing diffs…"]); + h.pendingQueries.delete("getTimeline"); + await render("files"); + expect(document.querySelector('[role="status"][aria-label^="Refreshing"]')).toBeNull(); + }); + it("invalidates commits, checks and files after an update without subscribing inactive tabs", async () => { h.data.get = { ...detail, diff --git a/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.tsx b/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.tsx index 4d30f46220..d891aefe6a 100644 --- a/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.tsx +++ b/apps/web/src/components/pullRequests/detail/PullRequestsDetailView.tsx @@ -3,17 +3,19 @@ import { formatChangeRequestNumber, } from "@bibcode/shared/sourceControl"; import { useAtomRefresh } from "@effect/atom-react"; +import { environmentRpcKey, squashAtomCommandFailure } from "@bibcode/client-runtime/state/runtime"; import { projectKey } from "@bibcode/client-runtime/state/entities"; -import type { - EnvironmentId, - PullRequestsChecks as PullRequestsChecksData, - PullRequestsCommits as PullRequestsCommitsData, - PullRequestsContext, - PullRequestsDetail, - PullRequestsFiles as PullRequestsFilesData, - PullRequestsPipelineCopy, - PullRequestsTimeline, - ScopedProjectRef, +import { + PullRequestsOperationError, + type EnvironmentId, + type PullRequestsChecks as PullRequestsChecksData, + type PullRequestsCommits as PullRequestsCommitsData, + type PullRequestsContext, + type PullRequestsDetail, + type PullRequestsFiles as PullRequestsFilesData, + type PullRequestsPipelineCopy, + type PullRequestsTimeline, + type ScopedProjectRef, } from "@bibcode/contracts"; import { lazy, @@ -48,12 +50,16 @@ import { type KeptCopy, } from "../../repositoryModule/snapshotDisplay.logic"; import { PullRequestsQueryState } from "./PullRequestsQueryState"; +import { RefreshRegion } from "../../ui/loading-state"; import { PullRequestsHeader } from "./PullRequestsHeader"; import { PullRequestsConversation } from "./PullRequestsConversation"; import { PullRequestsSideColumn } from "./PullRequestsSideColumn"; import { PullRequestsCommits } from "./PullRequestsCommits"; import { PullRequestsChecks } from "./PullRequestsChecks"; import { usePullRequestsNavigation } from "./pullRequestsNavigation"; +import { useResourceRefusal } from "../../repositoryModule/resourceRefusal"; +import * as Schema from "effect/Schema"; +const isPullRequestsOperationError = Schema.is(PullRequestsOperationError); const PullRequestsFiles = lazy(() => import("./PullRequestsFiles").then((module) => ({ default: module.PullRequestsFiles })), ); @@ -264,9 +270,33 @@ export function PullRequestsDetailView({ // window: the atom still holds its own live value then, just a stale one. const liveDetail = detailQuery.data !== null && detailQuery.error === null ? detailQuery.data : null; - const displayedDetailData = detailQuery.data ?? paintedDetail?.payload ?? null; - const displayedDetailQuery: EnvironmentQueryView = - detailQuery.data !== null || paintedDetail === null + // A refusal hides every copy of this request, live, stored and painted, until a later + // read of it succeeds: the same rule as the pipeline detail. + const detailFailure = + detailQuery.emission._tag === "Failure" ? squashAtomCommandFailure(detailQuery.emission) : null; + const refusal = useResourceRefusal( + `pullRequests.get:${context.host}/${context.repository}:${environmentRpcKey(request)}`, + detailQuery, + isPullRequestsOperationError(detailFailure) && + (detailFailure.code === "forbidden" || detailFailure.code === "not_found") + ? detailFailure.code + : null, + ); + const refused = refusal !== null; + const requestName = resolveChangeRequestPresentationForKind(context.provider).longName; + const displayedDetailData = refused ? null : (detailQuery.data ?? paintedDetail?.payload ?? null); + const displayedDetailQuery: EnvironmentQueryView = refused + ? { + ...detailQuery, + data: null, + // A refusal held from an earlier read still says why nothing is shown. + error: + detailQuery.error ?? + (refusal === "forbidden" + ? `You can't view this ${requestName}.` + : `This ${requestName} no longer exists.`), + } + : detailQuery.data !== null || paintedDetail === null ? detailQuery : { ...detailQuery, data: paintedDetail.payload, isPending: false }; const paintedActivePayload = paintedTab?.tab === tab ? paintedTab.payload : null; @@ -345,7 +375,15 @@ export function PullRequestsDetailView({ files: vocabulary.filesChanged, }; const detail = displayedDetailData; - const refreshing = detailQuery.isPending || activeQuery.isPending; + // Every read that updates what is shown: the Files tab also waits on its review threads. + // A tab with nothing on screen yet announces its own first load instead. + const refreshing = + detailQuery.isPending || + // A pipeline-change event updates the shown copy through the stored read. Opening a + // cold tab also starts that read, and the tab's own first load names it. + (snapshotQuery.isPending && detail !== null && displayedActiveData !== null) || + (activeQuery.isPending && displayedActiveData !== null) || + (tab === "files" && timelineQuery.isPending && displayedTimeline !== null); const refreshDetail = detailQuery.refresh; const refreshTab = activeQuery.refresh; const refreshTimeline = timelineQuery.refresh; @@ -385,15 +423,22 @@ export function PullRequestsDetailView({ > {detail ? ( <> - + status={`Refreshing ${presentation.longName} ${formatChangeRequestNumber(context.provider, number)}…`} + > + + {tab === "conversation" && displayedTimeline ? ( } > - + {displayedTimeline ? ( - + + + diff --git a/apps/web/src/components/pullRequests/detail/PullRequestsHeader.tsx b/apps/web/src/components/pullRequests/detail/PullRequestsHeader.tsx index 1103d209a2..501582e92a 100644 --- a/apps/web/src/components/pullRequests/detail/PullRequestsHeader.tsx +++ b/apps/web/src/components/pullRequests/detail/PullRequestsHeader.tsx @@ -12,6 +12,7 @@ import { PullRequestsExternalLink } from "../shared/PullRequestsMarkdown"; import { PermissionButton } from "../../ui/permission-button"; import { PullRequestsStateIcon } from "../shared/PullRequestsStateIcon"; import { headerSentence } from "./pullRequestsDetail.logic"; +import { cn } from "../../../lib/utils"; export interface PullRequestsHeaderProps { scope: PullRequestsScope; projectRef: ScopedProjectRef; @@ -134,8 +135,11 @@ export const PullRequestsHeader = memo(function PullRequestsHeader({ variant="outline" size="sm" > -