fix(sidechat): preserve child history across session restore

This commit is contained in:
路从今夜白 committed 2026-10-22 23:06:13 +08:00
1 parent 9a11166c92
commit 34fbad8a75
5 files changed
+131 -21

No files matched your search

+5 -14
View File
@@ -5,8 +5,9 @@
* display rows.
*
* A thread child's log starts with the ENTIRE inherited parent log as its
* fork seed. The route already cuts everything up to the LAST
* `session/end-seed` marker; the mapping re-applies the same cut so any
* fork seed. The route already cuts everything up to the last tagged
* `session/end-seed { inherited: true }` marker; the mapping re-applies the
* same cut (never a restore/replay lifecycle marker) so any
* seed event that somehow crosses the wire still never renders, and maps
* context injections (the "Side conversation boundary" prompt,
* plugin-sourced context) onto a collapsible injection row, so the view
@@ -24,7 +25,7 @@
*/
import type { DiffHunk, ReadBlockLine } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarHistoryEntry } from '../context-types.ts'
import { isContextInjectionMessage, SIDE_BOUNDARY_PROMPT } from '../sidechat-core.ts'
import { isContextInjectionMessage, SIDE_BOUNDARY_PROMPT, threadOwnLogEvents } from '../sidechat-core.ts'
/**
* Structured render payload for a tool row that maps onto one of the host's
@@ -190,14 +191,6 @@ function resultTextOf(data: Record<string, unknown>): string {
return parts.join('\n')
}
/** Index of the last `session/end-seed` event (fork seed marker), or -1. */
function lastSeedEnd(events: readonly { type: string }[]): number {
for (let index = events.length - 1; index >= 0; index--) {
if (events[index]?.type === 'session/end-seed') return index
}
return -1
}
/** Parse the tool's raw arguments JSON to an object, or undefined. */
function parseArgsObject(args: string | undefined): Record<string, unknown> | undefined {
if (args === undefined) return undefined
@@ -379,8 +372,7 @@ function attemptFailure(stream: unknown): string | undefined {
* @returns display rows in log order.
*/
export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: readonly SidechatTranscriptRow[]): SidechatTranscriptRow[] {
const events = entries.map(entry => entry.event)
const seedEnd = lastSeedEnd(events)
const events = threadOwnLogEvents(entries.map(entry => entry.event))
const rows: SidechatTranscriptRow[] = []
/** (turn, step, index, kind) key → index of its accumulating stream row. */
const streamRows = new Map<string, number>()
@@ -396,7 +388,6 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
* context re-sent, so summing would double-count). */
const turnUsage = new Map<number, { inputTokens: number; outputTokens: number }>()
for (let index = 0; index < events.length; index++) {
if (index <= seedEnd) continue
const event = events[index]
if (event === undefined) continue
const data = event.data as Record<string, unknown>
+7 -4
View File
@@ -1353,12 +1353,15 @@ export function effectiveModelSelection(
return parentModelSelection(events)
}
/** The events a thread produced itself: everything after the LAST
* `session/end-seed` marker (the fork-seed boundary). A log with no marker
* (a thread created before seeding existed) is returned whole. */
/** The events a thread produced itself: everything after its last
* `session/end-seed { inherited: true }` fork boundary. Untagged markers
* delimit restore/replay lifecycles, not inherited history. A log with no
* inherited marker (including an already-cut route payload) is returned whole. */
export function threadOwnLogEvents(events: readonly SidechatLogEvent[]): SidechatLogEvent[] {
for (let index = events.length - 1; index >= 0; index--) {
if (events[index]?.type === 'session/end-seed') return events.slice(index + 1)
const event = events[index]
if (event?.type === 'session/end-seed' && typeof event.data === 'object' && event.data !== null
&& 'inherited' in event.data && event.data.inherited === true) return events.slice(index + 1)
}
return [...events]
}
+105
View File
@@ -0,0 +1,105 @@
/** Real Session restore semantics, synthetic in-memory events only. No host/browser/provider. */
import { describe, expect, it } from 'vitest'
import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
import type { SessionId, SessionSeedEventState } from '@deepseek-ai/dsh-session'
import type { SidebarHistoryEntry } from '../src/context-types.ts'
import { threadOwnLogEvents, threadHasCompletedTurn, threadTrailingPending, type SidechatLogEvent } from '../src/sidechat-core.ts'
import { transcriptRows } from '../src/client/sidechat-transcript.ts'
const childContent = [
{ type: 'text', text: 'Synthetic child block zero.' },
{ type: 'reasoning', text: 'Synthetic non-text-block gap.' },
{ type: 'text', text: 'Synthetic child block two.' },
]
function turn(session: Session, number: number, label: string, content = childContent): void {
session.append('turn/start', { turn: number })
session.append('step/start', { turn: number, step: 1 })
session.append('user/message', { id: `${label}-user`, role: 'user', source: { kind: 'user' },
content: [{ type: 'text', text: label }] } as never, { surfaceOp: 'append' })
session.append('assistant/message', { turn: number, step: 1,
message: { id: `${label}-assistant`, role: 'assistant', source: { kind: 'model', provider: 'synthetic', model: 'fixture' }, content },
stream: [] } as never, { surfaceOp: 'append' })
session.append('step/end', { turn: number, step: 1 })
session.append('turn/end', { turn: number, reason: { kind: 'completed' } })
}
function fork(parent: Session, id: string): Session {
return Session.create(id as SessionId, parent.snapshotEvents(), {
version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: 1, isSeeded: true,
}, SessionLogOffset(parent.snapshotEvents().length))
}
function seed(): Session {
const parent = Session.create('session-synthetic-parent' as SessionId)
turn(parent, 1, 'synthetic inherited parent', [{ type: 'text', text: 'Inherited parent output must stay excluded.' }])
const child = fork(parent, 'session-synthetic-child')
turn(child, 2, 'synthetic child turn')
return child
}
function restore(session: Session, mode: SessionSeedEventState): Session {
return Session.fromRestore(session.id,
mode === 'detached' ? structuredClone(session.snapshotEvents()) : session.snapshotEvents(),
mode === 'detached' ? structuredClone(session.header) : session.header, session.inheritedEventCount, mode)
}
const log = (session: Session): readonly SidechatLogEvent[] => session.snapshotEvents()
const entries = (events: readonly SidechatLogEvent[]): SidebarHistoryEntry[] => events.map(event => ({ event } as SidebarHistoryEntry))
const assistants = (events: readonly SidechatLogEvent[]) => transcriptRows(entries(events)).filter(row => row.kind === 'assistant')
const marker = (seq: number, data: unknown): SidechatLogEvent => ({ type: 'session/end-seed', seq, time: seq, data })
const message = (seq: number): SidechatLogEvent => ({ type: 'user/message', seq, time: seq, data: { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: `synthetic-${seq}` }] } })
describe('inherited boundary is not a restore boundary', () => {
it('cuts only the last tagged inherited prefix, including nested forks', () => {
const events = [message(0), marker(1, { inherited: true }), message(2), marker(3, {}),
marker(4, { inherited: true }), message(5), marker(6, {})]
expect(threadOwnLogEvents(events).map(event => event.seq)).toEqual([5, 6])
})
it('is idempotent on the already-cut route payload containing restore markers', () => {
const events = [message(0), marker(1, { inherited: true }), message(2), marker(3, {})]
const own = threadOwnLogEvents(events)
expect(own.map(event => event.seq)).toEqual([2, 3])
expect(threadOwnLogEvents(own)).toEqual(own)
expect(transcriptRows(entries(own))).toEqual([{ kind: 'user', seq: 2, text: 'synthetic-2' }])
})
it('does not invent a fork cut from replay, false, malformed or absent markers', () => {
const events = [message(0), marker(1, {}), marker(2, { inherited: false }), marker(3, { inherited: 'true' }),
marker(4, null), message(5)]
expect(threadOwnLogEvents(events)).toEqual(events)
expect(transcriptRows(entries(events)).filter(row => row.kind === 'user').map(row => row.seq)).toEqual([0, 5])
})
for (const mode of ['detached', 'shared-frozen'] as const) {
it(`preserves both original text-block indexes across actual ${mode} restore and route→client composition`, () => {
const child = seed(), before = assistants(log(child))
expect(before.map(row => row.contentBlockIndex)).toEqual([0, 2])
const resumed = restore(child, mode), events = log(resumed)
expect(events.at(-1)).toMatchObject({ type: 'session/end-seed', data: {} })
expect(resumed.inheritedEventCount).toBe(child.inheritedEventCount)
expect(assistants(events)).toEqual(before)
expect(assistants(threadOwnLogEvents(events))).toEqual(before)
expect(JSON.stringify(transcriptRows(entries(threadOwnLogEvents(events))))).not.toContain('Inherited parent output')
expect(threadHasCompletedTurn(entries(events))).toBe(true)
expect(threadTrailingPending(entries(events))).toBe(false)
})
it(`retains earlier child turns across multiple actual ${mode} restore markers`, () => {
const first = restore(seed(), mode)
turn(first, 3, 'synthetic second child turn')
const second = restore(first, mode), events = log(second)
expect(events.filter(event => event.type === 'session/end-seed').map(event => event.data)).toEqual([
{ inherited: true }, {}, {},
])
expect(assistants(threadOwnLogEvents(events)).map(row => row.contentBlockIndex)).toEqual([0, 2, 0, 2])
expect(assistants(events)).toEqual(assistants(threadOwnLogEvents(events)))
second.append('user/message', { id: 'synthetic pending', role: 'user', source: { kind: 'user' },
content: [{ type: 'text', text: 'synthetic follow-up' }] } as never, { surfaceOp: 'append' })
expect(threadTrailingPending(entries(log(second)))).toBe(true)
})
it(`keeps nested parent history excluded after actual ${mode} restore`, () => {
const parent = restore(seed(), mode)
const empty = fork(parent, 'session-synthetic-empty-child')
expect(assistants(log(restore(empty, mode)))).toEqual([])
const grandchild = fork(parent, 'session-synthetic-grandchild')
turn(grandchild, 4, 'synthetic grandchild')
const resumed = restore(grandchild, mode)
const output = assistants(threadOwnLogEvents(log(resumed)))
expect(output.map(row => row.contentBlockIndex)).toEqual([0, 2])
expect(output.every(row => row.seq > Number(grandchild.inheritedEventCount))).toBe(true)
})
}
})
+12 -1
View File
@@ -645,7 +645,7 @@ function threadLog(): Array<ReturnType<typeof ev>> {
return [
ev('user/message', 0, { content: [{ type: 'text', text: 'inherited parent question' }], source: { kind: 'user' } }),
ev('turn/end', 1, { turn: 0, reason: { kind: 'completed' } }),
ev('session/end-seed', 2),
ev('session/end-seed', 2, { inherited: true }),
ev('subagent/descriptor', 3, { mode: 'continuable' }),
ev('user/message', 4, { content: [{ type: 'text', text: 'Side conversation boundary.' }], source: { kind: SIDE_INJECTION_SOURCE_KIND } }),
ev('user/message', 5, { content: [{ type: 'text', text: 'the side question' }], source: { kind: 'user' } }),
@@ -665,6 +665,17 @@ describe('sidechat.events', () => {
expect(services.open).not.toHaveBeenCalled()
})
it('keeps pre-resume child history when a live restored log ends in an untagged lifecycle marker', async () => {
const child = agent('child', { events: [...threadLog(), ev('session/end-seed', 8, {})] })
const services = happyServices(undefined, child)
const api = buildSidechatApi(ctxWith(services))
const result = await api['sidechat.events']({ childId: 'child' })
expect(result.events.map(event => event.seq)).toEqual([3, 4, 5, 6, 7, 8])
const delta = await api['sidechat.events']({ childId: 'child', afterSeq: 6 })
expect(delta.events.map(event => event.seq)).toEqual([7, 8])
expect(services.open).not.toHaveBeenCalled()
})
it('narrows to the afterSeq delta on polls (and never resurrects the seed)', async () => {
const child = agent('child', { events: threadLog() })
const services = happyServices(undefined, child)
+2 -2
View File
@@ -58,10 +58,10 @@ function toolRoleResultMessage(callId: string, text: string, isError = false): R
}
describe('transcriptRows', () => {
it('cuts the inherited seed at the last end-seed and renders the boundary as an injection row', () => {
it('cuts the inherited seed at the last tagged end-seed and renders the boundary as an injection row', () => {
const entries = [
entry(ev('user/message', 0, { content: textBlocks('inherited'), source: { kind: 'user' } })),
entry(ev('session/end-seed', 1)),
entry(ev('session/end-seed', 1, { inherited: true })),
entry(ev('user/message', 2, { content: textBlocks(`${SIDE_BOUNDARY_PREFIX}\n\nmode`), source: { kind: SIDE_INJECTION_SOURCE_KIND } })),
entry(ev('user/message', 3, { content: textBlocks('the side question'), source: { kind: 'user' } })),
]