diff --git a/.ai/contexts/bg-agents.md b/.ai/contexts/bg-agents.md index ba01359f0..9b688222d 100644 --- a/.ai/contexts/bg-agents.md +++ b/.ai/contexts/bg-agents.md @@ -369,6 +369,17 @@ is finished. Busy/head-turn and blocked waiting still follow turn evidence. `runVerb`, the fresh conversation check and `liveJobCheck` use the same hosting rule, including descriptors that changed after the last snapshot. +A non-hosted working/blocked job is grouped and labelled `Unknown` in Agents, +including the detail pane's job state, matching its finished count and Finished +filter (#767). Its labels and tooltip do not claim an active or blocked job. +Without a PTY here, activity selection ignores these stale jobs through marker, +identity and unique-head routes. The activity label and initial sidebar paint +respect that empty selection, so the interactive conversation keeps its normal +descriptor and transcript activity. A missing marked job still reads +`Activity unavailable`. +Owned PTYs retain their existing foreground projection; hosted jobs and +finished done/stopped/failed activity keep their existing selection rules. + | Display / verb | Hosted (including idle done) | Finished | |---|---|---| | State label after turn ends | Idle | done | diff --git a/public/agents-view.js b/public/agents-view.js index 5281c094e..41b10b862 100644 --- a/public/agents-view.js +++ b/public/agents-view.js @@ -74,6 +74,7 @@ function normalizeAgentsGroupBy(value) { function agentStateGroupKey(entry) { if (entry.kind === 'interactive') return 'external'; + if (['working', 'blocked'].includes(entry.state) && !agentJobIsLive(entry)) return 'unknown'; if (entry.state === 'done' && agentJobIsLive(entry)) return 'idle'; const known = entry.state && entry.state !== 'external' && entry.state !== 'unknown' && Object.hasOwn(AGENT_STATE_META, entry.state); return known ? entry.state : 'unknown'; @@ -174,7 +175,7 @@ function agentRowIcon(entry) { let snapshot = typeof taskActivitySnapshot === 'function' ? taskActivitySnapshot(entry.sessionId, ports, row, selection) : { ...ports, headTurn: 'unknown' }; if (entry.kind === 'background' && !foreground) snapshot = projectBackgroundActivity(entry, snapshot); const icon = renderSessionIcon(snapshot); - const title = entry.kind === 'background' && entry.state === 'blocked' + const title = entry.kind === 'background' && agentStateGroupKey(entry) === 'blocked' ? entry.sessionId && backgroundActivityLabel(entry.sessionId, snapshot, row, selection)?.title || `${icon.title} · job blocked` : icon.title; return { slotClass: icon.slotClasses[0], live, glyph: icon.glyph, title }; } @@ -203,7 +204,10 @@ function selectBackgroundActivity(sessionId, row) { row ||= typeof localActivityRow === 'function' ? localActivityRow(sessionId) : null; row ||= { sessionId }; const head = lower(row.headSessionId || row.sessionId || sessionId); - const finish = (entry, selection, unavailable = false) => ({ entry: entry || null, selection, + const superseded = entry => entry && ['working', 'blocked'].includes(entry.state) && !agentJobIsLive(entry) + && !(typeof activePtyIds !== 'undefined' && activePtyIds.has(sessionId)); + const finish = (entry, selection, unavailable = false) => superseded(entry) + ? { entry: null, selection: 'none', unavailable: false, source: 'none' } : ({ entry: entry || null, selection, unavailable, source: entry ? entry.taskEvidence?.valid === true ? 'job-valid' : 'job-invalid' : unavailable ? 'unavailable' : 'none' }); const exact = (jobId, target, selection) => { const entry = bgActivityEntries.get(lower(jobId)); @@ -220,7 +224,7 @@ function selectBackgroundActivity(sessionId, row) { if (attaches.size > 1) return finish(null, 'attach', true); if (attaches.size === 1) return attaches.values().next().value; if (row.identityJobId && (!row.identitySessionId || lower(row.identitySessionId) === head)) return exact(row.identityJobId, row.identitySessionId || 'missing', 'identity'); - const entries = [...bgActivityEntries.values()].filter(e => lower(e.sessionId) === head); + const entries = [...bgActivityEntries.values()].filter(e => lower(e.sessionId) === head && !superseded(e)); return entries.length === 1 ? finish(entries[0], 'unique-head') : finish(null, 'none', entries.length > 1); } @@ -263,19 +267,19 @@ function backgroundActivityLabel(sessionId, snapshot, row, selection) { selection ||= selectBackgroundActivity(sessionId, row); const entry = selection.entry; if (!entry) { - const background = selection.unavailable || row?.bgJobId; - return background ? { text: 'Activity unavailable', title: `${renderSessionIcon(snapshot).title}\nJob activity unavailable` } : null; + return selection.unavailable ? { text: 'Activity unavailable', title: `${renderSessionIcon(snapshot).title}\nJob activity unavailable` } : null; } if (backgroundActivityIsForeground(sessionId, row, selection)) return { text: renderSessionIcon(snapshot).title, title: '' }; + const state = ['working', 'blocked'].includes(entry.state) ? agentStateGroupKey(entry) : entry.state; const valid = entry.taskEvidence?.valid === true; const terminal = ['done', 'stopped', 'failed'].includes(entry.state); const kinds = valid ? (entry.taskEvidence.inFlightKinds || []).map(k => k.label).join(', ') : ''; const source = valid ? `Job updated ${new Date(entry.taskEvidence.at).toLocaleString()} (job metadata)${kinds ? ` · ${kinds}` : ''}` : 'Job activity unavailable'; - const title = `${renderSessionIcon(snapshot).title} · job ${entry.state || 'unknown'}\n${source}`; - if (entry.state === 'done' && agentJobIsLive(entry)) return { text: 'Idle', title }; - const text = entry.state === 'blocked' ? 'Blocked' : terminal ? `Job ${entry.state}` - : entry.state === 'working' && snapshot.attention ? 'Needs attention' : !valid ? 'Activity unavailable' - : entry.state === 'working' ? '' : 'Activity unavailable'; + const title = `${renderSessionIcon(snapshot).title} · job ${state || 'unknown'}\n${source}`; + if (state === 'done' && agentJobIsLive(entry)) return { text: 'Idle', title }; + const text = state === 'unknown' ? 'Unknown' : state === 'blocked' ? 'Blocked' : terminal ? `Job ${state}` + : state === 'working' && snapshot.attention ? 'Needs attention' : !valid ? 'Activity unavailable' + : state === 'working' ? '' : 'Activity unavailable'; return { text, title }; } @@ -475,7 +479,9 @@ function renderAgentDetail(entry) { const btn = (verb, label, enabled) => ``; const meta = []; - if (entry.id) meta.push('job ' + entry.id + (entry.jobState || entry.state ? ' · ' + (entry.jobState || entry.state) : '')); + const state = ['working', 'blocked'].includes(entry.state) && agentStateGroupKey(entry) === 'unknown' + ? 'Unknown' : entry.jobState || entry.state; + if (entry.id) meta.push('job ' + entry.id + (state ? ' · ' + state : '')); if (Number.isFinite(entry.tokens)) meta.push(formatTokens(entry.tokens) + ' tokens'); if (entry.model) meta.push(entry.model); if (Number.isFinite(entry.startedAt)) meta.push('started ' + new Date(entry.startedAt).toLocaleString()); diff --git a/public/sidebar.js b/public/sidebar.js index 114419f22..bcff8fbd4 100644 --- a/public/sidebar.js +++ b/public/sidebar.js @@ -2173,8 +2173,8 @@ function buildSessionItem(session) { // One icon slot per row, painted by session-activity-dom.js — see .ai/contexts/session-state.md const icon = document.createElement('span'); icon.className = 'session-icon' + (rowSessionIds(session).some(id => activePtyIds.has(id)) ? ' running' : ''); - const bgActivity = (typeof backgroundActivityLabel === 'function' && backgroundActivityLabel(rowHeadId(session), snapshot, session)) - || (session.bgJobId ? { text: 'Activity unavailable', title: `${renderSessionIcon(snapshot).title}\nJob activity unavailable` } : null); + const bgActivity = typeof backgroundActivityLabel === 'function' ? backgroundActivityLabel(rowHeadId(session), snapshot, session) + : (session.bgJobId ? { text: 'Activity unavailable', title: `${renderSessionIcon(snapshot).title}\nJob activity unavailable` } : null); const descriptor = localSessionForStatus(rowHeadId(session), session); paintSessionIconFromSnapshot(icon, snapshot, bgActivity?.title, bgActivity?.text, !bgActivity && descriptor, session); if (remoteAttention) paintSessionIconFromSnapshot(icon, remoteAttention, undefined, undefined, !bgActivity && descriptor, session); diff --git a/test/bg-stale-activity-767.test.js b/test/bg-stale-activity-767.test.js new file mode 100644 index 000000000..2f0c30d38 --- /dev/null +++ b/test/bg-stale-activity-767.test.js @@ -0,0 +1,65 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { setupSidebarDom } = require('./dom-setup'); +const { parseJobState, mergeRoster } = require('../bg-agents-roster'); + +const SID = 'aaaaaaaa-1234-4321-abcd-123456789abc'; +const JOB = 'abcdef01'; +const AT = Date.now() - 10_000; + +for (const state of ['working', 'blocked']) { + for (const route of ['marker', 'identity', 'unique-head']) { + for (const owned of [false, true]) { + test(`[767] ${state} ${route} interactive ${owned ? 'owned-PTY' : 'outside-terminal'} keeps normal activity`, t => { + const h = setupSidebarDom(); + t.after(() => h.destroy()); + h.window.Date.now = () => AT + 10_000; + const descriptor = { kind: 'interactive', sessionId: SID.toUpperCase(), pid: 12345, + cwd: '/repo', status: 'waiting', statusUpdatedAt: AT }; + const job = parseJobState(JSON.stringify({ state, sessionId: SID, updatedAt: new Date(AT).toISOString(), + inFlight: { tasks: 1, kinds: ['agent'] }, fan: [{ id: 'stale-agent', kind: 'agent', startedAt: AT }] })); + const roster = mergeRoster({ cli: [], jobs: new Map([[JOB, job]]), descriptors: [descriptor], isOwnPid: () => owned }); + assert.equal(roster.find(e => e.id === JOB).hosted, false); + const row = { sessionId: SID, projectPath: descriptor.cwd, status: descriptor.status, + statusUpdatedAt: AT, waitingFor: 'Choose a branch', summary: 'Interactive conversation', + ...(route === 'marker' ? { bgJobId: JOB, bgSessionId: SID } : {}), + ...(route === 'identity' ? { identityJobId: JOB, identitySessionId: SID } : {}) }; + h.window.sessionMap.set(SID, row); + if (owned) { + h.window.activePtyIds.add(SID); + h.window.openSessions.set(SID, { session: row, attach: false }); + h.window.setActivity(SID, true, 'test'); + h.emitHeadTurn(SID, 'open'); + } + const render = (session = row) => { + const item = h.sidebar.buildSessionItem(session); + h.document.getElementById('sidebar-content').replaceChildren(item); + return item; + }; + const before = render({ ...row, bgJobId: undefined, bgSessionId: undefined }); + const expectedTitle = owned ? 'Working · Open here' : before.querySelector('.session-icon').title; + const expectedStatus = owned ? 'Working' : before.querySelector('.session-status').textContent; + assert.match(expectedTitle, owned ? /^Working · Open here/ : /Running elsewhere\nCLI status: waiting · Choose a branch/); + h.evalPublic('agents-view.js'); + h.window.applyAgentsSnapshot({ roster, daemonReachable: true }); + const check = item => { + assert.equal(item.querySelector('.session-icon').title, expectedTitle, 'stale job must not replace interactive activity'); + assert.equal(item.querySelector('.session-status').textContent, expectedStatus); + assert.equal(!!item.querySelector('.bg-badge'), route === 'marker'); + const snapshot = h.window.storedActivitySnapshot(SID, row); + assert.equal(snapshot.liveness, 'alive'); + if (!owned) assert.equal(h.window.backgroundActivityLabel(SID, snapshot, row), null); + }; + const item = render(); + check(item); + h.window.applyStateClasses(SID, h.window.storedActivitySnapshot(SID, row)); + check(item); + h.window.paintSessionIcon(item.querySelector('.session-icon'), SID); + check(item); + if (!owned) assert.equal(h.window.selectBackgroundActivity(SID, row).entry, null, 'interactive session does not select stale job tasks'); + }); + } + } +} diff --git a/test/dom-agents-view.test.js b/test/dom-agents-view.test.js index 1d579d06f..374207f8e 100644 --- a/test/dom-agents-view.test.js +++ b/test/dom-agents-view.test.js @@ -117,6 +117,48 @@ const ROSTER = [ { id: null, sessionId: 's-i', name: 'lvds-1b', cwd: '/w/l', kind: 'interactive', state: null, status: 'busy', pid: 30, startedAt: Date.now() - 10_000, agent: null, model: null, detail: null, tempo: null, tokens: null, fan: [], children: [], result: null, attachedHere: false }, ]; +for (const [state, hosted, label] of [['working', false, 'Unknown'], ['blocked', false, 'Unknown'], ['working', true, 'Active']]) { + test(`[767] ${hosted ? 'hosted' : 'non-hosted'} ${state} job reads ${label} consistently with Finished`, async t => { + const h = setup({ storage: { agentsGroupBy: 'state' } }); + t.after(() => h.destroy()); + const entry = { ...ROSTER[0], state, hosted }; + h.setSnapshot({ daemonReachable: true, roster: [entry] }); + await h.window.showAgentsView(); + assert.equal(h.document.querySelector('.agents-group-label').textContent, label, 'group label follows hosting'); + assert.equal(h.document.querySelector('.agents-row-state').textContent.trim().replace(/^\S+\s+/, ''), label); + assert.equal(h.window.agentStateMeta(entry).key, hosted ? 'working' : 'unknown'); + assert.equal(h.document.getElementById('agents-viewer-count').textContent, hosted ? '1 running · 0 finished' : '0 running · 1 finished'); + if (!hosted) { + assert.doesNotMatch(h.document.querySelector('.session-icon').title, /job (working|blocked)/); + const detail = h.window.backgroundActivityLabel(entry.sessionId, {}, null, { entry, selection: 'unique-head' }); + assert.equal(detail.text, 'Unknown'); + assert.match(detail.title, /job unknown/); + assert.doesNotMatch(h.window.agentRowIcon({ ...entry, sessionId: null }).title, /job (working|blocked)/); + } + const finished = h.document.getElementById('agents-show-finished'); + finished.checked = false; + finished.dispatchEvent(new h.window.Event('change')); + assert.equal(h.document.querySelectorAll('.agents-row').length, hosted ? 1 : 0); + }); +} + +for (const [state, hosted, expected] of [ + ['working', false, 'Unknown'], ['blocked', false, 'Unknown'], + ['working', true, 'working'], ['blocked', true, 'blocked'], ['done', true, 'done'], +]) { + test(`[767b] ${hosted ? 'hosted' : 'non-hosted'} ${state} detail reads ${expected}`, async t => { + const h = setup(); + t.after(() => h.destroy()); + const entry = { ...ROSTER[0], state, jobState: state, hosted }; + h.setSnapshot({ daemonReachable: true, roster: [entry] }); + await h.window.showAgentsView(); + h.document.querySelector('.agents-row').click(); + const meta = h.document.querySelector('.agents-detail-meta').textContent; + assert.ok(meta.startsWith(`job ${entry.id} · ${expected} ·`), `detail state follows hosting: ${meta}`); + if (!hosted) assert.match(h.document.querySelector('.agents-row-state').textContent, /Unknown/); + }); +} + test('#563 every AGENT_STATE_META key reads its exact Title Case word', async t => { const h = setup(); t.after(() => h.destroy()); diff --git a/test/dom-grid-shared-activity-629.test.js b/test/dom-grid-shared-activity-629.test.js index b36e31b51..2740c8754 100644 --- a/test/dom-grid-shared-activity-629.test.js +++ b/test/dom-grid-shared-activity-629.test.js @@ -40,7 +40,7 @@ test('#563 sidebar and grid distinguish finished jobs from unknown liveness on r ctx.window.refreshSidebar = render; const card = create(); for (const [state, title] of [[null, 'Liveness unknown'], ['unrecognized', 'Liveness unknown'], - ['working', 'Liveness unknown'], ['blocked', 'Liveness unknown'], + ['working', 'Turn state unavailable'], ['blocked', 'Turn state unavailable'], ['done', 'Not running'], ['stopped', 'Not running'], ['failed', 'Not running']]) { ctx.window.applyAgentsSnapshot({ roster: [{ kind: 'background', id: 'job-629', sessionId: session.sessionId, state, hosted: false, status: null }], daemonReachable: true }); @@ -52,8 +52,9 @@ test('#563 sidebar and grid distinguish finished jobs from unknown liveness on r } const snapshot = ctx.window.storedActivitySnapshot(session.sessionId); const projected = ctx.window.backgroundActivitySnapshot(session.sessionId, snapshot); - assert.equal(projected.liveness, title === 'Not running' ? 'dead' : 'unknown'); + assert.equal(projected.liveness, ['working', 'blocked'].includes(state) ? 'alive' : title === 'Not running' ? 'dead' : 'unknown'); assert.equal(projected.stale, title === 'Not running'); + if (['working', 'blocked'].includes(state)) assert.equal(ctx.window.selectBackgroundActivity(session.sessionId).entry, null); }; check(); render();