From c4bb9d58d69d92485c014ef884b968abf046c617 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:52:17 +0000 Subject: [PATCH 01/79] test(snap): keep main's lines about the first tab's start when D1 is red aicc_planning#513, step 1 (evidence only; no app code). A red D1 restarts the Playwright worker and closeIsolatedApp deletes the data dir with its debug/app.log, so the run that failed kept nothing to read. - Part one's afterAll now writes, before closeIsolatedApp: - $SNAP_E2E_OUT/part1-main-lines.json: main's console lines on the launch path, each at the test's Date.now(); - $SNAP_E2E_OUT/part1-app.log: the app log's launch-path records, at main's own times. - D1 records readings.snapButtonAt (Date.now()), on the stand-in's clock. - tests/e2e/helpers/launch-evidence.ts filters by prefix and scrubs folders, the account name and anything token-shaped (the artifact is public); tests/unit/e2e-launch-evidence.test.ts plants each shape and proves none survives. TAB_MS and every timeout are unchanged (rule 27). ci.yml already uploads the folder with if: always(). Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 159 +++++++++++++++++++++ tests/e2e/snap-windows.spec.ts | 52 ++++++- tests/unit/e2e-launch-evidence.test.ts | 190 +++++++++++++++++++++++++ 3 files changed, 399 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/helpers/launch-evidence.ts create mode 100644 tests/unit/e2e-launch-evidence.test.ts diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts new file mode 100644 index 000000000..bee1407b9 --- /dev/null +++ b/tests/e2e/helpers/launch-evidence.ts @@ -0,0 +1,159 @@ +/** + * What the Snap e2e keeps of the first Claude Code tab's start, so that a red + * D1 can be read afterwards (aicc_planning#513, step 1). + * + * The lines main writes between a tab's spawn request and its launch line + * (pty-handlers.ts pty:spawn and its holds, pty-manager.ts spawnPty, and the + * start's work those holds wait for), from its console and from its log file + * (/debug/app.log, debug-logger.ts), filtered by their prefix, then + * scrubbed: the repo is public and the job's artifact can be downloaded by + * anyone, so no user folder, account name, credential or token-shaped value + * may stay in what is kept. + * + * No Playwright import, so the unit suite reads this directly + * (tests/unit/e2e-launch-evidence.test.ts). + */ +import fs from 'fs' +import os from 'os' + +/** The prefixes of main's lines on a local Claude Code tab's way to its + * launch line. The last two are console only (index.ts): the scripts + * folders' check and deploys a launch waits for (awaitScriptFolders). */ +export const LAUNCH_PATH_PREFIXES: readonly string[] = [ + '[pty]', '[pty-manager]', '[spawn]', '[spawn-claude]', '[scripts]', '[start]', '[profiles]', + '[session-helper]', '[launch]', '[jank]', '[path]', '[setup]', '[claude-version]', '[claude-provider]', + '[managed-launch]', + '[main] Failed to check the scripts folders', '[main] Failed to deploy the scripts', +] + +/** Whether a message of main's is one on the launch path. */ +export function isLaunchPathMessage(message: string): boolean { + return LAUNCH_PATH_PREFIXES.some((p) => message.startsWith(p)) +} + +/** One record of the app's log (debug-logger.ts formatMessage: + * `[] [] `), or null for a line that starts no + * record (the rest of an Error's stack, an empty line). */ +const RECORD = /^\[(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)\] \[([A-Z]+)\] (.*)$/ +export function appLogRecord(line: string): { at: string; level: string; message: string } | null { + const m = RECORD.exec(line) + return m ? { at: m[1], level: m[2], message: m[3] } : null +} + +/** What is put in place of what may not be kept: folders by a label of their + * own (the data dir as ``), the account the runner runs as as + * ``. */ +export interface EvidenceScrub { + folders: ReadonlyArray<{ label: string; dir: string | undefined }> + user?: string +} + +const escapeRegExp = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** A folder however a line spells it: either slash, a doubled backslash (a + * JSON string's), any case; only where the folder ends (a separator, a + * space, a quote or the end of the text follows), so a longer name that + * starts with it is not cut. */ +function folderPattern(dir: string): RegExp { + const parts = dir.split(/[\\/]+/).filter(Boolean).map(escapeRegExp) + return new RegExp(`${dir.startsWith('/') ? '[\\\\/]+' : ''}${parts.join('[\\\\/]+')}(?=[\\\\/\\s"'<>|;,)\\]]|$)`, 'gi') +} + +/** A user's folder on Windows (C:\Users\, a doubled backslash or a + * slash too) and on macOS or Linux (/Users/, /home/). */ +const WINDOWS_USER_FOLDER = /([A-Za-z]:(?:\\+|\/+)Users(?:\\+|\/+))([^\\/\s"'<>|:*?;,)\]]+)/gi +const POSIX_USER_FOLDER = /(^|[\s"'=(:;,[/])(\/(?:Users|home)\/)([^/\s"'<>|:;,)\]]+)/g + +/** Token-shaped values and what stands in their place, in order. */ +const SECRET_RULES: ReadonlyArray = [ + // A private key's block, whole. + [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, '[redacted]'], + // An Authorization header or field: its whole value, whatever its scheme. + [/(authorization[\\"']*\s*[:=]\s*)([\\"']*)(?!\[redacted\])[^\\"'\r\n,;}\]]+/gi, '$1$2[redacted]'], + // A bearer credential anywhere. + [/\b(bearer)(\s+|[\\"']*\s*[:=]\s*[\\"']*)(?!\[redacted\])[^\s\\"',;}\]]+/gi, '$1$2[redacted]'], + // key=value, key: value, "key":"value", where the key says what it is + // (tried only where a key can begin, so a long run is not tried at every + // character). + [/(? typeof f.dir === 'string' && f.dir.split(/[\\/]+/).filter(Boolean).length >= 2) + .sort((a, b) => b.dir.length - a.dir.length) + for (const { label, dir } of folders) out = out.replace(folderPattern(dir), label) + out = out.replace(WINDOWS_USER_FOLDER, '$1').replace(POSIX_USER_FOLDER, '$1$2') + if (scrub.user && scrub.user.length >= 3) out = out.replace(new RegExp(`(?') + for (const [re, to] of SECRET_RULES) out = out.replace(re, to) + return out.length > EVIDENCE_LINE_MAX ? `${out.slice(0, EVIDENCE_LINE_MAX)}...[cut]` : out +} + +/** Main's console lines on the launch path, each with the time the test saw + * it (Date.now(), the clock of the stand-in's `at` and readings.snapButtonAt), + * scrubbed. */ +export function launchPathMainLines(lines: ReadonlyArray<{ at: number; text: string }>, scrub: EvidenceScrub): Array<{ at: number; line: string }> { + return lines.filter((l) => isLaunchPathMessage(l.text)).map((l) => ({ at: l.at, line: scrubEvidence(l.text, scrub) })) +} + +/** The records of the app's log on the launch path, each with main's own + * time, scrubbed; the rest of a record's stack and every other record left + * out. */ +export function launchPathAppLog(text: string, scrub: EvidenceScrub): string[] { + const out: string[] = [] + for (const line of text.split(/\r?\n/)) { + const record = appLogRecord(line) + if (record && isLaunchPathMessage(record.message)) out.push(scrubEvidence(line, scrub)) + } + return out +} + +/** The scrub for this computer: the app's data dir, the temp folder and the + * home (each also by its real path, as main may spell it: a short 8.3 name + * against its long one), the repo, and the account the test runs as. */ +export function localEvidenceScrub(dataDir: string | undefined, repoRoot: string): EvidenceScrub { + const real = (dir: string | undefined): string | undefined => { + if (!dir) return undefined + try { return fs.realpathSync.native(dir) } catch { return undefined } + } + let user: string | undefined + try { user = os.userInfo().username } catch { user = undefined } + return { + folders: [ + { label: '', dir: dataDir }, { label: '', dir: real(dataDir) }, + { label: '', dir: os.tmpdir() }, { label: '', dir: real(os.tmpdir()) }, + { label: '', dir: os.homedir() }, { label: '', dir: real(os.homedir()) }, + { label: '', dir: repoRoot }, + ], + user, + } +} diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index dfd425d08..656490dda 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -193,7 +193,12 @@ * from the file to its path. Each picture test now ends at its own Enter, * within OVERLAY_MS: about four and a half times that 2.2 s, not ten, and not * raised. - * The readings go to the log and to $SNAP_E2E_OUT/readings.json. + * The readings go to the log and to $SNAP_E2E_OUT/readings.json. Whatever D1 + * answers, part one also keeps main's lines about the first tab's start + * (aicc_planning#513): $SNAP_E2E_OUT/part1-main-lines.json, its console lines + * at the test's Date.now() (the clock of readings.snapButtonAt and of the + * stand-in's `at`), and part1-app.log, the app's log at main's own times; the + * launch path's lines only, scrubbed (helpers/launch-evidence.ts). * * PART TWO, A CODEX TAB WHILE CODEX SHOWS ITS WARNING COUNT (plan * 2.1.3-beta.18, section 7.5; aicc_planning#428). An app of its own, in a @@ -257,6 +262,7 @@ import { seedCodexAccount, realmDirOf, createCodexConfig, openSession, activeSes import { nextFirstScreen, FOOTER, type FirstScreenAnswer } from './helpers/codex-first-screens' import { pathWithoutCodex } from './helpers/fake-codex' import { isolatedHomeDir } from './helpers/isolated-env' +import { launchPathAppLog, launchPathMainLines, localEvidenceScrub, scrubEvidence } from './helpers/launch-evidence' /** A Claude Code the app supports (CLAUDE_MIN_MANAGED_CLI_VERSION, as * onboarding-provider-select.spec.ts's stand-in answers). */ @@ -438,6 +444,41 @@ const appLogLines = (): string[] => { } const mark = (): Mark => ({ console: mainLines.length, fileLines: appLogLines().length }) +/** Part one's console lines, each at the time the test saw it (Date.now(): + * the clock of readings.snapButtonAt and of the stand-in's `at`). */ +const part1Main: Array<{ at: number; text: string }> = [] + +/** aicc_planning#513, step 1: main's lines about the first tab's start, kept + * whatever D1 answers. Written in part one's afterAll, before + * closeIsolatedApp deletes the data dir and debug/app.log with it: a red D1 + * restarts the worker, so nothing after part one could write them. The + * launch path's lines only (launch-evidence.ts LAUNCH_PATH_PREFIXES), + * scrubbed of folders, the account name and anything token-shaped, as the + * artifact is public. part1-main-lines.json: main's console lines from the + * window's start on, each at the test's time. part1-app.log: the app's log + * (the file appLogLines reads) from main's own start, each at main's time. + * Never throws: a file not written is said in the job's log, and the app is + * closed all the same. */ +function writePart1LaunchEvidence(): void { + const scrub = localEvidenceScrub(ctx?.dataDir, path.resolve(__dirname, '../..')) + const write = (name: string, body: () => string): void => { + try { + fs.writeFileSync(path.join(OUT, name), body()) + } catch (err) { + console.warn(`[snap-e2e] ${name} not written: ${scrubEvidence(err instanceof Error ? err.message : String(err), scrub)}`) + } + } + write('part1-main-lines.json', () => JSON.stringify({ + clock: 'Date.now() on the runner: the clock of readings.snapButtonAt and of launches[].at', + lines: launchPathMainLines(part1Main, scrub), + }, null, 2)) + write('part1-app.log', () => { + if (!ctx) return 'no app: part one launched none\n' + const lines = launchPathAppLog(appLogLines().join('\n'), scrub) + return lines.length > 0 ? `${lines.join('\n')}\n` : 'no launch-path line in the app log\n' + }) +} + /** Main's lines that start with `prefix` since `from`: from its console when it * has any, else from the log file (the file's lines carry a time and a level first). */ function linesSince(from: Mark, prefix: string): string[] { @@ -909,7 +950,11 @@ test.describe('Snap on Windows', () => { }), }) readings.launchMs = Math.round(performance.now() - started) - ctx.app.on('console', (m) => { mainLines.push(m.text()) }) + ctx.app.on('console', (m) => { + const text = m.text() + mainLines.push(text) + part1Main.push({ at: Date.now(), text }) + }) readings.appWindow = await placeAppWindow() }) @@ -918,6 +963,7 @@ test.describe('Snap on Windows', () => { fs.mkdirSync(OUT, { recursive: true }) fs.writeFileSync(path.join(OUT, 'readings.json'), JSON.stringify(readings, null, 2)) console.log(`[snap-e2e] readings ${JSON.stringify(readings)}`) + writePart1LaunchEvidence() await closeIsolatedApp(ctx) // Part two shares `ctx`: never leave it naming this closed app, whose // process id Windows may have given to another program by then. @@ -940,6 +986,8 @@ test.describe('Snap on Windows', () => { await expect(page.locator('text=New saved config')).toHaveCount(0, { timeout: TAB_MS }) await expect(snapButton()).toBeVisible({ timeout: TAB_MS }) readings.tabMs = Math.round(performance.now() - started) + // On the clock of the stand-in's `at` and part1-main-lines.json (aicc_planning#513). + readings.snapButtonAt = Date.now() // The tab runs the stand-in on a terminal: a Snap's path is typed into it. try { await expect.poll(() => launches().some((l) => l.stdinTty === true), { timeout: TAB_MS, intervals: [100] }).toBe(true) diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts new file mode 100644 index 000000000..65eeabcf9 --- /dev/null +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -0,0 +1,190 @@ +/** + * aicc_planning#513, step 1: the Snap e2e keeps main's lines about the first + * Claude Code tab's start (tests/e2e/snap-windows.spec.ts, part one's + * afterAll) in the job's artifact, which anyone can download from this public + * repo. The e2e harness cannot run here, so this pins the filter and the + * scrub it uses (tests/e2e/helpers/launch-evidence.ts, which imports no + * Playwright): only launch-path lines are kept, each with its time, and no + * planted credential, user folder or account name survives in what is kept. + * + * Touches no file: every value here is made in memory. + */ +import { describe, it, expect } from 'vitest' +import crypto from 'crypto' +import { + LAUNCH_PATH_PREFIXES, isLaunchPathMessage, appLogRecord, scrubEvidence, launchPathMainLines, launchPathAppLog, + EVIDENCE_LINE_MAX, type EvidenceScrub, +} from '../e2e/helpers/launch-evidence' + +const DATA = 'C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\ccc-e2e-AbC123' +const SCRUB: EvidenceScrub = { + folders: [ + { label: '', dir: DATA }, + { label: '', dir: 'C:\\Users\\RUNNER~1\\AppData\\Local\\Temp' }, + { label: '', dir: 'C:\\Users\\runneradmin' }, + { label: '', dir: 'D:\\a\\ai-code-conductor\\ai-code-conductor' }, + ], + user: 'runneradmin', +} + +// Planted values, each the shape of one the app or a user's environment holds. +const MCP_CREDENTIAL = crypto.createHmac('sha256', crypto.randomBytes(32)).update('run:nonce:session', 'utf8').digest('hex') +const INSTALL_SECRET = crypto.randomBytes(32).toString('hex') +const HOOKS_SECRET = crypto.randomUUID() +// Fixed, not random: a random one can lack a digit (this one has none) or a +// symbol, and the scrub must take it all the same. +const BASE64_SECRET = 'q9Xk+Lm2/Pz7Rt5Wv8Yb1Nc4Hd6Jf3Gs0Ae+Ui7Ko2==' +const BASE64URL_SECRET = 'QwErTyUiOpAsDfGhJkLzXcVbNmQwErTyUiOpAs_-QwEr' +const SECRETS = { + mcp: MCP_CREDENTIAL, + install: INSTALL_SECRET, + hooks: HOOKS_SECRET, + base64: BASE64_SECRET, + base64url: BASE64URL_SECRET, + headerValue: 'q7.Zx-Header_Value9', + bearer: 'bEaReRvalue42xyz', + envToken: 's3cr3tTokenValue', + jsonToken: 'v4lueOfStatusToken', + escapedToken: 'escapedT0kenValue', + password: 'hunter2hunter2', + clientSecret: 'cl1entSecretValue', + apiKeyFlag: 'flagKeyValue77', + anthropic: `sk-ant-api03-${'A1b2C3d4'.repeat(6)}`, + github: `ghp_${'aB3dE5gH7jK9mN1pQ3sT5vW7yZ9bD1fH3jL5'}`, + jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U', + aws: 'AKIAIOSFODNN7EXAMPLE', + userName: 'runneradmin', + otherUser: 'some.one', + longUser: 'jane-doe', +} + +/** Main's launch-path lines as it writes them, each carrying planted values. */ +const PLANTED_MESSAGES = [ + `[profiles] session 0123456789abcdef01234567 account spawn: requestedProfileId=(none) resolvedProfileId=(none/bare-global) shellOnly=false USERPROFILE=${DATA}\\home`, + `[pty-manager] Launching Claude via shell in PTY: powershell.exe -> ${DATA}\\stand-in-claude\\claude.cmd cwd=${DATA} (resumePicker=false, resume=none)`, + `[pty] Session 0123456789abcdef01234567: mcp credential ${MCP_CREDENTIAL} install ${INSTALL_SECRET}`, + `[pty] hooks gateway secret ${HOOKS_SECRET} and a key ${BASE64_SECRET} and ${BASE64URL_SECRET}`, + `[pty] request headers {"Authorization":"Bearer ${SECRETS.headerValue}"} then Authorization: Bearer ${SECRETS.headerValue}`, + `[pty] escaped {\\"authorization\\":\\"Basic ${SECRETS.headerValue}\\"} and a lone bearer ${SECRETS.bearer}`, + `[spawn] env CCC_HOOKS_TOKEN=${SECRETS.envToken} and {"statusToken":"${SECRETS.jsonToken}"} and {\\"mcpToken\\":\\"${SECRETS.escapedToken}\\"}`, + `[start] password=${SECRETS.password}; client_secret: ${SECRETS.clientSecret}`, + `[claude-provider] argv --api-key ${SECRETS.apiKeyFlag} --token ${SECRETS.apiKeyFlag}`, + `[setup] Claude CLI found: ${SECRETS.anthropic} ${SECRETS.github} ${SECRETS.jwt} ${SECRETS.aws}`, + '[scripts] the scripts folder could not be made this user\'s alone (C:\\Users\\runneradmin\\AppData\\x), so it is skipped', + '[jank] main loop stalled 1100ms (expected ~100ms) near start of icacls.exe', + '[path] Added to PATH from the registry: C:\\\\Users\\\\some.one\\\\bin;C:/Users/jane-doe/tools;/home/jane-doe/.local/bin;/Users/some.one/bin', + `[session-helper] ${'d:\\a\\ai-code-conductor\\ai-code-conductor'}\\out\\main\\index.js under c:/users/runner~1/appdata/local/temp/ccc-e2e-abc123/home`, +] + +const allText = (lines: string[]): string => lines.join('\n') +function expectNoneSurvive(text: string): void { + for (const [name, value] of Object.entries(SECRETS)) { + expect(text.toLowerCase().includes(value.toLowerCase()), `${name} survived: ${text}`).toBe(false) + } + expect(text, 'the runner temp folder survived').not.toMatch(/RUNNER~1/i) + expect(text, 'a user folder survived').not.toMatch(/Users[\\/]+(?!)[^\\/<\s]/i) +} + +describe('which of main\'s lines are kept: the launch path only', () => { + it('keeps a line with each launch-path prefix', () => { + for (const p of LAUNCH_PATH_PREFIXES) expect(isLaunchPathMessage(`${p} something`), p).toBe(true) + // The holds' and the spawn's own prefixes are all among them. + for (const p of ['[pty]', '[pty-manager]', '[spawn]', '[scripts]', '[start]', '[profiles]', '[session-helper]']) expect(LAUNCH_PATH_PREFIXES).toContain(p) + }) + + it('leaves out every other line, a prefix that only starts like one included', () => { + for (const m of ['[snap] new engine: cancelled; the helper took 12 ms', '[canvas] served', '[pty-integrity] x', '[ptyx] x', 'pty] x', ' [pty] indented', '[main] createWindow failed', '', 'Error: boom']) { + expect(isLaunchPathMessage(m), m).toBe(false) + } + }) + + it('reads an app.log record\'s time, level and message, and nothing from a stack line', () => { + expect(appLogRecord('[2026-12-03T17:55:00.123Z] [INFO] [pty] x')).toEqual({ at: '2026-12-03T17:55:00.123Z', level: 'INFO', message: '[pty] x' }) + expect(appLogRecord(' at foo (C:\\x.js:1:2)')).toBeNull() + expect(appLogRecord('[pty] no time first')).toBeNull() + }) +}) + +describe('main\'s console lines: kept with the time the test saw them, scrubbed', () => { + it('keeps every planted launch-path line, in order, at its time, and none of what was planted in them', () => { + const lines = [ + { at: 1, text: '[snap] new engine: not kept' }, + ...PLANTED_MESSAGES.map((text, i) => ({ at: 100 + i, text })), + { at: 999, text: '[canvas] not kept' }, + ] + const kept = launchPathMainLines(lines, SCRUB) + expect(kept.map((k) => k.at)).toEqual(PLANTED_MESSAGES.map((_, i) => 100 + i)) + expectNoneSurvive(allText(kept.map((k) => k.line))) + }) + + it('keeps what a reader needs: prefixes, session ids, the stand-in by name, the times in ms', () => { + const kept = launchPathMainLines(PLANTED_MESSAGES.map((text, at) => ({ at, text })), SCRUB).map((k) => k.line) + expect(kept[0]).toBe('[profiles] session 0123456789abcdef01234567 account spawn: requestedProfileId=(none) resolvedProfileId=(none/bare-global) shellOnly=false USERPROFILE=\\home') + expect(kept[1]).toBe('[pty-manager] Launching Claude via shell in PTY: powershell.exe -> \\stand-in-claude\\claude.cmd cwd= (resumePicker=false, resume=none)') + expect(kept[2]).toBe('[pty] Session 0123456789abcdef01234567: mcp credential [redacted] install [redacted]') + expect(kept[4]).toBe('[pty] request headers {"Authorization":"[redacted]"} then Authorization: [redacted]') + expect(kept[6]).toBe('[spawn] env CCC_HOOKS_TOKEN=[redacted] and {"statusToken":"[redacted]"} and {\\"mcpToken\\":\\"[redacted]\\"}') + expect(kept[11]).toBe('[jank] main loop stalled 1100ms (expected ~100ms) near start of icacls.exe') + expect(kept[12]).toBe('[path] Added to PATH from the registry: C:\\\\Users\\\\\\\\bin;C:/Users//tools;/home//.local/bin;/Users//bin') + expect(kept[13]).toBe('[session-helper] \\out\\main\\index.js under /home') + }) +}) + +describe('the app log: launch-path records only, main\'s own times kept, scrubbed', () => { + const log = [ + '[2026-12-03T17:55:00.001Z] [INFO] [snap] new engine: not kept', + ...PLANTED_MESSAGES.flatMap((m, i) => [ + `[2026-12-03T17:55:0${i % 10}.${String(100 + i)}Z] [${i % 2 ? 'WARN' : 'INFO'}] ${m}`, + // The rest of a record's stack: never kept, whatever it holds. + ` at Object. (C:\\Users\\runneradmin\\x.js:1:2) ${MCP_CREDENTIAL}`, + ]), + '[2026-12-03T17:55:09.999Z] [DEBUG] [canvas] not kept', + '', + ].join('\r\n') + + it('keeps one line per launch-path record, with its time and level, and none of what was planted', () => { + const kept = launchPathAppLog(log, SCRUB) + expect(kept).toHaveLength(PLANTED_MESSAGES.length) + kept.forEach((line, i) => expect(line.startsWith(`[2026-12-03T17:55:0${i % 10}.${String(100 + i)}Z] [${i % 2 ? 'WARN' : 'INFO'}] [`), line).toBe(true)) + expectNoneSurvive(allText(kept)) + expect(allText(kept)).not.toContain('Object.') + }) + + it('an empty or missing log keeps nothing', () => { + expect(launchPathAppLog('', SCRUB)).toEqual([]) + }) +}) + +describe('the scrub on its own', () => { + it('puts the data dir in place however it is spelt, and only where the folder ends', () => { + expect(scrubEvidence(`[pty] ${DATA.replace(/\\/g, '/')}/x and ${DATA.replace(/\\/g, '\\\\')}\\\\y`, SCRUB)).toBe('[pty] /x and \\\\y') + // A longer folder that starts with the data dir's name is not cut there. + expect(scrubEvidence(`[pty] ${DATA}9\\x`, SCRUB)).toBe('[pty] \\ccc-e2e-AbC1239\\x') + }) + + it('puts the account name in place wherever it shows, and only as a whole word', () => { + expect(scrubEvidence('[pty] runneradmin ran; RunnerAdmin too; runneradmins is another word', SCRUB)).toBe('[pty] ran; too; runneradmins is another word') + }) + + it('a session id (24 hex digits) and a short hex value stay; 32 or more go', () => { + expect(scrubEvidence('[pty] 0123456789abcdef01234567 deadbeef', SCRUB)).toBe('[pty] 0123456789abcdef01234567 deadbeef') + expect(scrubEvidence(`[pty] x_${'a'.repeat(32)}_y`, SCRUB)).toBe('[pty] x_[redacted]_y') + }) + + it('cuts a runaway line, after the scrub', () => { + const long = `[pty] ${MCP_CREDENTIAL} ${'word '.repeat(2000)}` + const out = scrubEvidence(long, SCRUB) + expect(out.length).toBeLessThanOrEqual(EVIDENCE_LINE_MAX + 10) + expect(out.endsWith('...[cut]')).toBe(true) + expect(out).not.toContain(MCP_CREDENTIAL) + }) + + it('a long run of letters, with a key word in it or many, is scrubbed in bounded time', () => { + const started = performance.now() + const out = scrubEvidence(`[pty] ${'x'.repeat(1_500)}token=${'y'.repeat(6_000)}`, SCRUB) + scrubEvidence(`[pty] ${'token'.repeat(4_000)}`, SCRUB) + scrubEvidence(`[pty] ${'Ab'.repeat(20_000)}`, SCRUB) + expect(performance.now() - started).toBeLessThan(2_000) + expect(out).not.toContain('yyyy') + }) +}) From 28153cb019b140afb0f237685c4a59d5046a4448 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:52:53 +0000 Subject: [PATCH 02/79] chore(wp1): refresh the legacy Codex manifest after the Snap evidence capture The two new test files move the tracked and scanned file counts and the manifest head; no matched path and no predicate hit changed (pathDigest 968553bf, ledger complete in the candidate phase). Co-Authored-By: Claude Opus 5.5 --- docs/wp1/legacy-codex-manifest.json | 10 +++++----- tests/wp1/legacy-codex-ledger.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/wp1/legacy-codex-manifest.json b/docs/wp1/legacy-codex-manifest.json index 33f615377..26306b876 100644 --- a/docs/wp1/legacy-codex-manifest.json +++ b/docs/wp1/legacy-codex-manifest.json @@ -1,8 +1,8 @@ { "schema": "wp1-legacy-codex-manifest/3", - "generatedAt": "2026-12-03T20:05:11.321Z", - "head": "24b5a8e91bfcb3bc40cab91d78753b8ace8007ca", - "tree": "b262ccbc44e14aa955b663afd798b7864eeb2452", + "generatedAt": "2026-12-03T20:52:42.578Z", + "head": "c4bb9d58d69d92485c014ef884b968abf046c617", + "tree": "7a09be349d98a2d2a136c9e7051dbaa915c882d4", "scannedWorkingTree": false, "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "predicates": [ @@ -116,9 +116,9 @@ "\\.(png|jpg|jpeg|gif|ico|icns|webp|svg|woff2?|ttf|otf|mp4|zip|asar|node|exe|dll|dylib|so|pdf)$", "^package-lock\\.json$" ], - "trackedFileCount": 4326, + "trackedFileCount": 4328, "excludedFileCount": 725, - "scannedFileCount": 3601, + "scannedFileCount": 3603, "unscopedFileCount": 15, "unscoped": [ ".claude/settings.json", diff --git a/tests/wp1/legacy-codex-ledger.json b/tests/wp1/legacy-codex-ledger.json index 069185255..e04ed657a 100644 --- a/tests/wp1/legacy-codex-ledger.json +++ b/tests/wp1/legacy-codex-ledger.json @@ -2,7 +2,7 @@ "schema": "wp1-legacy-codex-ledger/2", "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "manifestPathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", - "manifestHead": "24b5a8e91bfcb3bc40cab91d78753b8ace8007ca", + "manifestHead": "c4bb9d58d69d92485c014ef884b968abf046c617", "dispositions": { "retain": "unchanged observable behaviour, characterization proof", "move": "moved behind a package boundary and/or adapted at the call site, regression proof (newPath when relocated)", From b39da3c7cb272eb8032358980d0e63d3ae03e928 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:17:29 +0000 Subject: [PATCH 03/79] test(snap): cut a long evidence line safely and mark the cut scrubEvidence read the first 8000 characters of a line and said the part past that was "far past the part kept". It is not: each credential becomes "[redacted]", so an 8000 character line can end up under 2000 with its tail intact, and a credential the cut fell in left a piece shorter than 32 characters, which no shape rule takes. A probe with about 300 unlabelled base64 keys ended in 24 characters of a live-shaped key, and nothing in the output said the line had been cut. When a line is longer than SCRUB_INPUT_MAX, drop the last run of token characters of what is read before any rule runs, and end the line with "...[cut]" whenever either cut (that one, or the one at EVIDENCE_LINE_MAX) was made. The comment now says what is true. The unit cases plant 44 character values so that the cut falls 1, 9, 17, 24 and 31 characters inside one, and require that no 8 character piece of any planted value survives and that the line ends with the cut mark; they are red without the drop and without the mark. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 32 +++++++++++++---- tests/unit/e2e-launch-evidence.test.ts | 49 +++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index bee1407b9..23c72dd7e 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -98,16 +98,35 @@ const SECRET_RULES: ReadonlyArray = [ /** The longest a kept line may be: one runaway line cannot fill the artifact. */ export const EVIDENCE_LINE_MAX = 2000 /** How much of a line is scrubbed at most (the rules' cost grows with a - * line's length): four times what is kept, so a value cut here is far past - * the part kept. */ -const SCRUB_INPUT_MAX = 4 * EVIDENCE_LINE_MAX + * line's length): four times what is kept. That is no guarantee that a value + * cut here is past the part kept: each credential becomes '[redacted]', so a + * line this long can end up far shorter than EVIDENCE_LINE_MAX, its tail + * kept. So the cut is made safe on its own (see scrubEvidence), and marked. */ +export const SCRUB_INPUT_MAX = 4 * EVIDENCE_LINE_MAX + +/** What a value's characters can be for the shape rules below (base64, base64 + * url, hex, a JWT's dots, a key's dashes). */ +const TOKEN_CHAR = /[A-Za-z0-9+/_=.~-]/ + +/** `s` without its last run of token characters: a value the cut fell in the + * middle of leaves a piece too short for any shape rule, so none of it is + * kept. */ +function withoutTrailingToken(s: string): string { + let end = s.length + while (end > 0 && TOKEN_CHAR.test(s[end - 1])) end-- + return s.slice(0, end) +} /** `text` with every folder, user and token-shaped value of `scrub` put in * its place, cut to EVIDENCE_LINE_MAX after. Folders first (the longest * first, so the data dir wins over the temp folder it is in), then any user - * folder and the account name, then the credentials. */ + * folder and the account name, then the credentials. A line longer than + * SCRUB_INPUT_MAX is cut there before any of that, its last run of token + * characters dropped; and whichever cut was made (that one, or the one at + * EVIDENCE_LINE_MAX), the line ends with '...[cut]'. */ export function scrubEvidence(text: string, scrub: EvidenceScrub): string { - let out = text.slice(0, SCRUB_INPUT_MAX) + const inputCut = text.length > SCRUB_INPUT_MAX + let out = inputCut ? withoutTrailingToken(text.slice(0, SCRUB_INPUT_MAX)) : text const folders = scrub.folders .filter((f): f is { label: string; dir: string } => typeof f.dir === 'string' && f.dir.split(/[\\/]+/).filter(Boolean).length >= 2) .sort((a, b) => b.dir.length - a.dir.length) @@ -115,7 +134,8 @@ export function scrubEvidence(text: string, scrub: EvidenceScrub): string { out = out.replace(WINDOWS_USER_FOLDER, '$1').replace(POSIX_USER_FOLDER, '$1$2') if (scrub.user && scrub.user.length >= 3) out = out.replace(new RegExp(`(?') for (const [re, to] of SECRET_RULES) out = out.replace(re, to) - return out.length > EVIDENCE_LINE_MAX ? `${out.slice(0, EVIDENCE_LINE_MAX)}...[cut]` : out + if (out.length > EVIDENCE_LINE_MAX) return `${out.slice(0, EVIDENCE_LINE_MAX)}...[cut]` + return inputCut ? `${out}...[cut]` : out } /** Main's console lines on the launch path, each with the time the test saw diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts index 65eeabcf9..49136bf2e 100644 --- a/tests/unit/e2e-launch-evidence.test.ts +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -13,7 +13,7 @@ import { describe, it, expect } from 'vitest' import crypto from 'crypto' import { LAUNCH_PATH_PREFIXES, isLaunchPathMessage, appLogRecord, scrubEvidence, launchPathMainLines, launchPathAppLog, - EVIDENCE_LINE_MAX, type EvidenceScrub, + EVIDENCE_LINE_MAX, SCRUB_INPUT_MAX, type EvidenceScrub, } from '../e2e/helpers/launch-evidence' const DATA = 'C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\ccc-e2e-AbC123' @@ -179,6 +179,53 @@ describe('the scrub on its own', () => { expect(out).not.toContain(MCP_CREDENTIAL) }) + describe('a line longer than the scrub reads', () => { + /** An unlabelled base64 value of 44 characters (33 bytes), the same every run. */ + const planted = (n: number): string => Buffer.concat([ + crypto.createHash('sha256').update(`planted-a-${n}`).digest(), + crypto.createHash('sha256').update(`planted-b-${n}`).digest(), + ]).subarray(0, 33).toString('base64') + + /** `[pty]` and values one space apart, laid so that the cut at SCRUB_INPUT_MAX + * falls `into` characters inside one of them. */ + function lineCutInside(into: number): { line: string; values: string[] } { + const first = SCRUB_INPUT_MAX - into + const pad = (first - 6) % 45 + const at = (first - 6 - pad) / 45 + const values = Array.from({ length: at + 20 }, (_, n) => planted(n)) + const line = `[pty]${' '.repeat(1 + pad)}${values.join(' ')}` + expect(line.slice(first, first + 44), 'the planted value is where the test says').toBe(values[at]) + expect(line.length).toBeGreaterThan(SCRUB_INPUT_MAX) + return { line, values } + } + + it('keeps no piece of the value the cut falls in, whatever is left of the line, and says it cut', () => { + for (const into of [1, 9, 17, 24, 31]) { + const { line, values } = lineCutInside(into) + // Each value is what the shape rule takes: a capital and a small letter in it. + expect(values.every((v) => /[A-Z]/.test(v) && /[a-z]/.test(v)), 'every planted value has both cases').toBe(true) + const out = scrubEvidence(line, SCRUB) + // The redactions are shorter than the keys: what is scrubbed ends well under + // EVIDENCE_LINE_MAX, so the output cut alone could never have hidden the tail. + expect(out.length - '...[cut]'.length, `${into}: the redacted line is shorter than what is kept`).toBeLessThan(EVIDENCE_LINE_MAX) + expect(out.endsWith(' ...[cut]'), `${into}: ends with the cut mark, after the last whole redaction: ...${out.slice(-40)}`).toBe(true) + const survivors: string[] = [] + for (const v of values) for (let k = 0; k + 8 <= v.length; k++) if (out.includes(v.slice(k, k + 8))) survivors.push(`${into}: ${v.slice(k, k + 8)}`) + expect(survivors).toEqual([]) + } + }) + + it('a line that is one long run keeps none of it, and says it cut', () => { + expect(scrubEvidence(`[pty] ${'Ab'.repeat(20_000)}`, SCRUB)).toBe('[pty] ...[cut]') + }) + + it('a line the scrub reads whole, and that stays short, is not marked', () => { + const line = `[pty] ${planted(1)} and some words` + expect(line.length).toBeLessThan(SCRUB_INPUT_MAX) + expect(scrubEvidence(line, SCRUB)).toBe('[pty] [redacted] and some words') + }) + }) + it('a long run of letters, with a key word in it or many, is scrubbed in bounded time', () => { const started = performance.now() const out = scrubEvidence(`[pty] ${'x'.repeat(1_500)}token=${'y'.repeat(6_000)}`, SCRUB) From 3611d8ea9a64ed6b05d34d6a4fc94ed23975c85d Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:17:51 +0000 Subject: [PATCH 04/79] test(snap): scrub bare auth and key pairs, e-mail addresses and spaced user names Probes of the evidence scrub found four things that survive it. None has a source in the kept prefixes on the CI runner, which runs as runneradmin with no signed-in account, so this is hardening, not a leak: - a bare auth=value or key=value pair (neither word was in the key alternation); a bare auth or key now counts, alone or as the last part of a key (x-auth, ssh_key), and never inside a word (author, keyboard, monkey); - an e-mail address; one is now taken, tried only where its first word begins and with no slash in it, so a scoped package's path (node_modules\@types\node.js) is not mistaken for one; - the part after the space in another user's folder (C:\Users\Jane Doe\x became C:\Users\ Doe\x); the words of a name are now taken whole when a separator follows them, and a following word of prose is not. URL-encoded paths still survive; that was not asked for and has no source on the launch path either. Each new case is red against the rule it covers put back as it was. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 15 +++++++++++---- tests/unit/e2e-launch-evidence.test.ts | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index 23c72dd7e..f278ef7c0 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -60,8 +60,10 @@ function folderPattern(dir: string): RegExp { } /** A user's folder on Windows (C:\Users\, a doubled backslash or a - * slash too) and on macOS or Linux (/Users/, /home/). */ -const WINDOWS_USER_FOLDER = /([A-Za-z]:(?:\\+|\/+)Users(?:\\+|\/+))([^\\/\s"'<>|:*?;,)\]]+)/gi + * slash too) and on macOS or Linux (/Users/, /home/). A Windows + * name may hold spaces (C:\Users\Jane Doe\x): the words after the first are + * part of it when a separator follows them, else the name is its first word. */ +const WINDOWS_USER_FOLDER = /([A-Za-z]:(?:\\+|\/+)Users(?:\\+|\/+))((?:[^\\/\s"'<>|:*?;,)\]]+ )*[^\\/\s"'<>|:*?;,)\]]+(?=[\\/])|[^\\/\s"'<>|:*?;,)\]]+)/gi const POSIX_USER_FOLDER = /(^|[\s"'=(:;,[/])(\/(?:Users|home)\/)([^/\s"'<>|:;,)\]]+)/g /** Token-shaped values and what stands in their place, in order. */ @@ -74,8 +76,9 @@ const SECRET_RULES: ReadonlyArray = [ [/\b(bearer)(\s+|[\\"']*\s*[:=]\s*[\\"']*)(?!\[redacted\])[^\s\\"',;}\]]+/gi, '$1$2[redacted]'], // key=value, key: value, "key":"value", where the key says what it is // (tried only where a key can begin, so a long run is not tried at every - // character). - [/(?\\/])[^\s@"'<>\\/]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}/g, '[redacted]'], /** What a value's characters can be for the shape rules below (base64, base64 * url, hex, a JWT's dots, a key's dashes). */ const TOKEN_CHAR = /[A-Za-z0-9+/_=.~-]/ diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts index 49136bf2e..40e35febb 100644 --- a/tests/unit/e2e-launch-evidence.test.ts +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -226,6 +226,27 @@ describe('the scrub on its own', () => { }) }) + it('a bare auth or key pair is scrubbed, a key ending in one too, and a word holding one is not', () => { + expect(scrubEvidence('[spawn] auth=abc123 key: "q1w2" x-auth=zzz ssh_key=hhh {"key":"v1"}', SCRUB)) + .toBe('[spawn] auth=[redacted] key: "[redacted]" x-auth=[redacted] ssh_key=[redacted] {"key":"[redacted]"}') + const words = '[spawn] author=jane keyboard=us monkey=banana keys=3' + expect(scrubEvidence(words, SCRUB)).toBe(words) + }) + + it('an e-mail address is scrubbed, a scoped package\'s path is not', () => { + expect(scrubEvidence('[start] mail jane.doe+x@Example.co.uk and and ssh://git@github.com/x', SCRUB)) + .toBe('[start] mail [redacted] and <[redacted]> and ssh://[redacted]/x') + const path = '[path] C:\\x\\node_modules\\@types\\node.js and /x/node_modules/@types/node and @mention' + expect(scrubEvidence(path, SCRUB)).toBe(path) + }) + + it('another user\'s folder is taken whole when the name holds a space, and a following word is not taken for a name', () => { + expect(scrubEvidence('[path] C:\\Users\\Jane Doe\\bin and C:/Users/Mary Ann Smith/x and C:\\\\Users\\\\Jane Doe\\\\y', SCRUB)) + .toBe('[path] C:\\Users\\\\bin and C:/Users//x and C:\\\\Users\\\\\\\\y') + expect(scrubEvidence('[path] cwd=C:\\Users\\bob into D:\\x and C:\\Users\\bob and then /srv/y', SCRUB)) + .toBe('[path] cwd=C:\\Users\\ into D:\\x and C:\\Users\\ and then /srv/y') + }) + it('a long run of letters, with a key word in it or many, is scrubbed in bounded time', () => { const started = performance.now() const out = scrubEvidence(`[pty] ${'x'.repeat(1_500)}token=${'y'.repeat(6_000)}`, SCRUB) From 2698e0a1dcbe97beb689997762653be35a1bb43e Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:18:51 +0000 Subject: [PATCH 05/79] test(snap): say what the launch evidence cannot split, and anchor it at the submit click The helper header promised "the lines main writes between a tab's spawn request and its launch line (pty-handlers.ts pty:spawn and its holds ...)", which reads as a per-hold breakdown that step 2 will not get. Most holds write none on the normal path: awaitScriptFolders and awaitClaudeLaunchWalk are silent; hardenSpawnFoldersAhead ('[spawn] ...') and the start lookup ('[start] ...') write only when they ran out their bound; the launch line is an unlogged 300 ms timer after '[pty-manager] Launching Claude via shell'. Both comments (and the spec's own header) now say it: the artifact gives the holds' total, from the submit click to '[pty] Spawning PTY for session', and then the tab's own PowerShell, from '[pty-manager] Launching Claude via shell' (plus 300 ms) to launches[].at. It names a hold only when that hold ran out its bound. D1 also records readings.submitAt right after the click on the session dialog's submit, on the same Date.now() clock as the lines. That is the start anchor of the whole path; readings.snapButtonAt is set only once the Snap button shows, which depends on the tab itself. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 19 +++++++++++++++---- tests/e2e/snap-windows.spec.ts | 26 ++++++++++++++++++++------ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index f278ef7c0..f2eb3bb8a 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -10,6 +10,17 @@ * anyone, so no user folder, account name, credential or token-shaped value * may stay in what is kept. * + * What the lines can and cannot tell. A hold that ends within its bound writes + * no line: awaitScriptFolders (script-folders.ts) and awaitClaudeLaunchWalk + * (claude-launch-walk.ts) write none at all, and hardenSpawnFoldersAhead + * ('[spawn] ...') and the start's lookup ('[start] ...') write one only when + * they ran out their bound. So the artifact gives the holds' total, from the + * click on the session dialog's submit (readings.submitAt) to '[pty] Spawning + * PTY for session', and then the tab's own PowerShell, from '[pty-manager] + * Launching Claude via shell' (the launch line is typed 300 ms after it, + * pty-manager.ts) to the stand-in's `at`. It names a hold only when that one + * ran out its bound; it does not split the total between holds that did not. + * * No Playwright import, so the unit suite reads this directly * (tests/unit/e2e-launch-evidence.test.ts). */ @@ -96,6 +107,10 @@ const SECRET_RULES: ReadonlyArray = [ // of that alphabet, with a capital and a small letter in it. A folder // written with slashes can be taken too: a lost path, never a kept secret. [/(?\\/])[^\s@"'<>\\/]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}/g, '[redacted]'], ] /** The longest a kept line may be: one runaway line cannot fill the artifact. */ @@ -107,10 +122,6 @@ export const EVIDENCE_LINE_MAX = 2000 * kept. So the cut is made safe on its own (see scrubEvidence), and marked. */ export const SCRUB_INPUT_MAX = 4 * EVIDENCE_LINE_MAX - // An e-mail address (a name is a person's). Tried only where its first word - // begins, and with no slash in it, so a scoped package's path - // (node_modules\@types\node.js) is not taken for one. - [/(?\\/])[^\s@"'<>\\/]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}/g, '[redacted]'], /** What a value's characters can be for the shape rules below (base64, base64 * url, hex, a JWT's dots, a key's dashes). */ const TOKEN_CHAR = /[A-Za-z0-9+/_=.~-]/ diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index 656490dda..51dcc4a44 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -196,9 +196,12 @@ * The readings go to the log and to $SNAP_E2E_OUT/readings.json. Whatever D1 * answers, part one also keeps main's lines about the first tab's start * (aicc_planning#513): $SNAP_E2E_OUT/part1-main-lines.json, its console lines - * at the test's Date.now() (the clock of readings.snapButtonAt and of the - * stand-in's `at`), and part1-app.log, the app's log at main's own times; the - * launch path's lines only, scrubbed (helpers/launch-evidence.ts). + * at the test's Date.now() (the clock of readings.submitAt, readings.snapButtonAt + * and the stand-in's `at`), and part1-app.log, the app's log at main's own + * times; the launch path's lines only, scrubbed (helpers/launch-evidence.ts). + * A hold that ends within its bound writes no line, so these give the holds' + * total and the tab's own PowerShell, and name a hold only when it ran out its + * bound (the header of that file). * * PART TWO, A CODEX TAB WHILE CODEX SHOWS ITS WARNING COUNT (plan * 2.1.3-beta.18, section 7.5; aicc_planning#428). An app of its own, in a @@ -445,7 +448,8 @@ const appLogLines = (): string[] => { const mark = (): Mark => ({ console: mainLines.length, fileLines: appLogLines().length }) /** Part one's console lines, each at the time the test saw it (Date.now(): - * the clock of readings.snapButtonAt and of the stand-in's `at`). */ + * the clock of readings.submitAt, readings.snapButtonAt and the stand-in's + * `at`). */ const part1Main: Array<{ at: number; text: string }> = [] /** aicc_planning#513, step 1: main's lines about the first tab's start, kept @@ -457,6 +461,14 @@ const part1Main: Array<{ at: number; text: string }> = [] * artifact is public. part1-main-lines.json: main's console lines from the * window's start on, each at the test's time. part1-app.log: the app's log * (the file appLogLines reads) from main's own start, each at main's time. + * What they can tell: a hold that ends within its bound writes no line + * (awaitScriptFolders and awaitClaudeLaunchWalk write none at all; + * hardenSpawnFoldersAhead's '[spawn] ...' and the start lookup's '[start] ...' + * are written only when they ran out their bound). So they give the holds' + * total (readings.submitAt to '[pty] Spawning PTY for session') and the tab's + * own PowerShell ('[pty-manager] Launching Claude via shell', the launch line + * typed 300 ms after it, to launches[].at), and name a hold only when it ran + * out its bound. * Never throws: a file not written is said in the job's log, and the app is * closed all the same. */ function writePart1LaunchEvidence(): void { @@ -469,7 +481,7 @@ function writePart1LaunchEvidence(): void { } } write('part1-main-lines.json', () => JSON.stringify({ - clock: 'Date.now() on the runner: the clock of readings.snapButtonAt and of launches[].at', + clock: 'Date.now() on the runner: the clock of readings.submitAt, readings.snapButtonAt and launches[].at', lines: launchPathMainLines(part1Main, scrub), }, null, 2)) write('part1-app.log', () => { @@ -983,10 +995,12 @@ test.describe('Snap on Windows', () => { await page.locator('input[placeholder*="path"]').first().fill(ctx!.dataDir) await page.locator('input[placeholder="e.g. App Dev"]').fill(LABEL) await page.locator('[data-testid="session-dialog-submit"]').click() + // On the clock of the stand-in's `at` and part1-main-lines.json (aicc_planning#513): + // where the tab's start begins, whether or not the Snap button ever shows. + readings.submitAt = Date.now() await expect(page.locator('text=New saved config')).toHaveCount(0, { timeout: TAB_MS }) await expect(snapButton()).toBeVisible({ timeout: TAB_MS }) readings.tabMs = Math.round(performance.now() - started) - // On the clock of the stand-in's `at` and part1-main-lines.json (aicc_planning#513). readings.snapButtonAt = Date.now() // The tab runs the stand-in on a terminal: a Snap's path is typed into it. try { From f6c383ee429e06abac198ae56583927f6a481de3 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:19:04 +0000 Subject: [PATCH 06/79] test(snap): close part one's app in a finally after the evidence is written Part one's afterAll wrote readings.json and the launch evidence, then closed the app. Any throw in the writes (a full disk on mkdirSync or the readings.json write, or os.homedir() inside localEvidenceScrub) skipped closeIsolatedApp and left the tab's shell and the data dir behind. D1's own error would still have been reported, since Playwright reports an afterAll error separately. The writes now sit in a try with closeIsolatedApp and the reset of ctx in its finally. localEvidenceScrub is called inside writePart1LaunchEvidence's own guard, so its "never throws" is literally true: when the scrub cannot be made nothing is written, never a line unscrubbed, and the job's log says so without the error's text (it may name a folder). Co-Authored-By: Claude Opus 5.5 --- tests/e2e/snap-windows.spec.ts | 38 +++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index 51dcc4a44..a387d839b 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -265,7 +265,7 @@ import { seedCodexAccount, realmDirOf, createCodexConfig, openSession, activeSes import { nextFirstScreen, FOOTER, type FirstScreenAnswer } from './helpers/codex-first-screens' import { pathWithoutCodex } from './helpers/fake-codex' import { isolatedHomeDir } from './helpers/isolated-env' -import { launchPathAppLog, launchPathMainLines, localEvidenceScrub, scrubEvidence } from './helpers/launch-evidence' +import { launchPathAppLog, launchPathMainLines, localEvidenceScrub, scrubEvidence, type EvidenceScrub } from './helpers/launch-evidence' /** A Claude Code the app supports (CLAUDE_MIN_MANAGED_CLI_VERSION, as * onboarding-provider-select.spec.ts's stand-in answers). */ @@ -469,10 +469,19 @@ const part1Main: Array<{ at: number; text: string }> = [] * own PowerShell ('[pty-manager] Launching Claude via shell', the launch line * typed 300 ms after it, to launches[].at), and name a hold only when it ran * out its bound. - * Never throws: a file not written is said in the job's log, and the app is - * closed all the same. */ + * Never throws: a file not written is said in the job's log; when the scrub + * itself cannot be made nothing is written (never a line unscrubbed), and + * that is said too; the caller closes the app all the same (the hook's + * finally). */ function writePart1LaunchEvidence(): void { - const scrub = localEvidenceScrub(ctx?.dataDir, path.resolve(__dirname, '../..')) + let scrub: EvidenceScrub + try { + scrub = localEvidenceScrub(ctx?.dataDir, path.resolve(__dirname, '../..')) + } catch { + // Nothing of the error: its message may name a folder. + console.warn('[snap-e2e] part-one launch evidence not written: the scrub could not be made') + return + } const write = (name: string, body: () => string): void => { try { fs.writeFileSync(path.join(OUT, name), body()) @@ -972,14 +981,19 @@ test.describe('Snap on Windows', () => { test.afterAll(async () => { test.setTimeout(120_000) - fs.mkdirSync(OUT, { recursive: true }) - fs.writeFileSync(path.join(OUT, 'readings.json'), JSON.stringify(readings, null, 2)) - console.log(`[snap-e2e] readings ${JSON.stringify(readings)}`) - writePart1LaunchEvidence() - await closeIsolatedApp(ctx) - // Part two shares `ctx`: never leave it naming this closed app, whose - // process id Windows may have given to another program by then. - ctx = undefined + try { + fs.mkdirSync(OUT, { recursive: true }) + fs.writeFileSync(path.join(OUT, 'readings.json'), JSON.stringify(readings, null, 2)) + console.log(`[snap-e2e] readings ${JSON.stringify(readings)}`) + writePart1LaunchEvidence() + } finally { + // Whatever the writes above did (a full disk, say), the tab's shell and + // the data dir are not left behind. + await closeIsolatedApp(ctx) + // Part two shares `ctx`: never leave it naming this closed app, whose + // process id Windows may have given to another program by then. + ctx = undefined + } }) test('D1 START: one Claude Code tab opens and shows the Snap button', async () => { From a05fbf41d73b588dbfc2e1463708f6e2f124614a Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:38:12 +0000 Subject: [PATCH 07/79] test(snap): record the stand-in's starts when part one closes, not only when D1 got far enough The evidence's end anchor, 'the tab's own PowerShell', is the stand-in's `at` in launches.jsonl. Only D1's finally set readings.launches, and that finally is reached only after the Snap button shows. D1's budget (TAB_MS + 10 s) is shared by four waits that can each take TAB_MS: the dialog showing, the dialog closing, the Snap button, and the launch poll. On a slow runner the budget can run out before the try is entered, or the stand-in can start after the poll gave up. Then readings.json carries no launches, and closeIsolatedApp deletes launches.jsonl: the artifact could not say whether the stand-in ever started, or when. afterAll now sets readings.launchesAtClose (the stand-in's records as the app closes) and readings.terminalAtClose (the tab's text then, bounded to 5 s so a page that does not answer cannot stop the close) before readings.json is written. Both have the shape of what readings.launches and readings.terminalAtStart already hold. writePart1LaunchEvidence's comment and the spec's header name them as the anchor that survives every way D1 can end, and the clock note in part1-main-lines.json names them. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/snap-windows.spec.ts | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index a387d839b..2f8a564a4 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -201,7 +201,9 @@ * times; the launch path's lines only, scrubbed (helpers/launch-evidence.ts). * A hold that ends within its bound writes no line, so these give the holds' * total and the tab's own PowerShell, and name a hold only when it ran out its - * bound (the header of that file). + * bound (the header of that file). The stand-in's records are in readings.json + * twice: readings.launches (D1, once the Snap button shows) and + * readings.launchesAtClose (afterAll, whatever D1 did). * * PART TWO, A CODEX TAB WHILE CODEX SHOWS ITS WARNING COUNT (plan * 2.1.3-beta.18, section 7.5; aicc_planning#428). An app of its own, in a @@ -469,6 +471,13 @@ const part1Main: Array<{ at: number; text: string }> = [] * own PowerShell ('[pty-manager] Launching Claude via shell', the launch line * typed 300 ms after it, to launches[].at), and name a hold only when it ran * out its bound. + * The end anchor, 'the tab's own PowerShell', is read two ways. D1's + * readings.launches is set only once the Snap button has shown, and D1's + * budget can run out before that. So afterAll also sets + * readings.launchesAtClose (the stand-in's records as the app closes) and + * readings.terminalAtClose (the tab's text then): the anchor that survives + * every way D1 can end, a stand-in that starts after D1 stopped polling + * included. * Never throws: a file not written is said in the job's log; when the scrub * itself cannot be made nothing is written (never a line unscrubbed), and * that is said too; the caller closes the app all the same (the hook's @@ -490,7 +499,7 @@ function writePart1LaunchEvidence(): void { } } write('part1-main-lines.json', () => JSON.stringify({ - clock: 'Date.now() on the runner: the clock of readings.submitAt, readings.snapButtonAt and launches[].at', + clock: 'Date.now() on the runner: the clock of readings.submitAt, readings.snapButtonAt, and the at of readings.launches and readings.launchesAtClose', lines: launchPathMainLines(part1Main, scrub), }, null, 2)) write('part1-app.log', () => { @@ -982,6 +991,25 @@ test.describe('Snap on Windows', () => { test.afterAll(async () => { test.setTimeout(120_000) try { + // The end anchor of the launch evidence that survives every way D1 can + // end (aicc_planning#513): the stand-in's records and the tab's text as + // they are when the app closes. D1's own readings.launches is set only + // once the Snap button has shown, and D1's budget (TAB_MS + 10 s) can run + // out before that, or the stand-in can start after D1 stopped polling; + // closeIsolatedApp deletes launches.jsonl, so this is the last read. + // The tab's text is bounded: a page that does not answer must not stop + // the app from being closed below. + if (ctx) { + readings.launchesAtClose = launches() + try { + readings.terminalAtClose = await Promise.race([ + terminalText(ctx.page).catch((e: Error) => `unread: ${e.message}`), + new Promise((resolve) => setTimeout(() => resolve('unread: the page did not answer in 5 s'), 5_000)), + ]) + } catch (e) { + readings.terminalAtClose = `unread: ${e instanceof Error ? e.message : String(e)}` + } + } fs.mkdirSync(OUT, { recursive: true }) fs.writeFileSync(path.join(OUT, 'readings.json'), JSON.stringify(readings, null, 2)) console.log(`[snap-e2e] readings ${JSON.stringify(readings)}`) From 2e03ff4c296550ea1fc2ebdc9670a10e41fd498a Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:39:10 +0000 Subject: [PATCH 08/79] test(snap): keep the [canvas-plugin] and [acl] lines of the folders hold's work hardenSpawnFoldersAhead holds a start while it makes ~/.claude and the canvas plugin's tree owner-only. Two kinds of line from that work were not on the launch path's prefix list: - '[canvas-plugin]': ensureCanvasPluginOffThread catches its own failure ('could not materialize ...', and 'could not restrict permissions on ' when an icacls run failed or timed out) and returns null, so foldersAhead's own '[spawn]' catch never fires. The dropped line was the only record of what that hold's work met. - '[acl]': the two notes account-profiles.ts writes from the same off-thread hardening (no user SID; the fallback that could not prove its grant). Step 2 has to name the hold that used the time, and a hold that runs long without hitting its overall bound writes nothing else. Neither line carries a secret (the first names a folder, which the scrub already puts in place; the second is fixed words), and both are written only on a failure. The unit test's prefix loop lists both, a case keeps a planted line of each with its folder put in place, and near-miss prefixes stay out. Each is red with either prefix taken out of the list. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 11 ++++++++--- tests/unit/e2e-launch-evidence.test.ts | 19 ++++++++++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index f2eb3bb8a..63a9acce8 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -28,12 +28,17 @@ import fs from 'fs' import os from 'os' /** The prefixes of main's lines on a local Claude Code tab's way to its - * launch line. The last two are console only (index.ts): the scripts - * folders' check and deploys a launch waits for (awaitScriptFolders). */ + * launch line. '[canvas-plugin]' and '[acl]' are the work inside + * hardenSpawnFoldersAhead's hold: ensureCanvasPluginOffThread catches its own + * failure (canvas-plugin.ts) and returns null, and the ACL notes come from + * the same off-thread hardening (account-profiles.ts), so foldersAhead's own + * '[spawn]' catch never fires for them and these lines are the only record of + * what that hold's work met. The last two are console only (index.ts): the + * scripts folders' check and deploys a launch waits for (awaitScriptFolders). */ export const LAUNCH_PATH_PREFIXES: readonly string[] = [ '[pty]', '[pty-manager]', '[spawn]', '[spawn-claude]', '[scripts]', '[start]', '[profiles]', '[session-helper]', '[launch]', '[jank]', '[path]', '[setup]', '[claude-version]', '[claude-provider]', - '[managed-launch]', + '[managed-launch]', '[canvas-plugin]', '[acl]', '[main] Failed to check the scripts folders', '[main] Failed to deploy the scripts', ] diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts index 40e35febb..f205bbbf2 100644 --- a/tests/unit/e2e-launch-evidence.test.ts +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -90,10 +90,13 @@ describe('which of main\'s lines are kept: the launch path only', () => { for (const p of LAUNCH_PATH_PREFIXES) expect(isLaunchPathMessage(`${p} something`), p).toBe(true) // The holds' and the spawn's own prefixes are all among them. for (const p of ['[pty]', '[pty-manager]', '[spawn]', '[scripts]', '[start]', '[profiles]', '[session-helper]']) expect(LAUNCH_PATH_PREFIXES).toContain(p) + // The work inside hardenSpawnFoldersAhead's hold writes under these, not + // under '[spawn]': ensureCanvasPluginOffThread catches its own failure. + for (const p of ['[canvas-plugin]', '[acl]']) expect(LAUNCH_PATH_PREFIXES).toContain(p) }) it('leaves out every other line, a prefix that only starts like one included', () => { - for (const m of ['[snap] new engine: cancelled; the helper took 12 ms', '[canvas] served', '[pty-integrity] x', '[ptyx] x', 'pty] x', ' [pty] indented', '[main] createWindow failed', '', 'Error: boom']) { + for (const m of ['[snap] new engine: cancelled; the helper took 12 ms', '[canvas] served', '[pty-integrity] x', '[ptyx] x', 'pty] x', ' [pty] indented', '[main] createWindow failed', '', 'Error: boom', '[canvas-plugins] x', '[aclx] x', '[canvas-plug] x']) { expect(isLaunchPathMessage(m), m).toBe(false) } }) @@ -117,6 +120,20 @@ describe('main\'s console lines: kept with the time the test saw them, scrubbed' expectNoneSurvive(allText(kept.map((k) => k.line))) }) + it('keeps what the work inside the folders hold writes when it fails: [canvas-plugin] and [acl], with their folders put in place', () => { + const kept = launchPathMainLines([ + { at: 1, text: `[canvas-plugin] could not restrict permissions on ${DATA}\\resources\\canvas-plugin; it keeps whatever access its parent grants` }, + { at: 2, text: "[canvas-plugin] could not materialize the canvas plugin: Error: EPERM: operation not permitted, mkdir 'C:\\Users\\runneradmin\\x'" }, + { at: 3, text: "[acl] folders were not narrowed to you alone: whoami.exe did not say which account the app runs as, so no folder's rights were changed" }, + { at: 4, text: '[canvas] served' }, + ], SCRUB) + expect(kept).toEqual([ + { at: 1, line: '[canvas-plugin] could not restrict permissions on \\resources\\canvas-plugin; it keeps whatever access its parent grants' }, + { at: 2, line: "[canvas-plugin] could not materialize the canvas plugin: Error: EPERM: operation not permitted, mkdir '\\x'" }, + { at: 3, line: "[acl] folders were not narrowed to you alone: whoami.exe did not say which account the app runs as, so no folder's rights were changed" }, + ]) + }) + it('keeps what a reader needs: prefixes, session ids, the stand-in by name, the times in ms', () => { const kept = launchPathMainLines(PLANTED_MESSAGES.map((text, at) => ({ at, text })), SCRUB).map((k) => k.line) expect(kept[0]).toBe('[profiles] session 0123456789abcdef01234567 account spawn: requestedProfileId=(none) resolvedProfileId=(none/bare-global) shellOnly=false USERPROFILE=\\home') From 17d6be1666e5fbbf2e26372b8d285edbcbd9982a Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:39:41 +0000 Subject: [PATCH 09/79] test(snap): say the evidence's first span is the way to the spawn, and that a hold also writes on a failure Two comments overstated what the artifact gives: - 'readings.submitAt to [pty] Spawning PTY for session' was called the holds' total. The span also holds the renderer's way to pty:spawn (the dialog closing, the tab mounting, the account gate in TerminalView, the IPC) and main's awaits before the holds in the pty:spawn handler. It is now called the way to the spawn: the renderer's request, then main's work before the spawn and the holds. The artifact does not split it between those and the holds that wrote nothing. - hardenSpawnFoldersAhead was said to write '[spawn] ...' only when its holds ran out their bound. foldersAhead also writes one when a folder's hardening or the canvas plugin's materialize throws (spawn-folders-ahead.ts). The comments now say 'ran out their bound or failed'. The helper's header, the spec's header and writePart1LaunchEvidence's comment are corrected the same way. Comments only. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 15 +++++++++------ tests/e2e/snap-windows.spec.ts | 18 ++++++++++-------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index 63a9acce8..89b8021d5 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -14,12 +14,15 @@ * no line: awaitScriptFolders (script-folders.ts) and awaitClaudeLaunchWalk * (claude-launch-walk.ts) write none at all, and hardenSpawnFoldersAhead * ('[spawn] ...') and the start's lookup ('[start] ...') write one only when - * they ran out their bound. So the artifact gives the holds' total, from the - * click on the session dialog's submit (readings.submitAt) to '[pty] Spawning - * PTY for session', and then the tab's own PowerShell, from '[pty-manager] - * Launching Claude via shell' (the launch line is typed 300 ms after it, - * pty-manager.ts) to the stand-in's `at`. It names a hold only when that one - * ran out its bound; it does not split the total between holds that did not. + * they ran out their bound or failed. So the artifact gives the way to the + * spawn, from the click on the session dialog's submit (readings.submitAt) to + * '[pty] Spawning PTY for session': the renderer's request first (the dialog + * closing, the tab mounting, its account gate, the IPC to pty:spawn), then + * main's work before the spawn and the holds. And then the tab's own + * PowerShell, from '[pty-manager] Launching Claude via shell' (the launch line + * is typed 300 ms after it, pty-manager.ts) to the stand-in's `at`. It names a + * hold only when that one ran out its bound or failed; it does not split the + * way to the spawn between the renderer and the holds that did neither. * * No Playwright import, so the unit suite reads this directly * (tests/unit/e2e-launch-evidence.test.ts). diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index 2f8a564a4..f21202d9a 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -199,9 +199,10 @@ * at the test's Date.now() (the clock of readings.submitAt, readings.snapButtonAt * and the stand-in's `at`), and part1-app.log, the app's log at main's own * times; the launch path's lines only, scrubbed (helpers/launch-evidence.ts). - * A hold that ends within its bound writes no line, so these give the holds' - * total and the tab's own PowerShell, and name a hold only when it ran out its - * bound (the header of that file). The stand-in's records are in readings.json + * A hold that ends within its bound writes no line, so these give the way to + * the spawn (the renderer's request, then the holds) and the tab's own + * PowerShell, and name a hold only when it ran out its bound or failed (the + * header of that file). The stand-in's records are in readings.json * twice: readings.launches (D1, once the Snap button shows) and * readings.launchesAtClose (afterAll, whatever D1 did). * @@ -466,11 +467,12 @@ const part1Main: Array<{ at: number; text: string }> = [] * What they can tell: a hold that ends within its bound writes no line * (awaitScriptFolders and awaitClaudeLaunchWalk write none at all; * hardenSpawnFoldersAhead's '[spawn] ...' and the start lookup's '[start] ...' - * are written only when they ran out their bound). So they give the holds' - * total (readings.submitAt to '[pty] Spawning PTY for session') and the tab's - * own PowerShell ('[pty-manager] Launching Claude via shell', the launch line - * typed 300 ms after it, to launches[].at), and name a hold only when it ran - * out its bound. + * are written only when they ran out their bound or failed). So they give the + * way to the spawn (readings.submitAt to '[pty] Spawning PTY for session': + * the renderer's request, then main's work before the spawn and the holds) + * and the tab's own PowerShell ('[pty-manager] Launching Claude via shell', + * the launch line typed 300 ms after it, to launches[].at), and name a hold + * only when it ran out its bound or failed. * The end anchor, 'the tab's own PowerShell', is read two ways. D1's * readings.launches is set only once the Snap button has shown, and D1's * budget can run out before that. So afterAll also sets From 026809128992671a51f873f6c0f199779ac5b785 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:46:32 +0000 Subject: [PATCH 10/79] test(snap): harden the evidence scrub: quoted values, cookies, passphrases, bare names, URL paths, cut e-mails A probe of the evidence scrub found shapes that survive it. None has a source in the kept prefixes on the CI runner (runneradmin, no signed-in account), so this is hardening, not a leak. Each is fixed at its cause: - a quoted value with spaces ("password": "correct horse battery staple" kept 'horse battery staple'): a value that opens with a quote now goes to its closing quote, in plain and in escaped JSON, single or double quotes; - a second cookie (Cookie: session=c1; other=c2secretvalue kept the second pair): the generic rule stops at ';'. A cookie's value now goes to the end of the line or to its quote; - passphrase= (and --passphrase): added to the key words and to the flag rule; - auth or key with no separator before it (oauth=, sshkey=): auth at the end of any name, and key at the end of any name but the few English words that end in it (monkey, turkey, hockey, donkey, jockey, whiskey, lackey, hickey, mickey), now count. Anything else ending in key is redacted, the safer way round; author and keyboard still are not keys; - a URL-encoded home path (C:%5CUsers%5Crunneradmin): the account-name rule's lookbehind failed after '%5C' because the C is alphanumeric, and the user-folder rules knew only raw separators. The name is now a whole word after %5C or %2F, and the Windows and POSIX user-folder rules take %5C, %2F and %3A as separators too; - the local part of an e-mail address that straddles the 8000-character input cut (jane.doe@exa kept 'jane.doe@'): the cut drops the last run of token characters, and neither '@' nor the local part's characters were among them. They are now. The new key rules are built from one KEY_NAME so the quoted, cookie and general rules cannot drift apart. A bounded-time case covers the new rules on long inputs. Each new case is red against its rule put back as it was (twelve mutants: the quoted rule, the cookie rule, passphrase as a key and as a flag, auth and key at the end of a name, the English-word exceptions, the account-name lookbehind, the Windows separators and colon, the POSIX separators, and the cut's token characters); the files restored byte for byte, sha-checked. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 51 ++++++++++++++++------ tests/unit/e2e-launch-evidence.test.ts | 59 ++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 12 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index 89b8021d5..3e4f22c40 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -79,11 +79,30 @@ function folderPattern(dir: string): RegExp { } /** A user's folder on Windows (C:\Users\, a doubled backslash or a - * slash too) and on macOS or Linux (/Users/, /home/). A Windows + * slash too) and on macOS or Linux (/Users/, /home/), each also as + * a URL spells it (the separators %5C and %2F, the colon %3A). A Windows * name may hold spaces (C:\Users\Jane Doe\x): the words after the first are * part of it when a separator follows them, else the name is its first word. */ -const WINDOWS_USER_FOLDER = /([A-Za-z]:(?:\\+|\/+)Users(?:\\+|\/+))((?:[^\\/\s"'<>|:*?;,)\]]+ )*[^\\/\s"'<>|:*?;,)\]]+(?=[\\/])|[^\\/\s"'<>|:*?;,)\]]+)/gi -const POSIX_USER_FOLDER = /(^|[\s"'=(:;,[/])(\/(?:Users|home)\/)([^/\s"'<>|:;,)\]]+)/g +const WINDOWS_USER_FOLDER = /([A-Za-z](?::|%3A)(?:\\+|\/+|%5C|%2F)Users(?:\\+|\/+|%5C|%2F))((?:[^\\/\s"'<>|:*?;,)\]]+ )*[^\\/\s"'<>|:*?;,)\]]+(?=[\\/])|[^\\/\s"'<>|:*?;,)\]]+)/gi +const POSIX_USER_FOLDER = /(^|[\s"'=(:;,[/])((?:\/|%2[Ff])(?:Users|home)(?:\/|%2[Ff]))([^/\s"'<>|:;,)\]]+)/g + +/** The words that make a key's name a credential's. */ +const KEY_WORDS = 'token|secret|passw(?:or)?d|passphrase|pwd|bearer|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie|session[_-]?key' +/** The start of the few English words that end in `key`: a name that ends + * with one of them (monkey, turkey) is a word, not a key. Any other name that + * ends in key counts (sshkey, licenseKey), as the safer way round. */ +const KEY_NOT_WORDS = 'mon|don|tur|hoc|joc|whis|lac|hic|mic' +/** A key's name where it says what it is: a credential word anywhere in it, or + * a bare auth or key, alone or as the last part of a name (x-auth, ssh_key), + * or auth, or key but for KEY_NOT_WORDS, at the end of any name with no + * separator before it (oauth, sshkey); never inside a word (author, + * keyboard). Tried only where a key can begin (KEY_START), so a long run is + * not tried at every character. */ +const KEY_NAME = `(?:[A-Za-z0-9_.-]*(?:${KEY_WORDS})[A-Za-z0-9_.-]*|(?:[A-Za-z0-9_.-]*[_.-])?key|[A-Za-z0-9_.-]*(?:auth|(? = [ @@ -94,12 +113,16 @@ const SECRET_RULES: ReadonlyArray = [ // A bearer credential anywhere. [/\b(bearer)(\s+|[\\"']*\s*[:=]\s*[\\"']*)(?!\[redacted\])[^\s\\"',;}\]]+/gi, '$1$2[redacted]'], // key=value, key: value, "key":"value", where the key says what it is - // (tried only where a key can begin, so a long run is not tried at every - // character). A bare auth or key counts too, alone or as the last part of a - // key (x-auth, ssh_key), never inside a word (author, keyboard, monkey). - [/(? 0 && TOKEN_CHAR.test(s[end - 1])) end-- @@ -158,7 +183,9 @@ export function scrubEvidence(text: string, scrub: EvidenceScrub): string { .sort((a, b) => b.dir.length - a.dir.length) for (const { label, dir } of folders) out = out.replace(folderPattern(dir), label) out = out.replace(WINDOWS_USER_FOLDER, '$1').replace(POSIX_USER_FOLDER, '$1$2') - if (scrub.user && scrub.user.length >= 3) out = out.replace(new RegExp(`(?') + // Whole word only, but a name that follows a separator a URL spells + // (C:%5CUsers%5Crunneradmin, %2Fhome%2Frunneradmin) is a whole word too. + if (scrub.user && scrub.user.length >= 3) out = out.replace(new RegExp(`(?<=^|[^A-Za-z0-9]|%5C|%2F)${escapeRegExp(scrub.user)}(?![A-Za-z0-9])`, 'gi'), '') for (const [re, to] of SECRET_RULES) out = out.replace(re, to) if (out.length > EVIDENCE_LINE_MAX) return `${out.slice(0, EVIDENCE_LINE_MAX)}...[cut]` return inputCut ? `${out}...[cut]` : out diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts index f205bbbf2..be8458adf 100644 --- a/tests/unit/e2e-launch-evidence.test.ts +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -232,6 +232,25 @@ describe('the scrub on its own', () => { } }) + it('keeps no part of an e-mail address the cut falls in, the name before the @ included', () => { + const address = 'jane.doe@example.com' + for (const into of [3, 8, 9, 12, 16, 20]) { + // 88-character values (two of `planted`) one space apart, so that the + // address begins at SCRUB_INPUT_MAX - into and the redacted line stays + // well under EVIDENCE_LINE_MAX: the output cut alone could not hide it. + const first = SCRUB_INPUT_MAX - into + const n = Math.floor((first - 6) / 89) + const pad = first - 6 - 89 * n + const values = Array.from({ length: n }, (_, k) => `${planted(2 * k)}${planted(2 * k + 1)}`) + const line = `[pty]${' '.repeat(1 + pad)}${values.join(' ')} ${address} and then some more words` + expect(line.indexOf(address), 'the address is where the test says').toBe(first) + const out = scrubEvidence(line, SCRUB) + expect(out.length - '...[cut]'.length, `${into}: the redacted line is shorter than what is kept`).toBeLessThan(EVIDENCE_LINE_MAX) + expect(out.endsWith('...[cut]'), `${into}: says it cut`).toBe(true) + expect(out, `${into}: ...${out.slice(-40)}`).not.toMatch(/jane|doe|example|@/i) + } + }) + it('a line that is one long run keeps none of it, and says it cut', () => { expect(scrubEvidence(`[pty] ${'Ab'.repeat(20_000)}`, SCRUB)).toBe('[pty] ...[cut]') }) @@ -250,6 +269,42 @@ describe('the scrub on its own', () => { expect(scrubEvidence(words, SCRUB)).toBe(words) }) + it('a value in quotes is taken to its closing quote, spaces and all, whatever the quote and the escaping', () => { + expect(scrubEvidence('[spawn] {"password": "correct horse battery staple"} and password=\'two words\' next', SCRUB)) + .toBe('[spawn] {"password": "[redacted]"} and password=\'[redacted]\' next') + expect(scrubEvidence('[spawn] {\\"passwd\\": \\"correct horse battery staple\\"} tail', SCRUB)) + .toBe('[spawn] {\\"passwd\\": \\"[redacted]\\"} tail') + // An apostrophe inside a double-quoted value does not end it; an empty value takes nothing after it. + expect(scrubEvidence('[spawn] secret: "it\'s a long phrase" then', SCRUB)).toBe('[spawn] secret: "[redacted]" then') + expect(scrubEvidence('[spawn] token="" next words', SCRUB)).toBe('[spawn] token="" next words') + }) + + it('a cookie is taken whole, every pair of it, to the end of the line or its quote', () => { + expect(scrubEvidence('[spawn] Cookie: session=c1; other=c2secretvalue', SCRUB)).toBe('[spawn] Cookie: [redacted]') + expect(scrubEvidence('[spawn] Set-Cookie: sid=abc123; Path=/; HttpOnly', SCRUB)).toBe('[spawn] Set-Cookie: [redacted]') + expect(scrubEvidence('[spawn] {"cookie":"session=c1; other=c2secretvalue","x":1}', SCRUB)).toBe('[spawn] {"cookie":"[redacted]","x":1}') + }) + + it('a passphrase is scrubbed as a password is, as a key and as a flag', () => { + expect(scrubEvidence('[start] passphrase=hunter2 {"ssh_passphrase":"two words"} --passphrase hunter3', SCRUB)) + .toBe('[start] passphrase=[redacted] {"ssh_passphrase":"[redacted]"} --passphrase [redacted]') + }) + + it('auth or key at the end of a name, with no separator before it, is a key; the English words that end in key, and words that only hold one, are not', () => { + expect(scrubEvidence('[spawn] oauth=abc sshkey=def licenseKey: "lk 1" passkey=h basicauth: z', SCRUB)) + .toBe('[spawn] oauth=[redacted] sshkey=[redacted] licenseKey: "[redacted]" passkey=[redacted] basicauth: [redacted]') + const words = '[spawn] monkey=banana turkey=1 Hockey=2 donkey=3 jockey=4 whiskey=5 lackey=6 author=jane keyboard=us' + expect(scrubEvidence(words, SCRUB)).toBe(words) + }) + + it('a user folder and the account name are taken as a URL spells them (%5C, %2F, %3A) too', () => { + expect(scrubEvidence('[path] C:%5CUsers%5Crunneradmin%5CAppData and C%3A%5CUsers%5Cjane.doe%5Cx and %2Fhome%2Fjane%2Fx and %2FUsers%2Fmary%2Fy', SCRUB)) + .toBe('[path] C:%5CUsers%5C and C%3A%5CUsers%5C and %2Fhome%2F and %2FUsers%2F') + // The account name where no Users folder names it, and only as a whole word. + expect(scrubEvidence('[path] D:%5Cprofiles%5Crunneradmin and %2Fsrv%2FRunnerAdmin%2Fx and xrunneradmin and x5Crunneradmin', SCRUB)) + .toBe('[path] D:%5Cprofiles%5C and %2Fsrv%2F%2Fx and xrunneradmin and x5Crunneradmin') + }) + it('an e-mail address is scrubbed, a scoped package\'s path is not', () => { expect(scrubEvidence('[start] mail jane.doe+x@Example.co.uk and and ssh://git@github.com/x', SCRUB)) .toBe('[start] mail [redacted] and <[redacted]> and ssh://[redacted]/x') @@ -269,6 +324,10 @@ describe('the scrub on its own', () => { const out = scrubEvidence(`[pty] ${'x'.repeat(1_500)}token=${'y'.repeat(6_000)}`, SCRUB) scrubEvidence(`[pty] ${'token'.repeat(4_000)}`, SCRUB) scrubEvidence(`[pty] ${'Ab'.repeat(20_000)}`, SCRUB) + // The quoted-value, cookie and key-name rules too. + scrubEvidence(`[pty] ${'token="'.repeat(1_300)} ${'password: "a '.repeat(600)} ${'cookie: a=b; '.repeat(600)}`, SCRUB) + scrubEvidence(`[pty] ${'sshkey'.repeat(1_300)} ${'oauth'.repeat(1_600)} ${'passphrase'.repeat(800)}`, SCRUB) + scrubEvidence(`[pty] ${'C%3A%5CUsers%5C'.repeat(500)} ${'%5Crunneradmin '.repeat(500)}`, SCRUB) expect(performance.now() - started).toBeLessThan(2_000) expect(out).not.toContain('yyyy') }) From 83fb9dac8de3bdf693cf904bbb5faa94a3e149e5 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:37:29 +0000 Subject: [PATCH 11/79] fix(pty): run a first tab's holds side by side and bound the scripts wait from the check's start The Snap e2e's first Claude Code tab waited 5.4 to 5.5 s from its ask to its spawn (runs 47213031983 and 47213083589). That was the scripts folders' hold running out its 5 s bound, counted from the tab's own ask: the start's owner-only check of the scripts folders is one Windows PowerShell call that takes 8.8 to 13.6 s on a runner's first app, and the tab started without the resume list all the same. The other holds then ran one after another. - script-folders.ts: one deadline for the run, counted from the check's start (scriptFoldersWaitLeft). A launch asked for once it has passed is not held, and no launch waits longer than before. - pty-handlers.ts: the holds run side by side, so a launch waits for the longest, not the sum. The start's look for Claude Code and the walk of PATH stay one after the other, and the session folders' owner-only step and the walk are still asked again once every hold is over. A launch with nothing to hold goes on in the same tick, as before (the one-at-a-time rule relies on that). A sign-in tab is not held for the scripts, since its line runs none. - One [spawn] line per hold of 250 ms or more (its name, its ms, and whether it ran out its bound), and one [pty] line when the launch line is written into the shell. Both carry the session id only. The scripts hold guards nothing: a launch takes a script only through the launch-time checks, which fail closed. The spawn's folders are still made owner-only before it starts. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty-handlers.ts | 110 +++++++++++++++++++++++++---------- src/main/pty-manager.ts | 6 +- src/main/script-folders.ts | 47 ++++++++++++--- 3 files changed, 122 insertions(+), 41 deletions(-) diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index 31aae276b..776b07e82 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -54,7 +54,7 @@ import { CODEX_PRESETS, } from '../sanitize-restored-spawn-options' import { startProfileStepsPending, startProfileStepsSettled } from '../account-profiles' -import { scriptFoldersPending, awaitScriptFolders } from '../script-folders' +import { scriptFoldersPending, scriptFoldersWaitLeft, awaitScriptFolders } from '../script-folders' import { claudeStartLookupPending, awaitClaudeStartLookup } from '../claude-start-lookup' import { claudeLaunchWalkPending, awaitClaudeLaunchWalk } from '../claude-launch-walk' import { gsudoAnswerKept, gsudoLookAnswered } from '../gsudo-lookup' @@ -746,6 +746,31 @@ function codexAccountOwnership(service: AccountsService, accountId: string): 'co } } +/** aicc_planning#513: a hold on the way to a spawn that takes this long or + * longer is said in one line, so a slow first tab can be read from the + * app's log; a start whose holds answer at once writes none. */ +export const SPAWN_HOLD_LOG_MS = 250 + +/** One hold on the way to a spawn (pty:spawn), timed. Once `wait` has + * settled, when it took SPAWN_HOLD_LOG_MS or longer, one line says the hold's + * name, how long it took, and whether what it waited for had come by then + * (`stillWaiting()` true: the wait ended at its bound, or with no answer). + * The line carries the session id and the hold's name, nothing else. + * Rejects only when `wait` does (no hold here does). */ +async function heldFor(sessionId: string, hold: string, wait: Promise, stillWaiting: () => boolean): Promise { + const began = performance.now() + try { + await wait + } finally { + const ms = Math.round(performance.now() - began) + if (ms >= SPAWN_HOLD_LOG_MS) { + try { + logInfo(`[spawn] Session ${sessionId}: held ${ms} ms for ${hold} (${stillWaiting() ? 'not done: it ran out its bound' : 'done'})`) + } catch { /* the launch goes on all the same */ } + } + } +} + /** WP2 PR 4, P4.1: `canvas:sessionGuidance`'s payload: one session id. */ const sessionGuidanceSchema = z.object({ sessionId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/) }).strict() @@ -1068,8 +1093,12 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // resources folder's scripts folders, and the deploys into them, still // run (script-folders.ts) waits for them, bounded, as a prepared spawn, // so a tab restored at start gets its status line, resume list and hooks; - // past the bound it starts without them. - const holdForScripts = launchProvider !== null && !options?.ssh && scriptFoldersPending() + // past the bound it starts without them. The bound is the run's, counted + // from the check's start (scriptFoldersWaitLeft): a launch asked for once + // it has passed is not held for a check that has not come in its usual + // time (aicc_planning#513). A sign-in tab is not held for them: its line + // runs no script of the app's (local-sign-in-tab.ts localSignInLine). + const holdForScripts = launchProvider !== null && !options?.shellOnly && !options?.ssh && scriptFoldersPending() && scriptFoldersWaitLeft() > 0 // On Windows, while the start still looks for Claude Code // (claude-start-lookup.ts: its walk of PATH and, when that finds none, // the PATH refresh, the first Claude Code lookup and the version probe): @@ -1224,11 +1253,38 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void if (Object.keys(secrets).length > 0) resolvedOptions = { ...resolvedOptions, commandSecrets: secrets } } - // The scripts folders (holdForScripts above). Waited for before a Codex - // launch's own wait for its hook folders below: the start wires those - // only after the scripts folders' check and the deploys (index.ts), so - // each wait's bound then covers its own work alone. - if (holdForScripts) await awaitScriptFolders() + // The holds decided above, side by side (aicc_planning#513), so a launch + // waits for the longest of them, not for their sum: each waits for work + // of its own that none of the others reads or writes (the scripts + // folders, the start's profile steps, the start's look for Claude Code, + // the spawn's folders, the look for gsudo.exe). One after another, a + // first tab at start paid every bound in turn. The start's look and the + // launch's own walk of PATH stay one after the other (the start can + // bring PATH up to date, and the walk is for the PATH it leaves). What + // can have changed while they ran is asked again below, once all of + // them are over (the spawn's folders, the walk of PATH). Each is timed + // (heldFor). The scripts folders come before a Codex launch's own wait + // for its hook folders below: the start wires those only after the + // scripts folders' check and the deploys (index.ts), so each wait's + // bound then covers its own work alone. + const holds: Array> = [] + if (holdForScripts) holds.push(heldFor(sessionId, "the scripts folders' check", awaitScriptFolders(), scriptFoldersPending)) + if (holdForStartSteps) holds.push(heldFor(sessionId, "the start's profile steps", startProfileStepsSettled(), startProfileStepsPending)) + if (holdForClaudeLookup) { + holds.push((async () => { + await heldFor(sessionId, "the start's look for Claude Code", awaitClaudeStartLookup(), claudeStartLookupPending) + await heldFor(sessionId, 'the walk of PATH', awaitClaudeLaunchWalk(opensResumeList), () => claudeLaunchWalkPending(opensResumeList)) + })()) + } + if (holdForSpawnFolders) holds.push(heldFor(sessionId, "the session folders' owner-only step", hardenSpawnFoldersAhead(), spawnFoldersWantHardeningAhead)) + // The elevated terminal's look for gsudo.exe (holdForGsudo above), + // bounded by its own deadline; past it the launch is refused by + // buildClaudeLocalSpawn, never by a walk in place. + if (holdForGsudo) holds.push(heldFor(sessionId, 'the look for gsudo.exe', gsudoLookAnswered(), () => !gsudoAnswerKept())) + // Only when something holds: a launch held for nothing goes on in the + // same tick, as before, so a copy asked for in the same tick finds it + // started (the one-at-a-time rule, launch-one-at-a-time.ts). + if (holds.length > 0) await Promise.all(holds) // WP2 (plan A10): a Codex session runs in its account's realm -- the // account the request names, else the provider default -- validated, @@ -1308,14 +1364,9 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void } } - // The start's profile steps (holdForStartSteps above), and the scripts - // folders before them, waited for before the check below, so nothing - // starts for a tab closed meanwhile. - if (holdForStartSteps) await startProfileStepsSettled() - // The start's walk of PATH and, when that found no Claude Code, its - // PATH refresh, first lookup and version probe (holdForClaudeLookup - // above). - if (holdForClaudeLookup) await awaitClaudeStartLookup() + // Every hold above is over by here, so nothing starts for a tab closed + // meanwhile (the check below). + // // The spawn's folders (holdForSpawnFolders above), made owner-only off // the main thread before the spawn writes into them. Asked again here, // as the walk below is, for a session start held for any wait above, @@ -1323,25 +1374,22 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // can have changed while the launch waited for something else (a // folder's ten minutes as proven have run out, or another start has // begun the plugin's rebuild, which this one then joins rather than - // wiping the tree under it at its spawn). hardenSpawnFoldersAhead does - // only what is still wanted, and nothing once all of it is done. It - // waits at most SPAWN_FOLDERS_WAIT_MS (one icacls run's time limit and - // as long again); past that the launch goes on, and the spawn's writers - // do their folders themselves, as before. Before the walk below, not - // after it, so the walk is asked once this wait is over too. - if (preparation && startWritesSpawnFolders) await hardenSpawnFoldersAhead() + // wiping the tree under it at its spawn). Only what is still wanted is + // done, and nothing once all of it is done. It waits at most + // SPAWN_FOLDERS_WAIT_MS (one icacls run's time limit and as long + // again); past that the launch goes on, and the spawn's writers do their + // folders themselves, as before. Before the walk below, not after it, + // so the walk is asked once this wait is over too. + if (preparation && startWritesSpawnFolders && spawnFoldersWantHardeningAhead()) { + await heldFor(sessionId, "the session folders' owner-only step", hardenSpawnFoldersAhead(), spawnFoldersWantHardeningAhead) + } // Then the launch's own walk of PATH, when it has one to make by now: // an answer the start kept meanwhile is read, and nothing is walked. // Asked again here, after every wait above, for any launch held for // any of them: an answer that was recent when the hold was decided - // can have run out while the launch waited for something else. One - // wait after the other, never side by side: the start's own first, - // then this. - if (preparation && localClaudeLaunch) await awaitClaudeLaunchWalk(opensResumeList) - // The elevated terminal's look for gsudo.exe (holdForGsudo above), - // bounded by its own deadline; past it the launch is refused by - // buildClaudeLocalSpawn, never by a walk in place. - if (holdForGsudo) await gsudoLookAnswered() + // can have run out while the launch waited for something else. Never + // side by side with the start's own look: that one first, then this. + if (preparation && localClaudeLaunch) await heldFor(sessionId, 'the walk of PATH', awaitClaudeLaunchWalk(opensResumeList), () => claudeLaunchWalkPending(opensResumeList)) // Closed, swept or superseded while it was prepared: start nothing, and // SAY so. The renderer holds any pty:exit that arrives while its own diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts index 4f693103d..482dd2bde 100644 --- a/src/main/pty-manager.ts +++ b/src/main/pty-manager.ts @@ -6669,12 +6669,12 @@ function spawnPtyResolved( launchWriteScheduled = true launchPendingSessions.add(sessionId) setTimeout(() => { - // Liveness guard (see shell-only branch): the 300ms launch-write can race - // a kill / Restart / app-quit; writing to a dead/replaced PTY from this - // timer would crash main. Only write when our PTY is still registered. + // Liveness guard (see shell-only branch): the 300ms launch-write can race a kill / Restart / app-quit; + // writing to a dead/replaced PTY from this timer would crash main. Only write when our PTY is still registered. if (ptySessions.get(sessionId)?.ptyProcess !== ptyProcess) { abandonLaunchHold(); return } try { ptyProcess.write(escapedCmd + '\r') + logInfo(`[pty] Launch line written into the shell for ${sessionId} (the resume list's script ${pickerScript ? 'ready' : 'not ready'})`) releaseLaunchHold() } catch { abandonLaunchHold() /* session died mid-launch */ } }, 300) diff --git a/src/main/script-folders.ts b/src/main/script-folders.ts index 328e7053c..c9a182053 100644 --- a/src/main/script-folders.ts +++ b/src/main/script-folders.ts @@ -29,7 +29,12 @@ // // A local session launch waits for this, bounded // (awaitScriptFolders, from pty-handlers), so a tab restored at start has its -// scripts; past the bound it starts without them. A folder the rule cannot +// scripts; past the bound it starts without them. The bound is counted from +// the start of this run's check, not from each launch's ask +// (aicc_planning#513): a check still running that long after it began is a +// cold start's, which main saw take 8.8 to 13.6 s on a runner's first app, +// and a launch that waited a bound of its own then started without the +// scripts all the same, its wait spent on nothing. A folder the rule cannot // make owner-only (a network share, a FAT drive) is said once at start, and // the features its scripts serve are skipped for the run; the sessions still // start. @@ -77,7 +82,14 @@ function noRead(a: Asked | undefined): boolean { return !a?.answer || a.answer.unread === true } -/** How long a local launch waits for this run's check and deploys. */ +/** How long after this run's check began a local launch may still wait for + * the check and the deploys (awaitScriptFolders): one deadline for the run, + * never a fresh bound per launch. A launch asked for 3 s into the check + * waits at most 2 s more, and one asked for later is not held for it at all + * (aicc_planning#513). As main saw the check (the owner-only call), it took + * 1.0 to 1.6 s in every later app on a runner and 2.6 to 3.5 s with the + * disk cache purged; a runner's first app, whose first Windows PowerShell + * starts cold, took 8.8 to 13.6 s (CONTEXT.d/2026-11-27-b20-snap-d1.md). */ export const SCRIPT_FOLDERS_LAUNCH_WAIT_MS = 5000 /** How much of the rule's reason a warning carries. */ const DETAIL_MAX = 300 @@ -119,6 +131,9 @@ let phase: Phase = 'idle' let passed = new Map() /** Launches waiting for the deploys to have run. */ let waiters: Array<() => void> = [] +/** When this run's check began (performance.now(), a clock that never goes + * back), or null when none began. */ +let checkBeganAt: number | null = null /** A folder's identity (its volume and file id), or null when the file system * gives none. */ @@ -152,6 +167,7 @@ function scriptFolders(resourcesDir: string): [string, string] { * scripts serve is skipped for the run. Never throws. */ export async function secureScriptFolders(resourcesDir: string, secure: SecureScriptFolders): Promise { phase = 'securing' + checkBeganAt = performance.now() passed = new Map() const refused: Array<{ name: string; why: string }> = [] try { @@ -204,16 +220,32 @@ export function scriptFoldersDeployed(): void { } } -/** Whether this run's check and deploys are still running (a launch that - * starts now waits for them, awaitScriptFolders). */ +/** Whether this run's check and deploys are still running. A launch asked + * for now waits for them only while scriptFoldersWaitLeft() is above 0 + * too (awaitScriptFolders). */ export function scriptFoldersPending(): boolean { return phase === 'securing' || phase === 'deploying' } -/** A local launch: wait, at most `waitMs`, for this run's check and deploys. - * At once when they ran, or when nothing started them. Never rejects. */ +/** How long, at most, a launch asked for now would wait for this run's check + * and deploys: `waitMs` less the time since the check began, never below 0; + * all of `waitMs` when no check began. The deadline is the run's, counted + * from the check's start (SCRIPT_FOLDERS_LAUNCH_WAIT_MS), so a check that + * has run that long holds no launch any more. It says nothing of whether the + * check still runs (scriptFoldersPending). */ +export function scriptFoldersWaitLeft(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_MS): number { + if (checkBeganAt === null) return waitMs + return Math.max(0, checkBeganAt + waitMs - performance.now()) +} + +/** A local launch: wait for this run's check and deploys, at most until + * `waitMs` after the check began (scriptFoldersWaitLeft). At once when they + * ran, when nothing started them, or when that deadline has passed. Never + * rejects. */ export function awaitScriptFolders(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_MS): Promise { if (!scriptFoldersPending()) return Promise.resolve() + const left = scriptFoldersWaitLeft(waitMs) + if (left <= 0) return Promise.resolve() return new Promise((resolve) => { let done = false const finish = (): void => { @@ -222,7 +254,7 @@ export function awaitScriptFolders(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_M clearTimeout(timer) resolve() } - const timer = setTimeout(finish, waitMs) + const timer = setTimeout(finish, left) ;(timer as { unref?: () => void }).unref?.() waiters.push(finish) }) @@ -283,4 +315,5 @@ export function __resetScriptFoldersForTests(): void { phase = 'idle' passed = new Map() waiters = [] + checkBeganAt = null } From 255c4e16b56b2f652104b1f4b501bfb3b7266f94 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:37:29 +0000 Subject: [PATCH 12/79] test(pty): prove a first tab's holds overlap and the scripts wait ends at the run's deadline - pty-spawn-holds-side-by-side.test.ts (new): drives the real pty:spawn handler over the real script-folders module on fake timers. It covers: - the evidence case: a check that never answers, so a tab asked 3 s in starts 2 s later, and one asked past the deadline is not held; - five 5 s + 8 s pairs of holds that spawn at 8 s, not 13 s; - a sign-in tab, and a check that answers in its usual time; - the 250 ms log threshold. - script-folders.test.ts: the run's deadline and scriptFoldersWaitLeft. - pty-claude-picker-plain.test.ts: the launch-line log, with the resume list's script ready and not ready, and no path in the line. All 15 new tests are red on the old source. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- .../unit/main/pty-claude-picker-plain.test.ts | 25 +- .../main/pty-spawn-holds-side-by-side.test.ts | 313 ++++++++++++++++++ tests/unit/main/script-folders.test.ts | 41 ++- 3 files changed, 376 insertions(+), 3 deletions(-) create mode 100644 tests/unit/main/pty-spawn-holds-side-by-side.test.ts diff --git a/tests/unit/main/pty-claude-picker-plain.test.ts b/tests/unit/main/pty-claude-picker-plain.test.ts index 0871c274d..56f0811f1 100644 --- a/tests/unit/main/pty-claude-picker-plain.test.ts +++ b/tests/unit/main/pty-claude-picker-plain.test.ts @@ -21,7 +21,7 @@ import * as os from 'os' import * as path from 'path' const h = vi.hoisted(() => ({ - writes: [] as string[], warns: [] as string[], builds: [] as Array<{ pickerScript?: string | null }>, + writes: [] as string[], warns: [] as string[], infos: [] as string[], builds: [] as Array<{ pickerScript?: string | null }>, files: { settings: '', mcp: '', plugin: '' }, res: '', bin: 'claude', lstat: null as null | ((p: unknown) => unknown), })) @@ -54,7 +54,7 @@ vi.mock('electron', () => ({ safeStorage: { isEncryptionAvailable: () => false }, })) vi.mock('../../../src/main/ipc/setup-handlers', () => ({ getResourcesDirectory: () => h.res, getDataDirectory: () => os.tmpdir(), registerSetupHandlers: () => {}, writeCliSetupPty: () => {} })) -vi.mock('../../../src/main/debug-logger', () => ({ logInfo: () => {}, logWarn: (m: string) => { h.warns.push(String(m)) }, logError: () => {}, logDebug: () => {} })) +vi.mock('../../../src/main/debug-logger', () => ({ logInfo: (m: string) => { h.infos.push(String(m)) }, logWarn: (m: string) => { h.warns.push(String(m)) }, logError: () => {}, logDebug: () => {} })) vi.mock('../../../src/main/spawn-claude-command', async (importOriginal) => { const actual = await importOriginal() return { @@ -130,6 +130,7 @@ beforeEach(() => { h.bin = process.platform === 'win32' ? 'C:\\Users\\u\\.local\\bin\\claude.exe' : 'claude' h.writes = [] h.warns = [] + h.infos = [] h.builds = [] h.lstat = null // As the start does before any launch: the scripts folder made the user's alone. @@ -265,3 +266,23 @@ describe('a fresh local Claude session that does not ask for the resume list', ( expect(h.warns.filter((w) => PICKER_SAID.test(w))).toHaveLength(1) }) }) + +// aicc_planning#513: the moment the launch line goes into the shell is said, +// so a slow first tab's log splits main's part (the holds, the spawn) from +// the shell's own start. It names the session and whether the resume list's +// script was ready, never a path. Mutation to prove this can fail: drop the +// line. +describe('the launch line written into the shell', () => { + const said = (): string[] => h.infos.filter((m) => m.startsWith('[pty] Launch line written')) + it('is said once it is written, with the resume list\'s script ready', async () => { + fs.writeFileSync(picker(), '// picker\n', { mode: 0o600 }) + await launch() + expect(said()).toEqual([`[pty] Launch line written into the shell for ${SID} (the resume list's script ready)`]) + }) + + it('and with it not ready (not deployed yet, as for a first tab started before the scripts folders\' check ended)', async () => { + await launch() + expect(said()).toEqual([`[pty] Launch line written into the shell for ${SID} (the resume list's script not ready)`]) + expect(said().join('')).not.toContain(tmp) + }) +}) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts new file mode 100644 index 000000000..36db68520 --- /dev/null +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -0,0 +1,313 @@ +/** + * aicc_planning#513: the holds pty:spawn puts on a local launch before its + * spawn, on the clock. + * + * The Snap e2e's first Claude Code tab (runs 47213031983 and 47213083589) + * waited 5.4 to 5.5 s in main between its request and its spawn, and then + * started without the resume list: the scripts folders' check (one cold + * Windows PowerShell call at start) had not answered, the tab's wait ran out + * its own 5 s bound, and the other holds ran after it, one after another. + * Here: + * + * - a launch waits for the scripts folders' check at most until the run's + * deadline, counted from the check's start (script-folders.ts + * SCRIPT_FOLDERS_LAUNCH_WAIT_MS), not a bound of its own from its ask; + * - the holds it was held for run side by side, so it waits for the longest + * of them, not their sum; + * - a sign-in tab is not held for the scripts folders, whose scripts it never + * runs; + * - each hold that took SPAWN_HOLD_LOG_MS or longer says so in one line. + * + * Driven through the REAL pty:spawn handler on a fake ipcMain, with the REAL + * scripts-folders module (its check over a stand-in rule that never answers, + * on a fresh temp folder). The other holds are stand-ins that end on the + * fake clock; pty-manager is faked (a Set of session ids with a PTY, one of + * spawns it is still preparing), so nothing spawns, no PowerShell starts and + * no folder's access list is read or changed. setTimeout, clearTimeout, + * performance and Date are fake; setImmediate is real. + */ +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest' +import nodeFs from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' + +const handlers = new Map unknown>() +vi.mock('electron', () => ({ + ipcMain: { handle: (ch: string, fn: (...a: unknown[]) => unknown) => { handlers.set(ch, fn) }, on: (ch: string, fn: (...a: unknown[]) => unknown) => { handlers.set(ch, fn) } }, + BrowserWindow: class {}, + app: { getVersion: () => '0.0.0-test' }, +})) +const live = new Set() +const pending = new Set() +/** Each spawn that ran: its session id and when (the fake performance clock). */ +const spawned: Array<{ sid: string; at: number }> = [] +let preparations = 0 +const spawnNow = (sid: string): void => { live.add(sid); spawned.push({ sid, at: performance.now() }) } +vi.mock('../../../src/main/pty-manager', () => ({ + spawnPty: (_w: unknown, s: string) => spawnNow(s), + writePty: vi.fn(), resizePty: vi.fn(), + killPty: (id: string) => { live.delete(id); pending.delete(id) }, + getSshFlow: () => undefined, endSshRemote: vi.fn(), + beginSpawnPreparation: (_w: unknown, sid: string) => { + preparations += 1 + pending.add(sid) + return { get current() { return pending.has(sid) }, spawn: () => { pending.delete(sid); spawnNow(sid) }, abandon: () => { pending.delete(sid) } } + }, + isSessionWritable: (id: string) => live.has(id), + isSessionLiveOrStarting: (id: string) => live.has(id) || pending.has(id), + endAgentRunsInFolder: async () => true, + getKeptCodexConversationSource: () => undefined, + getKeptCodexConversation: () => undefined, + holdsCodexLaunchLease: () => false, + codexLaunchLeaseTaken: () => false, +})) +/** The other holds, as their modules time them (each stand-in on the fake clock): + * - the session folders' owner-only step does its work from the call + * (spawn-folders-ahead.ts hardenSpawnFoldersAhead starts it there), `ms` + * of it; + * - the start's profile steps run from the start (index.ts), whoever waits, + * and end at `settled`; + * - the start's look for Claude Code runs from the start too, and here never + * answers: a launch's wait ends at its own bound, `ms` from the call + * (claude-start-lookup.ts awaitClaudeStartLookup). */ +const holds = vi.hoisted(() => ({ + folders: { want: false, ms: 0 }, + steps: { pending: false, settled: Promise.resolve() as Promise }, + lookup: { pending: false, ms: 0 }, +})) +/** `ms` from now on the fake clock, then `end`. */ +const endsIn = (ms: number, end: () => void = () => {}): Promise => + new Promise((resolve) => { setTimeout(() => { end(); resolve() }, ms) }) +vi.mock('../../../src/main/spawn-folders-ahead', () => ({ + spawnFoldersWantHardeningAhead: () => holds.folders.want, + // With nothing wanted, done at once, as the real one is. + hardenSpawnFoldersAhead: () => (holds.folders.want ? endsIn(holds.folders.ms, () => { holds.folders.want = false }) : Promise.resolve()), +})) +vi.mock('../../../src/main/claude-launch-walk', () => ({ + armClaudeLaunchWalk: () => {}, + claudeLaunchWalkPending: () => false, + awaitClaudeLaunchWalk: async () => {}, +})) +vi.mock('../../../src/main/account-profiles', async (importOriginal) => ({ + ...(await importOriginal()), + startProfileStepsPending: () => holds.steps.pending, + startProfileStepsSettled: () => holds.steps.settled, +})) +vi.mock('../../../src/main/claude-start-lookup', async (importOriginal) => ({ + ...(await importOriginal()), + claudeStartLookupPending: () => holds.lookup.pending, + awaitClaudeStartLookup: () => endsIn(holds.lookup.ms), +})) +const logged = vi.hoisted(() => [] as string[]) +vi.mock('../../../src/main/debug-logger', () => ({ logInfo: (m: string) => { logged.push(String(m)) }, logWarn: vi.fn(), logError: vi.fn() })) +vi.mock('../../../src/main/debug-capture', () => ({ logUserInput: vi.fn(), isDebugModeEnabled: () => false })) +vi.mock('../../../src/main/legacy-version-manager', () => ({ isVersionInstalled: () => true, installVersion: vi.fn(async () => ({ ok: true })) })) +vi.mock('../../../src/main/services/pty-integrity-monitor', () => ({ getPtyIntegrityMonitor: () => ({ record: vi.fn(), report: vi.fn() }) })) +vi.mock('../../../src/main/canvas/canvas-session-link', () => ({ noteSessionSpawnForCanvas: vi.fn() })) +vi.mock('../../../src/main/help-workspace', () => ({ ensureHelpWorkspace: vi.fn(() => '/res/help'), helpWorkspaceDir: (dir: string) => `${dir}/help` })) +vi.mock('../../../src/main/ipc/setup-handlers', () => ({ getResourcesDirectory: () => '/res' })) +vi.mock('../../../src/main/config-manager', () => ({ readConfig: () => null })) +vi.mock('../../../src/main/credential-store', () => ({ loadCredential: () => null })) +vi.mock('../../../src/main/hooks', async (importOriginal) => ({ + ...(await importOriginal()), + getGateway: () => null, +})) +vi.mock('../../../src/main/provider-accounts', () => ({ + getAccountsService: () => ({ launchRefusal: () => null, remoteLaunchRefusal: () => null, snapshot: () => ({ accounts: [] }) }), +})) + +// The scripts folders' check itself: not a stand-in. +const { secureScriptFolders, scriptFoldersDeployed, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS } = await import('../../../src/main/script-folders') +const { registerPtyHandlers } = await import('../../../src/main/ipc/pty-handlers') +registerPtyHandlers(() => ({} as never)) +const spawn = handlers.get('pty:spawn')! +// Claude Code's accounts sign in in a tab on this computer +// (SessionProvider.localSignInTab, asked by local-sign-in-tab.ts), so the real +// rule makes the sign-in tab below a Claude Code launch, as in the app. +const { registerProvider } = await import('../../../src/main/providers/core') +registerProvider({ id: 'claude', localSignInTab: true } as unknown as Parameters[0]) + +const S = 'c1d2e3f4a5b6c1d2e3f4a5b6' +const CLAUDE_TAB = { cwd: 'C:/w' } +/** A sign-in tab on this computer (useAddAccount, useReauthAccount). */ +const SIGN_IN_TAB = { cwd: 'C:/w', shellOnly: true, provider: 'claude', localAccountSignIn: true, profileId: 'p1' } + +const PREFIX = 'ccc-spawn-holds-' +const made: string[] = [] +/** A fresh resources folder for the real check (it makes the folder; the rule reads nothing). */ +function resourcesFolder(): string { + const dir = nodeFs.realpathSync.native(nodeFs.mkdtempSync(join(tmpdir(), PREFIX))) + made.push(dir) + return dir +} +/** The start's check of the scripts folders, begun now, whose owner-only + * call never answers: a cold Windows PowerShell that has not come back. */ +function aCheckThatNeverAnswers(): void { + void secureScriptFolders(resourcesFolder(), () => new Promise(() => {})) +} + +const outcome = async (p: unknown): Promise => { + try { + const r = await p as { refused?: { code?: string }; started?: boolean } | undefined + return r?.refused?.code ?? (r?.started === false ? 'not-started' : 'started') + } catch (e) { + return `threw: ${(e as Error).message}` + } +} +/** Let every promise the handler waits on, other than the fake clock, settle (setImmediate is real). */ +const settle = async (): Promise => { for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r)) } +/** What a spawn has answered by now; 'still held' while it waits. */ +const asItStands = (p: Promise): Promise => Promise.race([p, settle().then(() => 'still held')]) +/** Move the fake clock on by `ms`, running what falls due, then let the handler go on. */ +const after = async (ms: number): Promise => { await vi.advanceTimersByTimeAsync(ms); await settle() } + +/** Each hold, made to take `ms` for a launch asked for now. */ +const HOLDS: Record void> = { + "the scripts folders' check": (ms) => { + // The real check, begun now, whose call never answers: a launch asked for + // now is held to its deadline, which is this test's 5 s. + expect(ms).toBe(SCRIPT_FOLDERS_LAUNCH_WAIT_MS) + aCheckThatNeverAnswers() + }, + "the session folders' owner-only step": (ms) => { holds.folders.want = true; holds.folders.ms = ms }, + "the start's profile steps": (ms) => { holds.steps.pending = true; holds.steps.settled = endsIn(ms, () => { holds.steps.pending = false }) }, + "the start's look for Claude Code": (ms) => { holds.lookup.pending = true; holds.lookup.ms = ms }, +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'] }) + live.clear(); pending.clear(); spawned.length = 0; preparations = 0 + logged.length = 0 + holds.folders.want = false; holds.folders.ms = 0 + holds.steps.pending = false; holds.steps.settled = Promise.resolve() + holds.lookup.pending = false; holds.lookup.ms = 0 + __resetScriptFoldersForTests() +}) +afterEach(() => { + vi.useRealTimers() + __resetScriptFoldersForTests() +}) +afterAll(() => { + // TEST CLEANUP GUARD: only this suite's own folders, by their prefix and parent. + const root = join(nodeFs.realpathSync.native(tmpdir()), PREFIX) + for (const dir of made) if (dir.startsWith(root)) nodeFs.rmSync(dir, { recursive: true, force: true }) +}) + +describe('the scripts folders\' check, when it does not come in its usual time (the Snap e2e\'s first tab)', () => { + // Mutation to prove this can fail: count the bound from the launch's ask + // (script-folders.ts awaitScriptFolders: setTimeout(finish, waitMs)). The + // launch then waits 5 s of its own and starts at 8 s, without the scripts + // all the same. + it('a tab asked for 3 s into the check starts 2 s later, at the run\'s deadline, not 5 s later', async () => { + aCheckThatNeverAnswers() + await after(3000) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS - 3000 - 1) + expect(await asItStands(started), 'held for the check until its deadline').toBe('still held') + expect(preparations).toBe(1) + await after(1) + expect(await asItStands(started), 'started at the run\'s deadline, 5 s after the check began').toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + 2000 }]) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 2000 ms for the scripts folders' check (not done: it ran out its bound)`, + ]) + }) + + // Mutation to prove this can fail: hold whenever the check still runs + // (drop scriptFoldersWaitLeft() > 0 from holdForScripts, and count the + // bound from the ask). + it('a tab asked for once the run\'s deadline has passed is not held for it at all', async () => { + aCheckThatNeverAnswers() + await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS + 1000) + expect(await asItStands(outcome(spawn({}, S, CLAUDE_TAB)))).toBe('started') + expect(preparations, 'not even a prepared spawn').toBe(0) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([]) + }) + + // What the hold is for is kept: a check that comes in its usual time is + // waited for. Mutation to prove this can fail: never hold for the check. + it('a check that answers in its usual time is still waited for, and the tab starts once it and the deploys have run', async () => { + let answer = (): void => {} + const began = performance.now() + const checked = secureScriptFolders(resourcesFolder(), (dirs) => new Promise((resolve) => { + answer = () => resolve(dirs.map((d) => { nodeFs.mkdirSync(d, { recursive: true }); return { dir: d, ok: true } })) + })) + await after(500) + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(1000) + expect(await asItStands(started), 'held for the check').toBe('still held') + answer() + await checked + expect(await asItStands(started), 'and for the deploys after it').toBe('still held') + scriptFoldersDeployed() + expect(await asItStands(started)).toBe('started') + expect(spawned, 'started as the deploys ended, 1.5 s after the check began').toEqual([{ sid: S, at: began + 1500 }]) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 1000 ms for the scripts folders' check (done)`, + ]) + }) + + // A sign-in tab runs Claude Code with no settings and no resume list + // (local-sign-in-tab.ts localSignInLine): none of the scripts the check + // is for. Mutation to prove this can fail: drop !options?.shellOnly from + // holdForScripts. + it('a sign-in tab is not held for it', async () => { + aCheckThatNeverAnswers() + await after(1000) + expect(await asItStands(outcome(spawn({}, S, SIGN_IN_TAB)))).toBe('started') + expect(preparations).toBe(0) + }) +}) + +describe('the holds a first tab is held for run side by side: it waits for the longest, not the sum', () => { + // One after another, a hold whose clock starts at its own call (a bound, + // or work begun there) began only once the hold before it was over, and + // the first tab paid both: in the evidence, the scripts folders' 5 s, then + // the session folders' work. Mutation to prove each can fail: await the + // holds one after another, as before #513 (the spawn then runs at 13 s). + const pairs: Array<[string, string]> = [ + // The evidence's pair: the scripts folders' check (a launch held to its + // deadline) and the session folders made owner-only. + ["the scripts folders' check", "the session folders' owner-only step"], + ["the scripts folders' check", "the start's look for Claude Code"], + ["the start's look for Claude Code", "the session folders' owner-only step"], + ["the start's profile steps", "the session folders' owner-only step"], + ["the start's profile steps", "the start's look for Claude Code"], + ] + for (const [fiveSeconds, eightSeconds] of pairs) { + it(`${fiveSeconds} (5 s) and ${eightSeconds} (8 s): the spawn runs at 8 s, not 13 s`, async () => { + HOLDS[fiveSeconds](5000) + HOLDS[eightSeconds](8000) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(7999) + expect(await asItStands(started)).toBe('still held') + await after(1) + expect(await asItStands(started), 'started when the longer hold ended').toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + 8000 }]) + // One line for each, with its own time. + const lines = logged.filter((l) => l.startsWith('[spawn]')) + expect(lines).toHaveLength(2) + expect(lines.find((l) => l.includes(`for ${fiveSeconds} (`))).toContain(`held 5000 ms for ${fiveSeconds} (`) + expect(lines.find((l) => l.includes(`for ${eightSeconds} (`))).toContain(`held 8000 ms for ${eightSeconds} (`) + }) + } +}) + +describe('what is said of the holds', () => { + // Mutation to prove this can fail: say every hold, whatever it took (the + // usual start would then write a line per launch). + it('a hold that took less than SPAWN_HOLD_LOG_MS says nothing; one that took that long or longer says its name, its time and whether it ran out', async () => { + const { SPAWN_HOLD_LOG_MS } = await import('../../../src/main/ipc/pty-handlers') + HOLDS["the start's profile steps"](SPAWN_HOLD_LOG_MS - 1) + HOLDS["the session folders' owner-only step"](SPAWN_HOLD_LOG_MS) + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(SPAWN_HOLD_LOG_MS) + expect(await asItStands(started)).toBe('started') + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held ${SPAWN_HOLD_LOG_MS} ms for the session folders' owner-only step (done)`, + ]) + expect(SPAWN_HOLD_LOG_MS).toBe(250) + }) +}) diff --git a/tests/unit/main/script-folders.test.ts b/tests/unit/main/script-folders.test.ts index da8b81e81..f4d2005ba 100644 --- a/tests/unit/main/script-folders.test.ts +++ b/tests/unit/main/script-folders.test.ts @@ -30,7 +30,7 @@ vi.mock('../../../src/main/debug-logger', () => ({ })) import { - secureScriptFolders, scriptFoldersDeployed, scriptFoldersPending, awaitScriptFolders, scriptFolderRefusal, + secureScriptFolders, scriptFoldersDeployed, scriptFoldersPending, scriptFoldersWaitLeft, awaitScriptFolders, scriptFolderRefusal, checkDeployedScript, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS, } from '../../../src/main/script-folders' import type { SecureScriptFolders } from '../../../src/main/script-folders' @@ -436,4 +436,43 @@ describe('awaitScriptFolders: a local launch waits for the start, bounded', () = expect(done).toBe(true) expect(SCRIPT_FOLDERS_LAUNCH_WAIT_MS).toBe(5000) }) + + // aicc_planning#513: the bound is the run's, counted from the check's start, + // not a fresh one from each launch's ask. Mutation to prove this can fail: + // count it from the ask (setTimeout(finish, waitMs)). + it('a launch asked for 3 s into a check that has not answered waits only to 5 s after the check began', async () => { + vi.useFakeTimers() + void secureScriptFolders(res, () => new Promise(() => {})) + await vi.advanceTimersByTimeAsync(3000) + let done = false + void awaitScriptFolders().then(() => { done = true }) + await vi.advanceTimersByTimeAsync(1999) + expect(done).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(done, 'ended at the run\'s deadline').toBe(true) + expect(scriptFoldersPending(), 'the check itself still runs').toBe(true) + }) + + // Mutation to prove this can fail: count the bound from the ask. + it('past the run\'s deadline a launch does not wait at all, though the check still runs', async () => { + vi.useFakeTimers() + void secureScriptFolders(res, () => new Promise(() => {})) + await vi.advanceTimersByTimeAsync(SCRIPT_FOLDERS_LAUNCH_WAIT_MS + 1) + expect(scriptFoldersPending()).toBe(true) + let done = false + void awaitScriptFolders().then(() => { done = true }) + await vi.advanceTimersByTimeAsync(0) + expect(done).toBe(true) + }) + + it('the wait left: the whole bound with no check begun, less the time since it began, never below 0', async () => { + expect(scriptFoldersWaitLeft()).toBe(SCRIPT_FOLDERS_LAUNCH_WAIT_MS) + expect(scriptFoldersWaitLeft(10)).toBe(10) + vi.useFakeTimers() + void secureScriptFolders(res, () => new Promise(() => {})) + await vi.advanceTimersByTimeAsync(3000) + expect(scriptFoldersWaitLeft()).toBe(2000) + await vi.advanceTimersByTimeAsync(3000) + expect(scriptFoldersWaitLeft()).toBe(0) + }) }) From a26047b3515e0dcde1e19dff2bafc88f0a21f6ed Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:37:30 +0000 Subject: [PATCH 13/79] docs(context): record the Snap D1 first-tab wait, its cause and the fix Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 90 +++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 CONTEXT.d/2026-12-03-b28-snap-d1-holds.md diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md new file mode 100644 index 000000000..a071f3f46 --- /dev/null +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -0,0 +1,90 @@ +## 2026-12-03 -- Snap e2e D1: the first tab waited out the scripts folders' 5 s bound (aicc_planning#513, step 2) + +Branch `fix/b28-snap-d1-evidence`, from beta at 591eb8fb (2.1.3-beta.27). Step 1 +(the evidence capture in the Snap e2e's part one) is the `test(snap)` commits +before this entry; this is step 2, the fix at the cause. + +### Evidence + +Two dispatches of the Snap e2e (windows-2025) with the capture: 47213031983 +(green) and 47213083589 (forced red). Times are the runner's clock. + +| | green 47213031983 | forced red 47213083589 | +|---|---|---| +| main's first line to the Claude Code tab asked for (submit) | 2.9 s | 2.8 s | +| submit to `[pty] Spawning PTY` | 5502 ms | 5400 ms | +| spawn to the launch line's hold released (`Replaying 1 buffered write`) | 401 ms | 335 ms | +| spawn to the stand-in Claude Code started | 5232 ms | (forced red) | + +`[claude-version]` was logged before the submit in both runs, so the start's +look for Claude Code was over. In the forced red's terminal the launch line +was the direct one (`& '...claude.cmd'`), though the launch asked for the +resume list (`resumePicker=true`), and no line said the list was skipped. +`getResumePickerPath` (pty-manager.ts) returns null without a word only when +`resume-picker.js` is not there: the deploys had not run yet. + +### Cause + +The scripts folders' hold (`awaitScriptFolders`, script-folders.ts) holds a +local launch until the start's owner-only check of the scripts folders and the +deploys after it have run (index.ts), at most `SCRIPT_FOLDERS_LAUNCH_WAIT_MS` +(5 s), counted from each launch's own ask. Only `scriptFoldersDeployed()`, at +the end of that chain, ends it early. The check is one Windows PowerShell call; +on a runner's first app it takes 8.8 to 13.6 s (2026-11-27-b20-snap-d1.md), and +the tab is asked for about 3 s after main starts. So the hold always ran out +its full 5 s, and the tab started without the scripts all the same: the wait +bought nothing. The other holds ran after it, one after another; with the +IPC they took the remaining 0.4 to 0.5 s (not split: no line said them). + +Who meets it: a tab asked for while the check runs (tabs restored at start, or +one opened in the first seconds). Where Windows PowerShell is warm the check +took 1.0 to 1.6 s on the runner (2.6 to 3.5 s with the disk cache purged); the +tab waits that long and gets its status line and resume list. Where the check +runs past 5 s (a slow cold start), every such tab waited 5 s from its own ask +and started without them. A tab asked for once the check is over waits for +nothing. + +### Fix + +- script-folders.ts: the bound is the run's, counted from the check's start + (`scriptFoldersWaitLeft`). A tab asked 3 s into the check waits at most 2 s; + one asked once the deadline has passed is not held at all. No launch waits + longer than before. +- pty-handlers.ts: the holds a launch is held for run side by side + (`Promise.all`), so it waits for the longest, not the sum. The start's look + for Claude Code and the launch's walk of PATH stay one after the other. The + session folders' owner-only step and the walk are asked again once every hold + is over, as before. With nothing to hold, the launch still goes on in the same + tick (the one-at-a-time rule relies on that). A sign-in tab is not held for + the scripts: its line runs none of them. +- Logging: `[spawn] Session : held ms for (done | not done: it + ran out its bound)`, one line per hold that took 250 ms or longer, and + `[pty] Launch line written into the shell for (the resume list's script + ready | not ready)`. Both carry the session id and nothing else. The Snap + evidence filter keeps both prefixes, so the next red can be split. + +Safety is unchanged. The scripts hold guards nothing: a launch takes a script +only through `checkDeployedScript` / `scriptFolderRefusal` at launch time, and +a folder not yet checked fails closed (the feature is skipped). The session +folders are still made owner-only before the spawn, and each writer still +makes its own folder owner-only before it writes. + +### Tests + +- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 10): the real + pty:spawn handler over the real script-folders module, on fake timers. + Covers the evidence case (a check that never answers: the tab asked 3 s in + starts 2 s later; asked past the deadline, not held), five 5 s + 8 s pairs + that spawn at 8 s rather than 13 s, sign-in tabs, a check that answers in its + usual time, and the 250 ms log threshold. +- `tests/unit/main/script-folders.test.ts` (+3): the run's deadline. +- `tests/unit/main/pty-claude-picker-plain.test.ts` (+2): the launch-line log. +- All 15 new tests fail on the old code (source stashed, restored, sha-checked). + Mutants each turn the matching tests red: bound from the ask, holds one after + another, the look and the walk side by side, no re-ask of the folders or of + the walk, sign-in tabs held, logging every hold, the launch-line log dropped, + and an await with nothing to hold. + +Not measured: the split of the remaining 0.4 to 0.5 s. The tab's own Windows +PowerShell start (5.2 s from spawn to the stand-in in the green run) is the +runner's cold start, outside these holds. From bf9479dda31d64dd2894237abee7363898cbee8d Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:11 +0000 Subject: [PATCH 14/79] test(pty): drop the Codex stubs the side-by-side holds test never reaches The test drives Claude Code launches only, so it needs none of pty-manager's Codex calls, and without them it names no Codex (WP1 predicate P13). Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- tests/unit/main/pty-spawn-holds-side-by-side.test.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index 36db68520..834c05cd8 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -56,10 +56,6 @@ vi.mock('../../../src/main/pty-manager', () => ({ isSessionWritable: (id: string) => live.has(id), isSessionLiveOrStarting: (id: string) => live.has(id) || pending.has(id), endAgentRunsInFolder: async () => true, - getKeptCodexConversationSource: () => undefined, - getKeptCodexConversation: () => undefined, - holdsCodexLaunchLease: () => false, - codexLaunchLeaseTaken: () => false, })) /** The other holds, as their modules time them (each stand-in on the fake clock): * - the session folders' owner-only step does its work from the call From f4bc7b4d0c7eb3dd8fec9c343ecc7ba2badf64ac Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:27 +0000 Subject: [PATCH 15/79] chore(wp1): refresh the legacy Codex manifest after the first-tab holds fix The new test file and the context fragment move the tracked, scanned and excluded file counts and the manifest head. No matched path and no predicate hit changed (pathDigest 968553bf, ledger complete in the candidate phase). Co-Authored-By: Claude Opus 5.5 --- docs/wp1/legacy-codex-manifest.json | 12 ++++++------ tests/wp1/legacy-codex-ledger.json | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/wp1/legacy-codex-manifest.json b/docs/wp1/legacy-codex-manifest.json index 26306b876..a24ca7b5c 100644 --- a/docs/wp1/legacy-codex-manifest.json +++ b/docs/wp1/legacy-codex-manifest.json @@ -1,8 +1,8 @@ { "schema": "wp1-legacy-codex-manifest/3", - "generatedAt": "2026-12-03T20:52:42.578Z", - "head": "c4bb9d58d69d92485c014ef884b968abf046c617", - "tree": "7a09be349d98a2d2a136c9e7051dbaa915c882d4", + "generatedAt": "2026-12-03T22:38:19.883Z", + "head": "bf9479dda31d64dd2894237abee7363898cbee8d", + "tree": "f9e9d4ea47708a02d20b22752e5b2760beddd260", "scannedWorkingTree": false, "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "predicates": [ @@ -116,9 +116,9 @@ "\\.(png|jpg|jpeg|gif|ico|icns|webp|svg|woff2?|ttf|otf|mp4|zip|asar|node|exe|dll|dylib|so|pdf)$", "^package-lock\\.json$" ], - "trackedFileCount": 4328, - "excludedFileCount": 725, - "scannedFileCount": 3603, + "trackedFileCount": 4330, + "excludedFileCount": 726, + "scannedFileCount": 3604, "unscopedFileCount": 15, "unscoped": [ ".claude/settings.json", diff --git a/tests/wp1/legacy-codex-ledger.json b/tests/wp1/legacy-codex-ledger.json index e04ed657a..b2838fd1c 100644 --- a/tests/wp1/legacy-codex-ledger.json +++ b/tests/wp1/legacy-codex-ledger.json @@ -2,7 +2,7 @@ "schema": "wp1-legacy-codex-ledger/2", "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "manifestPathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", - "manifestHead": "c4bb9d58d69d92485c014ef884b968abf046c617", + "manifestHead": "bf9479dda31d64dd2894237abee7363898cbee8d", "dispositions": { "retain": "unchanged observable behaviour, characterization proof", "move": "moved behind a package boundary and/or adapted at the call site, regression proof (newPath when relocated)", From 3eb19ddc18592d971855aed26a01eca674006f09 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:41:35 +0000 Subject: [PATCH 16/79] test(pty): read the start's profile steps as one of the side-by-side holds - account-profiles-owner-only-wiring.test.ts: the steps are now one of the holds a launch awaits together before the closed-or-superseded check. The test reads that shape (pushed as a hold, all holds awaited, then the check) instead of the old serial await. Mutation that turns it red: hold for the steps without awaiting them. - pty-spawn-holds-side-by-side.test.ts: two more pairs where the steps are the longer hold (8 s), so a launch that names no account is shown to wait for them in full. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- .../main/account-profiles-owner-only-wiring.test.ts | 11 ++++++++--- tests/unit/main/pty-spawn-holds-side-by-side.test.ts | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/unit/main/account-profiles-owner-only-wiring.test.ts b/tests/unit/main/account-profiles-owner-only-wiring.test.ts index 7b10cb8fa..3027599f0 100644 --- a/tests/unit/main/account-profiles-owner-only-wiring.test.ts +++ b/tests/unit/main/account-profiles-owner-only-wiring.test.ts @@ -231,9 +231,14 @@ describe('a Claude session that names no account waits for the start\'s profile const name = hold![1] // Held as a prepared spawn, so a close or a newer spawn of the tab supersedes it while it waits. expect(body).toMatch(new RegExp(`const preparation = [^\\n]*\\b${name}\\b[^\\n]*\\? beginSpawnPreparation\\(`)) - // It waits for the steps before the closed-or-superseded check, so nothing starts for a tab closed meanwhile. - const wait = body.search(new RegExp(`if \\(${name}\\) await startProfileStepsSettled\\(\\)`)) - expect(wait).toBeGreaterThan(-1) + // It waits for the steps before the closed-or-superseded check, so nothing starts for a tab closed meanwhile: + // the steps are one of the holds (aicc_planning#513: side by side with the others), and the holds are + // all awaited before that check. + const held = body.search(new RegExp(`if \\(${name}\\) holds\\.push\\(heldFor\\(sessionId, [^\\n]*, startProfileStepsSettled\\(\\), startProfileStepsPending\\)\\)`)) + expect(held).toBeGreaterThan(-1) + const wait = body.indexOf('if (holds.length > 0) await Promise.all(holds)') + expect(wait).toBeGreaterThan(held) + expect(body.indexOf('const holds: Array> = []')).toBeLessThan(held) const superseded = body.indexOf('closed or superseded while its spawn was prepared') expect(superseded).toBeGreaterThan(-1) expect(wait).toBeLessThan(superseded) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index 834c05cd8..d7cb2b673 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -270,6 +270,10 @@ describe('the holds a first tab is held for run side by side: it waits for the l ["the start's look for Claude Code", "the session folders' owner-only step"], ["the start's profile steps", "the session folders' owner-only step"], ["the start's profile steps", "the start's look for Claude Code"], + // The steps the longer one: a launch that names no account still waits + // for them in full (mutation: hold for them without awaiting them). + ["the session folders' owner-only step", "the start's profile steps"], + ["the start's look for Claude Code", "the start's profile steps"], ] for (const [fiveSeconds, eightSeconds] of pairs) { it(`${fiveSeconds} (5 s) and ${eightSeconds} (8 s): the spawn runs at 8 s, not 13 s`, async () => { From 76c0f0719f69fd945cdac82051e3bbb51b1f3714 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:44:32 +0000 Subject: [PATCH 17/79] docs(context): bring the Snap D1 holds entry's test counts up to date Seven pairs and twelve tests in the side-by-side file, the wiring test's new reading, and the steps mutant. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md index a071f3f46..349e5ce3b 100644 --- a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -71,19 +71,22 @@ makes its own folder owner-only before it writes. ### Tests -- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 10): the real +- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 12): the real pty:spawn handler over the real script-folders module, on fake timers. Covers the evidence case (a check that never answers: the tab asked 3 s in - starts 2 s later; asked past the deadline, not held), five 5 s + 8 s pairs + starts 2 s later; asked past the deadline, not held), seven 5 s + 8 s pairs that spawn at 8 s rather than 13 s, sign-in tabs, a check that answers in its usual time, and the 250 ms log threshold. - `tests/unit/main/script-folders.test.ts` (+3): the run's deadline. - `tests/unit/main/pty-claude-picker-plain.test.ts` (+2): the launch-line log. -- All 15 new tests fail on the old code (source stashed, restored, sha-checked). +- `tests/unit/main/account-profiles-owner-only-wiring.test.ts`: reads the steps + as one of the holds, all awaited before the closed-or-superseded check. +- All 17 new tests and the updated wiring test fail on the old code (source + stashed or restored from the base, then put back and sha-checked). Mutants each turn the matching tests red: bound from the ask, holds one after another, the look and the walk side by side, no re-ask of the folders or of - the walk, sign-in tabs held, logging every hold, the launch-line log dropped, - and an await with nothing to hold. + the walk, sign-in tabs held, the steps held but not awaited, logging every + hold, the launch-line log dropped, and an await with nothing to hold. Not measured: the split of the remaining 0.4 to 0.5 s. The tab's own Windows PowerShell start (5.2 s from spawn to the stand-in in the green run) is the From dac58f14b4a204a5db13675fb0051d12f15acb50 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:26:23 +0000 Subject: [PATCH 18/79] fix(pty): say a launch's holds only when slow or still pending, in words that claim no more Review round on aicc_planning#513 step 2 (its logging findings). - A hold is said when it took 1 s or more (SPAWN_HOLD_LOG_MS, was 250 ms), or when what it waited for was still pending as its wait ended, however short. A warm start's holds (the scripts check takes 1.0 to 1.6 s from its start) write none. - The words are "no longer pending" and "still pending when the wait ended". "done" was wrong for a folders hold whose work failed and for the start's look past its own deadline; "ran out its bound" was wrong for a walk that ended without an answer. - The per-launch "[pty] Launch line written into the shell" line is gone. Whether the resume list's script was ready rides the "[pty-manager] Launching Claude via shell" line every local launch already writes, and only for a launch that asked for the list. Nothing is logged inside the launch-line timer's try any more, so a logger fault cannot drop the buffered keystrokes after a good write. pty-manager.ts stays under its line cap (7475 of 7476). Tests: pty-spawn-holds-side-by-side (the 1 s rule, a short hold still pending, the words) and pty-claude-picker-plain (3: the script's state in the launch's line, only for a resume-list launch, in no line of its own). Each is red on the previous commit's source. Mutants each turn its test red: log every hold, log only by time, a 250 ms threshold, the old words, the state dropped, said for every launch, said in a line of its own. Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty-handlers.ts | 29 +++++++------ src/main/pty-manager.ts | 5 +-- .../unit/main/pty-claude-picker-plain.test.ts | 41 +++++++++++++------ .../main/pty-spawn-holds-side-by-side.test.ts | 32 +++++++++++---- 4 files changed, 72 insertions(+), 35 deletions(-) diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index 776b07e82..f6b6ccedc 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -748,26 +748,31 @@ function codexAccountOwnership(service: AccountsService, accountId: string): 'co /** aicc_planning#513: a hold on the way to a spawn that takes this long or * longer is said in one line, so a slow first tab can be read from the - * app's log; a start whose holds answer at once writes none. */ -export const SPAWN_HOLD_LOG_MS = 250 + * app's log. Longer than a warm start's usual holds (the scripts folders' + * check takes 1.0 to 1.6 s from its start, and a tab restored at start asks + * part way into it), so a usual start writes none. */ +export const SPAWN_HOLD_LOG_MS = 1000 /** One hold on the way to a spawn (pty:spawn), timed. Once `wait` has - * settled, when it took SPAWN_HOLD_LOG_MS or longer, one line says the hold's - * name, how long it took, and whether what it waited for had come by then - * (`stillWaiting()` true: the wait ended at its bound, or with no answer). - * The line carries the session id and the hold's name, nothing else. - * Rejects only when `wait` does (no hold here does). */ + * settled, one line says the hold's name, how long it took, and whether + * what it waited for was still pending then (`stillWaiting()`: the wait ran + * out its bound, or ended with no answer kept): only when it was, or when + * the hold took SPAWN_HOLD_LOG_MS or longer. The words say no more than + * that: a hold no longer pending may have answered, failed, or passed a + * deadline of its own. The line carries the session id and the hold's + * name, nothing else. Rejects only when `wait` does (no hold here does). */ async function heldFor(sessionId: string, hold: string, wait: Promise, stillWaiting: () => boolean): Promise { const began = performance.now() try { await wait } finally { const ms = Math.round(performance.now() - began) - if (ms >= SPAWN_HOLD_LOG_MS) { - try { - logInfo(`[spawn] Session ${sessionId}: held ${ms} ms for ${hold} (${stillWaiting() ? 'not done: it ran out its bound' : 'done'})`) - } catch { /* the launch goes on all the same */ } - } + try { + const pending = stillWaiting() + if (pending || ms >= SPAWN_HOLD_LOG_MS) { + logInfo(`[spawn] Session ${sessionId}: held ${ms} ms for ${hold} (${pending ? 'still pending when the wait ended' : 'no longer pending'})`) + } + } catch { /* the launch goes on all the same */ } } } diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts index 482dd2bde..33b56a5a3 100644 --- a/src/main/pty-manager.ts +++ b/src/main/pty-manager.ts @@ -6427,11 +6427,11 @@ function spawnPtyResolved( // The directory the CLI will actually run in, after the resume decision. assertGatedDirectory(options, claudeCwd, 'resume directory', recordUnverifiedDirectory) - logInfo(`[pty-manager] Launching Claude via shell in PTY: ${spawnCmd} -> ${cmd} cwd=${describePathForLog(claudeCwd)} (resumePicker=${!!options?.useResumePicker}, resume=${resumeUuid ?? 'none'})`) - // Asked once: the launch line below starts the picker exactly when this // spawn's agent templates were written for it. const pickerScript = getResumePickerPath(!!options?.useResumePicker) + // #513: a resume-list launch says if its script was ready (if not, the direct line runs); never its path. + logInfo(`[pty-manager] Launching Claude via shell in PTY: ${spawnCmd} -> ${cmd} cwd=${describePathForLog(claudeCwd)} (resumePicker=${!!options?.useResumePicker}${options?.useResumePicker ? `, pickerScript=${pickerScript ? 'ready' : 'not ready'}` : ''}, resume=${resumeUuid ?? 'none'})`) // This session's agent templates, as the one object keyed by name that // Claude Code's --agents takes; a set it would not take is refused here, // before anything starts (claudeAgentsObject). Windows: they ride the @@ -6674,7 +6674,6 @@ function spawnPtyResolved( if (ptySessions.get(sessionId)?.ptyProcess !== ptyProcess) { abandonLaunchHold(); return } try { ptyProcess.write(escapedCmd + '\r') - logInfo(`[pty] Launch line written into the shell for ${sessionId} (the resume list's script ${pickerScript ? 'ready' : 'not ready'})`) releaseLaunchHold() } catch { abandonLaunchHold() /* session died mid-launch */ } }, 300) diff --git a/tests/unit/main/pty-claude-picker-plain.test.ts b/tests/unit/main/pty-claude-picker-plain.test.ts index 56f0811f1..3989733a8 100644 --- a/tests/unit/main/pty-claude-picker-plain.test.ts +++ b/tests/unit/main/pty-claude-picker-plain.test.ts @@ -267,22 +267,39 @@ describe('a fresh local Claude session that does not ask for the resume list', ( }) }) -// aicc_planning#513: the moment the launch line goes into the shell is said, -// so a slow first tab's log splits main's part (the holds, the spawn) from -// the shell's own start. It names the session and whether the resume list's -// script was ready, never a path. Mutation to prove this can fail: drop the -// line. -describe('the launch line written into the shell', () => { - const said = (): string[] => h.infos.filter((m) => m.startsWith('[pty] Launch line written')) - it('is said once it is written, with the resume list\'s script ready', async () => { +// aicc_planning#513: a launch that asked for the resume list says, in the +// one line every local Claude Code launch already writes, whether the list's +// script was ready: a first tab started before the start's scripts folders' +// check and deploys ended takes the direct line, and only this says why. A +// launch that did not ask for the list says nothing of its script, and no +// launch writes a line of its own for this. Never the script's path. +// Mutations to prove this can fail: drop the script's state from the line; +// say it whatever the launch asked for; write it in a line of its own. +describe('the launch\'s line says whether the resume list\'s script was ready', () => { + const launching = (): string[] => h.infos.filter((m) => m.startsWith('[pty-manager] Launching Claude via shell')) + const saysScript = (): string[] => h.infos.filter((m) => /pickerScript|resume list's script/.test(m)) + + it('ready, for a launch that asked for the list', async () => { fs.writeFileSync(picker(), '// picker\n', { mode: 0o600 }) await launch() - expect(said()).toEqual([`[pty] Launch line written into the shell for ${SID} (the resume list's script ready)`]) + expect(launching()).toHaveLength(1) + expect(launching()[0]).toMatch(/ \(resumePicker=true, pickerScript=ready, resume=none\)$/) + expect(saysScript(), 'in that line only').toEqual(launching()) }) - it('and with it not ready (not deployed yet, as for a first tab started before the scripts folders\' check ended)', async () => { + it('not ready (not deployed yet, as for a first tab started before the scripts folders\' check ended), never its path', async () => { await launch() - expect(said()).toEqual([`[pty] Launch line written into the shell for ${SID} (the resume list's script not ready)`]) - expect(said().join('')).not.toContain(tmp) + expect(launching()).toHaveLength(1) + expect(launching()[0]).toMatch(/ \(resumePicker=true, pickerScript=not ready, resume=none\)$/) + expect(saysScript(), 'in that line only').toEqual(launching()) + expect(launching()[0]).not.toContain('resume-picker.js') + }) + + it('nothing of the script for a launch that did not ask for the list', async () => { + fs.writeFileSync(picker(), '// picker\n', { mode: 0o600 }) + await launch(false) + expect(launching()).toHaveLength(1) + expect(launching()[0]).toMatch(/ \(resumePicker=false, resume=none\)$/) + expect(saysScript()).toEqual([]) }) }) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index d7cb2b673..870593df4 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -16,7 +16,8 @@ * of them, not their sum; * - a sign-in tab is not held for the scripts folders, whose scripts it never * runs; - * - each hold that took SPAWN_HOLD_LOG_MS or longer says so in one line. + * - a hold that took SPAWN_HOLD_LOG_MS or longer, or whose wait ended with + * what it waited for still pending, says so in one line. * * Driven through the REAL pty:spawn handler on a fake ipcMain, with the REAL * scripts-folders module (its check over a stand-in rule that never answers, @@ -206,7 +207,7 @@ describe('the scripts folders\' check, when it does not come in its usual time ( expect(await asItStands(started), 'started at the run\'s deadline, 5 s after the check began').toBe('started') expect(spawned).toEqual([{ sid: S, at: asked + 2000 }]) expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ - `[spawn] Session ${S}: held 2000 ms for the scripts folders' check (not done: it ran out its bound)`, + `[spawn] Session ${S}: held 2000 ms for the scripts folders' check (still pending when the wait ended)`, ]) }) @@ -240,7 +241,7 @@ describe('the scripts folders\' check, when it does not come in its usual time ( expect(await asItStands(started)).toBe('started') expect(spawned, 'started as the deploys ended, 1.5 s after the check began').toEqual([{ sid: S, at: began + 1500 }]) expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ - `[spawn] Session ${S}: held 1000 ms for the scripts folders' check (done)`, + `[spawn] Session ${S}: held 1000 ms for the scripts folders' check (no longer pending)`, ]) }) @@ -296,18 +297,33 @@ describe('the holds a first tab is held for run side by side: it waits for the l }) describe('what is said of the holds', () => { - // Mutation to prove this can fail: say every hold, whatever it took (the - // usual start would then write a line per launch). - it('a hold that took less than SPAWN_HOLD_LOG_MS says nothing; one that took that long or longer says its name, its time and whether it ran out', async () => { + // A warm start's holds (the scripts folders' check takes 1.0 to 1.6 s from + // its start) write nothing. Mutation to prove this can fail: say every + // hold, whatever it took (the usual start would then write a line per + // launch); or bring SPAWN_HOLD_LOG_MS back to 250 ms. + it('a hold that took less than SPAWN_HOLD_LOG_MS and is no longer pending says nothing; one that took that long or longer says its name, its time and that it is no longer pending', async () => { const { SPAWN_HOLD_LOG_MS } = await import('../../../src/main/ipc/pty-handlers') + expect(SPAWN_HOLD_LOG_MS).toBe(1000) HOLDS["the start's profile steps"](SPAWN_HOLD_LOG_MS - 1) HOLDS["the session folders' owner-only step"](SPAWN_HOLD_LOG_MS) const started = outcome(spawn({}, S, CLAUDE_TAB)) await after(SPAWN_HOLD_LOG_MS) expect(await asItStands(started)).toBe('started') expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ - `[spawn] Session ${S}: held ${SPAWN_HOLD_LOG_MS} ms for the session folders' owner-only step (done)`, + `[spawn] Session ${S}: held ${SPAWN_HOLD_LOG_MS} ms for the session folders' owner-only step (no longer pending)`, + ]) + }) + + // Mutation to prove this can fail: say a hold only when it took + // SPAWN_HOLD_LOG_MS or longer (drop `pending ||`). + it('a hold whose wait ended with what it waited for still pending is said however short it was', async () => { + aCheckThatNeverAnswers() + await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS - 500) + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(500) + expect(await asItStands(started)).toBe('started') + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 500 ms for the scripts folders' check (still pending when the wait ended)`, ]) - expect(SPAWN_HOLD_LOG_MS).toBe(250) }) }) From 9bc21454832312e588c3c477f3e8bcedf65889ef Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:26:51 +0000 Subject: [PATCH 19/79] fix(pty): give a launch one bound for its session folders, not one per ask Review round on aicc_planning#513 step 2 (its MAJOR on the folders hold). With the holds side by side, a launch held for its session folders whose work did not answer waited twice: its hold ended at SPAWN_FOLDERS_WAIT_MS (10 s) with the work still wanted, and the ask again after the holds joined the same icacls runs with a fresh 10 s. The spawn ran at 20 s with two "ran out" lines; on the base it ran at 10 s. Now the launch has one bound for its folders, SPAWN_FOLDERS_WAIT_MS across every wait it makes for them. hardenSpawnFoldersAhead takes the time left and answers whether its work ended in time. A launch whose wait ran out is not asked again. One whose folders were done in time and came to want doing again while it waited for a longer hold waits at most what is left. That is counted as time spent waiting for the folders, not from the first wait's start: before #513 the folders' one wait came after every other hold, so folders wanted by then were still done off the main thread, and they still are. A launch held only by other holds gets the whole bound on the ask again, as before. Tests: pty-spawn-holds-side-by-side (+3, its folders stand-in now shaped as the real module: one work for every caller, each wait bounded by what it is given): work that never answers spawns at 10 s with one call and one line (20 s and two calls on the previous commit, 10 s on the base); done in time then wanted again spawns at 15 s, not 18 s; held only by another hold keeps the whole bound (kept behaviour, proven by mutants). spawn-folders-off-main-thread (+1, 1 changed): a wait waits what it is given and answers whether the work ended in time. pty-spawn-waits-for-spawn-folders: its stand-in answers as the real module does. Mutants each turn the matching tests red: ask again whenever wanted, with the whole bound, after a wait that ran out, from the launch's ask, or only for launches held for the folders; the module ignoring the time given, or answering wrongly at its bound or when done. Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty-handlers.ts | 41 +++++-- src/main/spawn-folders-ahead.ts | 45 ++++--- .../main/pty-spawn-holds-side-by-side.test.ts | 116 ++++++++++++++++-- .../pty-spawn-waits-for-spawn-folders.test.ts | 7 +- .../spawn-folders-off-main-thread.test.ts | 33 ++++- 5 files changed, 199 insertions(+), 43 deletions(-) diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index f6b6ccedc..b0266323b 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -59,7 +59,7 @@ import { claudeStartLookupPending, awaitClaudeStartLookup } from '../claude-star import { claudeLaunchWalkPending, awaitClaudeLaunchWalk } from '../claude-launch-walk' import { gsudoAnswerKept, gsudoLookAnswered } from '../gsudo-lookup' import { launchLookupsArmed } from '../launch-lookups-armed' -import { spawnFoldersWantHardeningAhead, hardenSpawnFoldersAhead } from '../spawn-folders-ahead' +import { spawnFoldersWantHardeningAhead, hardenSpawnFoldersAhead, SPAWN_FOLDERS_WAIT_MS } from '../spawn-folders-ahead' import { startSshProgramLookup } from '../ssh-program' /** SSH options as received from the renderer (no passwords — only configId) */ @@ -1272,6 +1272,27 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // for its hook folders below: the start wires those only after the // scripts folders' check and the deploys (index.ts), so each wait's // bound then covers its own work alone. + // + // The session folders have one bound for the whole launch, + // SPAWN_FOLDERS_WAIT_MS across every wait it makes for them (its hold + // here and the ask again below), never a fresh one per ask: the ask + // again joins the same work (the same icacls runs, the same rebuild of + // the plugin), so a fresh bound would hold a start whose work did not + // answer twice as long for it. A launch whose wait ran out its bound is + // not held for them again; one whose folders were done in time, and + // came to want doing again while it waited for a longer hold, waits at + // most what is left. Counted as time spent waiting for the folders, not + // from the first wait's start: before #513 the folders' one wait came + // after every other hold, so a launch held for a longer one still had + // folders wanted by then done off the main thread, and it still does. + let spawnFoldersWaitLeftMs = SPAWN_FOLDERS_WAIT_MS + const waitForSpawnFolders = async (): Promise => { + const began = performance.now() + let inTime = false + await heldFor(sessionId, "the session folders' owner-only step", + hardenSpawnFoldersAhead(spawnFoldersWaitLeftMs).then((ended) => { inTime = ended }), () => !inTime) + spawnFoldersWaitLeftMs = inTime ? Math.max(0, spawnFoldersWaitLeftMs - (performance.now() - began)) : 0 + } const holds: Array> = [] if (holdForScripts) holds.push(heldFor(sessionId, "the scripts folders' check", awaitScriptFolders(), scriptFoldersPending)) if (holdForStartSteps) holds.push(heldFor(sessionId, "the start's profile steps", startProfileStepsSettled(), startProfileStepsPending)) @@ -1281,7 +1302,7 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void await heldFor(sessionId, 'the walk of PATH', awaitClaudeLaunchWalk(opensResumeList), () => claudeLaunchWalkPending(opensResumeList)) })()) } - if (holdForSpawnFolders) holds.push(heldFor(sessionId, "the session folders' owner-only step", hardenSpawnFoldersAhead(), spawnFoldersWantHardeningAhead)) + if (holdForSpawnFolders) holds.push(waitForSpawnFolders()) // The elevated terminal's look for gsudo.exe (holdForGsudo above), // bounded by its own deadline; past it the launch is refused by // buildClaudeLocalSpawn, never by a walk in place. @@ -1380,14 +1401,14 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // folder's ten minutes as proven have run out, or another start has // begun the plugin's rebuild, which this one then joins rather than // wiping the tree under it at its spawn). Only what is still wanted is - // done, and nothing once all of it is done. It waits at most - // SPAWN_FOLDERS_WAIT_MS (one icacls run's time limit and as long - // again); past that the launch goes on, and the spawn's writers do their - // folders themselves, as before. Before the walk below, not after it, - // so the walk is asked once this wait is over too. - if (preparation && startWritesSpawnFolders && spawnFoldersWantHardeningAhead()) { - await heldFor(sessionId, "the session folders' owner-only step", hardenSpawnFoldersAhead(), spawnFoldersWantHardeningAhead) - } + // done, and nothing once all of it is done. It waits at most what is + // left of the launch's one bound for its folders (spawnFoldersWaitLeftMs + // above: SPAWN_FOLDERS_WAIT_MS, one icacls run's time limit and as long + // again, less what its hold above waited), and not at all when that + // hold ran out the bound; past it the launch goes on, and the spawn's + // writers do their folders themselves, as before. Before the walk + // below, not after it, so the walk is asked once this wait is over too. + if (preparation && startWritesSpawnFolders && spawnFoldersWaitLeftMs > 0 && spawnFoldersWantHardeningAhead()) await waitForSpawnFolders() // Then the launch's own walk of PATH, when it has one to make by now: // an answer the start kept meanwhile is read, and nothing is walked. // Asked again here, after every wait above, for any launch held for diff --git a/src/main/spawn-folders-ahead.ts b/src/main/spawn-folders-ahead.ts index a5c131a49..d35acc83a 100644 --- a/src/main/spawn-folders-ahead.ts +++ b/src/main/spawn-folders-ahead.ts @@ -11,9 +11,10 @@ // ~/.claude and the plugin's six folders: 1.15-1.36 s under load on CI. // // pty:spawn now awaits hardenSpawnFoldersAhead first, holding the launch as a -// prepared spawn (ipc/pty-handlers.ts), at most SPAWN_FOLDERS_WAIT_MS, and a -// session start held for any other wait asks it again once that wait is -// over: the same hardening, the same sequence, +// prepared spawn (ipc/pty-handlers.ts), at most SPAWN_FOLDERS_WAIT_MS in all, +// and a session start held for any other wait asks it again once that wait +// is over, within what is left of that bound: the same hardening, the same +// sequence, // with every icacls run started by execFile and awaited // (hardenCredentialDirOffThread), and the plugin's rebuild with it // (ensureCanvasPluginOffThread). What it proves is remembered by the rules @@ -101,12 +102,15 @@ export function spawnFoldersWantHardeningAhead(): boolean { } /** - * The most a held start waits for its folders: the time limit of one icacls - * run, and as long again. The work takes a second or so even under load; a - * start still waiting past this is waiting on a run that does not answer. - * It then goes on, and the spawn's writers make their folders owner-only - * themselves, on the main thread, as before. The work runs on to its own - * end, each run bounded by its own limit. + * The most a held start waits for its folders, in all: the time limit of one + * icacls run, and as long again. The work takes a second or so even under + * load; a start still waiting past this is waiting on a run that does not + * answer. It then goes on, and the spawn's writers make their folders + * owner-only themselves, on the main thread, as before. The work runs on to + * its own end, each run bounded by its own limit. A start that asks again + * (pty-handlers.ts) does not get this bound afresh: the ask again joins the + * same work, so the start waits only what its earlier wait left of it + * (aicc_planning#513 review). */ export const SPAWN_FOLDERS_WAIT_MS = 2 * ICACLS_TIMEOUT_MS @@ -115,22 +119,25 @@ export const SPAWN_FOLDERS_WAIT_MS = 2 * ICACLS_TIMEOUT_MS * (made as its writers make it, then hardened; a link there is accepted, as * before, and never remembered as proven), then, * with the built-in tools on, the canvas plugin's tree. Each only when it - * still wants it. Settles once that is done, or once SPAWN_FOLDERS_WAIT_MS - * has passed, whichever comes first. Never rejects: whatever does not get - * done here is done by the spawn's own writers, as before. + * still wants it. Settles once that is done, or once `waitMs` has passed, + * whichever comes first: true when the work ended in time (done, or left to + * the spawn's writers after a failure), false when the wait ran out first + * (the work runs on to its own end). `waitMs` is what the start has left of + * SPAWN_FOLDERS_WAIT_MS, all of it on its first wait. Never rejects: whatever + * does not get done here is done by the spawn's own writers, as before. */ -export function hardenSpawnFoldersAhead(): Promise { - if (!armed) return Promise.resolve() +export function hardenSpawnFoldersAhead(waitMs: number = SPAWN_FOLDERS_WAIT_MS): Promise { + if (!armed) return Promise.resolve(true) const work = foldersAhead() - return new Promise((resolve) => { + return new Promise((resolve) => { // Cleared once the work is done, so it runs only when the bound passed. const timer = setTimeout(() => { try { - logWarn(`[spawn] the session folders were not made owner-only ahead of the start within ${SPAWN_FOLDERS_WAIT_MS / 1000} s; the start goes on and does it itself`) - } catch { /* the wait ends all the same */ } finally { resolve() } - }, SPAWN_FOLDERS_WAIT_MS) + logWarn(`[spawn] the session folders were not made owner-only ahead of the start within ${Math.round(waitMs / 100) / 10} s; the start goes on and does it itself`) + } catch { /* the wait ends all the same */ } finally { resolve(false) } + }, waitMs) ;(timer as { unref?: () => void }).unref?.() - const done = (): void => { clearTimeout(timer); resolve() } + const done = (): void => { clearTimeout(timer); resolve(true) } void work.then(done, done) }) } diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index 870593df4..bf25238c3 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -16,6 +16,9 @@ * of them, not their sum; * - a sign-in tab is not held for the scripts folders, whose scripts it never * runs; + * - the session folders have one bound for the whole launch + * (SPAWN_FOLDERS_WAIT_MS across its hold and the ask again after the + * holds), so work that does not answer holds it once, not twice; * - a hold that took SPAWN_HOLD_LOG_MS or longer, or whose wait ended with * what it waited for still pending, says so in one line. * @@ -59,27 +62,43 @@ vi.mock('../../../src/main/pty-manager', () => ({ endAgentRunsInFolder: async () => true, })) /** The other holds, as their modules time them (each stand-in on the fake clock): - * - the session folders' owner-only step does its work from the call - * (spawn-folders-ahead.ts hardenSpawnFoldersAhead starts it there), `ms` - * of it; + * - the session folders' owner-only step: work that ends `ms` after it is + * set (then nothing is wanted), or never; one work for every caller (a + * call while it runs joins it, as the real one joins the same icacls runs + * and the same rebuild), each call waiting at most the `waitMs` it is + * given and answering whether the work ended in time + * (spawn-folders-ahead.ts hardenSpawnFoldersAhead); * - the start's profile steps run from the start (index.ts), whoever waits, * and end at `settled`; * - the start's look for Claude Code runs from the start too, and here never * answers: a launch's wait ends at its own bound, `ms` from the call * (claude-start-lookup.ts awaitClaudeStartLookup). */ const holds = vi.hoisted(() => ({ - folders: { want: false, ms: 0 }, + folders: { want: false, work: null as Promise | null, asked: [] as number[] }, steps: { pending: false, settled: Promise.resolve() as Promise }, lookup: { pending: false, ms: 0 }, })) /** `ms` from now on the fake clock, then `end`. */ const endsIn = (ms: number, end: () => void = () => {}): Promise => new Promise((resolve) => { setTimeout(() => { end(); resolve() }, ms) }) -vi.mock('../../../src/main/spawn-folders-ahead', () => ({ - spawnFoldersWantHardeningAhead: () => holds.folders.want, - // With nothing wanted, done at once, as the real one is. - hardenSpawnFoldersAhead: () => (holds.folders.want ? endsIn(holds.folders.ms, () => { holds.folders.want = false }) : Promise.resolve()), -})) +vi.mock('../../../src/main/spawn-folders-ahead', async (importOriginal) => { + const real = await importOriginal() + return { + ...real, + spawnFoldersWantHardeningAhead: () => holds.folders.want, + // With nothing wanted, done at once, as the real one is. Each call's + // `waitMs` is kept, so a test can read what each wait was given. + hardenSpawnFoldersAhead: (waitMs: number = real.SPAWN_FOLDERS_WAIT_MS): Promise => { + holds.folders.asked.push(waitMs) + const work = holds.folders.want ? holds.folders.work : null + if (!work) return Promise.resolve(true) + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(false), waitMs) + void work.then(() => { clearTimeout(timer); resolve(true) }) + }) + }, + } +}) vi.mock('../../../src/main/claude-launch-walk', () => ({ armClaudeLaunchWalk: () => {}, claudeLaunchWalkPending: () => false, @@ -115,6 +134,7 @@ vi.mock('../../../src/main/provider-accounts', () => ({ // The scripts folders' check itself: not a stand-in. const { secureScriptFolders, scriptFoldersDeployed, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS } = await import('../../../src/main/script-folders') +const { SPAWN_FOLDERS_WAIT_MS } = await import('../../../src/main/spawn-folders-ahead') const { registerPtyHandlers } = await import('../../../src/main/ipc/pty-handlers') registerPtyHandlers(() => ({} as never)) const spawn = handlers.get('pty:spawn')! @@ -158,6 +178,13 @@ const asItStands = (p: Promise): Promise => Promise.race([p, set /** Move the fake clock on by `ms`, running what falls due, then let the handler go on. */ const after = async (ms: number): Promise => { await vi.advanceTimersByTimeAsync(ms); await settle() } +/** The session folders wanted, by work that ends `ms` from now (then they + * are wanted no more), or by work that never answers. */ +function foldersWork(ms: number | 'never'): void { + holds.folders.want = true + holds.folders.work = ms === 'never' ? new Promise(() => {}) : endsIn(ms, () => { holds.folders.want = false }) +} + /** Each hold, made to take `ms` for a launch asked for now. */ const HOLDS: Record void> = { "the scripts folders' check": (ms) => { @@ -166,7 +193,7 @@ const HOLDS: Record void> = { expect(ms).toBe(SCRIPT_FOLDERS_LAUNCH_WAIT_MS) aCheckThatNeverAnswers() }, - "the session folders' owner-only step": (ms) => { holds.folders.want = true; holds.folders.ms = ms }, + "the session folders' owner-only step": (ms) => foldersWork(ms), "the start's profile steps": (ms) => { holds.steps.pending = true; holds.steps.settled = endsIn(ms, () => { holds.steps.pending = false }) }, "the start's look for Claude Code": (ms) => { holds.lookup.pending = true; holds.lookup.ms = ms }, } @@ -175,7 +202,7 @@ beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'] }) live.clear(); pending.clear(); spawned.length = 0; preparations = 0 logged.length = 0 - holds.folders.want = false; holds.folders.ms = 0 + holds.folders.want = false; holds.folders.work = null; holds.folders.asked = [] holds.steps.pending = false; holds.steps.settled = Promise.resolve() holds.lookup.pending = false; holds.lookup.ms = 0 __resetScriptFoldersForTests() @@ -327,3 +354,70 @@ describe('what is said of the holds', () => { ]) }) }) + +describe('the session folders: one bound for the whole launch, not one per ask', () => { + // The review's probe: a launch held for the folders, whose work does not + // answer, ran out its bound at 10 s, then asked again after the holds, + // joined the same work and waited a fresh 10 s: the spawn at 20 s, with + // two lines. Mutation to prove this can fail: ask again whenever the + // folders are still wanted (drop `spawnFoldersWaitLeftMs > 0`, or leave + // the bound at its whole on a wait that ran out). + it('work that does not answer holds the launch SPAWN_FOLDERS_WAIT_MS once: the spawn runs at that bound, the folders are not asked again, and one line says the wait ran out', async () => { + foldersWork('never') + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(SPAWN_FOLDERS_WAIT_MS - 1) + expect(await asItStands(started)).toBe('still held') + await after(1) + expect(await asItStands(started), 'started at the bound, not a second bound later').toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + SPAWN_FOLDERS_WAIT_MS }]) + expect(holds.folders.asked, 'asked once, with the whole bound').toEqual([SPAWN_FOLDERS_WAIT_MS]) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held ${SPAWN_FOLDERS_WAIT_MS} ms for the session folders' owner-only step (still pending when the wait ended)`, + ]) + }) + + // Folders done in time (3 s), a longer hold (the start's profile steps, + // 8 s), and meanwhile the folders come to want doing again by work that + // does not answer: the ask again waits what is left of the bound, 7 s, so + // the spawn runs at 15 s, not 18 s. Mutation to prove this can fail: give + // the ask again the whole bound (hardenSpawnFoldersAhead(SPAWN_FOLDERS_WAIT_MS)). + it('folders done in time, then wanted again while a longer hold runs: the ask again waits only what the first wait left of the bound', async () => { + foldersWork(3000) + HOLDS["the start's profile steps"](8000) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(6000) + foldersWork('never') + await after(2000 + (SPAWN_FOLDERS_WAIT_MS - 3000) - 1) + expect(await asItStands(started)).toBe('still held') + await after(1) + expect(await asItStands(started)).toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + 8000 + SPAWN_FOLDERS_WAIT_MS - 3000 }]) + expect(holds.folders.asked).toEqual([SPAWN_FOLDERS_WAIT_MS, SPAWN_FOLDERS_WAIT_MS - 3000]) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 3000 ms for the session folders' owner-only step (no longer pending)`, + `[spawn] Session ${S}: held 8000 ms for the start's profile steps (no longer pending)`, + `[spawn] Session ${S}: held ${SPAWN_FOLDERS_WAIT_MS - 3000} ms for the session folders' owner-only step (still pending when the wait ended)`, + ]) + }) + + // What the ask again is for is kept: a launch held only by another hold, + // whose folders come to want doing while it waits, waits for them with the + // whole bound. Mutations to prove this can fail: count the bound from the + // launch's ask rather than from its waits for the folders; ask again only + // for a launch held for the folders. + it('a launch held only by another hold, whose folders come to want doing meanwhile, waits for them with the whole bound', async () => { + HOLDS["the start's profile steps"](4000) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(2000) + foldersWork('never') + await after(2000 + SPAWN_FOLDERS_WAIT_MS - 1) + expect(await asItStands(started)).toBe('still held') + await after(1) + expect(await asItStands(started)).toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + 4000 + SPAWN_FOLDERS_WAIT_MS }]) + expect(holds.folders.asked).toEqual([SPAWN_FOLDERS_WAIT_MS]) + }) +}) diff --git a/tests/unit/main/pty-spawn-waits-for-spawn-folders.test.ts b/tests/unit/main/pty-spawn-waits-for-spawn-folders.test.ts index adc83bb1a..981f67895 100644 --- a/tests/unit/main/pty-spawn-waits-for-spawn-folders.test.ts +++ b/tests/unit/main/pty-spawn-waits-for-spawn-folders.test.ts @@ -53,9 +53,12 @@ vi.mock('../../../src/main/pty-manager', () => ({ })) // The work ahead of the spawn: wanted while `want`, done when the test opens the gate. const ahead = vi.hoisted(() => ({ want: false, done: Promise.resolve() as Promise, open: () => {}, runs: 0, spawnedBeforeDone: false })) -vi.mock('../../../src/main/spawn-folders-ahead', () => ({ +// The bound itself is the real module's (SPAWN_FOLDERS_WAIT_MS); the gate here +// has none, and answers, as the real one does, that the work ended in time. +vi.mock('../../../src/main/spawn-folders-ahead', async (importOriginal) => ({ + ...(await importOriginal()), spawnFoldersWantHardeningAhead: () => ahead.want, - hardenSpawnFoldersAhead: () => { ahead.runs++; return ahead.done }, + hardenSpawnFoldersAhead: () => { ahead.runs++; return ahead.done.then(() => true) }, })) // The launch's own walk of PATH: one to wait for while `pending`, and when it was asked. const walk = vi.hoisted(() => ({ asked: [] as string[], pending: false })) diff --git a/tests/unit/main/spawn-folders-off-main-thread.test.ts b/tests/unit/main/spawn-folders-off-main-thread.test.ts index e11e38e64..102860ad0 100644 --- a/tests/unit/main/spawn-folders-off-main-thread.test.ts +++ b/tests/unit/main/spawn-folders-off-main-thread.test.ts @@ -1014,7 +1014,9 @@ describe.runIf(process.platform === 'win32')('a start waits a bounded time for i armSpawnFoldersAhead() vi.useFakeTimers({ toFake: ['performance', 'setTimeout', 'clearTimeout'] }) const before = vi.getTimerCount() - await drive(hardenSpawnFoldersAhead()) + const { value, answered } = await drive(hardenSpawnFoldersAhead()) + expect(answered, 'its runs were made, and answered').toBeGreaterThan(0) + expect(value, 'it answers that the work ended in time').toBe(true) expect(credentialDirHardeningStartsIcacls(claudeDir()), 'done in time').toBe(false) expect(vi.getTimerCount() - before, 'the bound\'s timer is cleared once the work is done').toBe(0) vi.advanceTimersByTime(SPAWN_FOLDERS_WAIT_MS) @@ -1022,6 +1024,35 @@ describe.runIf(process.platform === 'win32')('a start waits a bounded time for i expect(h.warned.filter((w) => w.includes('ahead of the start within')), 'no word of a bound it did not reach').toEqual([]) }) + // aicc_planning#513 review: a start that asks again (pty-handlers.ts) waits + // only what its earlier wait left of the bound, and it reads whether the + // work ended in time, so a start whose wait ran out its bound is not held + // for the same work again. Mutations to prove this can fail: wait + // SPAWN_FOLDERS_WAIT_MS whatever is given (setTimeout(..., SPAWN_FOLDERS_WAIT_MS)); + // answer nothing (resolve() at the bound, or once the work is done). + it('a wait given less of the bound waits only that and answers that the work did not end in time; a wait whose work ends in time answers so', async () => { + learnPairAtStart() + h.conductorOn = false + armSpawnFoldersAhead() + vi.useFakeTimers({ toFake: ['performance', 'setTimeout', 'clearTimeout'] }) + let answer: boolean | undefined + void hardenSpawnFoldersAhead(3000).then((v) => { answer = v }) + await turns(5) + expect(h.pending.length, 'its first run started, and not answered').toBe(1) + vi.advanceTimersByTime(2999) + await turns(5) + expect(answer, 'still waiting, just short of what it was given').toBeUndefined() + vi.advanceTimersByTime(1) + await turns(5) + expect(answer, 'ran out at the 3 s it was given').toBe(false) + expect(h.warned.filter((w) => w.includes('ahead of the start within 3 s')), 'it logs the bound it was given').toHaveLength(1) + // The work goes on to its end; a wait for folders done by then answers + // that the work ended in time. + for (let i = 0; i < 50 && h.pending.length > 0; i++) await answerOne() + expect(credentialDirHardeningStartsIcacls(claudeDir()), 'proven once its runs answered').toBe(false) + expect((await drive(hardenSpawnFoldersAhead())).value).toBe(true) + }) + // Every bound above is relative to one run's time limit, so only this holds // the wait itself. Mutation to prove this can fail: raise ICACLS_TIMEOUT_MS // (to 120000, say, which makes the hold 240 s). From 3dcc60b9af4c973e1c6c72597489262a2ea51933 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:27:35 +0000 Subject: [PATCH 20/79] test(snap): record when the first tab's Windows PowerShell showed its prompt Review round on aicc_planning#513 step 2: the D1 red's main share is the tab's own cold Windows PowerShell start, which the holds fix does not touch, and the evidence could not split it. D1 now keeps readings.promptSeenAt, the first time its poll for the stand-in saw the shell's prompt, on the clock of readings.submitAt. A red D1 then splits into main's part (to the spawn), the shell's start (to its prompt) and the stand-in's (to its at). Only the time is kept, never the text, which names the data dir. It is absent when no read saw a prompt (none came within D1's budget, or the stand-in cleared the screen first). A read that fails is let go; the poll still waits for the stand-in. The prompt test is showsPowerShellPrompt in helpers/launch-evidence.ts (no Playwright import), and the comments there and in the spec now say what the step-2 hold lines tell. Tests: e2e-launch-evidence (+2) for the banner alone, an empty screen and the stand-in's screen against a prompt with the launch line after it or its location wrapped. Red without the helper, and under two mutants (match PS anywhere; miss a wrapped location). The spec and helper also pass a strict tsc run; the Snap e2e itself only runs on CI. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/helpers/launch-evidence.ts | 35 ++++++++++++++----- tests/e2e/snap-windows.spec.ts | 47 ++++++++++++++++++-------- tests/unit/e2e-launch-evidence.test.ts | 25 +++++++++++++- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/tests/e2e/helpers/launch-evidence.ts b/tests/e2e/helpers/launch-evidence.ts index 3e4f22c40..218112925 100644 --- a/tests/e2e/helpers/launch-evidence.ts +++ b/tests/e2e/helpers/launch-evidence.ts @@ -10,19 +10,23 @@ * anyone, so no user folder, account name, credential or token-shaped value * may stay in what is kept. * - * What the lines can and cannot tell. A hold that ends within its bound writes - * no line: awaitScriptFolders (script-folders.ts) and awaitClaudeLaunchWalk - * (claude-launch-walk.ts) write none at all, and hardenSpawnFoldersAhead - * ('[spawn] ...') and the start's lookup ('[start] ...') write one only when - * they ran out their bound or failed. So the artifact gives the way to the - * spawn, from the click on the session dialog's submit (readings.submitAt) to + * What the lines can and cannot tell. Each hold pty:spawn puts on a launch + * (step 2) says itself in one '[spawn] Session : held ms for ' + * line when it took a second or more, or when its wait ended with what it + * waited for still pending (pty-handlers.ts heldFor); a shorter hold that + * answered writes none. hardenSpawnFoldersAhead ('[spawn] ...') and the + * start's lookup ('[start] ...') also write one of their own when they ran + * out their bound or failed. So the artifact gives the way to the spawn, from + * the click on the session dialog's submit (readings.submitAt) to * '[pty] Spawning PTY for session': the renderer's request first (the dialog * closing, the tab mounting, its account gate, the IPC to pty:spawn), then * main's work before the spawn and the holds. And then the tab's own * PowerShell, from '[pty-manager] Launching Claude via shell' (the launch line - * is typed 300 ms after it, pty-manager.ts) to the stand-in's `at`. It names a - * hold only when that one ran out its bound or failed; it does not split the - * way to the spawn between the renderer and the holds that did neither. + * is typed 300 ms after it, pty-manager.ts; for a resume-list launch it says + * whether the list's script was ready) to the stand-in's `at`, split by + * readings.promptSeenAt, when D1 saw the shell's prompt (showsPowerShellPrompt + * below). It does not split the way to the spawn between the renderer and + * holds under a second. * * No Playwright import, so the unit suite reads this directly * (tests/unit/e2e-launch-evidence.test.ts). @@ -50,6 +54,19 @@ export function isLaunchPathMessage(message: string): boolean { return LAUNCH_PATH_PREFIXES.some((p) => message.startsWith(p)) } +/** Windows PowerShell's prompt at the start of a row: `PS >`, the + * location's rows wrapped or not. */ +const POWERSHELL_PROMPT = /^PS [^>]*>/m + +/** Whether a terminal's text (one row per line) shows Windows PowerShell's + * prompt: the tab's shell has started and reads its input. Its banner alone + * ('Windows PowerShell', the copyright, the link to the newer one) does not, + * nor does the stand-in's own screen. Reads the text only; what is kept of + * it is the time it was seen, never the text (it names the data dir). */ +export function showsPowerShellPrompt(text: string): boolean { + return POWERSHELL_PROMPT.test(text) +} + /** One record of the app's log (debug-logger.ts formatMessage: * `[] [] `), or null for a line that starts no * record (the rest of an Error's stack, an empty line). */ diff --git a/tests/e2e/snap-windows.spec.ts b/tests/e2e/snap-windows.spec.ts index f21202d9a..ab7e3cb6b 100644 --- a/tests/e2e/snap-windows.spec.ts +++ b/tests/e2e/snap-windows.spec.ts @@ -199,10 +199,11 @@ * at the test's Date.now() (the clock of readings.submitAt, readings.snapButtonAt * and the stand-in's `at`), and part1-app.log, the app's log at main's own * times; the launch path's lines only, scrubbed (helpers/launch-evidence.ts). - * A hold that ends within its bound writes no line, so these give the way to - * the spawn (the renderer's request, then the holds) and the tab's own - * PowerShell, and name a hold only when it ran out its bound or failed (the - * header of that file). The stand-in's records are in readings.json + * A hold under a second that answered writes no line, so these give the way + * to the spawn (the renderer's request, then the holds) and the tab's own + * PowerShell, and name a hold when it took a second or more or ended still + * pending (the header of that file). readings.promptSeenAt is when D1 first + * saw that PowerShell's prompt. The stand-in's records are in readings.json * twice: readings.launches (D1, once the Snap button shows) and * readings.launchesAtClose (afterAll, whatever D1 did). * @@ -268,7 +269,7 @@ import { seedCodexAccount, realmDirOf, createCodexConfig, openSession, activeSes import { nextFirstScreen, FOOTER, type FirstScreenAnswer } from './helpers/codex-first-screens' import { pathWithoutCodex } from './helpers/fake-codex' import { isolatedHomeDir } from './helpers/isolated-env' -import { launchPathAppLog, launchPathMainLines, localEvidenceScrub, scrubEvidence, type EvidenceScrub } from './helpers/launch-evidence' +import { launchPathAppLog, launchPathMainLines, localEvidenceScrub, scrubEvidence, showsPowerShellPrompt, type EvidenceScrub } from './helpers/launch-evidence' /** A Claude Code the app supports (CLAUDE_MIN_MANAGED_CLI_VERSION, as * onboarding-provider-select.spec.ts's stand-in answers). */ @@ -464,15 +465,16 @@ const part1Main: Array<{ at: number; text: string }> = [] * artifact is public. part1-main-lines.json: main's console lines from the * window's start on, each at the test's time. part1-app.log: the app's log * (the file appLogLines reads) from main's own start, each at main's time. - * What they can tell: a hold that ends within its bound writes no line - * (awaitScriptFolders and awaitClaudeLaunchWalk write none at all; - * hardenSpawnFoldersAhead's '[spawn] ...' and the start lookup's '[start] ...' - * are written only when they ran out their bound or failed). So they give the - * way to the spawn (readings.submitAt to '[pty] Spawning PTY for session': - * the renderer's request, then main's work before the spawn and the holds) - * and the tab's own PowerShell ('[pty-manager] Launching Claude via shell', - * the launch line typed 300 ms after it, to launches[].at), and name a hold - * only when it ran out its bound or failed. + * What they can tell: each hold on the way to the spawn writes a '[spawn] + * Session : held ...' line when it took a second or more, or ended with + * what it waited for still pending (pty-handlers.ts heldFor), and none + * otherwise; hardenSpawnFoldersAhead's own '[spawn] ...' and the start + * lookup's '[start] ...' are written only when they ran out their bound or + * failed. So they give the way to the spawn (readings.submitAt to '[pty] + * Spawning PTY for session': the renderer's request, then main's work before + * the spawn and the holds) and the tab's own PowerShell ('[pty-manager] + * Launching Claude via shell', the launch line typed 300 ms after it, to + * readings.promptSeenAt, then to launches[].at). * The end anchor, 'the tab's own PowerShell', is read two ways. D1's * readings.launches is set only once the Snap button has shown, and D1's * budget can run out before that. So afterAll also sets @@ -1046,9 +1048,24 @@ test.describe('Snap on Windows', () => { await expect(snapButton()).toBeVisible({ timeout: TAB_MS }) readings.tabMs = Math.round(performance.now() - started) readings.snapButtonAt = Date.now() + // aicc_planning#513, step 2 review: when the tab's own Windows PowerShell + // first showed its prompt (readings.promptSeenAt, on the clock of + // submitAt), so a slow or red D1 splits into main's part (to the spawn), + // the shell's start (to its prompt) and the stand-in's (to its `at`). + // Read in the poll for the stand-in's start: the first read that shows + // the prompt, so up to one interval and one read late. Absent when no read + // showed it: the prompt never came within D1's budget, or the stand-in + // had cleared the screen before a read. Only the time is kept, never the + // text; a read that fails is let go (the poll waits for the stand-in). + const notePrompt = async (): Promise => { + if (readings.promptSeenAt !== undefined) return + try { + if (showsPowerShellPrompt(await terminalText(page))) readings.promptSeenAt = Date.now() + } catch { /* the poll's own question is the stand-in's start */ } + } // The tab runs the stand-in on a terminal: a Snap's path is typed into it. try { - await expect.poll(() => launches().some((l) => l.stdinTty === true), { timeout: TAB_MS, intervals: [100] }).toBe(true) + await expect.poll(async () => { await notePrompt(); return launches().some((l) => l.stdinTty === true) }, { timeout: TAB_MS, intervals: [100] }).toBe(true) await expect.poll(() => terminalText(page), { timeout: TAB_MS, intervals: [100] }).toContain('stand-in Claude Code ready') } finally { readings.launches = launches() diff --git a/tests/unit/e2e-launch-evidence.test.ts b/tests/unit/e2e-launch-evidence.test.ts index be8458adf..31f621202 100644 --- a/tests/unit/e2e-launch-evidence.test.ts +++ b/tests/unit/e2e-launch-evidence.test.ts @@ -13,7 +13,7 @@ import { describe, it, expect } from 'vitest' import crypto from 'crypto' import { LAUNCH_PATH_PREFIXES, isLaunchPathMessage, appLogRecord, scrubEvidence, launchPathMainLines, launchPathAppLog, - EVIDENCE_LINE_MAX, SCRUB_INPUT_MAX, type EvidenceScrub, + showsPowerShellPrompt, EVIDENCE_LINE_MAX, SCRUB_INPUT_MAX, type EvidenceScrub, } from '../e2e/helpers/launch-evidence' const DATA = 'C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\ccc-e2e-AbC123' @@ -108,6 +108,29 @@ describe('which of main\'s lines are kept: the launch path only', () => { }) }) +// aicc_planning#513, step 2 review: D1 keeps when the tab's own Windows +// PowerShell first showed its prompt (readings.promptSeenAt), so a red D1 +// splits between main's part and the shell's start. The texts are the tab's +// rows as terminalText reads them, shaped as the forced red's +// (run 47213083589) and the failing run's (47192226861, the banner alone). +// Mutation to prove this can fail: take the banner for a prompt (match 'PS' +// anywhere), or miss a prompt whose location wraps onto the next row. +describe('the tab\'s Windows PowerShell prompt, as D1 reads it', () => { + const BANNER = 'Windows PowerShell 5.1\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nInstall the latest PowerShell for new features and improvements! https://aka.ms/PSWindows\n' + it('the banner alone, an empty screen and the stand-in\'s own screen show no prompt', () => { + expect(showsPowerShellPrompt(BANNER)).toBe(false) + expect(showsPowerShellPrompt('')).toBe(false) + const rule = String.fromCodePoint(0x2500).repeat(40) + expect(showsPowerShellPrompt(`stand-in Claude Code ready\n\n${rule}\n${String.fromCodePoint(0x276f)}\n${rule}\n ? for shortcuts\n`)).toBe(false) + }) + + it('the prompt shows, with the launch line typed after it or not, and with its location wrapped onto the next row', () => { + expect(showsPowerShellPrompt(`${BANNER}\nPS ${DATA}> `)).toBe(true) + expect(showsPowerShellPrompt(`${BANNER}\nPS ${DATA}> Microsoft.PowerShell.Management\\Set-Location -LiteralPath '${DATA}'; & '${DATA}\\stand-in-claude\\claude.cmd'`)).toBe(true) + expect(showsPowerShellPrompt(`${BANNER}\nPS C:\\Users\\RUNNER~1\\AppData\\Local\\Te\nmp\\ccc-e2e-AbC123> `)).toBe(true) + }) +}) + describe('main\'s console lines: kept with the time the test saw them, scrubbed', () => { it('keeps every planted launch-path line, in order, at its time, and none of what was planted in them', () => { const lines = [ From d58277d8d2b216914a1fcb669eca7a204b40572d Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:27:53 +0000 Subject: [PATCH 21/79] docs(context): say what the Snap D1 holds fix saves, what it trades, and what stays open Review round on aicc_planning#513 step 2 (its note and comment findings). - The note now says it plainly. This step removes about 2 to 3 s of a first tab's wait (the tab, asked about 2.9 s in, waits about 2.4 to 2.7 s for the scripts check, not 5 s). It does not remove the D1 red. In the failing run 47192226861 the spawn happened and the tab's own Windows PowerShell did not reach its prompt in the rest of the 30 s, the runner's cold start that no hold covers. A run like it is expected to stay red, is not a regression of this fix, and is not re-run. #513 stays open on it, as an owner decision (a warm-up step changes what D1 measures; TAB_MS stays). - The run-wide scripts deadline is a trade, stated in the note and in script-folders.ts. A check that ends 5 s or more after it began, but within 5 s of a tab's ask, was waited for before; now that tab starts without its status line (for the session's life) and without the resume list. No check measured so far ended in that window (the b20 first app's ended about 0.8 s outside it). Raised as an owner choice; the note's "the wait bought nothing" and "every such tab waited 5 s" are corrected to what holds. - The note records the folders' one bound, the quieter log lines and the prompt time D1 now keeps, with this round's tests and mutants. Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 143 +++++++++++++++++----- src/main/script-folders.ts | 24 +++- 2 files changed, 127 insertions(+), 40 deletions(-) diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md index 349e5ce3b..90d622a54 100644 --- a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -2,7 +2,32 @@ Branch `fix/b28-snap-d1-evidence`, from beta at 591eb8fb (2.1.3-beta.27). Step 1 (the evidence capture in the Snap e2e's part one) is the `test(snap)` commits -before this entry; this is step 2, the fix at the cause. +before this entry; this is step 2, the fix at the cause, and its review round. + +### What this step fixes, and what it does not + +This step removes about 2 to 3 s of a first tab's wait at start. It does not +remove the D1 red, and #513 stays open. + +- In the evidence below, the tab was asked about 2.9 s after main's first + line. The scripts check begins at boot, about 0.3 to 0.6 s in (the review's + reading; not measured). Under the run's deadline the tab now waits about + 2.4 to 2.7 s for the check, not 5 s. +- In the failing run (47192226861) the spawn did happen: the tab showed + Windows PowerShell's banner. Its own Windows PowerShell then did not reach + its prompt in the rest of D1's 30 s, about 24 s or more if its holds took + 5.4 s as they did here. That share is the runner's cold Windows PowerShell + start (plan branch 2 of #513), outside every hold, and this step does not + touch it. +- So a run like 47192226861 is expected to stay red. A red D1 whose time went + to the shell's start is not a regression of this step, and it is not re-run + to green. +- What to do about that share is the owner's decision (below). + +D1 now keeps `readings.promptSeenAt`: the first time it saw the tab's +Windows PowerShell prompt. The next red can then be split into main's part +(to the spawn), the shell's start (to its prompt) and the stand-in's (to its +`at`). ### Evidence @@ -31,25 +56,32 @@ deploys after it have run (index.ts), at most `SCRIPT_FOLDERS_LAUNCH_WAIT_MS` (5 s), counted from each launch's own ask. Only `scriptFoldersDeployed()`, at the end of that chain, ends it early. The check is one Windows PowerShell call; on a runner's first app it takes 8.8 to 13.6 s (2026-11-27-b20-snap-d1.md), and -the tab is asked for about 3 s after main starts. So the hold always ran out -its full 5 s, and the tab started without the scripts all the same: the wait -bought nothing. The other holds ran after it, one after another; with the -IPC they took the remaining 0.4 to 0.5 s (not split: no line said them). +the tab is asked for about 3 s after main starts. In both runs here the hold +ran out its full 5 s, and the tab started without the scripts all the same. +The other holds ran after it, one after another; with the IPC they took the +remaining 0.4 to 0.5 s (not split: no line said them). Who meets it: a tab asked for while the check runs (tabs restored at start, or one opened in the first seconds). Where Windows PowerShell is warm the check took 1.0 to 1.6 s on the runner (2.6 to 3.5 s with the disk cache purged); the -tab waits that long and gets its status line and resume list. Where the check -runs past 5 s (a slow cold start), every such tab waited 5 s from its own ask -and started without them. A tab asked for once the check is over waits for -nothing. +tab waits that long and gets its status line and resume list. Before this +step, a check that ended within 5 s of a tab's ask was waited for, and the tab +got them; one that ended later cost that tab 5 s, and it started without them. +A tab asked for once the check is over waits for nothing. ### Fix - script-folders.ts: the bound is the run's, counted from the check's start (`scriptFoldersWaitLeft`). A tab asked 3 s into the check waits at most 2 s; - one asked once the deadline has passed is not held at all. No launch waits - longer than before. + one asked once the deadline has passed is not held at all. For this hold + alone, no launch waits longer than before. +- That is a trade, stated in script-folders.ts too. A check that ends 5 s or + more after it began, but within 5 s of a tab's ask, was waited for before; + now that tab starts without the scripts: no status line of the app's for the + session's whole life, and the direct Claude Code line, not the resume list. + In the b20 record the first app's check ended 8.8 s in with the tab asked + about 3 s in, only about 0.8 s outside that window; no check measured so far + ended inside it. This is an owner choice (below). - pty-handlers.ts: the holds a launch is held for run side by side (`Promise.all`), so it waits for the longest, not the sum. The start's look for Claude Code and the launch's walk of PATH stay one after the other. The @@ -57,11 +89,29 @@ nothing. is over, as before. With nothing to hold, the launch still goes on in the same tick (the one-at-a-time rule relies on that). A sign-in tab is not held for the scripts: its line runs none of them. -- Logging: `[spawn] Session : held ms for (done | not done: it - ran out its bound)`, one line per hold that took 250 ms or longer, and - `[pty] Launch line written into the shell for (the resume list's script - ready | not ready)`. Both carry the session id and nothing else. The Snap - evidence filter keeps both prefixes, so the next red can be split. +- The session folders have one bound for the whole launch + (`SPAWN_FOLDERS_WAIT_MS`, 10 s, across its hold and the ask again). The + review found that running them side by side made a launch whose folders work + did not answer wait twice: its hold ended at 10 s with the work still + wanted, and the ask again joined the same icacls runs with a fresh 10 s, so + the spawn ran at 20 s with two "ran out" lines. Now `hardenSpawnFoldersAhead` + takes the time left and answers whether its work ended in time. A launch + whose wait ran out is not asked again; one whose folders were done in time + and came to want doing again while it waited for a longer hold waits at + most what is left. That is counted as time spent waiting for the folders, + not from the first wait's start: before this step the folders' one wait + came after every other hold, so folders wanted by then were still done off + the main thread, and they still are. A launch held only by other holds gets + the whole bound on the ask again, as before. +- Logging: `[spawn] Session : held ms for (no longer pending | + still pending when the wait ended)`, one line per hold, written only when + the hold took 1 s or more, or when what it waited for was still pending as + the wait ended. A warm start's holds write none. "No longer pending" is all + the line claims: the hold answered, failed, or passed a deadline of its own. + The resume list's script state rides the `[pty-manager] Launching Claude via + shell` line every local launch already writes (`pickerScript=ready | not + ready`), only for a launch that asked for the list; no line of its own. All + carry the session id and nothing else. Safety is unchanged. The scripts hold guards nothing: a launch takes a script only through `checkDeployedScript` / `scriptFolderRefusal` at launch time, and @@ -69,25 +119,50 @@ a folder not yet checked fails closed (the feature is skipped). The session folders are still made owner-only before the spawn, and each writer still makes its own folder owner-only before it writes. +### Owner decisions raised + +1. The cold Windows PowerShell share of D1. A warm-up step before the Snap + step would change what D1 measures; TAB_MS stays. #513 stays open on this. +2. The scripts deadline's trade. Keep the run's deadline as is, or add a + small wait counted from the ask that the run's deadline caps. + ### Tests -- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 12): the real - pty:spawn handler over the real script-folders module, on fake timers. - Covers the evidence case (a check that never answers: the tab asked 3 s in - starts 2 s later; asked past the deadline, not held), seven 5 s + 8 s pairs - that spawn at 8 s rather than 13 s, sign-in tabs, a check that answers in its - usual time, and the 250 ms log threshold. +- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 16): the real + pty:spawn handler over the real script-folders module, on fake timers, with + a folders stand-in shaped as the real module (one work for every caller, + each wait bounded by what it is given). Covers the evidence case (a check + that never answers: the tab asked 3 s in starts 2 s later; asked past the + deadline, not held), seven 5 s + 8 s pairs that spawn at 8 s rather than + 13 s, sign-in tabs, a check that answers in its usual time, the log rule + (1 s, or still pending), and the folders' one bound: work that never answers + spawns at 10 s with one call and one line (20 s and two calls before the + review round, 10 s on the base); done in time then wanted again spawns at + 15 s, not 18 s; held only by another hold keeps the whole bound. +- `tests/unit/main/spawn-folders-off-main-thread.test.ts` (+1, 1 changed): a + wait waits what it is given and answers whether the work ended in time. - `tests/unit/main/script-folders.test.ts` (+3): the run's deadline. -- `tests/unit/main/pty-claude-picker-plain.test.ts` (+2): the launch-line log. +- `tests/unit/main/pty-claude-picker-plain.test.ts` (+3): the script state in + the launch's line, only for a resume-list launch, in no line of its own. +- `tests/unit/e2e-launch-evidence.test.ts` (+2): the prompt D1 looks for, not + the banner, wrapped rows included. - `tests/unit/main/account-profiles-owner-only-wiring.test.ts`: reads the steps - as one of the holds, all awaited before the closed-or-superseded check. -- All 17 new tests and the updated wiring test fail on the old code (source - stashed or restored from the base, then put back and sha-checked). - Mutants each turn the matching tests red: bound from the ask, holds one after - another, the look and the walk side by side, no re-ask of the folders or of - the walk, sign-in tabs held, the steps held but not awaited, logging every - hold, the launch-line log dropped, and an await with nothing to hold. - -Not measured: the split of the remaining 0.4 to 0.5 s. The tab's own Windows -PowerShell start (5.2 s from spawn to the stand-in in the green run) is the -runner's cold start, outside these holds. + as one of the holds, all awaited before the closed-or-superseded check; + `pty-spawn-waits-for-spawn-folders.test.ts`: its stand-in answers as the + real module does. +- Each new or changed test fails without its fix (source restored from the + commit before, or the helper taken out, then put back and sha-checked), but + one: the "held only by another hold" test guards kept behaviour and is + proven by mutants. Mutants each turn the matching tests red: bound from the + ask, holds one after another, the look and the walk side by side, sign-in + tabs held, the steps held but not awaited, an await with nothing to hold; + the ask again whenever the folders are wanted, with the whole bound, after + a wait that ran out, from the launch's ask, or only for launches held for + the folders; the module ignoring the time it is given or answering wrongly; + logging every hold, only by time, from 250 ms, with the old words; the script + state dropped, said for every launch, or in a line of its own; the prompt + test matching the banner or missing a wrapped location. + +Not measured: the split of the remaining 0.4 to 0.5 s, and the check's start +time at boot. The tab's own Windows PowerShell start (5.2 s from spawn to the +stand-in in the green run) is the runner's cold start, outside these holds. diff --git a/src/main/script-folders.ts b/src/main/script-folders.ts index c9a182053..5561d32aa 100644 --- a/src/main/script-folders.ts +++ b/src/main/script-folders.ts @@ -33,11 +33,20 @@ // the start of this run's check, not from each launch's ask // (aicc_planning#513): a check still running that long after it began is a // cold start's, which main saw take 8.8 to 13.6 s on a runner's first app, -// and a launch that waited a bound of its own then started without the -// scripts all the same, its wait spent on nothing. A folder the rule cannot -// make owner-only (a network share, a FAT drive) is said once at start, and -// the features its scripts serve are skipped for the run; the sessions still -// start. +// where a launch that waited a bound of its own started without the scripts +// all the same. That is a trade, not a free gain. A tab asked for while the +// check runs (restored at start, or opened in the first seconds) starts +// sooner, by up to the time between the check's start and its ask (about +// 2.5 s on the runner); but when the check ends 5 s or more after it began +// and yet within 5 s of the ask, a bound from the ask would have waited for +// it, and that tab now starts without the scripts: no status line of the +// app's for the session's whole life, and the direct Claude Code line, not +// the resume list. None of the checks measured so far ended in that window +// (1.0 to 3.5 s, or 8.8 s and later); it is the owner's choice, raised with +// #513, whether a small wait counted from the ask should cover it. A folder +// the rule cannot make owner-only (a network share, a FAT drive) is said +// once at start, and the features its scripts serve are skipped for the run; +// the sessions still start. import * as fs from 'fs' import * as path from 'path' import { logWarn } from './debug-logger' @@ -89,7 +98,10 @@ function noRead(a: Asked | undefined): boolean { * (aicc_planning#513). As main saw the check (the owner-only call), it took * 1.0 to 1.6 s in every later app on a runner and 2.6 to 3.5 s with the * disk cache purged; a runner's first app, whose first Windows PowerShell - * starts cold, took 8.8 to 13.6 s (CONTEXT.d/2026-11-27-b20-snap-d1.md). */ + * starts cold, took 8.8 to 13.6 s (CONTEXT.d/2026-11-27-b20-snap-d1.md). + * The trade (the header of this file): a check that ends 5 s or more after + * it began, but within 5 s of a launch's ask, is no longer waited for, and + * that launch starts without its status line and resume list. */ export const SCRIPT_FOLDERS_LAUNCH_WAIT_MS = 5000 /** How much of the rule's reason a warning carries. */ const DETAIL_MAX = 300 From ece28f23d8efbc5d071cb00f9a6904612e973e4b Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:00:55 +0000 Subject: [PATCH 22/79] fix(pty): bound the scripts folders' wait from each launch's own ask again Round 3 on aicc_planning#513 step 2. The run-wide deadline for the scripts folders' wait is dropped, decided by the orchestrator with the owner away, under the owner's standing rules (decide, no option rounds; the status line is a top priority). Under that deadline a tab asked late into a slow check (one that ended 5 s or more after it began, but within 5 s of the tab's ask) started without the app's status line for the session's whole life, and without the resume list. That costs more than the up to about 2.5 s of wait it saved on a slow cold start, and the holds now run side by side, so they no longer add up. - script-folders.ts: as on 591eb8fb. awaitScriptFolders waits at most its bound from its own call; scriptFoldersWaitLeft and the check's start time are gone. SCRIPT_FOLDERS_LAUNCH_WAIT_MS now says why the bound counts from the ask. - pty-handlers.ts: holdForScripts holds while the check runs, as before, and the hold stays one of the side-by-side holds. A sign-in tab is still not held for it: its line (localSignInLine) passes no --settings and no resume list, so it runs none of the scripts. The Codex hook folders' comment now says what holds: when the scripts wait ran out its bound first, the hook folders' wait covers what is left of the check and the deploys too. - script-folders.test.ts: as on the base; its three deadline tests go with the deadline. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty-handlers.ts | 20 +++---- src/main/script-folders.ts | 73 +++++++------------------- tests/unit/main/script-folders.test.ts | 41 +-------------- 3 files changed, 30 insertions(+), 104 deletions(-) diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index b0266323b..e58c4fccb 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -54,7 +54,7 @@ import { CODEX_PRESETS, } from '../sanitize-restored-spawn-options' import { startProfileStepsPending, startProfileStepsSettled } from '../account-profiles' -import { scriptFoldersPending, scriptFoldersWaitLeft, awaitScriptFolders } from '../script-folders' +import { scriptFoldersPending, awaitScriptFolders } from '../script-folders' import { claudeStartLookupPending, awaitClaudeStartLookup } from '../claude-start-lookup' import { claudeLaunchWalkPending, awaitClaudeLaunchWalk } from '../claude-launch-walk' import { gsudoAnswerKept, gsudoLookAnswered } from '../gsudo-lookup' @@ -1098,12 +1098,12 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // resources folder's scripts folders, and the deploys into them, still // run (script-folders.ts) waits for them, bounded, as a prepared spawn, // so a tab restored at start gets its status line, resume list and hooks; - // past the bound it starts without them. The bound is the run's, counted - // from the check's start (scriptFoldersWaitLeft): a launch asked for once - // it has passed is not held for a check that has not come in its usual - // time (aicc_planning#513). A sign-in tab is not held for them: its line - // runs no script of the app's (local-sign-in-tab.ts localSignInLine). - const holdForScripts = launchProvider !== null && !options?.shellOnly && !options?.ssh && scriptFoldersPending() && scriptFoldersWaitLeft() > 0 + // past the bound (SCRIPT_FOLDERS_LAUNCH_WAIT_MS, counted from this + // launch's own ask) it starts without them. A sign-in tab is not held for + // them: its line runs no script of the app's (local-sign-in-tab.ts + // localSignInLine: no --settings, so no status line of the app's, and no + // resume list). + const holdForScripts = launchProvider !== null && !options?.shellOnly && !options?.ssh && scriptFoldersPending() // On Windows, while the start still looks for Claude Code // (claude-start-lookup.ts: its walk of PATH and, when that finds none, // the PATH refresh, the first Claude Code lookup and the version probe): @@ -1270,8 +1270,10 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // them are over (the spawn's folders, the walk of PATH). Each is timed // (heldFor). The scripts folders come before a Codex launch's own wait // for its hook folders below: the start wires those only after the - // scripts folders' check and the deploys (index.ts), so each wait's - // bound then covers its own work alone. + // scripts folders' check and the deploys (index.ts). When the scripts + // wait saw them end, the hook folders' wait covers its own work alone; + // when it ran out its bound first, the hook folders' wait, bounded from + // its own call, covers what is left of the check and the deploys too. // // The session folders have one bound for the whole launch, // SPAWN_FOLDERS_WAIT_MS across every wait it makes for them (its hold diff --git a/src/main/script-folders.ts b/src/main/script-folders.ts index 5561d32aa..c407c5dab 100644 --- a/src/main/script-folders.ts +++ b/src/main/script-folders.ts @@ -29,24 +29,10 @@ // // A local session launch waits for this, bounded // (awaitScriptFolders, from pty-handlers), so a tab restored at start has its -// scripts; past the bound it starts without them. The bound is counted from -// the start of this run's check, not from each launch's ask -// (aicc_planning#513): a check still running that long after it began is a -// cold start's, which main saw take 8.8 to 13.6 s on a runner's first app, -// where a launch that waited a bound of its own started without the scripts -// all the same. That is a trade, not a free gain. A tab asked for while the -// check runs (restored at start, or opened in the first seconds) starts -// sooner, by up to the time between the check's start and its ask (about -// 2.5 s on the runner); but when the check ends 5 s or more after it began -// and yet within 5 s of the ask, a bound from the ask would have waited for -// it, and that tab now starts without the scripts: no status line of the -// app's for the session's whole life, and the direct Claude Code line, not -// the resume list. None of the checks measured so far ended in that window -// (1.0 to 3.5 s, or 8.8 s and later); it is the owner's choice, raised with -// #513, whether a small wait counted from the ask should cover it. A folder -// the rule cannot make owner-only (a network share, a FAT drive) is said -// once at start, and the features its scripts serve are skipped for the run; -// the sessions still start. +// scripts; past the bound it starts without them. A folder the rule cannot +// make owner-only (a network share, a FAT drive) is said once at start, and +// the features its scripts serve are skipped for the run; the sessions still +// start. import * as fs from 'fs' import * as path from 'path' import { logWarn } from './debug-logger' @@ -91,17 +77,15 @@ function noRead(a: Asked | undefined): boolean { return !a?.answer || a.answer.unread === true } -/** How long after this run's check began a local launch may still wait for - * the check and the deploys (awaitScriptFolders): one deadline for the run, - * never a fresh bound per launch. A launch asked for 3 s into the check - * waits at most 2 s more, and one asked for later is not held for it at all - * (aicc_planning#513). As main saw the check (the owner-only call), it took - * 1.0 to 1.6 s in every later app on a runner and 2.6 to 3.5 s with the - * disk cache purged; a runner's first app, whose first Windows PowerShell - * starts cold, took 8.8 to 13.6 s (CONTEXT.d/2026-11-27-b20-snap-d1.md). - * The trade (the header of this file): a check that ends 5 s or more after - * it began, but within 5 s of a launch's ask, is no longer waited for, and - * that launch starts without its status line and resume list. */ +/** How long a local launch waits for this run's check and deploys, counted + * from that launch's own ask (awaitScriptFolders). Not a deadline counted + * from the check's start: aicc_planning#513 tried one and dropped it, since + * a tab asked late into a slow check would then start without the app's + * status line for the session's whole life, a bigger cost than the wait it + * saved. As main saw the check, it took 1.0 to 1.6 s in every later app on + * a runner, 2.6 to 3.5 s with the disk cache purged, and 8.8 to 13.6 s in a + * runner's first app, whose first Windows PowerShell starts cold + * (CONTEXT.d/2026-11-27-b20-snap-d1.md). */ export const SCRIPT_FOLDERS_LAUNCH_WAIT_MS = 5000 /** How much of the rule's reason a warning carries. */ const DETAIL_MAX = 300 @@ -143,9 +127,6 @@ let phase: Phase = 'idle' let passed = new Map() /** Launches waiting for the deploys to have run. */ let waiters: Array<() => void> = [] -/** When this run's check began (performance.now(), a clock that never goes - * back), or null when none began. */ -let checkBeganAt: number | null = null /** A folder's identity (its volume and file id), or null when the file system * gives none. */ @@ -179,7 +160,6 @@ function scriptFolders(resourcesDir: string): [string, string] { * scripts serve is skipped for the run. Never throws. */ export async function secureScriptFolders(resourcesDir: string, secure: SecureScriptFolders): Promise { phase = 'securing' - checkBeganAt = performance.now() passed = new Map() const refused: Array<{ name: string; why: string }> = [] try { @@ -232,32 +212,16 @@ export function scriptFoldersDeployed(): void { } } -/** Whether this run's check and deploys are still running. A launch asked - * for now waits for them only while scriptFoldersWaitLeft() is above 0 - * too (awaitScriptFolders). */ +/** Whether this run's check and deploys are still running (a launch that + * starts now waits for them, awaitScriptFolders). */ export function scriptFoldersPending(): boolean { return phase === 'securing' || phase === 'deploying' } -/** How long, at most, a launch asked for now would wait for this run's check - * and deploys: `waitMs` less the time since the check began, never below 0; - * all of `waitMs` when no check began. The deadline is the run's, counted - * from the check's start (SCRIPT_FOLDERS_LAUNCH_WAIT_MS), so a check that - * has run that long holds no launch any more. It says nothing of whether the - * check still runs (scriptFoldersPending). */ -export function scriptFoldersWaitLeft(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_MS): number { - if (checkBeganAt === null) return waitMs - return Math.max(0, checkBeganAt + waitMs - performance.now()) -} - -/** A local launch: wait for this run's check and deploys, at most until - * `waitMs` after the check began (scriptFoldersWaitLeft). At once when they - * ran, when nothing started them, or when that deadline has passed. Never - * rejects. */ +/** A local launch: wait, at most `waitMs`, for this run's check and deploys. + * At once when they ran, or when nothing started them. Never rejects. */ export function awaitScriptFolders(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_MS): Promise { if (!scriptFoldersPending()) return Promise.resolve() - const left = scriptFoldersWaitLeft(waitMs) - if (left <= 0) return Promise.resolve() return new Promise((resolve) => { let done = false const finish = (): void => { @@ -266,7 +230,7 @@ export function awaitScriptFolders(waitMs: number = SCRIPT_FOLDERS_LAUNCH_WAIT_M clearTimeout(timer) resolve() } - const timer = setTimeout(finish, left) + const timer = setTimeout(finish, waitMs) ;(timer as { unref?: () => void }).unref?.() waiters.push(finish) }) @@ -327,5 +291,4 @@ export function __resetScriptFoldersForTests(): void { phase = 'idle' passed = new Map() waiters = [] - checkBeganAt = null } diff --git a/tests/unit/main/script-folders.test.ts b/tests/unit/main/script-folders.test.ts index f4d2005ba..da8b81e81 100644 --- a/tests/unit/main/script-folders.test.ts +++ b/tests/unit/main/script-folders.test.ts @@ -30,7 +30,7 @@ vi.mock('../../../src/main/debug-logger', () => ({ })) import { - secureScriptFolders, scriptFoldersDeployed, scriptFoldersPending, scriptFoldersWaitLeft, awaitScriptFolders, scriptFolderRefusal, + secureScriptFolders, scriptFoldersDeployed, scriptFoldersPending, awaitScriptFolders, scriptFolderRefusal, checkDeployedScript, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS, } from '../../../src/main/script-folders' import type { SecureScriptFolders } from '../../../src/main/script-folders' @@ -436,43 +436,4 @@ describe('awaitScriptFolders: a local launch waits for the start, bounded', () = expect(done).toBe(true) expect(SCRIPT_FOLDERS_LAUNCH_WAIT_MS).toBe(5000) }) - - // aicc_planning#513: the bound is the run's, counted from the check's start, - // not a fresh one from each launch's ask. Mutation to prove this can fail: - // count it from the ask (setTimeout(finish, waitMs)). - it('a launch asked for 3 s into a check that has not answered waits only to 5 s after the check began', async () => { - vi.useFakeTimers() - void secureScriptFolders(res, () => new Promise(() => {})) - await vi.advanceTimersByTimeAsync(3000) - let done = false - void awaitScriptFolders().then(() => { done = true }) - await vi.advanceTimersByTimeAsync(1999) - expect(done).toBe(false) - await vi.advanceTimersByTimeAsync(1) - expect(done, 'ended at the run\'s deadline').toBe(true) - expect(scriptFoldersPending(), 'the check itself still runs').toBe(true) - }) - - // Mutation to prove this can fail: count the bound from the ask. - it('past the run\'s deadline a launch does not wait at all, though the check still runs', async () => { - vi.useFakeTimers() - void secureScriptFolders(res, () => new Promise(() => {})) - await vi.advanceTimersByTimeAsync(SCRIPT_FOLDERS_LAUNCH_WAIT_MS + 1) - expect(scriptFoldersPending()).toBe(true) - let done = false - void awaitScriptFolders().then(() => { done = true }) - await vi.advanceTimersByTimeAsync(0) - expect(done).toBe(true) - }) - - it('the wait left: the whole bound with no check begun, less the time since it began, never below 0', async () => { - expect(scriptFoldersWaitLeft()).toBe(SCRIPT_FOLDERS_LAUNCH_WAIT_MS) - expect(scriptFoldersWaitLeft(10)).toBe(10) - vi.useFakeTimers() - void secureScriptFolders(res, () => new Promise(() => {})) - await vi.advanceTimersByTimeAsync(3000) - expect(scriptFoldersWaitLeft()).toBe(2000) - await vi.advanceTimersByTimeAsync(3000) - expect(scriptFoldersWaitLeft()).toBe(0) - }) }) From 894fab7ff70b9b7356ed7a4a79f606ca1a116528 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:00:55 +0000 Subject: [PATCH 23/79] test(pty): read a first tab's scripts wait from its own ask, beside the other holds Round 3 on aicc_planning#513 step 2, with the run's deadline dropped. - The evidence case: a check that never answers, the tab asked 3 s in, beside a 1.3 s folders hold and a 0.4 s look for Claude Code. It spawns 5 s after its ask, not 5.4 s. Red on round 2's source (d58277d8, the run's deadline: 2 s), under a deadline from the check's start put back into the fixed code (2 s), and with the holds one after another (5.4 s). - New: a check that ends 6 s after it began, with the tab asked 3 s in, is waited for, and at the spawn the resume list's script may be run (checkDeployedScript, as pty-manager reads it). Red on the same two deadlines and with the scripts hold taken out. Its check at the spawn is red on its own under the deadline (the script not yet deployed), with the test's earlier checks taken out. - The run-deadline cases go. The short still-pending line is read from a 500 ms look for Claude Code, not the scripts wait's last 500 ms; red when a hold is said only by its time. - The pairs' comment says what the one-after-another mutant shows: a pair whose second hold in the old order starts its clock at its own call spawns at 13 s; the others still spawn at 8 s and are caught by their lines. Each mutant was applied in place, the tests run, and the files restored byte for byte and sha256-checked. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- .../main/pty-spawn-holds-side-by-side.test.ts | 113 ++++++++++++------ 1 file changed, 79 insertions(+), 34 deletions(-) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index bf25238c3..74513451d 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -9,9 +9,11 @@ * its own 5 s bound, and the other holds ran after it, one after another. * Here: * - * - a launch waits for the scripts folders' check at most until the run's - * deadline, counted from the check's start (script-folders.ts - * SCRIPT_FOLDERS_LAUNCH_WAIT_MS), not a bound of its own from its ask; + * - a launch waits for the scripts folders' check at most its own bound, + * counted from its ask (script-folders.ts SCRIPT_FOLDERS_LAUNCH_WAIT_MS), + * as before #513: never a deadline counted from the check's start, under + * which a tab asked late into a slow check would start without its status + * line for the session's whole life; * - the holds it was held for run side by side, so it waits for the longest * of them, not their sum; * - a sign-in tab is not held for the scripts folders, whose scripts it never @@ -46,7 +48,14 @@ const pending = new Set() /** Each spawn that ran: its session id and when (the fake performance clock). */ const spawned: Array<{ sid: string; at: number }> = [] let preparations = 0 -const spawnNow = (sid: string): void => { live.add(sid); spawned.push({ sid, at: performance.now() }) } +/** What a test reads at each spawn (`probe`), kept in `seen`: what the + * launch would find then, as pty-manager reads it at its spawn. */ +const atSpawn = { probe: null as (() => unknown) | null, seen: [] as unknown[] } +const spawnNow = (sid: string): void => { + live.add(sid) + spawned.push({ sid, at: performance.now() }) + if (atSpawn.probe) atSpawn.seen.push(atSpawn.probe()) +} vi.mock('../../../src/main/pty-manager', () => ({ spawnPty: (_w: unknown, s: string) => spawnNow(s), writePty: vi.fn(), resizePty: vi.fn(), @@ -133,7 +142,7 @@ vi.mock('../../../src/main/provider-accounts', () => ({ })) // The scripts folders' check itself: not a stand-in. -const { secureScriptFolders, scriptFoldersDeployed, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS } = await import('../../../src/main/script-folders') +const { secureScriptFolders, scriptFoldersDeployed, checkDeployedScript, __resetScriptFoldersForTests, SCRIPT_FOLDERS_LAUNCH_WAIT_MS } = await import('../../../src/main/script-folders') const { SPAWN_FOLDERS_WAIT_MS } = await import('../../../src/main/spawn-folders-ahead') const { registerPtyHandlers } = await import('../../../src/main/ipc/pty-handlers') registerPtyHandlers(() => ({} as never)) @@ -189,7 +198,7 @@ function foldersWork(ms: number | 'never'): void { const HOLDS: Record void> = { "the scripts folders' check": (ms) => { // The real check, begun now, whose call never answers: a launch asked for - // now is held to its deadline, which is this test's 5 s. + // now is held its whole bound from its ask, which is this test's 5 s. expect(ms).toBe(SCRIPT_FOLDERS_LAUNCH_WAIT_MS) aCheckThatNeverAnswers() }, @@ -201,6 +210,7 @@ const HOLDS: Record void> = { beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'] }) live.clear(); pending.clear(); spawned.length = 0; preparations = 0 + atSpawn.probe = null; atSpawn.seen = [] logged.length = 0 holds.folders.want = false; holds.folders.work = null; holds.folders.asked = [] holds.steps.pending = false; holds.steps.settled = Promise.resolve() @@ -218,35 +228,65 @@ afterAll(() => { }) describe('the scripts folders\' check, when it does not come in its usual time (the Snap e2e\'s first tab)', () => { - // Mutation to prove this can fail: count the bound from the launch's ask - // (script-folders.ts awaitScriptFolders: setTimeout(finish, waitMs)). The - // launch then waits 5 s of its own and starts at 8 s, without the scripts - // all the same. - it('a tab asked for 3 s into the check starts 2 s later, at the run\'s deadline, not 5 s later', async () => { + // The evidence: the tab, asked about 3 s after the app's start while a + // check that did not answer within its bound ran, spawned 5.4 to 5.5 s + // after its ask: its 5 s for the check, then 0.4 to 0.5 s more (the other + // holds one after another, and the IPC; not split). Mutations to prove + // this can fail: await the holds one after another, as before #513 (the + // spawn then runs 5.4 s after the ask); bound the wait from the check's + // start, not from the ask (it then runs 2 s after the ask). + it('a check that never answers: the tab spawns 5 s from its ask, not 5 s plus the other holds', async () => { aCheckThatNeverAnswers() await after(3000) + HOLDS["the session folders' owner-only step"](1300) + HOLDS["the start's look for Claude Code"](400) const asked = performance.now() const started = outcome(spawn({}, S, CLAUDE_TAB)) - await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS - 3000 - 1) - expect(await asItStands(started), 'held for the check until its deadline').toBe('still held') + await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS - 1) + expect(await asItStands(started), 'held for the check, its whole bound from the ask').toBe('still held') expect(preparations).toBe(1) await after(1) - expect(await asItStands(started), 'started at the run\'s deadline, 5 s after the check began').toBe('started') - expect(spawned).toEqual([{ sid: S, at: asked + 2000 }]) + expect(await asItStands(started), 'started at the bound, the other holds run beside it').toBe('started') + expect(spawned).toEqual([{ sid: S, at: asked + SCRIPT_FOLDERS_LAUNCH_WAIT_MS }]) expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ - `[spawn] Session ${S}: held 2000 ms for the scripts folders' check (still pending when the wait ended)`, + `[spawn] Session ${S}: held 400 ms for the start's look for Claude Code (still pending when the wait ended)`, + `[spawn] Session ${S}: held 1300 ms for the session folders' owner-only step (no longer pending)`, + `[spawn] Session ${S}: held ${SCRIPT_FOLDERS_LAUNCH_WAIT_MS} ms for the scripts folders' check (still pending when the wait ended)`, ]) }) - // Mutation to prove this can fail: hold whenever the check still runs - // (drop scriptFoldersWaitLeft() > 0 from holdForScripts, and count the - // bound from the ask). - it('a tab asked for once the run\'s deadline has passed is not held for it at all', async () => { - aCheckThatNeverAnswers() - await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS + 1000) - expect(await asItStands(outcome(spawn({}, S, CLAUDE_TAB)))).toBe('started') - expect(preparations, 'not even a prepared spawn').toBe(0) - expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([]) + // The case a deadline counted from the check's start would lose: the + // check ends 6 s after it began, the tab was asked 3 s in, so its own 5 s + // bound covers the end, and it starts with its scripts (the status line's + // and the resume list's, read at its spawn as pty-manager reads them). + // Mutation to prove this can fail: bound the wait from the check's start + // (the tab then starts 2 s after its ask, while the check still runs, with + // no script deployed to run). + it('a check that ends 6 s after it began, with the tab asked 3 s in: the tab waits for it and starts with its scripts', async () => { + let answer = (): void => {} + const res = resourcesFolder() + const began = performance.now() + const checked = secureScriptFolders(res, (dirs) => new Promise((resolve) => { + answer = () => resolve(dirs.map((d) => { nodeFs.mkdirSync(d, { recursive: true, mode: 0o700 }); return { dir: d, ok: true } })) + })) + const script = join(res, 'scripts', 'resume-picker.js') + atSpawn.probe = () => checkDeployedScript(script) + await after(3000) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(3000) + expect(await asItStands(started), 'still held 3 s after its ask, within its bound').toBe('still held') + answer() + await checked + nodeFs.writeFileSync(script, '// the app\'s\n', { mode: 0o600 }) + scriptFoldersDeployed() + expect(await asItStands(started)).toBe('started') + expect(spawned, 'started as the deploys ended, 6 s after the check began').toEqual([{ sid: S, at: began + 6000 }]) + expect(asked).toBe(began + 3000) + expect(atSpawn.seen, 'the script may be run at its spawn').toEqual([{ ok: true }]) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 3000 ms for the scripts folders' check (no longer pending)`, + ]) }) // What the hold is for is kept: a check that comes in its usual time is @@ -288,11 +328,15 @@ describe('the holds a first tab is held for run side by side: it waits for the l // One after another, a hold whose clock starts at its own call (a bound, // or work begun there) began only once the hold before it was over, and // the first tab paid both: in the evidence, the scripts folders' 5 s, then - // the session folders' work. Mutation to prove each can fail: await the - // holds one after another, as before #513 (the spawn then runs at 13 s). + // what the others took. Mutation to prove each can fail: await the holds + // one after another, in the order before #513. Where a hold whose clock + // starts at its own call (the scripts folders' bound, the look for Claude + // Code) comes second in that order, the spawn then runs at 13 s; otherwise + // it still runs at 8 s, and the lines then say a hold took only what was + // left of it, or say nothing of it, not its own time. const pairs: Array<[string, string]> = [ - // The evidence's pair: the scripts folders' check (a launch held to its - // deadline) and the session folders made owner-only. + // The scripts folders' check (a launch held its whole bound) and the + // session folders made owner-only. ["the scripts folders' check", "the session folders' owner-only step"], ["the scripts folders' check", "the start's look for Claude Code"], ["the start's look for Claude Code", "the session folders' owner-only step"], @@ -341,16 +385,17 @@ describe('what is said of the holds', () => { ]) }) - // Mutation to prove this can fail: say a hold only when it took - // SPAWN_HOLD_LOG_MS or longer (drop `pending ||`). + // A 500 ms hold whose wait ends with what it waited for still pending + // (the stand-in look for Claude Code, which never answers). Mutation to + // prove this can fail: say a hold only when it took SPAWN_HOLD_LOG_MS or + // longer (drop `pending ||`). it('a hold whose wait ended with what it waited for still pending is said however short it was', async () => { - aCheckThatNeverAnswers() - await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS - 500) + HOLDS["the start's look for Claude Code"](500) const started = outcome(spawn({}, S, CLAUDE_TAB)) await after(500) expect(await asItStands(started)).toBe('started') expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ - `[spawn] Session ${S}: held 500 ms for the scripts folders' check (still pending when the wait ended)`, + `[spawn] Session ${S}: held 500 ms for the start's look for Claude Code (still pending when the wait ended)`, ]) }) }) From 30924608cb46d2882cac331ae5ea5856cd7f05d9 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:00:55 +0000 Subject: [PATCH 24/79] docs(context): record the Snap D1 holds' dropped deadline, expected saving and open decision Round 3 on aicc_planning#513 step 2. - Fix and the decisions: the run-wide scripts deadline and its trade are gone, decided by the orchestrator for the status line, with the reason. Only the runner's cold Windows PowerShell share of D1 stays open, for the owner. - The saving is now stated as expected, not measured: up to about 0.4 s for the evidence's first tab (the part of its 0.4 to 0.5 s after the scripts wait that was other holds), more where several holds each take long. The next Snap e2e dispatch of this head measures it, through its [spawn] lines and readings.promptSeenAt. - Who meets a run-out scripts wait now names the Codex case: its hook folders' wait usually brings the scripts back while the Hooks gateway listens; without the gateway the Codex resume list is lost too. - The known issue "A tab restored at start opened without the status line or the resume list" (app-knowledge.ts) needs nothing: a session that starts during the check again waits up to 5 seconds from its own start, as the entry says. - The sign-in tab's exemption is shown from the code (no --settings, no resume list, no picker script), and the tests and mutants are this round's. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 135 ++++++++++++++-------- 1 file changed, 90 insertions(+), 45 deletions(-) diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md index 90d622a54..56144cf33 100644 --- a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -2,17 +2,26 @@ Branch `fix/b28-snap-d1-evidence`, from beta at 591eb8fb (2.1.3-beta.27). Step 1 (the evidence capture in the Snap e2e's part one) is the `test(snap)` commits -before this entry; this is step 2, the fix at the cause, and its review round. - -### What this step fixes, and what it does not - -This step removes about 2 to 3 s of a first tab's wait at start. It does not -remove the D1 red, and #513 stays open. - -- In the evidence below, the tab was asked about 2.9 s after main's first - line. The scripts check begins at boot, about 0.3 to 0.6 s in (the review's - reading; not measured). Under the run's deadline the tab now waits about - 2.4 to 2.7 s for the check, not 5 s. +before this entry; this is step 2, the fix at the cause, and its review rounds. + +### What this step changes, and what it does not + +A first tab's holds now run side by side, so it waits for the longest of +them, not their sum. Its wait for the scripts folders' check is as on +591eb8fb: up to 5 s from its own ask. This step does not remove the D1 red, +and #513 stays open. + +- Expected saving, not measured: in the evidence below the tab waited its + full 5 s for the scripts check, then 0.4 to 0.5 s more. Only the part of + that which was other holds run after it is saved; the IPC, and the walk of + PATH asked again after the holds (one after the other by design), are not. + So the first tab is expected to spawn up to about 0.4 s sooner here. Where + several holds each take long (the session folders' work took 1.15 to + 1.36 s under load on CI), the saving is the sum less the longest. +- What will measure it: the next Snap e2e dispatch of this head writes one + `[spawn] Session : held N ms for (...)` line per hold that took + 1 s or more or ended still pending, and `readings.promptSeenAt`. Record the + measured figure here once that run exists. - In the failing run (47192226861) the spawn did happen: the tab showed Windows PowerShell's banner. Its own Windows PowerShell then did not reach its prompt in the rest of D1's 30 s, about 24 s or more if its holds took @@ -64,31 +73,34 @@ remaining 0.4 to 0.5 s (not split: no line said them). Who meets it: a tab asked for while the check runs (tabs restored at start, or one opened in the first seconds). Where Windows PowerShell is warm the check took 1.0 to 1.6 s on the runner (2.6 to 3.5 s with the disk cache purged); the -tab waits that long and gets its status line and resume list. Before this -step, a check that ended within 5 s of a tab's ask was waited for, and the tab -got them; one that ended later cost that tab 5 s, and it started without them. -A tab asked for once the check is over waits for nothing. +tab waits that long and gets its status line and resume list. A check that +ends within 5 s of a tab's ask is waited for, and the tab gets them; one that +ends later costs that tab 5 s, and it starts without them: a Claude Code tab +with no status line of the app's for the session's whole life, and the direct +line, not the resume list. A Codex launch then waits for its hook folders, +only while the Hooks gateway listens. The start wires those only after the +check and the deploys, so that wait (5 s, from its own call) usually brings +its scripts back. Without the gateway it starts without the Codex resume list +too. A tab asked for once the check is over waits for nothing. ### Fix -- script-folders.ts: the bound is the run's, counted from the check's start - (`scriptFoldersWaitLeft`). A tab asked 3 s into the check waits at most 2 s; - one asked once the deadline has passed is not held at all. For this hold - alone, no launch waits longer than before. -- That is a trade, stated in script-folders.ts too. A check that ends 5 s or - more after it began, but within 5 s of a tab's ask, was waited for before; - now that tab starts without the scripts: no status line of the app's for the - session's whole life, and the direct Claude Code line, not the resume list. - In the b20 record the first app's check ended 8.8 s in with the tab asked - about 3 s in, only about 0.8 s outside that window; no check measured so far - ended inside it. This is an owner choice (below). - pty-handlers.ts: the holds a launch is held for run side by side (`Promise.all`), so it waits for the longest, not the sum. The start's look for Claude Code and the launch's walk of PATH stay one after the other. The - session folders' owner-only step and the walk are asked again once every hold - is over, as before. With nothing to hold, the launch still goes on in the same - tick (the one-at-a-time rule relies on that). A sign-in tab is not held for - the scripts: its line runs none of them. + session folders' owner-only step and the walk are asked again once every + hold is over, as before. With nothing to hold, the launch still goes on in + the same tick (the one-at-a-time rule relies on that). +- The scripts folders' hold is one of them, bounded as on 591eb8fb: 5 s from + each launch's own ask. Round 2 had counted it from the check's start, one + deadline for the run; round 3 dropped that (decided below). +- A sign-in tab is not held for the scripts. Its line runs none of them, as + the code shows: pty-manager's shell-only branch types `localSignInLine` + (local-sign-in-tab.ts), which is `buildClaudeSignInLine` + (spawn-claude-command.ts) with no options, no `--settings` (so no status + line of the app's: that rides the per-session settings file a Claude Code + session's own launch writes, never a shell-only tab's), no resume list and + no picker script. - The session folders have one bound for the whole launch (`SPAWN_FOLDERS_WAIT_MS`, 10 s, across its hold and the ask again). The review found that running them side by side made a launch whose folders work @@ -112,6 +124,10 @@ A tab asked for once the check is over waits for nothing. shell` line every local launch already writes (`pickerScript=ready | not ready`), only for a launch that asked for the list; no line of its own. All carry the session id and nothing else. +- pty-handlers.ts's comment on the Codex hook folders now says what holds: + when the scripts wait saw the check and deploys end, the hook folders' wait + covers its own work alone; when it ran out its bound first, the hook + folders' wait covers what is left of the check and the deploys too. Safety is unchanged. The scripts hold guards nothing: a launch takes a script only through `checkDeployedScript` / `scriptFolderRefusal` at launch time, and @@ -119,12 +135,29 @@ a folder not yet checked fails closed (the feature is skipped). The session folders are still made owner-only before the spawn, and each writer still makes its own folder owner-only before it writes. -### Owner decisions raised - -1. The cold Windows PowerShell share of D1. A warm-up step before the Snap - step would change what D1 measures; TAB_MS stays. #513 stays open on this. -2. The scripts deadline's trade. Keep the run's deadline as is, or add a - small wait counted from the ask that the run's deadline caps. +User-facing surfaces: the known issue "A tab restored at start opened without +the status line or the resume list" (src/shared/app-knowledge.ts) needs +nothing. With the deadline dropped, a session that starts while the check +runs waits up to 5 seconds from its own start for it, which is what the entry +says, and its workaround stands. The side-by-side holds only shorten a first +tab's wait, and the `[spawn]` lines are log only. No tip, tour card or README +text names these holds. + +### Decided, and still open + +Decided by the orchestrator, with the owner away (2026-12-03), under the +owner's standing rules (decide, no option rounds; the status line is a top +priority): the run-wide scripts deadline is dropped. The scripts hold is +bounded again from each launch's own ask. Reason: under that deadline a tab +asked late into a slow check (one ending 5 s or more after it began, but +within 5 s of the tab's ask) started without the app's status line for the +session's whole life, and without the resume list. That costs more than up +to about 2.5 s of wait on a slow cold start, and the side-by-side holds +already keep the holds from adding up. + +Still open, an owner decision: the runner's cold Windows PowerShell share of +D1. A warm-up step before the Snap step would change what D1 measures; +TAB_MS stays. #513 stays open on this. ### Tests @@ -132,16 +165,19 @@ makes its own folder owner-only before it writes. pty:spawn handler over the real script-folders module, on fake timers, with a folders stand-in shaped as the real module (one work for every caller, each wait bounded by what it is given). Covers the evidence case (a check - that never answers: the tab asked 3 s in starts 2 s later; asked past the - deadline, not held), seven 5 s + 8 s pairs that spawn at 8 s rather than - 13 s, sign-in tabs, a check that answers in its usual time, the log rule - (1 s, or still pending), and the folders' one bound: work that never answers - spawns at 10 s with one call and one line (20 s and two calls before the - review round, 10 s on the base); done in time then wanted again spawns at - 15 s, not 18 s; held only by another hold keeps the whole bound. + that never answers, the tab asked 3 s in, beside a 1.3 s folders hold and a + 0.4 s look: the spawn runs 5 s after the ask, not 5.4 s), a check that ends + 6 s after it began with the tab asked 3 s in (waited for; at its spawn the + resume list's script may be run), seven 5 s + 8 s pairs that spawn at 8 s, + sign-in tabs, a check that answers in its usual time, the log rule (1 s, or + still pending), and the folders' one bound: work that never answers spawns + at 10 s with one call and one line (20 s and two calls before the review + round, 10 s on the base); done in time then wanted again spawns at 15 s, + not 18 s; held only by another hold keeps the whole bound. - `tests/unit/main/spawn-folders-off-main-thread.test.ts` (+1, 1 changed): a wait waits what it is given and answers whether the work ended in time. -- `tests/unit/main/script-folders.test.ts` (+3): the run's deadline. +- `tests/unit/main/script-folders.test.ts`: as on the base (round 2's three + deadline tests are gone with the deadline). - `tests/unit/main/pty-claude-picker-plain.test.ts` (+3): the script state in the launch's line, only for a resume-list launch, in no line of its own. - `tests/unit/e2e-launch-evidence.test.ts` (+2): the prompt D1 looks for, not @@ -162,7 +198,16 @@ makes its own folder owner-only before it writes. logging every hold, only by time, from 250 ms, with the old words; the script state dropped, said for every launch, or in a line of its own; the prompt test matching the banner or missing a wrapped location. +- Round 3 (the deadline dropped): the evidence case and the 6 s case are red + on round 2's source (the run's deadline: the tab spawns 2 s after its ask) + and under a deadline from the check's start put back into the fixed code. + The evidence case is red with the holds one after another too (5.4 s), and + the 6 s case with the scripts hold taken out. Its check of the script at the + spawn is red on its own under the deadline (the script not yet deployed), + with the test's earlier checks taken out. The short still-pending line, now + read from a 500 ms look, is red when a hold is said only by its time. Not measured: the split of the remaining 0.4 to 0.5 s, and the check's start -time at boot. The tab's own Windows PowerShell start (5.2 s from spawn to the +time at boot (it begins in a microtask after the start's synchronous setup, +index.ts). The tab's own Windows PowerShell start (5.2 s from spawn to the stand-in in the green run) is the runner's cold start, outside these holds. From 83a90ab0559fab6ef107c8234af478d93a099200 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:01:19 +0000 Subject: [PATCH 25/79] chore(wp1): refresh the legacy Codex manifest after round 3 of the first-tab holds fix Round 3 adds no file and matches no new path: the manifest head moves, and the counts, pathDigest 968553bf and predicate digest stay. The ledger is complete in the candidate phase. Co-Authored-By: Claude Opus 5.5 --- docs/wp1/legacy-codex-manifest.json | 6 +++--- tests/wp1/legacy-codex-ledger.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/wp1/legacy-codex-manifest.json b/docs/wp1/legacy-codex-manifest.json index a24ca7b5c..ffde2e858 100644 --- a/docs/wp1/legacy-codex-manifest.json +++ b/docs/wp1/legacy-codex-manifest.json @@ -1,8 +1,8 @@ { "schema": "wp1-legacy-codex-manifest/3", - "generatedAt": "2026-12-03T22:38:19.883Z", - "head": "bf9479dda31d64dd2894237abee7363898cbee8d", - "tree": "f9e9d4ea47708a02d20b22752e5b2760beddd260", + "generatedAt": "2026-12-04T00:01:07.107Z", + "head": "30924608cb46d2882cac331ae5ea5856cd7f05d9", + "tree": "9d07b4cb3104401930d3610f1f0e03e1b150d43b", "scannedWorkingTree": false, "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "predicates": [ diff --git a/tests/wp1/legacy-codex-ledger.json b/tests/wp1/legacy-codex-ledger.json index b2838fd1c..ad9411fca 100644 --- a/tests/wp1/legacy-codex-ledger.json +++ b/tests/wp1/legacy-codex-ledger.json @@ -2,7 +2,7 @@ "schema": "wp1-legacy-codex-ledger/2", "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "manifestPathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", - "manifestHead": "bf9479dda31d64dd2894237abee7363898cbee8d", + "manifestHead": "30924608cb46d2882cac331ae5ea5856cd7f05d9", "dispositions": { "retain": "unchanged observable behaviour, characterization proof", "move": "moved behind a package boundary and/or adapted at the call site, regression proof (newPath when relocated)", From d34718378ab79cab7d07203807226c939c76347c Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:20 +0000 Subject: [PATCH 26/79] fix(restore): reopen sessions saved for an update with nothing asked (#515) Save sessions on the update dialog now marks the saved set as saved for an update, with the version that saved it (SessionState.savedForUpdate). The next start of a NEWER version restores that set at the resume prompt's turn in the boot chain with no prompt (RestoreAfterUpdate), so the release notes and every page before it still come first. Each restored tab carries on on its own account whatever Resuming sessions says (shouldPredetermineRestoredAccount afterUpdate), so no account picker opens; a tab that cannot carry on says why in the tab, as a restore in the default mode does. The mark is used once: the offer never carries it, so the restore's own save and any write while the offer is up leave it out. A quit's Save, a crash's autosave, the same version starting again, an older version and a mark that does not read all keep today's resume prompt. The autosave is cancelled before the marked save, and a failed update writes the set again without it. Settings, Accounts help text under Resuming sessions now says the choice applies when the app reopens your sessions, and that after an update with Save sessions each session carries on as it was; the agent-sessions switch's text no longer says to resume within five minutes. Co-Authored-By: Claude Opus 5.5 --- src/renderer/App.tsx | 81 +++++++++++++------ .../components/RestoreAfterUpdate.tsx | 22 +++++ src/renderer/components/SettingsPage.tsx | 4 +- src/renderer/session-persistence.ts | 43 +++++++++- src/renderer/utils/sessionLaunch.ts | 10 ++- src/shared/types.ts | 7 ++ 6 files changed, 139 insertions(+), 28 deletions(-) create mode 100644 src/renderer/components/RestoreAfterUpdate.tsx diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 424c5d28b..c003f10b2 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -106,12 +106,13 @@ import LoggingConsentPrompt from './components/LoggingConsentPrompt' import LogsWipeModal from './components/LogsWipeModal' import { bootChain, launchDialogsSuppressed } from './utils/bootGates' import ResumeSessionsPrompt from './components/ResumeSessionsPrompt' +import RestoreAfterUpdate from './components/RestoreAfterUpdate' import GitHubPanel from './components/github/GitHubPanel' import OnboardingModal from './components/github/onboarding/OnboardingModal' import AutoDetectBanner from './components/github/AutoDetectBanner' import { handleAutoDetectAccept } from './utils/githubAutoDetectAccept' import type { SessionState } from './types/electron' -import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore } from './session-persistence' +import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, persistSessionState, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore, markSavedForUpdate, restoreOfferAtStart } from './session-persistence' import { useSessionAutosave, cancelSessionAutosave } from './hooks/useSessionAutosave' import { listenGoToSession } from './lib/goToSession' import { loggingConsentDue } from './utils/logging-consent' @@ -330,6 +331,12 @@ export default function App() { // this run. It is the whole saved set: a session whose provider cannot // launch is restored too and reopens as Not started (the prompt tags it). const [pendingRestore, setPendingRestore] = useState(null) + // aicc_planning#515: the saved set came from an app update the user chose + // Save sessions for, and this is a newer version (restoreOfferAtStart). Set + // with pendingRestore at the startup load: at the prompt's turn it is + // restored with nothing asked (RestoreAfterUpdate), each tab on its own + // account. + const [restoreAtOnce, setRestoreAtOnce] = useState(false) // P3.5 (a C item): while the prompt is unanswered, every write of the // session file keeps the set it offers (session-persistence), so a tab // launched meanwhile never overwrites it on disk. @@ -755,7 +762,14 @@ export default function App() { pingHosts: () => { void pingAllDetachedHosts() }, reconcile: () => useCommandBarStore.getState().reconcile(useSessionStore.getState().sessions.map((s) => s.id)), }) - if (savedState) setPendingRestore(savedState) + if (savedState) { + // aicc_planning#515: saved for an update by an older version, it is + // restored at the prompt's turn with nothing asked; the offer never + // carries the mark, so the restore's save leaves it out. + const { offer, atOnce } = restoreOfferAtStart(savedState, __APP_VERSION__) + setRestoreAtOnce(atOnce) + setPendingRestore(offer) + } // Nothing to ask about: nothing is restored, and what this start // brought back is the left-running registry just hydrated. else setRestoreTally({ sessions: [], detached: useDetachedRemotesStore.getState().entries }) @@ -918,6 +932,13 @@ export default function App() { } catch { stateToSave = buildSessionState() } + if (isUpdate) { + // aicc_planning#515: saved for this update, by this version, so the + // newer version's start reopens the set with nothing asked. A pending + // autosave would write the set again without the mark. + cancelSessionAutosave() + stateToSave = markSavedForUpdate(stateToSave, __APP_VERSION__) + } await window.electronAPI.session.save(stateToSave) console.log('[App] Session state saved') if (isUpdate) { @@ -930,6 +951,10 @@ export default function App() { } catch (err) { console.error('[App] Error during graceful shutdown:', err) if (!isUpdate) window.electronAPI.window.allowClose() + // aicc_planning#515: the update failed and the app stays, so the saved + // set is written again without the update's mark: a later start of this + // or another version asks as before. + else void persistSessionState() setIsClosing(false) // The update failed and the app stays: a later plain close must read // Closing..., not Updating... @@ -1347,6 +1372,28 @@ export default function App() { // here. } + // The restore of the saved set: the resume prompt's Resume, and + // (aicc_planning#515, `afterUpdate`) the restore after an app update the + // user chose Save sessions for, which asks nothing and carries each tab on + // on its own account. + const resumeSaved = (saved: SessionState, afterUpdate: boolean) => { + // Every saved session, as before: one whose provider cannot + // launch reopens as Not started and keeps its conversation, so a + // Restart once the provider is on carries on. + // What this start brings back, from the saved set itself (every + // session in it reopens, Not started or not), before the restore + // lands and before anything else can launch. + setRestoreTally({ sessions: saved.sessions, detached: saved.detachedRemotes ?? [] }) + // ADR-009 (Lens C, R7): mark the restore in flight BEFORE clearing + // the prompt, so a close before it lands keeps the saved file. + restoreUnsettledRef.current = true + setPendingRestore(null) + // P3.5: answered -- the file no longer keeps the offer (at once, + // before the restore's own write). + setUnansweredRestore(null) + void restoreSavedSessions(saved, restoreUnsettledRef, { probeGoneSessions, pingAllDetachedHosts, afterUpdate }) + } + // First-launch gates each have an independent trigger (wipe detection IPC, // version compare, settings flags, staggered boot timers); without a shared // priority they mount simultaneously and stack, with DOM order deciding who @@ -1494,28 +1541,16 @@ export default function App() { {/* Now a proper gate (bootGates: 'resume', lowest priority) rather than a surface that merely stepped around onboarding. It used to be gated on `bootGate !== 'onboarding'` alone, so a launch that showed - release notes painted this prompt over them. */} - {bootGate === 'resume' && pendingRestore && ( + release notes painted this prompt over them. aicc_planning#515: + after an app update the user chose Save sessions for, the same + turn restores with nothing asked (RestoreAfterUpdate), each tab on + its own account. */} + {bootGate === 'resume' && pendingRestore && (restoreAtOnce ? ( + resumeSaved(pendingRestore, true)} /> + ) : ( { - // Every saved session, as before: one whose provider cannot - // launch reopens as Not started and keeps its conversation, so a - // Restart once the provider is on carries on. - const saved = pendingRestore - // What this start brings back, from the saved set itself (every - // session in it reopens, Not started or not), before the restore - // lands and before anything else can launch. - setRestoreTally({ sessions: saved.sessions, detached: saved.detachedRemotes ?? [] }) - // ADR-009 (Lens C, R7): mark the restore in flight BEFORE clearing - // the prompt, so a close before it lands keeps the saved file. - restoreUnsettledRef.current = true - setPendingRestore(null) - // P3.5: answered -- the file no longer keeps the offer (at once, - // before the restore's own write). - setUnansweredRestore(null) - void restoreSavedSessions(saved, restoreUnsettledRef, { probeGoneSessions, pingAllDetachedHosts }) - }} + onResume={() => resumeSaved(pendingRestore, false)} onDontOpen={() => { const saved = pendingRestore setPendingRestore(null) @@ -1551,7 +1586,7 @@ export default function App() { } }} /> - )} + ))} {/* Last in the boot chain (bootGates): the second page of one upgrade story — release notes, then this — and its per-row copy counts read diff --git a/src/renderer/components/RestoreAfterUpdate.tsx b/src/renderer/components/RestoreAfterUpdate.tsx new file mode 100644 index 000000000..a0bedd5eb --- /dev/null +++ b/src/renderer/components/RestoreAfterUpdate.tsx @@ -0,0 +1,22 @@ +import { useEffect, useRef } from 'react' + +/** + * aicc_planning#515: the resume prompt's turn in the boot chain (bootGates, + * 'resume') when the saved set came from an app update the user chose Save + * sessions for, read by a newer version (restoreOfferAtStart's `atOnce`). + * Nothing is asked: it shows nothing and, once, restores (`onRestore`, the + * same restore the prompt's Resume starts). It takes the prompt's turn rather + * than restoring at load, so every page the chain shows before it (the + * release notes, the indexing notice) still comes first, and nothing starts + * behind one. Once only, also when React runs its effects twice in + * development. + */ +export default function RestoreAfterUpdate({ onRestore }: { onRestore: () => void }): null { + const done = useRef(false) + useEffect(() => { + if (done.current) return + done.current = true + onRestore() + }, [onRestore]) + return null +} diff --git a/src/renderer/components/SettingsPage.tsx b/src/renderer/components/SettingsPage.tsx index 563c11c62..b0c77dddf 100644 --- a/src/renderer/components/SettingsPage.tsx +++ b/src/renderer/components/SettingsPage.tsx @@ -627,7 +627,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat /> Claude Code and Codex sessions through the session helper - Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens: resume your sessions within five minutes of that and its tab takes the same session over. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. + Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens, which reopens your tabs by itself once the pages it opens with are closed: within five minutes of it opening, its tab takes the same session over. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. {/* 2.1.3-beta.17 (plan section A2): remote sessions through the session helper, a preview (Windows). */} @@ -708,7 +708,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat

- Only matters with two or more Claude accounts. Applies when the app restarts and reopens your sessions. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in. + Only matters with two or more Claude accounts. Applies when the app reopens your sessions. After an update where you chose Save sessions, each session carries on as it was, with nothing asked. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.

diff --git a/src/renderer/session-persistence.ts b/src/renderer/session-persistence.ts index 7c1b458a2..f51850223 100644 --- a/src/renderer/session-persistence.ts +++ b/src/renderer/session-persistence.ts @@ -9,6 +9,7 @@ import { markSessionForResumePicker } from './utils/resumePicker' import { shouldPredetermineRestoredAccount } from './utils/sessionLaunch' import { isConfigLaunchBlocked } from './hooks/useLaunchConfig' import { isProviderId } from '../shared/providers/ids' +import { compareVersions, releaseLine } from '../shared/version-order' import { tryGetRendererProvider } from './providers/core' // Type-only: livenessStore imports persistSessionState from THIS module, so a // value import of either store here closes a renderer import cycle (benign @@ -353,6 +354,38 @@ export async function loadSavedStateAtStartup(deps: { return null } +/** + * aicc_planning#515: the saved set Save sessions on the UPDATE dialog writes, + * marked as saved for an update by `version` (the app's own). Only that save + * marks it: a quit's Save, the autosave and every other write build a set + * without the mark (buildSessionState), so a later write drops it. + */ +export function markSavedForUpdate(state: SessionState, version: string): SessionState { + return { ...state, savedForUpdate: { fromVersion: version } } +} + +/** + * aicc_planning#515: how this start offers the saved set. `atOnce` when it + * was saved for an app update (markSavedForUpdate) by a version older than + * this one (`currentVersion`): the start that follows that update reopens it + * with no resume prompt, each tab on the account it was on (App's + * RestoreAfterUpdate, restoreSavedSessions' `afterUpdate`). Anything else + * (a quit's save, a crash's autosave, the same version starting again, an + * older one, a mark that does not read) is offered as before. `offer` never + * carries the mark: the restore's own save, and every write while the offer + * is open, write the set without it, so a later start asks as before. A set + * with no mark is offered as it is (the same object). + */ +export function restoreOfferAtStart(saved: SessionState, currentVersion: string): { offer: SessionState; atOnce: boolean } { + if (saved.savedForUpdate === undefined) return { offer: saved, atOnce: false } + const { savedForUpdate, ...offer } = saved + const from = savedForUpdate !== null && typeof savedForUpdate === 'object' ? (savedForUpdate as { fromVersion?: unknown }).fromVersion : undefined + // compareVersions reads a version that does not parse as the oldest there + // is, so the mark's own version must parse before it is compared. + const atOnce = typeof from === 'string' && releaseLine(from) !== null && releaseLine(currentVersion) !== null && compareVersions(currentVersion, from) > 0 + return { offer, atOnce } +} + /** * The zero-session close (no dialog). rc.15 review R7: while the restore prompt * is still unanswered the saved file holds the cards AND the remotes the user @@ -431,6 +464,10 @@ export async function discardAndClose(deps: { export interface RestoreSavedSessionsDeps { probeGoneSessions: typeof probeGoneSessions pingAllDetachedHosts: typeof pingAllDetachedHosts + /** aicc_planning#515: the restore after an app update the user chose Save + * sessions for (restoreOfferAtStart's `atOnce`): every tab carries on on + * the account it was on, whatever Resuming sessions says. */ + afterUpdate?: boolean } // Restore saved sessions on startup. Lifted out of App.tsx (2.1.1) as a pure @@ -536,10 +573,12 @@ export async function restoreSavedSessions( // Mark them RESTORED regardless of mode (#446): "was restored" is a // property of the session, and it is what lets a cancelled resume-gate // keep the session rather than discard it. Only the predetermined mark - // (which SKIPS the gate) is mode-conditional. + // (which SKIPS the gate) is mode-conditional. aicc_planning#515: the + // restore after an update the user chose Save sessions for skips it in + // either mode: each tab carries on on its own account. const restoredIds = restoredSessions.map((s) => s.id) useAccountGateStore.getState().markRestored(restoredIds) - if (shouldPredetermineRestoredAccount(useSettingsStore.getState().settings.resumeAccountMode)) { + if (shouldPredetermineRestoredAccount(useSettingsStore.getState().settings.resumeAccountMode, { afterUpdate: deps.afterUpdate === true })) { markRestoredSessionsPredetermined(restoredIds) } diff --git a/src/renderer/utils/sessionLaunch.ts b/src/renderer/utils/sessionLaunch.ts index ff2ec622e..167ea1df3 100644 --- a/src/renderer/utils/sessionLaunch.ts +++ b/src/renderer/utils/sessionLaunch.ts @@ -179,8 +179,16 @@ export function resolveResumeAccountMode(value: unknown): 'ask' | 'auto-last' { * (the default), false in 'ask' (let the gate open per restored session). * Extracted so the App restore branch is pinned by a unit test rather than * living only in App.tsx (which is not unit-testable). + * + * aicc_planning#515: the restore after an app update the user chose Save + * sessions for (`afterUpdate`) carries every tab on on the account it was on, + * whatever the setting says: the sessions were kept running for the update, + * and a tab the session helper kept is taken over only on that account. A + * tab that cannot carry on as it is (its account gone, its provider off) + * says why in the tab, as a restore in 'auto-last' does. */ -export function shouldPredetermineRestoredAccount(resumeAccountMode: unknown): boolean { +export function shouldPredetermineRestoredAccount(resumeAccountMode: unknown, restore: { afterUpdate?: boolean } = {}): boolean { + if (restore.afterUpdate === true) return true return resolveResumeAccountMode(resumeAccountMode) === 'auto-last' } diff --git a/src/shared/types.ts b/src/shared/types.ts index 8bc6c85a4..6fa47e177 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -358,6 +358,13 @@ export interface SessionState { * yet (the next run counts them); `gapMs` (P3.16): the part of those * turns a run had counted. */ conversationRunningTimes?: Array<{ id: string; ms: number; until: number; gaps?: Array<{ from: number; to: number }>; gapMs?: number }> + /** aicc_planning#515: written only by Save sessions on the update dialog, + * with the version that saved it. A start of a NEWER version reopens such + * a set with no resume prompt and no account question + * (session-persistence.ts restoreOfferAtStart); the restore's own save + * leaves it out, so a later start asks as before. Main round-trips it + * untouched, as it does detachedRemotes. */ + savedForUpdate?: { fromVersion: string } } /** From 8e4f2c3696620143b46a88fddac1d7cd0591fd55 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:38 +0000 Subject: [PATCH 27/79] fix(update): say what each close and update choice does to the open tabs (#514) The close and update dialogs now say, in plain lines with counts, what Save sessions does to each kind of tab open, then what Close sessions does. A kind with none open has no line. Update: how many keep running through the update and are back in their tabs straight away, SSH sessions that keep running on their hosts and reconnect, the rest that restart and pick up their conversations, terminals that start again, sign-in or install tabs that end. Quit: held sessions end; Claude Code and Codex tabs pick up their conversations at the next launch; SSH Persistent sessions keep running on their hosts. Close sessions says it leaves SSH Persistent sessions running on their hosts, which it always has (the old text said they were gone). How many an update keeps is main's answer, by the rule the install lets go of held sessions by: one read-only query, update:sessionsKept (typed channel, preload, update-handlers.ts). The renderer sends its open local tab ids in two lists; main reads them through updateKeepTabsFrom and answers two counts, no ids and no paths. Off Windows it answers none without asking the helper. The session helper's releaseForUpdate rule moves into updateKeeps, shared by the release and the new tabsKeptThroughUpdate, which lets go of nothing and counts an agent session only where its provider's take-over is wired. Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/update-handlers.ts | 28 ++++- src/main/session-helper/app-wiring.ts | 18 +++- src/main/session-helper/helper-pty.ts | 7 +- src/main/session-helper/manager.ts | 52 +++++++-- src/preload/index.ts | 6 ++ src/renderer/App.tsx | 5 +- src/renderer/components/CloseDialog.tsx | 53 ++++++++-- src/renderer/types/electron.d.ts | 4 + src/renderer/utils/closeDialogText.ts | 135 ++++++++++++++++++++++++ src/shared/ipc-channels.ts | 2 + src/shared/update-keep.ts | 59 +++++++++++ 11 files changed, 350 insertions(+), 19 deletions(-) create mode 100644 src/renderer/utils/closeDialogText.ts create mode 100644 src/shared/update-keep.ts diff --git a/src/main/ipc/update-handlers.ts b/src/main/ipc/update-handlers.ts index 84a8998ad..1880dadfc 100644 --- a/src/main/ipc/update-handlers.ts +++ b/src/main/ipc/update-handlers.ts @@ -6,7 +6,9 @@ import { checkForUpdatesOnDemand, markUpdateInstalled, getProjectRootPath, setSo import { checkGitHubRelease, downloadGitHubRelease, prepareLinuxAppImageUpdate, isPathOnNoexecMount, InstallerIntegrityError, stillMatchesDigest, createInstallerDir } from '../github-update' import { killAllPty } from '../pty-manager' import { noteUpdateHandOver } from '../conductor-mcp-server' -import { releaseHeldTerminalsForUpdate, reclaimReleasedTerminals } from '../session-helper/app-wiring' +import { releaseHeldTerminalsForUpdate, reclaimReleasedTerminals, sessionsKeptThroughUpdate } from '../session-helper/app-wiring' +import { IPC } from '../../shared/ipc-channels' +import { NOTHING_KEPT, updateKeepTabsFrom, type UpdateKeepCounts } from '../../shared/update-keep' import { hardExitTeardown } from '../hard-exit' import { expandArtifactName } from '../artifact-name' import { logInfo, logError } from '../debug-logger' @@ -54,6 +56,11 @@ async function checkInOrder(): Promise { /** Reentrancy latch for update:installAndRestart — see the handler. */ let updateInProgress = false +/** Whether an update lets go of the held sessions before its kill (plan + * section B2): Windows only; macOS and Linux end them. The install path and + * the update dialog's count (aicc_planning#514) both ask this. */ +const releasesHeldSessions = (): boolean => process.platform === 'win32' + export function registerUpdateHandlers(): void { ipcMain.handle('update:check', async () => { // Store builds are updated by the Store. Report "no update" so the UI never @@ -88,6 +95,23 @@ export function registerUpdateHandlers(): void { return cachedRelease?.displayVersion || cachedRelease?.version || null }) + // aicc_planning#514: the update dialog's counts. How many of the open local + // tabs the renderer names (by kind) an update now would keep running, by + // the rule the install below lets go of held sessions by + // (releasesHeldSessions, then the session helper's own rule). Read-only: + // nothing is let go of, written or started. Counts only: no id or path goes + // back. The question is read through updateKeepTabsFrom, so a malformed + // one is a question about no tab. + ipcMain.handle(IPC.UPDATE_SESSIONS_KEPT, async (_event, tabs?: unknown): Promise => { + if (!releasesHeldSessions()) return { ...NOTHING_KEPT } + try { + return sessionsKeptThroughUpdate(updateKeepTabsFrom(tabs)) + } catch (err) { + logError('[update] The sessions an update keeps could not be counted:', err) + return { ...NOTHING_KEPT } + } + }) + ipcMain.handle('update:hasSourcePath', async () => { return hasSourcePath() }) @@ -371,7 +395,7 @@ export function registerUpdateHandlers(): void { // takes it over (2.1.3-beta.17, S16 step 5); one no restored tab takes // over is ended there. macOS and Linux end them. // A release that fails stops nothing: what it did not let go of ends. - const releasing = process.platform === 'win32' + const releasing = releasesHeldSessions() try { if (releasing) { try { await releaseHeldTerminalsForUpdate({ discarded }) } catch (e) { logError('[update] The held terminals could not be let go of:', e) } diff --git a/src/main/session-helper/app-wiring.ts b/src/main/session-helper/app-wiring.ts index 03ebe778e..c9cb09076 100644 --- a/src/main/session-helper/app-wiring.ts +++ b/src/main/session-helper/app-wiring.ts @@ -3,7 +3,7 @@ * plugged into the Machines page (setMachinesSource), switched by Settings, * told which tabs are saved, and ended at a normal quit. index.ts calls these * and nothing else of the helper; update-handlers.ts calls the two for an app - * update on Windows. + * update on Windows, and the update dialog's count (sessionsKeptThroughUpdate). */ import { app } from 'electron' import { readConfig, readConfigChecked } from '../config-manager' @@ -16,6 +16,7 @@ import { endHelperHooks, helperHookEvent, helperHooksTaken } from '../session-si import { getConductorMcpPort, serveToolStream } from '../conductor-mcp-server' import { tryGetProvider } from '../providers' import type { ProviderId } from '../../shared/providers/ids' +import { NOTHING_KEPT, type UpdateKeepCounts, type UpdateKeepTabs } from '../../shared/update-keep' import { bundledHelperPath, helperRootDir } from './install' import { SessionHelperManager, agentRecordsIn, crashMarkIn, getSessionHelper, keptHookFoldersIn, keptSessionIdsIn, removeOldCopiesWithHelperOff, setSessionHelper, type HelperHookDeps, type HelperRouting, type HelperToolDeps, type SessionHelperServiceState } from './manager' @@ -247,6 +248,21 @@ export async function releaseHeldTerminalsForUpdate(choice: UpdateChoice = {}): return n } +/** + * aicc_planning#514: the update dialog's count. How many of the tabs the + * renderer names (its open local tabs, by kind) an app update now would keep + * running and show again in the new version, by the rule the update lets go + * of held sessions by (the manager's tabsKeptThroughUpdate). Counts only. + * None when the helper was never switched on this run. Lets go of nothing. + */ +export function sessionsKeptThroughUpdate(tabs: UpdateKeepTabs): UpdateKeepCounts { + const m = getSessionHelper() + if (!m) return { ...NOTHING_KEPT } + const kept = m.tabsKeptThroughUpdate(new Set([...tabs.agents, ...tabs.terminals])) + const count = (ids: readonly string[]) => new Set(ids.filter((id) => kept.has(id))).size + return { agents: count(tabs.agents), terminals: count(tabs.terminals) } +} + /** What the user chose at an app update: `discarded` only for "Close sessions" * on the update dialog. Nothing passed is Save. */ export interface UpdateChoice { diff --git a/src/main/session-helper/helper-pty.ts b/src/main/session-helper/helper-pty.ts index 335056f97..dab496807 100644 --- a/src/main/session-helper/helper-pty.ts +++ b/src/main/session-helper/helper-pty.ts @@ -517,6 +517,11 @@ export class HelperPty implements IPty { get heldRecord(): HolderRecord | undefined { return this.inner ? undefined : this.record } /** True once release() let go of the holder for an app update. */ get isReleased(): boolean { return this.released } + /** aicc_planning#514: whether release() would let go of the holder now (a + * holder that has been attached, not starting, ending, over or released); + * release() asks this, and so does the update dialog's count (manager.ts + * updateKeeps), which lets go of nothing. */ + get releasable(): boolean { return !(this.inner || this.exited || this.ending || this.released || !this.record || !this.everAttached) } /** The folder its program was launched in, and whether it runs on node-pty's * bundled ConPTY (2.1.3-beta.17, S16 step 5): what an update's record of an * agent session keeps for the take-over in its restored tab. */ @@ -635,7 +640,7 @@ export class HelperPty implements IPty { * (remote-helper/session.ts RemoteHelperPty.kill); its holder has no away clock. */ release(): boolean { - if (this.inner || this.exited || this.ending || this.released || !this.record || !this.everAttached) return false + if (!this.releasable) return false this.released = true const conn = this.conn // A flush waiting before a lone Enter sends the rest now, as it all went diff --git a/src/main/session-helper/manager.ts b/src/main/session-helper/manager.ts index d2dca6bfb..3650de5c6 100644 --- a/src/main/session-helper/manager.ts +++ b/src/main/session-helper/manager.ts @@ -2089,14 +2089,7 @@ export class SessionHelperManager implements MachinesSource { // B1f: each connection that takes hook events lets go by a detach, which // the update waits for (endsForUpdate): its later events wait in its holder. const lets: Promise[] = [] - for (const [sid, w] of this.live) { - if (!w.throughHelper || w.isReleased) continue - const kind = heldIdKind(sid) - const keeps = kind === 'agent' ? this.keepable(w) : null - if (kind !== 'plain' && !keeps) continue - const record = w.heldRecord - const tab = parentOfPartnerPtyId(w.label) ?? w.label - if (!record || !saved(tab)) continue + for (const { sid, w, keeps, record } of this.updateKeeps(saved)) { // An agent session's record is written before it is let go of: one // that cannot be recorded is left to the kill, which ends it. const kept = keeps ? this.recordKept(sid, w.label, keeps.kind, w.launchShape, keeps.hooks) : undefined @@ -2148,6 +2141,49 @@ export class SessionHelperManager implements MachinesSource { return n } + /** + * The held sessions an app update lets go of (releaseForUpdate's rule, and + * the update dialog's count's: tabsKeptThroughUpdate): on Windows and not + * quitting, each terminal through a holder that release() would let go of + * now (HelperPty.releasable), a plain or partner terminal, or an agent + * session whose routes an update keeps (keepable), when its holder has a + * record and its tab (a partner's is its session's) is `saved`. Reads only. + */ + private updateKeeps(saved: (tab: string) => boolean): Array<{ sid: string; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord }> { + const out: Array<{ sid: string; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord }> = [] + if (this.os !== 'windows' || this.quitting) return out + for (const [sid, w] of this.live) { + if (!w.throughHelper || !w.releasable) continue + const kind = heldIdKind(sid) + const keeps = kind === 'agent' ? this.keepable(w) : null + if (kind !== 'plain' && !keeps) continue + const record = w.heldRecord + const tab = parentOfPartnerPtyId(w.label) ?? w.label + if (!record || !saved(tab)) continue + out.push({ sid, w, keeps, record }) + } + return out + } + + /** + * aicc_planning#514: the tabs, of `tabs`, whose own session (not a partner + * terminal beside it) an app update now would keep running for the next + * version to show again: the update dialog's count, by releaseForUpdate's + * rule (updateKeeps), each of `tabs` taken as saved, as Save sessions + * saves it before the install. An agent session counts only where its + * provider's take-over is wired (deps.takeOver), because the next start + * ends any other (keptAtStart). Lets go of nothing, writes nothing, and + * leaves the update path as it is. + */ + tabsKeptThroughUpdate(tabs: ReadonlySet): Set { + const out = new Set() + for (const { w, keeps } of this.updateKeeps((tab) => tabs.has(tab))) { + if (keeps && this.deps.takeOver?.[keeps.kind] !== true) continue + if (tabs.has(w.label)) out.add(w.label) + } + return out + } + /** Settles once every end the last releaseForUpdate sent was answered (or * failed): the kept terminals ended because the user discarded the saved * sessions; and, B1f, once each holder it let go of by a detach answered diff --git a/src/preload/index.ts b/src/preload/index.ts index 13bb36a82..2b5a8c6b0 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -7,6 +7,7 @@ import { REMOTE_PLAN_MODE_WHYS, type RemotePlanModeWhy } from '../shared/types' import type { StatuslineData, SubmitTextResult, PromptButtonResult, CliBarCommand, AskConductorNotice, CanvasMarkerUndelivered, ClaudeMarkerAsk, ClaudeMarkerAnswer, CanvasSessionGuidance, AccountLogFolders, AccountLogFolderKind, AccountLogFolderOpenResult } from '../shared/types' import type { WebviewNavState } from '../shared/browser-url' import type { PasteKeyPress, PasteKeyResult, SnapPasteAnswer } from '../shared/clipboard-paste' +import type { UpdateKeepCounts, UpdateKeepTabs } from '../shared/update-keep' import type { AccountPaneStateView, CodexWebSessionView, CodexWebSignInState } from '../shared/account-web-session' import type { ModelRegistry } from '../shared/model-registry' import type { SentinelStateSnapshot } from '../shared/sentinel-types' @@ -648,6 +649,9 @@ export interface ElectronAPI { getVersion: () => Promise /** `discarded`: the user chose "Close sessions" on the update dialog. */ installAndRestart: (choice?: { discarded?: boolean }) => Promise + /** aicc_planning#514: how many of these open local tabs, by kind, an + * update now would keep running (the update dialog's counts). Counts only. */ + sessionsKept: (tabs: UpdateKeepTabs) => Promise hasSourcePath: () => Promise getSourcePath: () => Promise setSourcePath: (path: string) => Promise @@ -1379,6 +1383,8 @@ const electronAPI: ElectronAPI = { check: () => ipcRenderer.invoke(IPC.UPDATE_CHECK), getVersion: () => ipcRenderer.invoke(IPC.UPDATE_GET_VERSION), installAndRestart: (choice) => ipcRenderer.invoke(IPC.UPDATE_INSTALL_RESTART, { discarded: choice?.discarded === true }), + // Only the two id lists go; main reads them through updateKeepTabsFrom. + sessionsKept: (tabs) => ipcRenderer.invoke(IPC.UPDATE_SESSIONS_KEPT, { agents: tabs?.agents, terminals: tabs?.terminals }), hasSourcePath: () => ipcRenderer.invoke(IPC.UPDATE_HAS_SOURCE_PATH), getSourcePath: () => ipcRenderer.invoke(IPC.UPDATE_GET_SOURCE_PATH), setSourcePath: (path: string) => ipcRenderer.invoke(IPC.UPDATE_SET_SOURCE_PATH, path), diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index c003f10b2..d6275fcda 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -1624,7 +1624,10 @@ export default function App() { {closeDialog && ( { setCloseDialog(null); window.electronAPI.window.cancelClose() }} diff --git a/src/renderer/components/CloseDialog.tsx b/src/renderer/components/CloseDialog.tsx index 299ee31ef..b9f50b2ef 100644 --- a/src/renderer/components/CloseDialog.tsx +++ b/src/renderer/components/CloseDialog.tsx @@ -1,24 +1,56 @@ -import React, { useRef } from 'react' +import React, { useEffect, useRef, useState } from 'react' import { DialogOverlay, DialogPanel, DialogHeader, DialogBody, DialogFooter, DialogButton, useDialogEscape, WINDOW_CLOSE_Z } from './ui/Dialog' import { useContainFocus } from '../onboarding/contain-focus' import { useOccludesNativePanes } from '../stores/paneOcclusionStore' +import { closeDialogText, updateKeepQuestion, type CloseDialogTab } from '../utils/closeDialogText' +import { NOTHING_KEPT, updateKeepCountsFrom, type UpdateKeepCounts } from '../../shared/update-keep' interface CloseDialogProps { mode: 'close' | 'update' - sessionCount: number + /** The tabs open when the dialog opens; it reads them once. */ + tabs: ReadonlyArray onSaveAndClose: () => void onCloseWithoutSaving: () => void onCancel: () => void } +/** + * aicc_planning#514: how many of `tabs` an update now would keep running, by + * kind, as main answers (update:sessionsKept, by the rule the update itself + * goes by). Null while the answer is out. A quit keeps none, and so does an + * update with no local tab, a question that fails or an answer that does not + * read: the dialog then says less is kept, never more. + */ +function useKeptThroughUpdate(mode: 'close' | 'update', tabs: ReadonlyArray): UpdateKeepCounts | null { + const [kept, setKept] = useState(mode === 'update' ? null : NOTHING_KEPT) + useEffect(() => { + const question = updateKeepQuestion(tabs) + const ask = window.electronAPI?.update?.sessionsKept + if (mode !== 'update' || !ask || question.agents.length + question.terminals.length === 0) { + setKept(NOTHING_KEPT) + return + } + let live = true + setKept(null) + Promise.resolve() + .then(() => ask(question)) + .then((answer) => { if (live) setKept(updateKeepCountsFrom(answer) ?? NOTHING_KEPT) }, () => { if (live) setKept(NOTHING_KEPT) }) + return () => { live = false } + }, [mode, tabs]) + return kept +} + /** * Closing (or updating) with sessions open: save them, close them, or cancel. + * It says what each choice does to the tabs open now, with counts + * (closeDialogText, aicc_planning#514): a line for each kind of tab open, for + * Save sessions, then one for Close sessions. * It paints on the top layer (WINDOW_CLOSE_Z), above the onboarding pages and * the introduction's takeover and replay, and keeps Tab inside itself while * it is open: it was once painted under those surfaces, invisible, with focus * on "Save sessions", and Tab walked out of it into the page behind. */ -export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onCloseWithoutSaving, onCancel }: CloseDialogProps) { +export default function CloseDialog({ mode, tabs, onSaveAndClose, onCloseWithoutSaving, onCancel }: CloseDialogProps) { useDialogEscape(onCancel) const panelRef = useRef(null) // "Save sessions" keeps the focus it opens with (autoFocus below); the trap @@ -28,6 +60,12 @@ export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onClos // above all HTML, so they hide while this shows. The overlay is `absolute`, // and DialogOverlay holds that flag only for a `fixed` one. useOccludesNativePanes() + // The tabs as they were when it opened: the count, the lines and main's + // answer are all about the same set, and main is asked once. + const [open] = useState(tabs) + const kept = useKeptThroughUpdate(mode, open) + const text = kept ? closeDialogText(mode, open, kept) : null + const sessionCount = open.length return ( @@ -37,9 +75,12 @@ export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onClos subtitle={<>You have {sessionCount} active session{sessionCount !== 1 ? 's' : ''}.} /> -

- Save them and they come back at the next launch, in the same tabs; close them and they are gone. -

+ {text && ( +
+ {text.lines.map((line) =>

{line}

)} +

{text.close}

+
+ )}
Cancel diff --git a/src/renderer/types/electron.d.ts b/src/renderer/types/electron.d.ts index b55150842..b513bd575 100644 --- a/src/renderer/types/electron.d.ts +++ b/src/renderer/types/electron.d.ts @@ -51,6 +51,7 @@ export type { HookEvent, HookEventKind, HooksGatewayStatus } from '../../shared/ import type { AccountPaneStateView, CodexWebSessionView, CodexWebSignInState } from '../../shared/account-web-session' import type { ModelRegistry } from '../../shared/model-registry' import type { PasteKeyPress, PasteKeyResult, SnapPasteAnswer } from '../../shared/clipboard-paste' +import type { UpdateKeepCounts, UpdateKeepTabs } from '../../shared/update-keep' export type { ModelRegistry } from '../../shared/model-registry' import type { AccountsSnapshot as ProviderAccountsSnapshot, AccountsResult as ProviderAccountsResult, ProviderInstallationView, InstallRecipeView, PathHintView, @@ -704,6 +705,9 @@ export interface ElectronAPI { getVersion: () => Promise /** `discarded`: the user chose "Close sessions" on the update dialog. */ installAndRestart: (choice?: { discarded?: boolean }) => Promise + /** aicc_planning#514: how many of these open local tabs, by kind, an + * update now would keep running (the update dialog's counts). Counts only. */ + sessionsKept: (tabs: UpdateKeepTabs) => Promise hasSourcePath: () => Promise getSourcePath: () => Promise setSourcePath: (path: string) => Promise diff --git a/src/renderer/utils/closeDialogText.ts b/src/renderer/utils/closeDialogText.ts new file mode 100644 index 000000000..ebce1c0b3 --- /dev/null +++ b/src/renderer/utils/closeDialogText.ts @@ -0,0 +1,135 @@ +import type { UpdateKeepCounts, UpdateKeepTabs } from '../../shared/update-keep' + +/** + * aicc_planning#514: what the close and update dialogs say each choice does + * to the tabs open now, with counts, in plain lines. Each tab is in exactly + * one kind, and a kind with none open has no line. + * + * - kept (update only): its own session is held by the session helper and an + * update keeps it running, for the new version's tab to take over. Main + * says how many, by the rule the update itself goes by (the + * update:sessionsKept query): Windows only, the helper switches, a saved + * tab, a provider whose take-over is wired. The renderer never decides it. + * A quit ends every held session (a normal quit ends them). + * - SSH sessions that keep running on their hosts (sshKeepsRunning): an SSH + * Persistent tab, which a quit or an update detaches from, and the next + * start reattaches to. Close sessions leaves them running too: their tabs + * close, but nothing ends them on the host. + * - the rest of the Claude Code and Codex tabs: they restart and pick up + * their conversations; + * - the rest of the Terminal only tabs: they start again; + * - a sign-in or install tab (transient): never saved, it ends. + */ + +/** What the dialogs read of an open tab (a sessionStore Session is one). */ +export interface CloseDialogTab { + id: string + sessionType: 'local' | 'ssh' + shellOnly?: boolean + transient?: boolean + sshConfig?: { detachable?: boolean } + sshTmuxPersistent?: boolean + remoteVia?: 'helper' + remoteNotKept?: true + remoteAnchored?: true +} + +/** + * An SSH tab whose session keeps running on its host when the app closes or + * updates, by the app's own rule for SSH Persistent: its config's Connection + * (a config that never chose one is SSH Persistent: `detachable` absent or + * true), and not a Terminal only tab (remote-helper/route.ts persistentTab). + * What its start said wins over the config: kept by the session helper there + * (remoteVia), not kept by that machine or ending with its connection + * (remoteNotKept, remoteAnchored), or on the usual path without tmux + * (sshTmuxPersistent false). + */ +export function sshKeepsRunning(t: CloseDialogTab): boolean { + if (t.sessionType !== 'ssh' || !t.sshConfig || t.shellOnly || t.transient) return false + if (t.remoteNotKept || t.remoteAnchored) return false + if (t.remoteVia === 'helper') return true + return t.sshConfig.detachable !== false && t.sshTmuxPersistent !== false +} + +/** The update dialog's question to main: the open local tabs that are saved + * (not a sign-in or install tab), split into agent sessions and Terminal + * only tabs. Only a local tab's session can be held by the helper here. */ +export function updateKeepQuestion(tabs: ReadonlyArray): UpdateKeepTabs { + const local = tabs.filter((t) => t.sessionType === 'local' && !t.transient) + return { + agents: local.filter((t) => !t.shellOnly).map((t) => t.id), + terminals: local.filter((t) => t.shellOnly).map((t) => t.id), + } +} + +/** How many tabs of each kind (see the file's head). */ +export interface CloseDialogCounts { + total: number + kept: number + ssh: number + resume: number + fresh: number + oneOff: number +} + +/** Each open tab in one kind. `kept` is main's answer for the update dialog + * (nothing at a quit); a count higher than the tabs it is about counts as + * all of them. */ +export function closeDialogCounts(mode: 'close' | 'update', tabs: ReadonlyArray, kept: UpdateKeepCounts): CloseDialogCounts { + const question = updateKeepQuestion(tabs) + const keptAgents = mode === 'update' ? Math.min(Math.max(0, kept.agents), question.agents.length) : 0 + const keptTerminals = mode === 'update' ? Math.min(Math.max(0, kept.terminals), question.terminals.length) : 0 + let ssh = 0 + let agents = 0 + let terminals = 0 + let oneOff = 0 + for (const t of tabs) { + if (t.transient) oneOff++ + else if (sshKeepsRunning(t)) ssh++ + else if (t.shellOnly) terminals++ + else agents++ + } + return { + total: tabs.length, + kept: keptAgents + keptTerminals, + ssh, + resume: agents - keptAgents, + fresh: terminals - keptTerminals, + oneOff, + } +} + +/** The dialog's text: one line per kind with any open (what Save sessions + * does), then what Close sessions does. */ +export interface CloseDialogText { + lines: string[] + close: string +} + +export function closeDialogText(mode: 'close' | 'update', tabs: ReadonlyArray, kept: UpdateKeepCounts): CloseDialogText { + const c = closeDialogCounts(mode, tabs, kept) + const lines: string[] = [] + const say = (n: number, one: string, many: string) => { if (n > 0) lines.push(n === 1 ? one : many.replace('{n}', String(n))) } + if (mode === 'update') { + say(c.kept, '1 keeps running through the update and is back in its tab straight away.', '{n} keep running through the update and are back in their tabs straight away.') + say(c.ssh, '1 SSH session keeps running on its host and reconnects.', '{n} SSH sessions keep running on their hosts and reconnect.') + say(c.resume, '1 restarts and picks up its conversation.', '{n} restart and pick up their conversations.') + say(c.fresh, '1 terminal starts again.', '{n} terminals start again.') + } else { + say(c.resume, '1 ends and picks up its conversation at the next launch.', '{n} end and pick up their conversations at the next launch.') + say(c.ssh, '1 SSH session keeps running on its host and reconnects at the next launch.', '{n} SSH sessions keep running on their hosts and reconnect at the next launch.') + say(c.fresh, '1 terminal ends and starts again at the next launch.', '{n} terminals end and start again at the next launch.') + } + say(c.oneOff, '1 sign-in or install tab ends.', '{n} sign-in or install tabs end.') + return { lines, close: closeLine(c) } +} + +/** Close sessions ends every tab's session, but an SSH Persistent one: its + * tab closes and its session keeps running on its host. */ +function closeLine(c: CloseDialogCounts): string { + const ends = c.total - c.ssh + if (c.ssh === 0) return c.total === 1 ? 'Close sessions ends it.' : `Close sessions ends all ${c.total}.` + const running = c.ssh === 1 ? 'the SSH session keeps running on its host' : `the ${c.ssh} SSH sessions keep running on their hosts` + if (ends > 0) return `Close sessions ends ${ends} and closes every tab; ${running}.` + return `Close sessions closes ${c.total === 1 ? 'its tab' : 'every tab'}; ${running}.` +} diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts index 58036be8b..ea7342b80 100644 --- a/src/shared/ipc-channels.ts +++ b/src/shared/ipc-channels.ts @@ -152,6 +152,8 @@ export const IPC = { UPDATE_CHECK: 'update:check', UPDATE_GET_VERSION: 'update:getVersion', UPDATE_INSTALL_RESTART: 'update:installAndRestart', + // aicc_planning#514: the update dialog's counts (read-only, counts only). + UPDATE_SESSIONS_KEPT: 'update:sessionsKept', UPDATE_HAS_SOURCE_PATH: 'update:hasSourcePath', UPDATE_GET_SOURCE_PATH: 'update:getSourcePath', UPDATE_SET_SOURCE_PATH: 'update:setSourcePath', diff --git a/src/shared/update-keep.ts b/src/shared/update-keep.ts new file mode 100644 index 000000000..6822306bd --- /dev/null +++ b/src/shared/update-keep.ts @@ -0,0 +1,59 @@ +/** + * aicc_planning#514: the update dialog's one question to main, and its answer. + * + * The dialog says what each choice does to the tabs open now, and how many of + * them an app update keeps running is main's to say: the session helper's own + * rule, the one the install lets go of held sessions by (update-handlers.ts, + * session-helper/manager.ts updateKeeps). So the renderer names its open + * local tabs, split as it shows them (agent sessions and Terminal only tabs), + * and main answers how many of each it would keep. Counts only: main sends + * back no id and no path. Both sides read the other's message through the + * parsers here, so a malformed one reads as nothing kept. + */ + +/** The local tabs the dialog asks about, by id: a Claude Code or Codex + * session's tab, and a Terminal only tab. */ +export interface UpdateKeepTabs { + agents: string[] + terminals: string[] +} + +/** How many of each an app update now would keep running. */ +export interface UpdateKeepCounts { + agents: number + terminals: number +} + +export const NOTHING_KEPT: Readonly = Object.freeze({ agents: 0, terminals: 0 }) + +/** At most this many ids of each kind are read; more is not a real window. */ +export const UPDATE_KEEP_MAX_TABS = 512 + +/** A tab id as the session helper carries it (protocol.ts APP_PTY_ID_RE). */ +const TAB_ID_RE = /^[A-Za-z0-9_-]{1,128}$/ + +function idsFrom(raw: unknown, skip: ReadonlySet): string[] { + if (!Array.isArray(raw)) return [] + const out = new Set() + for (const v of raw.slice(0, UPDATE_KEEP_MAX_TABS)) { + if (typeof v === 'string' && TAB_ID_RE.test(v) && !skip.has(v)) out.add(v) + } + return [...out] +} + +/** Main's read of the renderer's question: ids of the tab id shape only, each + * once, and an id named as both kinds is an agent's. Anything else is none. */ +export function updateKeepTabsFrom(raw: unknown): UpdateKeepTabs { + const o = raw !== null && typeof raw === 'object' ? (raw as { agents?: unknown; terminals?: unknown }) : {} + const agents = idsFrom(o.agents, new Set()) + return { agents, terminals: idsFrom(o.terminals, new Set(agents)) } +} + +/** The renderer's read of main's answer: two whole numbers of 0 or more, or + * null when it is not that. */ +export function updateKeepCountsFrom(raw: unknown): UpdateKeepCounts | null { + if (raw === null || typeof raw !== 'object') return null + const { agents, terminals } = raw as { agents?: unknown; terminals?: unknown } + const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0 + return whole(agents) && whole(terminals) ? { agents, terminals } : null +} From edeb57ba094b344a946953ac8955ee56eeda4e6f Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:46 +0000 Subject: [PATCH 28/79] test(restore): pin the restore after an update with Save sessions (#515) The mark is written only by Save sessions on the update dialog, after the autosave is cancelled, and written again without it when the update fails; a start reopens the set at once only for a newer version with a mark that reads, and the offer never carries the mark on; RestoreAfterUpdate restores once under StrictMode; the restore after an update skips the account choice in 'ask' while a normal relaunch still asks; App wires the at-once restore at the resume prompt's turn with afterUpdate true and the prompt's Resume with false. The Settings and agent-switch copy pins follow the new text. Each case goes red under its mutant (13 run, all red, files restored byte for byte and sha-checked). Co-Authored-By: Claude Opus 5.5 --- .../renderer/app-lifecycle-wiring.test.ts | 88 +++++++++++++-- tests/unit/renderer/held-terminal-tab.test.ts | 5 +- .../renderer/restore-after-update.test.tsx | 100 ++++++++++++++++++ tests/unit/renderer/session-launch.test.ts | 11 +- .../session-persistence-restore.test.ts | 23 +++- 5 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 tests/unit/renderer/restore-after-update.test.tsx diff --git a/tests/unit/renderer/app-lifecycle-wiring.test.ts b/tests/unit/renderer/app-lifecycle-wiring.test.ts index d6f5985c7..1c35da042 100644 --- a/tests/unit/renderer/app-lifecycle-wiring.test.ts +++ b/tests/unit/renderer/app-lifecycle-wiring.test.ts @@ -116,6 +116,7 @@ describe('App.tsx wires the R6/R7 helpers', () => { closeDialog: 'update', setCloseDialog: vi.fn(), setIsClosing: vi.fn(), setIsUpdating: vi.fn(), flushPendingConfigSaves: vi.fn(async () => {}), buildSessionStateWithResumeTargets: vi.fn(async () => ({ sessions: [] })), buildSessionState: vi.fn(() => ({ sessions: [] })), + cancelSessionAutosave: vi.fn(), markSavedForUpdate: (s: object, v: string) => ({ ...s, savedForUpdate: { fromVersion: v } }), __APP_VERSION__: '2.1.3-beta.27', window: { electronAPI: saveApi }, }) await save() @@ -136,6 +137,35 @@ describe('App.tsx wires the R6/R7 helpers', () => { expect(noDiscard(noTabApi.update.installAndRestart)).toBe(true) }) + it('aicc_planning#515: Save sessions on the UPDATE dialog, and only there, writes the set marked as saved for an update by this version, with the autosave cancelled first', async () => { + const go = async (closeDialog: 'update' | 'close') => { + const order: string[] = [] + const api = { + session: { save: vi.fn(async (s: unknown) => { order.push('save'); return s !== undefined }), gracefulExit: vi.fn(async () => {}) }, + update: { installAndRestart: vi.fn(async () => true) }, + window: { allowClose: vi.fn() }, + } + const markSavedForUpdate = vi.fn((s: object, v: string) => { order.push(`mark:${v}`); return { ...s, savedForUpdate: { fromVersion: v } } }) + const handler = run<() => Promise>(namedArrow(APP, 'handleSaveAndClose'), { + closeDialog, setCloseDialog: vi.fn(), setIsClosing: vi.fn(), setIsUpdating: vi.fn(), + flushPendingConfigSaves: vi.fn(async () => {}), + buildSessionStateWithResumeTargets: vi.fn(async () => ({ sessions: [{ id: 'a' }] })), buildSessionState: vi.fn(() => ({ sessions: [{ id: 'a' }] })), + cancelSessionAutosave: () => { order.push('cancelAutosave') }, markSavedForUpdate, persistSessionState: vi.fn(async () => {}), __APP_VERSION__: '2.1.3-beta.27', + window: { electronAPI: api }, + }) + await handler() + return { order, written: api.session.save.mock.calls[0]?.[0], markSavedForUpdate } + } + const update = await go('update') + expect(update.order).toEqual(['cancelAutosave', 'mark:2.1.3-beta.27', 'save']) + expect(update.written).toEqual({ sessions: [{ id: 'a' }], savedForUpdate: { fromVersion: '2.1.3-beta.27' } }) + // A quit's Save sessions writes the set as before, with no mark. + const quit = await go('close') + expect(quit.markSavedForUpdate).not.toHaveBeenCalled() + expect(quit.order).toEqual(['save']) + expect(quit.written).toEqual({ sessions: [{ id: 'a' }] }) + }) + it('startup loads through loadSavedStateAtStartup (load wired to session.load) and offers the prompt only when it returns cards', async () => { // The try/catch around the load: the `try` block and the `catch` block that follows it. const marker = " try {\n // rc.15 review R7 (aicc_planning#53)" @@ -151,22 +181,28 @@ describe('App.tsx wires the R6/R7 helpers', () => { // starts TRUE (startup is unsettled) and is cleared only once the load // POSITIVELY resolves -- never in the catch. expect(APP, 'restoreUnsettledRef initialised true').toContain('const restoreUnsettledRef = useRef(true)') - const go = async (returned: unknown, throws = false) => { + const go = async (returned: unknown, throws = false, atOnce = false) => { const load = vi.fn(async () => { if (throws) throw new Error('synthetic load failure'); return returned }) const loadSavedStateAtStartup = vi.fn(async (deps: { load: () => Promise }) => { const r = await deps.load(); return r }) const setPendingRestore = vi.fn() + const setRestoreAtOnce = vi.fn() const setRestoreTally = vi.fn() const pingAllDetachedHosts = vi.fn() const reconcile = vi.fn() + // aicc_planning#515: what this start offers, and whether at once, is + // restoreOfferAtStart's answer for the saved set and this version (its + // own cases are in restore-after-update.test.tsx). + const restoreOfferAtStart = vi.fn((s: unknown, _v: string) => ({ offer: s, atOnce })) const restoreUnsettledRef = { current: true } // as the component initialises it const fn = run<() => Promise>(`async () => { ${stmt} }`, { - loadSavedStateAtStartup, setPendingRestore, setRestoreTally, pingAllDetachedHosts, restoreUnsettledRef, console, + loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, __APP_VERSION__: '2.1.3-beta.28', + setRestoreTally, pingAllDetachedHosts, restoreUnsettledRef, console, useCommandBarStore: { getState: () => ({ reconcile }) }, useSessionStore: { getState: () => ({ sessions: [] }) }, useDetachedRemotesStore: { getState: () => ({ entries: REGISTRY }) }, window: { electronAPI: { session: { load } } }, }) await fn() - return { load, loadSavedStateAtStartup, setPendingRestore, setRestoreTally, pingAllDetachedHosts, reconcile, restoreUnsettledRef } + return { load, loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, setRestoreTally, pingAllDetachedHosts, reconcile, restoreUnsettledRef } } const REGISTRY = [{ sessionId: 'left-1' }] const saved = { sessions: [{ id: 'a' }], activeSessionId: 'a', savedAt: 1 } @@ -174,6 +210,12 @@ describe('App.tsx wires the R6/R7 helpers', () => { expect(withCards.loadSavedStateAtStartup).toHaveBeenCalledTimes(1) expect(withCards.load).toHaveBeenCalledTimes(1) expect(withCards.setPendingRestore).toHaveBeenCalledWith(saved) + expect(withCards.restoreOfferAtStart).toHaveBeenCalledWith(saved, '2.1.3-beta.28') + expect(withCards.setRestoreAtOnce).toHaveBeenCalledWith(false) + // aicc_planning#515: saved for an update by an older version: offered at once. + const atOnce = await go(saved, false, true) + expect(atOnce.setRestoreAtOnce).toHaveBeenCalledWith(true) + expect(atOnce.setPendingRestore).toHaveBeenCalledWith(saved) expect(withCards.restoreUnsettledRef.current, 'cleared once the load resolved with cards').toBe(false) const deps = withCards.loadSavedStateAtStartup.mock.calls[0][0] as { pingHosts: () => void; reconcile: () => void } deps.pingHosts(); expect(withCards.pingAllDetachedHosts).toHaveBeenCalledTimes(1) @@ -184,6 +226,7 @@ describe('App.tsx wires the R6/R7 helpers', () => { expect(withCards.setRestoreTally).not.toHaveBeenCalled() const without = await go(null) expect(without.setPendingRestore).not.toHaveBeenCalled() + expect(without.setRestoreAtOnce).not.toHaveBeenCalled() expect(without.setRestoreTally).toHaveBeenCalledWith({ sessions: [], detached: REGISTRY }) expect(without.restoreUnsettledRef.current, 'cleared once the load resolved with no cards').toBe(false) // The load FAILED: the ref stays true so a zero-session close leaves the file. @@ -265,21 +308,29 @@ describe('App.tsx wires the R6/R7 helpers', () => { const probeGoneSessions = async () => [] const pingAllDetachedHosts = () => {} let tally: unknown - const handler = run<() => void>(jsxHandler(APP, 'onResume'), { - pendingRestore: saved, setPendingRestore: (v: unknown) => { order.push(`setPendingRestore:${v}`) }, + // aicc_planning#515: the prompt's Resume and the restore after an update + // are one named restore, resumeSaved(saved, afterUpdate). + expect(APP.split('onResume={').length, 'one onResume').toBe(2) + expect(APP).toContain('onResume={() => resumeSaved(pendingRestore, false)}') + const handler = run<(s: unknown, afterUpdate: boolean) => void>(namedArrow(APP, 'resumeSaved'), { + setPendingRestore: (v: unknown) => { order.push(`setPendingRestore:${v}`) }, setUnansweredRestore: (v: unknown) => { order.push(`unanswered:${v}`) }, setRestoreTally: (t: unknown) => { tally = t; order.push('tally') }, - restoreSavedSessions: async (s: unknown, _ref: unknown, deps: { probeGoneSessions: unknown; pingAllDetachedHosts: unknown }) => { + restoreSavedSessions: async (s: unknown, _ref: unknown, deps: { probeGoneSessions: unknown; pingAllDetachedHosts: unknown; afterUpdate?: unknown }) => { order.push(`restore:${s === saved}`) order.push(`deps:${deps.probeGoneSessions === probeGoneSessions && deps.pingAllDetachedHosts === pingAllDetachedHosts}`) + order.push(`afterUpdate:${deps.afterUpdate}`) }, restoreUnsettledRef, probeGoneSessions, pingAllDetachedHosts, }) - handler() + handler(saved, false) // P3.5 fix round 1 (item D): the offer is let go before the restore writes the file. - expect(order).toEqual(['tally', 'setPendingRestore:null', 'unanswered:null', 'restore:true', 'deps:true']) + expect(order).toEqual(['tally', 'setPendingRestore:null', 'unanswered:null', 'restore:true', 'deps:true', 'afterUpdate:false']) + order.length = 0 + handler(saved, true) + expect(order).toEqual(['tally', 'setPendingRestore:null', 'unanswered:null', 'restore:true', 'deps:true', 'afterUpdate:true']) // Walk fix N5: tallied from the saved set itself, every session in it // (one that will reopen Not started included), before the restore lands. expect(tally).toEqual({ sessions: saved.sessions, detached: [] }) @@ -288,6 +339,16 @@ describe('App.tsx wires the R6/R7 helpers', () => { expect(restoreUnsettledRef.current).toBe(true) }) + it('aicc_planning#515: at the resume prompt\'s turn, a set saved for an update is restored with nothing asked (RestoreAfterUpdate, afterUpdate true); any other set shows the prompt', () => { + const at = APP.indexOf("{bootGate === 'resume' && pendingRestore && (") + expect(at, 'the resume gate').toBeGreaterThan(-1) + const gate = APP.slice(at, APP.indexOf(' resumeSaved(pendingRestore, true)} /> ) : (") + // Set only by the startup load, from restoreOfferAtStart. + expect(APP.match(/setRestoreAtOnce\([^\n]*/g)).toEqual(['setRestoreAtOnce(atOnce)']) + expect(APP).toContain('const [restoreAtOnce, setRestoreAtOnce] = useState(false)') + }) + it('while the resume prompt is up, every write of the session file keeps its offer: App keeps it in step with pendingRestore (P3.5 fix round 1, item D)', () => { const at = APP.indexOf('setUnansweredRestore(pendingRestore)') expect(at, 'the effect that keeps the offer in step').toBeGreaterThan(-1) @@ -308,8 +369,10 @@ describe('App.tsx wires the R6/R7 helpers', () => { // (b) The one thing that sets a saved set is the startup load, which runs // once (hasRestoredRef); everything else clears it or is the Refresh below. const setters = APP.match(/setPendingRestore\((?!null\))[^\n]*/g) ?? [] - expect(setters).toEqual(['setPendingRestore(savedState)', 'setPendingRestore((prev) => refreshRestoreOffer(prev, saved, open))']) - expect(block(APP, APP.indexOf('async function postConfigInit()')).text).toContain('if (savedState) setPendingRestore(savedState)') + expect(setters).toEqual(['setPendingRestore(offer)', 'setPendingRestore((prev) => refreshRestoreOffer(prev, saved, open))']) + const init = block(APP, APP.indexOf('async function postConfigInit()')).text + expect(init).toContain('const { offer, atOnce } = restoreOfferAtStart(savedState, __APP_VERSION__)') + expect(init).toContain('setPendingRestore(offer)') expect(APP).toContain('if (!configLoaded || hasRestoredRef.current) return\n hasRestoredRef.current = true\n\n async function postConfigInit()') // (c) A Refresh read that lands after the prompt was answered leaves it // answered; while it is still up the fresh list replaces it, and a @@ -377,14 +440,19 @@ describe('App tells Settings when an update is under way, and lets go of it when update: { installAndRestart: vi.fn(async () => { throw new Error('Installer not found.') }) }, window: { allowClose: vi.fn() }, } + const persistSessionState = vi.fn(async () => {}) const save = run<() => Promise>(namedArrow(APP, 'handleSaveAndClose'), { console: quiet, closeDialog: 'update', setCloseDialog: vi.fn(), setIsClosing, setIsUpdating, flushPendingConfigSaves: vi.fn(async () => {}), buildSessionStateWithResumeTargets: vi.fn(async () => ({ sessions: [] })), buildSessionState: vi.fn(() => ({ sessions: [] })), + cancelSessionAutosave: vi.fn(), markSavedForUpdate: (s: object) => s, persistSessionState, __APP_VERSION__: '2.1.3-beta.27', window: { electronAPI: api }, }) await save() expect(api.update.installAndRestart).toHaveBeenCalledTimes(1) + // aicc_planning#515: the app stays, so the set is written again without + // the update's mark (a later start asks as before). + expect(persistSessionState).toHaveBeenCalledTimes(1) expect(api.window.allowClose, 'the app stays after a failed update').not.toHaveBeenCalled() expect(setIsClosing).toHaveBeenLastCalledWith(false) expect(setIsUpdating).toHaveBeenCalledWith(true) diff --git a/tests/unit/renderer/held-terminal-tab.test.ts b/tests/unit/renderer/held-terminal-tab.test.ts index f1b2dfaea..c895b94e7 100644 --- a/tests/unit/renderer/held-terminal-tab.test.ts +++ b/tests/unit/renderer/held-terminal-tab.test.ts @@ -94,7 +94,8 @@ describe('the setting', () => { expect(block).toContain('On Windows, ending a session also ends every program it started, even one it opened in a window of its own.') // 2.1.3-beta.9, plan section B1: the same switch carries Insights' report terminal. expect(block).toContain("Insights' Claude Code report runs this way too.") - // 2.1.3-beta.17, plan section B1 (the release smoke): an update keeps it running, and its tab takes it over. - expect(block).toContain('On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens: resume your sessions within five minutes of that and its tab takes the same session over.') + // 2.1.3-beta.17, plan section B1 (the release smoke): an update keeps it running, and its tab takes it over; + // aicc_planning#515: with no Resume to press. + expect(block).toContain('On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens, which reopens your tabs by itself once the pages it opens with are closed: within five minutes of it opening, its tab takes the same session over.') }) }) diff --git a/tests/unit/renderer/restore-after-update.test.tsx b/tests/unit/renderer/restore-after-update.test.tsx new file mode 100644 index 000000000..716dd4554 --- /dev/null +++ b/tests/unit/renderer/restore-after-update.test.tsx @@ -0,0 +1,100 @@ +// @vitest-environment jsdom +/** + * aicc_planning#515: Save sessions on the update dialog marks the saved set as + * saved for an update by this version (markSavedForUpdate), and the next start + * of a NEWER version reopens it with nothing asked (restoreOfferAtStart's + * atOnce; App renders RestoreAfterUpdate at the resume prompt's turn). Every + * other start (a quit's save, a crash, the same version, an older one, a mark + * that does not read) is offered as before, and the offer never carries the + * mark on, so it is used once. + */ +import { describe, it, expect, vi } from 'vitest' +import React, { StrictMode, act } from 'react' +import { createRoot } from 'react-dom/client' +import type { SessionState, SavedSession } from '../../../src/shared/types' + +;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true +;(globalThis as any).window = (globalThis as any).window ?? {} +;(globalThis as any).window.electronAPI = { ...((globalThis as any).window?.electronAPI ?? {}) } + +const { markSavedForUpdate, restoreOfferAtStart, buildSessionState } = await import('../../../src/renderer/session-persistence') +const { useSessionStore } = await import('../../../src/renderer/stores/sessionStore') +const RestoreAfterUpdate = (await import('../../../src/renderer/components/RestoreAfterUpdate')).default + +const tab = (id: string): SavedSession => ({ id, label: id, workingDirectory: 'C:/work', color: '#89B4FA', sessionType: 'local', provider: 'claude' }) +const saved = (extra: Partial = {}): SessionState => ({ sessions: [tab('a'), tab('b')], activeSessionId: 'a', savedAt: 1_700_000_000_000, ...extra }) + +describe('markSavedForUpdate', () => { + it('marks the set with the version that saved it, and keeps everything else', () => { + const state = saved({ detachedRemotes: [] }) + const marked = markSavedForUpdate(state, '2.1.3-beta.27') + expect(marked).toEqual({ ...state, savedForUpdate: { fromVersion: '2.1.3-beta.27' } }) + expect(state).not.toHaveProperty('savedForUpdate') + }) + + it('a set built for any other save (a quit, the autosave) carries no mark', () => { + useSessionStore.setState({ sessions: [], activeSessionId: null }) + expect(buildSessionState()).not.toHaveProperty('savedForUpdate') + }) +}) + +describe('restoreOfferAtStart', () => { + const marked = (from: unknown) => ({ ...saved(), savedForUpdate: from } as unknown as SessionState) + + it('saved for an update by an older version: reopened at once, and the offer no longer carries the mark', () => { + const { offer, atOnce } = restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3-beta.27'), '2.1.3-beta.28') + expect(atOnce).toBe(true) + expect(offer).toEqual(saved()) + expect(offer).not.toHaveProperty('savedForUpdate') + }) + + it('across a release line, and from a prerelease to its final release', () => { + expect(restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3-beta.27'), '2.1.3').atOnce).toBe(true) + expect(restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3'), '2.2.0-beta.1').atOnce).toBe(true) + }) + + it('a set with no mark (a quit, a crash) is offered as it is, the same object, with the prompt', () => { + const state = saved() + const { offer, atOnce } = restoreOfferAtStart(state, '2.1.3-beta.28') + expect(atOnce).toBe(false) + expect(offer).toBe(state) + }) + + it('the same version starting again, or an older one, asks as before (and drops the mark)', () => { + for (const current of ['2.1.3-beta.27', '2.1.3-beta.26', '2.1.2']) { + const { offer, atOnce } = restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3-beta.27'), current) + expect(atOnce, current).toBe(false) + expect(offer, current).not.toHaveProperty('savedForUpdate') + } + // rc outranks beta: a beta after an rc is the older version. + expect(restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3-rc.1'), '2.1.3-beta.28').atOnce).toBe(false) + }) + + it('a mark that does not read asks as before', () => { + for (const mark of [null, 'x', 7, true, {}, { fromVersion: 7 }, { fromVersion: '' }, { fromVersion: 'banana' }, { fromVersion: null }, []]) { + const { offer, atOnce } = restoreOfferAtStart(marked(mark), '2.1.3-beta.28') + expect(atOnce, JSON.stringify(mark)).toBe(false) + expect(offer).not.toHaveProperty('savedForUpdate') + } + }) + + it('a current version that does not parse asks as before', () => { + expect(restoreOfferAtStart(markSavedForUpdate(saved(), '2.1.3-beta.27'), 'dev').atOnce).toBe(false) + }) +}) + +describe('RestoreAfterUpdate', () => { + it('restores once and shows nothing, also when React runs its effects twice', () => { + const onRestore = vi.fn() + const container = document.createElement('div') + const root = createRoot(container) + act(() => { root.render() }) + expect(onRestore).toHaveBeenCalledTimes(1) + expect(container.innerHTML).toBe('') + // A new handler on a later render (App builds a new arrow each render) + // does not restore again. + act(() => { root.render( onRestore()} />) }) + expect(onRestore).toHaveBeenCalledTimes(1) + act(() => { root.unmount() }) + }) +}) diff --git a/tests/unit/renderer/session-launch.test.ts b/tests/unit/renderer/session-launch.test.ts index 98fe6355b..c6b491201 100644 --- a/tests/unit/renderer/session-launch.test.ts +++ b/tests/unit/renderer/session-launch.test.ts @@ -78,6 +78,13 @@ describe('shouldPredetermineRestoredAccount (#446)', () => { }) it("does NOT predetermine under 'ask' (the gate opens per restored session)", () => { expect(shouldPredetermineRestoredAccount('ask')).toBe(false) + expect(shouldPredetermineRestoredAccount('ask', {})).toBe(false) + expect(shouldPredetermineRestoredAccount('ask', { afterUpdate: false })).toBe(false) + }) + it("aicc_planning#515: the restore after an update with Save sessions predetermines whatever the setting, 'ask' included", () => { + for (const v of ['ask', 'auto-last', undefined, null, 'anything']) { + expect(shouldPredetermineRestoredAccount(v, { afterUpdate: true }), String(v)).toBe(true) + } }) }) @@ -108,8 +115,8 @@ describe('Settings, Resuming sessions wording (O9)', () => { expect(section).toContain('>Ask each time, with that account already chosen') expect(section).not.toContain('Auto-resume last') }) - it('says which sessions it does not touch, and nothing about a Codex sign-in on this computer', () => { - expect(section).toContain("Only matters with two or more Claude accounts. Applies when the app restarts and reopens your sessions. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.") + it('says which sessions it does not touch, that an update with Save sessions asks nothing, and nothing about a Codex sign-in on this computer', () => { + expect(section).toContain("Only matters with two or more Claude accounts. Applies when the app reopens your sessions. After an update where you chose Save sessions, each session carries on as it was, with nothing asked. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.") expect(section).not.toMatch(/this computer/i) expect(section).not.toContain(String.fromCodePoint(0x2014)) }) diff --git a/tests/unit/renderer/session-persistence-restore.test.ts b/tests/unit/renderer/session-persistence-restore.test.ts index 3f475ae1b..235427d13 100644 --- a/tests/unit/renderer/session-persistence-restore.test.ts +++ b/tests/unit/renderer/session-persistence-restore.test.ts @@ -26,7 +26,7 @@ const tabsToldRestored: Array<{ tabs: Array<{ id: string; cwd?: string }>; inSto pty: { tabsRestored: (tabs: Array<{ id: string; cwd?: string }>) => { tabsToldRestored.push({ tabs: structuredClone(tabs), inStore: useSessionStore.getState().sessions.map((s) => s.id) }) } }, } -const { restoreSavedSessions, buildSessionState, buildSessionStateWithResumeTargets, hydrateDetachedFromSavedState } = await import('../../../src/renderer/session-persistence') +const { restoreSavedSessions, buildSessionState, buildSessionStateWithResumeTargets, hydrateDetachedFromSavedState, markSavedForUpdate, restoreOfferAtStart } = await import('../../../src/renderer/session-persistence') const { useSessionStore } = await import('../../../src/renderer/stores/sessionStore') const { useAccountGateStore } = await import('../../../src/renderer/stores/accountGateStore') const { useSettingsStore, DEFAULT_SETTINGS } = await import('../../../src/renderer/stores/settingsStore') @@ -147,6 +147,27 @@ describe('restoreSavedSessions -- the restore lands', () => { expect(useAccountGateStore.getState().wasRestored('b')).toBe(true) }) + it("aicc_planning#515: the restore after an update with Save sessions skips the account choice even in 'ask'; the same restore without it still asks", async () => { + useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, resumeAccountMode: 'ask' } }) + await restoreSavedSessions(state([saved({ id: 'a', profileId: 'p2' }), saved({ id: 'b', provider: 'codex' }), saved({ id: 'c', shellOnly: true })]), ref(), { ...deps(), afterUpdate: true }) + for (const id of ['a', 'b', 'c']) { + expect(useAccountGateStore.getState().wasRestored(id), id).toBe(true) + expect(useAccountGateStore.getState().consumePredetermined(id), id).toBe(true) + } + // A normal relaunch in 'ask': the gate opens per restored session, as before. + await restoreSavedSessions(state([saved({ id: 'd', profileId: 'p2' })]), ref(), { ...deps(), afterUpdate: false }) + expect(useAccountGateStore.getState().consumePredetermined('d')).toBe(false) + await restoreSavedSessions(state([saved({ id: 'e', profileId: 'p2' })]), ref(), deps()) + expect(useAccountGateStore.getState().consumePredetermined('e')).toBe(false) + }) + + it('aicc_planning#515: the restore writes the set back without the update mark', async () => { + const offer = restoreOfferAtStart(markSavedForUpdate(state([saved({ id: 'a' })]), '2.1.3-beta.27'), '2.1.3-beta.28').offer + await restoreSavedSessions(offer, ref(), { ...deps(), afterUpdate: true }) + expect(save).toHaveBeenCalledTimes(1) + expect(save.mock.calls[0][0]).not.toHaveProperty('savedForUpdate') + }) + it('MUTANT 4: fires ONE reachability pass over the rehydrated left-running registry', async () => { const d = deps() await restoreSavedSessions(state([saved({ id: 'a' })], { detachedRemotes: [remote] }), ref(), d) From 2cdd376177bcd4c0cf11f3b365e05b471eb3eac1 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:22:55 +0000 Subject: [PATCH 29/79] test(update): pin the dialogs' lines and the update:sessionsKept query (#514) Each line and count of both dialogs, singular and plural, with a kind with none open left out and the quit wording; the Close sessions line with and without SSH Persistent sessions; the dialog asks main once, about local saved tabs by id only, shows nothing until it answers, and reads a malformed or failed answer as nothing kept. The query: registered on its typed channel, Windows only, the question parsed (ids only, each once), counts back; the preload sends only the two lists. The session helper's count names the tabs the update would keep by its own rule, takes each tab asked about as saved, leaves a partner terminal out, counts an agent session only with its provider's take-over wired, is none when quitting, and lets go of nothing. The dialog's other tests pass tabs instead of a count. Each case goes red under its mutant (19 run, all red, files restored byte for byte and sha-checked). Co-Authored-By: Claude Opus 5.5 --- .../main/session-helper-app-wiring.test.ts | 32 +++- .../unit/main/session-helper-manager.test.ts | 31 ++++ .../main/session-helper-take-over.test.ts | 39 +++++ tests/unit/main/update-handlers.test.ts | 65 +++++++ tests/unit/renderer/close-dialog-text.test.ts | 162 ++++++++++++++++++ .../renderer/close-dialogs-tokens.test.tsx | 88 +++++++++- .../renderer/hello-codex.acceptance.test.ts | 2 +- .../renderer/onboarding-focus-trap.test.tsx | 2 +- .../renderer/window-close-dialogs.test.tsx | 2 +- tests/unit/shared/update-keep.test.ts | 57 ++++++ tests/unit/update-install-bridge.test.ts | 21 +++ 11 files changed, 495 insertions(+), 6 deletions(-) create mode 100644 tests/unit/renderer/close-dialog-text.test.ts create mode 100644 tests/unit/shared/update-keep.test.ts diff --git a/tests/unit/main/session-helper-app-wiring.test.ts b/tests/unit/main/session-helper-app-wiring.test.ts index 3dd1a7b5b..a7436072e 100644 --- a/tests/unit/main/session-helper-app-wiring.test.ts +++ b/tests/unit/main/session-helper-app-wiring.test.ts @@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' const h = vi.hoisted(() => ({ settings: {} as Record | null, - made: [] as Array<{ deps: Record; start: ReturnType; setRouting: ReturnType; stopRouting: ReturnType; shutdown: ReturnType; noteSavedTabs: ReturnType; releaseForUpdate: ReturnType; reclaim: ReturnType; enabled: boolean }>, + made: [] as Array<{ deps: Record; start: ReturnType; setRouting: ReturnType; stopRouting: ReturnType; shutdown: ReturnType; noteSavedTabs: ReturnType; releaseForUpdate: ReturnType; reclaim: ReturnType; tabsKeptThroughUpdate: ReturnType; enabled: boolean }>, /** The saved session file as peekSessionState reads it; an Error: it does not read. */ savedState: null as { sessions: unknown[] } | null | Error, savedStateReads: 0, @@ -75,6 +75,8 @@ vi.mock('../../../src/main/session-helper/manager', () => { releaseForUpdate = vi.fn((tabs: ReadonlySet | null) => tabs?.size ?? 0) endsForUpdate = vi.fn(() => h.updateEnds) reclaim = vi.fn(() => 0) + /** aicc_planning#514: the stand-in keeps each tab whose id ends in 1. */ + tabsKeptThroughUpdate = vi.fn((tabs: ReadonlySet) => new Set([...tabs].filter((t) => t.endsWith('1')))) serviceState = () => ({ state: this.enabled ? 'ready' : 'off', held: 0, lastError: null }) constructor(readonly deps: Record) { h.made.push(this as never) } onChange() {} @@ -96,7 +98,7 @@ vi.mock('../../../src/main/session-helper/manager', () => { import { QUIT_WAIT_MS, agentSessionsThroughHelperIn, applySessionHelperSettings, holdQuitForSessionHelper, initSessionHelper, noteSessionHelperTabs, plainTerminalsThroughHelperIn, - UPDATE_END_WAIT_MS, reclaimReleasedTerminals, releaseHeldTerminalsForUpdate, sessionHelperServiceState, shutdownSessionHelper, + UPDATE_END_WAIT_MS, reclaimReleasedTerminals, releaseHeldTerminalsForUpdate, sessionHelperServiceState, sessionsKeptThroughUpdate, shutdownSessionHelper, } from '../../../src/main/session-helper/app-wiring' beforeEach(() => { @@ -291,6 +293,32 @@ describe('the start-up clean-up of old helper copies (B1)', () => { }) }) +describe("the update dialog's count (aicc_planning#514)", () => { + it('with no helper this run: nothing is kept, and nothing is made or read', () => { + initSessionHelper(() => {}) + expect(sessionsKeptThroughUpdate({ agents: ['abcdef0123456789abcdef01'], terminals: ['abcdef0123456789abcdef11'] })).toEqual({ agents: 0, terminals: 0 }) + expect(h.made).toHaveLength(0) + expect(h.savedStateReads).toBe(0) + }) + + it("with the helper on: the manager is asked about every tab once, and its answer is counted by the kind the dialog asked under; it lets go of nothing", () => { + h.settings = { plainTerminalsThroughHelper: true } + initSessionHelper(() => {}) + const m = h.made[0] + const counts = sessionsKeptThroughUpdate({ + agents: ['abcdef0123456789abcdef01', 'abcdef0123456789abcdef02', 'abcdef0123456789abcdef21'], + terminals: ['abcdef0123456789abcdef11', 'abcdef0123456789abcdef12'], + }) + expect(counts).toEqual({ agents: 2, terminals: 1 }) + expect(m.tabsKeptThroughUpdate).toHaveBeenCalledTimes(1) + expect([...(m.tabsKeptThroughUpdate.mock.calls[0][0] as ReadonlySet)].sort()).toEqual([ + 'abcdef0123456789abcdef01', 'abcdef0123456789abcdef02', 'abcdef0123456789abcdef11', 'abcdef0123456789abcdef12', 'abcdef0123456789abcdef21', + ]) + expect(m.releaseForUpdate).not.toHaveBeenCalled() + expect(h.savedStateReads).toBe(0) + }) +}) + describe('an app update on Windows (plan section B2)', () => { it('with no helper this run (both switches off, no crash mark): the release and the reclaim do nothing, and nothing is made or read', async () => { initSessionHelper(() => {}) diff --git a/tests/unit/main/session-helper-manager.test.ts b/tests/unit/main/session-helper-manager.test.ts index 65e44044d..6f0b06649 100644 --- a/tests/unit/main/session-helper-manager.test.ts +++ b/tests/unit/main/session-helper-manager.test.ts @@ -1728,6 +1728,37 @@ describe('an app update on Windows: held plain and partner terminals are let go crash(m) }) + it('aicc_planning#514: the count the update dialog shows (tabsKeptThroughUpdate) names the tabs whose own terminal the update would keep, by the same rule, each asked about taken as saved; it lets go of nothing', async () => { + const m = await startedWith(makeManager(), ON_BOTH) + const ptys = await fourHeld(m) + const s = sids() + // A partner terminal is beside its tab, not the tab's own session; the + // Claude session's routes are not kept here (it ends at the update below); + // the unsaved tab counts once it is asked about, as Save sessions saves it. + expect([...m.tabsKeptThroughUpdate(new Set([PLAIN, PARENT, UNSAVED, AGENT]))].sort()).toEqual([PLAIN, UNSAVED].sort()) + expect([...m.tabsKeptThroughUpdate(new Set([PLAIN]))]).toEqual([PLAIN]) + expect([...m.tabsKeptThroughUpdate(new Set([PARENT, AGENT]))]).toEqual([]) + expect([...m.tabsKeptThroughUpdate(new Set())]).toEqual([]) + // Nothing was let go of, ended or marked: the update itself still does all of it. + for (const sid of Object.values(s)) { + expect(helper.holders.get(sid)!.endsAsked).toBe(0) + expect(helper.holders.get(sid)!.attached).not.toBeNull() + } + expect(liveOf(m).size).toBe(4) + expect(m.releaseForUpdate(SAVED)).toBe(2) + // The ones the update let go of are not counted again. + expect([...m.tabsKeptThroughUpdate(new Set([PLAIN, PARENT]))]).toEqual([]) + killAll(ptys) + }) + + it('aicc_planning#514: a quit keeps none, so the count is none once quitting', async () => { + const m = await startedWith(makeManager(), ON_BOTH) + await fourHeld(m) + ;(m as unknown as { quitting: boolean }).quitting = true + expect([...m.tabsKeptThroughUpdate(new Set([PLAIN, PARENT, UNSAVED, AGENT]))]).toEqual([]) + ;(m as unknown as { quitting: boolean }).quitting = false + }) + it('the installer could not start: reclaim keeps them for their tabs and lists them on the Machines page; the mark is the usual one again, and a tab started again takes its terminal over', async () => { const m = await startedWith(makeManager(), ON_BOTH) const ptys = await fourHeld(m) diff --git a/tests/unit/main/session-helper-take-over.test.ts b/tests/unit/main/session-helper-take-over.test.ts index 07c6fcb50..579623955 100644 --- a/tests/unit/main/session-helper-take-over.test.ts +++ b/tests/unit/main/session-helper-take-over.test.ts @@ -237,6 +237,45 @@ async function updated(): Promise<{ hc: FakeHolder; ho: FakeHolder; stream: numb return { hc, ho, stream } } +describe('the count of agent sessions the update dialog shows (aicc_planning#514): only one a restored tab takes over is counted as kept', () => { + async function bothHeld(m: SessionHelperManager): Promise { + spawnAgentPty(claudeTab(CLAUDE_TAB), SHELL, [], agentOpts()) + spawnAgentPty(otherTab(OTHER_TAB), SHELL, [], agentOpts()) + await until(() => freshAttached(claudeSid, undefined) && freshAttached(otherSid, undefined), 'both sessions to attach') + } + const BOTH = new Set([CLAUDE_TAB, OTHER_TAB]) + const count = (m: SessionHelperManager) => [...m.tabsKeptThroughUpdate(BOTH)].sort() + + it('a take-over wired for Claude Code only: the Claude Code tab counts, the Codex tab does not (the next start would end its session)', async () => { + const m = await startedWith(makeManager()) + await bothHeld(m) + expect(count(m)).toEqual([CLAUDE_TAB]) + // A count lets go of nothing and records nothing. + expect(keptOnDisk()).toEqual([]) + expect(helper.holders.get(claudeSid)!.attached).not.toBeNull() + expect(helper.holders.get(otherSid)!.attached).not.toBeNull() + }) + + it('a take-over wired for both: both count', async () => { + const m = await startedWith(makeManager({ takeOver: 'both' })) + await bothHeld(m) + expect(count(m)).toEqual([CLAUDE_TAB, OTHER_TAB].sort()) + }) + + it('no take-over wired: neither counts', async () => { + const m = await startedWith(makeManager({ takeOver: false })) + await bothHeld(m) + expect(count(m)).toEqual([]) + }) + + it('the agent sessions setting off: neither counts', async () => { + const m = await startedWith(makeManager({ takeOver: 'both' }), { atStartup: true, plain: true, agents: false }) + spawnAgentPty(claudeTab(CLAUDE_TAB), SHELL, [], agentOpts()) + await tick(30) + expect(count(m)).toEqual([]) + }) +}) + describe('the next start after an update: a restored tab takes its kept session over (S16 steps 5 and 6)', () => { it('keeps the Claude Code session for its tab and ends the other provider\'s; the tab takes it over with no launch: the same holder attached, its replay shown, the queued hook event delivered, the kept tool stream given back and served with toolsChanged; the record goes, the files stay', async () => { const beforeRelease = Date.now() diff --git a/tests/unit/main/update-handlers.test.ts b/tests/unit/main/update-handlers.test.ts index 6000246b6..fd94fbe8c 100644 --- a/tests/unit/main/update-handlers.test.ts +++ b/tests/unit/main/update-handlers.test.ts @@ -18,6 +18,9 @@ const shownErrorBoxes: Array<[string, string]> = [] const exitCalls: number[] = [] /** The install path's steps, in the order they ran (plan section B2). */ const steps = vi.hoisted(() => ({ order: [] as string[], releaseThrows: false, releaseDelayMs: 0, choices: [] as unknown[], handOverNotedAt: [] as number[] })) +/** aicc_planning#514: the update dialog's count, as the session helper's + * wiring answers it (what it was asked, and what it says or throws). */ +const kept = vi.hoisted(() => ({ asked: [] as unknown[], answer: { agents: 0, terminals: 0 } as unknown, throws: false })) vi.mock('electron', () => ({ ipcMain: { handle: (ch: string, fn: (...a: unknown[]) => unknown) => { handlers.set(ch, fn) } }, @@ -138,6 +141,11 @@ vi.mock('../../../src/main/session-helper/app-wiring', () => ({ return 2 }), reclaimReleasedTerminals: vi.fn(() => { steps.order.push('reclaim released terminals') }), + sessionsKeptThroughUpdate: vi.fn((tabs: unknown) => { + kept.asked.push(tabs) + if (kept.throws) throw new Error('the helper is not there') + return kept.answer + }), })) vi.mock('../../../src/main/registry', () => ({ readRegistry: () => null, writeRegistry: () => true })) vi.mock('../../../src/main/data-paths', () => ({ getDataDirectory: () => '/mock/dataDir' })) @@ -177,9 +185,66 @@ beforeEach(() => { steps.releaseDelayMs = 0 steps.choices.length = 0 steps.handOverNotedAt.length = 0 + kept.asked.length = 0 + kept.answer = { agents: 0, terminals: 0 } + kept.throws = false registerUpdateHandlers() }) +describe('update:sessionsKept: the update dialog asks main how many open tabs an update keeps (aicc_planning#514)', () => { + const ask = (...args: unknown[]) => Promise.resolve(handlers.get('update:sessionsKept')!({ sender: {} }, ...args)) + async function on(platform: NodeJS.Platform, run: () => Promise): Promise { + const original = process.platform + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) + try { + await run() + } finally { + Object.defineProperty(process, 'platform', { value: original, configurable: true }) + } + } + + it('is registered on the typed channel', async () => { + const { IPC } = await import('../../../src/shared/ipc-channels') + expect(IPC.UPDATE_SESSIONS_KEPT).toBe('update:sessionsKept') + expect(handlers.has(IPC.UPDATE_SESSIONS_KEPT)).toBe(true) + }) + + it("on Windows: the session helper's count for the tabs asked about, read through the parser (ids only, each once), counts only back", async () => { + await on('win32', async () => { + kept.answer = { agents: 3, terminals: 1 } + await expect(ask({ agents: ['a1', 'a2', 'a1', '../x', 7], terminals: ['t1', 'a2'], extra: 'ignored' })).resolves.toEqual({ agents: 3, terminals: 1 }) + expect(kept.asked).toEqual([{ agents: ['a1', 'a2'], terminals: ['t1'] }]) + // Nothing runs: no release, no kill, no launch. + expect(steps.order).toEqual([]) + }) + }) + + it('on Windows: a malformed question is a question about no tab', async () => { + await on('win32', async () => { + await ask('not a question') + await ask() + expect(kept.asked).toEqual([{ agents: [], terminals: [] }, { agents: [], terminals: [] }]) + }) + }) + + it('on Windows: a count that fails reads as nothing kept, and is logged', async () => { + await on('win32', async () => { + kept.throws = true + await expect(ask({ agents: ['a1'], terminals: [] })).resolves.toEqual({ agents: 0, terminals: 0 }) + }) + }) + + it('on macOS and Linux an update keeps no held session: nothing kept, and the helper is not asked', async () => { + for (const platform of ['darwin', 'linux'] as const) { + await on(platform, async () => { + kept.answer = { agents: 3, terminals: 1 } + await expect(ask({ agents: ['a1'], terminals: ['t1'] })).resolves.toEqual({ agents: 0, terminals: 0 }) + }) + } + expect(kept.asked).toEqual([]) + }) +}) + describe('Microsoft Store builds do not self-update', () => { // The Store owns updates for an MSIX install. Offering one would download an // NSIS installer the package container cannot run, and shipping a diff --git a/tests/unit/renderer/close-dialog-text.test.ts b/tests/unit/renderer/close-dialog-text.test.ts new file mode 100644 index 000000000..6a0add3b5 --- /dev/null +++ b/tests/unit/renderer/close-dialog-text.test.ts @@ -0,0 +1,162 @@ +/** + * aicc_planning#514: what the close and update dialogs say each choice does + * to the tabs open now (src/renderer/utils/closeDialogText.ts). A line per + * kind of tab open, with its count; a kind with none open has no line; the + * update dialog's kept count is main's answer, never the renderer's guess. + */ +import { describe, it, expect } from 'vitest' +import { closeDialogCounts, closeDialogText, sshKeepsRunning, updateKeepQuestion, type CloseDialogTab } from '../../../src/renderer/utils/closeDialogText' + +let n = 0 +const id = () => `tab-${++n}` +const agent = (extra: Partial = {}): CloseDialogTab => ({ id: id(), sessionType: 'local', ...extra }) +const terminal = (extra: Partial = {}): CloseDialogTab => ({ id: id(), sessionType: 'local', shellOnly: true, ...extra }) +/** An SSH Persistent tab: its config never chose a Connection. */ +const sshPersistent = (extra: Partial = {}): CloseDialogTab => ({ id: id(), sessionType: 'ssh', sshConfig: {}, ...extra }) +const signIn = (): CloseDialogTab => ({ id: id(), sessionType: 'local', shellOnly: true, transient: true }) +const many = (count: number, make: () => T): T[] => Array.from({ length: count }, make) +const none = { agents: 0, terminals: 0 } + +describe('sshKeepsRunning: the SSH Persistent rule', () => { + it('a config that never chose a Connection, or chose SSH Persistent, keeps running', () => { + expect(sshKeepsRunning(sshPersistent())).toBe(true) + expect(sshKeepsRunning(sshPersistent({ sshConfig: { detachable: true } }))).toBe(true) + }) + it('a config set to end with the connection does not', () => { + expect(sshKeepsRunning(sshPersistent({ sshConfig: { detachable: false } }))).toBe(false) + }) + it('a Terminal only SSH tab, a local tab, an SSH tab with no config, a sign-in tab do not', () => { + expect(sshKeepsRunning(sshPersistent({ shellOnly: true }))).toBe(false) + expect(sshKeepsRunning(agent())).toBe(false) + expect(sshKeepsRunning({ id: id(), sessionType: 'ssh' })).toBe(false) + expect(sshKeepsRunning(sshPersistent({ transient: true }))).toBe(false) + }) + it('what the start said wins: kept by the helper there, not kept, anchored, no tmux', () => { + expect(sshKeepsRunning(sshPersistent({ sshConfig: { detachable: false }, remoteVia: 'helper' }))).toBe(true) + expect(sshKeepsRunning(sshPersistent({ remoteVia: 'helper', remoteNotKept: true }))).toBe(false) + expect(sshKeepsRunning(sshPersistent({ remoteAnchored: true }))).toBe(false) + expect(sshKeepsRunning(sshPersistent({ sshTmuxPersistent: false }))).toBe(false) + }) +}) + +describe('updateKeepQuestion: what the dialog asks main about', () => { + it('the local saved tabs only, split into agent sessions and Terminal only tabs, ids only', () => { + const a = agent() + const t = terminal() + const q = updateKeepQuestion([a, t, sshPersistent(), signIn(), { id: id(), sessionType: 'ssh', sshConfig: { detachable: false } }]) + expect(q).toEqual({ agents: [a.id], terminals: [t.id] }) + }) +}) + +describe('the update dialog', () => { + it('the example: 4 kept, 3 SSH Persistent, 2 restart, each kind its own line, in that order', () => { + const tabs = [...many(6, () => agent()), ...many(3, () => sshPersistent())] + const text = closeDialogText('update', tabs, { agents: 4, terminals: 0 }) + expect(text.lines).toEqual([ + '4 keep running through the update and are back in their tabs straight away.', + '3 SSH sessions keep running on their hosts and reconnect.', + '2 restart and pick up their conversations.', + ]) + }) + + it('kept counts both kinds; the Terminal only tabs not kept start again', () => { + const tabs = [...many(2, () => agent()), ...many(5, () => terminal())] + expect(closeDialogText('update', tabs, { agents: 2, terminals: 3 }).lines).toEqual([ + '5 keep running through the update and are back in their tabs straight away.', + '2 terminals start again.', + ]) + }) + + it('one of a kind reads in the singular', () => { + const tabs = [agent(), agent(), terminal(), sshPersistent(), signIn()] + expect(closeDialogText('update', tabs, { agents: 1, terminals: 0 }).lines).toEqual([ + '1 keeps running through the update and is back in its tab straight away.', + '1 SSH session keeps running on its host and reconnects.', + '1 restarts and picks up its conversation.', + '1 terminal starts again.', + '1 sign-in or install tab ends.', + ]) + }) + + it('a kind with none open has no line (nothing kept: no kept line, no SSH: no SSH line)', () => { + const text = closeDialogText('update', [agent(), agent(), agent()], none) + expect(text.lines).toEqual(['3 restart and pick up their conversations.']) + expect(text.lines.join(' ')).not.toMatch(/\b0\b/) + }) + + it('every agent kept leaves no restart line', () => { + expect(closeDialogText('update', [agent(), agent()], { agents: 2, terminals: 0 }).lines).toEqual([ + '2 keep running through the update and are back in their tabs straight away.', + ]) + }) + + it("main's answer above the tabs asked about counts as all of them, never more", () => { + const c = closeDialogCounts('update', [agent(), terminal()], { agents: 9, terminals: 9 }) + expect(c).toMatchObject({ total: 2, kept: 2, resume: 0, fresh: 0 }) + }) + + it('sign-in and install tabs, plural', () => { + expect(closeDialogText('update', [signIn(), signIn()], none).lines).toEqual(['2 sign-in or install tabs end.']) + }) +}) + +describe('the quit dialog', () => { + it('held sessions end at a quit: nothing is kept, whatever is passed', () => { + const tabs = [agent(), agent(), terminal()] + const c = closeDialogCounts('close', tabs, { agents: 2, terminals: 1 }) + expect(c.kept).toBe(0) + expect(closeDialogText('close', tabs, { agents: 2, terminals: 1 }).lines).toEqual([ + '2 end and pick up their conversations at the next launch.', + '1 terminal ends and starts again at the next launch.', + ]) + }) + + it('SSH Persistent sessions keep running on their hosts; singular forms', () => { + expect(closeDialogText('close', [agent(), sshPersistent(), terminal(), signIn()], none).lines).toEqual([ + '1 ends and picks up its conversation at the next launch.', + '1 SSH session keeps running on its host and reconnects at the next launch.', + '1 terminal ends and starts again at the next launch.', + '1 sign-in or install tab ends.', + ]) + expect(closeDialogText('close', [sshPersistent(), sshPersistent()], none).lines).toEqual([ + '2 SSH sessions keep running on their hosts and reconnect at the next launch.', + ]) + }) + + it('never says the update line', () => { + const text = closeDialogText('close', [agent(), terminal()], { agents: 1, terminals: 1 }) + expect(text.lines.join(' ')).not.toContain('through the update') + }) +}) + +describe('the Close sessions line', () => { + it('ends all of them when no SSH session keeps running', () => { + expect(closeDialogText('update', [...many(4, () => agent()), ...many(3, () => terminal())], { agents: 4, terminals: 0 }).close).toBe('Close sessions ends all 7.') + expect(closeDialogText('close', [agent()], none).close).toBe('Close sessions ends it.') + }) + + it('says the SSH Persistent sessions keep running: their tabs close, the hosts keep them', () => { + expect(closeDialogText('update', [agent(), agent(), sshPersistent(), sshPersistent(), sshPersistent()], none).close) + .toBe('Close sessions ends 2 and closes every tab; the 3 SSH sessions keep running on their hosts.') + expect(closeDialogText('close', [agent(), sshPersistent()], none).close) + .toBe('Close sessions ends 1 and closes every tab; the SSH session keeps running on its host.') + }) + + it('only SSH Persistent tabs: it closes the tabs and ends nothing', () => { + expect(closeDialogText('close', [sshPersistent(), sshPersistent()], none).close).toBe('Close sessions closes every tab; the 2 SSH sessions keep running on their hosts.') + expect(closeDialogText('close', [sshPersistent()], none).close).toBe('Close sessions closes its tab; the SSH session keeps running on its host.') + }) +}) + +describe('plain text', () => { + it('no em dash, no curly quotes, every line a sentence', () => { + const tabs = [agent(), agent(), terminal(), terminal(), sshPersistent(), sshPersistent(), signIn(), signIn()] + for (const mode of ['close', 'update'] as const) { + const text = closeDialogText(mode, tabs, { agents: 1, terminals: 1 }) + for (const line of [...text.lines, text.close]) { + expect(line).not.toMatch(/[—‘’“”]/) + expect(line).toMatch(/^[0-9A-Z].*\.$/) + } + } + }) +}) diff --git a/tests/unit/renderer/close-dialogs-tokens.test.tsx b/tests/unit/renderer/close-dialogs-tokens.test.tsx index 95b73ffd9..27dbc55d6 100644 --- a/tests/unit/renderer/close-dialogs-tokens.test.tsx +++ b/tests/unit/renderer/close-dialogs-tokens.test.tsx @@ -48,7 +48,7 @@ const click = (el: HTMLElement | null) => act(() => { el!.click() }) describe('CloseDialog', () => { function render(mode: 'close' | 'update' = 'close') { const props = { onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel: vi.fn() } - act(() => { root.render(React.createElement(CloseDialog, { mode, sessionCount: 2, ...props })) }) + act(() => { root.render(React.createElement(CloseDialog, { mode, tabs: [{ id: 'a', sessionType: 'local' }, { id: 'b', sessionType: 'local' }], ...props })) }) return props } @@ -75,6 +75,92 @@ describe('CloseDialog', () => { }) }) +describe('CloseDialog says what each choice does to the tabs open (aicc_planning#514)', () => { + type Tab = { id: string; sessionType: 'local' | 'ssh'; shellOnly?: boolean; transient?: boolean; sshConfig?: { detachable?: boolean } } + const tabs: Tab[] = [ + { id: 'a1', sessionType: 'local' }, { id: 'a2', sessionType: 'local' }, { id: 'a3', sessionType: 'local' }, + { id: 't1', sessionType: 'local', shellOnly: true }, + { id: 's1', sessionType: 'ssh', sshConfig: {} }, { id: 's2', sessionType: 'ssh', sshConfig: {} }, + { id: 'x1', sessionType: 'local', shellOnly: true, transient: true }, + ] + const lines = () => Array.from(byTest('close-dialog-lines')?.querySelectorAll('p') ?? []).map((p) => p.textContent) + const sessionsKept = vi.fn<(q: unknown) => Promise>() + beforeEach(() => { + sessionsKept.mockReset() + ;(window as any).electronAPI = { update: { sessionsKept } } + }) + afterEach(() => { delete (window as any).electronAPI }) + async function show(mode: 'close' | 'update', open: Tab[] = tabs) { + const props = { onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel: vi.fn() } + await act(async () => { root.render(React.createElement(CloseDialog, { mode, tabs: open, ...props })) }) + await act(async () => { await Promise.resolve() }) + } + + it('update: asks main once, about the local saved tabs by id only, and shows a line per kind with its count', async () => { + sessionsKept.mockResolvedValue({ agents: 2, terminals: 1 }) + await show('update') + expect(sessionsKept).toHaveBeenCalledTimes(1) + expect(sessionsKept).toHaveBeenCalledWith({ agents: ['a1', 'a2', 'a3'], terminals: ['t1'] }) + expect(container.textContent).toContain('You have 7 active sessions.') + expect(lines()).toEqual([ + '3 keep running through the update and are back in their tabs straight away.', + '2 SSH sessions keep running on their hosts and reconnect.', + '1 restarts and picks up its conversation.', + '1 sign-in or install tab ends.', + 'Close sessions ends 5 and closes every tab; the 2 SSH sessions keep running on their hosts.', + ]) + expect(container.textContent).not.toContain('Save them and they come back') + }) + + it('update: shows no line until main has answered (never a guess that it then takes back)', async () => { + let answer: (v: unknown) => void = () => {} + sessionsKept.mockReturnValue(new Promise((r) => { answer = r })) + await show('update') + expect(byTest('close-dialog-lines')).toBeNull() + await act(async () => { answer({ agents: 0, terminals: 0 }) }) + expect(lines()[0]).toBe('2 SSH sessions keep running on their hosts and reconnect.') + }) + + it('update: an answer that does not read, or a failed question, reads as nothing kept', async () => { + sessionsKept.mockResolvedValue({ agents: 'all', terminals: 1 }) + await show('update') + expect(lines()).not.toContain('3 keep running through the update and are back in their tabs straight away.') + expect(lines()).toContain('3 restart and pick up their conversations.') + act(() => { root.unmount() }) + root = createRoot(container) + sessionsKept.mockRejectedValue(new Error('gone')) + await show('update') + expect(lines()).toContain('3 restart and pick up their conversations.') + expect(lines()).toContain('1 terminal starts again.') + }) + + it('update with no local tab: main is not asked', async () => { + await show('update', [{ id: 's1', sessionType: 'ssh', sshConfig: {} }]) + expect(sessionsKept).not.toHaveBeenCalled() + expect(lines()).toEqual([ + '1 SSH session keeps running on its host and reconnects.', + 'Close sessions closes its tab; the SSH session keeps running on its host.', + ]) + }) + + it('quit: main is not asked, held sessions end, and the wording is for the next launch', async () => { + await show('close') + expect(sessionsKept).not.toHaveBeenCalled() + expect(lines()).toEqual([ + '3 end and pick up their conversations at the next launch.', + '2 SSH sessions keep running on their hosts and reconnect at the next launch.', + '1 terminal ends and starts again at the next launch.', + '1 sign-in or install tab ends.', + 'Close sessions ends 5 and closes every tab; the 2 SSH sessions keep running on their hosts.', + ]) + }) + + it('no kind with none open: two Claude Code tabs at a quit read two lines', async () => { + await show('close', [{ id: 'a1', sessionType: 'local' }, { id: 'a2', sessionType: 'local' }]) + expect(lines()).toEqual(['2 end and pick up their conversations at the next launch.', 'Close sessions ends all 2.']) + }) +}) + describe('SshCloseDialog', () => { function render() { act(() => { root.render(React.createElement(SshCloseDialog)) }) diff --git a/tests/unit/renderer/hello-codex.acceptance.test.ts b/tests/unit/renderer/hello-codex.acceptance.test.ts index bdccc1819..67bbcac9a 100644 --- a/tests/unit/renderer/hello-codex.acceptance.test.ts +++ b/tests/unit/renderer/hello-codex.acceptance.test.ts @@ -882,7 +882,7 @@ describe('Hello Codex: review round 1', () => { const onCancel = vi.fn() const both = (withDialog: boolean) => h(React.Fragment, null, h(HelloCodexTakeover, { onClose, onStartSession: vi.fn() }), - withDialog ? h(CloseDialog, { mode: 'close', sessionCount: 2, onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel }) : null) + withDialog ? h(CloseDialog, { mode: 'close', tabs: [{ id: 'a', sessionType: 'local' }, { id: 'b', sessionType: 'local' }], onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel }) : null) await renderArmed(both(true)) await key('Escape') expect(onCancel).toHaveBeenCalledTimes(1) diff --git a/tests/unit/renderer/onboarding-focus-trap.test.tsx b/tests/unit/renderer/onboarding-focus-trap.test.tsx index a0c638538..1370c135e 100644 --- a/tests/unit/renderer/onboarding-focus-trap.test.tsx +++ b/tests/unit/renderer/onboarding-focus-trap.test.tsx @@ -231,7 +231,7 @@ describe('Hello Codex, the takeover and a replay, keep Tab in', () => { const onCancel = vi.fn() await render(h(React.Fragment, null, h(HelloCodexTakeover, { replay: true, onClose, onStartSession: vi.fn() }), - h(CloseDialog, { mode: 'close', sessionCount: 2, onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel }))) + h(CloseDialog, { mode: 'close', tabs: [{ id: 'a', sessionType: 'local' }, { id: 'b', sessionType: 'local' }], onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel }))) const dialog = document.querySelector('[role="dialog"][aria-modal="true"]:not([data-testid="hello-codex"])') as HTMLElement const buttons = Array.from(dialog.querySelectorAll('button')) buttons[buttons.length - 1].focus() diff --git a/tests/unit/renderer/window-close-dialogs.test.tsx b/tests/unit/renderer/window-close-dialogs.test.tsx index 861e89ffb..a46310786 100644 --- a/tests/unit/renderer/window-close-dialogs.test.tsx +++ b/tests/unit/renderer/window-close-dialogs.test.tsx @@ -104,7 +104,7 @@ async function tab(shift = false) { await act(async () => { target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: shift, bubbles: true, cancelable: true })) }) } -const closeDialog = () => h(CloseDialog, { mode: 'close', sessionCount: 2, onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel: vi.fn() }) +const closeDialog = () => h(CloseDialog, { mode: 'close', tabs: [{ id: 'a', sessionType: 'local' }, { id: 'b', sessionType: 'local' }], onSaveAndClose: vi.fn(), onCloseWithoutSaving: vi.fn(), onCancel: vi.fn() }) const PENDING = { sessionId: 's1', label: 'prod box', host: 'prod.example' } /** The z-index a Tailwind class list sets (`z-50`, `z-[200]`), or null. */ diff --git a/tests/unit/shared/update-keep.test.ts b/tests/unit/shared/update-keep.test.ts new file mode 100644 index 000000000..25ac99671 --- /dev/null +++ b/tests/unit/shared/update-keep.test.ts @@ -0,0 +1,57 @@ +/** + * aicc_planning#514: the update dialog's question to main and main's answer + * (src/shared/update-keep.ts). Each side reads the other's message through + * these parsers: main never trusts the renderer's lists, and the renderer + * never shows a count that is not a whole number. + */ +import { describe, it, expect } from 'vitest' +import { NOTHING_KEPT, UPDATE_KEEP_MAX_TABS, updateKeepCountsFrom, updateKeepTabsFrom } from '../../../src/shared/update-keep' + +const A = 'abcdef0123456789abcdef01' +const B = 'abcdef0123456789abcdef02' +const C = 'abcdef0123456789abcdef03' + +describe("updateKeepTabsFrom: main's read of the renderer's question", () => { + it('keeps the two id lists, each id once', () => { + expect(updateKeepTabsFrom({ agents: [A, B, A], terminals: [C, C] })).toEqual({ agents: [A, B], terminals: [C] }) + }) + + it('an id named as both kinds is read as an agent session only', () => { + expect(updateKeepTabsFrom({ agents: [A], terminals: [A, B] })).toEqual({ agents: [A], terminals: [B] }) + }) + + it('drops anything that is not a tab id: a path, an empty or too long string, a number, an object', () => { + const odd = ['C:\\Users\\someone', '../x', '', 'x'.repeat(129), 7, { id: A }, null, `${A} `] + expect(updateKeepTabsFrom({ agents: [...odd, A], terminals: odd })).toEqual({ agents: [A], terminals: [] }) + }) + + it('a question that is not two lists is a question about no tab', () => { + for (const raw of [undefined, null, 'x', 5, [], [A], { agents: A }, { agents: { 0: A } }, { terminals: 'abc' }]) { + expect(updateKeepTabsFrom(raw), JSON.stringify(raw)).toEqual({ agents: [], terminals: [] }) + } + }) + + it(`reads at most ${UPDATE_KEEP_MAX_TABS} ids of each kind`, () => { + const many = Array.from({ length: UPDATE_KEEP_MAX_TABS + 40 }, (_, i) => `tab-${i}`) + const read = updateKeepTabsFrom({ agents: many, terminals: many.map((id) => `t${id}`) }) + expect(read.agents).toHaveLength(UPDATE_KEEP_MAX_TABS) + expect(read.terminals).toHaveLength(UPDATE_KEEP_MAX_TABS) + }) +}) + +describe("updateKeepCountsFrom: the renderer's read of main's answer", () => { + it('two whole numbers of 0 or more, and nothing else is passed on', () => { + expect(updateKeepCountsFrom({ agents: 4, terminals: 0, ids: [A] })).toEqual({ agents: 4, terminals: 0 }) + }) + + it('anything else is null (the dialog then says nothing is kept)', () => { + for (const raw of [undefined, null, 3, 'x', {}, { agents: 1 }, { agents: -1, terminals: 0 }, { agents: 1.5, terminals: 0 }, { agents: '2', terminals: 0 }, { agents: Number.NaN, terminals: 0 }]) { + expect(updateKeepCountsFrom(raw), JSON.stringify(raw)).toBeNull() + } + }) + + it('NOTHING_KEPT is none of either, and cannot be changed', () => { + expect(NOTHING_KEPT).toEqual({ agents: 0, terminals: 0 }) + expect(Object.isFrozen(NOTHING_KEPT)).toBe(true) + }) +}) diff --git a/tests/unit/update-install-bridge.test.ts b/tests/unit/update-install-bridge.test.ts index 30bf910ed..53040e6b6 100644 --- a/tests/unit/update-install-bridge.test.ts +++ b/tests/unit/update-install-bridge.test.ts @@ -50,3 +50,24 @@ describe('update.installAndRestart bridge (section B3)', () => { await expect(api.update.installAndRestart()).resolves.toBe(true) }) }) + +describe('update.sessionsKept bridge (aicc_planning#514)', () => { + it('sends only the two id lists on the typed channel, and nothing else it was given', async () => { + el.ipcRenderer.invoke.mockClear() + await api.update.sessionsKept({ agents: ['a1'], terminals: ['t1'], cwd: 'C:/somewhere', label: 'x' }) + expect(el.ipcRenderer.invoke).toHaveBeenCalledTimes(1) + expect(el.ipcRenderer.invoke).toHaveBeenCalledWith(IPC.UPDATE_SESSIONS_KEPT, { agents: ['a1'], terminals: ['t1'] }) + expect(IPC.UPDATE_SESSIONS_KEPT).toBe('update:sessionsKept') + }) + + it('a call with no question still goes as the two lists (main reads them as none)', async () => { + el.ipcRenderer.invoke.mockClear() + await api.update.sessionsKept(undefined) + expect(el.ipcRenderer.invoke).toHaveBeenCalledWith(IPC.UPDATE_SESSIONS_KEPT, { agents: undefined, terminals: undefined }) + }) + + it('hands back what main answers', async () => { + el.ipcRenderer.invoke.mockResolvedValueOnce({ agents: 2, terminals: 1 }) + await expect(api.update.sessionsKept({ agents: [], terminals: [] })).resolves.toEqual({ agents: 2, terminals: 1 }) + }) +}) From 59a84c6c1a9fcf4db8b7d701602f73ca0bae2229 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:23:03 +0000 Subject: [PATCH 30/79] docs(knowledge): describe the close and update dialogs and the restore after an update (#514, #515) The Feature Guide reference (and what Ask Conductor knows) now describes what the close and update dialogs say, and that after an update with Save sessions the new version reopens the tabs by itself, with no resume prompt and no account picker, each session on its own account; a quit, a crash or the same version starting again still asks. The accounts entry says the same for Resuming sessions. The update tip, the Machines card and the README no longer tell the user to resume within five minutes: the tabs reopen by themselves once the pages the new version opens with are closed, still within five minutes. The hook-event known issue no longer names a Resume press. The tip and card pins follow the new text. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/renderer/tips-library.ts | 2 +- src/renderer/training-steps.ts | 2 +- src/shared/app-knowledge.ts | 8 +++++--- tests/unit/shared/app-knowledge.test.ts | 8 ++++++-- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fa0616cb9..37e1336ca 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ On-demand reports over your own usage, Claude Code's and Codex's, runnable acros - **Feature Guide** — a searchable in-app reference with a card for every feature (what it does, how to open it, a tip) plus the complete What's New history, a click away from the sidebar's help button. - **Browser pane** — every session has a browser beside its terminal: an address bar (type `localhost:5173` and press Enter), working history, a home page per config, saved favourites, and a button to open the page in your real browser. Pages load in a sandbox with every permission off. A command button can point it at a dev server as it starts ("watch for a page") or simply open a page; freeze the page to annotate a snapshot in Excalidraw. - **Partner terminal and scratchpad** — every session carries a partner shell in the same tab (on the host, for an SSH session), and a per-session Excalidraw whiteboard that persists with the config; export the drawing straight into the session. -- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: each restored tab takes over the same running session, with no resume, even a tab you open later. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. +- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: the new version reopens your tabs with nothing to answer (no resume prompt, no account picker), and each restored tab takes over the same running session, with no resume, even a tab you open later. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. - **Multi-account usage strip** — every signed-in account's usage along the bottom of the window, one pill per person, grouped by provider so Claude Code and Codex figures are never merged, and a minimal mode that shows just the account name and two traffic-light dots (green under 70 %, amber to 89 %, red from 90 %) so the strip stays readable with many accounts. The **Accounts** page shows every Claude and Codex account's 5-hour and weekly allowance at once, one line each: each bar fills with what is used, the lines are grouped In use, Not in use and Not usable now, you sort by Room, Weekly or Name, and with both assistants on you can show one of them. The **Most room now** line above the groups names the free account with the most room, and a line says when it is out of its limit until a time, inactive, or must sign in again. Click a line to open it for its sign-ins: Claude Code's or Codex's, and the account's claude.ai or chatgpt.com sign-in, who it is signed in as and since when. There is no Refresh, and the page never asks for a reading itself: an account in use reads live from its session, an idle one keeps its last reading (a window past its reset reads 0% used), and the app checks the usage of idle accounts still signed in, Claude Code's and Codex's, in the background, one at a time, at least 10 minutes apart and each account at most every 3 hours; while Anthropic rate-limits those checks, the lines count down to the next one. Sign-ins on a machine you added (remote sessions preview) are on that machine's card on the Machines page. - **Snap and Vision capture** — region or window capture from any screen, capped at 1920px, with a JPEG copy saved. Snap puts the picture on your clipboard and presses the assistant's own paste key, so a Claude Code or Codex session gets it as its own pasted image with a short sentence, and no file path is typed; the picture stays on your clipboard afterwards. An SSH tab on the usual path fetches it over the tunnel. `Alt+V` (`Option+V` on a Mac) pastes a clipboard image the same way, and `Ctrl+V` (`Cmd+V`) does too when the clipboard holds only a picture; in a plain terminal, `Alt+V` goes to the program there as a key. On Linux, Claude Code reads the clipboard with `xclip` or `wl-paste`, and the hint names them when the one your desktop needs (`xclip` under X11, `wl-paste` under Wayland) is not installed. On a Mac, Snap checks the Screen Recording permission first and, without it, offers to open System Settings instead of capturing. On Windows, Snap's region capture uses the app's own overlay (a rectangle or the whole screen, no drawing tools); the earlier Snap is a setting away and opens by itself for any press the new one cannot take. - **A first-run tour and What's New that know where you came from**: a fresh install gets the tour; an update shows what is new since the version you came from (every prerelease of a release shows that release's whole story, and release notes can open with warnings, shown first, including those of any release you skipped), and an update across a release line also walks the tour again. diff --git a/src/renderer/tips-library.ts b/src/renderer/tips-library.ts index 663cd29cf..cebfcedce 100644 --- a/src/renderer/tips-library.ts +++ b/src/renderer/tips-library.ts @@ -1822,7 +1822,7 @@ export const TIPS_LIBRARY: Tip[] = [ primary: { shortText: 'Save sessions at an update keeps held terminals running', title: 'Terminals That Live Through an Update', - body: 'With **Plain terminals through the session helper** on (**Settings, General, Terminal**; a preview, off by default), choose **Save sessions** when the app asks before an update. The terminals the session helper holds keep running, and the new version shows each one again in its tab, with what it printed meanwhile, up to the last 2 MiB.\n\nFinish the installer within **two minutes**: a held terminal waits that long for the new version, counted from when the old one closed. **Close sessions** ends them instead. With **Claude Code and Codex sessions through the session helper** on as well, a Claude Code or Codex session is kept the same way: resume your sessions within **five minutes** of the new version opening and its tab shows the same session, with no resume.', + body: 'With **Plain terminals through the session helper** on (**Settings, General, Terminal**; a preview, off by default), choose **Save sessions** when the app asks before an update. The terminals the session helper holds keep running, and the new version shows each one again in its tab, with what it printed meanwhile, up to the last 2 MiB.\n\nFinish the installer within **two minutes**: a held terminal waits that long for the new version, counted from when the old one closed. **Close sessions** ends them instead. With **Claude Code and Codex sessions through the session helper** on as well, a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing to answer, once you close the pages it opens with (such as the release notes). Close them within **five minutes** of it opening and each tab shows the same session, on the same account, with no resume.', actionLabel: 'Open Settings', actionTarget: 'settings', focusHint: 'Settings -- General, under Terminal', diff --git a/src/renderer/training-steps.ts b/src/renderer/training-steps.ts index 2369cc8c3..128bbf3c6 100644 --- a/src/renderer/training-steps.ts +++ b/src/renderer/training-steps.ts @@ -718,7 +718,7 @@ export const trainingSteps: TrainingStep[] = [ '**Re-attach** connects a detached terminal again, and opens a Terminal only tab for one no tab shows; **End** stops one after you confirm', 'After a crash on Windows, open the app within two minutes and resume your sessions: each held terminal shows again in its tab, with what it printed meanwhile, up to the last 2 MiB. Quitting normally ends them. If the app only freezes for a while, what the helper holds keeps running, a Claude Code or Codex session included, and each tab shows it again once the app answers; a terminal or session that a version before 2.1.3-beta.24 started is not kept this way', 'On Windows, choose **Save sessions** when you update the app and each held Terminal or Partner terminal keeps running. If the new version opens within two minutes, it shows them again. **Close sessions** ends them', - 'A Claude Code or Codex session has **End** only. After a crash it is ended, reading **Being ended** until it is gone, and its tab resumes the conversation. On Windows, **Save sessions** at an update keeps it running: resume your sessions within five minutes of the new version opening and its tab shows the same session again', + 'A Claude Code or Codex session has **End** only. After a crash it is ended, reading **Being ended** until it is gone, and its tab resumes the conversation. On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once the pages it opens with are closed, and within five minutes of it opening the tab shows the same session again', 'With **Claude Code and Codex sessions through the session helper** on, an Insights report for a Claude Code account runs inside the helper too, and is listed as **Insights report** while it runs, with **End** only', 'SSH tabs and their partner terminals, a terminal run as administrator, and the tabs the app opens for a sign-in or to install or update a program start as before', 'On Windows, the Machines page also lists, under **Other machines**, the Linux machines (x86-64 or arm64, a Raspberry Pi included) you added for remote sessions through the session helper (preview), with Add, Check and Remove, and the sessions each one keeps for an SSH Persistent tab, with Re-attach and End. Each card leads with the mark of its system, names it and its version, and says when the machine was last seen or that it is **Not reachable**; with many machines, filter them by name, kind or status and sort them by last seen, name or kind. A card also shows the Claude Code and Codex versions its last Check found. A config that keeps a password signs in with it, and a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you press Add, Check or Remove. A Claude Code or Codex session on such a machine through the helper has a **Restart** menu in its status strip: **Restart Claude Code on** the machine (or **Restart Codex**) ends that program there and starts it again on the same conversation, so an update it installed applies', diff --git a/src/shared/app-knowledge.ts b/src/shared/app-knowledge.ts index e16b456cb..f7c06910b 100644 --- a/src/shared/app-knowledge.ts +++ b/src/shared/app-knowledge.ts @@ -34,6 +34,8 @@ A Terminal only config over SSH is a terminal and nothing more, so the app never Quitting the app. When you quit, the app closes down each Claude Code or Codex session it started by typing that assistant's exit keys into it (Escape, Ctrl-C and /exit for Claude Code; Escape, Ctrl-C and a second Ctrl-C a moment later for Codex), and an SSH Persistent session is detached and keeps running on its host. Every other terminal is closed with nothing typed into it: Terminal only tabs, partner terminals, and SSH tabs where the app did not start an assistant. Whatever runs in such a terminal is left as closing any terminal leaves it, so a tmux session you attached to keeps running. +Closing or updating with sessions open. The dialog that asks says what each choice does to the tabs open, with how many of each kind, and leaves out a kind with none open. At a quit, Save sessions closes the Claude Code and Codex tabs and they pick up their conversations at the next launch, an SSH Persistent session keeps running on its host and reconnects, and a Terminal only tab starts again. Before an update it also says how many keep running through the update and are back in their tabs straight away (on Windows, the sessions the session helper holds, with its switches on), and the rest restart and pick up their conversations. A sign-in or install tab is never saved and ends. Close sessions ends every session, except that an SSH Persistent session keeps running on its host while its tab closes. After an update where you chose Save sessions, the new version reopens your tabs by itself once the pages it opens with (such as the release notes) are closed: there is no resume prompt and no account picker, and each session carries on as it was, on its own account. A quit, a crash, or the same version starting again still asks with the resume prompt. + Reopening after a crash. When the app stops without closing, from a crash, a power cut or a killed process, each Claude Code tab reopens on the newest conversation it was on, even when you moved it to a new conversation with /clear or /resume after the app last saved the tab list. The app now saves a tab's place as soon as the tab moves to another conversation, and writes the saved tab file so that a power cut cannot leave it half written. At the next start, a newer record of a tab's conversation wins over an older saved one, and the start log says which conversation each tab resumes. This needs session logging on, which is the default; with it off a tab reopens as before. A tab that never moved reopens as before. At a start, one Claude Code conversation is never reopened in two tabs. With session logging on, when you use /resume in one tab to open the conversation another tab was on (its Claude Code had ended, or the tab had not been opened yet since the app started), that conversation goes to the tab you opened it in. If that tab is still on it when the app stops, the other tab comes back on the resume picker at the next start; if not, the other tab may resume it. A tab not opened yet starts a new conversation if you open it while that tab's Claude Code is still running on that conversation; open it later and it may resume it instead. The app log names the tab that gave the conversation up.`, }, { @@ -56,7 +58,7 @@ What an SSH session's setup does to your user settings (~/.claude/settings.json) { id: 'accounts', title: 'Multiple Claude accounts', - body: `On Windows and Linux you can run each local session under a different Claude account. Logins never mix between accounts, while memory, projects, and history are shared, so switching never loses your place. Your existing login becomes the primary account and is backed up once before anything is set up. Switching accounts applies to local sessions and, in the remote sessions preview, to a Claude Code tab through the session helper on a Linux machine you added, where each account signs in once on that machine (see The Machines page). A usual SSH session uses the remote machine's own login, and Codex has accounts of its own (see Codex: sessions and accounts). A remote session still shows which account it is signed in as, on its session card, in its session header and in the multi-account strip, and it contributes its own usage there; running /login on the remote moves it to the right account within a few seconds. When a remote session is signed in as one of the accounts you also run locally, its header and its right-click menu carry that account's claude.ai and Claude Code tools too, Open artifacts and the sign-in items included, because those act on the account here on your own machine; the account switch itself stays local-only for a usual SSH session, and a remote session with no matching local account simply shows the account name. Add accounts on the Accounts page (Accounts on the left rail), and switch them in the New Session picker or from the account pill, which sits at the far left of every session's status line. Adding a Claude account, or signing one in again, opens a sign-in tab on this computer in which Claude Code starts under that account: sign in when it asks, or type /login, and choose the account. The app notices the sign-in on its own. It starts Claude Code for you because Windows PowerShell can refuse to run a Claude Code installed with npm when you type claude yourself. A sign-in tab whose account is no longer set up here, because it was removed while the tab was open for example, starts nothing and says to add the account again on the Accounts page. A sign-in tab on an inactive account starts nothing either, and says so: The Claude account "NAME" is inactive, so this sign-in tab did not start Claude Code. Make the account active first: use Make active on "NAME" on the Accounts page, then sign it in again. A Claude session whose account is no longer set up here, because the account was removed for example, starts nothing and says so: This session's Claude account is no longer set up here. Choose an account for it and start it again. It never runs on another account in its place. When the app reopens your sessions after a restart, each Claude session runs on the account it last ran on. Set Settings, Accounts, Resuming sessions to Ask each time to be asked for each one instead: its picker has that account already chosen and marked This session's account. When you start a new session, the picker marks the account you used most recently as Most recent. The claude.ai pill in the session header follows the account's live claude.ai sign-in; press the refresh arrow on the Claude Code pill next to it to check both again. On macOS this is not available yet, because Claude Code keeps its sign-in in the login Keychain, which cannot be isolated per account, so a session, cloud agent or Insights run on an account other than the primary one is refused there with a sentence that says to choose the primary account (once a primary account is recorded; with none recorded, sessions start as before). A Claude session on an inactive account (Make inactive on the Accounts page) is refused on every system, wherever it comes from, with a sentence that names the account and says how to switch the tab or make the account active again. + body: `On Windows and Linux you can run each local session under a different Claude account. Logins never mix between accounts, while memory, projects, and history are shared, so switching never loses your place. Your existing login becomes the primary account and is backed up once before anything is set up. Switching accounts applies to local sessions and, in the remote sessions preview, to a Claude Code tab through the session helper on a Linux machine you added, where each account signs in once on that machine (see The Machines page). A usual SSH session uses the remote machine's own login, and Codex has accounts of its own (see Codex: sessions and accounts). A remote session still shows which account it is signed in as, on its session card, in its session header and in the multi-account strip, and it contributes its own usage there; running /login on the remote moves it to the right account within a few seconds. When a remote session is signed in as one of the accounts you also run locally, its header and its right-click menu carry that account's claude.ai and Claude Code tools too, Open artifacts and the sign-in items included, because those act on the account here on your own machine; the account switch itself stays local-only for a usual SSH session, and a remote session with no matching local account simply shows the account name. Add accounts on the Accounts page (Accounts on the left rail), and switch them in the New Session picker or from the account pill, which sits at the far left of every session's status line. Adding a Claude account, or signing one in again, opens a sign-in tab on this computer in which Claude Code starts under that account: sign in when it asks, or type /login, and choose the account. The app notices the sign-in on its own. It starts Claude Code for you because Windows PowerShell can refuse to run a Claude Code installed with npm when you type claude yourself. A sign-in tab whose account is no longer set up here, because it was removed while the tab was open for example, starts nothing and says to add the account again on the Accounts page. A sign-in tab on an inactive account starts nothing either, and says so: The Claude account "NAME" is inactive, so this sign-in tab did not start Claude Code. Make the account active first: use Make active on "NAME" on the Accounts page, then sign it in again. A Claude session whose account is no longer set up here, because the account was removed for example, starts nothing and says so: This session's Claude account is no longer set up here. Choose an account for it and start it again. It never runs on another account in its place. When the app reopens your sessions after a restart, each Claude session runs on the account it last ran on. Set Settings, Accounts, Resuming sessions to Ask each time to be asked for each one instead: its picker has that account already chosen and marked This session's account. After an app update where you chose Save sessions, nothing is asked whatever that setting says: each session carries on as it was, on its own account. When you start a new session, the picker marks the account you used most recently as Most recent. The claude.ai pill in the session header follows the account's live claude.ai sign-in; press the refresh arrow on the Claude Code pill next to it to check both again. On macOS this is not available yet, because Claude Code keeps its sign-in in the login Keychain, which cannot be isolated per account, so a session, cloud agent or Insights run on an account other than the primary one is refused there with a sentence that says to choose the primary account (once a primary account is recorded; with none recorded, sessions start as before). A Claude session on an inactive account (Make inactive on the Accounts page) is refused on every system, wherever it comes from, with a sentence that names the account and says how to switch the tab or make the account active again. The Accounts page (Accounts on the left rail, after Machines) lists every Claude Code and Codex account, one line each. Click a line to open it; one line is open at a time, and Escape closes it. An open line holds everything about its account: its name and colour, with Edit, which opens its editor (its name, colour and group, and Link another account to tie it to another of your accounts, Claude or Codex; Unlink undoes it); Linked with, naming the accounts it is linked to; its status, with Make active or Make inactive; Reviews, when it cannot run code reviews, and why; the tabs running on it; how its assistant signs in, with Sign in again for a Claude Code account or Check sign-in for a Codex account, and a Claude Code account's organisation when Claude Code records one that says more than its email; and its claude.ai or chatgpt.com sign-in, saying who it is signed in as and since when, with Sign in, Open my artifacts (claude.ai) and Sign out. While one account's claude.ai sign-in runs, every other line's claude.ai Sign in waits for it. The name, colour and group show on every linked account, and the colour on the account's chips everywhere. Each line's menu (its three dots) holds Sign in again now, Make reviewer and Remove for a Claude Code account, and Make default, Make reviewer, Sign out and, once the account is inactive, Archive for a Codex account. When an account cannot be made inactive, archived or removed because tabs use it, its line opens and names each of them with Go to. Add account is in the page's header, and in the middle of the page when there is no account yet. Settings, Accounts keeps what is not about one account: the Providers card, which account each provider's code reviews use, archived accounts with Restore, setups that did not finish (Resume or Discard), where claude.ai sign-in and the artifacts open, and Resuming sessions; the page links to it. @@ -180,7 +182,7 @@ Two settings in Settings, General, under Terminal, each carry their own kind of While Plain terminals through the session helper is on, a Terminal only tab on this computer and the partner terminal beside a session on this computer start inside the session helper, a small program installed with the app, instead of under the app itself. They work as before, and they keep running if the app crashes. When the app starts again it finds them at once, and a tab that comes back with the restored sessions shows its terminal again, with what it printed while the app was gone; nothing is typed into it again. When it printed more than the last 2 MiB the helper keeps, the tab first shows one line saying its earlier output is no longer held, then the last of its output that the tab can keep, and its program, if it is still running, is asked to draw its screen again. A held terminal no tab shows is listed on this page, and Re-attach opens a Terminal only tab on it. A held terminal waits two minutes for the app to come back, and then ends. While the app is still running but stops answering for a while (it froze), a held terminal does not end, one the app took over after a crash or an update included: once the app answers again, its tab shows it again with what it printed meanwhile. A terminal that a version before 2.1.3-beta.24 started is not kept this way. If a tab's held terminal was lost all the same, the tab starts it again on its own in its folder, at most once a minute, with a note above it saying so. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal starts again by itself: the session beside it is left as it is. Quitting the app normally ends every terminal the helper holds. On Windows an app update keeps them when you choose Save sessions on the update dialog: they keep running, and the new version shows each one again in its tab, or lists it on this page if no tab shows it, as after a crash. Close sessions ends them. The new version has the same two minutes, counted from when the old one closed, and while the update runs Re-attach is refused and says the app is being updated. On a Mac or Linux an update still ends them. Claude Code and Codex sessions are kept through an update only on Windows, with Claude Code and Codex sessions through the session helper on (below); any other one is not kept, and its tab resumes the conversation. SSH sessions and their partner terminals, a terminal run as administrator, and the tabs the app opens for a sign-in or to install or update a program do not start through it. Claude Code and Codex sessions have their own setting, below. The switch applies to terminals opened after the change; a terminal already open carries on as it started. Surviving a crash is promised on Windows for now: on a Mac or Linux a held terminal may not outlive the app until that has been checked there. Where Windows keeps the session helper inside the app's own job, the card says so, and held terminals then end with the app. The app runs the helper from its own copy in your user folder, checks that copy against the one installed with the app before each use, and makes it again once if it does not match; if it still does not match, the helper reads Failed and terminals start the usual way. -While Claude Code and Codex sessions through the session helper is on, a Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before: the same command, folder, account and settings. Its status line, hooks, the Conductor's tools, the resume list and the Watchdog work as they did, and on Windows a Codex session keeps its scrollback. With the HTTP Hooks Gateway switch on (Settings, Hooks), a Claude Code or Codex session the helper holds sends its hook events to the app through the session helper, the check before each tool runs (PreToolUse) included. The attention dot, the Watchdog and canvas notes work as before. With Claude Code and Codex sessions through the session helper off, which is the default, every session sends its hooks to the gateway as before. A Claude Code or Codex session the helper holds can also reach the Conductor's tools through the session helper. If the app's connection to the session helper drops and comes back, those tools keep working: a tool call made while the connection is down waits up to 30 seconds for the app, and if the app is not back by then, it gets the answer "AI Code Conductor is updating, try again shortly". A call the app was already answering when the connection dropped gets that answer at once and is not sent again, because a tool may not be safe to run twice. Such a session does not survive a crash yet. While the app is still running but stops answering for a while (it froze), such a session keeps running, one taken over after an update included, and its tab shows it again once the app answers. A session that a version before 2.1.3-beta.24 started is not kept this way: if it is lost, its tab only starts again. If a tab's session was lost all the same, the tab starts again on its own, at most once a minute, with a note above it saying so: a Claude Code session resumes the conversation it was on, or offers the resume list when the app does not know it, and a Codex session starts as its Restart starts it. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal that still runs is left running, its output still on screen. On Windows it does survive an app update, when its Conductor tools go through the helper and you choose Save sessions on the update dialog: the new version's restored tab takes over the same running session, with no resume and nothing typed into it. A Claude Code or Codex session is taken over only when its tab is still on the same account; if you pick another account for the tab, a new session starts on that account. A restored tab you have not opened yet keeps its session running until you open it or close it. While it waits, the session kept for it has its tool calls answered, its hook events reach the app at once (the tab's attention mark shows when it asks for approval, or about a minute after its turn ends, as on an open tab), and its status line keeps the tab's model, context and cost up to date; when you open the tab, the same session goes on and keeps its hook history. A kept session whose tab is not restored is ended after five minutes. A Codex session's hook events made during the update wait in the session helper and reach the app when the new version starts, as a Claude Code session's do. A Codex session that 2.1.3-beta.17 or earlier started still sends them the old way, at the update from that version and at any later update it is kept through: one made from the update until a few seconds after you press Resume, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. Open the tab to see it. When you open the app again after a crash, the session the helper held is ended and its tab resumes the conversation, as it would without the setting; a session a normal quit could not end in time is ended the same way at the next start. A tab never starts a second Claude Code or Codex on a conversation the helper still runs: it waits until the earlier one has ended. Quitting the app normally ends these sessions. On Windows, ending such a session, whether you close or restart its tab, end it on this page or quit the app, also ends every program it started, even one it opened in a window of its own. While this setting is on, an Insights report for a Claude Code account also runs inside the session helper: this page lists it as Insights report while it runs, with End, and a report the app could not end, after a crash for example, is ended at the next start. A Codex account's report runs as before. SSH sessions do not start through it. The switch applies to sessions started after the change; a session already open carries on as it started. +While Claude Code and Codex sessions through the session helper is on, a Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before: the same command, folder, account and settings. Its status line, hooks, the Conductor's tools, the resume list and the Watchdog work as they did, and on Windows a Codex session keeps its scrollback. With the HTTP Hooks Gateway switch on (Settings, Hooks), a Claude Code or Codex session the helper holds sends its hook events to the app through the session helper, the check before each tool runs (PreToolUse) included. The attention dot, the Watchdog and canvas notes work as before. With Claude Code and Codex sessions through the session helper off, which is the default, every session sends its hooks to the gateway as before. A Claude Code or Codex session the helper holds can also reach the Conductor's tools through the session helper. If the app's connection to the session helper drops and comes back, those tools keep working: a tool call made while the connection is down waits up to 30 seconds for the app, and if the app is not back by then, it gets the answer "AI Code Conductor is updating, try again shortly". A call the app was already answering when the connection dropped gets that answer at once and is not sent again, because a tool may not be safe to run twice. Such a session does not survive a crash yet. While the app is still running but stops answering for a while (it froze), such a session keeps running, one taken over after an update included, and its tab shows it again once the app answers. A session that a version before 2.1.3-beta.24 started is not kept this way: if it is lost, its tab only starts again. If a tab's session was lost all the same, the tab starts again on its own, at most once a minute, with a note above it saying so: a Claude Code session resumes the conversation it was on, or offers the resume list when the app does not know it, and a Codex session starts as its Restart starts it. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal that still runs is left running, its output still on screen. On Windows it does survive an app update, when its Conductor tools go through the helper and you choose Save sessions on the update dialog: the new version's restored tab takes over the same running session, with no resume and nothing typed into it. A Claude Code or Codex session is taken over only when its tab is still on the same account; if you pick another account for the tab, a new session starts on that account. A restored tab you have not opened yet keeps its session running until you open it or close it. While it waits, the session kept for it has its tool calls answered, its hook events reach the app at once (the tab's attention mark shows when it asks for approval, or about a minute after its turn ends, as on an open tab), and its status line keeps the tab's model, context and cost up to date; when you open the tab, the same session goes on and keeps its hook history. The new version reopens your tabs by itself, with nothing asked, once the pages it opens with are closed; a kept session whose tab is not restored within five minutes of it opening is ended. A Codex session's hook events made during the update wait in the session helper and reach the app when the new version starts, as a Claude Code session's do. A Codex session that 2.1.3-beta.17 or earlier started still sends them the old way, at the update from that version and at any later update it is kept through: one made from the update until a few seconds after the new version reopens your tabs, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. Open the tab to see it. When you open the app again after a crash, the session the helper held is ended and its tab resumes the conversation, as it would without the setting; a session a normal quit could not end in time is ended the same way at the next start. A tab never starts a second Claude Code or Codex on a conversation the helper still runs: it waits until the earlier one has ended. Quitting the app normally ends these sessions. On Windows, ending such a session, whether you close or restart its tab, end it on this page or quit the app, also ends every program it started, even one it opened in a window of its own. While this setting is on, an Insights report for a Claude Code account also runs inside the session helper: this page lists it as Insights report while it runs, with End, and a report the app could not end, after a crash for example, is ended at the next start. A Codex account's report runs as before. SSH sessions do not start through it. The switch applies to sessions started after the change; a session already open carries on as it started. Remote sessions through the session helper is a preview on Windows, off by default (Settings, General, under Terminal). On Windows the Machines page also lists the Linux machines you added, each with Check and Remove, whether the setting is on or off; a machine you add is used once the setting is on. Add a machine there (a Linux machine, x86-64 or arm64) from a saved SSH config that signs in by key or with its saved password: the app asks first, then uploads one file into the .aicc folder of your home folder on that machine (~/.aicc), checks its SHA-256 against the one installed with the app and runs a self-test. A Claude Code tab whose saved config signs in by key or with its saved password, with no container, to a checked machine, then runs through the session helper there: nothing is typed into the host's shell to set it up or start it, and a dropped connection comes back within two minutes with what you missed. An SSH Persistent tab (the default for a config that never chose a Connection) goes through the helper too. On a machine whose last Check read that logind does not end your processes when you log out, it is kept there until you end it: close it and choose Leave running, quit the app or update it, and the next start brings it back where it was, with its status line, the hook events it missed and its tools; End, in its tab's close question or on the Machines page, ends it. On a machine whose logind ends your processes when you log out, it is not kept (no re-attach; the machine's card says so, and so do the tab's SSH pill in its header and its config's SSH Persistent chip when you point at them): its session ends when you close the tab, quit the app or lose the connection, and its next start carries on with the conversation it was on, by that conversation's own id, never another tab's in the same folder; a tab with no message sent yet carries on with the newest conversation in its folder (see Known issues). On a machine whose logind gave the Check no answer (no loginctl there, or no logind), it keeps the usual SSH path, where tmux keeps it, and a Codex session there, which has no usual SSH path, goes through the helper not kept. A machine last checked by an older version of the app, which did not read logind, keeps such tabs on the usual SSH path until you press Check. A config with a session still under tmux (left running, or open in a tab) keeps the usual SSH path until that session is ended. The Machines page lists the sessions each machine keeps, with Re-attach and End, also while the setting is off. A Terminal only tab whose config signs in that way, and the partner terminal beside any SSH tab whose config signs in that way (on the machine itself, also for a config whose session runs in a container), are plain terminals with no assistant in them, and on a checked machine they run through the session helper as well, whatever their Connection, and are never kept: each is the machine's login shell, read with your rc files, in your home folder (a partner: in the session's folder, with nothing typed into it, or in your home folder when that folder is not on the machine, as on the usual SSH path), and it ends when you close it or quit. A Terminal only tab's post-connect command (an attach to a tmux session started elsewhere, for example) runs first in that login shell, carried to the machine in a variable of the session and never on a command line, and you are at an interactive shell when it ends or when you stop it with Ctrl-C; a machine whose login shell is not of the sh family (bash, zsh, sh, dash, ksh, mksh, ash or yash) keeps the usual SSH path for that tab, which types it at the first prompt as before. A Terminal only tab whose config runs in a container (its Runtime) enters that container as a step after its post-connect command, so it runs through the helper too, and when you leave the container a line says you are back on the machine, outside the container, and you are at your shell there; a config whose container name or folder the app does not accept keeps the usual SSH path, which refuses it and says why. The post-connect command of a Claude Code or Codex session runs through the helper too, as a step before the assistant starts: it runs first in the login shell, in your home folder, as the usual path types it there, and the assistant then starts in the session's folder with what the command exported (an activated environment or a PATH it set, for example), with no Run post-connect command? question and no launch anyway? question. Where the command fails or you stop it with Ctrl-C, the assistant is not started: the tab says why in one line and leaves you at your shell on the machine, and Restart tries again. A command that can fail for a harmless reason should end with ; true, so the assistant starts all the same (see Known issues). A login shell outside the sh family keeps the usual SSH path, as for a Terminal only tab. So does a command that opens a shell or a session of its own (su, sudo -i, ssh to another machine, a tmux or screen attach, a container's or a development environment's shell, exec), because the usual SSH path starts Claude Code inside that shell, where the helper would start it only once that shell ends; a Codex session with such a command starts nothing and says what to change. Every other SSH tab, and every new tab while the setting is off, runs the usual way: not through the helper yet are Claude Code and Codex sessions in a container (the assistant would run inside the container, where the helper is not), and macOS and Windows hosts. A sudo a post-connect command calls by that name, for any of these tabs, is answered with the config's saved sudo password through the helper: the app gives it once for each start of the tab, over the session's own connection, never typed into the terminal or shown, and only before the assistant starts; the container's own sudo (The container engine needs sudo, in Runtime) is answered the same way. A sudo that asks after that answer (a wrong saved password, or a second sudo on a machine set to ask for every one) asks in the terminal, where you type the password as on the usual SSH path. A config that saves a sudo password while its command calls no sudo by that name (its sudo is inside a script the command runs, or called by its full path (/usr/bin/sudo)) keeps the usual SSH path, which types the saved password at sudo's prompt; a Codex session, and an SSH Persistent session the helper keeps, go through the helper all the same, and that sudo asks in the terminal. With no saved sudo password, sudo asks in the terminal as before. A config that keeps a password signs in with it through the helper too: the app answers ssh's own password prompt for that machine, once for each connection, and only on a host key this computer already knows (open an SSH tab to it once with the setting off, to accept its key). It keeps the usual SSH path (a Codex config starts nothing) where the app cannot do that: the app's folder has a letter outside plain ASCII in its name and Windows keeps no plain short name for it, or this computer's ssh is older than OpenSSH 8.4. A password the machine refused is not sent again, and nothing is asked for that machine, until you correct it in the config or press Check. A key with a passphrase, or a password for a machine none of whose configs keeps a saved password the app can use, is asked for in a dialog when you press Add, Check or Remove on the Machines page or open a tab there; tick Keep to have the app hold it in memory for the rest of the run, so a reconnect can use it. A Codex config runs through the helper only (see Codex: sessions and accounts). A tab through the helper has its status line, its hooks (the attention mark, the canvas turn boundary, the Watchdog) and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) through the helper too. The session's own settings (your Claude Code settings on that machine, with the helper there for the status line and hooks) go into the .aicc folder on that machine and are removed when its session ends (quitting the app does not wait for that, so the next Check on the Machines page removes any that a quit or a dropped connection left, up to 1024 at one Check with any more at the next, and its message says how many sessions' files it removed and their size); no address or token of this computer is sent to the host. After a dropped connection, the hook events and the newest status line it missed arrive once it is back. Its status line names the account Claude Code is signed in as on that machine (read at each start from one field of Claude Code's config file there, never the whole file) and, when this computer holds that account, shows the usage reading this computer holds of it, never read on the host: the account counts as in use on the Accounts page, and its reading there is the 5-hour and weekly figures the tab reports, so the weekly limits by model and the extra usage show until the tab first reports, and the limits by model after that only while a Claude Code session on this computer runs on the same account; otherwise it says Model limits: not available, and its tooltip gives the reason (this machine uses its own sign-in, or this computer has no usage reading of the account yet), and when Claude Code on that machine names no account the header says Account not available. Prompt buttons and broadcast type into it as into any Claude Code tab. A tab whose Connection is SSH ends its session when you close it or quit. Restart of a Claude Code tab through the helper, and its restore when the app starts again, carry on with that tab's own conversation, by its id, never another tab's in the same folder; a tab with no message sent yet carries on with the newest conversation in its folder there. Linux x86-64 or arm64 hosts (an arm64 Raspberry Pi included; 32-bit Arm is not taken) with sha256sum, shasum or openssl only. Remove takes the helper away; it is refused while a tab runs there or a session is kept there (End it first). After an app update that changes the session helper, each added Linux machine reads not checked until you press Check on the Machines page; Check installs the new helper there and removes each earlier copy of the session helper there that no session kept there still uses, and its message says how many it removed and their size, and how many it kept. A copy a kept session may still use stays until a Check after that session ends. Earlier copies, and the files a quit or a dropped connection left, are removed only by a Check you press (or by Remove, which takes everything), over the connection that Check already made: the app never connects to a machine just to remove them, listing a machine's sessions (at the app's start, or when the Machines page opens) removes none of them, and a machine it cannot reach keeps them until its next Check. @@ -538,7 +540,7 @@ With Claude Code and Codex sessions through the session helper on, a Claude Code On Windows, with Claude Code and Codex sessions through the session helper on, ending such a session ends every program it started, even one it opened in a window of its own (a server started with Start-Process, for example). That happens when you close or restart its tab, end it on the Machines page or quit the app, and when the app ends it after a crash. Without the setting, such a program may keep running after its tab closes. Workaround: start a program that must keep running in a terminal outside that session, or switch the setting off before you start the sessions that start such programs. -On Windows, with Claude Code and Codex sessions through the session helper on, a Codex session that 2.1.3-beta.17 or earlier started, and that an app update keeps running, still sends its hook events the old way, at that update and at any later update it is kept through. A hook event it makes from the update until a few seconds after you press Resume, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. A Codex session started on 2.1.3-beta.18 or later keeps those events in the session helper and they reach the app after the update. Workaround: open the tab after the update to see where the session is, or start a new Codex session on this version. +On Windows, with Claude Code and Codex sessions through the session helper on, a Codex session that 2.1.3-beta.17 or earlier started, and that an app update keeps running, still sends its hook events the old way, at that update and at any later update it is kept through. A hook event it makes from the update until a few seconds after the new version reopens your tabs, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. A Codex session started on 2.1.3-beta.18 or later keeps those events in the session helper and they reach the app after the update. Workaround: open the tab after the update to see where the session is, or start a new Codex session on this version. Restart Claude Code on a machine (preview, through the session helper): the one-click offer shows only for Claude Code, whose screen says Update installed and restart to apply once it has updated itself there. Codex says an update is available and asks for it to be installed first, which a restart does not do. Workaround: install the Codex update on that machine yourself, then choose Restart Codex in the status strip's Restart menu. The versions on a machine's card are the ones its last Check found, so after an update press Check to see the new one. A tab that takes the usual SSH path, not the session helper, has no such menu: its Restart works as before. diff --git a/tests/unit/shared/app-knowledge.test.ts b/tests/unit/shared/app-knowledge.test.ts index 32dc98316..8f5c09977 100644 --- a/tests/unit/shared/app-knowledge.test.ts +++ b/tests/unit/shared/app-knowledge.test.ts @@ -2300,8 +2300,12 @@ describe('the 2.1.3-beta.8 sweep', () => { // Agent sessions the helper holds end after a crash (#713); since // 2.1.3-beta.17 B1 (aicc_planning#412) Save sessions keeps them on Windows. expect(machines).toContain('A Claude Code or Codex session has **End** only. After a crash it is ended') - expect(machines).toContain('On Windows, **Save sessions** at an update keeps it running: resume your sessions within five minutes of the new version opening') - expect(t.variants.primary.body).toContain('a Claude Code or Codex session is kept the same way: resume your sessions within **five minutes**') + // aicc_planning#515: after an update with Save sessions the new version + // reopens the tabs by itself (no Resume to press), still within five minutes. + expect(machines).toContain('On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once the pages it opens with are closed, and within five minutes of it opening') + expect(t.variants.primary.body).toContain('a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing to answer') + expect(t.variants.primary.body).toContain('Close them within **five minutes** of it opening') + expect([machines, t.variants.primary.body].join(' ')).not.toMatch(/resume your sessions within/) expect(step('settings').highlights.join('\n')).toContain('or through an update when you choose **Save sessions**') // Combined Mode reads the same for either assistant, so it names no provider. expect(step('combined-mode').highlights.join('\n')).toContain('On Windows it also keeps running through an app update when you choose **Save sessions**') From a133930c47fe67d376db10b629698cb9e4f5ca47 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:24:38 +0000 Subject: [PATCH 31/79] chore(wp1): refresh the legacy Codex manifest and ledger for #514 and #515 Two new files name Codex in their comments only: closeDialogText.ts (the close and update dialogs' lines) and update-keep.ts (the update dialog's query and its parsers). Both are recorded as added, with their tests; no other entry's predicates moved. The ledger is complete in the candidate phase. Co-Authored-By: Claude Opus 5.5 --- docs/wp1/legacy-codex-manifest.json | 34 ++++++++++++++++++++--------- tests/wp1/legacy-codex-ledger.json | 24 ++++++++++++++++++-- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/docs/wp1/legacy-codex-manifest.json b/docs/wp1/legacy-codex-manifest.json index 33f615377..55976e5c5 100644 --- a/docs/wp1/legacy-codex-manifest.json +++ b/docs/wp1/legacy-codex-manifest.json @@ -1,8 +1,8 @@ { "schema": "wp1-legacy-codex-manifest/3", - "generatedAt": "2026-12-03T20:05:11.321Z", - "head": "24b5a8e91bfcb3bc40cab91d78753b8ace8007ca", - "tree": "b262ccbc44e14aa955b663afd798b7864eeb2452", + "generatedAt": "2026-12-04T00:23:35.978Z", + "head": "59a84c6c1a9fcf4db8b7d701602f73ca0bae2229", + "tree": "7fc9fdfdec4fd73b2fbfb2a24bb7ba6c3fc3ec2a", "scannedWorkingTree": false, "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "predicates": [ @@ -116,9 +116,9 @@ "\\.(png|jpg|jpeg|gif|ico|icns|webp|svg|woff2?|ttf|otf|mp4|zip|asar|node|exe|dll|dylib|so|pdf)$", "^package-lock\\.json$" ], - "trackedFileCount": 4326, + "trackedFileCount": 4332, "excludedFileCount": 725, - "scannedFileCount": 3601, + "scannedFileCount": 3607, "unscopedFileCount": 15, "unscoped": [ ".claude/settings.json", @@ -139,8 +139,8 @@ ], "unscopedMentions": [], "unreadable": [], - "matchedPathCount": 1290, - "pathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", + "matchedPathCount": 1292, + "pathDigest": "c20e8d8780f5975319653947156bc8d22151ba1d4b2e1be6feee208cdffd42f9", "entries": [ { "path": ".github/workflows/ci.yml", @@ -4093,6 +4093,13 @@ ], "lineCount": 29 }, + { + "path": "src/renderer/utils/closeDialogText.ts", + "predicates": [ + "P11" + ], + "lineCount": 1 + }, { "path": "src/renderer/utils/heldTerminalLost.ts", "predicates": [ @@ -4183,7 +4190,7 @@ "P12", "P14" ], - "lineCount": 220 + "lineCount": 222 }, { "path": "src/shared/ask-conductor-provider.ts", @@ -4364,6 +4371,13 @@ ], "lineCount": 60 }, + { + "path": "src/shared/update-keep.ts", + "predicates": [ + "P14" + ], + "lineCount": 1 + }, { "path": "tests/e2e/cloud-agents.spec.ts", "predicates": [ @@ -7034,7 +7048,7 @@ "predicates": [ "P13" ], - "lineCount": 32 + "lineCount": 33 }, { "path": "tests/unit/main/session-helper-update-keep.test.ts", @@ -9445,7 +9459,7 @@ "P07", "P13" ], - "lineCount": 44 + "lineCount": 45 }, { "path": "tests/unit/renderer/session-persistence-resume.test.ts", diff --git a/tests/wp1/legacy-codex-ledger.json b/tests/wp1/legacy-codex-ledger.json index 069185255..34ce0f1a8 100644 --- a/tests/wp1/legacy-codex-ledger.json +++ b/tests/wp1/legacy-codex-ledger.json @@ -1,8 +1,8 @@ { "schema": "wp1-legacy-codex-ledger/2", "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", - "manifestPathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", - "manifestHead": "24b5a8e91bfcb3bc40cab91d78753b8ace8007ca", + "manifestPathDigest": "c20e8d8780f5975319653947156bc8d22151ba1d4b2e1be6feee208cdffd42f9", + "manifestHead": "59a84c6c1a9fcf4db8b7d701602f73ca0bae2229", "dispositions": { "retain": "unchanged observable behaviour, characterization proof", "move": "moved behind a package boundary and/or adapted at the call site, regression proof (newPath when relocated)", @@ -6039,6 +6039,16 @@ "evidence": "WP2 commit 6f: the Codex introduction's one-time takeover takes the last turn in the boot chain, after every gate and the due waits (WP1.34, WP1.6); tests/unit/renderer/boot-gates.test.ts; tests/unit/renderer/hello-codex.acceptance.test.ts; WP2 commit 6f review round 1: bootChain, App's whole decision, so the takeover's two answers are tested as App uses them (WP1.34); tests/unit/renderer/hello-codex.acceptance.test.ts; WP2 reconfirm (owner decision 2026-09-26): the one-time Codex question takes its turn after the release notes and the upgrade harness, before the rest (WP1.34); tests/unit/renderer/codex-reconfirm-gate.test.ts, tests/unit/renderer/boot-gates.test.ts; WP2 PR 4 (59dd48c7): changed by those commits (WP1.34); tests/unit/renderer/boot-gates.test.ts", "note": "" }, + { + "path": "src/renderer/utils/closeDialogText.ts", + "predicates": [ + "P11" + ], + "category": "UI-ONLY", + "disposition": "added", + "evidence": "2.1.3-beta.28 (aicc_planning#514) module (src/renderer/utils/closeDialogText.ts): the close and update dialogs say what each choice does to the tabs open, with counts; its comment names the Claude Code and Codex tabs as the agent sessions that restart and pick up their conversations; text only, no provider name compared, no Codex code path (WP1.68); tests/unit/renderer/close-dialog-text.test.ts, tests/unit/renderer/close-dialogs-tokens.test.tsx", + "note": "created by 2.1.3-beta.28 aicc_planning#514; pure" + }, { "path": "src/renderer/utils/heldTerminalLost.ts", "predicates": [ @@ -6430,6 +6440,16 @@ "evidence": "type-level; binding types exercised by tests/wp1/launch-handoff.test.ts (WP1.42); WP2 provider-off enforcement (main refuses every launch of a provider that is off; WP1.60 enable/disable): TerminalOptions.noCommandSecrets for the install tab; tests/unit/main/install-tab-command-secrets.test.ts; WP2 P3 usage track MP2: StatuslineData gains rateLimitsAt and usageUnavailable, set by the rollout telemetry (WP1.68); tests/unit/providers/codex/telemetry.test.ts; WP2 P3 usage track MP9 (owner decision 2026-09-26, Q1.4 and Q1.10/U3: Codex attributed from the realm folder, ~/.codex as this computer's sign-in): the session row's account key, the provider and account filter, and the attribution progress (WP1.2); tests/unit/tokenomics/tokenomics2-handlers.test.ts; WP2 P3 usage track MP11 (owner decision 2026-09-26, Q1.4: unpriced models read \"no price\", not $0; each KPI and the cost chart split by provider): the same Tokenomics types for the renderer (WP1.39); tests/unit/renderer/tokenomics-t19-components.test.tsx; WP2 P3 usage track MP12 (owner decisions 2026-09-26, Q1.4 and Q1.5; the approved canvas \"Tokenomics with two providers\", option A): the same for the renderer (WP1.39); tests/unit/renderer/tokenomics-mp12.test.tsx; WP2 P3 usage track MP11 round 1 (review fixes) and the MP9 lens B nits: the same for the renderer (WP1.39); tests/unit/renderer/tokenomics-mp12.test.tsx; WP2 P3 usage track MP9 (VM final pass, defect 4 follow-up): stage 1 of the account re-read says it is counting its files until they are counted, in the progress the page reads (WP1.2); tests/unit/renderer/tokenomics-mp12.test.tsx; WP2 PR 3 P3.8 (row 40): CodexOptions' effort gains max and ultra; a model is any registry Codex model or a saved one (WP1.68); tests/unit/main/codex-effort-allowlist.test.ts; WP2 PR 3 P3.8 round 1 (row 69): CodexOptions' preset gains plan (WP1.68); tests/unit/main/codex-effort-allowlist.test.ts; WP2 PR 3 P3.11 (row 62, extra CLI arguments; parity) (WP1.68): CodexOptions gains extraArgs; tests/unit/main/codex-extra-args-guard.test.ts; WP2 PR 3 P3.11 round 1 (ADR-009 pass 1, spec and quality findings) (WP1.68): the CodexOptions.extraArgs comment; tests/unit/main/codex-extra-args-guard.test.ts; WP2 PR 3 P3.12 (rows 31, 32, 65; logs and GitHub context; parity) (WP1.68): CodexOptions.loggingEnabled; tests/unit/main/codex-logging-optout-spawn.test.ts; WP2 PR 3 P3.16a main track (WP1.68): the saved running-time entry type names gapMs (type only); tests/unit/main/conversation-running-time.test.ts; WP2 PR 4 S0 and P4.5: the shapes of the PR 4 channels, a provider on the Cloud Agent and Insights records, the Cloud Agent dispatch and retry shapes (WP1.42); tests/unit/pr4-scaffold-bridges.test.ts, tests/unit/main/cloud-agent-dispatch-ipc.test.ts; WP2 PR 4 P4.1 (row 51; dd869a08): the canvas guidance reason skills-not-staged (WP1.68); tests/unit/main/canvas-codex-launch-wiring.test.ts, tests/unit/renderer/codex-canvas-notices.test.tsx; WP2 PR 4 VM checkpoint fixes (aa581eda), review fixes (758cb407): changed by those fixes (WP1.68); tests/unit/renderer/codex-canvas-notices.test.tsx; WP2 PR 4 (c1c34f1f): changed by those commits (WP1.68); tests/unit/renderer/codex-canvas-notices.test.tsx; WP2 PR 4 owner answers (2026-10-04) (integration round 3, lane B's patch): CanvasSessionGuidance is full or tools-only with reason own-skill or skills-not-staged and the skills it names; option A's reasons and the picker record gone (WP1.68); tests/unit/main/canvas-session-guidance-ipc.test.ts, tests/unit/renderer/codex-canvas-notices.test.tsx", "note": "binding/identity types added; CodexOptions retained" }, + { + "path": "src/shared/update-keep.ts", + "predicates": [ + "P14" + ], + "category": "OTHER", + "disposition": "added", + "evidence": "2.1.3-beta.28 (aicc_planning#514) module (src/shared/update-keep.ts): the update dialog's update:sessionsKept question (open local tab ids, agent sessions and Terminal only tabs) and answer (two counts), with the parsers each side reads the other's message through; its comment names a Claude Code or Codex session's tab as an agent tab; no provider name compared, no Codex code path (WP1.68); tests/unit/shared/update-keep.test.ts, tests/unit/main/update-handlers.test.ts", + "note": "created by 2.1.3-beta.28 aicc_planning#514; pure" + }, { "path": "tests/e2e/cloud-agents.spec.ts", "predicates": [ From 28b606abaca2bb7defe6f2f9ceba929cd7a0b8d6 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:31:52 +0000 Subject: [PATCH 32/79] test(pty): keep the review's probe of the side-by-side holds' trade Round 5 on aicc_planning#513 step 2. The review found that running the holds side by side costs a tab its scripts when the check ends after the tab's own 5 s but before the holds, one after another as on 591eb8fb, would have ended: pty-manager reads the scripts at the spawn, and that time is the saving. The orchestrator accepted the trade. The probe, kept as a test: a check begun 3 s before the ask and ended 5.2 s after it, beside a 1.3 s session folders' hold and a 0.4 s look. The spawn runs 5 s after the ask with the resume list's script not there. It is red with the holds one after another (5.4 s, the script ready), on 591eb8fb's pty-handlers.ts and script-folders.ts (5.4 s), and, with its spawn-time and log checks taken out, on what it finds at the spawn alone. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- .../main/pty-spawn-holds-side-by-side.test.ts | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index 74513451d..c84799a75 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -15,7 +15,10 @@ * which a tab asked late into a slow check would start without its status * line for the session's whole life; * - the holds it was held for run side by side, so it waits for the longest - * of them, not their sum; + * of them, not their sum. The trade, decided: pty-manager reads the + * scripts at the spawn, so a check that ends past the launch's own bound, + * in the time the other holds took one after another before #513, no + * longer reaches it; * - a sign-in tab is not held for the scripts folders, whose scripts it never * runs; * - the session folders have one bound for the whole launch @@ -289,6 +292,45 @@ describe('the scripts folders\' check, when it does not come in its usual time ( ]) }) + // The trade decided in #513 (CONTEXT.d/2026-12-03-b28-snap-d1-holds.md): + // pty-manager reads the scripts at the spawn, not when the hold ends. + // Before #513 a launch whose own 5 s ran out still had the other holds, + // one after another, before its spawn, and a check that ended in that + // time reached it by chance. Side by side, that time is the saving, and a + // check that ends in it no longer reaches the launch: it starts without + // its scripts, as one past its 5 s always could. Mutation to prove this + // can fail: await the holds one after another, as before #513 (the spawn + // then runs 5.4 s after the ask, with the script there to run). + it('a check that ends 5.2 s after the ask, past the tab\'s own 5 s but before the other holds one after another would have ended: the tab starts at its 5 s, without its scripts (the trade decided in #513)', async () => { + let answer = (): void => {} + const res = resourcesFolder() + const checked = secureScriptFolders(res, (dirs) => new Promise((resolve) => { + answer = () => resolve(dirs.map((d) => { nodeFs.mkdirSync(d, { recursive: true, mode: 0o700 }); return { dir: d, ok: true } })) + })) + const script = join(res, 'scripts', 'resume-picker.js') + atSpawn.probe = () => checkDeployedScript(script) + await after(3000) + HOLDS["the session folders' owner-only step"](1300) + HOLDS["the start's look for Claude Code"](400) + const asked = performance.now() + const started = outcome(spawn({}, S, CLAUDE_TAB)) + await after(SCRIPT_FOLDERS_LAUNCH_WAIT_MS + 200) + answer() + await checked + nodeFs.writeFileSync(script, '// the app\'s\n', { mode: 0o600 }) + scriptFoldersDeployed() + await after(200) + expect(await asItStands(started)).toBe('started') + expect(spawned, 'started at its own 5 s, not once the other holds would have ended one after another').toEqual([{ sid: S, at: asked + SCRIPT_FOLDERS_LAUNCH_WAIT_MS }]) + expect(atSpawn.seen, 'the script is not there to run at its spawn: the check had not ended').toEqual([{ ok: false, absent: true }]) + expect(checkDeployedScript(script), 'by the time the holds one after another would have ended, it is').toEqual({ ok: true }) + expect(logged.filter((l) => l.startsWith('[spawn]'))).toEqual([ + `[spawn] Session ${S}: held 400 ms for the start's look for Claude Code (still pending when the wait ended)`, + `[spawn] Session ${S}: held 1300 ms for the session folders' owner-only step (no longer pending)`, + `[spawn] Session ${S}: held ${SCRIPT_FOLDERS_LAUNCH_WAIT_MS} ms for the scripts folders' check (still pending when the wait ended)`, + ]) + }) + // What the hold is for is kept: a check that comes in its usual time is // waited for. Mutation to prove this can fail: never hold for the check. it('a check that answers in its usual time is still waited for, and the tab starts once it and the deploys have run', async () => { From 4fab9571991e670e2d1bff0ff4cb1768ab93b2c5 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:31:52 +0000 Subject: [PATCH 33/79] docs(pty): say what the side-by-side holds cost a check past a launch's bound Round 5 on aicc_planning#513 step 2. The holds comment (pty-handlers.ts) and the SCRIPT_FOLDERS_LAUNCH_WAIT_MS doc (script-folders.ts) now say the trade the orchestrator accepted: pty-manager reads the scripts at the spawn, so a check that ends past a launch's own bound reaches it only if something else still holds it then. One after another, the other holds gave such a check their sum to end in; side by side, only what the longest runs past the bound. No code changes. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- src/main/ipc/pty-handlers.ts | 30 +++++++++++++++++++----------- src/main/script-folders.ts | 10 ++++++++-- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index e58c4fccb..5118c07fe 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -1263,17 +1263,25 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // of its own that none of the others reads or writes (the scripts // folders, the start's profile steps, the start's look for Claude Code, // the spawn's folders, the look for gsudo.exe). One after another, a - // first tab at start paid every bound in turn. The start's look and the - // launch's own walk of PATH stay one after the other (the start can - // bring PATH up to date, and the walk is for the PATH it leaves). What - // can have changed while they ran is asked again below, once all of - // them are over (the spawn's folders, the walk of PATH). Each is timed - // (heldFor). The scripts folders come before a Codex launch's own wait - // for its hook folders below: the start wires those only after the - // scripts folders' check and the deploys (index.ts). When the scripts - // wait saw them end, the hook folders' wait covers its own work alone; - // when it ran out its bound first, the hook folders' wait, bounded from - // its own call, covers what is left of the check and the deploys too. + // first tab at start paid every bound in turn. The price, decided in + // #513 (CONTEXT.d/2026-12-03-b28-snap-d1-holds.md): pty-manager reads + // the scripts at the spawn, not when their wait ends. One after + // another, the other holds came after a scripts wait that ran out its + // bound, and a check that ended while they ran still reached the + // launch. Side by side, that time is the saving: a check that ends in + // it no longer reaches the launch, which starts without its scripts + // unless the hook folders' wait below covers it. + // The start's look and the launch's own walk of PATH stay one after the + // other (the start can bring PATH up to date, and the walk is for the + // PATH it leaves). What can have changed while they ran is asked again + // below, once all of them are over (the spawn's folders, the walk of + // PATH). Each is timed (heldFor). The scripts folders come before a + // Codex launch's own wait for its hook folders below: the start wires + // those only after the scripts folders' check and the deploys + // (index.ts). When the scripts wait saw them end, the hook folders' wait + // covers its own work alone; when it ran out its bound first, the hook + // folders' wait, bounded from its own call, covers what is left of the + // check and the deploys too. // // The session folders have one bound for the whole launch, // SPAWN_FOLDERS_WAIT_MS across every wait it makes for them (its hold diff --git a/src/main/script-folders.ts b/src/main/script-folders.ts index c407c5dab..d143cb174 100644 --- a/src/main/script-folders.ts +++ b/src/main/script-folders.ts @@ -82,8 +82,14 @@ function noRead(a: Asked | undefined): boolean { * from the check's start: aicc_planning#513 tried one and dropped it, since * a tab asked late into a slow check would then start without the app's * status line for the session's whole life, a bigger cost than the wait it - * saved. As main saw the check, it took 1.0 to 1.6 s in every later app on - * a runner, 2.6 to 3.5 s with the disk cache purged, and 8.8 to 13.6 s in a + * saved. Past this bound the launch no longer waits for the check: one that + * ends later reaches it only if something else still holds the launch then + * (pty-manager reads the scripts at the spawn). Before #513 the other holds + * came after this wait, one after another, so such a check had their sum to + * end in; side by side it has only what the longest of them runs past this + * bound, a trade #513 decided (CONTEXT.d/2026-12-03-b28-snap-d1-holds.md). + * As main saw the check, it took 1.0 to 1.6 s in every later app on a + * runner, 2.6 to 3.5 s with the disk cache purged, and 8.8 to 13.6 s in a * runner's first app, whose first Windows PowerShell starts cold * (CONTEXT.d/2026-11-27-b20-snap-d1.md). */ export const SCRIPT_FOLDERS_LAUNCH_WAIT_MS = 5000 From bd586c155b3d15d1a84943ccf9152a57f06eaa62 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:31:52 +0000 Subject: [PATCH 34/79] docs(context): record the Snap D1 side-by-side holds' accepted trade Round 5 on aicc_planning#513 step 2. The entry no longer says the branch keeps every tab's scripts as 591eb8fb did. - Decided: the orchestrator's acceptance of the trade, with the window's bounds (from when the side-by-side holds end to where the holds one after another would have ended), its width (the saving: up to about 0.4 s in the evidence, up to about 1.4 s where the session folders' work runs), why no measured check ended in it, the review's probe numbers, and why it was accepted. - What this step changes, the Fix bullet and Who meets it now say that a check ending in the time saved no longer reaches the tab. - User-facing surfaces: the trade is a case the known issue already describes, and its workaround covers it. - Tests: the probe kept as a test and its mutant runs. Refs aicc_planning#513 Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 94 ++++++++++++++++++++--- 1 file changed, 83 insertions(+), 11 deletions(-) diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md index 56144cf33..5f8c0ab0a 100644 --- a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -8,8 +8,12 @@ before this entry; this is step 2, the fix at the cause, and its review rounds. A first tab's holds now run side by side, so it waits for the longest of them, not their sum. Its wait for the scripts folders' check is as on -591eb8fb: up to 5 s from its own ask. This step does not remove the D1 red, -and #513 stays open. +591eb8fb: up to 5 s from its own ask. What follows a wait that ran out is +not: pty-manager reads the scripts at the spawn, and the spawn now comes +sooner. A check that ends in the time saved gave the tab its scripts on +591eb8fb, by chance, and now does not (a Codex launch's later wait for its +hook folders aside): the tab starts without them. That trade is decided +below. This step does not remove the D1 red, and #513 stays open. - Expected saving, not measured: in the evidence below the tab waited its full 5 s for the scripts check, then 0.4 to 0.5 s more. Only the part of @@ -17,7 +21,8 @@ and #513 stays open. PATH asked again after the holds (one after the other by design), are not. So the first tab is expected to spawn up to about 0.4 s sooner here. Where several holds each take long (the session folders' work took 1.15 to - 1.36 s under load on CI), the saving is the sum less the longest. + 1.36 s under load on CI), the saving is the sum less the longest. The time + saved is also the trade's window (decided below). - What will measure it: the next Snap e2e dispatch of this head writes one `[spawn] Session : held N ms for (...)` line per hold that took 1 s or more or ended still pending, and `readings.promptSeenAt`. Record the @@ -75,9 +80,16 @@ one opened in the first seconds). Where Windows PowerShell is warm the check took 1.0 to 1.6 s on the runner (2.6 to 3.5 s with the disk cache purged); the tab waits that long and gets its status line and resume list. A check that ends within 5 s of a tab's ask is waited for, and the tab gets them; one that -ends later costs that tab 5 s, and it starts without them: a Claude Code tab -with no status line of the app's for the session's whole life, and the direct -line, not the resume list. A Codex launch then waits for its hook folders, +ends later costs that tab 5 s, and, unless another of its holds still holds +it then, it starts without them: a Claude Code tab with no status line of the +app's for the session's whole life, and the direct line, not the resume list. +On 591eb8fb such a tab still waited for its other holds, one after another, +before its spawn, and a check that ended in that time gave it its scripts by +chance. With this branch a check that ends there costs the tab them too: the +trade decided below, as wide as the time saved (up to about 0.4 s in the +evidence). It meets a tab whose check ends just past the tab's own 5 s, as +with a check of 8.2 s and the tab asked 3 s into it (the probe below); no +measured check ended there. A Codex launch then waits for its hook folders, only while the Hooks gateway listens. The start wires those only after the check and the deploys, so that wait (5 s, from its own call) usually brings its scripts back. Without the gateway it starts without the Codex resume list @@ -93,7 +105,10 @@ too. A tab asked for once the check is over waits for nothing. the same tick (the one-at-a-time rule relies on that). - The scripts folders' hold is one of them, bounded as on 591eb8fb: 5 s from each launch's own ask. Round 2 had counted it from the check's start, one - deadline for the run; round 3 dropped that (decided below). + deadline for the run; round 3 dropped that (decided below). The time after + a wait that ran out is not as on 591eb8fb: the other holds no longer come + after it, and a check that ended while they ran no longer reaches the tab + (the trade, decided below). - A sign-in tab is not held for the scripts. Its line runs none of them, as the code shows: pty-manager's shell-only branch types `localSignInLine` (local-sign-in-tab.ts), which is `buildClaudeSignInLine` @@ -139,8 +154,10 @@ User-facing surfaces: the known issue "A tab restored at start opened without the status line or the resume list" (src/shared/app-knowledge.ts) needs nothing. With the deadline dropped, a session that starts while the check runs waits up to 5 seconds from its own start for it, which is what the entry -says, and its workaround stands. The side-by-side holds only shorten a first -tab's wait, and the `[spawn]` lines are log only. No tip, tour card or README +says, and its workaround stands. The side-by-side holds shorten a first tab's +wait. Their trade (decided below) is a case the entry already describes, a +check that takes longer than a session's 5 seconds, and its workaround brings +the scripts back. The `[spawn]` lines are log only. No tip, tour card or README text names these holds. ### Decided, and still open @@ -155,20 +172,69 @@ session's whole life, and without the resume list. That costs more than up to about 2.5 s of wait on a slow cold start, and the side-by-side holds already keep the holds from adding up. +Decided by the orchestrator in round 5 (2026-12-04), with the owner away, on +the review's finding that the side-by-side holds cost some tabs their +scripts: the holds stay side by side, and that trade is accepted. So this +branch does not keep every tab's scripts as 591eb8fb did. + +- The trade. pty-manager reads the scripts at the spawn, not when the + scripts wait ends. On 591eb8fb a tab whose 5 s ran out still waited for its + other holds, one after another, before its spawn, and a check that ended + in that time gave it its scripts by chance. Side by side, that time is the + saving, and a check that ends in it now costs a Claude Code tab the app's + status line for the session's whole life, and the resume list (it gets the + direct line). A Codex launch's wait for its hook folders still comes after + the holds and, while the Hooks gateway listens, can still cover it. +- The window's bounds. It opens when the tab's side-by-side holds end: its + own 5 s from the ask where the scripts wait is the longest of them, as in + the evidence. It closes where the same holds one after another would have + ended. Its width is the saving, exactly: up to about 0.4 s in the evidence + (the part of the 0.4 to 0.5 s after the scripts wait that was other holds; + not split), up to about 1.4 s where the session folders' work runs after + the scripts wait (1.15 to 1.36 s under load on CI), and more only where + the other holds run longer (the saving grows with it). +- No measured check ended in it. Both evidence runs held their tab one hold + after another and still started it without its scripts, so neither check, + with its deploys, had ended by the spawn, 5.4 to 5.5 s after the submit: + past the window's end. On a runner's first app the check takes 8.8 to + 13.6 s (2026-11-27-b20-snap-d1.md) and the tab is asked about 3 s after + main starts, so the check ends about 5.8 s or more after the ask. Where + Windows PowerShell is warm it took 1.0 to 1.6 s (2.6 to 3.5 s with the disk + cache purged): inside the tab's 5 s, and waited for. +- The recheck's probe (round 5's review, on the holds test's harness): a + check begun 3 s before the ask and ended 5.2 s after it, beside a 1.3 s + session folders' hold and a 0.4 s look for Claude Code. On 83a90ab0 the + spawn ran 5000 ms after the ask with the resume list's script not ready + (`checkDeployedScript` ok=false); with the holds one after another, as on + 591eb8fb, it ran 5400 ms after the ask with the script ready (ok=true). + This round keeps it as a test (below). +- Why accepted. A first tab must wait for its slowest hold, not their sum: + one after another the holds' bounds add up (5 s for the scripts, 15 s for + the start's look for Claude Code, 10 s for the session folders, each from + its own call), and a slow first start paid them in turn. The window is the + same time as the saving, so getting it back means waiting as long as + before; the nearest other order (the scripts wait first, the other holds + side by side after it) narrows the window only by giving back as much of + the saving. No measured check ended in it, and a check that ends past it + was lost on 591eb8fb too. + Still open, an owner decision: the runner's cold Windows PowerShell share of D1. A warm-up step before the Snap step would change what D1 measures; TAB_MS stays. #513 stays open on this. ### Tests -- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 16): the real +- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 17): the real pty:spawn handler over the real script-folders module, on fake timers, with a folders stand-in shaped as the real module (one work for every caller, each wait bounded by what it is given). Covers the evidence case (a check that never answers, the tab asked 3 s in, beside a 1.3 s folders hold and a 0.4 s look: the spawn runs 5 s after the ask, not 5.4 s), a check that ends 6 s after it began with the tab asked 3 s in (waited for; at its spawn the - resume list's script may be run), seven 5 s + 8 s pairs that spawn at 8 s, + resume list's script may be run), the trade (the review's probe: a check + that ends 5.2 s after the ask, beside the same holds: the spawn runs 5 s + after the ask with the resume list's script not there, not 5.4 s after it + with the script ready), seven 5 s + 8 s pairs that spawn at 8 s, sign-in tabs, a check that answers in its usual time, the log rule (1 s, or still pending), and the folders' one bound: work that never answers spawns at 10 s with one call and one line (20 s and two calls before the review @@ -206,6 +272,12 @@ TAB_MS stays. #513 stays open on this. spawn is red on its own under the deadline (the script not yet deployed), with the test's earlier checks taken out. The short still-pending line, now read from a 500 ms look, is red when a hold is said only by its time. +- Round 5 (the trade, accepted): the trade test is red with the holds one + after another (11 of 17 red; it spawns 5.4 s after the ask), and on + 591eb8fb's pty-handlers.ts and script-folders.ts (16 of 17 red; 5.4 s too). + With its spawn-time and log checks taken out it is red on what the launch + finds at its spawn alone (the script ready, `{ ok: true }`). Each run put + the files back and sha-checked them. Not measured: the split of the remaining 0.4 to 0.5 s, and the check's start time at boot (it begins in a microtask after the start's synchronous setup, From ebff5e69737304a9b9892ccd132dabd1488193f8 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:43:06 +0000 Subject: [PATCH 35/79] docs(context): say only the forced red is shown to have started without its scripts The round-6 recheck's MINOR: the green run's script state at its spawn was not recorded, so 'no measured check ended in the window' becomes 'no check is known to have ended in it', with what rests on the b20 times. Wording only, in the CONTEXT note and one test header comment. Independent review: the reviewer's own wording fix, applied as given in a doc and a comment, so it takes the trivial-edit exception. Co-Authored-By: Claude Opus 5.5 --- CONTEXT.d/2026-12-03-b28-snap-d1-holds.md | 23 ++++++++++++------- .../main/pty-spawn-holds-side-by-side.test.ts | 4 ++-- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md index 5f8c0ab0a..128d9691d 100644 --- a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -71,7 +71,9 @@ deploys after it have run (index.ts), at most `SCRIPT_FOLDERS_LAUNCH_WAIT_MS` the end of that chain, ends it early. The check is one Windows PowerShell call; on a runner's first app it takes 8.8 to 13.6 s (2026-11-27-b20-snap-d1.md), and the tab is asked for about 3 s after main starts. In both runs here the hold -ran out its full 5 s, and the tab started without the scripts all the same. +ran out its full 5 s. The forced red's tab is shown to have started without +the scripts (its launch line was the direct one); the green run's script +state at its spawn was not recorded. The other holds ran after it, one after another; with the IPC they took the remaining 0.4 to 0.5 s (not split: no line said them). @@ -193,12 +195,17 @@ branch does not keep every tab's scripts as 591eb8fb did. not split), up to about 1.4 s where the session folders' work runs after the scripts wait (1.15 to 1.36 s under load on CI), and more only where the other holds run longer (the saving grows with it). -- No measured check ended in it. Both evidence runs held their tab one hold - after another and still started it without its scripts, so neither check, - with its deploys, had ended by the spawn, 5.4 to 5.5 s after the submit: - past the window's end. On a runner's first app the check takes 8.8 to - 13.6 s (2026-11-27-b20-snap-d1.md) and the tab is asked about 3 s after - main starts, so the check ends about 5.8 s or more after the ask. Where +- No check is known to have ended in it. The forced red's tab is shown to + have started without its scripts (its launch line was the direct one), so + its check, with its deploys, had not ended by the spawn, 5.4 s after the + submit: past the window's end. The green run's script state at its spawn + was not recorded; for it the reading rests on the b20 first-app check + times. On a runner's first app the check takes 8.8 to 13.6 s + (2026-11-27-b20-snap-d1.md) and the tab is asked about 3 s after main + starts, so the check ends about 5.8 s or more after the ask, about 0.3 to + 0.5 s past the evidence's window. A run whose other holds take longer (the + up to about 1.4 s case above) would put the fastest measured first-app + check inside the window. Where Windows PowerShell is warm it took 1.0 to 1.6 s (2.6 to 3.5 s with the disk cache purged): inside the tab's 5 s, and waited for. - The recheck's probe (round 5's review, on the holds test's harness): a @@ -215,7 +222,7 @@ branch does not keep every tab's scripts as 591eb8fb did. same time as the saving, so getting it back means waiting as long as before; the nearest other order (the scripts wait first, the other holds side by side after it) narrows the window only by giving back as much of - the saving. No measured check ended in it, and a check that ends past it + the saving. No check is known to have ended in it, and a check that ends past it was lost on 591eb8fb too. Still open, an owner decision: the runner's cold Windows PowerShell share of diff --git a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts index c84799a75..f584f4d41 100644 --- a/tests/unit/main/pty-spawn-holds-side-by-side.test.ts +++ b/tests/unit/main/pty-spawn-holds-side-by-side.test.ts @@ -3,8 +3,8 @@ * spawn, on the clock. * * The Snap e2e's first Claude Code tab (runs 47213031983 and 47213083589) - * waited 5.4 to 5.5 s in main between its request and its spawn, and then - * started without the resume list: the scripts folders' check (one cold + * waited 5.4 to 5.5 s in main between its request and its spawn; the forced + * red's tab then started without the resume list: the scripts folders' check (one cold * Windows PowerShell call at start) had not answered, the tab's wait ran out * its own 5 s bound, and the other holds ran after it, one after another. * Here: From 2ec39cfea699e881fcaf698a304e2bd9dc28c1a9 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:43:55 +0000 Subject: [PATCH 36/79] fix(usage): file a plain SSH tab's usage under its account (planning #516) A Claude Code tab over plain SSH never reached its account on the Accounts page: the account read Not in use at its last background reading while the tab's own status line showed live figures. The usage sink's no-local-profile branch (account-usage.ts recordLiveUsageForSession) returned when a report carried no transcript path, before it read the email or marked the session open. The SSH status line shim never sends one (only the local bridge does), so every plain SSH report was dropped. The gate was there to keep a session helper tab's frames out, whose bars are this computer's own reading. - session-signals/status.ts: deliverStatus takes an optional { usageIsThisComputers } and, when set, offers nothing to the usage sink. - statusline-watcher.ts: both helper delivery points (dispatchHelperStatus and deliverHelperAccount) pass it, so a helper tab's joined bars never loop back as its live reading; its own windows still come in by noteHelperReading / recordHelperTabUsage. - account-usage.ts: the transcript-path gate goes; the email check, the profile match by email and noteRemoteSessionProfile stay. A report that is not filed now logs one line per session saying why (no email reported, or no profile here holds it), with neither the email nor a path. ssh-shim.ts and pty-manager.ts are unchanged. Tests: the shape a real shim sends (no transcript path) is filed and the account is in use; sshDelivered's default transcript is undefined and the test that pinned the drop is gone; a helper tab's bars never reach the sink (red if either delivery point drops the option); the one-line diagnostic; and a contract test that feeds a body the real shim POSTs through ingestStatusPayload to the sink. Co-Authored-By: Claude Opus 5.5 --- src/main/session-signals/status.ts | 29 +++++++--- src/main/statusline-watcher.ts | 14 +++-- src/main/usage/account-usage.ts | 37 ++++++++---- tests/unit/account-usage-live-open.test.ts | 46 +++++++++++---- .../main/statusline-helper-account.test.ts | 11 +++- .../claude/ssh-shim-account-delivery.test.ts | 57 ++++++++++++++++++- 6 files changed, 153 insertions(+), 41 deletions(-) diff --git a/src/main/session-signals/status.ts b/src/main/session-signals/status.ts index e384dc709..38a2fba3a 100644 --- a/src/main/session-signals/status.ts +++ b/src/main/session-signals/status.ts @@ -85,6 +85,17 @@ export function setStatuslineUsageSink(sink: StatuslineUsageSink): void { statuslineUsageSink = sink } +/** How the fan-out reads a payload's usage (nubbymong/aicc_planning#516). */ +export interface DeliverStatusOptions { + /** The bars are this computer's own reading of the account, not the + * session's: a frame of a tab through the session helper, whose bars + * statusline-watcher.ts joins from what main already holds. They go to the + * strip, never to the usage sink, which would file main's own reading back + * as the tab's live one. The tab's own windows reach its account through + * noteHelperReading and recordHelperTabUsage instead. */ + usageIsThisComputers?: boolean +} + /** * Common fan-out for any parsed StatuslineData payload — used by both the * file watcher and the SSH OSC sentinel dispatch path. Sends to the renderer @@ -95,7 +106,7 @@ export function setStatuslineUsageSink(sink: StatuslineUsageSink): void { * rebuild on EVERY tick — the ~30s UI freeze). The tokenomics worker now * indexes from raw transcripts on its own fs-watch/timer. */ -export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWindow | null) | null): void { +export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWindow | null) | null, opts: DeliverStatusOptions = {}): void { // Copilot review on PR #31 (p9.17): decorate with accountColour HERE, // at the renderer-send site, so the ContextBar sees accountColour. Decorate // once and forward the enriched object to every consumer. @@ -137,16 +148,20 @@ export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWin // Plan P2: harvest the account-level usage this session just delivered so the // account-usage page can reuse an OPEN account's figure. Read from raw `data` // (account-level, so unaffected by the subagent model/effort strip on - // forDisplay). Best-effort and guarded: the sink resolves the session's profile - // and stores nothing for an SSH or default-home session, and must never break - // the fan-out. + // forDisplay). Best-effort and guarded: the sink resolves the session's + // profile, and must never break the fan-out. // nubbymong/aicc_planning#509: with Claude Code's own 5-hour and weekly // windows (statuslineUsageOf), so a reading reaches the account even when // the status line script read no usage of its own. - const usage = data.sessionId && statuslineUsageSink ? statuslineUsageOf(data) : [] + // nubbymong/aicc_planning#516: a payload whose bars are this computer's own + // reading (a helper tab's frame) is never offered to the sink. + const usage = data.sessionId && statuslineUsageSink && !opts.usageIsThisComputers ? statuslineUsageOf(data) : [] if (data.sessionId && usage.length > 0 && statuslineUsageSink) { - // The transcript path goes with it: the sink files the figure under a - // profile only when the transcript lies in that profile's folder. + // The transcript path and the account email go with it: a session on + // this computer is filed under its profile only when the transcript lies + // in that profile's folder; a session with no local profile (an SSH tab, + // whose shim sends no transcript path) under the profile that holds the + // email its status line names. try { statuslineUsageSink(data.sessionId, usage, data.rateLimitExtra != null, data.transcriptPath, data.accountEmail) } catch { /* sink must not break fan-out */ } } // Sentinel Trigger A: observe the raw model id (modelId preferred; fall back to diff --git a/src/main/statusline-watcher.ts b/src/main/statusline-watcher.ts index df4ab7c72..bd3a2696e 100644 --- a/src/main/statusline-watcher.ts +++ b/src/main/statusline-watcher.ts @@ -128,9 +128,10 @@ export function dispatchSSHStatuslineUpdate(json: string, fromSessionId?: string * this computer holds of that account (setHelperAccount), joined to each * frame here, each through its own gate. A frame of a tab whose account this * computer holds also asks for that reading again once it is due. The bars - * joined here are that reading: the fan-out offers them to the usage sink as - * any frame's, and the sink files nothing for them, since the frame carries - * no transcript path (usage/account-usage.ts recordLiveUsageForSession). + * joined here are that reading, so the fan-out is told they are this + * computer's own (usageIsThisComputers) and offers them to no usage sink + * (nubbymong/aicc_planning#516: the sink no longer tells a helper frame by its + * missing transcript path, which a plain SSH tab's report lacks too). * * nubbymong/aicc_planning#509: the tab is a session open on that account, so * its 5-hour and weekly windows (the frame's rateLimitCurrent and @@ -146,7 +147,7 @@ export function dispatchHelperStatus(appPtyId: string, line: Readonly { return out } -/** The tab's account fields alone, at once (before its first status frame). */ +/** The tab's account fields alone, at once (before its first status frame). + * Its bars are this computer's own reading, as a frame's are. */ function deliverHelperAccount(appPtyId: string): void { if (!sshDispatchWindow || !helperAccounts.has(appPtyId)) return - deliverStatus({ sessionId: appPtyId, ...helperAccountFields(appPtyId) }, sshDispatchWindow) + deliverStatus({ sessionId: appPtyId, ...helperAccountFields(appPtyId) }, sshDispatchWindow, { usageIsThisComputers: true }) } /** One usage reading of a held account's tab; delivered when it lands, if that start still stands. */ diff --git a/src/main/usage/account-usage.ts b/src/main/usage/account-usage.ts index ad195fada..35c6d4c8b 100644 --- a/src/main/usage/account-usage.ts +++ b/src/main/usage/account-usage.ts @@ -43,7 +43,7 @@ import { heldProfileFor } from './remote-tab-usage' import { USAGE_HOST, parseRetryAfter, usageHostPauses } from './usage-rate-limit' import { UsageChecker, IDLE_CHECK_INTERVAL_MS, type CheckOutcome, type CheckSchedule } from './usage-checker' import { USAGE_DETAIL_RENEWING, USAGE_DETAIL_NOT_SIGNED_IN, USAGE_DETAIL_DUPLICATE, USAGE_DETAIL_WRONG_ACCOUNT, USAGE_DETAIL_NO_READING, usageSignInProblem, type UsageSignInProblem, type AccountUsage, type UsageBucket, type CreditsInfo } from '../../shared/usage-types' -import { logWarn } from '../debug-logger' +import { logInfo, logWarn } from '../debug-logger' export type { AccountUsage } from '../../shared/usage-types' @@ -472,6 +472,21 @@ function profileForReportedEmail(sessionId: string, email: string): string | und return profileId } +/** Sessions a report that was not filed has been logged for: one line per + * session, so a session reporting every few seconds cannot fill the log. + * Bounded like the maps above; cleared when full. */ +const remoteNotFiledLogged = new Set() + +/** nubbymong/aicc_planning#516: say once per session why a report from a + * session with no local profile was not filed, so the drop leaves a line in + * the log. Neither the email nor any path is written. */ +function noteRemoteNotFiled(sessionId: string, why: string): void { + if (remoteNotFiledLogged.has(sessionId)) return + if (remoteNotFiledLogged.size >= LIVE_SESSIONS_MAX) remoteNotFiledLogged.clear() + remoteNotFiledLogged.add(sessionId) + try { logInfo(`[account-usage] session ${sessionId} (no local profile): its usage is not filed under an account, because ${why}. Later reports of this session are not logged.`) } catch { /* the log must not break the fan-out */ } +} + /** File a reading a session delivered, under the profile it runs on: the * session's own, and the profile's newest reading, kept in the snapshots * (nubbymong/aicc_planning#509: every reading the app sees is kept, so an @@ -498,7 +513,14 @@ function fileLiveReading(sessionId: string, profileId: string, buckets: UsageBuc * - a session with no local profile (an SSH tab, on its machine's own * sign-in), under the profile whose email is the one its status line * reports (`accountEmail`), when this computer holds one; that session - * then counts as open on the profile (noteRemoteSessionProfile). + * then counts as open on the profile (noteRemoteSessionProfile). Its + * report carries no transcript path (the SSH shim sends none), so none is + * asked for (nubbymong/aicc_planning#516). A tab through the session + * helper never reaches here: its frames' bars are this computer's own + * reading, which the fan-out keeps from the sink (session-signals/status.ts + * usageIsThisComputers); its own windows come in by recordHelperTabUsage. + * A report that is not filed says why once per session in the log + * (noteRemoteNotFiled), with neither the email nor any path. * An empty or all-malformed set is ignored (nothing to show). `hasCredits` is * not kept: the status line has no credits figure to show, so the credits row * comes from the last fetch (see newestFigure). @@ -516,17 +538,12 @@ export function recordLiveUsageForSession(sessionId: string, buckets: unknown, h if (owner !== localProfile) return profileId = localProfile } else { - // A session's own report carries its transcript path. A frame of a tab - // through the session helper carries none (the bars it shows are the - // reading main holds, statusline-watcher.ts dispatchHelperStatus), so it - // is never filed here: its own windows come in by recordHelperTabUsage. - if (typeof transcriptPath !== 'string' || !transcriptPath) return - if (typeof accountEmail !== 'string' || !accountEmail) return + if (typeof accountEmail !== 'string' || !accountEmail) { noteRemoteNotFiled(sessionId, 'its status line names no account email'); return } profileId = profileForReportedEmail(sessionId, accountEmail) // An account this computer does not hold (a switch on that machine) is // forgotten: the session no longer counts as open on the earlier one. noteRemoteSessionProfile(sessionId, profileId ?? '') - if (!profileId) return + if (!profileId) { noteRemoteNotFiled(sessionId, 'no account profile on this computer has the email its status line names'); return } } fileLiveReading(sessionId, profileId, clean, now) } @@ -683,7 +700,7 @@ async function inSessionUsage(base: AccountUsage, profileId: string, isPrimary: } /** Test seam: the live cache is module state and outlives a test file otherwise. */ -export function _resetLiveUsageForTest(): void { liveUsageBySession.clear(); remoteProfileCache.clear() } +export function _resetLiveUsageForTest(): void { liveUsageBySession.clear(); remoteProfileCache.clear(); remoteNotFiledLogged.clear() } /** Test seam: reset the hydrate latch + last-good map so a test can seed fresh * snapshots. Without it the once-per-process hydrate keeps the first test's view. */ diff --git a/tests/unit/account-usage-live-open.test.ts b/tests/unit/account-usage-live-open.test.ts index 6ef81642e..fd0740611 100644 --- a/tests/unit/account-usage-live-open.test.ts +++ b/tests/unit/account-usage-live-open.test.ts @@ -11,8 +11,10 @@ // newest reading wins. Before its sessions report, the card says it waits for // its session's first reading and keeps the last reading with its age. A // session on another machine (an SSH tab, no local profile) counts too, filed -// by the account email its status line reports. The background checker never -// queues an account in use. +// by the account email its status line reports. Its report carries no +// transcript path, as the real SSH shim sends none (nubbymong/aicc_planning#516; +// ssh-shim-account-delivery.test.ts feeds the shim's own POST body through the +// ingest to the sink). The background checker never queues an account in use. // // The page's read (accountUsageNow, allAccountsUsageNow, // streamAccountsUsageNow) sends NOTHING for any account. Only the background @@ -95,6 +97,7 @@ vi.mock('https', () => { return { default: { request }, request } }) +const { logInfo } = await import('../../src/main/debug-logger') const { fetchAccountUsage, accountUsageNow, allAccountsUsageNow, streamAccountsUsageNow, recordLiveUsageForSession, setLiveUsageTranscriptProfile, setLiveUsageSessionReports, _resetLiveUsageForTest, _resetSnapshotsForTest, @@ -110,8 +113,6 @@ const { bandOf, usageRowEntry } = await import('../../src/renderer/utils/account const transcriptOf = (sessionId: string, profileId = profileBySession.get(sessionId)) => `/profiles/${profileId}/projects/p/00000000-0000-4000-8000-000000000000.jsonl` const fakeFolderRule = (transcriptPath: string) => /^\/profiles\/([^/]+)\/projects\/[^/]+\/[^/]+\.jsonl$/.exec(transcriptPath)?.[1] -/** A transcript path on another machine: no profile folder here holds it. */ -const REMOTE_TRANSCRIPT = '/home/someone/.claude/projects/p/00000000-0000-4000-8000-000000000001.jsonl' const USAGE_HOST = 'api.anthropic.com' @@ -140,8 +141,9 @@ function sessionDelivered(profileId: string, buckets: unknown[], opts: { hasCred recordLiveUsageForSession(sessionId, buckets, !!opts.hasCredits, transcriptOf(sessionId), Date.now() - (opts.ageMs ?? 0)) } -/** A session on another machine (no local profile) whose status line names `email`. */ -function sshDelivered(sessionId: string, email: unknown, buckets: unknown[], transcript: unknown = REMOTE_TRANSCRIPT, ageMs = 0): void { +/** A session on another machine (no local profile) whose status line names + * `email`. By default with no transcript path: the SSH shim sends none (#516). */ +function sshDelivered(sessionId: string, email: unknown, buckets: unknown[], transcript: unknown = undefined, ageMs = 0): void { profileBySession.set(sessionId, undefined) recordLiveUsageForSession(sessionId, buckets, false, transcript, Date.now() - ageMs, email) } @@ -158,6 +160,7 @@ beforeEach(() => { remoteProfile.clear() seededSnapshots = {} requestedHosts.length = 0 + vi.mocked(logInfo).mockClear() _resetLiveUsageForTest() _resetSnapshotsForTest() // so each test's seededSnapshots is hydrated fresh _resetUsageCheckerForTest() @@ -356,13 +359,32 @@ describe('a session on another machine (SSH) counts as open on the account its s expect(r.buckets.map((b) => b.percent)).toEqual([44]) }) - it('a frame with no transcript path (a tab through the session helper, this computer\'s own figure) is never filed', async () => { - sshDelivered('helper-1', 'x@example.com', [bucket({ percent: 44 })], null) - sshDelivered('helper-2', 'x@example.com', [bucket({ percent: 44 })], '') + // nubbymong/aicc_planning#516: the shape a real SSH shim sends. Its report + // carried no transcript path, and the sink dropped it for that alone, so + // an account in use only over SSH read Not in use at its last reading. + it('the report a real SSH tab sends, with no transcript path, is filed under the account, and the account is in use (#516)', async () => { + sshDelivered('ssh-1', 'x@example.com', [bucket({ percent: 13 })], undefined) + expect(remoteProfile.get('ssh-1')).toBe('profile-x-1') const r = await accountUsageNow('profile-x-1') - expect(r.inSession).toBeUndefined() - expect(remoteProfile.size).toBe(0) + expect(r).toMatchObject({ status: 'ok', inSession: true, sessionReading: true }) + expect(r.buckets.map((b) => b.percent)).toEqual([13]) + expect(requestedHosts).toEqual([]) + }) + + it('a report that is not filed says why in the log, once per session, with neither the email nor a path (#516)', async () => { + sshDelivered('ssh-1', 'someone-else@example.com', [bucket()]) + sshDelivered('ssh-1', 'someone-else@example.com', [bucket()]) + sshDelivered('ssh-2', undefined, [bucket()]) + sshDelivered('ssh-3', 'x@example.com', [bucket()]) // filed: no line + + const lines = vi.mocked(logInfo).mock.calls.map((c) => String(c[0])).filter((l) => l.startsWith('[account-usage]')) + expect(lines).toHaveLength(2) + expect(lines[0]).toContain('session ssh-1 ') + expect(lines[0]).toContain('no account profile on this computer has the email its status line names') + expect(lines[1]).toContain('session ssh-2 ') + expect(lines[1]).toContain('its status line names no account email') + for (const l of lines) expect(l).not.toMatch(/@|example|\//) }) it('an email this computer holds no profile for, or none at all, files nothing', async () => { @@ -384,7 +406,7 @@ describe('a session on another machine (SSH) counts as open on the account its s it('local and SSH sessions on one account: the newest reading wins', async () => { sessionDelivered('profile-x-1', [bucket({ percent: 10 })], { ageMs: 30_000 }) - sshDelivered('ssh-1', 'x@example.com', [bucket({ percent: 15 })], REMOTE_TRANSCRIPT, 1_000) + sshDelivered('ssh-1', 'x@example.com', [bucket({ percent: 15 })], undefined, 1_000) expect((await accountUsageNow('profile-x-1')).buckets.map((b) => b.percent)).toEqual([15]) }) diff --git a/tests/unit/main/statusline-helper-account.test.ts b/tests/unit/main/statusline-helper-account.test.ts index 573660ffe..14cd2baab 100644 --- a/tests/unit/main/statusline-helper-account.test.ts +++ b/tests/unit/main/statusline-helper-account.test.ts @@ -165,12 +165,17 @@ describe('a helper tab\'s weekly bars and extra usage, from this computer', () = expect(reads).toEqual(['profile-work']) expect(last()).toMatchObject({ sessionId: 'tab-remote', accountEmail: 'me@example.com', usageBuckets: BUCKETS, rateLimitExtra: { enabled: true, utilization: 25, usedUsd: 5, limitUsd: 20 } }) expect(last().remoteUsageNotShown).toBeUndefined() + // nubbymong/aicc_planning#516: the bars joined to the tab are this + // computer's own reading, so they never reach the usage sink, which would + // file them back as the tab's live reading; the tab's own windows reach + // its account by recordHelperTabUsage. The sink no longer tells a helper + // frame by its missing transcript path (a plain SSH tab's report has none + // either), so the fan-out is told instead. + expect(usageSink).toEqual([]) // A host frame carries the same, from this computer's reading. dispatchHelperStatus('tab-remote', { model: 'Opus', transcriptPath: '/home/dev/.claude/projects/x/y.jsonl' }) expect(last()).toMatchObject({ model: 'Opus', usageBuckets: BUCKETS }) - // The fan-out offers the tab's bars to the usage sink with no transcript path, so it files nothing (account-usage.ts recordLiveUsageForSession files a figure only for a transcript in the profile's folder). - expect(usageSink.length).toBeGreaterThan(0) - expect(usageSink.every((c) => c.id === 'tab-remote' && c.transcriptPath === undefined)).toBe(true) + expect(usageSink).toEqual([]) }) it('an account with no extra usage switched on shows no extra usage block', async () => { diff --git a/tests/unit/providers/claude/ssh-shim-account-delivery.test.ts b/tests/unit/providers/claude/ssh-shim-account-delivery.test.ts index 929e6804b..c74ce72c2 100644 --- a/tests/unit/providers/claude/ssh-shim-account-delivery.test.ts +++ b/tests/unit/providers/claude/ssh-shim-account-delivery.test.ts @@ -17,10 +17,32 @@ // the two POSTs fire -- and what each carries -- is what is under test, not a // restatement of it. Sibling to ssh-shim-runtime-harness.test.ts (which covers // the OSC-ladder branch); this one drives the tunnel POST branch. -import { describe, it, expect } from 'vitest' +// +// nubbymong/aicc_planning#516: the last block feeds a body the shim really +// POSTs through the /status ingest (ingestStatusPayload) and the fan-out to +// the usage sink, so what the sink needs to file a remote tab's reading under +// its account (a reading and the account email; no transcript path, which the +// shim never sends) is tied to the shim's own payload, not a hand-written one. +import { describe, it, expect, vi, afterAll } from 'vitest' import { EventEmitter } from 'events' import * as nodePath from 'path' import { generateRemoteSetupScript } from '../../../../src/main/providers/claude/ssh-shim' +import { ingestStatusPayload } from '../../../../src/main/conductor-mcp-server' +import { setStatuslineUsageSink, startStatuslineWatcher } from '../../../../src/main/statusline-watcher' + +// The watcher the contract block starts makes /status: a temp +// folder of its own here, removed after. Everything else of the module is real. +const h = vi.hoisted(() => ({ + dir: (() => { + const os = require('node:os'); const fs = require('node:fs'); const path = require('node:path') + return fs.mkdtempSync(path.join(os.tmpdir(), 'ccc-shim-usage-')) as string + })(), +})) +vi.mock('../../../../src/main/ipc/setup-handlers', async (importOriginal) => ({ + ...(await importOriginal>()), + getResourcesDirectory: () => h.dir, +})) +afterAll(() => { try { require('node:fs').rmSync(h.dir, { recursive: true, force: true }) } catch { /* best effort */ } }) const NONCE = 'acctnonce123abc' // argv[3] starting with 'http' is used directly as the tunnel URL (no file @@ -76,7 +98,7 @@ interface RunResult { * drives deliver()'s failure path so the legacy-ladder fallback (or its absence, * for the immediate deliver) can be observed via `legacySentinels`. */ -function runShim(shimSource: string, opts: { warmCache?: boolean; httpStatus?: number } = {}): RunResult { +function runShim(shimSource: string, opts: { warmCache?: boolean; httpStatus?: number; stdin?: Record } = {}): RunResult { const httpStatus = opts.httpStatus ?? 200 const posts: Array> = [] const legacySentinels: string[] = [] @@ -158,7 +180,7 @@ function runShim(shimSource: string, opts: { warmCache?: boolean; httpStatus?: n // eslint-disable-next-line no-new-func -- deliberate: this IS the harness. const runner = new Function('require', 'process', shimSource) runner(fakeRequire, fakeProcess) - fakeStdin.emit('data', JSON.stringify({ context_window: {}, cost: {} })) + fakeStdin.emit('data', JSON.stringify(opts.stdin ?? { context_window: {}, cost: {} })) fakeStdin.emit('end') const resolveUsage = (usageJson: string) => { @@ -244,3 +266,32 @@ describe('SSH statusline shim -- account delivered before the cold usage fetch ( expect(legacySentinels).toHaveLength(1) }) }) + +describe('the shim\'s own POST body gives the usage sink what it needs to file the remote account (#516)', () => { + // Mutations to prove this can fail: drop `data.accountEmail` from the + // sink's call in session-signals/status.ts deliverStatus, or pass + // { usageIsThisComputers: true } from dispatchSSHStatuslineUpdate. Either + // way an SSH tab's reading can no longer be filed under its account. + it('a body the real shim POSTs, through the /status ingest: the sink gets the reading and the remote account, and no transcript path', () => { + // Claude Code's own weekly window at 13%, on its status line input. + const { posts } = runShim(extractShimSource(), { + stdin: { context_window: {}, cost: {}, rate_limits: { seven_day: { used_percentage: 13, resets_at: 1_765_357_200 } } }, + }) + expect(posts).toHaveLength(1) + const calls: Array<{ sessionId: string; buckets: unknown; transcriptPath?: string; accountEmail?: string }> = [] + const stop = startStatuslineWatcher(() => ({ isDestroyed: () => false, webContents: { send: () => {} } }) as never) + try { + setStatuslineUsageSink((sessionId, buckets, _hasCredits, transcriptPath, accountEmail) => { calls.push({ sessionId, buckets, transcriptPath, accountEmail }) }) + expect(ingestStatusPayload('ssh-1', JSON.stringify(posts[0])).status).toBe(204) + } finally { + stop() + } + expect(calls).toHaveLength(1) + expect(calls[0].sessionId).toBe('ssh-1') + expect((calls[0].buckets as Array<{ key: string; percent: number }>).map((b) => `${b.key}=${b.percent}`)).toEqual(['weekly_all:=13']) + expect(calls[0].accountEmail).toBe(REMOTE_EMAIL) + // The shape account-usage.ts recordLiveUsageForSession files by email: + // the shim sends no transcript path (account-usage-live-open.test.ts). + expect(calls[0].transcriptPath).toBeUndefined() + }) +}) From 0d70aefa9e5e1b5e49e445192bd66c49d3e15f7d Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:54:45 +0000 Subject: [PATCH 37/79] fix(update): count every session an update with Save keeps for a tab (#514) The update dialog's kept count read only this run's held terminals, so it missed what the update really keeps. A Claude Code or Codex session kept for a restored tab that has not been shown yet is not one of them: the update lets it go by a detach, and the next start keeps it for its tab again. Nor is a plain terminal kept after a crash (or by Re-attach, or by a reclaim) with no tab of this run showing it: it runs on past the exit, and the next start keeps it again. After an at-once restore that shows only the tab on screen, an update before the other tabs were opened said they would restart, while all of them carried on. One manager function, keptThroughUpdate, now lists every session an update with Save sessions leaves running and the tab each is shown under: this run's releasable terminals (as before), the agent sessions kept for their tabs (agent sessions' switch on and the provider's take-over wired, as the next start requires), and the plain terminals kept with no terminal (keptWithNoTerminal). releaseForUpdate lets go of the first kind from it and logs the kept-for-tab ones; tabsKeptThroughUpdate counts through it. Tests: a session kept for its restored tab not shown is counted, and is taken over after the next update (not counted with the switch off); a crash-kept terminal whose tab is not shown is counted, runs on through the update and is taken over by its tab at the next start, while a partner terminal is not counted as its tab's own session. Co-Authored-By: Claude Opus 5.5 --- src/main/session-helper/app-wiring.ts | 5 +- src/main/session-helper/helper-pty.ts | 2 +- src/main/session-helper/manager.ts | 96 ++++++++++++++----- src/shared/update-keep.ts | 2 +- .../unit/main/session-helper-manager.test.ts | 25 +++++ ...ssion-helper-update-handover-hooks.test.ts | 25 +++++ 6 files changed, 128 insertions(+), 27 deletions(-) diff --git a/src/main/session-helper/app-wiring.ts b/src/main/session-helper/app-wiring.ts index c9cb09076..8445eda51 100644 --- a/src/main/session-helper/app-wiring.ts +++ b/src/main/session-helper/app-wiring.ts @@ -251,8 +251,9 @@ export async function releaseHeldTerminalsForUpdate(choice: UpdateChoice = {}): /** * aicc_planning#514: the update dialog's count. How many of the tabs the * renderer names (its open local tabs, by kind) an app update now would keep - * running and show again in the new version, by the rule the update lets go - * of held sessions by (the manager's tabsKeptThroughUpdate). Counts only. + * running and show again in the new version, by the update's own rule: what + * it lets go of, and what it leaves running for the next start to keep again + * (the manager's tabsKeptThroughUpdate). Counts only. * None when the helper was never switched on this run. Lets go of nothing. */ export function sessionsKeptThroughUpdate(tabs: UpdateKeepTabs): UpdateKeepCounts { diff --git a/src/main/session-helper/helper-pty.ts b/src/main/session-helper/helper-pty.ts index dab496807..9acfa1227 100644 --- a/src/main/session-helper/helper-pty.ts +++ b/src/main/session-helper/helper-pty.ts @@ -520,7 +520,7 @@ export class HelperPty implements IPty { /** aicc_planning#514: whether release() would let go of the holder now (a * holder that has been attached, not starting, ending, over or released); * release() asks this, and so does the update dialog's count (manager.ts - * updateKeeps), which lets go of nothing. */ + * keptThroughUpdate), which lets go of nothing. */ get releasable(): boolean { return !(this.inner || this.exited || this.ending || this.released || !this.record || !this.everAttached) } /** The folder its program was launched in, and whether it runs on node-pty's * bundled ConPTY (2.1.3-beta.17, S16 step 5): what an update's record of an diff --git a/src/main/session-helper/manager.ts b/src/main/session-helper/manager.ts index 3650de5c6..db4e6aaf2 100644 --- a/src/main/session-helper/manager.ts +++ b/src/main/session-helper/manager.ts @@ -686,6 +686,13 @@ const lastLine = (s: string): string => s.split(/\r?\n/).map((l) => l.trim()).fi const firstLine = (s: string): string => s.split(/\r?\n/).map((l) => l.trim()).find(Boolean) ?? '' const message = (err: unknown): string => (err instanceof Error ? err.message : String(err)) +/** A session an app update with Save sessions leaves running, and the tab + * (`label`) it is shown under (SessionHelperManager keptThroughUpdate says + * each kind). `forTab`: the next start shows it in that tab. */ +type UpdateKeep = + | { how: 'release'; sid: string; label: string; forTab: boolean; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord } + | { how: 'keptForTab' | 'runsOn'; sid: string; label: string; forTab: true } + /** A session kept for its restored tab (SessionHelperManager keptForTabs). */ interface KeptForTab { kept: KeptRecord @@ -2089,7 +2096,10 @@ export class SessionHelperManager implements MachinesSource { // B1f: each connection that takes hook events lets go by a detach, which // the update waits for (endsForUpdate): its later events wait in its holder. const lets: Promise[] = [] - for (const { sid, w, keeps, record } of this.updateKeeps(saved)) { + const leaves = this.keptThroughUpdate(saved) + for (const k of leaves) { + if (k.how !== 'release') continue + const { sid, w, keeps, record } = k // An agent session's record is written before it is let go of: one // that cannot be recorded is left to the kill, which ends it. const kept = keeps ? this.recordKept(sid, w.label, keeps.kind, w.launchShape, keeps.hooks) : undefined @@ -2111,8 +2121,7 @@ export class SessionHelperManager implements MachinesSource { // That is what the user chose with Save; only "Close sessions" ends it here. const ends: Promise[] = [] let leftRunning = 0 - for (const [sid, r] of new Map([...this.reclaimed, ...this.adoptable])) { - if (this.live.has(sid) || heldIdKind(sid) !== 'plain') continue + for (const [sid, r] of this.keptWithNoTerminal()) { if (restorable !== null) { leftRunning++ this.deps.log(`[session-helper] ${sid}: kept with no tab showing it; left running through the update, for the next start to keep again`) @@ -2136,31 +2145,72 @@ export class SessionHelperManager implements MachinesSource { const tail = restorable === null ? `the sessions were discarded, so ${ends.length} kept terminal(s) are ended` : `${leftRunning} kept terminal(s) are left running` - this.deps.log(`[session-helper] an app update: ${n - agents} held terminal(s) are let go of, for the new version to show again${agents > 0 ? `, and ${agents} agent session(s) are let go of with their CLIs running, recorded for the next start` : ''}; ${tail}`) + // An agent session kept for its restored tab not shown stays kept: the + // next start keeps it for its tab again (keptAtStart). + const forTabs = leaves.filter((k) => k.how === 'keptForTab').length + this.deps.log(`[session-helper] an app update: ${n - agents} held terminal(s) are let go of, for the new version to show again${agents > 0 ? `, and ${agents} agent session(s) are let go of with their CLIs running, recorded for the next start` : ''}; ${tail}${forTabs > 0 ? `; ${forTabs} agent session(s) kept for their tabs stay kept for the next start` : ''}`) this.changed() return n } /** - * The held sessions an app update lets go of (releaseForUpdate's rule, and - * the update dialog's count's: tabsKeptThroughUpdate): on Windows and not - * quitting, each terminal through a holder that release() would let go of - * now (HelperPty.releasable), a plain or partner terminal, or an agent - * session whose routes an update keeps (keepable), when its holder has a - * record and its tab (a partner's is its session's) is `saved`. Reads only. + * Every session an app update with Save sessions leaves running, each with + * the tab it is shown under: releaseForUpdate goes by it, and so does the + * update dialog's count (tabsKeptThroughUpdate, aicc_planning#514), so the + * two cannot part. On Windows and not quitting; a tab (a partner's is its + * session's) counts as saved when `saved` says so. Three kinds: + * + * - `release`: a terminal of this run through a holder that release() would + * let go of now (HelperPty.releasable): a plain or partner terminal, or an + * agent session whose routes an update keeps (keepable), its holder with a + * record. `forTab`: the next start shows it in its tab, which for an agent + * session needs its provider's take-over wired (deps.takeOver), because + * the next start ends any other (keptAtStart). + * - `keptForTab`: an agent session the last update kept for its restored + * tab, not taken over yet (keptForTabs; its tab is not shown). The update + * does not reach it: its keeper lets go (B1f) or drops at the exit, and + * the next start keeps it for its tab again, with the agent sessions' + * setting on and its provider's take-over wired (keptAtStart). + * - `runsOn`: a plain or partner terminal kept with no terminal of this run + * showing it (keptWithNoTerminal). The update does not reach it either: + * it runs on past the exit, and the next start keeps it again for the tab + * it is bound to (section B3). + * + * Reads only. */ - private updateKeeps(saved: (tab: string) => boolean): Array<{ sid: string; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord }> { - const out: Array<{ sid: string; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord }> = [] + private keptThroughUpdate(saved: (tab: string) => boolean): UpdateKeep[] { + const out: UpdateKeep[] = [] if (this.os !== 'windows' || this.quitting) return out + const savedTab = (label: string) => saved(parentOfPartnerPtyId(label) ?? label) for (const [sid, w] of this.live) { if (!w.throughHelper || !w.releasable) continue const kind = heldIdKind(sid) const keeps = kind === 'agent' ? this.keepable(w) : null if (kind !== 'plain' && !keeps) continue const record = w.heldRecord - const tab = parentOfPartnerPtyId(w.label) ?? w.label - if (!record || !saved(tab)) continue - out.push({ sid, w, keeps, record }) + if (!record || !savedTab(w.label)) continue + out.push({ how: 'release', sid, label: w.label, forTab: !keeps || this.deps.takeOver?.[keeps.kind] === true, w, keeps, record }) + } + for (const [sid, e] of this.keptForTabs) { + if (!this.agentsOn || this.deps.takeOver?.[e.kept.provider] !== true || !savedTab(e.kept.label)) continue + out.push({ how: 'keptForTab', sid, label: e.kept.label, forTab: true }) + } + for (const [sid, r] of this.keptWithNoTerminal()) { + const label = this.appIdOf(r) + if (savedTab(label)) out.push({ how: 'runsOn', sid, label, forTab: true }) + } + return out + } + + /** The plain and partner terminals kept with no terminal of this run + * showing them (one a crash left, one Re-attach opened a tab for, one an + * earlier reclaim() kept), by session id: an update's kill does not reach + * them (releaseForUpdate, keptThroughUpdate). */ + private keptWithNoTerminal(): Map { + const out = new Map() + for (const [sid, r] of new Map([...this.reclaimed, ...this.adoptable])) { + if (this.live.has(sid) || heldIdKind(sid) !== 'plain') continue + out.set(sid, r) } return out } @@ -2168,18 +2218,18 @@ export class SessionHelperManager implements MachinesSource { /** * aicc_planning#514: the tabs, of `tabs`, whose own session (not a partner * terminal beside it) an app update now would keep running for the next - * version to show again: the update dialog's count, by releaseForUpdate's - * rule (updateKeeps), each of `tabs` taken as saved, as Save sessions - * saves it before the install. An agent session counts only where its - * provider's take-over is wired (deps.takeOver), because the next start - * ends any other (keptAtStart). Lets go of nothing, writes nothing, and + * version to show in that tab: the update dialog's count. Each of `tabs` is + * taken as saved, as Save sessions saves it before the install, and the + * rule is the update's own (keptThroughUpdate): a terminal it lets go of, + * an agent session kept for a restored tab not shown yet, and a terminal + * kept with no tab of this run showing it, each only where the next start + * shows it in its tab (`forTab`). Lets go of nothing, writes nothing, and * leaves the update path as it is. */ tabsKeptThroughUpdate(tabs: ReadonlySet): Set { const out = new Set() - for (const { w, keeps } of this.updateKeeps((tab) => tabs.has(tab))) { - if (keeps && this.deps.takeOver?.[keeps.kind] !== true) continue - if (tabs.has(w.label)) out.add(w.label) + for (const k of this.keptThroughUpdate((tab) => tabs.has(tab))) { + if (k.forTab && tabs.has(k.label)) out.add(k.label) } return out } diff --git a/src/shared/update-keep.ts b/src/shared/update-keep.ts index 6822306bd..90589aeb5 100644 --- a/src/shared/update-keep.ts +++ b/src/shared/update-keep.ts @@ -4,7 +4,7 @@ * The dialog says what each choice does to the tabs open now, and how many of * them an app update keeps running is main's to say: the session helper's own * rule, the one the install lets go of held sessions by (update-handlers.ts, - * session-helper/manager.ts updateKeeps). So the renderer names its open + * session-helper/manager.ts keptThroughUpdate). So the renderer names its open * local tabs, split as it shows them (agent sessions and Terminal only tabs), * and main answers how many of each it would keep. Counts only: main sends * back no id and no path. Both sides read the other's message through the diff --git a/tests/unit/main/session-helper-manager.test.ts b/tests/unit/main/session-helper-manager.test.ts index 6f0b06649..b09d4f768 100644 --- a/tests/unit/main/session-helper-manager.test.ts +++ b/tests/unit/main/session-helper-manager.test.ts @@ -2174,6 +2174,31 @@ describe('an app update on Windows: held plain and partner terminals are let go expect(logs).toContain('[session-helper] an app update: 0 held terminal(s) are let go of, for the new version to show again; the sessions were discarded, so 2 kept terminal(s) are ended') }) + it('aicc_planning#514: a terminal kept after a crash whose tab is not shown yet is counted as kept by the update dialog, as the update leaves it running and the next start\'s tab takes it over; one whose tab is not asked about, and a partner terminal beside its tab, are not counted', async () => { + const second = await keptAfterCrash([PLAIN, UNSAVED, PARTNER]) + const s = sids() + helper.holders.get(s.plain)!.output('kept output\r\n') + second.noteSavedTabs([{ id: PLAIN, label: 'Build' }, { id: PARENT, label: 'API' }]) + // No terminal of this run shows any of them: the count reads the kept ones too. + expect([...second.tabsKeptThroughUpdate(new Set([PLAIN]))]).toEqual([PLAIN]) + expect([...second.tabsKeptThroughUpdate(new Set([PLAIN, UNSAVED]))].sort()).toEqual([PLAIN, UNSAVED].sort()) + // A partner terminal is beside its tab, not the tab's own session. + expect([...second.tabsKeptThroughUpdate(new Set([PARENT]))]).toEqual([]) + // The update with Save leaves it running, as counted. + expect(second.releaseForUpdate(new Set([PLAIN]))).toBe(0) + await second.endsForUpdate() + crash(second) + const third = makeManager() + setSessionHelper(third) + void third.start({ atStartup: true }) + const q = spawnPlainPty({ plain: true, sessionId: PLAIN }, SHELL, [], opts()) + const seen: string[] = [] + q.onData((d) => seen.push(d)) + expect(await (q as HelperPty).adoption).toBe(true) + await until(() => seen.join('').includes('kept output'), 'the replay in its tab') + expect(helper.holders.get(s.plain)!.endsAsked).toBe(0) + }) + it('Save with no tab saved at all: a kept terminal no tab shows still runs on through the update (the choice is the user\'s, never read from an empty set) (section B3)', async () => { const second = await keptAfterCrash([UNSAVED]) const sid = heldSessionId(UNSAVED) diff --git a/tests/unit/main/session-helper-update-handover-hooks.test.ts b/tests/unit/main/session-helper-update-handover-hooks.test.ts index 7b7293aeb..3181471c2 100644 --- a/tests/unit/main/session-helper-update-handover-hooks.test.ts +++ b/tests/unit/main/session-helper-update-handover-hooks.test.ts @@ -268,6 +268,31 @@ describe('B1f: the hook events made after an update lets go of a kept Claude Cod expect(hc.ended).toBe(false) }) + it('aicc_planning#514: the update dialog\'s count names a session still kept for its restored tab not shown, as the update keeps it for its tab again; the agent sessions\' switch off, it is not named', async () => { + const { m1, claude, hc } = await runOne() + await update(m1, [claude]) + exit(m1) + const m2 = await startedWith(makeManager(2, { serveMs: 20 })) + m2.restoredTabs([{ id: CLAUDE_TAB, cwd: CWD }]) + await until(() => !!hc.attached?.ackedCaps.includes('hooks'), 'its keeper to take hook events while its tab is not shown') + m2.noteSavedTabs([{ id: CLAUDE_TAB, label: 'Claude' }]) + // Its tab is not shown, so no terminal of this run holds it: the count + // reads what the update leaves running for a tab, not only this run's terminals. + expect([...m2.tabsKeptThroughUpdate(new Set([CLAUDE_TAB, PLAIN_TAB]))]).toEqual([CLAUDE_TAB]) + expect([...m2.tabsKeptThroughUpdate(new Set([PLAIN_TAB]))]).toEqual([]) + // With the switch off the next start would end it (keptAtStart): not counted. + m2.setRouting({ plain: false, agents: false }) + expect([...m2.tabsKeptThroughUpdate(new Set([CLAUDE_TAB]))]).toEqual([]) + m2.setRouting({ plain: false, agents: true }) + // The count let go of nothing: the update still does it, and its tab takes it over after. + expect(detaches(hc)).toBe(1) + await update(m2, []) + exit(m2) + await takenOver(3, hc) + expect(hc.ended).toBe(false) + expect(logs).toContain('[session-helper] an app update: 0 held terminal(s) are let go of, for the new version to show again; 0 kept terminal(s) are left running; 1 agent session(s) kept for their tabs stay kept for the next start') + }) + it('the update does not start (its installer could not be launched): a keeper the update let go of is kept again, and takes what its holder kept meanwhile and what comes after, once each', async () => { const { m1, claude, hc } = await runOne() await update(m1, [claude]) From 919fc26b9bbed9355374439adc7d92b4dbd5862f Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:56:46 +0000 Subject: [PATCH 38/79] fix(restore): use up the update's mark at the start that reads it (#515) The mark Save sessions writes at an update came off the saved file only when the restore saved. A new version quit before the restore's turn (the release notes still up: closeWithNoSessions leaves the file alone while the restore is to come), or one that crashed, left the mark on disk, and the next start of any newer version, even days later, restored at once with no resume prompt and no account picker. The start that reads the mark now writes the offer (the same set, without the mark) back at once (dropUpdateMarkOnDisk), before any page of the boot chain. Main's exit flush writes only what this run saved, so nothing puts the mark back. A quit or a crash before the restore then leaves a set the next start asks about, as the Feature Guide says. A set the same version reads has its mark used up the same way; a set with no mark is not written; a failed write never throws and leaves the file as it was. Co-Authored-By: Claude Opus 5.5 --- src/renderer/App.tsx | 8 ++- src/renderer/session-persistence.ts | 25 +++++++- src/shared/types.ts | 7 ++- .../renderer/app-lifecycle-wiring.test.ts | 18 ++++-- .../renderer/restore-after-update.test.tsx | 63 ++++++++++++++++++- 5 files changed, 106 insertions(+), 15 deletions(-) diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index d6275fcda..8e9492f34 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -112,7 +112,7 @@ import OnboardingModal from './components/github/onboarding/OnboardingModal' import AutoDetectBanner from './components/github/AutoDetectBanner' import { handleAutoDetectAccept } from './utils/githubAutoDetectAccept' import type { SessionState } from './types/electron' -import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, persistSessionState, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore, markSavedForUpdate, restoreOfferAtStart } from './session-persistence' +import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, persistSessionState, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore, markSavedForUpdate, restoreOfferAtStart, dropUpdateMarkOnDisk } from './session-persistence' import { useSessionAutosave, cancelSessionAutosave } from './hooks/useSessionAutosave' import { listenGoToSession } from './lib/goToSession' import { loggingConsentDue } from './utils/logging-consent' @@ -764,11 +764,13 @@ export default function App() { }) if (savedState) { // aicc_planning#515: saved for an update by an older version, it is - // restored at the prompt's turn with nothing asked; the offer never - // carries the mark, so the restore's save leaves it out. + // restored at the prompt's turn with nothing asked. The offer never + // carries the mark, and it is written back at once, so a quit or a + // crash before that turn leaves a set the next start asks about. const { offer, atOnce } = restoreOfferAtStart(savedState, __APP_VERSION__) setRestoreAtOnce(atOnce) setPendingRestore(offer) + void dropUpdateMarkOnDisk(savedState, offer) } // Nothing to ask about: nothing is restored, and what this start // brought back is the left-running registry just hydrated. diff --git a/src/renderer/session-persistence.ts b/src/renderer/session-persistence.ts index f51850223..1189998ba 100644 --- a/src/renderer/session-persistence.ts +++ b/src/renderer/session-persistence.ts @@ -372,9 +372,9 @@ export function markSavedForUpdate(state: SessionState, version: string): Sessio * RestoreAfterUpdate, restoreSavedSessions' `afterUpdate`). Anything else * (a quit's save, a crash's autosave, the same version starting again, an * older one, a mark that does not read) is offered as before. `offer` never - * carries the mark: the restore's own save, and every write while the offer - * is open, write the set without it, so a later start asks as before. A set - * with no mark is offered as it is (the same object). + * carries the mark, and the start that reads it writes the offer back at + * once (dropUpdateMarkOnDisk), so a later start asks as before. A set with + * no mark is offered as it is (the same object). */ export function restoreOfferAtStart(saved: SessionState, currentVersion: string): { offer: SessionState; atOnce: boolean } { if (saved.savedForUpdate === undefined) return { offer: saved, atOnce: false } @@ -386,6 +386,25 @@ export function restoreOfferAtStart(saved: SessionState, currentVersion: string) return { offer, atOnce } } +/** + * aicc_planning#515: the update's mark is used up by the start that reads it. + * When the saved set carried one (`offer`, from restoreOfferAtStart, is then + * not `saved`), the offer is written back as it is, without the mark, at + * once: before any page of the boot chain, and long before the restore saves. + * A quit then (closeWithNoSessions leaves the file alone while the restore is + * still to come) or a crash leaves a set the next start asks about with the + * resume prompt, whatever version starts. Best effort: a write that fails + * leaves the file as it was, and the restore's own save drops the mark. + */ +export async function dropUpdateMarkOnDisk(saved: SessionState, offer: SessionState): Promise { + if (offer === saved) return + try { + await window.electronAPI?.session?.save(offer) + } catch { + /* best-effort: the restore's own save writes the set without the mark */ + } +} + /** * The zero-session close (no dialog). rc.15 review R7: while the restore prompt * is still unanswered the saved file holds the cards AND the remotes the user diff --git a/src/shared/types.ts b/src/shared/types.ts index 6fa47e177..5fe0cb775 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -361,9 +361,10 @@ export interface SessionState { /** aicc_planning#515: written only by Save sessions on the update dialog, * with the version that saved it. A start of a NEWER version reopens such * a set with no resume prompt and no account question - * (session-persistence.ts restoreOfferAtStart); the restore's own save - * leaves it out, so a later start asks as before. Main round-trips it - * untouched, as it does detachedRemotes. */ + * (session-persistence.ts restoreOfferAtStart); the start that reads it + * writes the set back without it at once (dropUpdateMarkOnDisk), so a + * later start asks as before. Main round-trips it untouched, as it does + * detachedRemotes. */ savedForUpdate?: { fromVersion: string } } diff --git a/tests/unit/renderer/app-lifecycle-wiring.test.ts b/tests/unit/renderer/app-lifecycle-wiring.test.ts index 1c35da042..531d21807 100644 --- a/tests/unit/renderer/app-lifecycle-wiring.test.ts +++ b/tests/unit/renderer/app-lifecycle-wiring.test.ts @@ -192,17 +192,20 @@ describe('App.tsx wires the R6/R7 helpers', () => { // aicc_planning#515: what this start offers, and whether at once, is // restoreOfferAtStart's answer for the saved set and this version (its // own cases are in restore-after-update.test.tsx). - const restoreOfferAtStart = vi.fn((s: unknown, _v: string) => ({ offer: s, atOnce })) + const restoreOfferAtStart = vi.fn((s: unknown, _v: string) => ({ offer: atOnce ? { ...(s as object), unmarked: true } : s, atOnce })) + // The mark is used up by this start, whatever the offer (its own cases + // are in restore-after-update.test.tsx). + const dropUpdateMarkOnDisk = vi.fn(async () => {}) const restoreUnsettledRef = { current: true } // as the component initialises it const fn = run<() => Promise>(`async () => { ${stmt} }`, { - loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, __APP_VERSION__: '2.1.3-beta.28', + loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, dropUpdateMarkOnDisk, __APP_VERSION__: '2.1.3-beta.28', setRestoreTally, pingAllDetachedHosts, restoreUnsettledRef, console, useCommandBarStore: { getState: () => ({ reconcile }) }, useSessionStore: { getState: () => ({ sessions: [] }) }, useDetachedRemotesStore: { getState: () => ({ entries: REGISTRY }) }, window: { electronAPI: { session: { load } } }, }) await fn() - return { load, loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, setRestoreTally, pingAllDetachedHosts, reconcile, restoreUnsettledRef } + return { load, loadSavedStateAtStartup, setPendingRestore, setRestoreAtOnce, restoreOfferAtStart, dropUpdateMarkOnDisk, setRestoreTally, pingAllDetachedHosts, reconcile, restoreUnsettledRef } } const REGISTRY = [{ sessionId: 'left-1' }] const saved = { sessions: [{ id: 'a' }], activeSessionId: 'a', savedAt: 1 } @@ -212,10 +215,14 @@ describe('App.tsx wires the R6/R7 helpers', () => { expect(withCards.setPendingRestore).toHaveBeenCalledWith(saved) expect(withCards.restoreOfferAtStart).toHaveBeenCalledWith(saved, '2.1.3-beta.28') expect(withCards.setRestoreAtOnce).toHaveBeenCalledWith(false) - // aicc_planning#515: saved for an update by an older version: offered at once. + expect(withCards.dropUpdateMarkOnDisk).toHaveBeenCalledWith(saved, saved) + // aicc_planning#515: saved for an update by an older version: offered at + // once, and the offer (no mark) is what the start writes back at once. const atOnce = await go(saved, false, true) expect(atOnce.setRestoreAtOnce).toHaveBeenCalledWith(true) - expect(atOnce.setPendingRestore).toHaveBeenCalledWith(saved) + expect(atOnce.setPendingRestore).toHaveBeenCalledWith({ ...saved, unmarked: true }) + expect(atOnce.dropUpdateMarkOnDisk).toHaveBeenCalledTimes(1) + expect(atOnce.dropUpdateMarkOnDisk).toHaveBeenCalledWith(saved, { ...saved, unmarked: true }) expect(withCards.restoreUnsettledRef.current, 'cleared once the load resolved with cards').toBe(false) const deps = withCards.loadSavedStateAtStartup.mock.calls[0][0] as { pingHosts: () => void; reconcile: () => void } deps.pingHosts(); expect(withCards.pingAllDetachedHosts).toHaveBeenCalledTimes(1) @@ -227,6 +234,7 @@ describe('App.tsx wires the R6/R7 helpers', () => { const without = await go(null) expect(without.setPendingRestore).not.toHaveBeenCalled() expect(without.setRestoreAtOnce).not.toHaveBeenCalled() + expect(without.dropUpdateMarkOnDisk).not.toHaveBeenCalled() expect(without.setRestoreTally).toHaveBeenCalledWith({ sessions: [], detached: REGISTRY }) expect(without.restoreUnsettledRef.current, 'cleared once the load resolved with no cards').toBe(false) // The load FAILED: the ref stays true so a zero-session close leaves the file. diff --git a/tests/unit/renderer/restore-after-update.test.tsx b/tests/unit/renderer/restore-after-update.test.tsx index 716dd4554..9a77bc343 100644 --- a/tests/unit/renderer/restore-after-update.test.tsx +++ b/tests/unit/renderer/restore-after-update.test.tsx @@ -17,7 +17,7 @@ import type { SessionState, SavedSession } from '../../../src/shared/types' ;(globalThis as any).window = (globalThis as any).window ?? {} ;(globalThis as any).window.electronAPI = { ...((globalThis as any).window?.electronAPI ?? {}) } -const { markSavedForUpdate, restoreOfferAtStart, buildSessionState } = await import('../../../src/renderer/session-persistence') +const { markSavedForUpdate, restoreOfferAtStart, buildSessionState, dropUpdateMarkOnDisk, loadSavedStateAtStartup, closeWithNoSessions } = await import('../../../src/renderer/session-persistence') const { useSessionStore } = await import('../../../src/renderer/stores/sessionStore') const RestoreAfterUpdate = (await import('../../../src/renderer/components/RestoreAfterUpdate')).default @@ -83,6 +83,67 @@ describe('restoreOfferAtStart', () => { }) }) +describe('the start that reads the mark uses it up (dropUpdateMarkOnDisk)', () => { + /** The saved file as main's session:load and session:save see it. */ + function fileApi(initial: SessionState | null) { + const disk = { file: initial } + const api = { + save: vi.fn(async (s: SessionState) => { disk.file = structuredClone(s); return true }), + clear: vi.fn(async () => { disk.file = null }), + load: vi.fn(async () => (disk.file ? structuredClone(disk.file) : null)), + } + ;(window as any).electronAPI.session = api + return { disk, api } + } + const startWith = async (api: { load: () => Promise }, version: string) => { + const loaded = await loadSavedStateAtStartup({ load: api.load, pingHosts: () => {}, reconcile: () => {} }) + return { loaded: loaded!, ...restoreOfferAtStart(loaded!, version) } + } + const quitBeforeTheRestore = () => closeWithNoSessions({ restorePromptPending: true, cancelAutosave: () => {}, flush: async () => {}, allowClose: () => {} }) + + it('an at-once start writes the set back without the mark at once: a quit before the restore (the release notes still up), or a crash, leaves a set every later start asks about', async () => { + const { disk, api } = fileApi(markSavedForUpdate(saved(), '2.1.3-beta.27')) + const first = await startWith(api, '2.1.3-beta.28') + expect(first.atOnce).toBe(true) + await dropUpdateMarkOnDisk(first.loaded, first.offer) + expect(api.save).toHaveBeenCalledTimes(1) + expect(disk.file).toEqual(saved()) + expect(disk.file).not.toHaveProperty('savedForUpdate') + // A quit while the restore is still to come leaves the file as it is. + expect(await quitBeforeTheRestore()).toBe('left-untouched') + // The same version again, and a later one days on: the resume prompt. + for (const version of ['2.1.3-beta.28', '2.1.3-beta.29']) { + const again = await startWith(api, version) + expect(again.atOnce, version).toBe(false) + expect(again.offer, version).toEqual(saved()) + } + }) + + it('a marked set the same version reads (no at-once restore) has its mark used up too', async () => { + const { disk, api } = fileApi(markSavedForUpdate(saved(), '2.1.3-beta.28')) + const first = await startWith(api, '2.1.3-beta.28') + expect(first.atOnce).toBe(false) + await dropUpdateMarkOnDisk(first.loaded, first.offer) + expect(disk.file).not.toHaveProperty('savedForUpdate') + expect((await startWith(api, '2.1.3-beta.29')).atOnce).toBe(false) + }) + + it('a set with no mark is not written at the start', async () => { + const { api } = fileApi(saved()) + const first = await startWith(api, '2.1.3-beta.28') + await dropUpdateMarkOnDisk(first.loaded, first.offer) + expect(api.save).not.toHaveBeenCalled() + }) + + it('a write that fails never throws, and the file is as it was', async () => { + const { disk, api } = fileApi(markSavedForUpdate(saved(), '2.1.3-beta.27')) + api.save.mockRejectedValueOnce(new Error('the disk is full')) + const first = await startWith(api, '2.1.3-beta.28') + await expect(dropUpdateMarkOnDisk(first.loaded, first.offer)).resolves.toBeUndefined() + expect(disk.file).toHaveProperty('savedForUpdate') + }) +}) + describe('RestoreAfterUpdate', () => { it('restores once and shows nothing, also when React runs its effects twice', () => { const onRestore = vi.fn() From 385292db9d193b072966fe30711fb917f6667ce6 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:00:51 +0000 Subject: [PATCH 39/79] fix(update): count only SSH sessions that really keep running on their hosts (#514) The dialogs' SSH line read the config and a few run-state marks, so an SSH Persistent tab that runs nothing on its host still counted as keeping running and reconnecting: a tab that started nothing (Not started: its provider off, its launch refused), and a restored tab whose remote session the restore's probe confirmed gone and that has not started again. Both are left out now. A gone tab that has started again inside tmux still counts: the wrapper's fresh branch made it a new session there (ssh-tmux.ts), which a quit or an update leaves running as any other. The config part was a renderer copy of main's rule. persistentTab moves to src/shared/ssh-persistent.ts, and main's route (route.ts, remote-helper index.ts) and the dialogs (closeDialogText.ts) all import that one function, so the two cannot drift. Co-Authored-By: Claude Opus 5.5 --- src/main/remote-helper/index.ts | 5 +- src/main/remote-helper/route.ts | 11 +---- src/renderer/utils/closeDialogText.ts | 30 ++++++++---- src/shared/ssh-persistent.ts | 14 ++++++ .../route-plain-terminal.test.ts | 3 +- tests/unit/renderer/close-dialog-text.test.ts | 47 ++++++++++++++++++- 6 files changed, 88 insertions(+), 22 deletions(-) create mode 100644 src/shared/ssh-persistent.ts diff --git a/src/main/remote-helper/index.ts b/src/main/remote-helper/index.ts index 0f73bc489..74e57bff9 100644 --- a/src/main/remote-helper/index.ts +++ b/src/main/remote-helper/index.ts @@ -69,7 +69,8 @@ import { tryGetProvider } from '../providers' import { colorFgBgValue, resolveHostColorScheme } from '../providers/host-color-scheme' import type { HeldScreenRows, PasteKey, ProviderRemoteLaunch, RemoteAccounts, RemoteHelperCommands, RemoteHostFile, RemoteLaunchOptions, SessionProvider } from '../providers/types' import type { SSHOptions } from '../ssh-options' -import { HELPER_ONLY_STEP, ROUTE_WHY, helperPostConnect, persistentTab, routeSshTab, type PersistentStanding, type Route } from './route' +import { HELPER_ONLY_STEP, ROUTE_WHY, helperPostConnect, routeSshTab, type PersistentStanding, type Route } from './route' +import { persistentTab } from '../../shared/ssh-persistent' import { NoticePty, RemoteDriver, RemoteHelperPty, newSudoToken, remoteCwd, remoteHelperCommands, remoteLaunchSpec, remotePlainLaunchSpec, remoteSessionId, type PlainTerminal, type RemoteLaunchPlan, type RemoteTabAccount, type SudoLaunch } from './session' import { sudoSecretFits, type LaunchSpec } from '../session-helper/protocol' import { isContainerRuntime, parseDockerPostCommand } from '../../shared/container-command' @@ -624,7 +625,7 @@ export function remoteHelperPty(win: OutputWindow, sessionId: string, options: R } catch { settings = null } - // 2.1.3-beta.26 (planning #485): a plain terminal is never kept (route.ts persistentTab). + // 2.1.3-beta.26 (planning #485): a plain terminal is never kept (shared/ssh-persistent.ts persistentTab). const persistent = persistentTab(ssh, options.shellOnly === true) // A tab's mark (2.1.3-beta.19): its saved record's, or its last start's this run. const marked = persistent && (options.remoteVia === 'helper' || lastPath.get(sessionId) === 'kept') diff --git a/src/main/remote-helper/route.ts b/src/main/remote-helper/route.ts index 334d672cb..9f9eb72aa 100644 --- a/src/main/remote-helper/route.ts +++ b/src/main/remote-helper/route.ts @@ -133,6 +133,7 @@ import { composeRuntimeCommand, isContainerRuntime, parseDockerPostCommand } fro import type { SSHOptions } from '../ssh-options' import { logoutCleanUp, type RemoteMachineRecord } from './machines' import { callsSudoByName, postCommandOpensShell } from '../../shared/post-connect-shape' +import { persistentTab } from '../../shared/ssh-persistent' import type { HolderKind } from './scripts' import { PASSWORD_SIGN_IN_ABSENT } from './askpass' @@ -324,7 +325,7 @@ export const MARKED_STEP = { export function routeSshTab(i: RouteInput): Route { const ssh = i.ssh // 2.1.3-beta.26 (planning #485): a plain terminal is never kept, whatever - // its config's Connection says (persistentTab). + // its config's Connection says (shared/ssh-persistent.ts persistentTab). const persistent = persistentTab(ssh, i.shellOnly) const marked = persistent && i.standing?.marked === true const helperOnly = i.helperOnly === true @@ -422,14 +423,6 @@ export function routeSshTab(i: RouteInput): Route { return { via: 'helper', machine: i.machine, kind: persistent ? 'until-ended' : 'away' } } -/** Whether a tab is SSH Persistent as the route counts it: its config's - * Connection (no `detachable` value, or true), and not a plain terminal - * (2.1.3-beta.26, planning #485: a Terminal only tab or a partner terminal - * ends with its tab, as its plain connection does on the usual path). */ -export function persistentTab(ssh: Pick, shellOnly: boolean): boolean { - return ssh.detachable !== false && !shellOnly -} - /** * planning #488's review (NIT): the one line a Terminal only tab shows when * its container entry returns, before its login shell on the machine takes diff --git a/src/renderer/utils/closeDialogText.ts b/src/renderer/utils/closeDialogText.ts index ebce1c0b3..b9d043121 100644 --- a/src/renderer/utils/closeDialogText.ts +++ b/src/renderer/utils/closeDialogText.ts @@ -1,4 +1,5 @@ import type { UpdateKeepCounts, UpdateKeepTabs } from '../../shared/update-keep' +import { persistentTab } from '../../shared/ssh-persistent' /** * aicc_planning#514: what the close and update dialogs say each choice does @@ -32,23 +33,34 @@ export interface CloseDialogTab { remoteVia?: 'helper' remoteNotKept?: true remoteAnchored?: true + neverStarted?: boolean + sshRemoteReattachGone?: boolean } /** * An SSH tab whose session keeps running on its host when the app closes or - * updates, by the app's own rule for SSH Persistent: its config's Connection + * updates, by the app's own rule for SSH Persistent, the one main's route + * goes by (shared/ssh-persistent.ts persistentTab): its config's Connection * (a config that never chose one is SSH Persistent: `detachable` absent or - * true), and not a Terminal only tab (remote-helper/route.ts persistentTab). - * What its start said wins over the config: kept by the session helper there - * (remoteVia), not kept by that machine or ending with its connection - * (remoteNotKept, remoteAnchored), or on the usual path without tmux - * (sshTmuxPersistent false). + * true), and not a Terminal only tab. What its tab runs wins over the + * config: + * - kept by the session helper there (remoteVia), not kept by that machine + * or ending with its connection (remoteNotKept, remoteAnchored), or on the + * usual path without tmux (sshTmuxPersistent false); + * - a tab that started nothing (neverStarted: its provider off, its launch + * refused) runs nothing on its host; + * - a restored tab whose remote session the restore's probe confirmed gone + * (sshRemoteReattachGone) runs nothing there until it starts again. Once + * it has, inside tmux (sshTmuxPersistent true), it is a new session there + * (ssh-tmux.ts: the wrapper's fresh branch makes one when the old one is + * gone), which a quit or an update leaves running as any other. */ export function sshKeepsRunning(t: CloseDialogTab): boolean { - if (t.sessionType !== 'ssh' || !t.sshConfig || t.shellOnly || t.transient) return false + if (t.sessionType !== 'ssh' || !t.sshConfig || t.transient || t.neverStarted) return false if (t.remoteNotKept || t.remoteAnchored) return false - if (t.remoteVia === 'helper') return true - return t.sshConfig.detachable !== false && t.sshTmuxPersistent !== false + if (t.remoteVia === 'helper') return !t.shellOnly + if (t.sshRemoteReattachGone && t.sshTmuxPersistent !== true) return false + return persistentTab(t.sshConfig, t.shellOnly === true) && t.sshTmuxPersistent !== false } /** The update dialog's question to main: the open local tabs that are saved diff --git a/src/shared/ssh-persistent.ts b/src/shared/ssh-persistent.ts new file mode 100644 index 000000000..1c0cd171d --- /dev/null +++ b/src/shared/ssh-persistent.ts @@ -0,0 +1,14 @@ +// The SSH Persistent rule for a tab, shared by main's route +// (main/remote-helper/route.ts, remote-helper/index.ts) and the close and +// update dialogs (renderer/utils/closeDialogText.ts, aicc_planning#514), so +// what the dialogs say keeps running on a host is the rule main goes by, not +// a copy of it. Pure and dependency-free. No default export (project +// convention). + +/** Whether a tab is SSH Persistent by its config and kind: its config's + * Connection (no `detachable` value, or true), and not a plain terminal + * (2.1.3-beta.26, planning #485: a Terminal only tab or a partner terminal + * ends with its tab, as its plain connection does on the usual path). */ +export function persistentTab(ssh: { detachable?: boolean }, shellOnly: boolean): boolean { + return ssh.detachable !== false && !shellOnly +} diff --git a/tests/unit/remote-helper/route-plain-terminal.test.ts b/tests/unit/remote-helper/route-plain-terminal.test.ts index 2b57d4c99..8e5f080eb 100644 --- a/tests/unit/remote-helper/route-plain-terminal.test.ts +++ b/tests/unit/remote-helper/route-plain-terminal.test.ts @@ -17,7 +17,8 @@ * never by an argument, and nothing of any provider. */ import { describe, it, expect } from 'vitest' -import { CONTAINER_LEFT, HELPER_ONLY_STEP, HELPER_ONLY_WHY, PASSWORD_SIGN_IN_ABSENT, PLAIN_WHY, ROUTE_WHY, helperPostConnect, persistentTab, routeSshTab, type PersistentStanding, type RouteInput } from '../../../src/main/remote-helper/route' +import { CONTAINER_LEFT, HELPER_ONLY_STEP, HELPER_ONLY_WHY, PASSWORD_SIGN_IN_ABSENT, PLAIN_WHY, ROUTE_WHY, helperPostConnect, routeSshTab, type PersistentStanding, type RouteInput } from '../../../src/main/remote-helper/route' +import { persistentTab } from '../../../src/shared/ssh-persistent' import { HOLDER_LAUNCH_FAILED, POST_CONNECT_ENV, POST_CONNECT_WRAPPER, SUDO_STEP, forgetOnBash, heldLaunchFailed, postConnectStopGuard, remotePlainLaunchSpec } from '../../../src/main/remote-helper/session' import { plainTerminalOf } from '../../../src/main/remote-helper' import { checkLaunch } from '../../../src/main/session-helper/protocol' diff --git a/tests/unit/renderer/close-dialog-text.test.ts b/tests/unit/renderer/close-dialog-text.test.ts index 6a0add3b5..9f05c4e89 100644 --- a/tests/unit/renderer/close-dialog-text.test.ts +++ b/tests/unit/renderer/close-dialog-text.test.ts @@ -4,8 +4,21 @@ * kind of tab open, with its count; a kind with none open has no line; the * update dialog's kept count is main's answer, never the renderer's guess. */ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' +import fs from 'fs' +import path from 'path' + +// The shared SSH Persistent rule, as main's route reads it, watched: the +// dialog must go by this function, not by a copy of its rule. +vi.mock('../../../src/shared/ssh-persistent', async (actual) => { + const real = await actual() + return { persistentTab: vi.fn(real.persistentTab) } +}) + import { closeDialogCounts, closeDialogText, sshKeepsRunning, updateKeepQuestion, type CloseDialogTab } from '../../../src/renderer/utils/closeDialogText' +import { persistentTab } from '../../../src/shared/ssh-persistent' + +const readSrc = (rel: string) => fs.readFileSync(path.resolve(process.cwd(), rel), 'utf8').replace(/\r\n/g, '\n') let n = 0 const id = () => `tab-${++n}` @@ -37,6 +50,38 @@ describe('sshKeepsRunning: the SSH Persistent rule', () => { expect(sshKeepsRunning(sshPersistent({ remoteAnchored: true }))).toBe(false) expect(sshKeepsRunning(sshPersistent({ sshTmuxPersistent: false }))).toBe(false) }) + it('a tab that started nothing (neverStarted: its provider off, its launch refused) runs nothing on its host, and is not counted as keeping running', () => { + expect(sshKeepsRunning(sshPersistent({ neverStarted: true }))).toBe(false) + expect(sshKeepsRunning(sshPersistent({ neverStarted: true, remoteVia: 'helper' }))).toBe(false) + expect(closeDialogCounts('update', [sshPersistent({ neverStarted: true }), sshPersistent()], none).ssh).toBe(1) + expect(closeDialogCounts('close', [sshPersistent({ neverStarted: true })], none).ssh).toBe(0) + }) + it('a restored tab whose remote session the probe confirmed gone runs nothing there until it starts again; started again inside tmux, it is a new session there, which keeps running', () => { + expect(sshKeepsRunning(sshPersistent({ sshRemoteReattachGone: true }))).toBe(false) + expect(sshKeepsRunning(sshPersistent({ sshRemoteReattachGone: true, sshTmuxPersistent: false }))).toBe(false) + expect(sshKeepsRunning(sshPersistent({ sshRemoteReattachGone: true, sshTmuxPersistent: true }))).toBe(true) + expect(closeDialogCounts('update', [sshPersistent({ sshRemoteReattachGone: true }), sshPersistent()], none).ssh).toBe(1) + }) + it("the config part is main's own rule (shared/ssh-persistent.ts persistentTab), not a copy of it", () => { + for (const config of [{}, { detachable: true }, { detachable: false }]) { + for (const shellOnly of [false, true]) { + expect(sshKeepsRunning(sshPersistent({ sshConfig: config, shellOnly })), JSON.stringify({ config, shellOnly })).toBe(persistentTab(config, shellOnly)) + } + } + // The dialog asks the shared function itself: what it answers, the dialog says. + const rule = vi.mocked(persistentTab) + rule.mockClear() + rule.mockReturnValueOnce(false) + expect(sshKeepsRunning(sshPersistent({ sshConfig: {} }))).toBe(false) + expect(rule).toHaveBeenCalledWith({}, false) + rule.mockReturnValueOnce(true) + expect(sshKeepsRunning(sshPersistent({ sshConfig: { detachable: false } }))).toBe(true) + // And main's route has no copy of its own. + const route = readSrc('src/main/remote-helper/route.ts') + expect(route).not.toMatch(/function persistentTab[(]/) + expect(route).toContain("import { persistentTab } from '../../shared/ssh-persistent'") + expect(readSrc('src/main/remote-helper/index.ts')).toContain("import { persistentTab } from '../../shared/ssh-persistent'") + }) }) describe('updateKeepQuestion: what the dialog asks main about', () => { From c8d58502d0376aaec752067686d448978c259c77 Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:04:01 +0000 Subject: [PATCH 40/79] fix(update): name Save sessions in the dialogs and say each outcome plainly (#514) Both dialogs now open their lines with "With Save sessions:", so what follows reads as that button's outcome, and the last line starts with "Close sessions": each half names its button. The wording follows the ticket and the UX review: - kept: "N keep running through the update and come back in the same tabs" (one: "comes back in its tab"), not "are back straight away": the new version shows its release notes first, and a tab not on screen takes its session over once it is shown. - one tab open starts its line with "It", every tab of one kind with "All N", as the Close sessions line already did. - "ends" is the Close sessions verb only. A quit's Save lines say the sessions "stop now and pick up their conversations at the next launch"; terminals "close and open again as new terminals at the next launch". - at an update, terminals "restart as new terminals": one verb, restart, for all the update interrupts. - sign-in or install tabs "close and do not come back". - Close sessions says the tabs close: "ends it and closes its tab", "ends all N and closes their tabs". - both dialogs list what keeps running first, then what stops. Departures from the ticket's plan, with evidence: - "Close sessions: all end" is not what happens to an SSH Persistent tab: its tab closes and its session keeps running on its host, as before. The quit's teardown detaches tmux instead of exiting (pty-manager.ts gracefulExitPty), and RemoteHelperPty.kill lets go of a kept remote (remote-helper/session.ts). The dialog keeps saying so. - "restart and pick up their conversations" holds for local Claude Code tabs (session-resume-enrich.ts saves the conversation) and local Codex tabs (pty-manager.ts keptCodexConversations, saved the same way). It does not hold for an SSH tab that is not SSH Persistent: on the usual path the first start after a relaunch is not a reconnect, so its launch carries neither --continue nor --resume (claudeCmdWith; sshReachedClaudeRunning is never saved). Those tabs get their own line, "N SSH sessions restart" (a quit: "stop now and start again at the next launch"), which promises no conversation. The ticket's "a Claude Code tab picks its conversation up again" is not used: it is untrue for such an SSH tab too, and leaves Codex out. Co-Authored-By: Claude Opus 5.5 --- src/renderer/components/CloseDialog.tsx | 6 +- src/renderer/utils/closeDialogText.ts | 149 +++++++++++++++--- tests/unit/renderer/close-dialog-text.test.ts | 141 ++++++++++++----- .../renderer/close-dialogs-tokens.test.tsx | 26 +-- 4 files changed, 249 insertions(+), 73 deletions(-) diff --git a/src/renderer/components/CloseDialog.tsx b/src/renderer/components/CloseDialog.tsx index b9f50b2ef..c49a8a67f 100644 --- a/src/renderer/components/CloseDialog.tsx +++ b/src/renderer/components/CloseDialog.tsx @@ -43,8 +43,9 @@ function useKeptThroughUpdate(mode: 'close' | 'update', tabs: ReadonlyArray {text && (
+

{text.lead}

{text.lines.map((line) =>

{line}

)}

{text.close}

diff --git a/src/renderer/utils/closeDialogText.ts b/src/renderer/utils/closeDialogText.ts index b9d043121..5b9ccbd70 100644 --- a/src/renderer/utils/closeDialogText.ts +++ b/src/renderer/utils/closeDialogText.ts @@ -3,8 +3,11 @@ import { persistentTab } from '../../shared/ssh-persistent' /** * aicc_planning#514: what the close and update dialogs say each choice does - * to the tabs open now, with counts, in plain lines. Each tab is in exactly - * one kind, and a kind with none open has no line. + * to the tabs open now, with counts, in plain lines: a lead-in that names + * Save sessions, a line for each kind of tab open (what Save sessions does + * to it), then one for Close sessions, so the two halves mirror the two + * buttons. Each tab is in exactly one kind, a kind with none open has no + * line, and what keeps running comes before what stops, in both dialogs. * * - kept (update only): its own session is held by the session helper and an * update keeps it running, for the new version's tab to take over. Main @@ -16,10 +19,18 @@ import { persistentTab } from '../../shared/ssh-persistent' * Persistent tab, which a quit or an update detaches from, and the next * start reattaches to. Close sessions leaves them running too: their tabs * close, but nothing ends them on the host. - * - the rest of the Claude Code and Codex tabs: they restart and pick up - * their conversations; - * - the rest of the Terminal only tabs: they start again; - * - a sign-in or install tab (transient): never saved, it ends. + * - the rest of the local Claude Code and Codex tabs: they restart and pick + * up their conversations (the conversation the app saved for each: a + * Claude Code tab's by session-resume-enrich.ts, a Codex tab's by its kept + * conversation, pty-manager.ts keptCodexConversations). + * - the rest of the SSH tabs that are not Terminal only: they restart, and + * nothing is promised of their conversation: on the usual SSH path the + * first start after a relaunch is not a reconnect, so its launch carries + * neither --continue nor --resume (pty-manager.ts claudeCmdWith; the mark + * it reads, sshReachedClaudeRunning, is never saved). + * - the rest of the Terminal only tabs: each restarts as a new terminal. + * - a sign-in or install tab (transient): never saved, it closes and does not + * come back. */ /** What the dialogs read of an open tab (a sessionStore Session is one). */ @@ -80,6 +91,7 @@ export interface CloseDialogCounts { kept: number ssh: number resume: number + sshRestart: number fresh: number oneOff: number } @@ -93,12 +105,14 @@ export function closeDialogCounts(mode: 'close' | 'update', tabs: ReadonlyArray< const keptTerminals = mode === 'update' ? Math.min(Math.max(0, kept.terminals), question.terminals.length) : 0 let ssh = 0 let agents = 0 + let sshRestart = 0 let terminals = 0 let oneOff = 0 for (const t of tabs) { if (t.transient) oneOff++ else if (sshKeepsRunning(t)) ssh++ else if (t.shellOnly) terminals++ + else if (t.sessionType === 'ssh') sshRestart++ else agents++ } return { @@ -106,41 +120,134 @@ export function closeDialogCounts(mode: 'close' | 'update', tabs: ReadonlyArray< kept: keptAgents + keptTerminals, ssh, resume: agents - keptAgents, + sshRestart, fresh: terminals - keptTerminals, oneOff, } } -/** The dialog's text: one line per kind with any open (what Save sessions - * does), then what Close sessions does. */ +/** The dialog's text: the lead-in, one line per kind with any open (what + * Save sessions does), then what Close sessions does. */ export interface CloseDialogText { + lead: string lines: string[] close: string } +/** One kind's line in its four shapes: `one` and `many` ({n}, the count) in + * a set of several kinds; `it` when the one tab open is of this kind; `all` + * ({n}) when every tab open, two or more, is. */ +interface KindLine { + one: string + many: string + it: string + all: string +} + +const UPDATE_LINES = { + kept: { + one: '1 keeps running through the update and comes back in its tab.', + many: '{n} keep running through the update and come back in the same tabs.', + it: 'It keeps running through the update and comes back in its tab.', + all: 'All {n} keep running through the update and come back in the same tabs.', + }, + ssh: { + one: '1 SSH session keeps running on its host and reconnects.', + many: '{n} SSH sessions keep running on their hosts and reconnect.', + it: 'It keeps running on its host and reconnects.', + all: 'All {n} SSH sessions keep running on their hosts and reconnect.', + }, + resume: { + one: '1 restarts and picks up its conversation.', + many: '{n} restart and pick up their conversations.', + it: 'It restarts and picks up its conversation.', + all: 'All {n} restart and pick up their conversations.', + }, + sshRestart: { + one: '1 SSH session restarts.', + many: '{n} SSH sessions restart.', + it: 'It restarts.', + all: 'All {n} SSH sessions restart.', + }, + fresh: { + one: '1 terminal restarts as a new terminal.', + many: '{n} terminals restart as new terminals.', + it: 'It restarts as a new terminal.', + all: 'All {n} terminals restart as new terminals.', + }, +} satisfies Record + +const QUIT_LINES = { + ssh: { + one: '1 SSH session keeps running on its host and reconnects at the next launch.', + many: '{n} SSH sessions keep running on their hosts and reconnect at the next launch.', + it: 'It keeps running on its host and reconnects at the next launch.', + all: 'All {n} SSH sessions keep running on their hosts and reconnect at the next launch.', + }, + resume: { + one: '1 stops now and picks up its conversation at the next launch.', + many: '{n} stop now and pick up their conversations at the next launch.', + it: 'It stops now and picks up its conversation at the next launch.', + all: 'All {n} stop now and pick up their conversations at the next launch.', + }, + sshRestart: { + one: '1 SSH session stops now and starts again at the next launch.', + many: '{n} SSH sessions stop now and start again at the next launch.', + it: 'It stops now and starts again at the next launch.', + all: 'All {n} SSH sessions stop now and start again at the next launch.', + }, + fresh: { + one: '1 terminal closes and opens again as a new terminal at the next launch.', + many: '{n} terminals close and open again as new terminals at the next launch.', + it: 'It closes and opens again as a new terminal at the next launch.', + all: 'All {n} terminals close and open again as new terminals at the next launch.', + }, +} satisfies Record + +const ONE_OFF_LINE: KindLine = { + one: '1 sign-in or install tab closes and does not come back.', + many: '{n} sign-in or install tabs close and do not come back.', + it: 'It closes and does not come back.', + all: 'All {n} sign-in or install tabs close and do not come back.', +} + +/** The lead-in, with the button's own name, so the lines below it read as + * what that button does. */ +export const SAVE_SESSIONS_LEAD = 'With Save sessions:' + export function closeDialogText(mode: 'close' | 'update', tabs: ReadonlyArray, kept: UpdateKeepCounts): CloseDialogText { const c = closeDialogCounts(mode, tabs, kept) const lines: string[] = [] - const say = (n: number, one: string, many: string) => { if (n > 0) lines.push(n === 1 ? one : many.replace('{n}', String(n))) } + const say = (n: number, w: KindLine) => { + if (n <= 0) return + const shape = c.total === 1 ? w.it : n === c.total ? w.all : n === 1 ? w.one : w.many + lines.push(shape.replace('{n}', String(n))) + } + // What keeps running first, then what stops. if (mode === 'update') { - say(c.kept, '1 keeps running through the update and is back in its tab straight away.', '{n} keep running through the update and are back in their tabs straight away.') - say(c.ssh, '1 SSH session keeps running on its host and reconnects.', '{n} SSH sessions keep running on their hosts and reconnect.') - say(c.resume, '1 restarts and picks up its conversation.', '{n} restart and pick up their conversations.') - say(c.fresh, '1 terminal starts again.', '{n} terminals start again.') + say(c.kept, UPDATE_LINES.kept) + say(c.ssh, UPDATE_LINES.ssh) + say(c.resume, UPDATE_LINES.resume) + say(c.sshRestart, UPDATE_LINES.sshRestart) + say(c.fresh, UPDATE_LINES.fresh) } else { - say(c.resume, '1 ends and picks up its conversation at the next launch.', '{n} end and pick up their conversations at the next launch.') - say(c.ssh, '1 SSH session keeps running on its host and reconnects at the next launch.', '{n} SSH sessions keep running on their hosts and reconnect at the next launch.') - say(c.fresh, '1 terminal ends and starts again at the next launch.', '{n} terminals end and start again at the next launch.') + say(c.ssh, QUIT_LINES.ssh) + say(c.resume, QUIT_LINES.resume) + say(c.sshRestart, QUIT_LINES.sshRestart) + say(c.fresh, QUIT_LINES.fresh) } - say(c.oneOff, '1 sign-in or install tab ends.', '{n} sign-in or install tabs end.') - return { lines, close: closeLine(c) } + say(c.oneOff, ONE_OFF_LINE) + return { lead: SAVE_SESSIONS_LEAD, lines, close: closeLine(c) } } -/** Close sessions ends every tab's session, but an SSH Persistent one: its - * tab closes and its session keeps running on its host. */ +/** Close sessions ends every tab's session and closes its tab, but an SSH + * Persistent one: its tab closes and its session keeps running on its host + * (a quit's or an update's teardown detaches tmux, pty-manager.ts + * gracefulExitPty, and lets go of a kept remote, remote-helper/session.ts + * RemoteHelperPty.kill). */ function closeLine(c: CloseDialogCounts): string { const ends = c.total - c.ssh - if (c.ssh === 0) return c.total === 1 ? 'Close sessions ends it.' : `Close sessions ends all ${c.total}.` + if (c.ssh === 0) return c.total === 1 ? 'Close sessions ends it and closes its tab.' : `Close sessions ends all ${c.total} and closes their tabs.` const running = c.ssh === 1 ? 'the SSH session keeps running on its host' : `the ${c.ssh} SSH sessions keep running on their hosts` if (ends > 0) return `Close sessions ends ${ends} and closes every tab; ${running}.` return `Close sessions closes ${c.total === 1 ? 'its tab' : 'every tab'}; ${running}.` diff --git a/tests/unit/renderer/close-dialog-text.test.ts b/tests/unit/renderer/close-dialog-text.test.ts index 9f05c4e89..18e541f93 100644 --- a/tests/unit/renderer/close-dialog-text.test.ts +++ b/tests/unit/renderer/close-dialog-text.test.ts @@ -27,6 +27,8 @@ const terminal = (extra: Partial = {}): CloseDialogTab => ({ id: /** An SSH Persistent tab: its config never chose a Connection. */ const sshPersistent = (extra: Partial = {}): CloseDialogTab => ({ id: id(), sessionType: 'ssh', sshConfig: {}, ...extra }) const signIn = (): CloseDialogTab => ({ id: id(), sessionType: 'local', shellOnly: true, transient: true }) +/** An SSH tab whose config ends with its connection (not SSH Persistent). */ +const sshPlain = (extra: Partial = {}): CloseDialogTab => ({ id: id(), sessionType: 'ssh', sshConfig: { detachable: false }, ...extra }) const many = (count: number, make: () => T): T[] => Array.from({ length: count }, make) const none = { agents: 0, terminals: 0 } @@ -93,79 +95,139 @@ describe('updateKeepQuestion: what the dialog asks main about', () => { }) }) +describe('the lead-in', () => { + it("names Save sessions with the button's own words, in both dialogs, so the lines below read as what that button does", () => { + for (const mode of ['close', 'update'] as const) { + expect(closeDialogText(mode, [agent()], none).lead).toBe('With Save sessions:') + } + }) +}) + describe('the update dialog', () => { - it('the example: 4 kept, 3 SSH Persistent, 2 restart, each kind its own line, in that order', () => { - const tabs = [...many(6, () => agent()), ...many(3, () => sshPersistent())] + it("the owner's case: 4 kept, 3 SSH Persistent, each kind its own line, then the Close sessions line", () => { + const tabs = [...many(4, () => agent()), ...many(3, () => sshPersistent())] const text = closeDialogText('update', tabs, { agents: 4, terminals: 0 }) + expect(text.lead).toBe('With Save sessions:') expect(text.lines).toEqual([ - '4 keep running through the update and are back in their tabs straight away.', + '4 keep running through the update and come back in the same tabs.', '3 SSH sessions keep running on their hosts and reconnect.', - '2 restart and pick up their conversations.', ]) + expect(text.close).toBe('Close sessions ends 4 and closes every tab; the 3 SSH sessions keep running on their hosts.') }) - it('kept counts both kinds; the Terminal only tabs not kept start again', () => { - const tabs = [...many(2, () => agent()), ...many(5, () => terminal())] - expect(closeDialogText('update', tabs, { agents: 2, terminals: 3 }).lines).toEqual([ - '5 keep running through the update and are back in their tabs straight away.', - '2 terminals start again.', + it('what keeps running first, then what stops: kept, SSH Persistent, restart, SSH restart, terminals, sign-in or install tabs', () => { + const tabs = [...many(4, () => agent()), ...many(2, () => sshPersistent()), ...many(2, () => sshPlain()), ...many(3, () => terminal()), signIn(), signIn()] + expect(closeDialogText('update', tabs, { agents: 2, terminals: 1 }).lines).toEqual([ + '3 keep running through the update and come back in the same tabs.', + '2 SSH sessions keep running on their hosts and reconnect.', + '2 restart and pick up their conversations.', + '2 SSH sessions restart.', + '2 terminals restart as new terminals.', + '2 sign-in or install tabs close and do not come back.', ]) }) - it('one of a kind reads in the singular', () => { - const tabs = [agent(), agent(), terminal(), sshPersistent(), signIn()] + it('one of a kind, among several tabs, reads in the singular', () => { + const tabs = [agent(), agent(), terminal(), sshPersistent(), sshPlain(), signIn()] expect(closeDialogText('update', tabs, { agents: 1, terminals: 0 }).lines).toEqual([ - '1 keeps running through the update and is back in its tab straight away.', + '1 keeps running through the update and comes back in its tab.', '1 SSH session keeps running on its host and reconnects.', '1 restarts and picks up its conversation.', - '1 terminal starts again.', - '1 sign-in or install tab ends.', + '1 SSH session restarts.', + '1 terminal restarts as a new terminal.', + '1 sign-in or install tab closes and does not come back.', + ]) + }) + + it('one tab open: the line starts with It, as the Close sessions line does', () => { + const one = (tab: CloseDialogTab, kept = none) => closeDialogText('update', [tab], kept) + expect(one(agent(), { agents: 1, terminals: 0 }).lines).toEqual(['It keeps running through the update and comes back in its tab.']) + expect(one(agent()).lines).toEqual(['It restarts and picks up its conversation.']) + expect(one(sshPersistent()).lines).toEqual(['It keeps running on its host and reconnects.']) + expect(one(sshPlain()).lines).toEqual(['It restarts.']) + expect(one(terminal()).lines).toEqual(['It restarts as a new terminal.']) + expect(one(signIn()).lines).toEqual(['It closes and does not come back.']) + expect(one(agent()).close).toBe('Close sessions ends it and closes its tab.') + }) + + it('every tab open of one kind: the line starts with All', () => { + expect(closeDialogText('update', many(4, () => agent()), { agents: 4, terminals: 0 }).lines).toEqual(['All 4 keep running through the update and come back in the same tabs.']) + expect(closeDialogText('update', many(3, () => agent()), none).lines).toEqual(['All 3 restart and pick up their conversations.']) + expect(closeDialogText('update', many(2, () => sshPersistent()), none).lines).toEqual(['All 2 SSH sessions keep running on their hosts and reconnect.']) + expect(closeDialogText('update', many(2, () => sshPlain()), none).lines).toEqual(['All 2 SSH sessions restart.']) + expect(closeDialogText('update', many(2, () => terminal()), none).lines).toEqual(['All 2 terminals restart as new terminals.']) + expect(closeDialogText('update', [signIn(), signIn()], none).lines).toEqual(['All 2 sign-in or install tabs close and do not come back.']) + // Every tab kept, agent sessions and terminals alike: one line, All. + expect(closeDialogText('update', [...many(2, () => agent()), ...many(3, () => terminal())], { agents: 2, terminals: 3 }).lines).toEqual([ + 'All 5 keep running through the update and come back in the same tabs.', + ]) + // A mixed set keeps the plain count. + expect(closeDialogText('update', [...many(2, () => agent()), terminal()], { agents: 2, terminals: 0 }).lines).toEqual([ + '2 keep running through the update and come back in the same tabs.', + '1 terminal restarts as a new terminal.', ]) }) it('a kind with none open has no line (nothing kept: no kept line, no SSH: no SSH line)', () => { - const text = closeDialogText('update', [agent(), agent(), agent()], none) - expect(text.lines).toEqual(['3 restart and pick up their conversations.']) + const text = closeDialogText('update', [agent(), agent(), agent(), terminal()], none) + expect(text.lines).toEqual(['3 restart and pick up their conversations.', '1 terminal restarts as a new terminal.']) expect(text.lines.join(' ')).not.toMatch(/\b0\b/) }) - it('every agent kept leaves no restart line', () => { - expect(closeDialogText('update', [agent(), agent()], { agents: 2, terminals: 0 }).lines).toEqual([ - '2 keep running through the update and are back in their tabs straight away.', - ]) + it('an SSH tab that is not SSH Persistent restarts, and is never promised its conversation; a Terminal only SSH tab is a terminal', () => { + const c = closeDialogCounts('update', [sshPlain(), sshPersistent({ sshTmuxPersistent: false }), sshPersistent({ neverStarted: true }), sshPersistent({ shellOnly: true }), agent()], none) + expect(c).toMatchObject({ total: 5, ssh: 0, resume: 1, sshRestart: 3, fresh: 1 }) }) it("main's answer above the tabs asked about counts as all of them, never more", () => { const c = closeDialogCounts('update', [agent(), terminal()], { agents: 9, terminals: 9 }) expect(c).toMatchObject({ total: 2, kept: 2, resume: 0, fresh: 0 }) }) - - it('sign-in and install tabs, plural', () => { - expect(closeDialogText('update', [signIn(), signIn()], none).lines).toEqual(['2 sign-in or install tabs end.']) - }) }) describe('the quit dialog', () => { - it('held sessions end at a quit: nothing is kept, whatever is passed', () => { + it('held sessions stop at a quit: nothing is kept, whatever is passed', () => { const tabs = [agent(), agent(), terminal()] const c = closeDialogCounts('close', tabs, { agents: 2, terminals: 1 }) expect(c.kept).toBe(0) expect(closeDialogText('close', tabs, { agents: 2, terminals: 1 }).lines).toEqual([ - '2 end and pick up their conversations at the next launch.', - '1 terminal ends and starts again at the next launch.', + '2 stop now and pick up their conversations at the next launch.', + '1 terminal closes and opens again as a new terminal at the next launch.', ]) }) - it('SSH Persistent sessions keep running on their hosts; singular forms', () => { - expect(closeDialogText('close', [agent(), sshPersistent(), terminal(), signIn()], none).lines).toEqual([ - '1 ends and picks up its conversation at the next launch.', + it('the same order as the update dialog: what keeps running first (SSH Persistent), then what stops; singular forms', () => { + expect(closeDialogText('close', [agent(), sshPersistent(), sshPlain(), terminal(), signIn()], none).lines).toEqual([ '1 SSH session keeps running on its host and reconnects at the next launch.', - '1 terminal ends and starts again at the next launch.', - '1 sign-in or install tab ends.', + '1 stops now and picks up its conversation at the next launch.', + '1 SSH session stops now and starts again at the next launch.', + '1 terminal closes and opens again as a new terminal at the next launch.', + '1 sign-in or install tab closes and does not come back.', ]) - expect(closeDialogText('close', [sshPersistent(), sshPersistent()], none).lines).toEqual([ - '2 SSH sessions keep running on their hosts and reconnect at the next launch.', + }) + + it('plural, It and All forms', () => { + expect(closeDialogText('close', [...many(2, () => agent()), ...many(3, () => sshPersistent()), ...many(2, () => sshPlain()), ...many(2, () => terminal())], none).lines).toEqual([ + '3 SSH sessions keep running on their hosts and reconnect at the next launch.', + '2 stop now and pick up their conversations at the next launch.', + '2 SSH sessions stop now and start again at the next launch.', + '2 terminals close and open again as new terminals at the next launch.', ]) + expect(closeDialogText('close', [agent()], none).lines).toEqual(['It stops now and picks up its conversation at the next launch.']) + expect(closeDialogText('close', [sshPersistent()], none).lines).toEqual(['It keeps running on its host and reconnects at the next launch.']) + expect(closeDialogText('close', [sshPlain()], none).lines).toEqual(['It stops now and starts again at the next launch.']) + expect(closeDialogText('close', [terminal()], none).lines).toEqual(['It closes and opens again as a new terminal at the next launch.']) + expect(closeDialogText('close', many(2, () => agent()), none).lines).toEqual(['All 2 stop now and pick up their conversations at the next launch.']) + expect(closeDialogText('close', many(2, () => sshPersistent()), none).lines).toEqual(['All 2 SSH sessions keep running on their hosts and reconnect at the next launch.']) + expect(closeDialogText('close', many(2, () => sshPlain()), none).lines).toEqual(['All 2 SSH sessions stop now and start again at the next launch.']) + expect(closeDialogText('close', many(2, () => terminal()), none).lines).toEqual(['All 2 terminals close and open again as new terminals at the next launch.']) + }) + + it('"ends" is the Close sessions verb only: no Save line says a session ends', () => { + const tabs = [agent(), agent(), sshPersistent(), sshPlain(), terminal(), signIn()] + for (const mode of ['close', 'update'] as const) { + for (const line of closeDialogText(mode, tabs, none).lines) expect(line).not.toMatch(/\bends?\b/) + } }) it('never says the update line', () => { @@ -175,9 +237,9 @@ describe('the quit dialog', () => { }) describe('the Close sessions line', () => { - it('ends all of them when no SSH session keeps running', () => { - expect(closeDialogText('update', [...many(4, () => agent()), ...many(3, () => terminal())], { agents: 4, terminals: 0 }).close).toBe('Close sessions ends all 7.') - expect(closeDialogText('close', [agent()], none).close).toBe('Close sessions ends it.') + it('ends them and says their tabs close when no SSH session keeps running', () => { + expect(closeDialogText('update', [...many(4, () => agent()), ...many(3, () => terminal())], { agents: 4, terminals: 0 }).close).toBe('Close sessions ends all 7 and closes their tabs.') + expect(closeDialogText('close', [agent()], none).close).toBe('Close sessions ends it and closes its tab.') }) it('says the SSH Persistent sessions keep running: their tabs close, the hosts keep them', () => { @@ -195,13 +257,14 @@ describe('the Close sessions line', () => { describe('plain text', () => { it('no em dash, no curly quotes, every line a sentence', () => { - const tabs = [agent(), agent(), terminal(), terminal(), sshPersistent(), sshPersistent(), signIn(), signIn()] + const tabs = [agent(), agent(), terminal(), terminal(), sshPersistent(), sshPersistent(), sshPlain(), signIn(), signIn()] for (const mode of ['close', 'update'] as const) { const text = closeDialogText(mode, tabs, { agents: 1, terminals: 1 }) for (const line of [...text.lines, text.close]) { - expect(line).not.toMatch(/[—‘’“”]/) + expect(line).not.toMatch(/[\u2014\u2018\u2019\u201c\u201d]/) expect(line).toMatch(/^[0-9A-Z].*\.$/) } + expect(text.lead).toMatch(/^[A-Z][^.]*:$/) } }) }) diff --git a/tests/unit/renderer/close-dialogs-tokens.test.tsx b/tests/unit/renderer/close-dialogs-tokens.test.tsx index 27dbc55d6..9d8432ebf 100644 --- a/tests/unit/renderer/close-dialogs-tokens.test.tsx +++ b/tests/unit/renderer/close-dialogs-tokens.test.tsx @@ -103,12 +103,14 @@ describe('CloseDialog says what each choice does to the tabs open (aicc_planning expect(sessionsKept).toHaveBeenCalledWith({ agents: ['a1', 'a2', 'a3'], terminals: ['t1'] }) expect(container.textContent).toContain('You have 7 active sessions.') expect(lines()).toEqual([ - '3 keep running through the update and are back in their tabs straight away.', + 'With Save sessions:', + '3 keep running through the update and come back in the same tabs.', '2 SSH sessions keep running on their hosts and reconnect.', '1 restarts and picks up its conversation.', - '1 sign-in or install tab ends.', + '1 sign-in or install tab closes and does not come back.', 'Close sessions ends 5 and closes every tab; the 2 SSH sessions keep running on their hosts.', ]) + expect(byTest('close-dialog-lead')?.textContent).toBe('With Save sessions:') expect(container.textContent).not.toContain('Save them and they come back') }) @@ -118,27 +120,28 @@ describe('CloseDialog says what each choice does to the tabs open (aicc_planning await show('update') expect(byTest('close-dialog-lines')).toBeNull() await act(async () => { answer({ agents: 0, terminals: 0 }) }) - expect(lines()[0]).toBe('2 SSH sessions keep running on their hosts and reconnect.') + expect(lines().slice(0, 2)).toEqual(['With Save sessions:', '2 SSH sessions keep running on their hosts and reconnect.']) }) it('update: an answer that does not read, or a failed question, reads as nothing kept', async () => { sessionsKept.mockResolvedValue({ agents: 'all', terminals: 1 }) await show('update') - expect(lines()).not.toContain('3 keep running through the update and are back in their tabs straight away.') + expect(lines()).not.toContain('3 keep running through the update and come back in the same tabs.') expect(lines()).toContain('3 restart and pick up their conversations.') act(() => { root.unmount() }) root = createRoot(container) sessionsKept.mockRejectedValue(new Error('gone')) await show('update') expect(lines()).toContain('3 restart and pick up their conversations.') - expect(lines()).toContain('1 terminal starts again.') + expect(lines()).toContain('1 terminal restarts as a new terminal.') }) it('update with no local tab: main is not asked', async () => { await show('update', [{ id: 's1', sessionType: 'ssh', sshConfig: {} }]) expect(sessionsKept).not.toHaveBeenCalled() expect(lines()).toEqual([ - '1 SSH session keeps running on its host and reconnects.', + 'With Save sessions:', + 'It keeps running on its host and reconnects.', 'Close sessions closes its tab; the SSH session keeps running on its host.', ]) }) @@ -147,17 +150,18 @@ describe('CloseDialog says what each choice does to the tabs open (aicc_planning await show('close') expect(sessionsKept).not.toHaveBeenCalled() expect(lines()).toEqual([ - '3 end and pick up their conversations at the next launch.', + 'With Save sessions:', '2 SSH sessions keep running on their hosts and reconnect at the next launch.', - '1 terminal ends and starts again at the next launch.', - '1 sign-in or install tab ends.', + '3 stop now and pick up their conversations at the next launch.', + '1 terminal closes and opens again as a new terminal at the next launch.', + '1 sign-in or install tab closes and does not come back.', 'Close sessions ends 5 and closes every tab; the 2 SSH sessions keep running on their hosts.', ]) }) - it('no kind with none open: two Claude Code tabs at a quit read two lines', async () => { + it('no kind with none open: two Claude Code tabs at a quit read the lead-in, one line and the Close sessions line', async () => { await show('close', [{ id: 'a1', sessionType: 'local' }, { id: 'a2', sessionType: 'local' }]) - expect(lines()).toEqual(['2 end and pick up their conversations at the next launch.', 'Close sessions ends all 2.']) + expect(lines()).toEqual(['With Save sessions:', 'All 2 stop now and pick up their conversations at the next launch.', 'Close sessions ends all 2 and closes their tabs.']) }) }) From 1dc2d75a9775459e1600abca15cb2014e2aa8d0b Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:07:26 +0000 Subject: [PATCH 41/79] docs(update): say what the dialog says on every surface, and that an update asks nothing (#514, #515) The Feature Guide (and so Ask Conductor), Settings, the guided tour, the tips and the README now use the UX review's wording: - Feature Guide, sessions: "The app asks first, with Save sessions, Close sessions and Cancel, and says what each does to your open tabs, with a count for each kind"; kept sessions "come back in the same tabs"; the switches are named ("with Plain terminals through the session helper or Claude Code and Codex sessions through the session helper on"); Close sessions "ends every session and closes its tab"; and each session carries on "on the account it was on". - Feature Guide, accounts and machines: "on the account it was on"; "a kept session whose tab is not restored within five minutes of the new version opening is ended". - Settings, the agent sessions' switch: "if the new version opens within two minutes. The new version reopens your tabs by itself once you close the pages it opens with (such as the release notes). Close them within five minutes and each tab shows the same session again." The Plain terminals switch beside it read "for up to two minutes until the new version opens" the same way, and now reads "if the new version opens within two minutes" too. - Settings, Resuming sessions: "Applies when you open the app again and resume your sessions. After an app update where you chose Save sessions, you are not asked: each session keeps the account it was on." - The guided tour and the tip: "with nothing asked, once you close the pages it opens with (such as the release notes)"; the README: "with nothing asked (no resume prompt, no account picker)". One departure from the review's wording, as it is untrue to the code: the quit sentence "the Claude Code and Codex sessions stop and pick up their conversations at the next launch" goes on "except over SSH", and the update's restart line says "on this computer". An SSH tab that is not SSH Persistent starts again without --continue or --resume at the first start after a relaunch (pty-manager.ts claudeCmdWith), so no conversation is promised for it, as in the dialog. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/renderer/components/SettingsPage.tsx | 6 +-- src/renderer/tips-library.ts | 2 +- src/renderer/training-steps.ts | 2 +- src/shared/app-knowledge.ts | 6 +-- tests/unit/renderer/held-terminal-tab.test.ts | 2 +- tests/unit/renderer/session-launch.test.ts | 2 +- tests/unit/shared/app-knowledge.test.ts | 40 +++++++++++++++++-- 8 files changed, 48 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 37e1336ca..e9218c7b9 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ On-demand reports over your own usage, Claude Code's and Codex's, runnable acros - **Feature Guide** — a searchable in-app reference with a card for every feature (what it does, how to open it, a tip) plus the complete What's New history, a click away from the sidebar's help button. - **Browser pane** — every session has a browser beside its terminal: an address bar (type `localhost:5173` and press Enter), working history, a home page per config, saved favourites, and a button to open the page in your real browser. Pages load in a sandbox with every permission off. A command button can point it at a dev server as it starts ("watch for a page") or simply open a page; freeze the page to annotate a snapshot in Excalidraw. - **Partner terminal and scratchpad** — every session carries a partner shell in the same tab (on the host, for an SSH session), and a per-session Excalidraw whiteboard that persists with the config; export the drawing straight into the session. -- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: the new version reopens your tabs with nothing to answer (no resume prompt, no account picker), and each restored tab takes over the same running session, with no resume, even a tab you open later. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. +- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: the new version reopens your tabs with nothing asked (no resume prompt, no account picker), and each restored tab takes over the same running session, with no resume, even a tab you open later. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. - **Multi-account usage strip** — every signed-in account's usage along the bottom of the window, one pill per person, grouped by provider so Claude Code and Codex figures are never merged, and a minimal mode that shows just the account name and two traffic-light dots (green under 70 %, amber to 89 %, red from 90 %) so the strip stays readable with many accounts. The **Accounts** page shows every Claude and Codex account's 5-hour and weekly allowance at once, one line each: each bar fills with what is used, the lines are grouped In use, Not in use and Not usable now, you sort by Room, Weekly or Name, and with both assistants on you can show one of them. The **Most room now** line above the groups names the free account with the most room, and a line says when it is out of its limit until a time, inactive, or must sign in again. Click a line to open it for its sign-ins: Claude Code's or Codex's, and the account's claude.ai or chatgpt.com sign-in, who it is signed in as and since when. There is no Refresh, and the page never asks for a reading itself: an account in use reads live from its session, an idle one keeps its last reading (a window past its reset reads 0% used), and the app checks the usage of idle accounts still signed in, Claude Code's and Codex's, in the background, one at a time, at least 10 minutes apart and each account at most every 3 hours; while Anthropic rate-limits those checks, the lines count down to the next one. Sign-ins on a machine you added (remote sessions preview) are on that machine's card on the Machines page. - **Snap and Vision capture** — region or window capture from any screen, capped at 1920px, with a JPEG copy saved. Snap puts the picture on your clipboard and presses the assistant's own paste key, so a Claude Code or Codex session gets it as its own pasted image with a short sentence, and no file path is typed; the picture stays on your clipboard afterwards. An SSH tab on the usual path fetches it over the tunnel. `Alt+V` (`Option+V` on a Mac) pastes a clipboard image the same way, and `Ctrl+V` (`Cmd+V`) does too when the clipboard holds only a picture; in a plain terminal, `Alt+V` goes to the program there as a key. On Linux, Claude Code reads the clipboard with `xclip` or `wl-paste`, and the hint names them when the one your desktop needs (`xclip` under X11, `wl-paste` under Wayland) is not installed. On a Mac, Snap checks the Screen Recording permission first and, without it, offers to open System Settings instead of capturing. On Windows, Snap's region capture uses the app's own overlay (a rectangle or the whole screen, no drawing tools); the earlier Snap is a setting away and opens by itself for any press the new one cannot take. - **A first-run tour and What's New that know where you came from**: a fresh install gets the tour; an update shows what is new since the version you came from (every prerelease of a release shows that release's whole story, and release notes can open with warnings, shown first, including those of any release you skipped), and an update across a release line also walks the tour again. diff --git a/src/renderer/components/SettingsPage.tsx b/src/renderer/components/SettingsPage.tsx index b0c77dddf..aa4ce60cb 100644 --- a/src/renderer/components/SettingsPage.tsx +++ b/src/renderer/components/SettingsPage.tsx @@ -614,7 +614,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat /> Plain terminals through the session helper - Preview, off by default. A Terminal only tab and the partner terminal of a session on this computer start inside the session helper. On Windows they keep running if the app crashes, and come back with their tabs if you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, for up to two minutes until the new version opens. Claude Code and Codex sessions have their own switch below, and SSH sessions are not affected. Quitting normally ends them. Applies to terminals opened after the change. The Machines page shows the helper and what it holds. + Preview, off by default. A Terminal only tab and the partner terminal of a session on this computer start inside the session helper. On Windows they keep running if the app crashes, and come back with their tabs if you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, if the new version opens within two minutes. Claude Code and Codex sessions have their own switch below, and SSH sessions are not affected. Quitting normally ends them. Applies to terminals opened after the change. The Machines page shows the helper and what it holds. {/* 2.1.3-beta.7 (plan section A3): agent sessions through the session helper, a preview. */} @@ -627,7 +627,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat /> Claude Code and Codex sessions through the session helper - Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens, which reopens your tabs by itself once the pages it opens with are closed: within five minutes of it opening, its tab takes the same session over. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. + Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, if the new version opens within two minutes. The new version reopens your tabs by itself once you close the pages it opens with (such as the release notes). Close them within five minutes and each tab shows the same session again. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. {/* 2.1.3-beta.17 (plan section A2): remote sessions through the session helper, a preview (Windows). */} @@ -708,7 +708,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat

- Only matters with two or more Claude accounts. Applies when the app reopens your sessions. After an update where you chose Save sessions, each session carries on as it was, with nothing asked. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in. + Only matters with two or more Claude accounts. Applies when you open the app again and resume your sessions. After an app update where you chose Save sessions, you are not asked: each session keeps the account it was on. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.

diff --git a/src/renderer/tips-library.ts b/src/renderer/tips-library.ts index cebfcedce..78df44284 100644 --- a/src/renderer/tips-library.ts +++ b/src/renderer/tips-library.ts @@ -1822,7 +1822,7 @@ export const TIPS_LIBRARY: Tip[] = [ primary: { shortText: 'Save sessions at an update keeps held terminals running', title: 'Terminals That Live Through an Update', - body: 'With **Plain terminals through the session helper** on (**Settings, General, Terminal**; a preview, off by default), choose **Save sessions** when the app asks before an update. The terminals the session helper holds keep running, and the new version shows each one again in its tab, with what it printed meanwhile, up to the last 2 MiB.\n\nFinish the installer within **two minutes**: a held terminal waits that long for the new version, counted from when the old one closed. **Close sessions** ends them instead. With **Claude Code and Codex sessions through the session helper** on as well, a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing to answer, once you close the pages it opens with (such as the release notes). Close them within **five minutes** of it opening and each tab shows the same session, on the same account, with no resume.', + body: 'With **Plain terminals through the session helper** on (**Settings, General, Terminal**; a preview, off by default), choose **Save sessions** when the app asks before an update. The terminals the session helper holds keep running, and the new version shows each one again in its tab, with what it printed meanwhile, up to the last 2 MiB.\n\nFinish the installer within **two minutes**: a held terminal waits that long for the new version, counted from when the old one closed. **Close sessions** ends them instead. With **Claude Code and Codex sessions through the session helper** on as well, a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing asked, once you close the pages it opens with (such as the release notes). Close them within **five minutes** of it opening and each tab shows the same session, on the same account, with no resume.', actionLabel: 'Open Settings', actionTarget: 'settings', focusHint: 'Settings -- General, under Terminal', diff --git a/src/renderer/training-steps.ts b/src/renderer/training-steps.ts index 128bbf3c6..bae0e9d4b 100644 --- a/src/renderer/training-steps.ts +++ b/src/renderer/training-steps.ts @@ -718,7 +718,7 @@ export const trainingSteps: TrainingStep[] = [ '**Re-attach** connects a detached terminal again, and opens a Terminal only tab for one no tab shows; **End** stops one after you confirm', 'After a crash on Windows, open the app within two minutes and resume your sessions: each held terminal shows again in its tab, with what it printed meanwhile, up to the last 2 MiB. Quitting normally ends them. If the app only freezes for a while, what the helper holds keeps running, a Claude Code or Codex session included, and each tab shows it again once the app answers; a terminal or session that a version before 2.1.3-beta.24 started is not kept this way', 'On Windows, choose **Save sessions** when you update the app and each held Terminal or Partner terminal keeps running. If the new version opens within two minutes, it shows them again. **Close sessions** ends them', - 'A Claude Code or Codex session has **End** only. After a crash it is ended, reading **Being ended** until it is gone, and its tab resumes the conversation. On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once the pages it opens with are closed, and within five minutes of it opening the tab shows the same session again', + 'A Claude Code or Codex session has **End** only. After a crash it is ended, reading **Being ended** until it is gone, and its tab resumes the conversation. On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once you close the pages it opens with (such as the release notes). Close them within five minutes and the tab shows the same session again', 'With **Claude Code and Codex sessions through the session helper** on, an Insights report for a Claude Code account runs inside the helper too, and is listed as **Insights report** while it runs, with **End** only', 'SSH tabs and their partner terminals, a terminal run as administrator, and the tabs the app opens for a sign-in or to install or update a program start as before', 'On Windows, the Machines page also lists, under **Other machines**, the Linux machines (x86-64 or arm64, a Raspberry Pi included) you added for remote sessions through the session helper (preview), with Add, Check and Remove, and the sessions each one keeps for an SSH Persistent tab, with Re-attach and End. Each card leads with the mark of its system, names it and its version, and says when the machine was last seen or that it is **Not reachable**; with many machines, filter them by name, kind or status and sort them by last seen, name or kind. A card also shows the Claude Code and Codex versions its last Check found. A config that keeps a password signs in with it, and a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you press Add, Check or Remove. A Claude Code or Codex session on such a machine through the helper has a **Restart** menu in its status strip: **Restart Claude Code on** the machine (or **Restart Codex**) ends that program there and starts it again on the same conversation, so an update it installed applies', diff --git a/src/shared/app-knowledge.ts b/src/shared/app-knowledge.ts index f7c06910b..73975dce2 100644 --- a/src/shared/app-knowledge.ts +++ b/src/shared/app-knowledge.ts @@ -34,7 +34,7 @@ A Terminal only config over SSH is a terminal and nothing more, so the app never Quitting the app. When you quit, the app closes down each Claude Code or Codex session it started by typing that assistant's exit keys into it (Escape, Ctrl-C and /exit for Claude Code; Escape, Ctrl-C and a second Ctrl-C a moment later for Codex), and an SSH Persistent session is detached and keeps running on its host. Every other terminal is closed with nothing typed into it: Terminal only tabs, partner terminals, and SSH tabs where the app did not start an assistant. Whatever runs in such a terminal is left as closing any terminal leaves it, so a tmux session you attached to keeps running. -Closing or updating with sessions open. The dialog that asks says what each choice does to the tabs open, with how many of each kind, and leaves out a kind with none open. At a quit, Save sessions closes the Claude Code and Codex tabs and they pick up their conversations at the next launch, an SSH Persistent session keeps running on its host and reconnects, and a Terminal only tab starts again. Before an update it also says how many keep running through the update and are back in their tabs straight away (on Windows, the sessions the session helper holds, with its switches on), and the rest restart and pick up their conversations. A sign-in or install tab is never saved and ends. Close sessions ends every session, except that an SSH Persistent session keeps running on its host while its tab closes. After an update where you chose Save sessions, the new version reopens your tabs by itself once the pages it opens with (such as the release notes) are closed: there is no resume prompt and no account picker, and each session carries on as it was, on its own account. A quit, a crash, or the same version starting again still asks with the resume prompt. +Closing or updating with sessions open. The app asks first, with Save sessions, Close sessions and Cancel, and says what each does to your open tabs, with a count for each kind; a kind with none open is left out. At a quit, with Save sessions, the Claude Code and Codex sessions stop and pick up their conversations at the next launch, except over SSH: an SSH Persistent session keeps running on its host and reconnects, and another SSH session stops and starts again then. A Terminal only tab closes and opens again as a new terminal. Before an update it says how many keep running through the update and come back in the same tabs (on Windows, the sessions the session helper holds, with Plain terminals through the session helper or Claude Code and Codex sessions through the session helper on); the other Claude Code and Codex tabs on this computer restart and pick up their conversations, an SSH Persistent session keeps running on its host and reconnects, another SSH session restarts, and a Terminal only tab restarts as a new terminal. A sign-in or install tab is never saved: it closes and does not come back. Close sessions ends every session and closes its tab, except that an SSH Persistent session keeps running on its host while its tab closes. After an update where you chose Save sessions, the new version reopens your tabs by itself, with nothing asked, once the pages it opens with (such as the release notes) are closed: there is no resume prompt and no account picker, and each session carries on as it was, on the account it was on. A quit, a crash, or the same version starting again still asks with the resume prompt. Reopening after a crash. When the app stops without closing, from a crash, a power cut or a killed process, each Claude Code tab reopens on the newest conversation it was on, even when you moved it to a new conversation with /clear or /resume after the app last saved the tab list. The app now saves a tab's place as soon as the tab moves to another conversation, and writes the saved tab file so that a power cut cannot leave it half written. At the next start, a newer record of a tab's conversation wins over an older saved one, and the start log says which conversation each tab resumes. This needs session logging on, which is the default; with it off a tab reopens as before. A tab that never moved reopens as before. At a start, one Claude Code conversation is never reopened in two tabs. With session logging on, when you use /resume in one tab to open the conversation another tab was on (its Claude Code had ended, or the tab had not been opened yet since the app started), that conversation goes to the tab you opened it in. If that tab is still on it when the app stops, the other tab comes back on the resume picker at the next start; if not, the other tab may resume it. A tab not opened yet starts a new conversation if you open it while that tab's Claude Code is still running on that conversation; open it later and it may resume it instead. The app log names the tab that gave the conversation up.`, }, @@ -58,7 +58,7 @@ What an SSH session's setup does to your user settings (~/.claude/settings.json) { id: 'accounts', title: 'Multiple Claude accounts', - body: `On Windows and Linux you can run each local session under a different Claude account. Logins never mix between accounts, while memory, projects, and history are shared, so switching never loses your place. Your existing login becomes the primary account and is backed up once before anything is set up. Switching accounts applies to local sessions and, in the remote sessions preview, to a Claude Code tab through the session helper on a Linux machine you added, where each account signs in once on that machine (see The Machines page). A usual SSH session uses the remote machine's own login, and Codex has accounts of its own (see Codex: sessions and accounts). A remote session still shows which account it is signed in as, on its session card, in its session header and in the multi-account strip, and it contributes its own usage there; running /login on the remote moves it to the right account within a few seconds. When a remote session is signed in as one of the accounts you also run locally, its header and its right-click menu carry that account's claude.ai and Claude Code tools too, Open artifacts and the sign-in items included, because those act on the account here on your own machine; the account switch itself stays local-only for a usual SSH session, and a remote session with no matching local account simply shows the account name. Add accounts on the Accounts page (Accounts on the left rail), and switch them in the New Session picker or from the account pill, which sits at the far left of every session's status line. Adding a Claude account, or signing one in again, opens a sign-in tab on this computer in which Claude Code starts under that account: sign in when it asks, or type /login, and choose the account. The app notices the sign-in on its own. It starts Claude Code for you because Windows PowerShell can refuse to run a Claude Code installed with npm when you type claude yourself. A sign-in tab whose account is no longer set up here, because it was removed while the tab was open for example, starts nothing and says to add the account again on the Accounts page. A sign-in tab on an inactive account starts nothing either, and says so: The Claude account "NAME" is inactive, so this sign-in tab did not start Claude Code. Make the account active first: use Make active on "NAME" on the Accounts page, then sign it in again. A Claude session whose account is no longer set up here, because the account was removed for example, starts nothing and says so: This session's Claude account is no longer set up here. Choose an account for it and start it again. It never runs on another account in its place. When the app reopens your sessions after a restart, each Claude session runs on the account it last ran on. Set Settings, Accounts, Resuming sessions to Ask each time to be asked for each one instead: its picker has that account already chosen and marked This session's account. After an app update where you chose Save sessions, nothing is asked whatever that setting says: each session carries on as it was, on its own account. When you start a new session, the picker marks the account you used most recently as Most recent. The claude.ai pill in the session header follows the account's live claude.ai sign-in; press the refresh arrow on the Claude Code pill next to it to check both again. On macOS this is not available yet, because Claude Code keeps its sign-in in the login Keychain, which cannot be isolated per account, so a session, cloud agent or Insights run on an account other than the primary one is refused there with a sentence that says to choose the primary account (once a primary account is recorded; with none recorded, sessions start as before). A Claude session on an inactive account (Make inactive on the Accounts page) is refused on every system, wherever it comes from, with a sentence that names the account and says how to switch the tab or make the account active again. + body: `On Windows and Linux you can run each local session under a different Claude account. Logins never mix between accounts, while memory, projects, and history are shared, so switching never loses your place. Your existing login becomes the primary account and is backed up once before anything is set up. Switching accounts applies to local sessions and, in the remote sessions preview, to a Claude Code tab through the session helper on a Linux machine you added, where each account signs in once on that machine (see The Machines page). A usual SSH session uses the remote machine's own login, and Codex has accounts of its own (see Codex: sessions and accounts). A remote session still shows which account it is signed in as, on its session card, in its session header and in the multi-account strip, and it contributes its own usage there; running /login on the remote moves it to the right account within a few seconds. When a remote session is signed in as one of the accounts you also run locally, its header and its right-click menu carry that account's claude.ai and Claude Code tools too, Open artifacts and the sign-in items included, because those act on the account here on your own machine; the account switch itself stays local-only for a usual SSH session, and a remote session with no matching local account simply shows the account name. Add accounts on the Accounts page (Accounts on the left rail), and switch them in the New Session picker or from the account pill, which sits at the far left of every session's status line. Adding a Claude account, or signing one in again, opens a sign-in tab on this computer in which Claude Code starts under that account: sign in when it asks, or type /login, and choose the account. The app notices the sign-in on its own. It starts Claude Code for you because Windows PowerShell can refuse to run a Claude Code installed with npm when you type claude yourself. A sign-in tab whose account is no longer set up here, because it was removed while the tab was open for example, starts nothing and says to add the account again on the Accounts page. A sign-in tab on an inactive account starts nothing either, and says so: The Claude account "NAME" is inactive, so this sign-in tab did not start Claude Code. Make the account active first: use Make active on "NAME" on the Accounts page, then sign it in again. A Claude session whose account is no longer set up here, because the account was removed for example, starts nothing and says so: This session's Claude account is no longer set up here. Choose an account for it and start it again. It never runs on another account in its place. When the app reopens your sessions after a restart, each Claude session runs on the account it last ran on. Set Settings, Accounts, Resuming sessions to Ask each time to be asked for each one instead: its picker has that account already chosen and marked This session's account. After an app update where you chose Save sessions, your sessions reopen with nothing asked, whatever that setting says: each session carries on as it was, on the account it was on. When you start a new session, the picker marks the account you used most recently as Most recent. The claude.ai pill in the session header follows the account's live claude.ai sign-in; press the refresh arrow on the Claude Code pill next to it to check both again. On macOS this is not available yet, because Claude Code keeps its sign-in in the login Keychain, which cannot be isolated per account, so a session, cloud agent or Insights run on an account other than the primary one is refused there with a sentence that says to choose the primary account (once a primary account is recorded; with none recorded, sessions start as before). A Claude session on an inactive account (Make inactive on the Accounts page) is refused on every system, wherever it comes from, with a sentence that names the account and says how to switch the tab or make the account active again. The Accounts page (Accounts on the left rail, after Machines) lists every Claude Code and Codex account, one line each. Click a line to open it; one line is open at a time, and Escape closes it. An open line holds everything about its account: its name and colour, with Edit, which opens its editor (its name, colour and group, and Link another account to tie it to another of your accounts, Claude or Codex; Unlink undoes it); Linked with, naming the accounts it is linked to; its status, with Make active or Make inactive; Reviews, when it cannot run code reviews, and why; the tabs running on it; how its assistant signs in, with Sign in again for a Claude Code account or Check sign-in for a Codex account, and a Claude Code account's organisation when Claude Code records one that says more than its email; and its claude.ai or chatgpt.com sign-in, saying who it is signed in as and since when, with Sign in, Open my artifacts (claude.ai) and Sign out. While one account's claude.ai sign-in runs, every other line's claude.ai Sign in waits for it. The name, colour and group show on every linked account, and the colour on the account's chips everywhere. Each line's menu (its three dots) holds Sign in again now, Make reviewer and Remove for a Claude Code account, and Make default, Make reviewer, Sign out and, once the account is inactive, Archive for a Codex account. When an account cannot be made inactive, archived or removed because tabs use it, its line opens and names each of them with Go to. Add account is in the page's header, and in the middle of the page when there is no account yet. Settings, Accounts keeps what is not about one account: the Providers card, which account each provider's code reviews use, archived accounts with Restore, setups that did not finish (Resume or Discard), where claude.ai sign-in and the artifacts open, and Resuming sessions; the page links to it. @@ -182,7 +182,7 @@ Two settings in Settings, General, under Terminal, each carry their own kind of While Plain terminals through the session helper is on, a Terminal only tab on this computer and the partner terminal beside a session on this computer start inside the session helper, a small program installed with the app, instead of under the app itself. They work as before, and they keep running if the app crashes. When the app starts again it finds them at once, and a tab that comes back with the restored sessions shows its terminal again, with what it printed while the app was gone; nothing is typed into it again. When it printed more than the last 2 MiB the helper keeps, the tab first shows one line saying its earlier output is no longer held, then the last of its output that the tab can keep, and its program, if it is still running, is asked to draw its screen again. A held terminal no tab shows is listed on this page, and Re-attach opens a Terminal only tab on it. A held terminal waits two minutes for the app to come back, and then ends. While the app is still running but stops answering for a while (it froze), a held terminal does not end, one the app took over after a crash or an update included: once the app answers again, its tab shows it again with what it printed meanwhile. A terminal that a version before 2.1.3-beta.24 started is not kept this way. If a tab's held terminal was lost all the same, the tab starts it again on its own in its folder, at most once a minute, with a note above it saying so. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal starts again by itself: the session beside it is left as it is. Quitting the app normally ends every terminal the helper holds. On Windows an app update keeps them when you choose Save sessions on the update dialog: they keep running, and the new version shows each one again in its tab, or lists it on this page if no tab shows it, as after a crash. Close sessions ends them. The new version has the same two minutes, counted from when the old one closed, and while the update runs Re-attach is refused and says the app is being updated. On a Mac or Linux an update still ends them. Claude Code and Codex sessions are kept through an update only on Windows, with Claude Code and Codex sessions through the session helper on (below); any other one is not kept, and its tab resumes the conversation. SSH sessions and their partner terminals, a terminal run as administrator, and the tabs the app opens for a sign-in or to install or update a program do not start through it. Claude Code and Codex sessions have their own setting, below. The switch applies to terminals opened after the change; a terminal already open carries on as it started. Surviving a crash is promised on Windows for now: on a Mac or Linux a held terminal may not outlive the app until that has been checked there. Where Windows keeps the session helper inside the app's own job, the card says so, and held terminals then end with the app. The app runs the helper from its own copy in your user folder, checks that copy against the one installed with the app before each use, and makes it again once if it does not match; if it still does not match, the helper reads Failed and terminals start the usual way. -While Claude Code and Codex sessions through the session helper is on, a Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before: the same command, folder, account and settings. Its status line, hooks, the Conductor's tools, the resume list and the Watchdog work as they did, and on Windows a Codex session keeps its scrollback. With the HTTP Hooks Gateway switch on (Settings, Hooks), a Claude Code or Codex session the helper holds sends its hook events to the app through the session helper, the check before each tool runs (PreToolUse) included. The attention dot, the Watchdog and canvas notes work as before. With Claude Code and Codex sessions through the session helper off, which is the default, every session sends its hooks to the gateway as before. A Claude Code or Codex session the helper holds can also reach the Conductor's tools through the session helper. If the app's connection to the session helper drops and comes back, those tools keep working: a tool call made while the connection is down waits up to 30 seconds for the app, and if the app is not back by then, it gets the answer "AI Code Conductor is updating, try again shortly". A call the app was already answering when the connection dropped gets that answer at once and is not sent again, because a tool may not be safe to run twice. Such a session does not survive a crash yet. While the app is still running but stops answering for a while (it froze), such a session keeps running, one taken over after an update included, and its tab shows it again once the app answers. A session that a version before 2.1.3-beta.24 started is not kept this way: if it is lost, its tab only starts again. If a tab's session was lost all the same, the tab starts again on its own, at most once a minute, with a note above it saying so: a Claude Code session resumes the conversation it was on, or offers the resume list when the app does not know it, and a Codex session starts as its Restart starts it. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal that still runs is left running, its output still on screen. On Windows it does survive an app update, when its Conductor tools go through the helper and you choose Save sessions on the update dialog: the new version's restored tab takes over the same running session, with no resume and nothing typed into it. A Claude Code or Codex session is taken over only when its tab is still on the same account; if you pick another account for the tab, a new session starts on that account. A restored tab you have not opened yet keeps its session running until you open it or close it. While it waits, the session kept for it has its tool calls answered, its hook events reach the app at once (the tab's attention mark shows when it asks for approval, or about a minute after its turn ends, as on an open tab), and its status line keeps the tab's model, context and cost up to date; when you open the tab, the same session goes on and keeps its hook history. The new version reopens your tabs by itself, with nothing asked, once the pages it opens with are closed; a kept session whose tab is not restored within five minutes of it opening is ended. A Codex session's hook events made during the update wait in the session helper and reach the app when the new version starts, as a Claude Code session's do. A Codex session that 2.1.3-beta.17 or earlier started still sends them the old way, at the update from that version and at any later update it is kept through: one made from the update until a few seconds after the new version reopens your tabs, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. Open the tab to see it. When you open the app again after a crash, the session the helper held is ended and its tab resumes the conversation, as it would without the setting; a session a normal quit could not end in time is ended the same way at the next start. A tab never starts a second Claude Code or Codex on a conversation the helper still runs: it waits until the earlier one has ended. Quitting the app normally ends these sessions. On Windows, ending such a session, whether you close or restart its tab, end it on this page or quit the app, also ends every program it started, even one it opened in a window of its own. While this setting is on, an Insights report for a Claude Code account also runs inside the session helper: this page lists it as Insights report while it runs, with End, and a report the app could not end, after a crash for example, is ended at the next start. A Codex account's report runs as before. SSH sessions do not start through it. The switch applies to sessions started after the change; a session already open carries on as it started. +While Claude Code and Codex sessions through the session helper is on, a Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before: the same command, folder, account and settings. Its status line, hooks, the Conductor's tools, the resume list and the Watchdog work as they did, and on Windows a Codex session keeps its scrollback. With the HTTP Hooks Gateway switch on (Settings, Hooks), a Claude Code or Codex session the helper holds sends its hook events to the app through the session helper, the check before each tool runs (PreToolUse) included. The attention dot, the Watchdog and canvas notes work as before. With Claude Code and Codex sessions through the session helper off, which is the default, every session sends its hooks to the gateway as before. A Claude Code or Codex session the helper holds can also reach the Conductor's tools through the session helper. If the app's connection to the session helper drops and comes back, those tools keep working: a tool call made while the connection is down waits up to 30 seconds for the app, and if the app is not back by then, it gets the answer "AI Code Conductor is updating, try again shortly". A call the app was already answering when the connection dropped gets that answer at once and is not sent again, because a tool may not be safe to run twice. Such a session does not survive a crash yet. While the app is still running but stops answering for a while (it froze), such a session keeps running, one taken over after an update included, and its tab shows it again once the app answers. A session that a version before 2.1.3-beta.24 started is not kept this way: if it is lost, its tab only starts again. If a tab's session was lost all the same, the tab starts again on its own, at most once a minute, with a note above it saying so: a Claude Code session resumes the conversation it was on, or offers the resume list when the app does not know it, and a Codex session starts as its Restart starts it. Lost again within that minute, it is not restarted, and the note above it says so: use Restart to start it again. A partner terminal that still runs is left running, its output still on screen. On Windows it does survive an app update, when its Conductor tools go through the helper and you choose Save sessions on the update dialog: the new version's restored tab takes over the same running session, with no resume and nothing typed into it. A Claude Code or Codex session is taken over only when its tab is still on the same account; if you pick another account for the tab, a new session starts on that account. A restored tab you have not opened yet keeps its session running until you open it or close it. While it waits, the session kept for it has its tool calls answered, its hook events reach the app at once (the tab's attention mark shows when it asks for approval, or about a minute after its turn ends, as on an open tab), and its status line keeps the tab's model, context and cost up to date; when you open the tab, the same session goes on and keeps its hook history. The new version reopens your tabs by itself, with nothing asked, once the pages it opens with (such as the release notes) are closed; a kept session whose tab is not restored within five minutes of the new version opening is ended. A Codex session's hook events made during the update wait in the session helper and reach the app when the new version starts, as a Claude Code session's do. A Codex session that 2.1.3-beta.17 or earlier started still sends them the old way, at the update from that version and at any later update it is kept through: one made from the update until a few seconds after the new version reopens your tabs, or until you open its tab, does not reach the app, so a Codex turn that ends or asks for approval in that time may leave its tab unmarked. Open the tab to see it. When you open the app again after a crash, the session the helper held is ended and its tab resumes the conversation, as it would without the setting; a session a normal quit could not end in time is ended the same way at the next start. A tab never starts a second Claude Code or Codex on a conversation the helper still runs: it waits until the earlier one has ended. Quitting the app normally ends these sessions. On Windows, ending such a session, whether you close or restart its tab, end it on this page or quit the app, also ends every program it started, even one it opened in a window of its own. While this setting is on, an Insights report for a Claude Code account also runs inside the session helper: this page lists it as Insights report while it runs, with End, and a report the app could not end, after a crash for example, is ended at the next start. A Codex account's report runs as before. SSH sessions do not start through it. The switch applies to sessions started after the change; a session already open carries on as it started. Remote sessions through the session helper is a preview on Windows, off by default (Settings, General, under Terminal). On Windows the Machines page also lists the Linux machines you added, each with Check and Remove, whether the setting is on or off; a machine you add is used once the setting is on. Add a machine there (a Linux machine, x86-64 or arm64) from a saved SSH config that signs in by key or with its saved password: the app asks first, then uploads one file into the .aicc folder of your home folder on that machine (~/.aicc), checks its SHA-256 against the one installed with the app and runs a self-test. A Claude Code tab whose saved config signs in by key or with its saved password, with no container, to a checked machine, then runs through the session helper there: nothing is typed into the host's shell to set it up or start it, and a dropped connection comes back within two minutes with what you missed. An SSH Persistent tab (the default for a config that never chose a Connection) goes through the helper too. On a machine whose last Check read that logind does not end your processes when you log out, it is kept there until you end it: close it and choose Leave running, quit the app or update it, and the next start brings it back where it was, with its status line, the hook events it missed and its tools; End, in its tab's close question or on the Machines page, ends it. On a machine whose logind ends your processes when you log out, it is not kept (no re-attach; the machine's card says so, and so do the tab's SSH pill in its header and its config's SSH Persistent chip when you point at them): its session ends when you close the tab, quit the app or lose the connection, and its next start carries on with the conversation it was on, by that conversation's own id, never another tab's in the same folder; a tab with no message sent yet carries on with the newest conversation in its folder (see Known issues). On a machine whose logind gave the Check no answer (no loginctl there, or no logind), it keeps the usual SSH path, where tmux keeps it, and a Codex session there, which has no usual SSH path, goes through the helper not kept. A machine last checked by an older version of the app, which did not read logind, keeps such tabs on the usual SSH path until you press Check. A config with a session still under tmux (left running, or open in a tab) keeps the usual SSH path until that session is ended. The Machines page lists the sessions each machine keeps, with Re-attach and End, also while the setting is off. A Terminal only tab whose config signs in that way, and the partner terminal beside any SSH tab whose config signs in that way (on the machine itself, also for a config whose session runs in a container), are plain terminals with no assistant in them, and on a checked machine they run through the session helper as well, whatever their Connection, and are never kept: each is the machine's login shell, read with your rc files, in your home folder (a partner: in the session's folder, with nothing typed into it, or in your home folder when that folder is not on the machine, as on the usual SSH path), and it ends when you close it or quit. A Terminal only tab's post-connect command (an attach to a tmux session started elsewhere, for example) runs first in that login shell, carried to the machine in a variable of the session and never on a command line, and you are at an interactive shell when it ends or when you stop it with Ctrl-C; a machine whose login shell is not of the sh family (bash, zsh, sh, dash, ksh, mksh, ash or yash) keeps the usual SSH path for that tab, which types it at the first prompt as before. A Terminal only tab whose config runs in a container (its Runtime) enters that container as a step after its post-connect command, so it runs through the helper too, and when you leave the container a line says you are back on the machine, outside the container, and you are at your shell there; a config whose container name or folder the app does not accept keeps the usual SSH path, which refuses it and says why. The post-connect command of a Claude Code or Codex session runs through the helper too, as a step before the assistant starts: it runs first in the login shell, in your home folder, as the usual path types it there, and the assistant then starts in the session's folder with what the command exported (an activated environment or a PATH it set, for example), with no Run post-connect command? question and no launch anyway? question. Where the command fails or you stop it with Ctrl-C, the assistant is not started: the tab says why in one line and leaves you at your shell on the machine, and Restart tries again. A command that can fail for a harmless reason should end with ; true, so the assistant starts all the same (see Known issues). A login shell outside the sh family keeps the usual SSH path, as for a Terminal only tab. So does a command that opens a shell or a session of its own (su, sudo -i, ssh to another machine, a tmux or screen attach, a container's or a development environment's shell, exec), because the usual SSH path starts Claude Code inside that shell, where the helper would start it only once that shell ends; a Codex session with such a command starts nothing and says what to change. Every other SSH tab, and every new tab while the setting is off, runs the usual way: not through the helper yet are Claude Code and Codex sessions in a container (the assistant would run inside the container, where the helper is not), and macOS and Windows hosts. A sudo a post-connect command calls by that name, for any of these tabs, is answered with the config's saved sudo password through the helper: the app gives it once for each start of the tab, over the session's own connection, never typed into the terminal or shown, and only before the assistant starts; the container's own sudo (The container engine needs sudo, in Runtime) is answered the same way. A sudo that asks after that answer (a wrong saved password, or a second sudo on a machine set to ask for every one) asks in the terminal, where you type the password as on the usual SSH path. A config that saves a sudo password while its command calls no sudo by that name (its sudo is inside a script the command runs, or called by its full path (/usr/bin/sudo)) keeps the usual SSH path, which types the saved password at sudo's prompt; a Codex session, and an SSH Persistent session the helper keeps, go through the helper all the same, and that sudo asks in the terminal. With no saved sudo password, sudo asks in the terminal as before. A config that keeps a password signs in with it through the helper too: the app answers ssh's own password prompt for that machine, once for each connection, and only on a host key this computer already knows (open an SSH tab to it once with the setting off, to accept its key). It keeps the usual SSH path (a Codex config starts nothing) where the app cannot do that: the app's folder has a letter outside plain ASCII in its name and Windows keeps no plain short name for it, or this computer's ssh is older than OpenSSH 8.4. A password the machine refused is not sent again, and nothing is asked for that machine, until you correct it in the config or press Check. A key with a passphrase, or a password for a machine none of whose configs keeps a saved password the app can use, is asked for in a dialog when you press Add, Check or Remove on the Machines page or open a tab there; tick Keep to have the app hold it in memory for the rest of the run, so a reconnect can use it. A Codex config runs through the helper only (see Codex: sessions and accounts). A tab through the helper has its status line, its hooks (the attention mark, the canvas turn boundary, the Watchdog) and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) through the helper too. The session's own settings (your Claude Code settings on that machine, with the helper there for the status line and hooks) go into the .aicc folder on that machine and are removed when its session ends (quitting the app does not wait for that, so the next Check on the Machines page removes any that a quit or a dropped connection left, up to 1024 at one Check with any more at the next, and its message says how many sessions' files it removed and their size); no address or token of this computer is sent to the host. After a dropped connection, the hook events and the newest status line it missed arrive once it is back. Its status line names the account Claude Code is signed in as on that machine (read at each start from one field of Claude Code's config file there, never the whole file) and, when this computer holds that account, shows the usage reading this computer holds of it, never read on the host: the account counts as in use on the Accounts page, and its reading there is the 5-hour and weekly figures the tab reports, so the weekly limits by model and the extra usage show until the tab first reports, and the limits by model after that only while a Claude Code session on this computer runs on the same account; otherwise it says Model limits: not available, and its tooltip gives the reason (this machine uses its own sign-in, or this computer has no usage reading of the account yet), and when Claude Code on that machine names no account the header says Account not available. Prompt buttons and broadcast type into it as into any Claude Code tab. A tab whose Connection is SSH ends its session when you close it or quit. Restart of a Claude Code tab through the helper, and its restore when the app starts again, carry on with that tab's own conversation, by its id, never another tab's in the same folder; a tab with no message sent yet carries on with the newest conversation in its folder there. Linux x86-64 or arm64 hosts (an arm64 Raspberry Pi included; 32-bit Arm is not taken) with sha256sum, shasum or openssl only. Remove takes the helper away; it is refused while a tab runs there or a session is kept there (End it first). After an app update that changes the session helper, each added Linux machine reads not checked until you press Check on the Machines page; Check installs the new helper there and removes each earlier copy of the session helper there that no session kept there still uses, and its message says how many it removed and their size, and how many it kept. A copy a kept session may still use stays until a Check after that session ends. Earlier copies, and the files a quit or a dropped connection left, are removed only by a Check you press (or by Remove, which takes everything), over the connection that Check already made: the app never connects to a machine just to remove them, listing a machine's sessions (at the app's start, or when the Machines page opens) removes none of them, and a machine it cannot reach keeps them until its next Check. diff --git a/tests/unit/renderer/held-terminal-tab.test.ts b/tests/unit/renderer/held-terminal-tab.test.ts index c895b94e7..f9f795125 100644 --- a/tests/unit/renderer/held-terminal-tab.test.ts +++ b/tests/unit/renderer/held-terminal-tab.test.ts @@ -96,6 +96,6 @@ describe('the setting', () => { expect(block).toContain("Insights' Claude Code report runs this way too.") // 2.1.3-beta.17, plan section B1 (the release smoke): an update keeps it running, and its tab takes it over; // aicc_planning#515: with no Resume to press. - expect(block).toContain('On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens, which reopens your tabs by itself once the pages it opens with are closed: within five minutes of it opening, its tab takes the same session over.') + expect(block).toContain('On Windows it keeps running through an app update when you choose Save sessions, if the new version opens within two minutes. The new version reopens your tabs by itself once you close the pages it opens with (such as the release notes). Close them within five minutes and each tab shows the same session again.') }) }) diff --git a/tests/unit/renderer/session-launch.test.ts b/tests/unit/renderer/session-launch.test.ts index c6b491201..99f8ce6a1 100644 --- a/tests/unit/renderer/session-launch.test.ts +++ b/tests/unit/renderer/session-launch.test.ts @@ -116,7 +116,7 @@ describe('Settings, Resuming sessions wording (O9)', () => { expect(section).not.toContain('Auto-resume last') }) it('says which sessions it does not touch, that an update with Save sessions asks nothing, and nothing about a Codex sign-in on this computer', () => { - expect(section).toContain("Only matters with two or more Claude accounts. Applies when the app reopens your sessions. After an update where you chose Save sessions, each session carries on as it was, with nothing asked. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.") + expect(section).toContain("Only matters with two or more Claude accounts. Applies when you open the app again and resume your sessions. After an app update where you chose Save sessions, you are not asked: each session keeps the account it was on. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.") expect(section).not.toMatch(/this computer/i) expect(section).not.toContain(String.fromCodePoint(0x2014)) }) diff --git a/tests/unit/shared/app-knowledge.test.ts b/tests/unit/shared/app-knowledge.test.ts index 8f5c09977..0462328ef 100644 --- a/tests/unit/shared/app-knowledge.test.ts +++ b/tests/unit/shared/app-knowledge.test.ts @@ -2302,8 +2302,8 @@ describe('the 2.1.3-beta.8 sweep', () => { expect(machines).toContain('A Claude Code or Codex session has **End** only. After a crash it is ended') // aicc_planning#515: after an update with Save sessions the new version // reopens the tabs by itself (no Resume to press), still within five minutes. - expect(machines).toContain('On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once the pages it opens with are closed, and within five minutes of it opening') - expect(t.variants.primary.body).toContain('a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing to answer') + expect(machines).toContain('On Windows, **Save sessions** at an update keeps it running: the new version reopens its tab by itself, with nothing asked, once you close the pages it opens with (such as the release notes). Close them within five minutes and the tab shows the same session again') + expect(t.variants.primary.body).toContain('a Claude Code or Codex session is kept the same way: the new version reopens your tabs by itself, with nothing asked, once you close the pages it opens with (such as the release notes).') expect(t.variants.primary.body).toContain('Close them within **five minutes** of it opening') expect([machines, t.variants.primary.body].join(' ')).not.toMatch(/resume your sessions within/) expect(step('settings').highlights.join('\n')).toContain('or through an update when you choose **Save sessions**') @@ -2312,12 +2312,46 @@ describe('the 2.1.3-beta.8 sweep', () => { const line = readme().split('\n').find((l) => l.startsWith('- **Machines and the session helper**'))! expect(line).toContain('On Windows they also keep running through an app update when you choose Save sessions') const settingsPage = fs.readFileSync(path.resolve(__dirname, '..', '..', '..', 'src', 'renderer', 'components', 'SettingsPage.tsx'), 'utf8') - expect(settingsPage).toContain('On Windows they also keep running through an app update when you choose Save sessions, for up to two minutes until the new version opens.') + expect(settingsPage).toContain('On Windows they also keep running through an app update when you choose Save sessions, if the new version opens within two minutes.') // The update dialog's button is named exactly, as every other surface names it. const dialog = fs.readFileSync(path.resolve(__dirname, '..', '..', '..', 'src', 'renderer', 'components', 'CloseDialog.tsx'), 'utf8') expect(dialog).toContain('>Save sessions') }) + it('aicc_planning#514/#515: the Feature Guide and the README say what the dialog says, and that an update with Save sessions asks nothing', () => { + const body = (id: string) => APP_KNOWLEDGE_SECTIONS.find((s) => s.id === id)!.body + const sessions = body('sessions') + expect(sessions).toContain('Closing or updating with sessions open. The app asks first, with Save sessions, Close sessions and Cancel, and says what each does to your open tabs, with a count for each kind; a kind with none open is left out.') + expect(sessions).toContain('At a quit, with Save sessions, the Claude Code and Codex sessions stop and pick up their conversations at the next launch, except over SSH: an SSH Persistent session keeps running on its host and reconnects, and another SSH session stops and starts again then.') + expect(sessions).toContain('keep running through the update and come back in the same tabs (on Windows, the sessions the session helper holds, with Plain terminals through the session helper or Claude Code and Codex sessions through the session helper on)') + expect(sessions).toContain('the other Claude Code and Codex tabs on this computer restart and pick up their conversations') + expect(sessions).toContain('A sign-in or install tab is never saved: it closes and does not come back.') + expect(sessions).toContain('Close sessions ends every session and closes its tab') + expect(sessions).toContain('each session carries on as it was, on the account it was on.') + expect(body('accounts')).toContain('each session carries on as it was, on the account it was on.') + expect(body('machines')).toContain('a kept session whose tab is not restored within five minutes of the new version opening is ended.') + const line = readme().split('\n').find((l) => l.startsWith('- **Machines and the session helper**'))! + expect(line).toContain('the new version reopens your tabs with nothing asked (no resume prompt, no account picker)') + // The wording the review replaced is gone from every surface. + const settingsPage = fs.readFileSync(path.resolve(__dirname, '..', '..', '..', 'src', 'renderer', 'components', 'SettingsPage.tsx'), 'utf8') + const surfaces = [ + APP_KNOWLEDGE_SECTIONS.map((s) => s.body).join('\n'), + TIPS_LIBRARY.map((t) => t.variants.primary.body).join('\n'), + trainingSteps.flatMap((s) => [...(s.highlights ?? []), ...(s.withoutClaude?.highlights ?? [])]).join('\n'), + readme(), + settingsPage, + ].join('\n') + for (const gone of [ + /back in (?:their|its) tabs? straight away/, + /with its switches on/, + /carries on as it was, on its own account/, + /nothing to answer/, + /within five minutes of it opening/, + /for up to two minutes until the new version opens/, + /Applies when the app reopens your sessions/, + ]) expect(surfaces).not.toMatch(gone) + }) + it('the release notes carry the update warning, the way back and every change line', () => { const w = entry.warnings!.join('\n') expect(w).toContain("This beta series begins moving the app's background services") From d40240bb977ea7834f7ecbaefc3b881a0801692a Mon Sep 17 00:00:00 2001 From: nubbymong <192402368+nubbymong@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:09:10 +0000 Subject: [PATCH 42/79] fix(accounts): one shape per line, lines open on their own (planning #517) The Accounts page's closed lines came in two heights and said the same thing several times: a third line for the roles and "N running", a third for a per-model window or a note, a rate limit countdown on every idle line, and the same isolation change under every account it touched. - AccountsPage: lines open and close on their own (the open keys are a list; the setter's function form, so a refusal's late answer cannot close a line opened meanwhile). Escape closes only the open line that holds the keyboard focus, then focuses its toggle; the defaultPrevented and on-screen guards stay. The background check's rate limit is said once, in the Usage column heading. A strong rule (ROW_RULE) under each line, above each group, under the pending lines and above the unplaced ones. The foot: Tokenomics, the accounts note, the macOS note, the leftovers, How readings work on its own line, then What account isolation changed. - LedgerRow: every closed line is 64 px. Line 2 is the email, then the roles, in one span cut at its end; "N running" is the open line's Running row only. The inUseBand prop is gone. - UsageCell: closed, the account-wide windows only, and nothing under them. A per-model window at 90% or more is named in the last account-wide line's reset track ("Opus 92% used", warning colour), not over a used-up line's "back at". An estimate's figures read "~36% used" (aria "about 36% used"). Every note is on the open line's row, now labelled "Usage read". With no account-wide window, the one per-model window used most, so the cell is never empty. - AccountIsolationNotice: the row notice keeps only a refused or unchecked launch. New AccountIsolationChanges at the page's foot: one managedLaunchReports call per account, each on its own; findings joined only when id, title and detail are all equal; "All Claude Code accounts" when a change holds every account (more than one). - usage-parts: titleWhenCut, a tooltip only while the text is cut, in place of every title that repeated its own visible words; RateLimitedLine takes a testId. - layout: METER_COLS 44 / 132 / 68 / 128 (room for the "~"; the Usage floor stays 402 px), LINE_HEIGHTS_PX [64], ROW_RULE. Tests: independent opening, focus-scoped Escape, the late refusal, the heading's rate limit (and none from a line in use), ROW_RULE, the foot's order, the two-line Account cell, the closed shape, the "~" mark, the named per-model window, Usage read, titleWhenCut, and the foot's grouping (by id, title and detail; all accounts; one failure leaves the others; reordering refetches nothing). Co-Authored-By: Claude Opus 5.5 --- .../components/accounts/AccountsPage.tsx | 98 ++++++--- .../components/accounts/LedgerRow.tsx | 58 ++--- .../components/accounts/SignInLayers.tsx | 6 +- .../components/accounts/UsageCell.tsx | 163 +++++++++----- src/renderer/components/accounts/layout.ts | 28 ++- .../components/accounts/usage-parts.tsx | 26 ++- .../settings/AccountIsolationNotice.tsx | 169 ++++++++++---- .../account-isolation-notice.test.tsx | 144 +++++++++++- .../renderer/accounts-line-parity.test.tsx | 13 ++ tests/unit/renderer/accounts-page.test.tsx | 208 +++++++++++++++--- .../renderer/accounts-usage-cell.test.tsx | 144 ++++++++++-- 11 files changed, 807 insertions(+), 250 deletions(-) diff --git a/src/renderer/components/accounts/AccountsPage.tsx b/src/renderer/components/accounts/AccountsPage.tsx index 3fdb2b594..51fef1c46 100644 --- a/src/renderer/components/accounts/AccountsPage.tsx +++ b/src/renderer/components/accounts/AccountsPage.tsx @@ -13,6 +13,12 @@ // (28 px), the column headings (24 px) and the first group's heading (32 px). // Above them, only when there is one: an account whose name or colour was // changed both here and in its provider, to settle (ConflictBanner). +// +// nubbymong/aicc_planning#517: every closed line has one shape (64 px), a +// strong rule (ROW_RULE) parts one account from the next, lines open and +// close on their own, and what is the same for the whole page is said once: +// the background check's rate limit in the Usage heading, what account +// isolation changed at the foot. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react' import PageFrame from '../PageFrame' import { useRenderEvery } from '../../hooks/useRenderEvery' @@ -26,12 +32,13 @@ import { managedListProviders, providerView } from '../../stores/providerAccount import { PROVIDER_NAMES } from '../../provider-names' import { RowMenu } from '../ui/RowMenu' import { useMenuOccludesNativePanes, useSurfaceOnScreen } from '../../stores/paneOcclusionStore' -import { CLAUDE_OFF_USAGE_LINE, COUNTDOWN_TICK_MS, LineButton, MetersPending, MUTED, RENEWAL_BODY, Segmented } from './usage-parts' +import { CLAUDE_OFF_USAGE_LINE, COUNTDOWN_TICK_MS, LineButton, MetersPending, MUTED, RateLimitedLine, RENEWAL_BODY, Segmented } from './usage-parts' import { PROFILES_PROVIDER, leftoversLine, ledgerItems, nameOfProfile, type LedgerItem } from './ledger' import { LedgerRow, type LedgerRowSlots } from './LedgerRow' import { ConflictBanner } from './ConflictBanner' import { noBreakHyphens } from '../settings/accounts/accounts-ui' -import { ACCOUNT_GUTTER, LEDGER_INSET, LEDGER_TRACKS, WIDE_FROM_PX, type LedgerLayout } from './layout' +import { AccountIsolationChanges } from '../settings/AccountIsolationNotice' +import { ACCOUNT_GUTTER, LEDGER_INSET, LEDGER_TRACKS, ROW_RULE, WIDE_FROM_PX, type LedgerLayout } from './layout' import type { AccountsPageActions, AccountsPageData } from './model' /** Lines' ages move on while the page stays open. */ @@ -75,9 +82,9 @@ export const peopleIcon = ( ) -/** The open line and where each line stood, kept while the app runs (never - * saved), so coming back finds the page as it was left. */ -const memory: { open: string | null | undefined; basis: UsageGridEntry[] | null } = { open: undefined, basis: null } +/** The open lines and where each line stood, kept while the app runs + * (never saved), so coming back finds the page as it was left. */ +const memory: { open: readonly string[] | undefined; basis: UsageGridEntry[] | null } = { open: undefined, basis: null } /** Start the next drawing afresh (tests, the harness's seed switch). */ export function resetAccountsPageMemory(): void { @@ -176,7 +183,7 @@ function BandHeading({ band, alone }: { band: UsageBand; alone: boolean }) { /** A line before the profiles' list first resolves. */ function PendingRow({ layout }: { layout: LedgerLayout }) { return ( -