The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retire stale turn activity after completion and reconnect
Xipong30cab7927ef4
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex e5fefc9bfea..72aacd8d24f 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@ -579,7 +579,15 @@ describe('useSessionTileDelegate resumeTile', () => {describe('useSessionTileDelegate retireBusyClaim', () => {it('retires a stale busy claim through the session-state write path (#93059)', () => {- const busyState = { awaitingResponse: true, busy: true, messages: [{ id: 'm1' }], storedSessionId: 'stored-d' }+ const busyState = {+ awaitingResponse: true,+ busy: true,+ messages: [{ id: 'm1', pending: true }],+ storedSessionId: 'stored-d',+ turnLive: true,+ turnStartedAt: 1_000+ }+const sessionStateByRuntimeIdRef = { current: new Map([['runtime-dead', busyState]]) }const updateSessionState = vi.fn()@@ -591,10 +599,17 @@ describe('useSessionTileDelegate retireBusyClaim', () => {expect(sessionTileDelegate()!.retireBusyClaim!('runtime-dead')).toBe(true)expect(updateSessionState).toHaveBeenCalledWith('runtime-dead', expect.any(Function))- // The updater is the downgrade: busy/awaiting off, everything else intact.+ // Retire the running claim and its clock; a pending bubble can remain+ // until the transcript is rehydrated from the recovered backend.const updater = updateSessionState.mock.calls[0][1] as (state: typeof busyState) => typeof busyState- expect(updater(busyState)).toEqual({ ...busyState, awaitingResponse: false, busy: false })+ expect(updater(busyState)).toEqual({+ ...busyState,+ awaitingResponse: false,+ busy: false,+ turnLive: false,+ turnStartedAt: null+ })})it('reports a miss instead of minting a cache entry for a runtime it never held', () => {diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 7acfabe3769..92377be42d5 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -239,7 +239,13 @@ export function useSessionTileDelegate({return false}- updateSessionState(runtimeId, state => ({ ...state, awaitingResponse: false, busy: false }))+ updateSessionState(runtimeId, state => ({+ ...state,+ awaitingResponse: false,+ busy: false,+ turnLive: false,+ turnStartedAt: null+ }))return true},diff --git a/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx b/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsxindex b20846f776f..487a56a4b3b 100644--- a/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx@@ -9,7 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { __resetElapsedTimerRegistryForTests } from '@/components/chat/activity-timer'import { setSessionCompacting } from '@/store/compaction'-import { $activeSessionId, $turnStartedAt } from '@/store/session'+import { $activeSessionId, $busy, $turnStartedAt } from '@/store/session'import { stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'@@ -55,8 +55,9 @@ function runningAssistantMessage(id: string, text: string): ThreadMessage {}function Harness({ messages, isRunning = false }: { messages: ThreadMessage[]; isRunning?: boolean }) {- // isRunning: false at the runtime level. Per-message `status: {type:- // 'running'}` is what drives TurnActivityIndicator mounting.+ // The runtime adapter is idle to avoid auto-appending a placeholder to+ // trailing user/system rows. The session's busy claim independently owns+ // whether the tail activity row may render.// Passing isRunning: true makes useExternalStoreRuntime auto-append a// synthetic empty trailing assistant placeholder whenever the last message// is not already a running assistant, such as the trailing user prompt@@ -89,6 +90,7 @@ describe('TurnActivityIndicator tail gating (#68634)', () => {afterEach(() => {cleanup()setSessionCompacting(sessionId, false)+ $busy.set(false)$activeSessionId.set(null)$turnStartedAt.set(null)__resetElapsedTimerRegistryForTests()@@ -96,6 +98,8 @@ describe('TurnActivityIndicator tail gating (#68634)', () => {})it('renders exactly one indicator, on the later bubble, when two assistant bubbles are running with content', () => {+ $busy.set(true)+const { container } = render(<Harnessmessages={[diff --git a/apps/desktop/src/components/assistant-ui/thread/status.tsx b/apps/desktop/src/components/assistant-ui/thread/status.tsxindex d959a9e1f7c..d13b551a1a7 100644--- a/apps/desktop/src/components/assistant-ui/thread/status.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/status.tsx@@ -323,12 +323,14 @@ export const TurnActivityIndicator: FC = () => {// (`todo`, reactions) render nothing, so they narrate nothing.const toolNarrating = useAuiState(s => toolNarratesWait(s.message.content))- // Streaming counts as working too, and it leads busy by a flush on the first- // turn of a fresh chat — so the row can't wait for the store to catch up.+ // Streaming can lead busy by one view flush on the first turn of a fresh+ // chat. Honor that lead only while this session still has an armed turn+ // clock: a pending bubble can outlive the backend's busy=false settle and+ // must not keep its tail timer running after the turn ends.const messageRunning = useAuiState(s => s.message.status?.type === 'running')+ const working = busy || (messageRunning && turnStartedAt !== undefined)// Renderer-synthesized load bar (see ResponseLoadingIndicator).- const working = busy || messageRunningconst localLoad = useLocalModelLoad(working && !hint && !toolNarrating)useEffect(() => {diff --git a/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx b/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsxindex 419b3beb2f6..11760c0292d 100644--- a/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx@@ -2,11 +2,14 @@// is armed, but the tail bubble has settled — a sealed interim row, or a turn// whose last message completed while the agent kept going. The transcript used// to show nothing there, and the seconds went uncounted.-import { type ThreadMessage } from '@assistant-ui/react'+import { AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react'import { act, cleanup, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { useRuntimeMessageRepository } from '@/app/chat/runtime-repository'import { __resetElapsedTimerRegistryForTests } from '@/components/chat/activity-timer'+import type { ChatMessage } from '@/lib/chat-messages'+import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'import { $activeSessionId, $busy, $messages, $turnStartedAt } from '@/store/session'import { stubThreadEnvironment, ThreadRuntime, userMessage } from '../test-utils'@@ -42,6 +45,19 @@ const Harness = ({ messages }: { messages: ThreadMessage[] }) => (</ThreadRuntime>)+// Exercise the production conversion/adapter: reconnect may retire busy+// before a pending transcript row receives its terminal message.complete.+const RuntimeHarness = ({ messages }: { messages: ChatMessage[] }) => {+ const messageRepository = useRuntimeMessageRepository(messages)+ const runtime = useIncrementalExternalStoreRuntime({ messageRepository, isRunning: false, onNew: async () => {} })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread />+ </AssistantRuntimeProvider>+ )+}+const timerText = (value: string) => screen.getAllByText((_, node) => node?.textContent === value)describe('the turn timer covers the gaps, not just the streaming', () => {@@ -146,5 +162,36 @@ describe('the turn timer covers the gaps, not just the streaming', () => {act(() => $busy.set(true))act(() => vi.advanceTimersByTime(7_000))expect(container.querySelector('[data-slot="aui_turn-activity"][data-state="active"]')).toBe(row)++ it('does not revive a tail timer from a pending row after the session retires its busy claim', () => {+ $busy.set(false)+ $turnStartedAt.set(null)++ const messages: ChatMessage[] = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'do the thing' }] },+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: 'Done.' }], pending: true }+ ]++ const { container } = render(<RuntimeHarness messages={messages} />)++ act(() => vi.advanceTimersByTime(7_000))++ expect(container.querySelector('[data-slot="aui_turn-activity"]')).toBeNull()})++ it('still narrates a pending first bubble before the session busy flush arrives', () => {+ $busy.set(false)+ // Submit has armed the turn clock; the non-critical busy=true view flush+ // can trail the first streamed message by a frame.++ const messages: ChatMessage[] = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'do the thing' }] },+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: 'Working.' }], pending: true }+ ]++ const { container } = render(<RuntimeHarness messages={messages} />)++ act(() => vi.advanceTimersByTime(7_000))++ expect(container.querySelector('[data-slot="aui_turn-activity"]')).not.toBeNull() })})diff --git a/apps/desktop/src/store/session-states-reconnect.test.ts b/apps/desktop/src/store/session-states-reconnect.test.tsindex 297759eae7e..82d455aca76 100644--- a/apps/desktop/src/store/session-states-reconnect.test.ts+++ b/apps/desktop/src/store/session-states-reconnect.test.ts@@ -9,6 +9,7 @@ import {$awaitingResponse,$busy,$selectedStoredSessionId,+ $turnStartedAt,$unreadFinishedSessionIds} from './session'import { stampSecondaryProfileOwner } from './session-event-provenance'@@ -68,6 +69,7 @@ describe('reconcileBusyStatesOnReconnect', () => {$selectedStoredSessionId.set(null)$activeSessionId.set(null)$busy.set(false)+ $turnStartedAt.set(null)$awaitingResponse.set(false)setSessionTileDelegate(noDelegate)})@@ -80,6 +82,7 @@ describe('reconcileBusyStatesOnReconnect', () => {$selectedStoredSessionId.set(null)$activeSessionId.set(null)$busy.set(false)+ $turnStartedAt.set(null)$awaitingResponse.set(false)setSessionTileDelegate(noDelegate)})@@ -93,6 +96,17 @@ describe('reconcileBusyStatesOnReconnect', () => {expect($workingSessionIds.get()).not.toContain('s1')})+ it('retires the clock and live claim when the backend cannot finish a pending bubble', () => {+ $activeSessionId.set('rt1')+ publishSessionState('rt1', state({ busy: true, turnStartedAt: 1_000, turnLive: true }))+ $turnStartedAt.set(1_000)++ reconcileBusyStatesOnReconnect()++ expect($sessionStates.get()['rt1']).toMatchObject({ busy: false, turnStartedAt: null, turnLive: false })+ expect($turnStartedAt.get()).toBeNull()+ })+it('disarms the stall watchdog with the busy claim', () => {publishSessionState('rt1', state({ busy: true, storedSessionId: 's1' }))@@ -113,6 +127,31 @@ describe('reconcileBusyStatesOnReconnect', () => {expect($attentionSessionIds.get()).toContain('s1')})+ it('primary reconnect leaves a registry-scoped turn clock alone', () => {+ $activeSessionId.set('rtA')+ publishSessionState('rtA', state({ busy: true, storedSessionId: 'sA', turnStartedAt: 1_000, turnLive: true }))+ recordSessionEventScope({ connectionId: 'connA', profile: 'default', session_id: 'rtA' })+ $turnStartedAt.set(1_000)++ reconcileBusyStatesOnReconnect()++ expect($sessionStates.get()['rtA']).toMatchObject({ busy: true, turnStartedAt: 1_000, turnLive: true })+ expect($turnStartedAt.get()).toBe(1_000)+ })++ it('scoped reconnect retires its own focused turn clock', () => {+ const scope = registryBackendScopeKey('connA', 'default')+ $activeSessionId.set('rtA')+ publishSessionState('rtA', state({ busy: true, storedSessionId: 'sA', turnStartedAt: 1_000, turnLive: true }))+ recordSessionEventScope({ connectionId: 'connA', profile: 'default', session_id: 'rtA' })+ $turnStartedAt.set(1_000)++ reconcileBusyStatesOnReconnect(scope)++ expect($sessionStates.get()['rtA']).toMatchObject({ busy: false, turnStartedAt: null, turnLive: false })+ expect($turnStartedAt.get()).toBeNull()+ })+it('primary reconcile leaves registry-scoped sessions alone', () => {const scope = registryBackendScopeKey('connA', 'default')publishSessionState('rtA', state({ busy: true, storedSessionId: 'sA' }))diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex bbd40ea4910..a426c56ac69 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -72,7 +72,8 @@ import {setAwaitingResponse,setBusy,setSessions,- setTileSessionFocusStartedAt+ setTileSessionFocusStartedAt,+ setTurnStartedAt} from './session'import { secondaryProfileOwnerForEvent } from './session-event-provenance'import { $focusedTreePaneId } from './session-focus'@@ -1098,6 +1099,8 @@ export function clearAllSessionStates() {* alone — a background socket says nothing about the primary composer. */export function reconcileBusyStatesOnReconnect(scope?: string) {const states = $sessionStates.get()+ const focusedRuntimeId = $activeSessionId.get()+ let retiredFocusedTurn = false// Only the primary socket has a confirm producer for a parked completion// (the active profile's `session.active_list` poll); a scoped reconcile@@ -1116,13 +1119,23 @@ export function reconcileBusyStatesOnReconnect(scope?: string) {continue}+ if (runtimeId === focusedRuntimeId) {+ retiredFocusedTurn = true+ }+sessionTileDelegate()?.retireBusyClaim?.(runtimeId)// Re-read — the write path may have republished (and released) this entry.const published = $sessionStates.get()[runtimeId]if (published?.busy || published?.awaitingResponse) {- publishSessionState(runtimeId, { ...published, awaitingResponse: false, busy: false })+ publishSessionState(runtimeId, {+ ...published,+ awaitingResponse: false,+ busy: false,+ turnLive: false,+ turnStartedAt: null+ })}}} finally {@@ -1133,6 +1146,12 @@ export function reconcileBusyStatesOnReconnect(scope?: string) {setBusy(false)setAwaitingResponse(false)}++ // The global clock mirrors the focused session, whichever socket owns it.+ // A reconnect for a different backend must not reset that session's timer.+ if (retiredFocusedTurn) {+ setTurnStartedAt(null)+ }}// Derived per-session status sets — pure projections of `$sessionStates` (which