Skip to content

The agent that grows with you

fix(desktop): a send queued behind a turn a restart lost is shown after relaunch

Teknium167afc64df75
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 8cfa1c8beff..302a9cf0e24 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -137,6 +137,7 @@ import { useCwdActions } from '../session/hooks/use-cwd-actions'
import { useHermesConfig } from '../session/hooks/use-hermes-config'
import { useMessageStream } from '../session/hooks/use-message-stream'
import { useModelControls } from '../session/hooks/use-model-controls'
+import { useOwnerQueueReconcile } from '../session/hooks/use-owner-queue-reconcile'
import { usePreviewRouting } from '../session/hooks/use-preview-routing'
import { usePromptActions } from '../session/hooks/use-prompt-actions'
import { useRouteResume } from '../session/hooks/use-route-resume'
@@ -730,12 +731,9 @@ export function ContribWiring({ children }: { children: ReactNode }) {
// Runs outside the selected ChatBar so queues belonging to background
// sessions continue once those sessions are idle. The session dispatcher
// routes each send to its owner; a disconnected foreground is not a global gate.
- useBackgroundQueueDrain({
- enabled: true,
- runtimeIdByStoredSessionIdRef,
- selectedStoredSessionId,
- submitText
- })
+ // Queues of chats not on screen: drain the local ones, re-read the owner-held ones on each gateway open.
+ useBackgroundQueueDrain({ enabled: true, runtimeIdByStoredSessionIdRef, selectedStoredSessionId, submitText })
+ useOwnerQueueReconcile(requestGateway)
// Session-tile delegate (resume/submit/interrupt/slash + the session verbs
// the tile TAB menu needs, without touching the primary view).
diff --git a/apps/desktop/src/app/session/hooks/use-owner-queue-reconcile.ts b/apps/desktop/src/app/session/hooks/use-owner-queue-reconcile.ts
new file mode 100644
index 00000000000..1f58da45478
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-owner-queue-reconcile.ts
@@ -0,0 +1,8 @@
+import { useEffect } from 'react'
+
+import { watchOwnerQueues } from '@/store/owner-queue-reconcile'
+
+/** Re-read the owner's queue of chats holding owner work on every edge into an open gateway. */
+export function useOwnerQueueReconcile(requestGateway: Parameters<typeof watchOwnerQueues>[0]): void {
+ useEffect(() => watchOwnerQueues(requestGateway), [requestGateway])
+}
diff --git a/apps/desktop/src/store/owner-queue-reconcile.test.ts b/apps/desktop/src/store/owner-queue-reconcile.test.ts
new file mode 100644
index 00000000000..ccff0ed11f3
--- /dev/null
+++ b/apps/desktop/src/store/owner-queue-reconcile.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+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 { reconcilePendingSubmissions, trackPendingSubmission } from './pending-submissions'
+import { $sessions, setSessions } from './session'
+import { $sessionDotStateById } from './session-dot-state'
+import { clearAllSessionStates, publishSessionState } from './session-states'
+
+const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
+ ({ id, message_count: 4, source: 'desktop', started_at: 0, title: id, ...extra }) as SessionInfo
+
+// The owner's list after a restart cut the running turn: the turn is `unknown` (only Discard
+// resolves it) and the send queued behind it waits.
+const pausedSnapshot = [
+ { admission_id: 'lost-turn', status: 'unknown', user: 'HOLD running turn', execution_generation: 1 },
+ { admission_id: 'queued-send', status: 'queued', user: 'queued after hold' }
+]
+
+beforeEach(() => {
+ window.localStorage.clear()
+ $queuedPromptsBySession.set({})
+ clearAllSessionStates()
+ $sessions.set([])
+})
+
+afterEach(() => {
+ $sessions.set([])
+})
+
+it('a chat whose queue is paused behind a turn lost in a restart needs the user, it is not finished-unread', () => {
+ setSessions([row('beta', { unread: true }), row('alpha')])
+ reconcilePendingSubmissions('beta', pausedSnapshot)
+
+ expect($sessionDotStateById.get().beta).toBe('needs-input')
+ expect($sessionDotStateById.get().alpha).toBeUndefined()
+
+ // Discarded: the owner lists only the send, now running. The chat stops asking for the user.
+ reconcilePendingSubmissions('beta', [{ admission_id: 'queued-send', status: 'started', user: 'queued after hold' }])
+ 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 () => {
+ setSessions([row('beta'), row('alpha'), row('routed')])
+ // Before the quit this window saw the send queued behind a running turn.
+ trackPendingSubmission('beta', { id: 'queued-send', text: 'queued after hold', 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.
+ publishSessionState('runtime-routed', createClientSessionState('routed'))
+
+ 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)
+
+ 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' }
+ ])
+ expect($sessionDotStateById.get().beta).toBe('needs-input')
+})
diff --git a/apps/desktop/src/store/owner-queue-reconcile.ts b/apps/desktop/src/store/owner-queue-reconcile.ts
new file mode 100644
index 00000000000..f33e852c95f
--- /dev/null
+++ b/apps/desktop/src/store/owner-queue-reconcile.ts
@@ -0,0 +1,107 @@
+import { computed } from 'nanostores'
+
+import { singleFlightSessionResume } from '@/app/session/hooks/use-prompt-actions/single-flight-resume'
+import { stableArray } from '@/lib/stable-array'
+import type { SessionResumeResult } from '@/types/hermes'
+
+import { $queuedPromptsBySession } from './composer-queue'
+import { journaledPendingSessions, pendingSnapshotFence, reconcilePendingSubmissions } from './pending-submissions'
+import { $gatewayState, $sessions } from './session'
+import { $sessionStates, knownOwnerForSession, requestForOwnedSession } from './session-states'
+
+type GatewayRequest = <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
+
+// A queue card or journal entry the owner has to settle: everything but a local-only card.
+const holdsOwnerWork = (key: string): boolean =>
+ ($queuedPromptsBySession.get()[key] ?? []).some(entry => Boolean(entry.serverStatus))
+
+/** Sessions whose queue on this machine still names owner-held work: a send queued behind a
+ * running turn, or the lost turn that paused it. */
+export function sessionsWithOwnerWork(): string[] {
+ const keys = new Set(journaledPendingSessions())
+
+ for (const key of Object.keys($queuedPromptsBySession.get())) {
+ if (holdsOwnerWork(key)) {
+ keys.add(key)
+ }
+ }
+
+ return [...keys]
+}
+
+/**
+ * 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.
+ */
+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)
+ )
+ }
+ })
+ )
+}
+
+// One read per edge into an open gateway (first boot, relaunch, owner restart), taken once the
+// session list can route it.
+let readForThisOpen = false
+
+/** Keep the owner queues of chats not on screen current across gateway opens; returns the stop. */
+export function watchOwnerQueues(request: GatewayRequest): () => void {
+ const check = () => {
+ if ($gatewayState.get() !== 'open') {
+ readForThisOpen = false
+ } else if (!readForThisOpen && $sessions.get().length > 0) {
+ readForThisOpen = true
+ void reconcileOwnerQueues(request)
+ }
+ }
+
+ const stops = [$gatewayState.subscribe(check), $sessions.listen(check)]
+
+ return () => stops.forEach(stop => stop())
+}
+
+let pausedIds: readonly string[] = []
+
+/** Sessions whose owner FIFO is paused behind a turn it lost in a restart: the queue holds an
+ * `unknown` card that only the user's Discard resolves, so the session needs the user. */
+export const $pausedQueueSessionIds = computed(
+ $queuedPromptsBySession,
+ queues =>
+ (pausedIds = stableArray(
+ pausedIds,
+ Object.keys(queues).filter(key => queues[key]?.some(entry => entry.serverStatus === 'unknown'))
+ ))
+)
diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.ts
index 9941923bc07..73c7a0d779e 100644
--- a/apps/desktop/src/store/pending-submissions.ts
+++ b/apps/desktop/src/store/pending-submissions.ts
@@ -54,6 +54,28 @@ export function readPendingSubmissions(session: string): Record<string, PendingS
return entries
}
+/** Sessions the journal still holds an unsettled admission for (queued, started or unknown when
+ * last observed): the ones whose owner may have moved on while no window was watching. */
+export function journaledPendingSessions(): string[] {
+ const sessions = new Set<string>()
+ const unsettled = (entry: null | PendingSubmission | undefined) => Boolean(entry?.status && entry.status !== 'retired')
+
+ for (const [session, entries] of Object.entries(parse(window.localStorage.getItem(LEGACY_KEY), {} as Record<string, Record<string, PendingSubmission>>))) {
+ if (Object.values(entries ?? {}).some(unsettled)) { sessions.add(session) }
+ }
+
+ for (let index = 0; index < window.localStorage.length; index += 1) {
+ const key = window.localStorage.key(index)
+
+ if (!key?.startsWith(ENTRY_PREFIX)) { continue }
+ const [owner] = parse(key.slice(ENTRY_PREFIX.length), [] as unknown[])
+
+ if (typeof owner === 'string' && unsettled(parse<null | PendingSubmission>(window.localStorage.getItem(key), null))) { sessions.add(owner) }
+ }
+
+ return [...sessions]
+}
+
/** One admission's record without enumerating the journal: its v2 key, else the legacy blob. */
function readPendingSubmission(session: string, id: string): PendingSubmission | undefined {
return parse<null | PendingSubmission>(window.localStorage.getItem(entryKey(session, id)), null) ??
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index d4413f0b518..c9172f88103 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -28,6 +28,7 @@ import { computed } from 'nanostores'
import { stableArray, stableRecord } from '@/lib/stable-array'
import { $backgroundRunningSessionIds } from './composer-status'
+import { $pausedQueueSessionIds } from './owner-queue-reconcile'
import { $messagingSessions, $sessions, $unreadFinishedSessionIds, lineageAliases } from './session'
import {
$attentionSessionIds,
@@ -109,9 +110,10 @@ export const $sessionDotStateById = computed(
$unreadFinishedSessionIds,
$draftSessionIds,
$sessions,
- $unreadWriteGuard
+ $unreadWriteGuard,
+ $pausedQueueSessionIds
],
- (attention, working, stalled, background, delegating, unread, draft, sessions, unreadWriteGuard) => {
+ (attention, working, stalled, background, delegating, unread, draft, sessions, unreadWriteGuard, paused) => {
const next: Record<string, SessionDotState> = {}
const claim = (ids: readonly string[], state: SessionDotState) => {
@@ -177,6 +179,9 @@ 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))