Skip to content

The agent that grows with you

fix(desktop): bound the pre-start settle hold so a restore/edit arm can't latch the composer shut

Teknium2c0035d3b412
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 9750c609553..a56cc1ef04a 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -478,7 +478,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
)
)
} catch (err) {
- update(current => ({ ...current, busy: false, awaitingResponse: false }))
+ update(current => ({ ...current, busy: false, awaitingResponse: false, turnLive: false, turnStartedAt: null }))
notifyError(err, copy.regenerateFailed)
}
},
@@ -514,7 +514,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
)
)
} catch (err) {
- update(state => ({ ...state, busy: false, awaitingResponse: false, messages }))
+ update(state => ({ ...state, busy: false, awaitingResponse: false, turnLive: false, turnStartedAt: null, messages }))
throw err
}
},
@@ -555,7 +555,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
)
)
} catch (err) {
- update(state => ({ ...state, busy: false, awaitingResponse: false, messages }))
+ update(state => ({ ...state, busy: false, awaitingResponse: false, turnLive: false, turnStartedAt: null, messages }))
notifyError(err, copy.editFailed)
}
},
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
index 47760cac32e..8ce770e3b28 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
@@ -95,7 +95,13 @@ import type { RpcEvent } from '@/types/hermes'
import type { ClientSessionState } from '../../../types'
import { finalizeInterruptedMessages } from '../use-prompt-actions/rewind'
-import { hasSessionInfoStatePatch, sessionInfoStatePatch, SUBAGENT_EVENT_TYPES, toTodoPayload } from './utils'
+import {
+ hasSessionInfoStatePatch,
+ PRE_TURN_LIVE_SETTLE_GRACE_MS,
+ sessionInfoStatePatch,
+ SUBAGENT_EVENT_TYPES,
+ toTodoPayload
+} from './utils'
function firstBillingLine(text: string): string {
return (text || '').split('\n')[0]?.trim() ?? ''
@@ -658,7 +664,24 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
// here is exactly "no turn has been reported running yet".
// (turnStartedAt can't discriminate — it is optimistically
// seeded at submit so the visible timer starts at Enter.)
- if (state.awaitingResponse && !state.sawAssistantPayload && !state.turnLive) {
+ //
+ // BOUNDED (#86795): an armed turn that never goes live — a
+ // restore/edit whose rewind was refused after the optimistic
+ // arm, a submit response lost to a gateway bounce, a terminal
+ // error event that never arrived — would otherwise hold this
+ // gate forever. busy then latches until app restart:
+ // isTargetSessionBusy refuses every send, the composer queues
+ // each message, and the queue drain (gated on busy→false) never
+ // fires. turnStartedAt is seeded at the optimistic arm, so its
+ // age bounds the hold; past the grace window (or with no clock
+ // at all) the gateway's running=false is authoritative and the
+ // settle below releases the session.
+ const armedAt = state.turnStartedAt
+
+ const withinPreStartGrace =
+ typeof armedAt === 'number' && Date.now() - armedAt < PRE_TURN_LIVE_SETTLE_GRACE_MS
+
+ if (state.awaitingResponse && !state.sawAssistantPayload && !state.turnLive && withinPreStartGrace) {
return state
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
index 1906efb039e..a60e72d40fe 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
@@ -10,6 +10,8 @@ import { modelOptionsQueryKey } from '@/lib/model-options'
import { setCurrentModel, setCurrentProvider } from '@/store/session'
import type { RpcEvent } from '@/types/hermes'
+import { PRE_TURN_LIVE_SETTLE_GRACE_MS } from './utils'
+
import { useMessageStream } from './index'
// Per-turn REST amplification guards: session.info must not refetch config for
@@ -202,6 +204,60 @@ describe('session.info settles a turn that produced no assistant payload', () =>
expect(hydrateFromStoredSession).not.toHaveBeenCalled()
})
+ // #86795: the pre-start hold above must be BOUNDED. A restore/edit/submit
+ // that armed busy optimistically but whose turn never went live backend-side
+ // (rewind refused after the arm, gateway bounce, dropped submit response)
+ // otherwise ignores every running=false heartbeat forever: busy latches,
+ // isTargetSessionBusy refuses every send, the composer queues each message
+ // ("moves to the send area") and the queue drain — gated on busy→false —
+ // never fires. Only an app restart cleared it. Past the grace window the
+ // gateway's running=false is authoritative and must settle the session.
+ it('settles an armed-but-never-live turn once the pre-start grace expires (#86795)', async () => {
+ await mountStream()
+
+ act(() => {
+ sessionStates!.set(ACTIVE_SID, {
+ ...createClientSessionState(),
+ awaitingResponse: true,
+ busy: true,
+ sawAssistantPayload: false,
+ turnStartedAt: Date.now() - PRE_TURN_LIVE_SETTLE_GRACE_MS - 1,
+ turnLive: false
+ })
+ })
+
+ sessionInfo(ACTIVE_SID, { running: false })
+
+ const state = sessionStates!.get(ACTIVE_SID)!
+ expect(state.awaitingResponse).toBe(false)
+ expect(state.busy).toBe(false)
+ expect(state.turnStartedAt).toBeNull()
+ // The predicate submit.ts / slash.ts / the composer queue drain gate on.
+ expect(busyFor(ACTIVE_SID)).toBe(false)
+ })
+
+ // An armed-busy state that carries NO clock at all (no path today creates
+ // one — submit and the rewind optimistic transforms both seed the clock —
+ // but a regression that forgets the seed must fail open, not latch).
+ it('settles an armed turn with no clock instead of latching busy (#86795)', async () => {
+ await mountStream()
+
+ act(() => {
+ sessionStates!.set(ACTIVE_SID, {
+ ...createClientSessionState(),
+ awaitingResponse: true,
+ busy: true,
+ sawAssistantPayload: false,
+ turnStartedAt: null,
+ turnLive: false
+ })
+ })
+
+ sessionInfo(ACTIVE_SID, { running: false })
+
+ expect(busyFor(ACTIVE_SID)).toBe(false)
+ })
+
it('un-latches a background session but does not hydrate its transcript', async () => {
await mountStream()
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts b/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
index 99a159bcf0d..99219daf979 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/utils.ts
@@ -72,6 +72,21 @@ export const STREAM_DELTA_FLUSH_MS = 33
// still visibly updates at least ~4x per second no matter the load.
export const MAX_STREAM_FLUSH_GAP_MS = 250
+// How long an optimistically armed turn (busy/awaitingResponse set at submit /
+// restore / edit, before the backend confirms it live) may hold off a
+// session.info running=false heartbeat. Within this window a running=false is
+// treated as a PRE-START report — the submit round trip hasn't finished, so
+// settling on it would drop the spinner and reopen the send guard mid-flight.
+// Past it, the gateway's running=false is authoritative: the turn never went
+// live (rewind refused after the arm, gateway bounce, dropped submit response,
+// missed terminal error event) and holding busy any longer latches the
+// composer shut until app restart (#86795 — every send gets queued behind a
+// turn that does not exist, and the queue drain waits on busy→false forever).
+// Generous vs. the real pre-start gap: the busy-retry deadline is 6s and the
+// backend flips running=true on accept, so heartbeats stop carrying false
+// within a couple seconds of a healthy submit.
+export const PRE_TURN_LIVE_SETTLE_GRACE_MS = 15_000
+
// Gateway/provider failures sometimes arrive as message.complete text instead
// of an explicit error event. Treat matches as inline assistant errors so they
// persist like real error events and don't get erased by hydrate fallback.
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 193cc5b42a6..6324176f0f9 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -891,7 +891,9 @@ export function usePromptActions({
updateSessionState(sessionId, state => ({
...state,
busy: false,
- awaitingResponse: false
+ awaitingResponse: false,
+ turnLive: false,
+ turnStartedAt: null
}))
notifyError(err, copy.regenerateFailed)
}
@@ -965,6 +967,8 @@ export function usePromptActions({
...state,
busy: false,
awaitingResponse: false,
+ turnLive: false,
+ turnStartedAt: null,
messages
}))
throw err
@@ -1086,7 +1090,14 @@ export function usePromptActions({
setMutableRef(busyRef, false)
setBusy(false)
setAwaitingResponse(false)
- updateSessionState(sessionId, state => ({ ...state, busy: false, awaitingResponse: false, messages }))
+ updateSessionState(sessionId, state => ({
+ ...state,
+ busy: false,
+ awaitingResponse: false,
+ turnLive: false,
+ turnStartedAt: null,
+ messages
+ }))
notifyError(surfaced, unavailable ? copy.editTurnUnavailable : copy.editFailed)
}
},
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
index f1158f34c17..a7b785bad46 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it } from 'vitest'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
+import { createClientSessionState } from '@/lib/chat-runtime'
import {
appendMidTurnUserMessage,
+ applyReloadOptimistic,
+ applyRewindOptimistic,
finalizeInterruptedMessages,
planEdit,
planReload,
@@ -485,3 +488,41 @@ describe('runRewindSubmit durable-address discipline (#87059)', () => {
expect(submit?.params?.truncate_before_user_ordinal).toBe(1)
})
})
+
+describe('optimistic rewind/reload turn-clock seeding (#86795)', () => {
+ // The no-payload settle gate in gateway-event.ts holds a running=false
+ // heartbeat off while an optimistically armed turn waits for the backend —
+ // but only for a bounded grace window measured from turnStartedAt. These
+ // transforms are the arm sites for restore/edit/regenerate, so they must
+ // seed the clock (and reset turnLive): an armed state without a clock is
+ // settled by the first heartbeat, and a STALE clock from a previous turn
+ // would let a heartbeat settle the fresh arm immediately.
+ const seeded = (extra: Partial<ReturnType<typeof createClientSessionState>>) => ({
+ ...createClientSessionState(null, [row('u1', 'user', 'first'), row('a1', 'assistant', 'answer')]),
+ ...extra
+ })
+
+ it('applyRewindOptimistic arms busy with a fresh turn clock', () => {
+ const before = Date.now()
+ const next = applyRewindOptimistic(seeded({ turnLive: true, turnStartedAt: before - 60_000 }), 0)
+
+ expect(next.busy).toBe(true)
+ expect(next.awaitingResponse).toBe(true)
+ expect(next.turnLive).toBe(false)
+ expect(next.turnStartedAt).toBeGreaterThanOrEqual(before)
+ })
+
+ it('applyReloadOptimistic arms busy with a fresh turn clock', () => {
+ const state = seeded({ turnLive: true, turnStartedAt: Date.now() - 60_000 })
+ const plan = planReload(state.messages, null)
+ const before = Date.now()
+
+ expect(plan).not.toBeNull()
+
+ const next = applyReloadOptimistic(state, plan!)
+
+ expect(next.busy).toBe(true)
+ expect(next.turnLive).toBe(false)
+ expect(next.turnStartedAt).toBeGreaterThanOrEqual(before)
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
index 6cde8c434ba..8b83ba6c1d9 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
@@ -456,7 +456,13 @@ export function applyReloadOptimistic(state: ClientSessionState, plan: ReloadPla
.map(m => (m.role === 'assistant' ? { ...m, branchGroupId: plan.branchGroupId, hidden: true } : m))
],
pendingBranchGroup: plan.branchGroupId,
- sawAssistantPayload: false
+ sawAssistantPayload: false,
+ // Arm the turn clock with the optimistic busy. The clock is what bounds
+ // the no-payload settle gate's pre-start hold (#86795): an armed turn
+ // with no clock is settled by the first running=false heartbeat, so a
+ // regenerate racing a heartbeat would lose its spinner mid-flight.
+ turnLive: false,
+ turnStartedAt: Date.now()
}
}
@@ -585,7 +591,11 @@ export function applyRewindOptimistic(
? [...state.messages.slice(0, sourceIndex), editedMessage]
: state.messages.slice(0, sourceIndex + 1),
pendingBranchGroup: null,
- sawAssistantPayload: false
+ sawAssistantPayload: false,
+ // Same as applyReloadOptimistic: seed the clock so the no-payload settle
+ // gate holds through the submit round trip but never latches (#86795).
+ turnLive: false,
+ turnStartedAt: Date.now()
}
}