Skip to content

The agent that grows with you

fix(desktop): ask the backend before settling a silent live turn

emozilla77e2992020ea
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsx b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsx
index c1f1abd6d8d..8092d152ad6 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsx
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsx
@@ -1,9 +1,19 @@
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createClientSessionState } from '@/lib/chat-runtime'
import { $sidebarShowArchived } from '@/store/layout'
import { $changeEventsAvailable, $cronChangeTick, $sessionsChangeTick } from '@/store/live-sync'
+import { $onBattery } from '@/store/power'
import { $activeSessionId } from '@/store/session'
+import {
+ $sessionStates,
+ $workingSessionIds,
+ clearAllSessionStates,
+ LIVE_TURN_EVENT_SILENCE_MS,
+ noteSessionEvent,
+ publishSessionState
+} from '@/store/session-states'
import { loadArchivedSessions } from '@/store/sidebar-archive'
import { useBackgroundSync } from './use-background-sync'
@@ -124,3 +134,108 @@ describe('useBackgroundSync profile-scoped session refresh', () => {
expect(loadArchivedSessions).toHaveBeenCalledTimes(1)
})
})
+
+describe('useBackgroundSync keeps a quiet working turn live', () => {
+ // A foreground tool emits nothing between tool.start and tool.complete; the
+ // backend is the only witness that the turn is still running.
+ const LONG_TOOL_MS = LIVE_TURN_EVENT_SILENCE_MS * 4
+
+ const working = async () => ({
+ sessions: [{ id: 'rt-quiet', last_active: Date.now() / 1000, session_key: 's-quiet', status: 'working' }]
+ })
+
+ function startQuietTurn() {
+ publishSessionState('rt-quiet', {
+ ...createClientSessionState('s-quiet'),
+ awaitingResponse: true,
+ busy: true,
+ sawAssistantPayload: true,
+ turnLive: true,
+ turnStartedAt: Date.now()
+ })
+ noteSessionEvent('rt-quiet')
+ }
+
+ const cardShown = () =>
+ Boolean($sessionStates.get()['rt-quiet']?.messages.some(message => message.errorSurface))
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ clearAllSessionStates()
+ $activeSessionId.set(null)
+ $changeEventsAvailable.set(true)
+ $onBattery.set(false)
+ $sessionsChangeTick.set(0)
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ clearAllSessionStates()
+ $onBattery.set(false)
+ vi.useRealTimers()
+ })
+
+ it('while the window is not focused', async () => {
+ vi.spyOn(document, 'hasFocus').mockReturnValue(false)
+ startQuietTurn()
+ render('default', 'local', async () => undefined, working)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LONG_TOOL_MS)
+ })
+
+ expect($workingSessionIds.get()).toContain('s-quiet')
+ expect($sessionStates.get()['rt-quiet']?.interrupted).toBeFalsy()
+ expect(cardShown()).toBe(false)
+ })
+
+ it('on battery, where the backstop poll is slower than the silence window', async () => {
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)
+ $onBattery.set(true)
+ startQuietTurn()
+ render('default', 'local', async () => undefined, working)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LONG_TOOL_MS)
+ })
+
+ expect($workingSessionIds.get()).toContain('s-quiet')
+ expect(cardShown()).toBe(false)
+ })
+
+ it('while the gateway stops answering', async () => {
+ vi.spyOn(document, 'hasFocus').mockReturnValue(false)
+ startQuietTurn()
+ const request = vi.fn(working)
+ render('default', 'local', async () => undefined, request)
+ await act(async () => undefined)
+ request.mockImplementation(async () => {
+ throw new Error('Hermes gateway unavailable')
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LONG_TOOL_MS)
+ })
+
+ // No answer is not an ending: the stall hint and Stop stay available.
+ expect($workingSessionIds.get()).toContain('s-quiet')
+ expect(cardShown()).toBe(false)
+ })
+
+ it('and settles it once the backend reports it over', async () => {
+ vi.spyOn(document, 'hasFocus').mockReturnValue(false)
+ startQuietTurn()
+ const request = vi.fn(working)
+ render('default', 'local', async () => undefined, request)
+ await act(async () => undefined)
+ request.mockImplementation(async () => ({ sessions: [] }))
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LIVE_TURN_EVENT_SILENCE_MS)
+ })
+
+ expect($workingSessionIds.get()).not.toContain('s-quiet')
+ expect($sessionStates.get()['rt-quiet']?.interrupted).toBeFalsy()
+ })
+})
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index f13848b25ee..52338c9e35f 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -42,6 +42,7 @@ import {
noteSessionEvent,
publishSessionState,
SESSION_WATCHDOG_TIMEOUT_MS,
+ setLiveTurnBackend,
setSessionStalled
} from '@/store/session-states'
import { loadArchivedSessions } from '@/store/sidebar-archive'
@@ -736,10 +737,12 @@ export function rehydrateLiveSessionStatuses(
})
}
- if (working) {
- // A poll that still lists the turn is an event. Reset the silence clock
- // so a quiet tool call is not settled; a dead backend stops answering
- // this poll and the clock runs out.
+ if (working || session.status === 'starting') {
+ // A poll that still lists the turn is an event: reset the silence
+ // clock so a quiet tool call is not checked early. 'starting' is the
+ // agent build for a turn the backend accepted (a cold local model); it
+ // feeds the clock without claiming a spinner, since a lazy resume
+ // builds with no turn at all.
noteSessionEvent(runtimeSessionId)
}
@@ -1062,6 +1065,29 @@ export function useBackgroundSync({
// eslint-disable-next-line react-hooks/exhaustive-deps -- connect-scoped: session deps would fire on every switch
}, [activeConnectionId, activeGatewayProfile, gatewayState])
+ // A live turn that goes quiet is checked against the backend that runs it
+ // (store/session-states onEventSilence), not against this window's poll
+ // cadence, which pauses while unfocused and slows on battery. When that
+ // backend reports the turn over, the stored transcript catches up the
+ // reply its lost end events would have carried.
+ useEffect(
+ () =>
+ setLiveTurnBackend({
+ request: requestGateway,
+ refreshTranscript: (runtimeSessionId, storedSessionId) =>
+ hydrateStoredSessionTranscript({
+ attempts: 3,
+ runtimeSessionId,
+ storedProfile: profileScopeForTranscriptSession(
+ resolveActiveTranscriptSession(storedSessionId, runtimeSessionId)
+ ),
+ storedSessionId,
+ updateSessionState
+ })
+ }),
+ [requestGateway, updateSessionState]
+ )
+
// A reconnect loses renderer-only working/attention atoms while the backend
// keeps the actual turns alive. Re-seed from the gateway's in-memory session
// registry immediately, then re-pull on every sessions.changed broadcast; a
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.ts
index 0f11346d76d..7acfabe3769 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
@@ -243,6 +243,15 @@ export function useSessionTileDelegate({
return true
},
+ updateHeldSession: (runtimeId, updater) => {
+ if (!sessionStateByRuntimeIdRef.current.has(runtimeId)) {
+ return false
+ }
+
+ updateSessionState(runtimeId, updater)
+
+ return true
+ },
interruptSession: async runtimeId => {
// Read-only stored-transcript tiles have no live turn to interrupt.
if (isReadOnlyRuntimeId(runtimeId)) {
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index d5e7266fbbd..b2d1131a179 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -5527,6 +5527,10 @@ export const deOverrides = {
body: provider =>
`${provider} war nicht erreichbar oder hat nicht rechtzeitig geantwortet. Prüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.`
},
+ no_reply: {
+ title: 'Die Antwort wurde nicht fertig',
+ body: 'Hermes hat diesen Durchlauf ohne Antwort beendet. Versuchen Sie es erneut, um sie noch einmal zu senden.'
+ },
stream_drop: {
title: 'Die Antwort wurde abgebrochen',
body: 'Die Verbindung ist abgebrochen, bevor die Antwort fertig war. Versuchen Sie es erneut, um sie noch einmal zu senden.'
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index ee5a33acb71..8d530bc10a1 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -5129,6 +5129,10 @@ export const en: Translations = {
title: 'The reply was cut off',
body: 'The connection dropped before the reply finished. Retry to send it again.'
},
+ no_reply: {
+ title: "The reply didn't finish",
+ body: 'Hermes ended this turn without a reply. Retry to send it again.'
+ },
upstream_blocked: {
title: 'A firewall blocked the request',
body: provider =>
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 08ea1bafad5..11ba0c0e735 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -5520,6 +5520,10 @@ export const esOverrides = {
body: (provider: string) =>
`No se pudo conectar con ${provider} o no respondió a tiempo. Revisa tu conexión a internet y vuelve a intentarlo.`
},
+ no_reply: {
+ title: 'La respuesta no terminó',
+ body: 'Hermes terminó este turno sin respuesta. Reinténtalo para enviarla de nuevo.'
+ },
stream_drop: {
title: 'La respuesta se cortó',
body: 'La conexión se cortó antes de que terminara la respuesta. Reinténtalo para enviarla de nuevo.'
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index 7dd7ea632ae..4ca2f751e96 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -5542,6 +5542,10 @@ export const frOverrides = {
body: provider =>
`${provider} est injoignable ou n'a pas répondu à temps. Vérifiez votre connexion internet, puis réessayez.`
},
+ no_reply: {
+ title: "La réponse n'a pas abouti",
+ body: 'Hermes a terminé ce tour sans réponse. Réessayez pour la renvoyer.'
+ },
stream_drop: {
title: 'La réponse a été interrompue',
body: 'La connexion a été coupée avant la fin de la réponse. Réessayez pour la renvoyer.'
diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.ts
index 5e67a570af8..079d731d766 100644
--- a/apps/desktop/src/lib/error-surface.ts
+++ b/apps/desktop/src/lib/error-surface.ts
@@ -50,6 +50,9 @@ export const ERROR_CODE_KEYS = [
'loop_error',
'SESSION_NOT_OWNED',
'disk_full',
+ // Raised by the desktop, never by the backend: the backend reported a turn
+ // over after its events stopped, and no reply reached this window.
+ 'no_reply',
// The Nous free tier refused or could not serve the turn (agent/error_surface.py
// `free_tier_<kind>`). The backend's sentence rides in `message` and is the card body.
'free_tier_disabled',
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 8e5297e1fc9..bbd40ea4910 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -33,7 +33,12 @@ import {
} from '@/components/pane-shell/tree/store'
import { resolveRememberedActivePane, workspaceScopeKey } from '@/components/pane-shell/workspace-scope'
import type { WorkspaceMode } from '@/contrib/types'
-import type { ChatMessage } from '@/lib/chat-messages'
+import {
+ type ChatMessage,
+ chatMessageText,
+ finalizeInterruptedMessages,
+ sealOpenToolParts
+} from '@/lib/chat-messages'
import type { ErrorSurface } from '@/lib/error-surface'
import { tileFocusStampOnFocusChange } from '@/lib/session-timer-since'
import { stableArray } from '@/lib/stable-array'
@@ -395,18 +400,50 @@ export function setSessionStalled(storedSessionId: string | null | undefined, st
// 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 * 1000
-// A live turn that stops producing events — including after a partial payload —
-// must not wait out the presentation hint above. The clock resets on every
-// session event and on a live-status poll that still reports the turn working,
-// so a quiet tool call is left alone. The window outlasts the 30s live-status
-// backstop: a dead backend stops both events and polls, and this settles it
-// instead of leaving the spinner up. Not keyed on a model name or an error string.
+// A live turn that goes this long without a session event is checked against
+// its backend. Silence alone proves nothing: a foreground tool emits nothing
+// between tool.start and tool.complete, a local model can prefill for minutes,
+// and the live-status poll that also resets this clock pauses while the window
+// is not viewed and slows to 2 min on battery. Only the backend decides whether
+// the turn is over (see onEventSilence).
export const LIVE_TURN_EVENT_SILENCE_MS = 45_000
+// Bound on the status request itself; past it the check counts as unanswered.
+export const LIVE_TURN_PROBE_TIMEOUT_MS = 15_000
const sessionEventSilenceTimers = new Map<string, ReturnType<typeof setTimeout>>()
+// One token per status check in flight: an event, a settle, or a newer check
+// drops it, so a late answer cannot act on a turn that moved on.
+const silentTurnChecks = new Map<string, object>()
+
+type AmbientGatewayRequest = <R>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<R>
+
+interface LiveTurnBackend {
+ /** The window's gateway requester; the check routes through the session's
+ * owner, so this only answers for sessions it provably owns. */
+ request: AmbientGatewayRequest
+ /** Pull the stored transcript for an on-screen session whose turn the
+ * backend reported ended, so a reply that finished there shows up here. */
+ refreshTranscript?: (runtimeId: string, storedSessionId: string) => Promise<unknown> | unknown
+}
+
+let liveTurnBackend: LiveTurnBackend | null = null
+
+/** Register the backend a silent live turn is checked against. Returns the
+ * unregister function; with nothing registered, a silent turn is left alone. */
+export function setLiveTurnBackend(backend: LiveTurnBackend): () => void {
+ liveTurnBackend = backend
+
+ return () => {
+ if (liveTurnBackend === backend) {
+ liveTurnBackend = null
+ }
+ }
+}
function clearEventSilence(runtimeId: string) {
const timer = sessionEventSilenceTimers.get(runtimeId)
+ silentTurnChecks.delete(runtimeId)
+
if (timer) {
clearTimeout(timer)
sessionEventSilenceTimers.delete(runtimeId)
@@ -417,36 +454,140 @@ function isLiveTurnAwaitingEvents(state: ClientSessionState | undefined): boolea
return Boolean(state && (state.busy || state.awaitingResponse || state.turnLive) && !state.needsInput)
}
-const SILENT_TURN_RETRY: ErrorSurface = { code: 'stream_drop', layer: 'streaming', retryable: true }
+export type LiveTurnVerdict = 'ended' | 'running' | 'unknown'
-function withSilentTurnRetry(messages: ChatMessage[], streamId: string | null): ChatMessage[] {
- const occurredAt = Date.now() / 1000
- const error = 'The connection dropped before the reply finished.'
+interface LiveTurnStatusResponse {
+ sessions?: { id?: string; status?: string }[]
+}
+
+/** What one `session.active_list` snapshot says about `runtimeId`'s turn. A
+ * runtime missing from a well-formed list has been reaped: its turn is over.
+ * `starting` is an agent build for a turn the backend accepted. */
+export function liveTurnVerdict(response: LiveTurnStatusResponse | null | undefined, runtimeId: string): LiveTurnVerdict {
+ if (!Array.isArray(response?.sessions)) {
+ return 'unknown'
+ }
+
+ const status = response.sessions.find(session => session.id?.trim() === runtimeId)?.status
- const targetId =
- (streamId && messages.some(message => message.id === streamId) ? streamId : null) ??
- [...messages].reverse().find(message => message.role === 'assistant' && message.pending)?.id ??
- null
+ if (status === undefined || status === 'idle') {
+ return 'ended'
+ }
+
+ return status === 'starting' || status === 'waiting' || status === 'working' ? 'running' : 'unknown'
+}
- const unpended = messages
- .filter(message => !(message.pending && message.parts.length === 0 && message.id !== targetId))
- .map(message =>
- message.pending || message.id === targetId ? { ...message, completedAt: occurredAt, pending: false } : message
+async function checkLiveTurn(runtimeId: string): Promise<LiveTurnVerdict> {
+ const backend = liveTurnBackend
+
+ if (!backend) {
+ return 'unknown'
+ }
+
+ try {
+ // Owner-routed: a turn in another profile's pane is answered by the
+ // backend running it, not by whichever gateway this window shows. An
+ // unresolved owner throws, which counts as no answer.
+ const response = await requestForOwnedSession<LiveTurnStatusResponse>(
+ runtimeId,
+ backend.request,
+ 'session.active_list',
+ {},
+ LIVE_TURN_PROBE_TIMEOUT_MS
)
- if (targetId && unpended.some(message => message.id === targetId)) {
- return unpended.map(message =>
- message.id === targetId ? { ...message, error, errorSurface: SILENT_TURN_RETRY, pending: false } : message
+ return liveTurnVerdict(response, runtimeId)
+ } catch {
+ return 'unknown'
+ }
+}
+
+/** Write through the wiring cache when it holds the runtime, so the cache,
+ * the focused view, and tile mirrors agree (#93059); otherwise the mirror. */
+function writeSessionState(runtimeId: string, updater: (state: ClientSessionState) => ClientSessionState) {
+ if (sessionTileDelegate()?.updateHeldSession?.(runtimeId, updater)) {
+ return
+ }
+
+ const current = $sessionStates.get()[runtimeId]
+
+ if (current) {
+ publishSessionState(runtimeId, updater(current))
+ }
+}
+
+/** The backend reported the turn over and its end events never arrived. Settle
+ * it like the running=false edge: nothing is interrupted, the kept stream
+ * bubble is remembered so a late message.complete settles onto it. */
+function settleEndedLiveTurn(runtimeId: string) {
+ const occurredAt = Date.now() / 1000
+
+ writeSessionState(runtimeId, state => {
+ if (!isLiveTurnAwaitingEvents(state)) {
+ return state
+ }
+
+ const messages = sealOpenToolParts(finalizeInterruptedMessages(state.messages, state.streamId, occurredAt))
+
+ return {
+ ...state,
+ awaitingResponse: false,
+ busy: false,
+ heartbeatSettledStreamId:
+ state.streamId && messages.some(message => message.id === state.streamId) ? state.streamId : null,
+ messages,
+ pendingBranchGroup: null,
+ streamId: null,
+ turnLive: false,
+ turnStartedAt: null
+ }
+ })
+}
+
+// Raised only after the backend confirmed the turn is over and no reply reached
+// this window, so Retry cannot run the prompt twice.
+const NO_REPLY_SURFACE: ErrorSurface = { code: 'no_reply', layer: 'runtime', retryable: true }
+const NO_REPLY_ERROR = 'Hermes ended this turn without a reply.'
+
+function turnHasReply(messages: ChatMessage[]): boolean {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index]
+
+ if (message.hidden) {
+ continue
+ }
+
+ if (message.role === 'user') {
+ return false
+ }
+
+ if (message.role === 'assistant' && (message.error || chatMessageText(message).trim())) {
+ return true
+ }
+ }
+
+ return false
+}
+
+function withNoReplyNotice(messages: ChatMessage[]): ChatMessage[] {
+ const last = messages.findLast(message => !message.hidden)
+
+ // A turn that ran tools but never wrote text carries the notice on its own bubble.
+ if (last?.role === 'assistant') {
+ return messages.map(message =>
+ message === last ? { ...message, error: NO_REPLY_ERROR, errorSurface: NO_REPLY_SURFACE } : message
)
}
+ const occurredAt = Date.now() / 1000
+
return [
- ...unpended,
+ ...messages,
{
completedAt: occurredAt,
- error,
- errorSurface: SILENT_TURN_RETRY,
- id: `assistant-interrupted-${Date.now()}`,
+ error: NO_REPLY_ERROR,
+ errorSurface: NO_REPLY_SURFACE,
+ id: `assistant-no-reply-${Date.now()}`,
parts: [],
pending: false,
role: 'assistant',
@@ -455,29 +596,67 @@ function withSilentTurnRetry(messages: ChatMessage[], streamId: string | null):
]
}
-function settleSilentLiveTurn(runtimeId: string) {
- const current = $sessionStates.get()[runtimeId]
+/** Stamp the retry card on an ended turn that has no reply. A newer turn the
+ * user started meanwhile is either live (skipped) or has its own reply. */
+function markTurnWithoutReply(runtimeId: string) {
+ writeSessionState(runtimeId, state =>
+ isLiveTurnAwaitingEvents(state) || turnHasReply(state.messages)
+ ? state
+ : { ...state, messages: withNoReplyNotice(state.messages) }
+ )
+}
+
+async function recoverEndedLiveTurn(runtimeId: string) {
+ const storedSessionId = $sessionStates.get()[runtimeId]?.storedSessionId ?? null
+ const refreshTranscript = liveTurnBackend?.refreshTranscript
+
+ // Only a session on screen reads its history now; a background session
+ // reads it when the user opens it, like the running=false edge.
+ if (refreshTranscript && storedSessionId && runtimeReferenced(runtimeId, storedSessionId)) {
+ try {
+ await refreshTranscript(runtimeId, storedSessionId)
+ } catch {
+ // The local transcript still decides whether a reply arrived.
+ }
+ }
+
+ markTurnWithoutReply(runtimeId)
+}
- if (!current || !isLiveTurnAwaitingEvents(current)) {
+/** The silence window ran out: ask the backend. Running keeps the turn and
+ * restarts the clock; no answer (gateway down, request failed, owner unknown)
+ * also keeps it — the stall hint and Stop remain — and asks again next window.
+ * Only a backend that reports the turn over settles it. */
+async function onEventSilence(runtimeId: string) {
+ sessionEventSilenceTimers.delete(runtimeId)
+
+ if (!isLiveTurnAwaitingEvents($sessionStates.get()[runtimeId])) {
return
}
- publishSessionState(runtimeId, {
- ...current,
- awaitingResponse: false,
- busy: false,
- interrupted: true,
- messages: withSilentTurnRetry(current.messages, current.streamId),
- pendingBranchGroup: null,
- streamId: null,
- turnLive: false,
- turnStartedAt: null
- })
+ const check = {}
+ silentTurnChecks.set(runtimeId, check)
+ const verdict = await checkLiveTurn(runtimeId)
+
+ if (silentTurnChecks.get(runtimeId) !== check) {
+ return
+ }
+
+ silentTurnChecks.delete(runtimeId)
+
+ if (verdict !== 'ended') {
+ noteSessionEvent(runtimeId)
+
+ return
+ }
+
+ settleEndedLiveTurn(runtimeId)
+ await recoverEndedLiveTurn(runtimeId)
}
/** Record that this session just produced an event. A live turn that then goes
- * silent is force-settled; a turn still receiving events, or waiting on the
- * user, is not. */
+ * silent is checked against its backend; a turn still receiving events, or
+ * waiting on the user, is not. */
export function noteSessionEvent(runtimeId: string) {
if (!runtimeId) {
return
@@ -493,10 +672,7 @@ export function noteSessionEvent(runtimeId: string) {
sessionEventSilenceTimers.set(
runtimeId,
- setTimeout(() => {
- sessionEventSilenceTimers.delete(runtimeId)
- settleSilentLiveTurn(runtimeId)
- }, LIVE_TURN_EVENT_SILENCE_MS)
+ setTimeout(() => void onEventSilence(runtimeId), LIVE_TURN_EVENT_SILENCE_MS)
)
}
@@ -872,6 +1048,7 @@ export function clearAllSessionStates() {
}
sessionEventSilenceTimers.clear()
+ silentTurnChecks.clear()
settledExpiry.clear()
unconfirmedReconnectSettles.clear()
clearAllProviderWaits()
@@ -2104,6 +2281,11 @@ export interface SessionTileDelegate {
* it — the caller downgrades the mirror itself. Reconnect-time twin of
* invalidateRuntimeBindings (#93059). */
retireBusyClaim?(runtimeId: string): boolean
+ /** Apply `updater` through the wiring cache when it holds `runtimeId`, so
+ * cache, focused view, and tile mirrors settle together. Returns false
+ * without writing when the cache never held it (no phantom entries); the
+ * caller writes the mirror itself. */
+ updateHeldSession?(runtimeId: string, updater: (state: ClientSessionState) => ClientSessionState): boolean
/** Submit a prompt to a tile's live session. */
submitToSession(runtimeId: string, text: string): Promise<void>
/** THE session-state write path — routes through the wiring cache so the
diff --git a/apps/desktop/src/store/session-watchdog.test.ts b/apps/desktop/src/store/session-watchdog.test.ts
index 22919c60127..4124ad91abe 100644
--- a/apps/desktop/src/store/session-watchdog.test.ts
+++ b/apps/desktop/src/store/session-watchdog.test.ts
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ClientSessionState } from '@/app/types'
+import { chatMessageText, textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { errorRecoveryPlan } from '@/lib/error-surface'
+import { requestGatewayForAgent } from '@/store/gateway'
import { $activeSessionId, $selectedStoredSessionId, $unreadFinishedSessionIds } from './session'
import {
@@ -11,11 +13,22 @@ import {
$workingSessionIds,
clearAllSessionStates,
LIVE_TURN_EVENT_SILENCE_MS,
+ LIVE_TURN_PROBE_TIMEOUT_MS,
+ liveTurnVerdict,
noteSessionEvent,
publishSessionState,
- SESSION_WATCHDOG_TIMEOUT_MS
+ recordSessionEventScope,
+ SESSION_WATCHDOG_TIMEOUT_MS,
+ type SessionTileDelegate,
+ setLiveTurnBackend,
+ setSessionTileDelegate
} from './session-states'
+vi.mock('@/store/gateway', async importActual => ({
+ ...(await importActual<Record<string, unknown>>()),
+ requestGatewayForAgent: vi.fn()
+}))
+
// 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_MS
@@ -152,6 +165,23 @@ function partial(text: string, over: Partial<ClientSessionState> = {}): ClientSe
}
describe('live turn event silence', () => {
+ let releaseBackend: () => void = () => undefined
+
+ // What `session.active_list` answers for the runtime under test.
+ const listing = (id: string, status: string) => ({ sessions: [{ id, session_key: `stored-${id}`, status }] })
+
+ function backend(
+ answer: (method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<unknown>,
+ refreshTranscript?: (runtimeId: string, storedSessionId: string) => Promise<unknown> | unknown
+ ) {
+ const request = vi.fn(answer)
+ releaseBackend = setLiveTurnBackend({ request: request as never, refreshTranscript })
+
+ return request
+ }
+
+ const card = (runtimeId: string) => $sessionStates.get()[runtimeId]?.messages.find(message => message.errorSurface)
+
beforeEach(() => {
vi.useFakeTimers()
clearAllSessionStates()
@@ -161,6 +191,9 @@ describe('live turn event silence', () => {
})
afterEach(() => {
+ releaseBackend()
+ releaseBackend = () => undefined
+ vi.mocked(requestGatewayForAgent).mockReset()
vi.runOnlyPendingTimers()
vi.useRealTimers()
clearAllSessionStates()
@@ -169,94 +202,196 @@ describe('live turn event silence', () => {
$activeSessionId.set(null)
})
- it('force-settles a silent live turn even after a partial payload and offers retry', () => {
- $activeSessionId.set('rt1')
- publishSessionState('rt1', partial('partial answer', { model: 'glm-5.3-flash', storedSessionId: 's1' }))
- noteSessionEvent('rt1')
+ it('keeps a silent turn when nothing can answer for it', async () => {
+ publishSessionState('rt-alone', partial('long tool call', { storedSessionId: 's-alone' }))
+ noteSessionEvent('rt-alone')
- vi.advanceTimersByTime(SILENCE_MS)
+ await vi.advanceTimersByTimeAsync(SILENCE_MS * 4)
+
+ expect($workingSessionIds.get()).toContain('s-alone')
+ expect($sessionStates.get()['rt-alone']?.interrupted).toBeFalsy()
+ expect(card('rt-alone')).toBeUndefined()
+ })
+
+ it.each(['working', 'starting'])('keeps a turn the backend reports %s, and asks again next window', async status => {
+ publishSessionState('rt-quiet', partial('long tool call', { storedSessionId: 's-quiet' }))
+ const request = backend(async () => listing('rt-quiet', status))
+ noteSessionEvent('rt-quiet')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS * 3)
+
+ expect(request).toHaveBeenCalledTimes(3)
+ expect(request).toHaveBeenCalledWith('session.active_list', {}, LIVE_TURN_PROBE_TIMEOUT_MS)
+ expect($workingSessionIds.get()).toContain('s-quiet')
+ expect(card('rt-quiet')).toBeUndefined()
+ })
+
+ it('keeps the turn when the check fails, and asks again next window', async () => {
+ publishSessionState('rt-down', partial('partial', { storedSessionId: 's-down' }))
+
+ const request = backend(async () => {
+ throw new Error('Hermes gateway unavailable')
+ })
- const settled = $sessionStates.get().rt1
- expect($workingSessionIds.get()).not.toContain('s1')
+ noteSessionEvent('rt-down')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS * 2)
+
+ expect(request).toHaveBeenCalledTimes(2)
+ expect($workingSessionIds.get()).toContain('s-down')
+ expect($sessionStates.get()['rt-down']?.interrupted).toBeFalsy()
+ expect(card('rt-down')).toBeUndefined()
+ })
+
+ it('does not act on an answer that lands after the turn produced an event', async () => {
+ publishSessionState('rt-late', partial('partial', { storedSessionId: 's-late' }))
+ let answer!: (value: unknown) => void
+ backend(() => new Promise(resolve => (answer = resolve)))
+ noteSessionEvent('rt-late')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+ noteSessionEvent('rt-late')
+ answer({ sessions: [] })
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect($workingSessionIds.get()).toContain('s-late')
+ expect(card('rt-late')).toBeUndefined()
+ })
+
+ it('settles a turn the backend reports over, keeping its reply and a live path for late events', async () => {
+ // On screen, so the settled transcript stays in the mirror to inspect.
+ $activeSessionId.set('rt-done')
+ publishSessionState('rt-done', partial('the answer', { storedSessionId: 's-done' }))
+ backend(async () => listing('rt-done', 'idle'))
+ noteSessionEvent('rt-done')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+
+ const settled = $sessionStates.get()['rt-done']
+ expect($workingSessionIds.get()).not.toContain('s-done')
expect(settled?.busy).toBe(false)
- expect(settled?.awaitingResponse).toBe(false)
expect(settled?.turnLive).toBe(false)
+ // Not a Stop: the rest of the turn's events are still accepted.
+ expect(settled?.interrupted).toBeFalsy()
+ expect(settled?.heartbeatSettledStreamId).toBe('a1')
expect(settled?.messages.every(message => !message.pending)).toBe(true)
- expect(
- settled?.messages.some(message =>
- message.parts.some(part => part.type === 'text' && part.text === 'partial answer')
- )
- ).toBe(true)
-
- const failed = settled?.messages.find(message => message.errorSurface)
- expect(failed?.errorSurface?.retryable).toBe(true)
- expect(errorRecoveryPlan(failed?.errorSurface).retry).toBe(true)
- expect(failed?.error).not.toMatch(/glm|deepseek|interrupted mid-run/i)
+ expect(chatMessageText(settled!.messages[0])).toBe('the answer')
+ expect(card('rt-done')).toBeUndefined()
})
- it('force-settles a silent live turn that never produced a payload', () => {
+ it('offers a retry only once the backend confirms a turn ended without a reply', async () => {
$activeSessionId.set('rt-empty')
publishSessionState(
'rt-empty',
- state({ awaitingResponse: true, busy: true, model: 'deepseek-chat', storedSessionId: 's-empty', turnLive: true })
+ state({ awaitingResponse: true, busy: true, storedSessionId: 's-empty', turnLive: true })
)
+ // A reaped runtime is absent from the list.
+ backend(async () => ({ sessions: [] }))
noteSessionEvent('rt-empty')
- vi.advanceTimersByTime(SILENCE_MS)
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
- const settled = $sessionStates.get()['rt-empty']
+ const failed = card('rt-empty')
expect($workingSessionIds.get()).not.toContain('s-empty')
- expect(settled?.busy).toBe(false)
- expect(settled?.turnLive).toBe(false)
- const failed = settled?.messages.find(message => message.role === 'assistant' && message.errorSurface)
- expect(failed?.errorSurface?.retryable).toBe(true)
+ expect(failed?.errorSurface?.code).toBe('no_reply')
expect(errorRecoveryPlan(failed?.errorSurface).retry).toBe(true)
+ expect(failed?.error).not.toMatch(/connection/i)
})
- it('does not settle a live turn that keeps producing events', () => {
- publishSessionState('rt-live', partial('still working', { storedSessionId: 's-live' }))
- noteSessionEvent('rt-live')
+ it('pulls the stored reply for a turn on screen before deciding it had none', async () => {
+ $activeSessionId.set('rt-screen')
+ publishSessionState(
+ 'rt-screen',
+ state({ awaitingResponse: true, busy: true, storedSessionId: 's-screen', turnLive: true })
+ )
+
+ const refreshTranscript = vi.fn(async (runtimeId: string) => {
+ const current = $sessionStates.get()[runtimeId]!
- vi.advanceTimersByTime(SILENCE_MS - 1)
- noteSessionEvent('rt-live')
- vi.advanceTimersByTime(SILENCE_MS - 1)
+ publishSessionState(runtimeId, {
+ ...current,
+ messages: [{ id: 'stored-reply', parts: [textPart('finished on the backend')], role: 'assistant' }]
+ })
+ })
+
+ backend(async () => ({ sessions: [] }), refreshTranscript)
+ noteSessionEvent('rt-screen')
- expect($workingSessionIds.get()).toContain('s-live')
- expect($sessionStates.get()['rt-live']?.messages.some(message => message.errorSurface)).toBe(false)
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+
+ expect(refreshTranscript).toHaveBeenCalledWith('rt-screen', 's-screen')
+ expect(card('rt-screen')).toBeUndefined()
})
- it('does not settle a turn the user is still answering', () => {
+ it('leaves a background session to read its history when opened', async () => {
+ publishSessionState('rt-bg', state({ awaitingResponse: true, busy: true, storedSessionId: 's-bg', turnLive: true }))
+ const refreshTranscript = vi.fn()
+ backend(async () => ({ sessions: [] }), refreshTranscript)
+ noteSessionEvent('rt-bg')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+
+ expect(refreshTranscript).not.toHaveBeenCalled()
+ expect($workingSessionIds.get()).not.toContain('s-bg')
+ })
+
+ it('asks the backend that owns the turn, not the window gateway', async () => {
+ publishSessionState('rt-remote', partial('partial', { storedSessionId: 's-remote' }))
+ recordSessionEventScope({ connectionId: 'homelab', profile: 'work', session_id: 'rt-remote' })
+ vi.mocked(requestGatewayForAgent).mockResolvedValue(listing('rt-remote', 'working') as never)
+ const ambient = backend(async () => ({ sessions: [] }))
+ noteSessionEvent('rt-remote')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+
+ expect(ambient).not.toHaveBeenCalled()
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'homelab',
+ 'work',
+ 'session.active_list',
+ {},
+ LIVE_TURN_PROBE_TIMEOUT_MS,
+ undefined
+ )
+ expect($workingSessionIds.get()).toContain('s-remote')
+ })
+
+ it('writes the settle through the wiring cache that holds the session', async () => {
+ publishSessionState('rt-held', partial('the answer', { storedSessionId: 's-held' }))
+
+ const updateHeldSession = vi.fn((runtimeId: string, updater: (s: ClientSessionState) => ClientSessionState) => {
+ publishSessionState(runtimeId, updater($sessionStates.get()[runtimeId]!))
+
+ return true
+ })
+
+ setSessionTileDelegate({ updateHeldSession } as unknown as SessionTileDelegate)
+ backend(async () => ({ sessions: [] }))
+ noteSessionEvent('rt-held')
+
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+
+ expect(updateHeldSession).toHaveBeenCalledWith('rt-held', expect.any(Function))
+ expect($workingSessionIds.get()).not.toContain('s-held')
+ })
+
+ it('does not check a turn the user is still answering', async () => {
publishSessionState('rt-ask', partial('need a choice', { needsInput: true, storedSessionId: 's-ask' }))
+ const request = backend(async () => ({ sessions: [] }))
noteSessionEvent('rt-ask')
- vi.advanceTimersByTime(SILENCE_MS)
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
+ expect(request).not.toHaveBeenCalled()
expect($workingSessionIds.get()).toContain('s-ask')
- expect($sessionStates.get()['rt-ask']?.messages.some(message => message.errorSurface)).toBe(false)
})
- it('settles only the session that stopped producing events', () => {
- $activeSessionId.set('rt-a')
- publishSessionState('rt-a', partial('a', { storedSessionId: 's-a' }))
- publishSessionState('rt-b', partial('b', { storedSessionId: 's-b' }))
- noteSessionEvent('rt-a')
- noteSessionEvent('rt-b')
-
- vi.advanceTimersByTime(SILENCE_MS - 1)
- noteSessionEvent('rt-b')
- vi.advanceTimersByTime(1)
-
- expect($workingSessionIds.get()).not.toContain('s-a')
- expect($workingSessionIds.get()).toContain('s-b')
- expect($sessionStates.get()['rt-a']?.messages.some(message => message.errorSurface?.retryable)).toBe(true)
- expect($sessionStates.get()['rt-b']?.busy).toBe(true)
- })
-
- it('does not stamp a retry when the turn settles before the silence window', () => {
- const working = partial('done soon', { storedSessionId: 's-done' })
- publishSessionState('rt-done', working)
- noteSessionEvent('rt-done')
- publishSessionState('rt-done', {
+ it('does not check a turn that settled before the silence window', async () => {
+ const working = partial('done soon', { storedSessionId: 's-soon' })
+ const request = backend(async () => ({ sessions: [] }))
+ publishSessionState('rt-soon', working)
+ noteSessionEvent('rt-soon')
+ publishSessionState('rt-soon', {
...working,
awaitingResponse: false,
busy: false,
@@ -264,9 +399,32 @@ describe('live turn event silence', () => {
turnLive: false
})
- vi.advanceTimersByTime(SILENCE_MS)
+ await vi.advanceTimersByTimeAsync(SILENCE_MS)
- expect($sessionStates.get()['rt-done']?.messages.some(message => message.errorSurface)).toBe(false)
- expect($workingSessionIds.get()).not.toContain('s-done')
+ expect(request).not.toHaveBeenCalled()
+ expect(card('rt-soon')).toBeUndefined()
+ })
+})
+
+describe('liveTurnVerdict', () => {
+ it('reads one runtime out of an active-list snapshot', () => {
+ const snapshot = {
+ sessions: [
+ { id: 'a', status: 'working' },
+ { id: 'b', status: 'starting' },
+ { id: 'c', status: 'waiting' },
+ { id: 'd', status: 'idle' },
+ { id: 'e', status: 'from-a-newer-backend' }
+ ]
+ }
+
+ expect(liveTurnVerdict(snapshot, 'a')).toBe('running')
+ expect(liveTurnVerdict(snapshot, 'b')).toBe('running')
+ expect(liveTurnVerdict(snapshot, 'c')).toBe('running')
+ expect(liveTurnVerdict(snapshot, 'd')).toBe('ended')
+ expect(liveTurnVerdict(snapshot, 'gone')).toBe('ended')
+ expect(liveTurnVerdict(snapshot, 'e')).toBe('unknown')
+ expect(liveTurnVerdict({}, 'a')).toBe('unknown')
+ expect(liveTurnVerdict(null, 'a')).toBe('unknown')
})
})
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 53066131b68..28f9767d591 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -204,6 +204,8 @@
"assistant.thread.errorCodes.loop_error.title",
"assistant.thread.errorCodes.model_not_found.body",
"assistant.thread.errorCodes.model_not_found.title",
+ "assistant.thread.errorCodes.no_reply.body",
+ "assistant.thread.errorCodes.no_reply.title",
"assistant.thread.errorCodes.overloaded.body",
"assistant.thread.errorCodes.overloaded.title",
"assistant.thread.errorCodes.payload_too_large.body",