Skip to content

The agent that grows with you

fix(desktop): a stopped turn is not drawn twice while its completion is in flight

Teknium6d5f8a526e1e
diff --git a/apps/desktop/src/app/chat/transcript-receipt-turns.local-rows.test.ts b/apps/desktop/src/app/chat/transcript-receipt-turns.local-rows.test.ts
index 305b6daa0d2..70adddde8f3 100644
--- a/apps/desktop/src/app/chat/transcript-receipt-turns.local-rows.test.ts
+++ b/apps/desktop/src/app/chat/transcript-receipt-turns.local-rows.test.ts
@@ -163,4 +163,33 @@ describe('local notices inside a steered turn', () => {
expect(indexOf('SIDE ANSWER')).toBeLessThan(indexOf('change course'))
expect(indexOf('Switched to fallback model')).toBeLessThan(indexOf('change course'))
})
+
+ it('stay in front of a steer prompt the window drew before its row was written', () => {
+ const window = [
+ ...toChatMessages([...olderTurn(1, 'old-a'), ...olderTurn(7, 'old-b')]),
+ live('user-sub-steer', 'user', 'steered prompt', { rowId: 13 }),
+ live('assistant-stream-1', 'assistant', 'live look', { interim: false }),
+ ...notices,
+ live('user-other', 'user', 'change course'),
+ live('assistant-stream-2', 'assistant', 'steered answer', { rowId: 17, persistedTurn: receipt })
+ ]
+
+ const page = toChatMessages([
+ ...olderTurn(1, 'old-a').slice(3),
+ ...olderTurn(7, 'old-b'),
+ ...turnRows,
+ user(16, 'change course'),
+ answer(17, 'steered answer')
+ ])
+
+ const merged = refresh(page, window)
+ const indexOf = (text: string) => merged.findIndex(message => chatMessageText(message).includes(text))
+
+ for (const text of ['SIDE ANSWER', 'change course', 'steered answer']) {
+ expect(count(merged, text), text).toBe(1)
+ }
+
+ expect(indexOf('SIDE ANSWER')).toBeGreaterThan(indexOf('steered prompt'))
+ expect(indexOf('SIDE ANSWER')).toBeLessThan(indexOf('change course'))
+ })
})
diff --git a/apps/desktop/src/app/chat/transcript-receipt-turns.ts b/apps/desktop/src/app/chat/transcript-receipt-turns.ts
index a3d6d8ee12d..018fc9113dc 100644
--- a/apps/desktop/src/app/chat/transcript-receipt-turns.ts
+++ b/apps/desktop/src/app/chat/transcript-receipt-turns.ts
@@ -23,6 +23,7 @@
import type { PersistedTurn } from '@hermes/shared'
+import { isTurnUserBubble, receiptUserRowIds } from '@/app/session/hooks/use-message-stream/receipt-user-rows'
import { transcriptRowIds } from '@/app/session/hooks/use-session-actions/pending-turn-identity'
import { type ChatMessage, isLocalSystemNotice } from '@/lib/chat-messages'
@@ -120,14 +121,38 @@ export interface ReceiptTurnDrop {
noticeAnchors: Map<string, number>
}
-/** Stored id of the first dropped row after `at` that has one. */
-function nextDroppedRowId(window: ChatMessage[], indices: number[], at: number): number | undefined {
+/**
+ * Stored id of the first dropped row after `at`. A steer prompt the window
+ * drew before its row was written carries no id yet; when the turn's user
+ * bubbles pair one-to-one with the receipt's user rows, it takes its row's id,
+ * so the notice stays above the steer instead of sliding to the final answer.
+ */
+function nextDroppedRowId(
+ window: ChatMessage[],
+ indices: number[],
+ at: number,
+ receipt: PersistedTurn
+): number | undefined {
+ const userIndices = indices.filter(index => isTurnUserBubble(window[index]))
+ const userRows = receiptUserRowIds(receipt)
+ const paired = userIndices.length === userRows.length
+
for (const index of indices) {
- const ids = index > at ? transcriptRowIds(window[index]) : []
+ if (index <= at) {
+ continue
+ }
+
+ const ids = transcriptRowIds(window[index])
if (ids.length) {
return ids[0]
}
+
+ const userRow = paired ? userRows[userIndices.indexOf(index)] : undefined
+
+ if (userRow !== undefined) {
+ return userRow
+ }
}
return undefined
@@ -154,7 +179,7 @@ export function dropReceiptTurnsThePageHolds(window: ChatMessage[], page: ChatMe
indices.forEach(at => dropped.add(at))
for (let at = indices[0] ?? index; at < index; at += 1) {
- const anchor = isLocalSystemNotice(window[at]) ? nextDroppedRowId(window, indices, at) : undefined
+ const anchor = isLocalSystemNotice(window[at]) ? nextDroppedRowId(window, indices, at, message.persistedTurn) : undefined
if (anchor !== undefined) {
noticeAnchors.set(window[at].id, anchor)
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.stopped-turn.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.stopped-turn.test.ts
new file mode 100644
index 00000000000..d6f93be6f2b
--- /dev/null
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.stopped-turn.test.ts
@@ -0,0 +1,153 @@
+import type { PersistedTurn } from '@hermes/shared'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { bindStoppedTurnReceipt } from '@/app/session/hooks/use-message-stream/interrupted-reply'
+import { finalizeStoppedMessages } from '@/app/session/hooks/use-prompt-actions/rewind'
+import {
+ clearSessionRecentlyInterrupted,
+ markSessionRecentlyInterrupted
+} from '@/app/session/hooks/use-prompt-actions/utils'
+import type { ClientSessionState } from '@/app/types'
+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { $activeSessionId, $selectedStoredSessionId } from '@/store/session'
+import { $sessionStates, clearAllSessionStates, publishSessionState } from '@/store/session-states'
+import type { SessionMessage } from '@/types/hermes'
+
+import { reconcileActiveTranscript } from './use-background-sync'
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal()),
+ getLatestSessionMessages: vi.fn(),
+ getOlderSessionMessages: vi.fn()
+}))
+
+const { getLatestSessionMessages } = await import('@/hermes')
+
+const RUNTIME = 'runtime-stopped'
+const STORED = 'stored-stopped'
+
+/** The four rows a turn stopped after its first tool round stores. */
+function storedStoppedTurn(n: number, first: number, at: number): SessionMessage[] {
+ const call = `call-${n}`
+
+ return [
+ { id: first, role: 'user', content: `U${n} stop me`, timestamp: at },
+ {
+ id: first + 1,
+ role: 'assistant',
+ content: `A${n}i1 looking`,
+ timestamp: at + 0.2,
+ tool_calls: [{ id: call, type: 'function', function: { name: 'terminal', arguments: '{"command":"echo"}' } }]
+ },
+ { id: first + 2, role: 'tool', content: '{"output": "ok"}', tool_call_id: call, tool_name: 'terminal', timestamp: at + 0.3 },
+ { id: first + 3, role: 'assistant', content: `A${n} partial`, timestamp: at + 1.2, display_metadata: { interrupted: true } }
+ ] as SessionMessage[]
+}
+
+const count = (needle: string) =>
+ ($sessionStates.get()[RUNTIME]?.messages ?? []).filter(message => chatMessageText(message).includes(needle)).length
+
+function refresh() {
+ return reconcileActiveTranscript({
+ activeSessionIdRef: { current: RUNTIME },
+ busyRef: { current: false },
+ requestSequenceRef: { current: 0 },
+ resolveSession: () => ({ profile: 'default' }),
+ selectedStoredSessionIdRef: { current: STORED },
+ signatureRef: { current: new Map<string, string>() },
+ updateSessionState: (sessionId, updater) => {
+ const next = updater($sessionStates.get()[sessionId] ?? createClientSessionState(STORED))
+ publishSessionState(sessionId, next)
+
+ return next
+ }
+ })
+}
+
+beforeEach(() => {
+ // An inactive runtime's transcript is evicted on publish; this one is open.
+ $activeSessionId.set(RUNTIME)
+ $selectedStoredSessionId.set(STORED)
+})
+
+afterEach(() => {
+ $activeSessionId.set(null)
+ $selectedStoredSessionId.set(null)
+ clearAllSessionStates()
+ clearSessionRecentlyInterrupted()
+ vi.mocked(getLatestSessionMessages).mockReset()
+})
+
+describe('a page read right after Stop', () => {
+ it('draws the stopped turn once when the page lands before the interrupted completion (#144899 N2)', async () => {
+ const receipt: PersistedTurn = {
+ row_ids: [145, 146, 147, 148],
+ user_row_ids: [145],
+ submission_id: 'stop-10',
+ complete: false
+ }
+
+ const liveReply: ChatMessage = {
+ id: 'assistant-stream-10',
+ role: 'assistant',
+ pending: true,
+ timestamp: 1101.19,
+ parts: [
+ { type: 'text', text: 'A10i1 looking' },
+ {
+ type: 'tool-call',
+ toolCallId: 'call-10',
+ toolName: 'terminal',
+ args: { command: 'echo' },
+ argsText: '{"command":"echo"}',
+ result: '{"output": "ok"}'
+ },
+ { type: 'text', text: '\n\nA10 ' }
+ ]
+ }
+
+ // Stop sealed the reply at its first chunk and idled the view: the stopped
+ // turn's rows are live and unstored, below an earlier stopped turn.
+ const stopped: ClientSessionState = {
+ ...createClientSessionState(STORED),
+ interrupted: true,
+ messages: finalizeStoppedMessages(
+ [
+ ...toChatMessages(storedStoppedTurn(9, 141, 1090.29)),
+ { id: 'user-stop-10', role: 'user', parts: [{ type: 'text', text: 'U10 stop me' }], timestamp: 1100.93 },
+ liveReply
+ ],
+ liveReply.id
+ )
+ }
+
+ publishSessionState(RUNTIME, stopped)
+ markSessionRecentlyInterrupted(RUNTIME)
+
+ // The newest page already holds the stored stopped turn.
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ ...storedStoppedTurn(8, 137, 1079.93),
+ ...storedStoppedTurn(9, 141, 1090.29),
+ ...storedStoppedTurn(10, 145, 1101.04)
+ ],
+ session_id: STORED
+ } as never)
+
+ await refresh()
+
+ expect(count('U10 stop me')).toBe(1)
+ expect(count('A10i1 looking')).toBe(1)
+
+ // The interrupted completion binds the receipt; the retried read then lands.
+ const settled = $sessionStates.get()[RUNTIME]!
+ publishSessionState(RUNTIME, { ...settled, messages: bindStoppedTurnReceipt(settled.messages, receipt) })
+
+ await refresh()
+
+ expect(getLatestSessionMessages).toHaveBeenCalled()
+ expect(count('U10 stop me')).toBe(1)
+ expect(count('A10i1 looking')).toBe(1)
+ })
+})
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 7e55032e307..9d06caa9fd2 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -6,6 +6,10 @@ import {
graftRefreshedTailOntoBackfill,
olderPageReader
} from '@/app/chat/transcript-backfill'
+import {
+ isSessionRecentlyInterrupted,
+ recentInterruptRemainingMs
+} from '@/app/session/hooks/use-prompt-actions/utils'
import { sessionCreatedThisRun } from '@/app/session/hooks/use-session-actions/created-this-run'
import { preserveLocalPendingTurnMessages } from '@/app/session/hooks/use-session-actions/utils'
import { getLatestSessionMessages, type ProfileScope } from '@/hermes'
@@ -135,10 +139,36 @@ export interface ActiveTranscriptRefreshDeps {
) => ClientSessionState
}
+/**
+ * Stop idles the view at the click, but the stopped turn's rows stay unstored
+ * until its interrupted `message.complete` binds the receipt. A page read in
+ * that gap already holds the stored turn, so the merge drew it twice until the
+ * completion landed (#144899 N2). The hold ends with the binding, or with the
+ * Stop cooldown when no receipt ever comes.
+ */
+export function stopAwaitsItsReceipt(state: ClientSessionState, runtimeId: string): boolean {
+ if (!state.interrupted || !isSessionRecentlyInterrupted(runtimeId)) {
+ return false
+ }
+
+ const messages = state.messages
+ const lastUser = messages.findLastIndex(message => message.role === 'user')
+ const lastReply = messages.findLastIndex(message => message.role === 'assistant' && !message.hidden)
+
+ if (lastReply > lastUser) {
+ return !messages[lastReply].persistedTurn
+ }
+
+ return lastUser >= 0 && messages[lastUser].rowId === undefined
+}
+
function tileRuntimeOwnsLiveState(runtimeId: string): boolean {
const state = $sessionStates.get()[runtimeId]
- return Boolean(state && (state.busy || state.awaitingResponse || state.needsInput || state.turnLive))
+ return Boolean(
+ state &&
+ (state.busy || state.awaitingResponse || state.needsInput || state.turnLive || stopAwaitsItsReceipt(state, runtimeId))
+ )
}
/** Backfill/retention may prepend or release a prefix without changing the tail. */
@@ -1097,6 +1127,20 @@ export function useBackgroundSync({
$activeSessionId.get() === activeSessionId && $selectedStoredSessionId.get() === activeStoredSessionId
const isLive = () => $busy.get() || tileRuntimeOwnsLiveState(activeSessionId)
+ let stopHoldTimer: null | ReturnType<typeof setTimeout> = null
+
+ // A Stop hold whose receipt never comes ends on the clock, not on a store
+ // write, so wake the observer once the cooldown runs out.
+ const observeWhenStopHoldExpires = () => {
+ const state = $sessionStates.get()[activeSessionId]
+
+ if (stopHoldTimer === null && state && stopAwaitsItsReceipt(state, activeSessionId)) {
+ stopHoldTimer = setTimeout(() => {
+ stopHoldTimer = null
+ observe()
+ }, recentInterruptRemainingMs(activeSessionId) + 1)
+ }
+ }
const observe = () => {
if (!isCurrent()) {
@@ -1104,6 +1148,8 @@ export function useBackgroundSync({
}
if (isLive()) {
+ observeWhenStopHoldExpires()
+
const read = activeTranscriptReadRef.current
if (read?.sessionKey === sessionKey) {
@@ -1142,6 +1188,11 @@ export function useBackgroundSync({
disposed = true
unsubscribeState()
unsubscribeBusy()
+
+ if (stopHoldTimer !== null) {
+ clearTimeout(stopHoldTimer)
+ }
+
activeTranscriptReadRef.current = null
activeTranscriptRefreshPendingRef.current = null
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts b/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts
index 404093d40e6..aa5a03888ce 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts
@@ -7,7 +7,7 @@ const isRowId = (value: unknown): value is number =>
typeof value === 'number' && Number.isSafeInteger(value) && value > 0
/** The receipt's stored user rows in turn order (prompt first, then each steer/redirect row). */
-function receiptUserRowIds(receipt: PersistedTurn): number[] {
+export function receiptUserRowIds(receipt: PersistedTurn): number[] {
const listed = receipt.user_row_ids
if (Array.isArray(listed) && listed.length && listed.every(isRowId)) {
@@ -19,7 +19,7 @@ function receiptUserRowIds(receipt: PersistedTurn): number[] {
return isRowId(receipt.user_row_id) && receipt.complete === true ? [receipt.user_row_id] : []
}
-const isTurnUserBubble = (message: ChatMessage) =>
+export const isTurnUserBubble = (message: ChatMessage) =>
message.role === 'user' && !message.hidden && !message.id.startsWith('user-queued-')
/**
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
index cc4e662e6d0..2aa0f4bb9de 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
@@ -428,6 +428,11 @@ export function isSessionRecentlyInterrupted(sessionId: string, now = Date.now()
return true
}
+/** Milliseconds left on the session's Stop cooldown (0 when none). */
+export function recentInterruptRemainingMs(sessionId: string, now = Date.now()): number {
+ return isSessionRecentlyInterrupted(sessionId, now) ? (_recentlyInterruptedUntil.get(sessionId) ?? now) - now : 0
+}
+
export function clearSessionRecentlyInterrupted(sessionId?: string): void {
if (sessionId) {
_recentlyInterruptedUntil.delete(sessionId)