Skip to content

The agent that grows with you

fix(desktop): stop refusing sends from a window behind its chat

Brooklyn Nicholsonfcfc5c66ede7
diff --git a/apps/desktop/src/app/chat/transcript-backfill.stale-guard-loop.test.ts b/apps/desktop/src/app/chat/transcript-backfill.stale-guard-loop.test.ts
deleted file mode 100644
index 7c753df8081..00000000000
--- a/apps/desktop/src/app/chat/transcript-backfill.stale-guard-loop.test.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'
-import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
-import { messagesIfTranscriptBehind } from '@/lib/stale-transcript-guard'
-import type { SessionMessage } from '@/types/hermes'
-
-/**
- * REGRESSION: the pre-send stale-transcript guard never converges when the
- * newest display page opens on a page-local tool fold.
- *
- * `submit.ts` (use-prompt-actions) and `use-session-tile-delegate.ts` read the
- * cached transcript, drop the optimistic bubble, ask
- * `transcriptRefreshIfBehind` whether this window is behind, and when the
- * surplus is a competing view's (`competingView`) install the refreshed page
- * and REFUSE the send (own residue is grafted and the send proceeds). A user
- * who retries
- * re-runs that loop with the installed transcript as `localMessages`, so the
- * guard has to reach a fixed point: a window that was just refreshed must not
- * be reported behind again.
- *
- * `LATEST_SESSION_MESSAGES_LIMIT` means the guard's authoritative read is only
- * the last page of a long session, and that page can begin mid tool batch.
- * `toChatMessages` flushes such a batch as a synthetic assistant message whose
- * id is not durable, so the page's first rendered row has no `rowId`. When the
- * window was hydrated from that same page, `graftRefreshedTailOntoBackfill`
- * used to read that unanchored prefix row as proof of earlier history and
- * re-prepended it to the refreshed page on every read. The refreshed window
- * came back one row longer each round, so `messagesIfTranscriptBehind` kept
- * answering "behind": send is refused on every attempt and the transcript
- * grows a duplicate per attempt.
- */
-
-const OPTIMISTIC_ID = 'optimistic-1'
-
-const optimistic = (): ChatMessage => ({
- id: OPTIMISTIC_ID,
- parts: [{ type: 'text', text: 'next' }],
- role: 'user'
-})
-
-const userRow = (rowId: number, text: string): SessionMessage =>
- ({ id: rowId, role: 'user', content: text, timestamp: 1_000 + rowId }) as SessionMessage
-
-const assistantRow = (rowId: number, text: string): SessionMessage =>
- ({ id: rowId, role: 'assistant', content: text, timestamp: 1_000 + rowId }) as SessionMessage
-
-/** A standalone tool row: `toChatMessages` folds it into a message with no rowId. */
-const toolRow = (rowId: number, text: string): SessionMessage =>
- ({ id: rowId, role: 'tool', content: text, timestamp: 1_000 + rowId }) as SessionMessage
-
-/**
- * The shape that reproduces it: the newest page opens on a TOOL ROW with no
- * assistant answer under it yet, so `toChatMessages` flushes it as its own
- * message with no durable rowId — exactly the leading fold a tool-heavy turn
- * puts at the top of the page.
- */
-const pageOpeningOnToolRow = (): SessionMessage[] => [
- toolRow(100, 'reading files'),
- userRow(101, 'next question'),
- assistantRow(102, 'next answer'),
- userRow(103, 'final question'),
- assistantRow(104, 'final answer')
-]
-
-/** One submit attempt, mirroring the guard call + install both submit paths make. */
-const attempt = (local: ChatMessage[], page: SessionMessage[]) => {
- const baseline = local.filter(message => message.id !== OPTIMISTIC_ID)
- const refreshed = messagesIfTranscriptBehind(baseline, toChatMessages(page))
-
- return {
- installed: refreshed ? preserveLocalAssistantErrors(refreshed, baseline) : baseline,
- refreshed
- }
-}
-
-/**
- * Retry the send until the guard lets it through. `rounds` counts the refusals
- * that preceded the allowed send — 0 means the first attempt went out.
- */
-const retryUntilAllowed = (start: ChatMessage[], page: SessionMessage[], maxRounds = 4) => {
- let local = start
- const sizes: number[] = []
-
- for (let round = 0; round < maxRounds; round += 1) {
- const { refreshed, installed } = attempt(local, page)
-
- if (!refreshed) {
- return { rounds: round, settled: true, sizes }
- }
-
- sizes.push(installed.length)
- local = [...installed, optimistic()]
- }
-
- return { rounds: maxRounds, settled: false, sizes }
-}
-
-describe('stale transcript guard lets a retried send through', () => {
- it('is a fixed point when the window was hydrated from a page opening on a tool fold', () => {
- const page = pageOpeningOnToolRow()
- const local = toChatMessages(page)
- const remote = toChatMessages(page)
-
- // The page's leading fold is already in the window: nothing is missing, so
- // the graft must not manufacture an extra row.
- expect(local[0].rowId).toBeUndefined()
- expect(graftRefreshedTailOntoBackfill(remote, local)).toEqual(remote)
- expect(messagesIfTranscriptBehind(local, remote)).toBeNull()
- })
-
- it('sends on the first attempt when the window already holds the page', () => {
- const page = pageOpeningOnToolRow()
-
- expect(retryUntilAllowed([...toChatMessages(page), optimistic()], page)).toEqual({
- rounds: 0,
- settled: true,
- sizes: []
- })
- })
-
- it('refuses at most once from a genuinely behind window, then sends', () => {
- const page = pageOpeningOnToolRow()
- const behind = toChatMessages(page.slice(0, 4))
-
- expect(retryUntilAllowed([...behind, optimistic()], page)).toEqual({
- rounds: 1,
- settled: true,
- sizes: [toChatMessages(page).length]
- })
- })
-
- it('does not grow the window by one row on every retry', () => {
- const page = pageOpeningOnToolRow()
- const run = retryUntilAllowed([...toChatMessages(page), optimistic()], page)
-
- expect(run.settled).toBe(true)
- expect(run.sizes).toEqual([])
- })
-
- it('still keeps a backfilled prefix that is actually earlier than the page', () => {
- const page = pageOpeningOnToolRow()
- const olderPrefix = toChatMessages([userRow(1, 'ancient'), assistantRow(2, 'ancient reply')])
- const local = [...olderPrefix, ...toChatMessages(page)]
-
- const grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), local)
-
- expect(grafted.length).toBe(local.length)
- expect(grafted[0]).toEqual(olderPrefix[0])
- })
-
- it('stays stable across repeated refreshes over a backfilled prefix', () => {
- const page = pageOpeningOnToolRow()
- const olderPrefix = toChatMessages([userRow(1, 'ancient'), assistantRow(2, 'ancient reply')])
- const local = [...olderPrefix, ...toChatMessages(page)]
-
- let grafted = local
-
- for (let round = 0; round < 5; round += 1) {
- grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), grafted)
-
- expect(grafted.length).toBe(local.length)
- expect(grafted[0]).toEqual(olderPrefix[0])
- }
-
- expect(messagesIfTranscriptBehind(grafted, toChatMessages(page))).toBeNull()
- })
-
- it('still reads an unstored fold the page does not carry as earlier history', () => {
- const page = pageOpeningOnToolRow()
-
- // A fold the refreshed page has no copy of: it can only have come from an
- // older page, so it stays in front of the refreshed tail.
- const olderFold: ChatMessage = {
- id: '900-0-tools',
- parts: [{ completedAt: 900, type: 'tool-call', toolCallId: 'old-call', toolName: 'tool' }],
- role: 'assistant'
- }
-
- const local = [olderFold, ...toChatMessages(page)]
-
- const grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), local)
-
- // The older fold survives in front of the page; the fold the page already
- // carries is not duplicated.
- expect(grafted.length).toBe(local.length)
- expect(grafted[0]).toEqual(olderFold)
- })
-})
diff --git a/apps/desktop/src/app/chat/transcript-backfill.test.ts b/apps/desktop/src/app/chat/transcript-backfill.test.ts
index 707609fd3a2..fad37531dff 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.test.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ChatMessage } from '@/lib/chat-messages'
-import { messagesIfTranscriptBehind } from '@/lib/stale-transcript-guard'
import { $transcriptTailBySessionId, recordTranscriptTail, transcriptTailState } from '@/store/transcript-tail'
import {
@@ -278,11 +277,6 @@ describe('graftRefreshedTailOntoBackfill', () => {
const page = [chat('orphan-tools'), chat('user', 122886), chat('assistant', 122887)]
expect(graftRefreshedTailOntoBackfill(page, page)).toBe(page)
- expect(messagesIfTranscriptBehind(page, page)).toBeNull()
-
- const grown = [...page, chat('later', 122890)]
-
- expect(messagesIfTranscriptBehind(page, grown)).toBe(grown)
})
it('returns the refreshed tail when it is not shorter than the previous transcript', () => {
@@ -293,50 +287,6 @@ describe('graftRefreshedTailOntoBackfill', () => {
})
})
-describe('messagesIfTranscriptBehind retention tips (#123909)', () => {
- it('treats a retention-trimmed store ending on the page tip as current', () => {
- // Retention released the head: the store holds fewer messages than the
- // latest page renders, but its last durable row IS the page's own tip.
- // The count comparison refused every send on that shape.
- const trimmed = [chat('old-a', 110), chat('old-b', 111), chat('tip-user', 118), chat('tip-reply', 119)]
-
- const page = [
- chat('old-a', 110),
- chat('old-b', 111),
- chat('mid-turn', 115),
- chat('tip-user', 118),
- chat('tip-reply', 119)
- ]
-
- expect(page.length).toBeGreaterThan(trimmed.length)
-
- expect(messagesIfTranscriptBehind(trimmed, page)).toBeNull()
- })
-
- it('skips unpersisted tail rows when establishing the local tip', () => {
- // The guard runs on a baseline that may still end on a live row past the
- // last durable one; the durable tip decides, not the stream bubble.
- const local = [chat('durable-reply', 119), chat('live-stream')]
- const page = [chat('older', 118), chat('durable-reply', 119)]
-
- expect(messagesIfTranscriptBehind(local, page)).toBeNull()
- })
-
- it("still refuses when a peer window's newer row changes the tip (#65047)", () => {
- const local = [chat('a', 118), chat('b', 119)]
- const page = [...local, chat('peer-turn', 120)]
-
- expect(messagesIfTranscriptBehind(local, page)).toBe(page)
- })
-
- it('falls back to counts when neither side carries a durable row id', () => {
- const local = [chat('a'), chat('b')]
- const page = [chat('a'), chat('b'), chat('c')]
-
- expect(messagesIfTranscriptBehind(local, page)).toBe(page)
- })
-})
-
describe('extendRefreshPageToOverlap', () => {
it('reads older pages until a long refresh shares a durable row with the rendered transcript', async () => {
const previous = [chat('earlier', 1), chat('prompt', 2), chat('reply', 3)]
diff --git a/apps/desktop/src/app/chat/transcript-backfill.tool-fold-graft.test.ts b/apps/desktop/src/app/chat/transcript-backfill.tool-fold-graft.test.ts
new file mode 100644
index 00000000000..e939d433f19
--- /dev/null
+++ b/apps/desktop/src/app/chat/transcript-backfill.tool-fold-graft.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest'
+
+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'
+import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
+import type { SessionMessage } from '@/types/hermes'
+
+/**
+ * A refresh reads only the newest page of a long session, and that page can
+ * begin mid tool batch. `toChatMessages` flushes such a batch as a synthetic
+ * assistant message whose id is not durable, so the page's first rendered row
+ * has no `rowId`. `graftRefreshedTailOntoBackfill` used to read that
+ * unanchored row as proof of earlier history and re-prepend it on every
+ * refresh, so the window grew a duplicate fold per read (#123856).
+ */
+
+const userRow = (rowId: number, text: string): SessionMessage =>
+ ({ id: rowId, role: 'user', content: text, timestamp: 1_000 + rowId }) as SessionMessage
+
+const assistantRow = (rowId: number, text: string): SessionMessage =>
+ ({ id: rowId, role: 'assistant', content: text, timestamp: 1_000 + rowId }) as SessionMessage
+
+/** A standalone tool row: `toChatMessages` folds it into a message with no rowId. */
+const toolRow = (rowId: number, text: string): SessionMessage =>
+ ({ id: rowId, role: 'tool', content: text, timestamp: 1_000 + rowId }) as SessionMessage
+
+/** The newest page opens on a tool row with no assistant answer under it yet. */
+const pageOpeningOnToolRow = (): SessionMessage[] => [
+ toolRow(100, 'reading files'),
+ userRow(101, 'next question'),
+ assistantRow(102, 'next answer'),
+ userRow(103, 'final question'),
+ assistantRow(104, 'final answer')
+]
+
+describe('refresh graft over a page that opens on a tool fold', () => {
+ it('is a fixed point when the window was hydrated from that same page', () => {
+ const page = pageOpeningOnToolRow()
+ const local = toChatMessages(page)
+ const remote = toChatMessages(page)
+
+ // The page's leading fold is already in the window: nothing is missing, so
+ // the graft must not manufacture an extra row.
+ expect(local[0].rowId).toBeUndefined()
+ expect(graftRefreshedTailOntoBackfill(remote, local)).toEqual(remote)
+ })
+
+ it('still keeps a backfilled prefix that is actually earlier than the page', () => {
+ const page = pageOpeningOnToolRow()
+ const olderPrefix = toChatMessages([userRow(1, 'ancient'), assistantRow(2, 'ancient reply')])
+ const local = [...olderPrefix, ...toChatMessages(page)]
+
+ const grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), local)
+
+ expect(grafted.length).toBe(local.length)
+ expect(grafted[0]).toEqual(olderPrefix[0])
+ })
+
+ it('stays stable across repeated refreshes over a backfilled prefix', () => {
+ const page = pageOpeningOnToolRow()
+ const olderPrefix = toChatMessages([userRow(1, 'ancient'), assistantRow(2, 'ancient reply')])
+ const local = [...olderPrefix, ...toChatMessages(page)]
+
+ let grafted = local
+
+ for (let round = 0; round < 5; round += 1) {
+ grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), grafted)
+
+ expect(grafted.length).toBe(local.length)
+ expect(grafted[0]).toEqual(olderPrefix[0])
+ }
+ })
+
+ it('still reads an unstored fold the page does not carry as earlier history', () => {
+ const page = pageOpeningOnToolRow()
+
+ // A fold the refreshed page has no copy of: it can only have come from an
+ // older page, so it stays in front of the refreshed tail.
+ const olderFold: ChatMessage = {
+ id: '900-0-tools',
+ parts: [{ completedAt: 900, type: 'tool-call', toolCallId: 'old-call', toolName: 'tool' }],
+ role: 'assistant'
+ }
+
+ const local = [olderFold, ...toChatMessages(page)]
+
+ const grafted = graftRefreshedTailOntoBackfill(toChatMessages(page), local)
+
+ // The older fold survives in front of the page; the fold the page already
+ // carries is not duplicated.
+ expect(grafted.length).toBe(local.length)
+ expect(grafted[0]).toEqual(olderFold)
+ })
+})
diff --git a/apps/desktop/src/app/chat/transcript-backfill.ts b/apps/desktop/src/app/chat/transcript-backfill.ts
index c169121c37e..5bac291df53 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.ts
@@ -410,12 +410,11 @@ export function graftRefreshedTailOntoBackfill(refreshedTail: ChatMessage[], pre
// window's copy was hydrated from the same page, and the refreshed page
// re-emits that row with the same id. Keeping both copies makes the graft
// non-idempotent — the refreshed window comes back one row longer than the
- // local window on every read, so `messagesIfTranscriptBehind` reports
- // "behind" forever: the send is refused before `prompt.submit` runs and a
- // duplicate accumulates per retry. Drop only the prefix copies the page
- // already carries. Every durable prefix row keeps travelling in front of
- // the refreshed tail, and so does an unstored row the page has no copy of
- // (it can only have come from an older page).
+ // local window on every read, and a duplicate fold accumulates per refresh.
+ // Drop only the prefix copies the page already carries. Every durable
+ // prefix row keeps travelling in front of the refreshed tail, and so does
+ // an unstored row the page has no copy of (it can only have come from an
+ // older page).
const refreshedIds = new Set(refreshedTail.map(message => message.id))
const prefix = previous
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 de455ed5ff2..ac8cfb2fef7 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -1159,8 +1159,7 @@ export function useBackgroundSync({
// Wake/return backstop (#125532): a socket that zombie-survives laptop sleep
// never transitions gatewayState, so the reconnect backstop above cannot
// fire, and replies that completed while the machine slept leave the open
- // transcript behind — the first send after wake then bounces off the
- // stale-send guard (#65047) once. Catch up when the window is viewed again;
+ // transcript behind. Catch up when the window is viewed again;
// the reconcile is signature-gated, so an unchanged transcript costs one
// cheap tail read. Messaging transcripts keep their own visible poll below.
useEffect(() => {
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index bad3c8d92d1..6a417f14bb3 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { reasoningEffortPending } from '@/app/chat/session-view'
import type { ClientSessionState } from '@/app/types'
import type * as HermesModule from '@/hermes'
-import { type ChatMessage, textPart } from '@/lib/chat-messages'
+import { textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { $notifications } from '@/store/notifications'
import { $cronRunReadOnlyVerdicts, recordCronRunVerdict } from '@/store/read-only-transcript'
@@ -696,7 +696,7 @@ describe('useSessionTileDelegate interruptSession', () => {
})
})
-describe('useSessionTileDelegate stale multi-window guard (#65047)', () => {
+describe('useSessionTileDelegate send from a tile behind the stored transcript', () => {
const storedId = 'stored-tile-peer'
const runtimeId = 'rt-tile-peer'
@@ -712,7 +712,7 @@ describe('useSessionTileDelegate stale multi-window guard (#65047)', () => {
$notifications.set([])
})
- it('refuses submitToSession when a peer window advanced the transcript', async () => {
+ it('submits without a pre-send transcript read or a warning when a peer window advanced the chat (#65047)', async () => {
setSessions([row({ id: storedId, profile: 'work-vps' })])
vi.mocked(getLatestSessionMessages).mockResolvedValue({
session_id: storedId,
@@ -724,99 +724,7 @@ describe('useSessionTileDelegate stale multi-window guard (#65047)', () => {
]
})
- const stale = createClientSessionState(storedId, [
- { id: 'u1', role: 'user', parts: [textPart('a')] },
- { id: 'a1', role: 'assistant', parts: [textPart('b')] }
- ])
-
- const sessionStateByRuntimeIdRef = { current: new Map([[runtimeId, stale]]) }
- const runtimeIdByStoredSessionIdRef = { current: new Map([[storedId, runtimeId]]) }
- const seeds: unknown[] = []
- const requestGateway = vi.fn(async () => ({}) as never)
-
- renderTile(requestGateway, {
- runtimeIdByStoredSessionIdRef,
- sessionStateByRuntimeIdRef,
- updateSessionState: vi.fn((id, updater, stored) => {
- const prev = sessionStateByRuntimeIdRef.current.get(id) ?? createClientSessionState(stored)
- const next = updater(prev)
- sessionStateByRuntimeIdRef.current.set(id, next)
- seeds.push(next)
-
- return next
- })
- })
-
- await sessionTileDelegate()!.submitToSession(runtimeId, 'stale tile send')
-
- expect(getLatestSessionMessages).toHaveBeenCalledWith(storedId, 'work-vps')
- expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())
- expect(requestGatewayForProfile).not.toHaveBeenCalledWith(
- 'work-vps',
- 'prompt.submit',
- expect.anything(),
- expect.anything(),
- expect.anything()
- )
- expect(seeds.at(-1)).toEqual(expect.objectContaining({ busy: false, messages: expect.any(Array) }))
- expect((seeds.at(-1) as { messages: unknown[] }).messages).toHaveLength(4)
- expect($notifications.get().some(note => note.kind === 'warning')).toBe(true)
- })
-
- it('grafts same-window residue and still submits the Quick Entry prompt', async () => {
- setSessions([row({ id: storedId, profile: 'work-vps' })])
- vi.mocked(getLatestSessionMessages).mockResolvedValue({
- session_id: storedId,
- messages: [
- { content: 'a', id: 1, role: 'user', timestamp: 1 },
- { content: 'server-side turn residue', id: 2, role: 'assistant', timestamp: 2 }
- ]
- })
-
- const stale = createClientSessionState(storedId, [{ id: 'u1', role: 'user', rowId: 1, parts: [textPart('a')] }])
-
- const sessionStateByRuntimeIdRef = { current: new Map([[runtimeId, stale]]) }
- const runtimeIdByStoredSessionIdRef = { current: new Map([[storedId, runtimeId]]) }
- const seeds: unknown[] = []
- const requestGateway = vi.fn(async () => ({}) as never)
-
- renderTile(requestGateway, {
- runtimeIdByStoredSessionIdRef,
- sessionStateByRuntimeIdRef,
- updateSessionState: vi.fn((id, updater, stored) => {
- const prev = sessionStateByRuntimeIdRef.current.get(id) ?? createClientSessionState(stored)
- const next = updater(prev)
- sessionStateByRuntimeIdRef.current.set(id, next)
- seeds.push(next)
-
- return next
- })
- })
-
- await sessionTileDelegate()!.submitToSession(runtimeId, 'follow up')
-
- expect(requestGatewayForProfile).toHaveBeenCalledWith(
- 'work-vps',
- 'prompt.submit',
- { session_id: runtimeId, text: 'follow up' },
- 1_800_000,
- undefined
- )
- expect((seeds.at(-1) as { messages: ChatMessage[] }).messages.map(message => message.rowId)).toEqual([1, 2])
- expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)
- })
-
- it('allows submitToSession when the authoritative transcript is not ahead', async () => {
- setSessions([row({ id: storedId, profile: 'work-vps' })])
- vi.mocked(getLatestSessionMessages).mockResolvedValue({
- session_id: storedId,
- messages: [
- { content: 'a', role: 'user', timestamp: 1 },
- { content: 'b', role: 'assistant', timestamp: 2 }
- ]
- })
-
- const fresh = createClientSessionState(storedId, [
+ const behind = createClientSessionState(storedId, [
{ id: 'u1', role: 'user', parts: [textPart('a')] },
{ id: 'a1', role: 'assistant', parts: [textPart('b')] }
])
@@ -825,18 +733,19 @@ describe('useSessionTileDelegate stale multi-window guard (#65047)', () => {
renderTile(requestGateway, {
runtimeIdByStoredSessionIdRef: { current: new Map([[storedId, runtimeId]]) },
- sessionStateByRuntimeIdRef: { current: new Map([[runtimeId, fresh]]) }
+ sessionStateByRuntimeIdRef: { current: new Map([[runtimeId, behind]]) }
})
- await sessionTileDelegate()!.submitToSession(runtimeId, 'fresh tile send')
+ await sessionTileDelegate()!.submitToSession(runtimeId, 'tile send from behind')
expect(requestGatewayForProfile).toHaveBeenCalledWith(
'work-vps',
'prompt.submit',
- { session_id: runtimeId, text: 'fresh tile send' },
+ { session_id: runtimeId, text: 'tile send from behind' },
1_800_000,
undefined
)
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)
})
})
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 335ff3095ec..c25709c6726 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
@@ -14,7 +14,6 @@ import {
import { translateNow } from '@/i18n/runtime'
import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
import { markReasoningEffortPending } from '@/lib/chat-runtime'
-import { profileScopeForSessionOwner, transcriptRefreshIfBehind } from '@/lib/stale-transcript-guard'
import { noteMessageSent } from '@/store/desktop-metrics'
import { notify } from '@/store/notifications'
import {
@@ -25,7 +24,11 @@ import {
} from '@/store/read-only-transcript'
import { knownSessionOwner, ownerLookupSessionRows } from '@/store/session'
import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
-import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
+import {
+ profileScopeForSessionOwner,
+ requestForSessionProfile,
+ type SessionOwnerScope
+} from '@/store/session-request-router'
import {
$sessionTiles,
publishSessionState,
@@ -504,47 +507,6 @@ export function useSessionTileDelegate({
return { runtimeSessionId: runtimeId, storedSessionId: null }
}
- if (storedSessionId) {
- const cached = sessionStateByRuntimeIdRef.current.get(runtimeId)
- const owner = await ownerForStoredSession(storedSessionId)
-
- const refresh = await transcriptRefreshIfBehind(storedSessionId, cached?.messages ?? [], {
- profile: profileScopeForSessionOwner(owner)
- })
-
- // Only a competing view's surplus refuses the send; this window's own
- // server-side turn residue is grafted and the prompt proceeds (#130031).
- if (refresh?.competingView) {
- updateSessionState(
- runtimeId,
- state => ({
- ...state,
- awaitingResponse: false,
- busy: false,
- messages: refresh.messages,
- pendingBranchGroup: null
- }),
- storedSessionId
- )
- notify({
- kind: 'warning',
- message: translateNow('desktop.staleSessionBody'),
- title: translateNow('desktop.staleSessionTitle')
- })
-
- // Nothing was dispatched: the transcript was stale, so the prompt
- // never reached a backend. Report an unprovable binding rather than
- // success — the accepted-identity contract has no "refused" case,
- // and a null storedSessionId can never equal the requested session,
- // so callers never report delivery for this refusal.
- return { runtimeSessionId: runtimeId, storedSessionId: null }
- }
-
- if (refresh) {
- updateSessionState(runtimeId, state => ({ ...state, messages: refresh.messages }), storedSessionId)
- }
- }
-
const routedRequest = storedSessionId
? <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) =>
requestForStoredSession<T>(storedSessionId, method, params ?? {}, timeoutMs)
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
index 0699c3b203c..d7a35054ba5 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getLatestSessionMessages, getSession } from '@/hermes'
import { en } from '@/i18n/en'
-import { textPart, toChatMessages } from '@/lib/chat-messages'
+import { textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { $compactingSessions, setSessionCompacting } from '@/store/compaction'
import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'
@@ -6257,15 +6257,19 @@ describe('usePromptActions live-owner refusal (#106217)', () => {
})
})
-describe('usePromptActions stale multi-window guard (#65047)', () => {
+describe('usePromptActions send from a window behind the stored transcript', () => {
afterEach(() => {
cleanup()
$notifications.set([])
setSessions(() => [])
})
- it('refuses prompt.submit when the local transcript is behind and refreshes it', async () => {
- const storedId = 'stored-stale-submit'
+ it('sends without a pre-send transcript read or a warning, even when another view is ahead (#65047)', async () => {
+ // The backend owns the model's context: a second window shares the live
+ // session, and each turn folds rows other surfaces wrote into the model
+ // history before it runs. The window being behind is only a stale view,
+ // so the send goes out as typed.
+ const storedId = 'stored-behind-submit'
setSessions(() => [sessionInfo({ id: storedId, profile: 'work-vps', title: 'Remote chat' })])
vi.mocked(getLatestSessionMessages).mockResolvedValue({
session_id: storedId,
@@ -6278,13 +6282,11 @@ describe('usePromptActions stale multi-window guard (#65047)', () => {
})
const requestGateway = vi.fn(async () => ({}) as never)
- const seeds: Record<string, unknown>[] = []
let handle: HarnessHandle | null = null
await actRender(
<Harness
onReady={h => (handle = h)}
- onSeedState={state => seeds.push(state)}
refreshSessions={async () => undefined}
requestGateway={requestGateway}
seedMessages={[
@@ -6295,120 +6297,16 @@ describe('usePromptActions stale multi-window guard (#65047)', () => {
/>
)
- expect(await handle!.submitText('stale send from secondary window')).toBe(false)
- expect(getLatestSessionMessages).toHaveBeenCalledWith(storedId, 'work-vps')
- expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())
-
- const last = seeds.at(-1) as { awaitingResponse?: boolean; busy?: boolean; messages?: unknown[] } | undefined
- expect(last?.busy).toBe(false)
- expect(last?.awaitingResponse).toBe(false)
- expect(last?.messages).toHaveLength(4)
- expect($notifications.get().some(note => note.kind === 'warning')).toBe(true)
- })
-
- it('allows prompt.submit when the authoritative transcript is not ahead', async () => {
- vi.mocked(getLatestSessionMessages).mockResolvedValue({
- session_id: RUNTIME_SESSION_ID,
- messages: [
- { content: 'a', role: 'user', timestamp: 1 },
- { content: 'b', role: 'assistant', timestamp: 2 }
- ]
- })
-
- const requestGateway = vi.fn(async () => ({}) as never)
- let handle: HarnessHandle | null = null
-
- await actRender(
- <Harness
- onReady={h => (handle = h)}
- refreshSessions={async () => undefined}
- requestGateway={requestGateway}
- seedMessages={[
- { id: 'u1', role: 'user', parts: [textPart('a')] },
- { id: 'a1', role: 'assistant', parts: [textPart('b')] }
- ]}
- />
- )
-
- expect(await handle!.submitText('fresh enough')).toBe(true)
+ expect(await handle!.submitText('send from a window that missed a turn')).toBe(true)
expect(requestGateway).toHaveBeenCalledWith(
'prompt.submit',
- { session_id: RUNTIME_SESSION_ID, text: 'fresh enough' },
+ expect.objectContaining({ text: 'send from a window that missed a turn' }),
1_800_000
)
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)
})
- it('does not refuse when raw session rows are longer only because tools fold into chat messages', async () => {
- const remoteSessionMessages = [
- { content: 'check the repo', role: 'user' as const, timestamp: 1 },
- {
- content: 'Looking.',
- role: 'assistant' as const,
- timestamp: 2,
- tool_calls: [{ id: 'tc-1', function: { name: 'terminal', arguments: '{"command":"ls"}' } }]
- },
- {
- content: '{"output":"ok"}',
- role: 'tool' as const,
- tool_call_id: 'tc-1',
- tool_name: 'terminal',
- timestamp: 3
- },
- { content: 'Done.', role: 'assistant' as const, timestamp: 4 }
- ]
-
- const localChat = toChatMessages(remoteSessionMessages)
-
- expect(remoteSessionMessages.length).toBeGreaterThan(localChat.length)
- vi.mocked(getLatestSessionMessages).mockResolvedValue({
- session_id: RUNTIME_SESSION_ID,
- messages: remoteSessionMessages
- })
-
- const requestGateway = vi.fn(async () => ({}) as never)
- let handle: HarnessHandle | null = null
-
- await actRender(
- <Harness
- onReady={h => (handle = h)}
- refreshSessions={async () => undefined}
- requestGateway={requestGateway}
- seedMessages={localChat}
- />
- )
-
- expect(await handle!.submitText('follow-up after tools')).toBe(true)
- expect(requestGateway).toHaveBeenCalledWith(
- 'prompt.submit',
- { session_id: RUNTIME_SESSION_ID, text: 'follow-up after tools' },
- 1_800_000
- )
- })
-
- it('does not refuse when the authoritative transcript read fails', async () => {
- vi.mocked(getLatestSessionMessages).mockRejectedValue(new Error('wrong backend'))
-
- const requestGateway = vi.fn(async () => ({}) as never)
- let handle: HarnessHandle | null = null
-
- await actRender(
- <Harness
- onReady={h => (handle = h)}
- refreshSessions={async () => undefined}
- requestGateway={requestGateway}
- seedMessages={[{ id: 'u1', role: 'user', parts: [textPart('a')] }]}
- />
- )
-
- expect(await handle!.submitText('send anyway')).toBe(true)
- expect(requestGateway).toHaveBeenCalledWith(
- 'prompt.submit',
- { session_id: RUNTIME_SESSION_ID, text: 'send anyway' },
- 1_800_000
- )
- })
-
it('refuses a slash command sent alongside an attachment instead of silently degrading to a chat message (#81798)', async () => {
// The attachment's refText gets prepended ahead of the typed text by
// buildContextText, so the merged wire text no longer starts with "/".
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index f0bf0e40f42..3a579344e58 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -7,7 +7,6 @@ import { type ChatMessage, finalizeInterruptedMessages, textPart } from '@/lib/c
import { optimisticAttachmentRef } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import { setMutableRef } from '@/lib/mutable-ref'
-import { profileScopeForSessionOwner, transcriptRefreshIfBehind } from '@/lib/stale-transcript-guard'
import {
isVoicePlaybackActive,
markVoicePlaybackInterrupted,
@@ -36,13 +35,10 @@ import {
setMessages,
touchSessionActivity
} from '@/store/session'
+import { profileScopeForSessionOwner } from '@/store/session-request-router'
import { $sessionStates, $sessionTiles } from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
-import {
- profileScopeForTranscriptSession,
- resolveActiveTranscriptSession
-} from '../../../contrib/hooks/use-background-sync'
import { isCronRunSessionId, refreshCronRunWriteGate } from '../../../cron/open-cron-run'
import type { ClientSessionState } from '../../../types'
import { routeTargetFromToken, sessionContextDrift } from '../session-context-drift'
@@ -889,69 +885,6 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
rewriteOptimistic(liveSessionId, syncedAttachments)
const text = buildContextText(syncedAttachments)
- // Another Desktop window may own a newer transcript while this one
- // still shows an open-time snapshot. Refuse the send and refresh
- // rather than forking the session (#65047).
- const guardStoredId = targetStoredSessionId ?? selectedStoredSessionIdRef.current
-
- if (guardStoredId && liveSessionId) {
- const localSnapshot = updateSessionState(liveSessionId, state => state, targetStoredSessionId)
-
- const refresh = await transcriptRefreshIfBehind(guardStoredId, localSnapshot.messages, {
- excludeMessageId: optimisticId,
- profile: profileScopeForTranscriptSession(resolveActiveTranscriptSession(guardStoredId, liveSessionId))
- })
-
- if (sessionDriftReason()) {
- return abortForSessionSwitch(liveSessionId)
- }
-
- if (refresh) {
- if (refresh.competingView) {
- updateSessionState(
- liveSessionId,
- state => ({
- ...state,
- awaitingResponse: false,
- busy: false,
- messages: refresh.messages,
- pendingBranchGroup: null
- }),
- targetStoredSessionId
- )
-
- if (targetIsCurrentView()) {
- scope.setMessages(() => refresh.messages)
- notify({
- kind: 'warning',
- message: copy.staleSessionBody,
- title: copy.staleSessionTitle
- })
- }
-
- releaseBusy()
-
- return false
- }
-
- // The surplus was this window's own server-side turn residue — a turn
- // that died on an approval timeout leaves its tool/assistant rows
- // server-side while the window only holds its optimistic user message
- // (#124005). Graft the rows into the view silently and let the send
- // proceed: the local view being behind is the expected aftermath of the
- // turn's death, not evidence of a competing view.
- updateSessionState(
- liveSessionId,
- state => ({ ...state, messages: refresh.messages }),
- targetStoredSessionId
- )
-
- if (targetIsCurrentView()) {
- scope.setMessages(() => refresh.messages)
- }
- }
- }
-
const submitParams = (targetId: string) => ({
session_id: targetId,
text,
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index 27492d36a54..1d79a4d796a 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -222,10 +222,6 @@ function preserveStructuralParts(message: ChatMessage, previous: ChatMessage): C
// attachmentRefs — composer-side metadata; already reconciled in reconcileResumeMessages
// serverRowSpan — backend rows the folded message covers; the older-page offset
// accounting reads it, the transcript never paints it
-// systemNotice — hydration's provenance flag for a backend-authored notice
-// (a model switch, a process completion); the stale-transcript
-// compare reads it, while the visible system row is painted
-// from role + parts, and role is already COMPARED
//
// If your new field affects what the user sees in the transcript, add it to
// COMPARED. If it's metadata that shouldn't trigger a re-render, add it to
@@ -260,7 +256,7 @@ const COMPARED_FIELDS = [
'durationS'
] as const
-const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'serverRowSpan', 'systemNotice'] as const
+const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'serverRowSpan'] as const
// Compile-time check: every ChatMessagePart discriminant must be handled by
// chatPartsEquivalent. If @assistant-ui adds a new part type, this fails tsc.
diff --git a/apps/desktop/src/i18n/ar_chat.ts b/apps/desktop/src/i18n/ar_chat.ts
index 3a392ceba04..af7f5be8cfc 100644
--- a/apps/desktop/src/i18n/ar_chat.ts
+++ b/apps/desktop/src/i18n/ar_chat.ts
@@ -391,9 +391,6 @@ export const arChat = {
sessionUnavailable: 'الجلسة غير متاحة',
createSessionFailed: 'فشل إنشاء الجلسة',
promptFailed: 'فشل إرسال الرسالة',
- staleSessionTitle: 'المحادثة غير محدّثة',
- staleSessionBody:
- 'كانت هذه النافذة متأخرة عن عرض آخر لنفس المحادثة. تم تحميل أحدث الرسائل. أعد الإرسال إذا كنت لا تزال تريد ذلك.',
providerCredentialRequired: 'مطلوب اعتماد المزود',
emptySlashCommand: 'أمر slash فارغ',
slashCommandIgnoredTitle: 'لم يتم إرسال الأمر',
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 7c2da615130..5b9974ac767 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -6027,9 +6027,6 @@ export const deOverrides = {
sessionUnavailable: 'Session nicht verfügbar',
createSessionFailed: 'Neue Session konnte nicht erstellt werden',
promptFailed: 'Prompt fehlgeschlagen',
- staleSessionTitle: 'Chat veraltet',
- staleSessionBody:
- 'Dieses Fenster war hinter einer anderen Ansicht desselben Chats. Die neuesten Nachrichten wurden geladen. Senden Sie erneut, wenn Sie noch möchten.',
providerCredentialRequired:
'Fügen Sie Anmeldedaten für einen Anbieter hinzu, bevor Sie Ihre erste Nachricht senden.',
emptySlashCommand: 'leerer Slash-Befehl',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 4b712fb5d78..0ea0dd309f4 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -5504,9 +5504,6 @@ export const en: Translations = {
sessionUnavailable: 'Session unavailable',
createSessionFailed: 'Could not create a new session',
promptFailed: 'Prompt failed',
- staleSessionTitle: 'Chat out of date',
- staleSessionBody:
- 'This window was behind another view of the same chat. Latest messages were loaded. Send again if you still want to.',
providerCredentialRequired: 'Add a provider credential before sending your first message.',
emptySlashCommand: 'empty slash command',
slashCommandIgnoredTitle: 'Command not sent',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 0af7a1cdfc0..52820897243 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -6018,9 +6018,6 @@ export const esOverrides = {
sessionUnavailable: 'Sesión no disponible',
createSessionFailed: 'No se pudo crear una sesión nueva',
promptFailed: 'Falló el prompt',
- staleSessionTitle: 'Chat desactualizado',
- staleSessionBody:
- 'Esta ventana estaba detrás de otra vista del mismo chat. Se cargaron los mensajes más recientes. Envía de nuevo si aún quieres.',
providerCredentialRequired: 'Añade una credencial de proveedor antes de enviar tu primer mensaje.',
emptySlashCommand: 'comando slash vacío',
desktopCommands: 'Comandos de escritorio',
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index f07ad451190..f0e40f7d7d1 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -6040,9 +6040,6 @@ export const frOverrides = {
sessionUnavailable: 'Session indisponible',
createSessionFailed: 'Impossible de créer une nouvelle session',
promptFailed: "Échec de l'invite",
- staleSessionTitle: 'Conversation obsolète',
- staleSessionBody:
- 'Cette fenêtre était en retard sur une autre vue du même chat. Les derniers messages ont été chargés. Renvoyez si vous le souhaitez encore.',
providerCredentialRequired: "Ajoutez un identifiant de fournisseur avant d'envoyer votre premier message.",
emptySlashCommand: 'commande slash vide',
desktopCommands: 'Commandes Desktop',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index a7a180a3734..3790eb502c9 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -4094,9 +4094,6 @@ export const ja = defineLocale({
sessionUnavailable: 'セッションが利用できません',
createSessionFailed: '新しいセッションを作成できませんでした',
promptFailed: 'プロンプトに失敗しました',
- staleSessionTitle: 'チャットが最新ではありません',
- staleSessionBody:
- 'このウィンドウは同じチャットの別ビューより遅れています。最新のメッセージを読み込みました。送信する場合はもう一度送ってください。',
providerCredentialRequired: '最初のメッセージを送信する前にプロバイダー認証情報を追加してください。',
emptySlashCommand: '空のスラッシュコマンド',
slashCommandIgnoredTitle: 'コマンドが送信されませんでした',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index f225dcb6221..311ab4741c0 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -4211,9 +4211,6 @@ export const ru = defineLocale({
sessionUnavailable: 'Сеанс недоступен',
createSessionFailed: 'Не удалось создать новый сеанс',
promptFailed: 'Промпт не удался',
- staleSessionTitle: 'Чат устарел',
- staleSessionBody:
- 'Это окно отставало от другого вида того же чата. Загружены последние сообщения. Отправьте снова, если всё ещё хотите.',
providerCredentialRequired: 'Добавьте учётные данные провайдера перед отправкой первого сообщения.',
emptySlashCommand: 'пустая слэш-команда',
desktopCommands: 'Команды desktop',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index fc91cadffdf..3851fce23e3 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -4562,8 +4562,6 @@ export interface Translations {
sessionUnavailable: string
createSessionFailed: string
promptFailed: string
- staleSessionTitle: string
- staleSessionBody: string
providerCredentialRequired: string
emptySlashCommand: string
slashCommandIgnoredTitle: string
diff --git a/apps/desktop/src/i18n/zh-hant_chat.ts b/apps/desktop/src/i18n/zh-hant_chat.ts
index 3ad335170f7..467bdc7207c 100644
--- a/apps/desktop/src/i18n/zh-hant_chat.ts
+++ b/apps/desktop/src/i18n/zh-hant_chat.ts
@@ -414,8 +414,6 @@ export const zhHantChat = {
sessionUnavailable: '工作階段不可用',
createSessionFailed: '無法建立新工作階段',
promptFailed: '提示詞傳送失敗',
- staleSessionTitle: '對話已過期',
- staleSessionBody: '此視窗落後於同一對話的其他視窗。已載入最新訊息。若仍要傳送請再試一次。',
providerCredentialRequired: '傳送第一則訊息前請先新增提供方憑證。',
emptySlashCommand: '空的斜線指令',
slashCommandIgnoredTitle: '指令未傳送',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index cd3fe31addb..e0e708de334 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -5049,8 +5049,6 @@ export const zh = defineLocale({
sessionUnavailable: '会话不可用',
createSessionFailed: '无法创建新会话',
promptFailed: '提示词发送失败',
- staleSessionTitle: '对话已过期',
- staleSessionBody: '此窗口落后于同一对话的其他窗口。已加载最新消息。若仍要发送请再试一次。',
providerCredentialRequired: '发送第一条消息前请先添加提供方凭据。',
emptySlashCommand: '空 slash 命令',
slashCommandIgnoredTitle: '命令未发送',
diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.ts
index 09b3ed933ef..f04de45b2af 100644
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@ -158,8 +158,7 @@ function transcriptContent(
/**
* Backend-authored transcript notices. The gateway persists these itself and no
- * view "sent" them, so they render as system rows but are not authored
- * transcript content (see `ChatMessage.systemNotice`).
+ * view "sent" them, so they render as system rows.
*/
const NOTICE_DISPLAY_KINDS = [
'model_switch',
@@ -605,7 +604,6 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
? { asyncResult: asyncResultBody(displayContentForMessage(message.role, message.content || content)) }
: {}),
...(message.display_kind === 'process_complete' ? { asyncResultKind: 'process' as const } : {}),
- ...(isMachineNotice(message.display_kind) ? { systemNotice: true } : {}),
timestamp: earliestTimestamp(message.timestamp, ...parts.map(part => part.timestamp)),
...(rowId !== undefined ? { rowId } : {}),
...(pendingAbsorbedRows > 0 ? { serverRowSpan: pendingAbsorbedRows + 1 } : {}),
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index a50858d2bf9..011a8de5150 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -73,13 +73,6 @@ export type ChatMessage = {
serverRowSpan?: number
/** Emoji reactions on this message — one per author (see MessageReaction). */
reactions?: MessageReaction[]
- /** Backend-authored transcript notice rather than a message any view sent: a
- * model switch, an auto-continue, a background-process completion. It renders
- * on the timeline like any other system row but belongs to no view, so the
- * stale-transcript compare must not count it (see
- * `messagesIfTranscriptBehind`) — counting it made one model switch report a
- * second window ahead and refuse every send. */
- systemNotice?: boolean
}
export type GatewayEventPayload = {
diff --git a/apps/desktop/src/lib/stale-transcript-guard.test.ts b/apps/desktop/src/lib/stale-transcript-guard.test.ts
deleted file mode 100644
index 670c5bb5491..00000000000
--- a/apps/desktop/src/lib/stale-transcript-guard.test.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import type { ChatMessage } from '@/lib/chat-messages'
-import type { SessionMessage } from '@/types/hermes'
-
-import { toChatMessages } from './chat-messages'
-import { messagesIfTranscriptBehind, surplusIsCompetingView } from './stale-transcript-guard'
-
-/**
- * The guard refuses a send when the authoritative latest page holds MORE
- * transcript than the window does, rather than forking the session (#65047).
- * It measures that difference with `remoteChat.length > localMessages.length`
- * after `toChatMessages`.
- *
- * A backend-authored NOTICE also arrives as a `ChatMessage` (`model changed`,
- * `background agent work finished`): `tui_gateway/server.py` persists
- * `display_kind=model_switch` with `role=user` on an in-place model switch, and
- * hydration renders it as a system row. Nothing about it means another window
- * exists — but it inflates the page by one message per event, so the guard
- * reported "This window was behind another view of the same chat" to a user who
- * had only switched models, refused the send, and said the same thing on every
- * retry. Staleness must be measured in AUTHORED content, not array length.
- */
-
-const row = (over: Partial<SessionMessage> & Pick<SessionMessage, 'role'>): SessionMessage => ({
- content: '',
- timestamp: 1_700_000_000,
- ...over
-})
-
-const userTurn = (id: number, text: string): SessionMessage =>
- row({ content: text, id, role: 'user', timestamp: 1_700_000_000 + id })
-
-const assistantTurn = (id: number, text: string): SessionMessage =>
- row({ content: text, id, role: 'assistant', timestamp: 1_700_000_000 + id })
-
-/** What an in-place model switch persists, exactly as the gateway writes it. */
-const modelSwitchNotice = (id: number): SessionMessage =>
- row({
- content: 'switched to another model',
- display_kind: 'model_switch',
- id,
- role: 'user',
- timestamp: 1_700_000_000 + id
- })
-
-describe('messagesIfTranscriptBehind', () => {
- it('does not treat a backend-authored notice as another view being ahead', () => {
- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])
- const page = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer'), modelSwitchNotice(3)])
-
- // The notice is a real message in the page: this is what skews a length compare.
- expect(page).toHaveLength(3)
- expect(page.map(message => message.role)).toEqual(['user', 'assistant', 'system'])
-
- expect(messagesIfTranscriptBehind(windowMessages, page)).toBeNull()
- })
-
- it('still refuses when another view advanced the chat with a real turn', () => {
- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])
-
- const page = toChatMessages([
- userTurn(1, 'ask'),
- assistantTurn(2, 'answer'),
- userTurn(4, 'sent from another window')
- ])
-
- expect(messagesIfTranscriptBehind(windowMessages, page)).not.toBeNull()
- })
-
- it('still refuses when a notice arrives alongside a reply this window never saw', () => {
- const windowMessages = toChatMessages([userTurn(1, 'ask'), assistantTurn(2, 'answer')])
-
- const page = toChatMessages([
- userTurn(1, 'ask'),
- assistantTurn(2, 'answer'),
- modelSwitchNotice(3),
- assistantTurn(4, 'a reply this window never rendered')
- ])
-
- expect(messagesIfTranscriptBehind(windowMessages, page)).not.toBeNull()
- })
-
- it('is current when both sides hold the same notices and the same turns', () => {
- const rows = [userTurn(1, 'ask'), assistantTurn(2, 'answer'), modelSwitchNotice(3)]
-
- expect(messagesIfTranscriptBehind(toChatMessages(rows), toChatMessages(rows))).toBeNull()
- })
-
- it('is current when the page is empty, and refreshes a window that holds nothing', () => {
- const rows = [userTurn(1, 'ask'), assistantTurn(2, 'answer')]
-
- expect(messagesIfTranscriptBehind(toChatMessages(rows), [])).toBeNull()
- expect(messagesIfTranscriptBehind([], toChatMessages(rows))).toEqual(toChatMessages(rows))
- })
-
- // #125975: a tool-using turn folds into one bubble, and the two paths that
- // build it bind different ends of the span. Live settle stamps the turn's
- // FINAL row (withPersistedIdentity → rowId + the last text part's
- // sourceRowId); hydration keeps the folded bubble's FIRST row and stamps
- // every text part with its own sourceRowId. When the latest page starts
- // mid-turn, its first durable row is one the window's settled bubble never
- // carried — so a rowId-only tip compare misses, the graft appends, and the
- // count reports "behind": the first send after a tool-using turn bounces
- // with "Chat out of date" in a single window. The tip must read the highest
- // durable address the bubble carries (rowId or any text part's sourceRowId).
- it('matches tips when the live-settled bubble binds the final row and the page starts mid-turn', () => {
- const text = (rowId: number, body: string) => ({ sourceRowId: rowId, text: body, type: 'text' as const })
- const streamed = (body: string) => ({ text: body, type: 'text' as const })
- const tool = () => ({ toolCallId: 'call-1', toolName: 'shell', type: 'tool-call' as const })
-
- // The window settled both tool turns live: each folded bubble is addressed
- // by its FINAL row (withPersistedIdentity), and only the final text part
- // carries a durable sourceRowId — the streamed pre-tool text has none.
- const localWindow: ChatMessage[] = [
- { id: 'u1', parts: [streamed('ask')], role: 'user', rowId: 1 },
- {
- id: 'a-fold1-live',
- parts: [streamed('checking'), tool(), text(5, 'final one')],
- role: 'assistant',
- rowId: 5
- },
- { id: 'u3', parts: [streamed('run the tests')], role: 'user', rowId: 6 },
- {
- id: 'a-fold2-live',
- parts: [streamed('verifying'), tool(), text(10, 'final two')],
- role: 'assistant',
- rowId: 10
- }
- ]
-
- // The refreshed latest page starts INSIDE the first folded turn: hydration
- // addresses each folded bubble by its FIRST row (3, 8), the final rows
- // surviving only as text-part sourceRowIds. The window's settled bubbles
- // never carried rows 3 or 8, so a rowId-only tip compare sees 10 vs 8,
- // the graft finds no anchor, and the merge reports the window behind —
- // the first send after a tool-using turn bounces with "Chat out of date"
- // in a single window (#125975).
- const latestPage: ChatMessage[] = [
- {
- id: 'a-fold1-page',
- parts: [text(3, 'checking'), tool(), text(5, 'final one')],
- role: 'assistant',
- rowId: 3
- },
- { id: 'u3', parts: [streamed('run the tests')], role: 'user', rowId: 6 },
- {
- id: 'a-fold2-page',
- parts: [text(8, 'verifying'), tool(), text(10, 'final two')],
- role: 'assistant',
- rowId: 8
- }
- ]
-
- expect(messagesIfTranscriptBehind(localWindow, latestPage)).toBeNull()
- })
-})
-
-function competingViewUserMessage(id: string, text: string, rowId?: number): ChatMessage {
- return {
- id,
- role: 'user',
- parts: [{ type: 'text', text }],
- ...(rowId !== undefined && { rowId })
- }
-}
-
-function competingViewAssistantMessage(id: string, text: string, rowId?: number): ChatMessage {
- return {
- id,
- role: 'assistant',
- parts: [{ type: 'text', text }],
- ...(rowId !== undefined && { rowId })
- }
-}
-
-describe('surplusIsCompetingView', () => {
- // #124005: a turn that died on an approval timeout leaves its user row plus
- // tool/assistant residue server-side under durable ids the window never saw —
- // the window holds only its optimistic copy under a local id with no rowId.
- // That residue is this window's own turn aftermath, not a competing view.
- it('turn-death residue with an unreconciled optimistic user row is not a competing view', () => {
- const local = [competingViewUserMessage('opt-old', 'deploy the schema')]
-
- const refreshed = [
- competingViewUserMessage('msg-10', 'deploy the schema', 10),
- competingViewAssistantMessage('msg-11', '⌛ Approval timed out after 5 minutes', 11)
- ]
-
- expect(surplusIsCompetingView(local, refreshed, { optimisticMessageId: 'opt-old' })).toBe(false)
- })
-
- it('a plain completed tool turn single-window surplus is not a competing view', () => {
- // Issue comment 2: a successful plain tool turn reproduces the refusal
- // single-window — the server folded rows this window never streamed back.
- const local = [competingViewUserMessage('opt-old', 'run the tests')]
-
- const refreshed = [
- competingViewUserMessage('msg-10', 'run the tests', 10),
- competingViewAssistantMessage('msg-11', 'checking', 11),
- competingViewAssistantMessage('msg-12', 'all green', 12)
- ]
-
- expect(surplusIsCompetingView(local, refreshed, { optimisticMessageId: 'opt-old' })).toBe(false)
- })
-
- it('rejects a repeated prompt from another view even when the text matches', () => {
- const local = [competingViewUserMessage('prior', 'run the tests')]
-
- const refreshed = [
- competingViewUserMessage('prior', 'run the tests', 10),
- competingViewUserMessage('peer', 'run the tests', 12)
- ]
-
- expect(surplusIsCompetingView(local, refreshed)).toBe(true)
- })
-
- it('a user row with unknown text is a competing view', () => {
- const local = [competingViewUserMessage('opt-old', 'deploy the schema')]
-
- const refreshed = [
- competingViewUserMessage('msg-10', 'deploy the schema', 10),
- competingViewUserMessage('msg-12', 'typed in another window'),
- competingViewAssistantMessage('msg-13', 'ok', 13)
- ]
-
- expect(surplusIsCompetingView(local, refreshed)).toBe(true)
- })
-
- it('user rows matching by rowId or id are known', () => {
- const byRowId = [competingViewUserMessage('msg-10', 'deploy the schema', 10)]
- expect(
- surplusIsCompetingView(byRowId, [
- competingViewUserMessage('msg-10', 'deploy the schema', 10),
- competingViewAssistantMessage('msg-11', 'done', 11)
- ])
- ).toBe(false)
-
- const byId = [competingViewUserMessage('msg-10', 'deploy the schema')]
- expect(
- surplusIsCompetingView(byId, [
- competingViewUserMessage('msg-10', 'deploy the schema'),
- competingViewAssistantMessage('msg-11', 'done')
- ])
- ).toBe(false)
- })
-
- it('assistant/tool-only surplus is never a competing view', () => {
- const local = [competingViewUserMessage('opt-old', 'deploy the schema')]
-
- const refreshed = [
- competingViewUserMessage('msg-10', 'deploy the schema', 10),
- competingViewAssistantMessage('msg-11', 'running the command', 11),
- competingViewAssistantMessage('msg-12', '⌛ Approval timed out', 12)
- ]
-
- expect(surplusIsCompetingView(local, refreshed, { optimisticMessageId: 'opt-old' })).toBe(false)
- })
-})
diff --git a/apps/desktop/src/lib/stale-transcript-guard.ts b/apps/desktop/src/lib/stale-transcript-guard.ts
deleted file mode 100644
index 05ca6212e5d..00000000000
--- a/apps/desktop/src/lib/stale-transcript-guard.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'
-import { getLatestSessionMessages, type ProfileScope } from '@/hermes'
-import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
-import { knownSessionOwner, ownerLookupSessionRows } from '@/store/session'
-import type { SessionOwnerScope } from '@/store/session-request-router'
-
-/** REST scope for a session owner. Undefined when the owner is unknown. */
-export function profileScopeForSessionOwner(owner: SessionOwnerScope): ProfileScope {
- if (!owner) {
- return undefined
- }
-
- if (typeof owner === 'string') {
- return owner
- }
-
- return {
- connectionId: owner.connectionId,
- profile: owner.targetProfile ?? owner.profile
- }
-}
-
-export interface TranscriptRefresh {
- messages: ChatMessage[]
- /**
- * The refreshed surplus carries a user row this window never streamed: another
- * view of the same chat is ahead, and the pre-send guard must refuse (fork
- * risk). False when the surplus is this window's own server-side residue — a
- * turn that died on an approval timeout leaves its tool/assistant rows
- * server-side while the window only holds its optimistic user message, whose
- * id/rowId never reconciled. Graft silently and let the send proceed (#124005).
- */
- competingView: boolean
-}
-
-/**
- * Whether the refreshed transcript carries a user row this window does not know.
- * Durable ids and row ids are authoritative. The only text match allowed is the
- * current optimistic prompt identified by `optimisticMessageId`; matching all
- * user text would mistake a repeated prompt from another window for this
- * window's own turn. Assistant/tool-only surplus rows are this window's own
- * turn residue (#124005).
- */
-export function surplusIsCompetingView(
- localMessages: ChatMessage[],
- refreshed: ChatMessage[],
- options?: { optimisticMessageId?: string }
-): boolean {
- const localUsers = localMessages.filter(message => message.role === 'user')
- const matchedLocalUsers = new Set<number>()
-
- return refreshed.some(message => {
- if (message.role !== 'user') {
- return false
- }
-
- const matchIndex = localUsers.findIndex(
- (local, index) =>
- !matchedLocalUsers.has(index) &&
- (local.id === message.id ||
- (message.rowId !== undefined && local.rowId === message.rowId) ||
- (local.id === options?.optimisticMessageId &&
- local.rowId === undefined &&
- chatMessageText(local) === chatMessageText(message)))
- )
-
- if (matchIndex < 0) {
- return true
- }
-
- matchedLocalUsers.add(matchIndex)
-
- return false
- })
-}
-
-/**
- * Transcript content a view actually authored. Backend-written notices
- * (`ChatMessage.systemNotice`) render on the timeline but belong to no view, so
- * counting them reports a second window that does not exist: an in-place model
- * switch alone refused every send with "this window was behind another view of
- * the same chat".
- */
-function authoredMessageCount(messages: ChatMessage[]): number {
- return messages.reduce((count, message) => (message.systemNotice ? count : count + 1), 0)
-}
-
-/**
- * Highest durable row address a bubble carries: its own `rowId` plus any text
- * part's `sourceRowId`. A folded tool-turn bubble spans many stored rows, and
- * the two paths that build it bind different ends — live settle stamps the
- * turn's final row (use-message-stream's withPersistedIdentity) while
- * hydration keeps the folded bubble's first row — so the tip must read every
- * address the bubble owns (#125975).
- */
-function bubbleTipRowId(message: ChatMessage): number | undefined {
- let tip = message.rowId
-
- for (const part of message.parts) {
- if (part.type === 'text' && typeof part.sourceRowId === 'number') {
- tip = tip === undefined ? part.sourceRowId : Math.max(tip, part.sourceRowId)
- }
- }
-
- return tip
-}
-
-/**
- * Latest persisted backend row the view carries. Retention only ever releases
- * the head (rows older than the window plus its budget — see
- * app/chat/transcript-retention.ts), so the last durable row is always the
- * live tail; unpersisted rows (optimistic prompts, live streams) sit past it.
- */
-function lastDurableRowId(messages: readonly ChatMessage[]): number | undefined {
- for (let index = messages.length - 1; index >= 0; index -= 1) {
- const rowId = bubbleTipRowId(messages[index])
-
- if (typeof rowId === 'number') {
- return rowId
- }
- }
-
- return undefined
-}
-
-/**
- * Chat messages to install when the authoritative latest page is ahead of the
- * local view. Null when the local view is current.
- *
- * Tips are compared before counts: a view ending on the page's own last
- * durable row is current however much head retention has paged out — counts
- * never converge there (#123909), while a peer window's newer row still
- * changes the tip. Authored content is compared after `toChatMessages`, so
- * tool rows folded into an assistant bubble are not "ahead", and neither is a
- * backend-authored notice. A backfilled prefix is kept when the refreshed tail
- * anchors inside it. Live stream ids that do not anchor still use the count,
- * so the window that just finished the turn is not blocked when the counts
- * match.
- */
-export function messagesIfTranscriptBehind(
- localMessages: ChatMessage[],
- remoteChat: ChatMessage[]
-): ChatMessage[] | null {
- if (remoteChat.length === 0) {
- return null
- }
-
- if (localMessages.length === 0) {
- return remoteChat
- }
-
- const localTip = lastDurableRowId(localMessages)
- const remoteTip = lastDurableRowId(remoteChat)
-
- if (localTip !== undefined && localTip === remoteTip) {
- return null
- }
-
- const grafted = graftRefreshedTailOntoBackfill(remoteChat, localMessages)
- const localAuthored = authoredMessageCount(localMessages)
-
- if (grafted === remoteChat) {
- return authoredMessageCount(remoteChat) > localAuthored ? remoteChat : null
- }
-
- return authoredMessageCount(grafted) > localAuthored ? grafted : null
-}
-
-async function fetchRefreshedTranscript(
- storedSessionId: string,
- localMessages: ChatMessage[],
- options?: { excludeMessageId?: string; profile?: ProfileScope }
-): Promise<ChatMessage[] | null> {
- const baseline = options?.excludeMessageId
- ? localMessages.filter(message => message.id !== options.excludeMessageId)
- : localMessages
-
- const profile =
- options && 'profile' in options
- ? options.profile
- : profileScopeForSessionOwner(knownSessionOwner(ownerLookupSessionRows(), storedSessionId))
-
- try {
- const remote = await getLatestSessionMessages(storedSessionId, profile)
- const refreshed = messagesIfTranscriptBehind(baseline, toChatMessages(remote.messages))
-
- if (!refreshed) {
- return null
- }
-
- return preserveLocalAssistantErrors(refreshed, baseline)
- } catch {
- return null
- }
-}
-
-/**
- * Read the authoritative latest page; when this view is behind, return the
- * refreshed transcript plus whether the surplus is a competing view's message.
- * Null when current or the read fails — a missing profile or a down backend
- * must not soft-lock send. The pre-send guard refuses only a competing view; this window's own server-side
- * turn residue (a turn that died on an approval timeout) is grafted silently
- * and the send proceeds (#124005).
- */
-export async function transcriptRefreshIfBehind(
- storedSessionId: string,
- localMessages: ChatMessage[],
- options?: { excludeMessageId?: string; profile?: ProfileScope }
-): Promise<TranscriptRefresh | null> {
- const messages = await fetchRefreshedTranscript(storedSessionId, localMessages, options)
-
- if (!messages) {
- return null
- }
-
- return {
- messages,
- competingView: surplusIsCompetingView(localMessages, messages, {
- optimisticMessageId: options?.excludeMessageId
- })
- }
-}
diff --git a/apps/desktop/src/store/session-request-router.ts b/apps/desktop/src/store/session-request-router.ts
index 943ed192e74..f41c4b8633e 100644
--- a/apps/desktop/src/store/session-request-router.ts
+++ b/apps/desktop/src/store/session-request-router.ts
@@ -1,3 +1,4 @@
+import type { ProfileScope } from '@/hermes'
import { requestGatewayForAgent, requestGatewayForProfile, retainGatewayForSessionTurn } from '@/store/gateway'
import { resetBackgroundPollingGuardAfterRebind } from './session-gone-latch'
@@ -28,6 +29,22 @@ export type SessionProfileRoute = SessionOwnerRoute
export type SessionOwnerScope = undefined | null | string | SessionOwnerRoute
+/** REST scope for a session owner. Undefined when the owner is unknown. */
+export function profileScopeForSessionOwner(owner: SessionOwnerScope): ProfileScope {
+ if (!owner) {
+ return undefined
+ }
+
+ if (typeof owner === 'string') {
+ return owner
+ }
+
+ return {
+ connectionId: owner.connectionId,
+ profile: owner.targetProfile ?? owner.profile
+ }
+}
+
/** Exact owner reconstructed from a CONNECTION-TAGGED session row (the
* Electron unified-list splice tags foreign registry rows; an optimistic row
* carries the create route's connection; mergeSessionPage carries the tag
diff --git a/apps/desktop/src/store/transcript-sync.ts b/apps/desktop/src/store/transcript-sync.ts
index 8da76770a1a..ca6f6299e9f 100644
--- a/apps/desktop/src/store/transcript-sync.ts
+++ b/apps/desktop/src/store/transcript-sync.ts
@@ -1,8 +1,9 @@
// Cross-window transcript freshness. Each desktop window owns its own gateway
// transport for a session, so a turn that completes in window A never streams
// into window B. This bus pings peers with the stored session id so a window
-// viewing that chat can re-pull history before the user sends into an
-// out-of-date context. Distinct from hermes:sessions (sidebar list).
+// viewing that chat re-pulls history and stays current. Sends never wait on it:
+// the backend folds other surfaces' rows into the model's context itself.
+// Distinct from hermes:sessions (sidebar list).
export type TranscriptChangedPayload = {
/** Stored session id shared across Desktop windows. */