The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop the session status going idle while the turn is running
Brooklyn Nicholsonb70c5cadb399
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 06dc49b56b4..32abacdacd2 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -92,18 +92,26 @@ export function rehydrateLiveSessionStatuses(const existing = $sessionStates.get()[runtimeSessionId]+ // A turn we just submitted is not yet running as far as the backend is+ // concerned, so the snapshot honestly reports it idle — but the local+ // stream is already waiting on its first token, and it is the newer+ // information. The stream path refuses to clear busy in exactly this window+ // (`awaitingResponse && !sawAssistantPayload`); without the same refusal+ // here a poll lands between submit and first token and darkens the row.+ const busy = working || Boolean(existing?.awaitingResponse && !existing.sawAssistantPayload)+// Avoid re-arming the watchdog on every poll. Publish only when the// authoritative live snapshot differs from the renderer mirror; normal// gateway events continue to own subsequent transitions.if (!existing ||existing.storedSessionId !== storedSessionId ||- existing.busy !== working ||+ existing.busy !== busy ||existing.needsInput !== needsInput) {publishSessionState(runtimeSessionId, {...(existing ?? createClientSessionState(storedSessionId)),- busy: working,+ busy,needsInput,storedSessionId})diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.tsindex 46152e076d3..c7d6f07102b 100644--- a/apps/desktop/src/store/composer-status.ts+++ b/apps/desktop/src/store/composer-status.ts@@ -8,6 +8,7 @@ import { $gateway } from './gateway'import { $goalsBySession, type GoalStatus } from './goals'import { dispatchNativeNotification } from './native-notifications'import { notifyError } from './notifications'+import { $sessions, lineageAliases } from './session'import { $sessionStates } from './session-states'import { $subagentsBySession, type SubagentProgress } from './subagents'import { $todosBySession } from './todos'@@ -41,32 +42,38 @@ export interface ComposerStatusItem {export const $backgroundStatusBySession = atom<Record<string, ComposerStatusItem[]>>({})// Stored session ids that have at least one RUNNING background process. The-// sidebar row reads this for a pulsing gray dot — distinct from the accent-// pulse of an active LLM turn — so the user can tell at a glance "this session-// has something chugging along in the background" even when the turn is idle.+// sidebar row reads this for a hollow dot — distinct from the filled dot of an+// active LLM turn — so the user can tell at a glance "this session has+// something chugging along in the background" even when the turn is idle.//// $backgroundStatusBySession is keyed by RUNTIME session id (gateway events// and process.list both speak that); the sidebar row knows only the STORED id.-// $sessionStates bridges the two: runtime id → state.storedSessionId.+// $sessionStates bridges the two: runtime id → state.storedSessionId, then+// lineageAliases covers whichever tip of that conversation a surface holds.// Perf: recomputes on every $sessionStates change (message deltas, tens/sec),// but the background-running set rarely moves. `stableArray` keeps the prior// reference when unchanged so rows reading this don't re-render per token.let backgroundRunningIds: readonly string[] = []-export const $backgroundRunningSessionIds = computed([$backgroundStatusBySession, $sessionStates], (bg, states) => {- const ids = new Set<string>()-- for (const [runtimeId, items] of Object.entries(bg)) {- if (items.some(i => i.state === 'running')) {- const storedId = states[runtimeId]?.storedSessionId+export const $backgroundRunningSessionIds = computed(+ [$backgroundStatusBySession, $sessionStates, $sessions],+ (bg, states, sessions) => {+ const ids = new Set<string>()++ for (const [runtimeId, items] of Object.entries(bg)) {+ if (!items.some(i => i.state === 'running')) {+ continue+ }- if (storedId) {- ids.add(storedId)+ // Same fresh-chat fallback as the working/attention projections: before a+ // conversation is persisted its runtime id is the id surfaces key on.+ for (const alias of lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)) {+ ids.add(alias)}}- }- return (backgroundRunningIds = stableArray(backgroundRunningIds, [...ids]))-})+ return (backgroundRunningIds = stableArray(backgroundRunningIds, [...ids]))+ }+)// Rows the user X-ed away. The registry keeps finished processes around for a// while, so without this every refresh would resurrect a dismissed row.diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 8c6811bf6ef..d127d6bcfc5 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -30,12 +30,15 @@ import {} from '@/components/pane-shell/tree/store'import { stableArray } from '@/lib/stable-array'import { readJson, writeJson } from '@/lib/storage'+import type { SessionInfo } from '@/types/hermes'import { $activeGatewayProfile, normalizeProfileKey } from './profile'import {$activeSessionId,$selectedStoredSessionId,+ $sessions,$unreadFinishedSessionIds,+ lineageAliases,setActiveSessionStoredIdRotation} from './session'import { isSecondaryWindow } from './windows'@@ -67,8 +70,13 @@ export function setSessionStalled(storedSessionId: string | null | undefined, st}}-// --- Watchdog: marks busy sessions quiet after 8 min of stream silence ------export const SESSION_WATCHDOG_TIMEOUT_MS = 8 * 60 * 1000+// --- Watchdog: marks busy sessions quiet after a long stream silence -------+// Tuned against what this app actually does rather than a round number: a+// typecheck or a full test run here goes quiet for minutes at a stretch and is+// perfectly healthy, so anything under ~4 min would paint normal work as+// suspect. Eight minutes was the other failure — longer than a user is willing+// to sit and wonder, so the hint arrived after they had already given up on it.+export const SESSION_WATCHDOG_TIMEOUT_MS = 5 * 60 * 1000const sessionWatchdogTimers = new Map<string, ReturnType<typeof setTimeout>>()function armWatchdog(runtimeId: string) {@@ -249,28 +257,54 @@ export function clearAllSessionStates() {// a turn), but these sets only change on busy/needsInput edges. `stableArray`// keeps the prior reference when membership is unchanged so `computed` skips the// emit — otherwise the whole sidebar + every row re-renders per token.-const storedIds = (states: Record<string, ClientSessionState>, pred: (s: ClientSessionState) => boolean) =>- Object.values(states)- .filter(s => pred(s) && s.storedSessionId)- .map(s => s.storedSessionId!)+// Published under every id the conversation answers to, not just its current+// tip: consumers hold whichever id they were created with, and compression+// rotates the tip out from under them (see lineageAliases).+//+// A conversation that has not been persisted yet has no stored id at all, and+// dropping it here is what left the FIRST turn of a new chat with no running+// indicator anywhere — no dot, no row arc — for as long as it took the backend+// to hand one back. Its runtime id is the right fallback because until a stored+// id exists the two are the same value (submit.ts: "an unpersisted+// conversation's queue key IS its runtime id"), so the row matches; once a+// session is persisted its runtime id is nobody's key and the fallback is inert.+const storedIds = (+ states: Record<string, ClientSessionState>,+ sessions: readonly SessionInfo[],+ pred: (s: ClientSessionState) => boolean+) => {+ const ids = new Set<string>()++ for (const [runtimeId, state] of Object.entries(states)) {+ if (!pred(state)) {+ continue+ }++ for (const alias of lineageAliases(state.storedSessionId ?? runtimeId, sessions)) {+ ids.add(alias)+ }+ }++ return [...ids]+}let workingIds: readonly string[] = []export const $workingSessionIds = computed(- $sessionStates,- states =>+ [$sessionStates, $sessions],+ (states, sessions) =>(workingIds = stableArray(workingIds,- storedIds(states, s => s.busy)+ storedIds(states, sessions, s => s.busy))))let attentionIds: readonly string[] = []export const $attentionSessionIds = computed(- $sessionStates,- states =>+ [$sessionStates, $sessions],+ (states, sessions) =>(attentionIds = stableArray(attentionIds,- storedIds(states, s => s.needsInput)+ storedIds(states, sessions, s => s.needsInput))))diff --git a/apps/desktop/src/store/session-watchdog.test.ts b/apps/desktop/src/store/session-watchdog.test.tsindex 2b023fd3736..a78d606757a 100644--- a/apps/desktop/src/store/session-watchdog.test.ts+++ b/apps/desktop/src/store/session-watchdog.test.ts@@ -10,10 +10,13 @@ import {$workingSessionIds,clearAllSessionStates,getRecentlySettledSessionIds,- publishSessionState+ publishSessionState,+ SESSION_WATCHDOG_TIMEOUT_MS} from './session-states'-const WATCHDOG_MS = 8 * 60 * 1000+// Read from the store rather than restated here: these assert what happens on+// either side of the threshold, not what the threshold is.+const WATCHDOG_MS = SESSION_WATCHDOG_TIMEOUT_MSfunction state(over: Partial<ClientSessionState> = {}): ClientSessionState {return { ...createClientSessionState(null), storedSessionId: 's1', ...over }@@ -213,12 +216,14 @@ describe('computed $workingSessionIds', () => {expect($workingSessionIds.get()).toEqual([])})- it('reflects sessions with busy=true and a storedSessionId', () => {+ it('reflects busy sessions under the id their surfaces key on', () => {publishSessionState('rt1', state({ busy: true, storedSessionId: 's1' }))publishSessionState('rt2', state({ busy: false, storedSessionId: 's2' }))+ // Not yet persisted, so the runtime id is the only id it has — and the one+ // the row is keyed by until the backend hands a stored id back.publishSessionState('rt3', state({ busy: true, storedSessionId: null }))- expect($workingSessionIds.get()).toEqual(['s1'])+ expect($workingSessionIds.get()).toEqual(['s1', 'rt3'])})it('updates when session state changes', () => {diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex 5bc19f5f786..fc2e8967f5f 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -81,9 +81,12 @@ describe('computed $attentionSessionIds', () => {expect($attentionSessionIds.get()).toEqual([])})- it('ignores sessions without a storedSessionId', () => {+ // A chat that hasn't been persisted yet has no stored id, and until it gets+ // one the surfaces key on its runtime id — so publishing under that is what+ // lets a clarify prompt on the very first turn reach the row.+ it('falls back to the runtime id for a session with no storedSessionId', () => {publishSessionState('rt1', { ...createClientSessionState(null), needsInput: true })- expect($attentionSessionIds.get()).toEqual([])+ expect($attentionSessionIds.get()).toEqual(['rt1'])})})diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex cb84c2c9c6e..cd1e6003e4c 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -254,6 +254,35 @@ export const sessionMatchesStoredId = (storedSessionId: string): boolean => session.id === storedSessionId || session._lineage_root_id === storedSessionId+/** Every id one conversation answers to: the id we were handed, plus the live+ * id and lineage root of each session it resolves to.+ *+ * Status sets are published under a session's CURRENT stored id, but a sidebar+ * row, a persisted tile, and the route can each hold a different tip of the+ * same lineage after a compression. Publishing every alias lets those surfaces+ * keep using a plain membership test instead of each re-deriving lineage —+ * and getting it wrong, which reads as a running session going idle mid-turn. */+export function lineageAliases(+ storedId: string,+ sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id'>[]+): string[] {+ const aliases = new Set([storedId])++ for (const session of sessions) {+ if (!sessionMatchesStoredId(session, storedId)) {+ continue+ }++ aliases.add(session.id)++ if (session._lineage_root_id) {+ aliases.add(session._lineage_root_id)+ }+ }++ return [...aliases]+}+/** True when two ids name the same conversation across compression tip rotation. */export function idsShareLineage(a: string,diff --git a/apps/desktop/src/store/working-ids-stored-id.test.ts b/apps/desktop/src/store/working-ids-stored-id.test.tsindex f302385a444..23e1cf69df6 100644--- a/apps/desktop/src/store/working-ids-stored-id.test.ts+++ b/apps/desktop/src/store/working-ids-stored-id.test.ts@@ -4,24 +4,20 @@ import { createClientSessionState } from '@/lib/chat-runtime'import { $workingSessionIds, clearAllSessionStates, publishSessionState } from '@/store/session-states'/**- * (C) The sidebar spinner reads `$workingSessionIds`, which projects- * `$sessionStates` down to STORED session ids and drops any entry whose- * `storedSessionId` is null. `message.start` flips `busy` without carrying a- * stored id, so a runtime that was never seeded with one goes busy invisibly:- * the backend works, the thread name stays bare.+ * The sidebar spinner and the row arc read `$workingSessionIds`, which projects+ * `$sessionStates` down to the ids surfaces actually key on. `message.start`+ * flips `busy` without carrying a stored id, so an unpersisted chat has none+ * yet — and until it does, its runtime id is that id.*/describe('$workingSessionIds — a busy runtime with no stored id', () => {afterEach(() => {clearAllSessionStates()})- it('cannot show a spinner for a busy runtime that has no stored id', () => {+ it('shows a new chat as running under its runtime id before it is persisted', () => {publishSessionState('runtime-unmapped', { ...createClientSessionState(null), busy: true })- // Documents the constraint rather than asserting the bug is fine: the- // projection is keyed by stored id, so an unmapped runtime is unreachable- // from the sidebar no matter how busy it is.- expect($workingSessionIds.get()).toEqual([])+ expect($workingSessionIds.get()).toEqual(['runtime-unmapped'])})it('shows the spinner as soon as the stored id is known', () => {