Files
archived-orca/src/shared/structured-agent-session-reducer.ts
T
Brennan Benson a4c11f1889 fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows (#20581)
* fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows

A structured chat pane could latch "Working for N" forever after the agent had
finished, showing the send arrow rather than Stop, while the sidebar and
`worktree ps` correctly read idle.

The client replica has one position (`state.cursor`) and one body. Two
operations keep those consistent: replace (both from one host snapshot) and
append (rows contiguous with the cursor). The `tail-page` branch was a third
thing: it took the cursor from the journal head, the items from a bounded page
(200 items, byte-capped), then merged retained client submissions over the
page's. Under continuous journal writes the client is always slightly behind,
so the branch ran on every window focus and on every pane re-activation. When
more than a page of rows had landed since a send, that send's user item fell
off the page, its submission was not carried, the retained `pending` survived,
and the cursor jumped past the dispatch-acceptance row. Nothing re-sends it: a
batch carries only touched items and that submission is never touched again.

Delete the third operation rather than guard it. A live subscription is now the
only thing that moves the cursor, and `subscribe({ cursor })` already replays
exactly the missed rows.

- remove the window `focus` listener and the owner/transport `refresh` contract
- skip warm hydration: a retained owner subscribes at its applied cursor
- cold hydration keeps its history read, applied as the existing `snapshot`
  (replace) event rather than `tail-page`
- delete the `tail-page` action and its reducer branch
- delete `resumeCursor` and `shouldAdvanceStructuredResumeCursor`; two cursors
  with two advancement rules were how position and body drifted apart

`older-page`/`loadOlder`, the unattached-refusal grace, generation guards and
the coalescer are unchanged. No host, wire or schema change.

Also fixes a second cost of the same branch: focus during a busy turn discarded
paged-in older items, shrinking the transcript to one bounded page mid-turn.

* fix(native-chat): preserve unavailable mixed-version session fences
2026-09-14 10:28:16 -07:00

272 lines
9.7 KiB
TypeScript

import type {
AgentJournalCursor,
AgentJournalRenderItem,
AgentJournalSubmission
} from './agent-session-journal-types'
import type {
AgentSessionBackgroundTaskState,
AgentSessionSlashCommand,
AgentSessionHandoffStatus,
AgentSessionHistoryPage,
AgentSessionSubscribeEvent,
AgentSessionTurnActivity
} from './agent-session-wire'
import { backgroundTaskStatesEqual } from './agent-session-background-task-state-equality'
import { agentJournalSubmissionKey } from './agent-session-journal-item-key'
/** The last host clock sample: `hostNow - receivedAt` is the client's skew from the host,
* which is what lets a client attaching mid-turn anchor its live counter on the real start. */
export type StructuredAgentHostClock = {
hostNow: number
receivedAt: number
}
export type StructuredAgentSessionState = {
epoch: string | null
cursor: AgentJournalCursor | null
fence: number | null
items: AgentJournalRenderItem[]
submissions: AgentJournalSubmission[]
/** Head-trim floor for `items`; paging back raises it so a live batch cannot undo the page. */
retainedItemLimit: number
hasOlder: boolean
status: 'idle' | 'loading' | 'ready' | 'error'
error?: string
handoff: AgentSessionHandoffStatus | null
backgroundTasks?: AgentSessionBackgroundTaskState | null
commands?: AgentSessionSlashCommand[] | null
activity?: AgentSessionTurnActivity | null
/** Absent until a frame from a host that stamps `hostNow` has been applied. */
hostClock?: StructuredAgentHostClock
}
export type StructuredAgentSessionAction =
| { type: 'loading' }
| { type: 'error'; message: string }
| { type: 'handoff'; handoff: AgentSessionHandoffStatus }
| { type: 'event'; event: AgentSessionSubscribeEvent }
| { type: 'history-page'; page: AgentSessionHistoryPage }
| { type: 'older-page'; requestedCursor: AgentJournalCursor; page: AgentSessionHistoryPage }
const MAX_RETAINED_SUBMISSIONS = 256
// Well above the renderer's initial read window (300) plus a page, so only genuinely
// long live sessions trim; anything trimmed is still reachable by paging older.
const MAX_RETAINED_ITEMS = 1024
export const EMPTY_STRUCTURED_AGENT_SESSION: StructuredAgentSessionState = {
epoch: null,
cursor: null,
fence: null,
items: [],
submissions: [],
retainedItemLimit: MAX_RETAINED_ITEMS,
hasOlder: false,
status: 'idle',
handoff: null
}
/** A frame without `hostNow` (older host) leaves the previous sample in place. */
function hostClockField(
hostNow: number | undefined,
receivedAt: number,
previous: StructuredAgentHostClock | undefined
): { hostClock?: StructuredAgentHostClock } {
const hostClock = hostNow !== undefined ? { hostNow, receivedAt } : previous
return hostClock ? { hostClock } : {}
}
function replacePage(
page: AgentSessionHistoryPage,
fence: number | null,
handoff?: AgentSessionHandoffStatus,
backgroundTasks?: AgentSessionBackgroundTaskState | null,
activity?: AgentSessionTurnActivity | null
): StructuredAgentSessionState {
return {
epoch: page.epoch,
cursor: page.liveCursor ?? page.window.nextCursor,
fence,
items: [...page.items].sort((left, right) => left.sequence - right.sequence),
submissions: page.submissions,
retainedItemLimit: Math.max(MAX_RETAINED_ITEMS, page.items.length),
hasOlder: page.hasOlder,
status: 'ready',
handoff: handoff ?? null,
activity: activity ?? null,
...(backgroundTasks !== undefined
? { backgroundTasks }
: page.backgroundTasks !== undefined
? { backgroundTasks: page.backgroundTasks }
: {})
}
}
function mergeItems(
current: readonly AgentJournalRenderItem[],
incoming: readonly AgentJournalRenderItem[],
removedIds: readonly string[]
): AgentJournalRenderItem[] {
const removed = new Set(removedIds)
const byId = new Map(
current.filter((item) => !removed.has(item.itemId)).map((item) => [item.itemId, item])
)
for (const item of incoming) {
const prior = byId.get(item.itemId)
if (!prior || item.revision >= prior.revision) {
byId.set(item.itemId, item)
}
}
return [...byId.values()].sort((left, right) => left.sequence - right.sequence)
}
function trimRetainedItems(
items: AgentJournalRenderItem[],
limit: number
): AgentJournalRenderItem[] {
return items.length <= limit ? items : items.slice(items.length - limit)
}
function mergeSubmissions(
current: readonly AgentJournalSubmission[],
incoming: readonly AgentJournalSubmission[],
items: readonly AgentJournalRenderItem[]
): AgentJournalSubmission[] {
const byId = new Map(current.map((submission) => [submission.clientMessageId, submission]))
for (const submission of incoming) {
byId.set(submission.clientMessageId, submission)
}
const sorted = [...byId.values()].sort((left, right) => left.submittedAt - right.submittedAt)
const itemIds = new Set(
items
.filter((item) => item.body.kind === 'message' && item.body.role === 'user')
.map((item) => item.itemId)
)
// Loaded user messages need their provider alias for durable turn attribution.
return sorted.filter(
(submission, index) =>
index >= sorted.length - MAX_RETAINED_SUBMISSIONS ||
itemIds.has(agentJournalSubmissionKey(submission.clientMessageId))
)
}
/** `receivedAt` is the client clock at apply time; callers pass it so the reducer stays pure. */
export function reduceStructuredAgentSession(
state: StructuredAgentSessionState,
action: StructuredAgentSessionAction,
receivedAt: number = Date.now()
): StructuredAgentSessionState {
if (action.type === 'loading') {
// Keep the last transcript visible while a reconnect rehydrates the stream.
return { ...state, status: 'loading', error: undefined }
}
if (action.type === 'error') {
return { ...state, status: 'error', error: action.message }
}
if (action.type === 'handoff') {
return { ...state, handoff: action.handoff }
}
if (action.type === 'history-page') {
return {
...replacePage(
action.page,
action.page.fence ?? null,
state.handoff ?? undefined,
state.backgroundTasks,
state.activity
),
commands: state.commands,
...hostClockField(action.page.hostNow, receivedAt, state.hostClock)
}
}
if (action.type === 'older-page') {
const requested = action.requestedCursor
if (state.epoch !== requested.epoch || action.page.epoch !== requested.epoch) {
return state
}
const head = state.items[0]
// A live batch head-trimmed past the anchor while this read was in flight, so the
// page no longer abuts the retained window; merging it would leave a silent hole.
// The caller re-anchors on the new head and asks again.
if (head && head.sequence > requested.sequence) {
return state
}
const items = mergeItems(state.items, action.page.items, action.page.removedItemIds)
return {
...state,
items,
retainedItemLimit: Math.max(state.retainedItemLimit, items.length),
submissions: mergeSubmissions(state.submissions, action.page.submissions, items),
hasOlder: action.page.hasOlder,
...hostClockField(action.page.hostNow, receivedAt, state.hostClock)
}
}
const event = action.event
if (event.type === 'end') {
return state
}
if (event.type === 'snapshot' || event.type === 'reset') {
return {
...replacePage(event.page, event.fence, event.handoff, event.backgroundTasks, event.activity),
commands: event.commands,
...hostClockField(event.hostNow, receivedAt, state.hostClock)
}
}
if (state.epoch !== event.batch.cursor.epoch) {
return state
}
if (state.cursor && event.batch.cursor.sequence < state.cursor.sequence) {
return state
}
const backgroundTasks =
event.backgroundTasks !== undefined ? event.backgroundTasks : state.backgroundTasks
const activity = event.activity !== undefined ? event.activity : state.activity
const journalUnchanged =
event.batch.items.length === 0 &&
event.batch.removedItemIds.length === 0 &&
event.batch.submissions.length === 0
if (
event.batch.cursor.sequence === state.cursor?.sequence &&
journalUnchanged &&
(event.fence === undefined || event.fence === state.fence) &&
(event.handoff === undefined || event.handoff === state.handoff) &&
(event.commands === undefined || event.commands === state.commands) &&
backgroundTaskStatesEqual(backgroundTasks, state.backgroundTasks) &&
activity?.turnId === state.activity?.turnId &&
activity?.text === state.activity?.text &&
state.status === 'ready' &&
state.error === undefined
) {
return state
}
const merged = journalUnchanged
? state.items
: mergeItems(state.items, event.batch.items, event.batch.removedItemIds)
const items = trimRetainedItems(merged, state.retainedItemLimit)
return {
...state,
cursor: event.batch.cursor,
fence: event.fence ?? state.fence,
items,
// A trim leaves older items behind the cursor, so paging must stay offered.
hasOlder: items.length < merged.length ? true : state.hasOlder,
submissions:
event.batch.submissions.length === 0 && event.batch.removedItemIds.length === 0
? state.submissions
: mergeSubmissions(state.submissions, event.batch.submissions, items),
status: 'ready',
error: undefined,
handoff: event.handoff ?? state.handoff,
commands: event.commands !== undefined ? event.commands : state.commands,
...(backgroundTasks !== undefined ? { backgroundTasks } : {}),
...(activity !== undefined ? { activity } : {}),
...hostClockField(event.hostNow, receivedAt, state.hostClock)
}
}
export function oldestStructuredAgentSessionCursor(
state: StructuredAgentSessionState
): AgentJournalCursor | null {
const oldest = state.items[0]
return state.epoch && oldest ? { epoch: state.epoch, sequence: oldest.sequence } : null
}