From 3de0046bc445682a396e748259242bac3c51dd1b Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Fri, 20 Nov 2026 23:57:24 +0100 Subject: [PATCH 1/2] fix(terminals): assign a job to live tabs once the Windows job helper is ready Tabs whose job assignment failed during a slow start are now assigned once when a later helper start succeeds, the backoff expiry retries on its own, and the backoff uses a monotonic clock. --- .ai/contexts/ipc-bridge.md | 28 +++-- CHANGELOG.md | 2 +- src/main/terminals/pty-ops.js | 9 +- src/main/terminals/windows-job-helper.js | 40 ++++++- test/windows-job-helper.test.js | 9 +- test/windows-job-recovery.test.js | 133 +++++++++++++++++++++++ 6 files changed, 204 insertions(+), 17 deletions(-) create mode 100644 test/windows-job-recovery.test.js diff --git a/.ai/contexts/ipc-bridge.md b/.ai/contexts/ipc-bridge.md index 4214bff6b..267b06f6c 100644 --- a/.ai/contexts/ipc-bridge.md +++ b/.ai/contexts/ipc-bridge.md @@ -974,22 +974,34 @@ through its spawn port and a real Git bash; it skips when Git for Windows is unavailable. It does not exercise Electron or cover every MSYS tool. Before its first `ready`, a failed singleton settles requests false and permits up to three startup attempts per app session (#1140), each with the same 15 s -deadline. A later assignment (or explicit `start`) retries only after a backoff -of 1 s after the first failure and 2 s after the second; there is no background -retry timer. Concurrent tabs share one attempt and its readiness promise. +deadline. A later assignment (or explicit `start`) retries only after a monotonic +backoff of 1 s after the first failure and 2 s after the second. An unreferenced +timer also retries when that window expires while tracked live tabs are waiting +(#1156). Concurrent tabs share one attempt and its readiness promise. Close, release and observation cannot restart a failed helper. The fallback warning is emitted once per app session, while retry attempts, their failures and budget exhaustion are logged separately. Events from failed attempts are ignored, including delayed ready, exit and stream errors. -Failed assignments are not replayed: tabs created during failure/backoff keep -plain ConPTY close, and new tabs can acquire jobs after recovery. Retrofitting -old tabs would not capture children that already escaped and would complicate -PID/lifecycle ownership. Once a helper has been ready, its failure remains +Tracked tabs whose initial assignment fails during startup/backoff retain their +original PID and spawn timestamp. On readiness, each receives at most one late +assignment, only while its PTY is still live, unchanged, open and unreleased. +The helper removes the pending recovery before sending it; a failed late +assignment is never retried. Closing or releasing cancels pending recovery. +The late assignment promise updates the same PTY record as the initial one, +including evidence close and natural-exit observation. Plain ConPTY close stays +available while recovery is pending or has failed. +Children spawned before late assignment are not captured; only children spawned +after the root joins the job inherit membership and are ended on tab close. +Once a helper has been ready, its failure remains terminal for this session: a new process cannot inherit its existing job handles. This change only recovers startup failures, not lost jobs. Tests stub the spawn port and clock, including timeout-then-success through trackWindowsPty, permanent timeout/spawn failure, the retry cap and stale-attempt events. +`windows-job-recovery` combines the real PTY tracking and helper state machines +with a stubbed child process, independent monotonic/wall clocks and controlled +timers. It covers automatic and explicit recovery, lifetime guards, one late +attempt, job close, evidence close and backwards wall-clock steps. EOF/finally only closes handles, with no membership scan or termination. Release also just closes the handle; there is no limit flag to clear and no release-time flag API @@ -1160,7 +1172,7 @@ the assigned processes alive because no job is armed. Pure-Node native parent-ex tests exercise this property; they are not an Electron exit measurement. Resident PowerShell with P/Invoke may be flagged by EDR/AV or ended by the user. -There is no restart policy. No EDR product was tested. +After readiness there is no restart policy. No EDR product was tested. Tests load shipped production code: pty-ops-jobs covers close ordering, grace deadline, exclusions, detach and deferred assignment; windows-job-helper covers diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8b068f0..7d6943165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ### Fixed - After restarting the app or Windows, the sidebar shows the projects as they were at exit, even if the last project load finished just before you closed the app or signed out. (#1136) -- On Windows, a slow start no longer disables detached-process cleanup for every later tab: Switchboard retries up to twice for newly opened tabs. Tabs opened while cleanup is unavailable keep the existing close behavior. (#1140) +- On Windows, child processes of tabs restored at a slow start are now ended when the tab closes once cleanup recovers automatically. Children spawned before recovery cannot be captured. (#1140, #1156) - Claude and Codex sessions in `.work-files/worktrees/`, and Codex sessions in `.worktrees`, `.claude-worktrees` and `.claude/worktrees`, appear under their existing repository, including nested worktrees and sessions already indexed. Repository settings, archive and hidden state follow the group, and project deletion removes the session metadata it previews for both runtimes. Archiving a repository covers its worktrees' sessions; a new session in a worktree reopens the repository. Resume and fork use the recorded worktree directory and refuse to launch if it no longer exists; Claude sessions in a deleted `.claude/worktrees` directory are refused instead of starting in the repository. (#1137) - A conversation running as a background job (`claude --bg`) no longer slips into a project's collapsed "Older" rows: while its job is alive it stays visible and sorts with the running sessions, and the Running filter lists it, whatever the date of its last indexed message. (#1146) diff --git a/src/main/terminals/pty-ops.js b/src/main/terminals/pty-ops.js index ff23d1a1d..be07d9371 100644 --- a/src/main/terminals/pty-ops.js +++ b/src/main/terminals/pty-ops.js @@ -22,8 +22,15 @@ function trackWindowsPty(pty, { platform = process.platform, spawnTime = Date.no } else if (!record.closing) void releaseWindowsPty(pty); }); const current = () => !record.exited && !record.released && pty._agent?.exitCode === undefined; - const assign = at => record.assignment = jobs.assign(record.id, pty.pid, at, current) + const rememberAssignment = assignment => record.assignment = assignment .then(assigned => { record.assigned = assigned; return assigned; }); + const assign = at => { + const pid = pty.pid; + const samePty = () => current() && pty.pid === pid; + return rememberAssignment(jobs.assign(record.id, pid, at, samePty, { + current: () => samePty() && !record.closing, onLateAssignment: rememberAssignment, + })); + }; if (pty.pid > 0) return assign(spawnTime); return new Promise(resolve => { const socket = pty._agent?.outSocket; diff --git a/src/main/terminals/windows-job-helper.js b/src/main/terminals/windows-job-helper.js index 68911ed73..993dac6f4 100644 --- a/src/main/terminals/windows-job-helper.js +++ b/src/main/terminals/windows-job-helper.js @@ -3,6 +3,7 @@ const { spawn } = require('node:child_process'); const fs = require('node:fs'); const path = require('node:path'); +const { performance } = require('node:perf_hooks'); const ERROR_MEMBER_SKIPPED = 299; const MAX_START_ATTEMPTS = 3; @@ -10,16 +11,31 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st requestMs = 3000, protectedPids = () => [] } = {}) { let child, started = false, ready = false, failed = false, buffer = '', startupTimer, earlyCloseWarned = false; let attempts = 0, retryAt = 0, unavailableWarned = false; + let retryTimer; + const lateAssignments = new Map(); const pending = new Map(); const queued = new Map(); const waiting = new Map(); let resolveReady; let readiness; + function scheduleRetry() { + clearTimeout(retryTimer); + for (const [id, entry] of lateAssignments) if (!entry.current()) lateAssignments.delete(id); + if (ready || attempts >= MAX_START_ATTEMPTS) { lateAssignments.clear(); return; } + if (!failed || !lateAssignments.size) return; + retryTimer = setTimeout(() => { + retryTimer = undefined; + for (const [id, entry] of lateAssignments) if (!entry.current()) lateAssignments.delete(id); + if (lateAssignments.size) { start(); if (failed) scheduleRetry(); } + }, Math.max(0, retryAt - performance.now())); + retryTimer.unref?.(); + } + function fail(reason) { if (failed) return; failed = true; - retryAt = Date.now() + 1000 * 2 ** (attempts - 1); + retryAt = performance.now() + 1000 * 2 ** (attempts - 1); clearTimeout(startupTimer); resolveReady(false); for (const entry of pending.values()) { clearTimeout(entry.timer); entry.resolve(false); } @@ -32,6 +48,7 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st } catch {} unavailableWarned = true; try { child?.kill(); } catch {} + scheduleRetry(); } function settle(entry, value) { @@ -68,6 +85,11 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st ready = true; clearTimeout(startupTimer); resolveReady(true); for (const entry of queued.values()) send(entry); queued.clear(); + clearTimeout(retryTimer); + for (const [id, entry] of lateAssignments) { + lateAssignments.delete(id); + if (entry.current()) entry.onLateAssignment(request('assign', id, entry.args, entry.current)); + } continue; } const match = /^(assigned|terminated|released|observed|error) ([\w-]+)(?: (\d+))?$/.exec(line); @@ -84,9 +106,10 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st function start() { if (failed) { - if (ready || attempts >= MAX_START_ATTEMPTS || Date.now() < retryAt) return Promise.resolve(false); + if (ready || attempts >= MAX_START_ATTEMPTS || performance.now() < retryAt) return Promise.resolve(false); } else if (started) return readiness; started = true; + clearTimeout(retryTimer); failed = false; buffer = ''; const attempt = ++attempts; @@ -165,6 +188,8 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st } function finish(op, id, args = '') { + lateAssignments.delete(id); + if (!lateAssignments.size) clearTimeout(retryTimer); if (op === 'terminate' && !ready && !failed && !earlyCloseWarned) { earlyCloseWarned = true; try { warn('[pty] Tab closed before Windows job helper ready; using plain ConPTY close; hidden processes may remain'); } catch {} @@ -241,9 +266,16 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st if (!ready || failed || pending.has(id)) return Promise.resolve(null); return request('observe', id).then(value => value && typeof value === 'object' ? value : null); }, - assign(id, pid, spawnTime, current = () => true) { + assign(id, pid, spawnTime, current = () => true, { onLateAssignment, current: lateCurrent = current } = {}) { if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid || !Number.isSafeInteger(spawnTime)) return Promise.resolve(false); - return request('assign', id, ` ${pid} ${spawnTime}`, current); + const args = ` ${pid} ${spawnTime}`; + return request('assign', id, args, current).then(assigned => { + if (!assigned && failed && !ready && attempts < MAX_START_ATTEMPTS && onLateAssignment && lateCurrent()) { + lateAssignments.set(id, { args, current: lateCurrent, onLateAssignment }); + scheduleRetry(); + } + return assigned; + }); }, terminate, terminateWithEvidence, diff --git a/test/windows-job-helper.test.js b/test/windows-job-helper.test.js index 0406c1a16..93fad60d6 100644 --- a/test/windows-job-helper.test.js +++ b/test/windows-job-helper.test.js @@ -5,6 +5,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { EventEmitter } = require('node:events'); +const { performance } = require('node:perf_hooks'); for (const mode of ['nonempty', 'roster never settles', 'already expired']) { test(`A4c2afix evidence ${mode} preserves other jobs and releases its handle`, async t => { @@ -60,6 +61,7 @@ function fixture(t, options = {}) { test('a timed-out start followed by a successful retry gives the next tabs jobs', async t => { t.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + t.mock.method(performance, 'now', () => Date.now()); const { trackWindowsPty } = require('../src/main/terminals/pty-ops'); const children = [], writes = [], warnings = []; const { createWindowsJobHelper } = require('../src/main/terminals/windows-job-helper'); @@ -82,14 +84,14 @@ test('a timed-out start followed by a successful retry gives the next tabs jobs' t.mock.timers.tick(999); assert.equal(await helper.assign('during-backoff', 898, 100), false); assert.equal(children.length, 1, 'tab creation during backoff cannot spawn'); - t.mock.timers.tick(1); assert.equal(await helper.terminate('old-tab'), false, 'close must not trigger a retry'); assert.equal(await helper.release('old-tab'), false); assert.equal(await helper.observe('old-tab'), null); assert.equal(children.length, 1, 'cleanup and status must not trigger a retry'); + t.mock.timers.tick(1); const next = trackWindowsPty(tab(899), { jobs: helper, platform: 'win32', spawnTime: 100 }); const concurrent = trackWindowsPty(tab(900), { jobs: helper, platform: 'win32', spawnTime: 100 }); - assert.equal(children.length, 2, 'the next tab must retry helper startup'); + assert.equal(children.length, 2, 'waiting tabs and new tabs share one retry'); const retryReady = helper.start(); assert.notEqual(retryReady, firstReady, 'retry has its own readiness promise'); children[0].stdout.emit('data', 'ready\ninvalid\n'); @@ -100,7 +102,7 @@ test('a timed-out start followed by a successful retry gives the next tabs jobs' assert.deepEqual(writes, [], 'old helper events cannot flush the retry queue'); children[1].stdout.emit('data', 'ready\n'); assert.equal(await retryReady, true); - assert.equal(writes.length, 2, 'only new tabs are assigned; failed assignments are not replayed'); + assert.equal(writes.length, 3, 'new tabs and the failed live tab are assigned'); for (const line of writes) children[1].stdout.emit('data', `assigned ${line.split(' ')[1]}\n`); assert.equal(await next, true, 'next tab receives a job after recovery'); assert.equal(await concurrent, true); @@ -112,6 +114,7 @@ test('a timed-out start followed by a successful retry gives the next tabs jobs' for (const failure of ['timeout', 'spawn error']) { test(`permanently failing helper stops after three starts (${failure})`, async t => { t.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + t.mock.method(performance, 'now', () => Date.now()); let attempts = 0; const f = fixture(t, { spawn() { attempts++; diff --git a/test/windows-job-recovery.test.js b/test/windows-job-recovery.test.js new file mode 100644 index 000000000..32bc1c9b8 --- /dev/null +++ b/test/windows-job-recovery.test.js @@ -0,0 +1,133 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); +const { performance } = require('node:perf_hooks'); +const { createWindowsJobHelper } = require('../src/main/terminals/windows-job-helper'); +const { trackWindowsPty, killPty, releaseWindowsPty, stopPtyWithEvidence } = require('../src/main/terminals/pty-ops'); + +const flush = () => new Promise(resolve => setImmediate(resolve)); + +function fixture(t, { spawnError = false, lateError = false } = {}) { + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 100000 }); + let monotonic = 0; + t.mock.method(performance, 'now', () => monotonic); + const children = [], writes = [], tabs = []; + const helper = createWindowsJobHelper({ startupMs: 100, spawn() { + const child = new EventEmitter(); + children.push(child); + if (spawnError) throw new Error('denied'); + child.stdin = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); + child.kill = () => {}; + child.stdin.write = line => { + writes.push(line.trim()); + const [op, id] = line.trim().split(' '); + queueMicrotask(() => child.stdout.emit('data', op === 'assign' && lateError ? `error ${id} 5\n` + : op === 'observe' ? `observed ${id} 0\n` + : `${{ assign: 'assigned', terminate: 'terminated', release: 'released', 'terminate-retained': 'terminated' }[op]} ${id}\n`)); + }; + return child; + } }); + function tab(pid) { + let exited; + const pty = { pid, _agent: {}, onExit(fn) { exited = fn; }, + kill() { this._agent.exitCode = 0; exited(); }, exit() { exited(); } }; + tabs.push(pty); + pty.initial = trackWindowsPty(pty, { jobs: helper, platform: 'win32', spawnTime: 100 }); + return pty; + } + async function tick(ms) { monotonic += ms; t.mock.timers.tick(ms); await flush(); } + t.after(async () => { + children.forEach(child => child.emit('exit')); + await Promise.all(tabs.map(pty => releaseWindowsPty(pty))); + }); + return { helper, children, writes, tab, tick }; +} + +test('1156: waiting restored tabs recover without opening a new tab and close their jobs', async t => { + const f = fixture(t), a = f.tab(897), b = f.tab(898); + await f.tick(100); + assert.equal(await a.initial, false); assert.equal(await b.initial, false); + await f.tick(999); + assert.equal(f.children.length, 1); + await f.tick(1); + assert.equal(f.children.length, 2, 'backoff expiry must restart for waiting tabs'); + f.children[1].stdout.emit('data', 'ready\n'); await flush(); + assert.equal(f.writes.filter(line => line.startsWith('assign ')).length, 2, 'every live restored tab gets one late assignment'); + for (const pty of [a, b]) killPty({ pty, kind: 'local-pty' }, 'tab', { platform: 'win32' }); + await flush(); + const assigned = f.writes.filter(line => line.startsWith('assign ')).map(line => line.split(' ')[1]); + assert.deepEqual(f.writes.filter(line => line.startsWith('terminate ')), assigned.map(id => `terminate ${id}`)); +}); + +for (const state of ['exited', 'closed', 'released', 'native exit', 'changed pid']) { + test(`1156: recovery skips a ${state} tab and still assigns a live sibling`, async t => { + const f = fixture(t), gone = f.tab(897), live = f.tab(898); + await f.tick(100); await gone.initial; await live.initial; + if (state === 'exited') gone.exit(); + if (state === 'closed') { + gone.kill = () => {}; + killPty({ pty: gone, kind: 'local-pty' }, 'gone', { platform: 'win32' }); + } + if (state === 'released') await releaseWindowsPty(gone); + if (state === 'native exit') gone._agent.exitCode = 0; + if (state === 'changed pid') gone.pid = 999; + await f.tick(1000); + assert.equal(f.children.length, 2, 'a live sibling must trigger recovery'); + f.children[1].stdout.emit('data', 'ready\n'); await flush(); + const assignments = f.writes.filter(line => line.startsWith('assign ')); + assert.equal(assignments.length, 1, 'only the live sibling is assigned'); + assert.match(assignments[0], / 898 100$/); + }); +} + +test('1156: externally triggered readiness replays once and a failed late assignment stays failed', async t => { + const f = fixture(t, { lateError: true }), pty = f.tab(897); + await f.tick(100); await pty.initial; + t.mock.method(performance, 'now', () => 1100); + t.mock.timers.setTime(101100); + const ready = f.helper.start(); + assert.equal(f.children.length, 2, 'explicit start can recover before the retry timer fires'); + f.children[1].stdout.emit('data', 'ready\n'); await ready; await flush(); + assert.equal(f.writes.filter(line => line.startsWith('assign ')).length, 1, 'failed tab must receive its late attempt'); + await f.tick(60000); await f.helper.start(); await flush(); + assert.equal(f.writes.filter(line => line.startsWith('assign ')).length, 1, 'a native rejection must not loop'); +}); + +test('1156: late assignment updates the tracked assignment used by evidence close', async t => { + const f = fixture(t), pty = f.tab(897); + await f.tick(100); await pty.initial; + await f.tick(1000); + assert.equal(f.children.length, 2, 'waiting tab must recover'); + f.children[1].stdout.emit('data', 'ready\n'); await flush(); + const proof = await stopPtyWithEvidence({ pty, kind: 'local-pty', generation: 1 }, 'tab', { platform: 'win32' }); + assert.equal(proof.ended, true, 'evidence close must use the successful late assignment'); + assert.ok(f.writes.some(line => line.startsWith('terminate-retained '))); +}); + +for (const spawnError of [false, true]) { + test(`1156: autonomous retries exhaust three starts (${spawnError ? 'spawn error' : 'timeout'})`, async t => { + const f = fixture(t, { spawnError }), pty = f.tab(897); + await f.tick(100); await pty.initial; + await f.tick(1000); + assert.equal(f.children.length, 2, 'waiting tabs trigger the second attempt'); + if (!spawnError) await f.tick(100); + await f.tick(1999); assert.equal(f.children.length, 2); + await f.tick(1); assert.equal(f.children.length, 3); + await f.tick(100); await f.tick(60000); + assert.equal(f.children.length, 3, 'automatic retries must stop at the existing cap'); + }); +} + +test('1156: a backwards wall clock does not hold off helper startup retry', async t => { + const f = fixture(t); + const first = f.helper.assign('first', 897, 100); + await f.tick(100); assert.equal(await first, false); + t.mock.timers.setTime(0); + await f.tick(1000); + const next = f.helper.assign('next', 898, 100); + assert.equal(f.children.length, 2, 'monotonic backoff must expire despite Date.now moving backwards'); + f.children[1].stdout.emit('data', 'ready\n'); + assert.equal(await next, true); +}); From 9532f2ce1f3ab8f94462e2aef04082f697753492 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sat, 21 Nov 2026 00:24:53 +0100 Subject: [PATCH 2/2] fix(terminals): register a failed tab for late assignment even while it is being stopped A project-delete stop waiting on the first assignment no longer keeps the tab out of recovery, and the close/release/observe guard is tested again after the backoff expires. --- .ai/contexts/ipc-bridge.md | 15 ++++++++++++--- CHANGELOG.md | 2 +- src/main/terminals/windows-job-helper.js | 6 +++--- test/windows-job-helper.test.js | 17 +++++++++++++++++ test/windows-job-recovery.test.js | 24 ++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 7 deletions(-) diff --git a/.ai/contexts/ipc-bridge.md b/.ai/contexts/ipc-bridge.md index 267b06f6c..4b6adabd3 100644 --- a/.ai/contexts/ipc-bridge.md +++ b/.ai/contexts/ipc-bridge.md @@ -978,13 +978,20 @@ deadline. A later assignment (or explicit `start`) retries only after a monotoni backoff of 1 s after the first failure and 2 s after the second. An unreferenced timer also retries when that window expires while tracked live tabs are waiting (#1156). Concurrent tabs share one attempt and its readiness promise. -Close, release and observation cannot restart a failed helper. The fallback +Close, release and observation cannot restart a failed helper, even after the +backoff expires with no tracked tabs waiting. The fallback warning is emitted once per app session, while retry attempts, their failures and budget exhaustion are logged separately. Events from failed attempts are ignored, including delayed ready, exit and stream errors. Tracked tabs whose initial assignment fails during startup/backoff retain their -original PID and spawn timestamp. On readiness, each receives at most one late +original PID and spawn timestamp. Registration and retry retention check the +same live, unchanged, unreleased PTY even while an evidence stop is waiting for +its initial assignment. If that stop returns `IDENTITY` without killing the PTY, +the tab remains eligible for recovery and a later evidence stop can use its job. +The temporary `closing` guard is checked when readiness dispatches the late +assignment, not when registering or retaining the waiting tab. +On readiness, each receives at most one late assignment, only while its PTY is still live, unchanged, open and unreleased. The helper removes the pending recovery before sending it; a failed late assignment is never retried. Closing or releasing cancels pending recovery. @@ -1001,7 +1008,9 @@ permanent timeout/spawn failure, the retry cap and stale-attempt events. `windows-job-recovery` combines the real PTY tracking and helper state machines with a stubbed child process, independent monotonic/wall clocks and controlled timers. It covers automatic and explicit recovery, lifetime guards, one late -attempt, job close, evidence close and backwards wall-clock steps. +attempt, job close, evidence close racing a startup failure, and backwards +wall-clock steps. The helper tests also check cleanup after backoff expiry with +no waiting tabs; removing the non-assignment failure guard fails those checks. EOF/finally only closes handles, with no membership scan or termination. Release also just closes the handle; there is no limit flag to clear and no release-time flag API diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d6943165..fb9be14de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ### Fixed - After restarting the app or Windows, the sidebar shows the projects as they were at exit, even if the last project load finished just before you closed the app or signed out. (#1136) -- On Windows, child processes of tabs restored at a slow start are now ended when the tab closes once cleanup recovers automatically. Children spawned before recovery cannot be captured. (#1140, #1156) +- On Windows, a slow start no longer leaves tabs without process cleanup: tabs already open, restored ones included, are covered once cleanup starts, and programs they launch afterwards end when the tab closes. Programs launched before that can keep running. (#1140, #1156) - Claude and Codex sessions in `.work-files/worktrees/`, and Codex sessions in `.worktrees`, `.claude-worktrees` and `.claude/worktrees`, appear under their existing repository, including nested worktrees and sessions already indexed. Repository settings, archive and hidden state follow the group, and project deletion removes the session metadata it previews for both runtimes. Archiving a repository covers its worktrees' sessions; a new session in a worktree reopens the repository. Resume and fork use the recorded worktree directory and refuse to launch if it no longer exists; Claude sessions in a deleted `.claude/worktrees` directory are refused instead of starting in the repository. (#1137) - A conversation running as a background job (`claude --bg`) no longer slips into a project's collapsed "Older" rows: while its job is alive it stays visible and sorts with the running sessions, and the Running filter lists it, whatever the date of its last indexed message. (#1146) diff --git a/src/main/terminals/windows-job-helper.js b/src/main/terminals/windows-job-helper.js index 993dac6f4..d63eedbf7 100644 --- a/src/main/terminals/windows-job-helper.js +++ b/src/main/terminals/windows-job-helper.js @@ -88,7 +88,7 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st clearTimeout(retryTimer); for (const [id, entry] of lateAssignments) { lateAssignments.delete(id); - if (entry.current()) entry.onLateAssignment(request('assign', id, entry.args, entry.current)); + if (entry.lateCurrent()) entry.onLateAssignment(request('assign', id, entry.args, entry.lateCurrent)); } continue; } @@ -270,8 +270,8 @@ function createWindowsJobHelper({ spawn: spawnChild = spawn, warn = () => {}, st if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid || !Number.isSafeInteger(spawnTime)) return Promise.resolve(false); const args = ` ${pid} ${spawnTime}`; return request('assign', id, args, current).then(assigned => { - if (!assigned && failed && !ready && attempts < MAX_START_ATTEMPTS && onLateAssignment && lateCurrent()) { - lateAssignments.set(id, { args, current: lateCurrent, onLateAssignment }); + if (!assigned && failed && !ready && attempts < MAX_START_ATTEMPTS && onLateAssignment && current()) { + lateAssignments.set(id, { args, current, lateCurrent, onLateAssignment }); scheduleRetry(); } return assigned; diff --git a/test/windows-job-helper.test.js b/test/windows-job-helper.test.js index 93fad60d6..d63712aa8 100644 --- a/test/windows-job-helper.test.js +++ b/test/windows-job-helper.test.js @@ -111,6 +111,23 @@ test('a timed-out start followed by a successful retry gives the next tabs jobs' assert.equal(warnings.some(line => line.includes('stale warning')), false); }); +for (const operation of ['terminate', 'release', 'observe']) { + test(`1156: ${operation} cannot restart a failed helper after backoff without waiting tabs`, async t => { + t.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + t.mock.method(performance, 'now', () => Date.now()); + const f = fixture(t); + const assignment = f.helper.assign('untracked', 897, 100); + t.mock.timers.tick(5000); + assert.equal(await assignment, false); + t.mock.timers.tick(999); + assert.equal(f.invocations.length, 1); + t.mock.timers.tick(1); + const result = f.helper[operation]('untracked'); + assert.equal(f.invocations.length, 1, `${operation} must not restart after backoff expires`); + assert.equal(await result, operation === 'observe' ? null : false); + }); +} + for (const failure of ['timeout', 'spawn error']) { test(`permanently failing helper stops after three starts (${failure})`, async t => { t.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); diff --git a/test/windows-job-recovery.test.js b/test/windows-job-recovery.test.js index 32bc1c9b8..6e1846926 100644 --- a/test/windows-job-recovery.test.js +++ b/test/windows-job-recovery.test.js @@ -106,6 +106,30 @@ test('1156: late assignment updates the tracked assignment used by evidence clos assert.ok(f.writes.some(line => line.startsWith('terminate-retained '))); }); +test('1156: a failed evidence stop during startup preserves late recovery for the live tab', async t => { + const f = fixture(t), first = f.tab(897); + await f.tick(100); await first.initial; + await f.tick(1000); + assert.equal(f.children.length, 2); + const pty = f.tab(898); + const session = { pty, kind: 'local-pty', generation: 1 }; + const stopping = stopPtyWithEvidence(session, 'tab', { platform: 'win32' }); + await f.tick(100); + assert.equal(await pty.initial, false); + assert.equal((await stopping).code, 'IDENTITY'); + assert.equal(pty._agent.exitCode, undefined, 'failed evidence stop leaves the tab alive'); + await f.tick(2000); + assert.equal(f.children.length, 3); + f.children[2].stdout.emit('data', 'ready\n'); await flush(); + const assignments = f.writes.filter(line => line.startsWith('assign ')); + assert.equal(assignments.filter(line => line.endsWith(' 898 100')).length, 1, + 'the still-live tab must receive a late assignment after its failed evidence stop'); + const proof = await stopPtyWithEvidence(session, 'tab', { platform: 'win32' }); + assert.equal(proof.ended, true, 'a later evidence stop must use the recovered job'); + const id = assignments.find(line => line.endsWith(' 898 100')).split(' ')[1]; + assert.ok(f.writes.includes(`terminate-retained ${id}`)); +}); + for (const spawnError of [false, true]) { test(`1156: autonomous retries exhaust three starts (${spawnError ? 'spawn error' : 'timeout'})`, async t => { const f = fixture(t, { spawnError }), pty = f.tab(897);