Skip to content

The agent that grows with you

fix(desktop): a session's running highlight ends when its background work ends off screen

Tekniumc7da41dd522d
diff --git a/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts b/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts
new file mode 100644
index 00000000000..3b6f74be46d
--- /dev/null
+++ b/apps/desktop/e2e/sidebar-background-finish-offscreen.spec.ts
@@ -0,0 +1,93 @@
+/**
+ * A session's running highlight must end when its background work ends, even
+ * while the user is looking at another session.
+ *
+ * The background process here is spawned WITHOUT `notify_on_complete`, so its
+ * exit sends no event: the only things that can clear session A's row are the
+ * app-wide live-work roster read and the per-pane process poll, and the pane
+ * poll stops once A's pane is hidden. Before the fix the row kept its
+ * "Background task running" state until the user clicked back into A.
+ *
+ * Prerequisite: `npm run build` must have been run so dist/ exists.
+ */
+
+import { expect, test } from '@playwright/test'
+
+import {
+ createBackgroundReleaseHandle,
+ restartMockServer,
+ SIDEBAR_CROSS_TEXTS
+} from '../../../tests-js/scripts/mock-server'
+
+import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
+
+const BG_DOT_LABEL = 'Background task running'
+const SESSION_RUNNING_DOT_LABEL = 'Session running'
+// Script indices must line up with real chat turns (see sidebar-states.spec.ts).
+const DISABLE_AUTO_TITLE = 'auxiliary:\n title_generation:\n enabled: false'
+
+test.describe('sidebar — background work finishing off screen', () => {
+ test.describe.configure({ mode: 'serial' })
+
+ let fixture: MockBackendFixture
+ const bgRelease = createBackgroundReleaseHandle()
+
+ test.beforeAll(async () => {
+ restartMockServer()
+ fixture = await setupMockBackend({
+ extraConfig: DISABLE_AUTO_TITLE,
+ mockServer: { backgroundReleasePath: bgRelease.path, backgroundSilent: true }
+ })
+ await waitForAppReady(fixture, 120_000)
+ })
+
+ test.afterAll(async () => {
+ bgRelease.release()
+ await fixture?.cleanup()
+ bgRelease.cleanup()
+ })
+
+ test('a silent background process that exits while another session is open clears the row', async () => {
+ const page = fixture.page
+
+ const composer = page.locator('[contenteditable="true"]').first()
+ await composer.waitFor({ state: 'visible', timeout: 10_000 })
+ await composer.click()
+ await composer.type('E2E_SIDEBAR_CROSS', { delay: 20 })
+ await page.keyboard.press('Enter')
+
+ await page.waitForFunction(
+ text => (document.body.textContent ?? '').includes(text),
+ SIDEBAR_CROSS_TEXTS.finalText,
+ { timeout: 90_000 }
+ )
+ await expect
+ .poll(() => page.locator(`[aria-label="${SESSION_RUNNING_DOT_LABEL}"]`).count(), { timeout: 30_000 })
+ .toBe(0)
+ await expect
+ .poll(() => page.locator(`[aria-label="${BG_DOT_LABEL}"]`).count(), {
+ timeout: 30_000,
+ message: 'background dot should be visible after the turn completes'
+ })
+ .toBeGreaterThan(0)
+
+ await page.locator('button:has-text("New session")').first().click()
+ await page.waitForTimeout(2000)
+ await page.screenshot({ path: 'test-results/offscreen-bg-before-release.png' })
+
+ bgRelease.release()
+
+ // The roster is read every 10 s; two reads is ample. The screenshot is the
+ // evidence either way, so it is taken even when the row stays lit.
+ try {
+ await expect
+ .poll(() => page.locator(`[aria-label="${BG_DOT_LABEL}"]`).count(), {
+ timeout: 35_000,
+ message: 'background dot should clear without clicking back into the session'
+ })
+ .toBe(0)
+ } finally {
+ await page.screenshot({ path: 'test-results/offscreen-bg-after-release.png' })
+ }
+ })
+})
diff --git a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts
index 2d7dc50745c..80bd020c91c 100644
--- a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts
@@ -2,10 +2,12 @@ import { useStore } from '@nanostores/react'
import { useEffect } from 'react'
import { isMissingRpcMethod } from '@/lib/gateway-rpc'
+import { $backgroundRunningSessionIds } from '@/store/composer-status'
import { $gateway, activeGatewayProfileKey, gatewayRouteState, isActivePrimary } from '@/store/gateway'
import { $primaryGatewayRoute } from '@/store/gateway-primary-route'
import { $liveWorkRoster, rosterSourceHasWork, setLiveWorkRosterSource } from '@/store/live-work-roster'
import { $gatewayState, ownerLookupSessionRows } from '@/store/session'
+import { $delegatingSessionIds } from '@/store/session-dot-state'
import { ambientRequestFor } from '@/store/session-gone-latch'
import { isSessionOwnerRoute, requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
import { knownOwnerForSession } from '@/store/session-states'
@@ -22,6 +24,8 @@ interface RosterResult {
}
interface RosterSource {
+ /** Stored ids of the rows this source answers for. */
+ covers: string[]
open: boolean
owner: SessionOwnerScope
}
@@ -41,7 +45,7 @@ function rosterSources(): Map<string, RosterSource> {
// The ambient read carries no profile, so it shares a key only when it IS the
// window primary answering for its own profile.
const ambientKey = isActivePrimary() ? gatewayRouteState(null, activeGatewayProfileKey()).key : 'ambient'
- const sources = new Map<string, RosterSource>([[ambientKey, { open: true, owner: undefined }]])
+ const sources = new Map<string, RosterSource>([[ambientKey, { covers: [], open: true, owner: undefined }]])
// One row list per tick, each owner resolved against its own row: resolving
// through the whole list per row made a tick O(rows²).
@@ -53,9 +57,12 @@ function rosterSources(): Map<string, RosterSource> {
}
const route = routeOf(owner)
+ const source = sources.get(route.key)
- if (!sources.has(route.key)) {
- sources.set(route.key, { open: route.open, owner })
+ if (source) {
+ source.covers.push(row.id)
+ } else {
+ sources.set(route.key, { covers: [row.id], open: route.open, owner })
}
}
@@ -98,7 +105,11 @@ export function useLiveWorkRoster() {
const sentAt = new Map<string, number>()
const backoff = new Map<string, { failures: number; until: number }>()
- const readSource = async (key: string, owner: SessionOwnerScope, ambient: ReturnType<typeof ambientRequestFor>) => {
+ const readSource = async (
+ key: string,
+ { covers, owner }: RosterSource,
+ ambient: ReturnType<typeof ambientRequestFor>
+ ) => {
const at = Date.now()
sentAt.set(key, at)
inFlight.add(key)
@@ -109,7 +120,7 @@ export function useLiveWorkRoster() {
// A source whose rows left the sidebar mid-read stays pruned.
if (!cancelled && current.has(key)) {
- setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [], at)
+ setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [], at, covers)
}
} catch (error) {
if (isMissingRpcMethod(error)) {
@@ -138,6 +149,10 @@ export function useLiveWorkRoster() {
const sources = rosterSources()
const roster = $liveWorkRoster.get()
const now = Date.now()
+ // Rows lit right now: a closed source covering one is re-read on the busy
+ // cadence even when its last read was empty, so work an event feed saw
+ // start after that read still gets its end confirmed.
+ const lit = new Set([...$backgroundRunningSessionIds.get(), ...$delegatingSessionIds.get()])
current = new Set(sources.keys())
// Owners whose rows left the sidebar stop contributing.
@@ -147,15 +162,18 @@ export function useLiveWorkRoster() {
}
}
- for (const [key, { open, owner }] of sources) {
+ for (const [key, source] of sources) {
const last = sentAt.get(key)
const due = !inFlight.has(key) && !unsupported.has(key) && now >= (backoff.get(key)?.until ?? 0)
const warm =
- hydrate || open || last === undefined || (rosterSourceHasWork(roster, key) && now - last >= COLD_BUSY_MS)
+ hydrate ||
+ source.open ||
+ last === undefined ||
+ ((rosterSourceHasWork(roster, key) || source.covers.some(id => lit.has(id))) && now - last >= COLD_BUSY_MS)
if (due && warm) {
- void readSource(key, owner, ambient)
+ void readSource(key, source, ambient)
}
}
}
diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.ts
index e462bfa44d7..7a4e881ec86 100644
--- a/apps/desktop/src/store/composer-status.ts
+++ b/apps/desktop/src/store/composer-status.ts
@@ -6,7 +6,7 @@ import { type TodoItem, type TodoStatus, todoTree } from '@/lib/todos'
import { $gateway } from './gateway'
import { $goalsBySession, type GoalStatus } from './goals'
-import { $liveWorkRoster, noteEventFed, rosterLiveIds } from './live-work-roster'
+import { $liveWorkRoster, noteEventFed, rosterLiveIds, rosterSaysIdle } from './live-work-roster'
import { dispatchNativeNotification } from './native-notifications'
import { notifyError } from './notifications'
import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone, noteRuntimeAlive } from './runtime-gone'
@@ -84,9 +84,10 @@ export const $backgroundRunningSessionIds = computed(
// Same fresh-chat fallback as the working/attention projections: before a
// conversation is persisted its runtime id is the id surfaces key on.
const aliases = lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)
- noteEventFed(eventFedAt, aliases, backgroundWrittenAt.get(items) ?? -Infinity)
+ const writtenAt = backgroundWrittenAt.get(items) ?? -Infinity
+ noteEventFed(eventFedAt, aliases, writtenAt)
- if (items.some(i => i.state === 'running')) {
+ if (items.some(i => i.state === 'running') && !rosterSaysIdle(roster, 'background', aliases, writtenAt)) {
for (const alias of aliases) {
ids.add(alias)
}
diff --git a/apps/desktop/src/store/live-work-roster.test.ts b/apps/desktop/src/store/live-work-roster.test.ts
index ad2ba66ddac..fbb355e5ecc 100644
--- a/apps/desktop/src/store/live-work-roster.test.ts
+++ b/apps/desktop/src/store/live-work-roster.test.ts
@@ -49,6 +49,30 @@ describe('backend roster feeds rows no mounted tile speaks for', () => {
expect($backgroundRunningSessionIds.get()).toContain('old-pane')
})
+ it('a newer read from the source covering a row ends a running entry its hidden pane stopped updating', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000)
+ reconcileBackgroundProcesses('pane', [{ command: 'sleep', session_id: 'p1', status: 'running' }])
+ $subagentsBySession.set({ pane: [child('running', 1_000)] })
+ expect($backgroundRunningSessionIds.get()).toContain('pane')
+ expect($delegatingSessionIds.get()).toContain('pane')
+
+ setLiveWorkRosterSource('ambient', [], 2_000, ['pane'])
+
+ expect($backgroundRunningSessionIds.get()).not.toContain('pane')
+ expect($delegatingSessionIds.get()).not.toContain('pane')
+ })
+
+ it('a read from a source that does not cover the row never ends its running entry', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000)
+ reconcileBackgroundProcesses('pane', [{ command: 'sleep', session_id: 'p1', status: 'running' }])
+
+ setLiveWorkRosterSource('other-profile', [], 2_000, ['someone-else'])
+
+ expect($backgroundRunningSessionIds.get()).toContain('pane')
+ })
+
it('never stamps a local dismissal as a fresher backend snapshot than the roster read', () => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
diff --git a/apps/desktop/src/store/live-work-roster.ts b/apps/desktop/src/store/live-work-roster.ts
index 301887651bd..287d140ef69 100644
--- a/apps/desktop/src/store/live-work-roster.ts
+++ b/apps/desktop/src/store/live-work-roster.ts
@@ -20,6 +20,9 @@ export interface LiveWorkCounts {
export interface LiveWorkBucket {
at: number
+ /** Stored ids of the sidebar rows this source answers for: a row it covers
+ * and does not list has no live work as of `at`. */
+ covers: ReadonlySet<string>
sessions: Record<string, LiveWorkCounts>
}
@@ -27,7 +30,12 @@ export type LiveWorkRoster = Record<string, LiveWorkBucket>
export const $liveWorkRoster = atom<LiveWorkRoster>({})
-export function setLiveWorkRosterSource(source: string, entries: readonly unknown[] | null, at = Date.now()) {
+export function setLiveWorkRosterSource(
+ source: string,
+ entries: readonly unknown[] | null,
+ at = Date.now(),
+ covers: readonly string[] = []
+) {
const current = $liveWorkRoster.get()
if (!entries) {
@@ -58,7 +66,7 @@ export function setLiveWorkRosterSource(source: string, entries: readonly unknow
bucket[sid] = { background: Number(row.background) || 0, subagents: Number(row.subagents) || 0 }
}
- $liveWorkRoster.set({ ...current, [source]: { at, sessions: bucket } })
+ $liveWorkRoster.set({ ...current, [source]: { at, covers: new Set(covers), sessions: bucket } })
}
/** Stored ids (all lineage aliases) the roster says have `kind` running.
@@ -96,6 +104,26 @@ export function rosterLiveIds(
return [...ids]
}
+/** True when a source that answers for this conversation read it AFTER `eventAt`
+ * and found no `kind` work: an event-fed "running" entry that old is a
+ * leftover from a pane that stopped listening (its poll pauses while hidden,
+ * and a silent process exit sends no event), so the row must not stay lit
+ * until the user clicks back into it. A conversation no source covers keeps
+ * its event-fed state. */
+export function rosterSaysIdle(
+ roster: LiveWorkRoster,
+ kind: keyof LiveWorkCounts,
+ aliases: readonly string[],
+ eventAt: number
+): boolean {
+ return Object.values(roster).some(
+ ({ at, covers, sessions }) =>
+ at > eventAt &&
+ aliases.some(alias => covers.has(alias)) &&
+ aliases.every(alias => (sessions[alias]?.[kind] ?? 0) <= 0)
+ )
+}
+
/** Record `at` for every alias, keeping the freshest stamp per alias. */
export function noteEventFed(eventFedAt: Map<string, number>, aliases: readonly string[], at: number) {
for (const alias of aliases) {
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index 980c20715bc..87d199e5b3b 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -28,7 +28,7 @@ import { computed } from 'nanostores'
import { stableArray, stableRecord } from '@/lib/stable-array'
import { $backgroundRunningSessionIds } from './composer-status'
-import { $liveWorkRoster, noteEventFed, rosterLiveIds } from './live-work-roster'
+import { $liveWorkRoster, noteEventFed, rosterLiveIds, rosterSaysIdle } from './live-work-roster'
import { $pausedQueueSessionIds } from './owner-queue-reconcile'
import { $messagingSessions, $sessions, $unreadFinishedSessionIds, lineageAliases } from './session'
import {
@@ -62,9 +62,10 @@ export const $delegatingSessionIds = computed(
}
const aliases = lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)
- noteEventFed(eventFedAt, aliases, Math.max(...items.map(item => item.updatedAt || 0)))
+ const heardAt = Math.max(...items.map(item => item.updatedAt || 0))
+ noteEventFed(eventFedAt, aliases, heardAt)
- if (activeSubagentCount(items) > 0) {
+ if (activeSubagentCount(items) > 0 && !rosterSaysIdle(roster, 'subagents', aliases, heardAt)) {
for (const alias of aliases) {
ids.add(alias)
}
diff --git a/tests-js/scripts/mock-server.ts b/tests-js/scripts/mock-server.ts
index b6b7636803d..5f78b39bc37 100644
--- a/tests-js/scripts/mock-server.ts
+++ b/tests-js/scripts/mock-server.ts
@@ -55,6 +55,12 @@ verificationWritePath?: string
* handle's `path` to let the test decide when the process exits.
*/
backgroundReleasePath?: string
+/**
+ * Spawn the E2E_SIDEBAR_CROSS background process without `notify_on_complete`
+ * (default: notify). A silent process sends no completion event, so the only
+ * thing that can clear its sidebar state is a backend read.
+ */
+backgroundSilent?: boolean
/**
* Port to bind (default: any free port). An install/update journey runs its
@@ -244,7 +250,7 @@ function sidebarCrossBgCommand(releasePath?: string): string {
].join(' && ')
}
-function sidebarCrossScript(releasePath?: string): ScriptedTurn[] {
+function sidebarCrossScript(releasePath?: string, silent = false): ScriptedTurn[] {
return [
{
text: 'Starting a long background task and delegating work.',
@@ -254,7 +260,7 @@ function sidebarCrossScript(releasePath?: string): ScriptedTurn[] {
args: {
command: sidebarCrossBgCommand(releasePath),
background: true,
- notify_on_complete: true,
+ notify_on_complete: !silent,
},
},
{
@@ -892,7 +898,7 @@ export function startMockServer(options: MockServerOptions = {}): Promise<MockSe
}
if (isSidebarCrossTrigger) {
- const script = sidebarCrossScript(options.backgroundReleasePath)
+ const script = sidebarCrossScript(options.backgroundReleasePath, options.backgroundSilent)
const turn = script[_sidebarCrossIndex] ?? script[script.length - 1]
_sidebarCrossIndex++