Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions .ai/contexts/bg-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions bg-agents-roster.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 } = {}) {
Expand Down
147 changes: 147 additions & 0 deletions test/bg-stale-interactive-764.test.js
Original file line number Diff line number Diff line change
@@ -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;
}
Loading