Skip to content

The agent that grows with you

fix(desktop): an owner restart re-reads off-screen paused queues, and never auto-continues a turn

Teknium3ec4336bc118
diff --git a/apps/desktop/src/store/owner-queue-reconcile.test.ts b/apps/desktop/src/store/owner-queue-reconcile.test.ts
index ccff0ed11f3..fab8b50dfd4 100644
--- a/apps/desktop/src/store/owner-queue-reconcile.test.ts
+++ b/apps/desktop/src/store/owner-queue-reconcile.test.ts
@@ -1,15 +1,18 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { HermesConnection } from '@/global'
import { createClientSessionState } from '@/lib/chat-runtime'
import type { SessionInfo } from '@/types/hermes'
-import { $queuedPromptsBySession, getQueuedPrompts } from './composer-queue'
-import { reconcileOwnerQueues } from './owner-queue-reconcile'
+import { $queuedPromptsBySession } from './composer-queue'
+import { watchOwnerQueues } from './owner-queue-reconcile'
import { reconcilePendingSubmissions, trackPendingSubmission } from './pending-submissions'
-import { $sessions, setSessions } from './session'
+import { $connection, $gatewayState, $selectedStoredSessionId, $sessions, setSessions } from './session'
import { $sessionDotStateById } from './session-dot-state'
import { clearAllSessionStates, publishSessionState } from './session-states'
+const connectionAt = (wsUrl: string) => ({ mode: 'local', wsUrl }) as HermesConnection
+
const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
({ id, message_count: 4, source: 'desktop', started_at: 0, title: id, ...extra }) as SessionInfo
@@ -29,6 +32,9 @@ beforeEach(() => {
afterEach(() => {
$sessions.set([])
+ $connection.set(null)
+ $gatewayState.set('idle')
+ $selectedStoredSessionId.set(null)
})
it('a chat whose queue is paused behind a turn lost in a restart needs the user, it is not finished-unread', () => {
@@ -43,27 +49,61 @@ it('a chat whose queue is paused behind a turn lost in a restart needs the user,
expect($sessionDotStateById.get().beta).toBe('unread')
})
-it('after a relaunch the owner queue of a chat that is not on screen is read again, and only of chats holding owner work', async () => {
+it('a paused chat whose turn is running again reads working, not needs-input', () => {
+ setSessions([row('beta')])
+ reconcilePendingSubmissions('beta', pausedSnapshot)
+ publishSessionState('runtime-beta', { ...createClientSessionState('beta'), busy: true })
+
+ expect($sessionDotStateById.get().beta).toBe('working')
+})
+
+it('every gateway open re-reads the owner queue of each chat off screen with the open path params, and never a legacy backend', async () => {
setSessions([row('beta'), row('alpha'), row('routed')])
- // Before the quit this window saw the send queued behind a running turn.
+ $connection.set(connectionAt('ws://127.0.0.1:9/api/ws?native_dial=1'))
trackPendingSubmission('beta', { id: 'queued-send', text: 'queued after hold', status: 'queued' })
+ trackPendingSubmission('alpha', { id: 'on-screen', text: 'y', status: 'queued' })
trackPendingSubmission('routed', { id: 'other', text: 'x', status: 'queued' })
- // The routed chat was already resumed by this window: it holds its own live snapshot.
+ // A live snapshot from an earlier connection says nothing about what a restarted owner holds.
publishSessionState('runtime-routed', createClientSessionState('routed'))
+ // The chat on screen is read by its own route resume.
+ $selectedStoredSessionId.set('alpha')
- const request = vi.fn(async (method: string, params?: Record<string, unknown>) => ({
+ const request = vi.fn(async (_method: string, params?: Record<string, unknown>) => ({
session_id: params?.session_id,
info: { stored_session_id: params?.session_id, pending_submissions: pausedSnapshot }
- })) as unknown as Parameters<typeof reconcileOwnerQueues>[0]
+ }))
- await reconcileOwnerQueues(request)
+ const reads = () => request.mock.calls.map(([method, params]) => [method, params?.session_id, params?.defer_history])
+ const stop = watchOwnerQueues(request as unknown as Parameters<typeof watchOwnerQueues>[0])
- expect(
- (request as unknown as ReturnType<typeof vi.fn>).mock.calls.map(([method, params]) => [method, params?.session_id])
- ).toEqual([['session.resume', 'beta']])
- expect(getQueuedPrompts('beta').map(({ id, serverStatus }) => ({ id, serverStatus }))).toEqual([
- { id: 'lost-turn', serverStatus: 'unknown' },
- { id: 'queued-send', serverStatus: 'queued' }
+ const openEdge = async () => {
+ $gatewayState.set('closed')
+ $gatewayState.set('open')
+ await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(2))
+ await new Promise(resolve => setTimeout(resolve, 0))
+ }
+
+ await openEdge()
+ expect(reads().sort()).toEqual([
+ ['session.resume', 'beta', true],
+ ['session.resume', 'routed', true]
])
expect($sessionDotStateById.get().beta).toBe('needs-input')
+
+ // The owner restarts while the window stays up: the same chats are read again.
+ request.mockClear()
+ await openEdge()
+ expect(reads().sort()).toEqual([
+ ['session.resume', 'beta', true],
+ ['session.resume', 'routed', true]
+ ])
+
+ // A legacy (non-canonical) backend's cold resume can auto-continue a crashed turn: never read there.
+ request.mockClear()
+ $connection.set(connectionAt('wss://remote.example/api/ws?token=t'))
+ $gatewayState.set('closed')
+ $gatewayState.set('open')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(request).not.toHaveBeenCalled()
+ stop()
})
diff --git a/apps/desktop/src/store/owner-queue-reconcile.ts b/apps/desktop/src/store/owner-queue-reconcile.ts
index f33e852c95f..4cd33e6f603 100644
--- a/apps/desktop/src/store/owner-queue-reconcile.ts
+++ b/apps/desktop/src/store/owner-queue-reconcile.ts
@@ -1,13 +1,14 @@
import { computed } from 'nanostores'
import { singleFlightSessionResume } from '@/app/session/hooks/use-prompt-actions/single-flight-resume'
+import { primaryResumeParams } from '@/app/session/hooks/use-session-actions/resume-owner'
import { stableArray } from '@/lib/stable-array'
import type { SessionResumeResult } from '@/types/hermes'
-import { $queuedPromptsBySession } from './composer-queue'
+import { $queuedPromptsBySession, serverOwnsComposerQueue } from './composer-queue'
import { journaledPendingSessions, pendingSnapshotFence, reconcilePendingSubmissions } from './pending-submissions'
-import { $gatewayState, $sessions } from './session'
-import { $sessionStates, knownOwnerForSession, requestForOwnedSession } from './session-states'
+import { $gatewayState, $selectedStoredSessionId, $sessions } from './session'
+import { knownOwnerForSession, requestForOwnedSession } from './session-states'
type GatewayRequest = <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
@@ -29,48 +30,60 @@ export function sessionsWithOwnerWork(): string[] {
return [...keys]
}
+// Reads in flight at once: an open edge after a restart can find many chats with owner work.
+const RECONCILE_CONCURRENCY = 4
+
+async function reconcileOne(request: GatewayRequest, key: string): Promise<void> {
+ const owner = knownOwnerForSession(key)
+ const profile = owner ? (typeof owner === 'string' ? owner : owner.profile) : undefined
+
+ const snapshot = await singleFlightSessionResume(
+ key,
+ () =>
+ requestForOwnedSession<SessionResumeResult>(
+ key,
+ request,
+ 'session.resume',
+ primaryResumeParams(key, false, undefined, profile)
+ ),
+ { scope: owner }
+ ).catch(() => null)
+
+ const info = snapshot?.info
+
+ if (info && Array.isArray(info.pending_submissions)) {
+ reconcilePendingSubmissions(
+ info.stored_session_id ?? key,
+ info.pending_submissions,
+ pendingSnapshotFence(info.replay_epoch, info.last_sequence)
+ )
+ }
+}
+
/**
- * Re-read the owner's pending list for every session this machine queued work in that this window
- * has not resumed. The queue card of a send queued behind a running turn is otherwise refreshed only when
- * its chat is opened: after a relaunch that lands elsewhere (another chat, a fresh one, or
- * `display.resume_last_session: false`) a send paused behind a turn the restart lost sat invisible
- * and never ran. The read is the same `session.resume` snapshot opening the chat takes; an id the
- * owner cannot route is left for that chat's own resume.
+ * Re-read the owner's pending list for every chat this machine queued owner work in, except the
+ * one on screen (its route resume reads it). The queue card of a send queued behind a running turn
+ * is otherwise refreshed only when its chat is opened: after a relaunch that lands elsewhere, or an
+ * owner restart while the app stays up, a send paused behind a turn the restart lost sat invisible
+ * and never ran. Every open edge re-reads: a snapshot from an earlier connection says nothing about
+ * what the restarted owner holds.
+ *
+ * The read is the open path's own `session.resume` (deferred history, no messages). Only chats
+ * whose owner admits canonically are read: that owner answers with `pending_submissions` and never
+ * auto-continues an interrupted turn on resume, where a legacy remote backend's cold resume would
+ * start a billed model turn in a chat the user never opened.
*/
export async function reconcileOwnerQueues(request: GatewayRequest): Promise<void> {
- // A chat this window already resumed holds a live snapshot (and its fanout) of its own.
- const resumed = new Set(Object.values($sessionStates.get()).map(state => state.storedSessionId))
-
- await Promise.all(
- sessionsWithOwnerWork()
- .filter(key => !resumed.has(key))
- .map(async key => {
- const owner = knownOwnerForSession(key)
-
- const snapshot = await singleFlightSessionResume(
- key,
- () =>
- requestForOwnedSession<SessionResumeResult>(key, request, 'session.resume', {
- session_id: key,
- cols: 96,
- source: 'desktop',
- omit_messages: true,
- ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})
- }),
- { scope: owner }
- ).catch(() => null)
-
- const info = snapshot?.info
-
- if (info && Array.isArray(info.pending_submissions)) {
- reconcilePendingSubmissions(
- info.stored_session_id ?? key,
- info.pending_submissions,
- pendingSnapshotFence(info.replay_epoch, info.last_sequence)
- )
- }
- })
- )
+ const selected = $selectedStoredSessionId.get()
+ const queue = sessionsWithOwnerWork().filter(key => key !== selected && serverOwnsComposerQueue(key))
+
+ const worker = async () => {
+ for (let key = queue.shift(); key !== undefined; key = queue.shift()) {
+ await reconcileOne(request, key)
+ }
+ }
+
+ await Promise.all(Array.from({ length: Math.min(RECONCILE_CONCURRENCY, queue.length) }, worker))
}
// One read per edge into an open gateway (first boot, relaunch, owner restart), taken once the
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index c9172f88103..2217b49dfdb 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -165,6 +165,9 @@ export const $sessionDotStateById = computed(
// claim as background processes — and it yields to `working` below the
// moment the parent turn itself is live (synchronous orchestrator children).
claim(delegating, 'background')
+ // A queue paused behind a turn lost in a restart waits on the user's Discard, and a turn that
+ // never finished must not read as finished-unread. A turn actually running speaks over it.
+ claim(paused, 'needs-input')
claim(working, 'working')
// Stalled REFINES working rather than rivalling it — the turn is still
@@ -179,9 +182,6 @@ export const $sessionDotStateById = computed(
}
}
- // A queue paused behind a turn lost in a restart waits on the user's Discard, and a turn that
- // never finished must not read as finished-unread.
- claim(paused, 'needs-input')
claim(attention, 'needs-input')
return (dotStates = stableRecord(dotStates, next))