Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/system-specs/modules/history.md
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,15 @@ again. `switchSlot` likewise drops the cached
trailing reply when it has no row identity, the page reports the slot idle, no chunk
arrived during the fetch, and the page already answers the prompt that reply belongs
to (`pageAnswersLocalPrompt`): re-attached, that frozen partial would sit under the
finished reply.
finished reply. A page is read at one instant, so `switchSlot` also keeps the server
rows (a finalized segment, a tool row, a card) that a live frame added to the view
after the switch began and the page does not carry, ahead of the trailing reply; a
row the view already held when the switch began is left to the page. The page rebuilds
a JSON-`cls` row's meta from that `cls` and so drops its `meta.mid`; such a row is kept
only when it is a stop card the page does not hold by `meta.id` (inject rows keep their
`mid`), and any other one is left to the page. An idle page
that lacks such a row was read before the turn that wrote it, so the chat keeps the
run state that turn set.

**A failed open keeps what the pane showed.** When `switchSlot`'s read fails with
anything but a 404, the chat stays selected (`slotOpenFailed`) and the rows already
Expand Down
80 changes: 71 additions & 9 deletions website/src/store/chat/slotSwitch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createAction, createAsyncThunk, type ActionReducerMapBuilder } from '@r
import type { RootState } from '../index'
import type { ChatMessage } from '../../types'
import { emitSlotRead, newerTs, newestServerRowTs } from '../../lib/slotReadRelay'
import { isStopEvent } from '../../lib/stopEvent'
import { devLog, inspectorOn } from '../../dev/scrollInspector'
import { armConfirmedCloseHold, markSlotRead, confirmOrphanUnread, removeSlotOptimistic } from '../dashboardSlice'
import { slotLastTsOf } from '../slotLastTs'
Expand All @@ -19,7 +20,7 @@ import { chatSlotDetailPath } from '../../api/chatSlotPaths'
import { asFrontRead } from '../../api/readGate'
import type { ChatState } from './state'
import { fetchSlotDetail, isUnsafeKey, safeKey } from './wire'
import { deduplicateByMid, finalizePageStreaming, floorForGen, olderHeadAbovePage, pageAnswersLocalPrompt, pageRegressesSupersededSteer, rowIdentities, preserveSettledMcpOauth, preserveSettledStopState, preserveSettledUpsertRows, queueAfterSupersededDrain, raiseChunkSeq, sameTranscript, serverRowCount, snapshotChunkGen, snapshotChunkSeq, tailNotInPage } from './transcript'
import { deduplicateByMid, finalizePageStreaming, floorForGen, isDurableRow, olderHeadAbovePage, pageAnswersLocalPrompt, pageRegressesSupersededSteer, rowIdentities, preserveSettledMcpOauth, preserveSettledStopState, preserveSettledUpsertRows, queueAfterSupersededDrain, raiseChunkSeq, sameTranscript, serverRowCount, snapshotChunkGen, snapshotChunkSeq, tailNotInPage } from './transcript'
import { abortActiveOlderFetch, pagingCursorAfterKeptHead, slotCoverageShortfall, slotSwitchFetchLimit } from './paging'
import { mergePreservedThinking, reinsertThinkingOrphans, type ThinkingAnchor } from './thinking'
import { keepPendingCoordinatorApprovals } from './coordinatorApprovals'
Expand Down Expand Up @@ -205,8 +206,53 @@ function slotNoticeName(state: RootState, key: string): string | undefined {
return slot ? sessionDisplayTitle(slot) : undefined
}

/** Rows that reached the view by a live frame while a switch's page was in flight:
* server rows (`meta.mid`) whose identity the view did not hold when the switch
* began (`idsAtDispatch`), that the page does not carry, in view order. A page is
* read at one instant, so a segment or tool row the gateway pushed after that read
* is in the view and not on the page; replacing the view with the page alone drops
* it until the turn's end refresh. User rows are left to `liveSends`, and a row the
* view held at dispatch is left out, so a row the server since dropped cannot ride
* along. As in `liveSendsSince`, only rows below the last row that was on screen at
* dispatch qualify: a live frame lands at the bottom, and older rows another read
* wrote into the view meanwhile sit above that row. */
function rowsLandedDuringFetch(
view: readonly ChatMessage[], idsAtDispatch: readonly string[] | undefined, page: readonly ChatMessage[],
): ChatMessage[] {
if (!idsAtDispatch) return []
const before = new Set(idsAtDispatch)
let from = view.length
// A queued bubble is not that row: it sits below the reply a segment finalizes.
while (from > 0 && (view[from - 1].role === 'queued' || !rowIdentities(view[from - 1]).some(id => before.has(id)))) from -= 1
const pageStops = new Set(page.map(stopEventId).filter(Boolean))
return tailNotInPage(
view.slice(from).filter(m => isDurableRow(m) && m.role !== 'user'
&& typeof m.meta?.mid === 'string' && m.meta.mid && !before.has(`mid:${m.meta.mid}`)
&& carriesOverPage(m, pageStops)),
page as ChatMessage[],
)
}

/** The backend's upsert key of a stop card (`meta.id`), which its page copy keeps. */
function stopEventId(m: ChatMessage): string | undefined {
const id = isStopEvent(m) ? (m.meta as { id?: unknown } | undefined)?.id : undefined
return typeof id === 'string' && id ? id : undefined
}

/** Whether a live row may be kept beside the page, which must be able to show whether
* it already holds that row. The page rebuilds the meta of a row with a JSON `cls` from
* that `cls` alone, keeping `meta.mid` only on permission, elicitation and inject rows
* (`chat_utils_display`), so `tailNotInPage` cannot match such a row. A stop card is
* matched by its `meta.id` instead; any other such row is left to the page, which
* shows it once the turn ends. */
function carriesOverPage(m: ChatMessage, pageStops: ReadonlySet<string | undefined>): boolean {
if (m.role === 'inject' || !(m.cls ?? '').trimStart().startsWith('{')) return true
const stop = stopEventId(m)
return !!stop && !pageStops.has(stop)
}

export const switchSlot = createAsyncThunk<
Awaited<ReturnType<typeof fetchSlotDetail>>,
Awaited<ReturnType<typeof fetchSlotDetail>> & { idsAtDispatch?: string[] },
SwitchSlotArg,
{ rejectValue: StatusRejection }
>(
Expand Down Expand Up @@ -259,6 +305,8 @@ export const switchSlot = createAsyncThunk<
const state = (getState() as { chat: ChatState }).chat
const cachedRows = state.slotMessages?.[safeKey(key)] ?? []
const cached = cachedRows.length
// The view as `pending` left it: what a live frame can add to is judged against this.
const idsAtDispatch = state.messages.flatMap(rowIdentities)
const limit = slotSwitchFetchLimit({ cached })
// Inside `asFrontRead`: the person is waiting on this page, so it takes the
// next free place among the reads (api/readGate).
Expand Down Expand Up @@ -291,10 +339,10 @@ export const switchSlot = createAsyncThunk<
// atomically before this thunk body runs, so a superseded request
// observes someone else's key here.
if ((getState() as { chat: ChatState }).chat.activeSlot === key) emitSlotRead(key, newerTs(_newestSlotTs(), newestServerRowTs(walked.messages)))
return { ...walked, comparableTotal: first.total }
return { ...walked, comparableTotal: first.total, idsAtDispatch }
}
if ((getState() as { chat: ChatState }).chat.activeSlot === key) emitSlotRead(key, newerTs(_newestSlotTs(), newestServerRowTs(first.messages)))
return first
return { ...first, idsAtDispatch }
} catch (e) {
// A thrown error crosses the thunk boundary as `miniSerializeError(e)`,
// which keeps string fields only -- `ApiError.status` (a number) never
Expand Down Expand Up @@ -669,6 +717,16 @@ export function addSlotSwitchCases(builder: ActionReducerMapBuilder<ChatState>):
existing.slice(liveFrom).filter(m => m.role === 'user' && typeof m.meta?.sendId === 'string' && m.meta.sendId),
preserved,
)
// The segment, tool and card rows a live frame added after the page was read.
// They sit with the sends, in view order, ahead of the trailing reply, which
// the branches below re-attach themselves.
const liveRows = rowsLandedDuringFetch(existing, action.payload.idsAtDispatch, preserved)
.filter(m => m !== lastLocal || m.role !== 'assistant')
// shortcut: a queued bubble or stop card that lands below the live reply during the fetch makes
// it not the trailing row, so the chunks it took during the fetch are not kept.
// Finding the reply above the queue instead must not re-attach a stale partial
// from an earlier turn in any re-attach branch below.
const liveTail = liveRows.length ? existing.filter(m => liveSends.includes(m) || liveRows.includes(m)) : liveSends
// A page streaming row at or past the replay floor already folds every
// chunk this tab applied. The tab's own trailing streaming row can hold
// less: an open with no cached copy starts it at the first chunk after
Expand Down Expand Up @@ -708,7 +766,7 @@ export function addSlotSwitchCases(builder: ActionReducerMapBuilder<ChatState>):
&& lastLocal.content.length > 0
) {
// WS chunks arrived during fetch — use fetched history + local streaming
next = [...preserved.filter(m => m.role !== 'streaming'), ...liveSends, lastLocal]
next = [...preserved.filter(m => m.role !== 'streaming'), ...liveTail, lastLocal]
} else if (
lastLocal
&& (lastLocal.role === 'assistant' || lastLocal.role === 'streaming')
Expand Down Expand Up @@ -737,9 +795,11 @@ export function addSlotSwitchCases(builder: ActionReducerMapBuilder<ChatState>):
const finalized: ChatMessage = (lastLocal.role === 'streaming' && !running)
? { ...lastLocal, role: 'assistant' }
: lastLocal
next = [...preserved.filter(m => m.role !== 'streaming'), ...liveSends, finalized]
next = [...preserved.filter(m => m.role !== 'streaming'), ...liveTail, finalized]
} else {
next = liveSends.length ? [...preserved, ...liveSends] : preserved
// A live segment finalizes the text the page still folds into its streaming row.
const base = liveRows.some(m => m.role === 'assistant') ? preserved.filter(m => m.role !== 'streaming') : preserved
next = liveTail.length ? [...base, ...liveTail] : preserved
}
// None of the ended turn's live segments may stay the append target for
// the next turn. Finalized after the merge, not before it: a fetched
Expand Down Expand Up @@ -772,14 +832,16 @@ export function addSlotSwitchCases(builder: ActionReducerMapBuilder<ChatState>):
// composer swapped its placeholder for the interrupted-turn one while
// the reply was on its way. Keep the local run state the send (or a
// live `slots` frame) established; a page that caught the send, or
// one that reports running, is current and lands as before.
// one that reports running, is current and lands as before. A server
// row a live frame added (`liveRows`) proves the same: the idle page
// was read before the turn that wrote it.
//
// The active slot's server snapshot flipping to running is a turn
// start (see `ChatState.runEpoch`), as it is in
// syncSlotRunningFromServer; the hand-back in `enterActiveSlot` reads
// the epoch to tell a turn that ran on screen from a slot that saw
// nothing.
const pagePredatesLiveSend = !running && liveSends.length > 0
const pagePredatesLiveSend = !running && (liveSends.length > 0 || liveRows.length > 0)
if (!pagePredatesLiveSend) {
state.slotState = running ? 'streaming' : 'idle'
if (running && !state.slotRunning) bumpRunEpoch(state, key)
Expand Down
Loading
Loading