From e3d60c2263bbc170e9ad354a74dff23880039814 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Wed, 21 Oct 2026 15:16:39 +0200 Subject: [PATCH 1/2] harness: claim card branch Harness-Claim: true Agent: codex Host: ANCHOR Base-Ref: origin/main Base-SHA: 6af0716330841addf36c5e0cea60faa7fbb94980 Claimed-At: 2026-10-21T13:16:39.8546602Z Nonce: 01b7755065152bb1 From 215ec45e5cc0a73b6cd85c983d315d36f2d4d1ed Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Wed, 21 Oct 2026 16:56:05 +0200 Subject: [PATCH 2/2] (agents): a live interactive session is not hosted by a stale working job file (#764) --- .ai/contexts/bg-agents.md | 15 ++- CHANGELOG.md | 3 + bg-agents-roster.js | 7 +- test/bg-stale-interactive-764.test.js | 147 ++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 test/bg-stale-interactive-764.test.js diff --git a/.ai/contexts/bg-agents.md b/.ai/contexts/bg-agents.md index add33a942..421ec7f96 100644 --- a/.ai/contexts/bg-agents.md +++ b/.ai/contexts/bg-agents.md @@ -337,9 +337,18 @@ Leaving `blocked` removes that waiting evidence; the normal head-turn and PTY rules apply again. `stopped` and `failed` are finished even with a leftover descriptor. `isHostedJob(job, descriptors)` in `bg-agents-roster.js` is the single hosting -rule: a background job is hosted if working/blocked, or if a live `kind: bg` -descriptor matches its job id. Only a descriptor without a job id may match +rule: a background job is hosted if a live `kind: bg` descriptor matches its +job id. Only a descriptor without a job id may match its case-insensitive session id; two jobs can share a resumed conversation. +Without that bg evidence, a live interactive descriptor for the same +case-insensitive session id overrides a stale working/blocked job file (#764). +Otherwise working/blocked remains hosted: the original #374 file-only roster +and CLI fallback need no descriptor, and #682 retained that rule when adding +hosting between turns. No descriptor or job timestamp expires hosting. +The same override applies to conversation checks, `liveJobCheck` and `runVerb`. +Delete/Respawn and Stop then refuse through the existing interactive-process +guard (including processes owned here), naming the live pid rather than saying +to stop the stale daemon job first. Attach and daemon Stop are disabled in Agents. Stopped/failed override that evidence. Descriptors come from `cli-session-state.readAllDescriptors`: it parses the descriptor and checks `isProcessAlive(pid)`. Dead pids are excluded. It also reuses `deliveryProcessIdentity` to exclude confirmed stale process @@ -698,7 +707,7 @@ branch and the fallback keep the cwd's spelling. ## The sidebar `bgAgentSessionIds` (a `Set` of the `sessionId` of every live background job, -`agentJobIsLive`: working/blocked or done with a matching live bg descriptor) is rebuilt by `applyAgentsSnapshot`, +`agentJobIsLive`: the shared `hosted` verdict, including the interactive override above) is rebuilt by `applyAgentsSnapshot`, which refreshes the sidebar when membership or job activity changes. `sidebar.js` prefixes a `bg` badge ("click to attach") to a session row with #620's project membership or a matching roster id. Two diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d202a35..22e4f3637 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ### Changed - Quit (Exit on Windows), Restart to update and window close now name the local sessions, plain terminals and panel shells that will stop, with Stop and Cancel choices. Unsaved edits are handled first; attached background jobs and remote sessions are identified as continuing. (#546, #562) +### Fixed +- Sessions resumed interactively no longer keep a background badge or appear as running background jobs because of an old daemon job file. (#764) + ## v0.0.99 — 2026-10-21 ### Changed diff --git a/bg-agents-roster.js b/bg-agents-roster.js index 94e239a6d..c8e9b6574 100644 --- a/bg-agents-roster.js +++ b/bg-agents-roster.js @@ -253,8 +253,11 @@ function dispatchArgs(fields) { function isHostedJob(job, descriptors = []) { if (!job || job.kind && job.kind !== 'background' || job.state === 'stopped' || job.state === 'failed') return false; - return job.state === 'working' || job.state === 'blocked' || (descriptors || []).some(d => d?.kind === 'bg' - && (d.jobId ? d.jobId.toLowerCase() === String(job.id).toLowerCase() : job.sessionId && d.sessionId?.toLowerCase() === job.sessionId.toLowerCase())); + if ((descriptors || []).some(d => d?.kind === 'bg' + && (d.jobId ? d.jobId.toLowerCase() === String(job.id).toLowerCase() : job.sessionId && d.sessionId?.toLowerCase() === job.sessionId.toLowerCase()))) return true; + if ((descriptors || []).some(d => d?.kind === 'interactive' + && job.sessionId && d.sessionId?.toLowerCase() === job.sessionId.toLowerCase())) return false; + return job.state === 'working' || job.state === 'blocked'; } function dispatchRefusal({ sandbox, preLaunchCmd } = {}) { diff --git a/test/bg-stale-interactive-764.test.js b/test/bg-stale-interactive-764.test.js new file mode 100644 index 000000000..3f46a3fee --- /dev/null +++ b/test/bg-stale-interactive-764.test.js @@ -0,0 +1,147 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const bgAgents = require('../bg-agents'); +const cliSessionState = require('../cli-session-state'); +const bgIpc = require('../bg-agents-ipc'); +const { setupSidebarDom, makeSampleProject } = require('./dom-setup'); + +const SID = 'aaaaaaaa-1234-4321-abcd-123456789abc'; +const JOB = 'abcdef01'; +const PID = 987654; + +function fixture(t, state, descriptors) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sw-764-')); + const jobs = path.join(dir, 'jobs'); + const sessions = path.join(dir, 'sessions'); + fs.mkdirSync(path.join(jobs, JOB), { recursive: true }); + fs.mkdirSync(sessions); + fs.writeFileSync(path.join(jobs, JOB, 'state.json'), JSON.stringify({ state, sessionId: SID })); + for (const [index, descriptor] of descriptors.entries()) { + const pid = PID + index; + fs.writeFileSync(path.join(sessions, pid + '.json'), JSON.stringify({ + pid, sessionId: SID.toUpperCase(), status: 'idle', statusUpdatedAt: 1, cwd: dir, ...descriptor, + })); + } + cliSessionState.init({ dir: sessions, activeSessions: new Map(), onIdle() {}, + isProcessAlive: pid => descriptors[pid - PID]?.alive !== false, + readProcStartMany: async () => new Map(), platform: 'win32' }); + const calls = []; + bgAgents.init({ jobsDir: jobs, homeDir: dir, cliSessionState, + makeIsOwnPid: () => () => true, resolveProjectRoots: async () => null, + runClaude: async args => { + calls.push(args); + return { code: 0, stderr: '', stdout: args[0] === 'agents' + ? JSON.stringify([{ id: JOB, sessionId: SID, kind: 'background', state, cwd: dir }]) : '' }; + } }); + const handlers = new Map(); + bgIpc.init({ ipcMain: { handle: (name, fn) => handlers.set(name, fn) }, bgAgents, cliSessionState, + activeSessions: new Map(), sessionHasPty: () => false, ptyPids: () => [PID], + getMainWindow: () => null, log: { warn() {} } }); + t.after(() => { + bgAgents.stop(); + cliSessionState.stop(); + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 }); + }); + bgAgents.start(); + return { calls, handlers }; +} + +function sidebar(t, snapshot) { + const ctx = setupSidebarDom(); + t.after(() => ctx.destroy()); + ctx.evalPublic('agents-view.js'); + const project = makeSampleProject(); + project.sessions[0].sessionId = SID; + ctx.read('applyAgentsSnapshot')(snapshot); + ctx.sidebar.renderProjects([project], false); + return { ctx, row: ctx.document.querySelector(`[data-session-id="${SID}"]`) }; +} + +for (const state of ['working', 'blocked']) { + test(`[764] stale ${state} job with a live interactive descriptor is not hosted`, async t => { + fixture(t, state, [{ kind: 'interactive' }]); + const snapshot = await bgAgents.reconcile(); + assert.equal(snapshot.roster.find(e => e.id === JOB).hosted, false, + 'a live interactive conversation must override stale job state'); + assert.equal(bgAgents.conversationCheck(JOB).hosted, false); + assert.deepEqual(bgAgents.liveJobCheck(SID), { known: true, job: null }); + const { ctx, row } = sidebar(t, snapshot); + assert.ok(row); + assert.equal(row.querySelector('.bg-badge'), null, 'interactive sidebar row has no bg badge'); + assert.equal(ctx.read('bgAgentSessionIds').has(SID), false); + const entry = snapshot.roster.find(e => e.id === JOB); + assert.equal(ctx.read('agentJobIsLive')(entry), false, 'Agents must not count the job as running'); + const verbs = ctx.read('agentVerbAvailability')(entry, true); + assert.equal(verbs.attach, false); + assert.equal(verbs.stop, false); + assert.equal(verbs.rm, false, 'the live conversation still protects Delete'); + }); + + test(`[764] stale ${state} snapshot removes an existing sidebar bg badge`, async t => { + fixture(t, state, [{ kind: 'interactive' }]); + const { ctx, row } = sidebar(t, { daemonReachable: true, roster: [ + { id: JOB, sessionId: SID, kind: 'background', state, hosted: true }, + ] }); + assert.ok(row.querySelector('.bg-badge')); + ctx.read('applyAgentsSnapshot')(await bgAgents.reconcile()); + ctx.sidebar.renderProjects([makeProject()], false); + assert.equal(ctx.document.querySelector(`[data-session-id="${SID}"] .bg-badge`), null, + 'a refreshed interactive session must lose its stale bg badge'); + }); + + for (const jobId of [JOB.toUpperCase(), undefined]) { + test(`[764] ${state} job retains hosting with matching bg descriptor ${jobId || 'by session'}`, async t => { + fixture(t, state, [{ kind: 'interactive' }, { kind: 'bg', jobId }]); + const snapshot = await bgAgents.reconcile(); + assert.equal(snapshot.roster.find(e => e.id === JOB).hosted, true); + const { row } = sidebar(t, snapshot); + assert.ok(row.querySelector('.bg-badge'), 'real bg evidence keeps the badge'); + assert.equal(bgAgents.conversationCheck(JOB).hosted, true); + }); + } + + for (const descriptors of [[], [{ kind: 'interactive', alive: false }], + [{ kind: 'interactive', sessionId: 'bbbbbbbb-1234-4321-abcd-123456789abc' }]]) { + test(`[764] ${state} job remains hosted without a live matching interactive descriptor ${JSON.stringify(descriptors)}`, async t => { + fixture(t, state, descriptors); + const snapshot = await bgAgents.reconcile(); + assert.equal(snapshot.roster.find(e => e.id === JOB).hosted, true, + 'working/blocked file-only evidence must remain hosted'); + assert.ok(sidebar(t, snapshot).row.querySelector('.bg-badge')); + }); + } + + test(`[764] ${state} job cannot borrow another job's bg descriptor`, async t => { + fixture(t, state, [{ kind: 'interactive' }, { kind: 'bg', jobId: 'bbbbbbbb' }]); + const snapshot = await bgAgents.reconcile(); + assert.equal(snapshot.roster.find(e => e.id === JOB).hosted, false); + assert.equal(bgAgents.conversationCheck(JOB).hosted, false); + }); + + test(`[764] stale ${state} Delete and Stop refuse the live interactive pid, not stale hosting`, async t => { + const f = fixture(t, state, [{ kind: 'interactive' }]); + for (const verb of ['rm', 'respawn', 'stop']) { + for (const channel of ['check-bg-agent-verb', 'bg-agent-verb']) { + const result = await f.handlers.get(channel)({}, verb, JOB); + assert.equal(result.ok, false); + assert.match(result.error, new RegExp(String(PID)), 'refusal must identify the live interactive process'); + assert.doesNotMatch(result.error, /stop it first/); + } + } + assert.deepEqual(f.calls, [], 'no daemon command may touch the interactive conversation'); + assert.deepEqual(await bgAgents.runVerb('rm', JOB), { ok: true }, + 'the low-level daemon wrapper must not refuse solely on the stale state; IPC owns process safety'); + assert.deepEqual(f.calls[0], ['rm', JOB]); + }); +} + +function makeProject() { + const project = makeSampleProject(); + project.sessions[0].sessionId = SID; + return project; +}