Merge remote-tracking branch 'origin/master' into worktree/web-theme-settings-integration-fde706

# Conflicts:
#	.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.i18n.yaml
#	.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.zh.md
#	.agents/notes/implemented/feature/2026-07-30-web-queue-steer-action.i18n.yaml
#	.agents/notes/implemented/feature/2026-07-30-web-queue-steer-action.zh.md
#	.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.i18n.yaml
#	.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.zh.md
#	.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml
#	apps/web/tests/scaffold.ts
#	docs/module-graph.md
#	packages/client/runtime/README.i18n.yaml
#	packages/client/runtime/package.json
#	packages/client/test-runtime/README.i18n.yaml
#	packages/client/test-runtime/README.zh.md
#	packages/client/ui-conversation/README.i18n.yaml
#	packages/client/ui-conversation/README.zh.md
#	packages/client/ui-conversation/package.json
#	packages/client/ui-conversation/src/client/apply.ts
#	packages/client/ui-theme/README.i18n.yaml
#	packages/client/ui-theme/README.md
#	packages/client/ui-theme/README.zh.md
#	packages/host/apiproxy/README.i18n.yaml
#	packages/host/apiproxy/README.zh.md
#	pnpm-lock.yaml
This commit is contained in:
Yichen Jiang
2026-08-10 12:50:43 +08:00
3485 changed files with 86192 additions and 25255 deletions

View File

@@ -54,7 +54,7 @@ describe('apply wiring', () => {
await b.runtime.dispose()
})
it('registers the chat view as the first ring entry, declaring the whole-Tool seat', async () => {
it('registers the chat view and its keyed business-node seat', async () => {
const b = await bench()
const entries = b.slots.entries('conversation.view')
expect(entries.map(e => e.options.id)).toEqual(['chat'])
@@ -63,7 +63,9 @@ describe('apply wiring', () => {
expect(entries[0]?.options.order).toBe(0)
// Declaring is claiming: the chat entry's registration put the hole on
// the ledger with the contract's kind/scope.
expect(b.slots.spec('conversation.chat.tool')).toEqual({ kind: 'single', scope: 'session' })
const nodeSlot = b.slots.spec('conversation.chat.node')
expect(nodeSlot).toMatchObject({ kind: 'keyed', scope: 'session' })
expect(nodeSlot?.inject?.hooks?.turnData).toBeTypeOf('function')
await b.runtime.dispose()
})
@@ -83,9 +85,11 @@ describe('apply wiring', () => {
expect(conversationHeader?.store).toBe(conversationSession?.store)
expect(details?.store).toBe(conversationSession?.store)
expect(chatView?.store).toBe(conversationSession?.store)
// The hero workspace picker hole rides the conversation entry's children
// declaration (the empty-state occupant is gone).
// The hero holes ride the conversation entry's children declaration (the
// empty-state occupant is gone). Both are root-scoped: the new-session
// screen precedes the session either would belong to.
expect(b.slots.spec('conversation.hero.workspace')).toEqual({ kind: 'single', scope: 'root' })
expect(b.slots.spec('conversation.hero.agentPreset')).toEqual({ kind: 'single', scope: 'root' })
expect(b.slots.entries('settings.general.item').map(entry => entry.options.id)).toEqual(['composer-enter'])
await b.runtime.dispose()
})
@@ -96,7 +100,7 @@ describe('apply wiring', () => {
// file-mutation registrant claims both write and edit for the diff card; the
// one search row registers under both grep and glob; the web rows register
// one component under both web tool names.
expect(b.slots.entries('conversation.chat.tool')).toHaveLength(0)
expect(b.slots.entries('conversation.chat.node').map(entry => entry.options.key)).not.toContain('tool-call')
// Stats stick with the composer (not inside ChatView).
expect(b.slots.entries('conversation.composer.dock').map(e => e.options.id)).toEqual(['stats'])
await b.runtime.dispose()
@@ -109,8 +113,8 @@ describe('apply wiring', () => {
// The declared ring collapses with its declaring entry, and the chat
// entry's keyed hole (with the sample's registration) collapses with it.
expect(b.slots.entries('conversation.view')).toHaveLength(0)
expect(b.slots.entries('conversation.chat.tool')).toHaveLength(0)
expect(b.slots.spec('conversation.chat.tool')).toBeUndefined()
expect(b.slots.entries('conversation.chat.node')).toHaveLength(0)
expect(b.slots.spec('conversation.chat.node')).toBeUndefined()
expect(b.slots.entries('details')).toHaveLength(0)
expect(b.slots.entries('settings.general.item')).toHaveLength(0)
expect(b.runtime.ctx.get('conversation')).toBeUndefined()

View File

@@ -10,13 +10,21 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import type {
ChatConversationViewNode, ConversationNode,
} from '@deepseek-ai/dsh-client-runtime/client'
import type { ChatNodeViewProps } from '../src/client/contract/slots.ts'
import {
formatMessageClock, msUntilNextLocalMidnight, startOfLocalDay,
} from '../src/client/chat/message-chrome.ts'
import { MessageItem, type MessageItemProps } from '../src/client/chat/MessageItem.tsx'
import {
CompactionNodeView, ContextMessageNodeView, RetryNodeView, UnknownNodeView,
UserMessageNodeView,
} from '../src/client/chat/MessageItem.tsx'
import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx'
import { StatsLine, type StatsLineProps } from '../src/client/chat/StatsLine.tsx'
import { zh } from '../src/client/locales.ts'
import { chatSnapshotFixture } from './chat-snapshot-fixture.ts'
/** jsdom has no ResizeObserver; StatsLine watches its row for ellipsis truncation through one. */
class ResizeObserverStub {
@@ -33,7 +41,44 @@ afterEach(() => {
})
// Mirrors the real lookup chain (conversation namespace, then common).
const t: MessageItemProps['t'] = makeTranslate(zh, commonZh)
const t: ChatNodeViewProps['t'] = makeTranslate(zh, commonZh)
const RETRY_ID = 'retry-fixture' as Extract<ConversationNode, { kind: 'model-retry' }>['retryId']
interface MessageItemProps {
readonly node: ConversationNode
readonly t: ChatNodeViewProps['t']
}
/** Legacy-node fixture adapter for the independently registered renderers. */
function MessageItem({ node, t: translate }: MessageItemProps) {
const kind = node.kind === 'assistant' ? 'assistant-step' : node.kind
const viewNode: ChatConversationViewNode = {
key: `fixture:${node.kind}:${node.seq}`,
kind,
id: String(node.seq),
target: 'chat',
anchorSeq: node.seq,
location: { kind: 'session' },
visibility: 'visible',
data: node.kind === 'model-retry' ? { attempts: [node], current: node } : node,
}
const props = { node: viewNode, t: translate } as ChatNodeViewProps
switch (node.kind) {
case 'user':
case 'steering':
return <UserMessageNodeView {...props as ChatNodeViewProps<'user' | 'steering'>} />
case 'context':
return <ContextMessageNodeView {...props as ChatNodeViewProps<'context'>} />
case 'compaction':
return <CompactionNodeView {...props as ChatNodeViewProps<'compaction'>} />
case 'model-retry':
return <RetryNodeView {...props as ChatNodeViewProps<'model-retry'>} />
case 'unknown':
return <UnknownNodeView {...props as ChatNodeViewProps<'unknown'>} />
default:
throw new Error(`unsupported MessageItem fixture kind: ${node.kind}`)
}
}
describe('MessageItem arms', () => {
it('user bubbles expose clock / copy and neither branch nor edit; copy writes the text', () => {
@@ -226,7 +271,7 @@ describe('MessageItem arms', () => {
expect(disclosure.getAttribute('aria-expanded')).toBe('true')
// An unknown form renders the opaque body: the model-facing text keeps its
// real line breaks instead of being escaped into one JSON line, and the
// remaining provenance follows it as fields.
// remaining source data follows it as fields.
expect(ctxView.container.querySelector('[data-context-text]')?.textContent)
.toBe('line one\n\nline two')
const fields = [...ctxView.container.querySelectorAll('[data-context-fields] dt')].map(node => node.textContent)
@@ -418,7 +463,7 @@ describe('MessageItem arms', () => {
expect(view.container.querySelector('[data-context-text]')?.textContent).toBe('firstsecond')
})
it('bounds an oversized provenance field, not only the model-facing text', () => {
it('bounds an oversized source field, not only the model-facing text', () => {
const view = render(
<MessageItem t={t} node={{
kind: 'context',
@@ -708,7 +753,7 @@ describe('MessageItem arms', () => {
expect(row.getAttribute('aria-expanded')).toBe('false')
})
it('a marker whose provenance fell outside the window is not expandable', () => {
it('a marker whose cited summary event fell outside the window is not expandable', () => {
const view = render(<MessageItem t={t} node={{
kind: 'compaction', seq: 6, time: 1_000, summary: null,
summaryEventSeq: null, shadowedItemCount: null, shadowedTokenCount: null,
@@ -727,9 +772,9 @@ describe('MessageItem arms', () => {
const view = render(
<MessageItem
t={t}
retryActive
node={{
kind: 'model-retry',
retryId: RETRY_ID,
seq: 5,
time: 10_000,
retryState: 'scheduled',
@@ -761,9 +806,9 @@ describe('MessageItem arms', () => {
view.rerender(
<MessageItem
t={t}
retryActive
node={{
kind: 'model-retry',
retryId: RETRY_ID,
seq: 6,
time: 12_100,
retryState: 'scheduled',
@@ -788,6 +833,7 @@ describe('MessageItem arms', () => {
view.rerender(
<MessageItem t={t} node={{
kind: 'model-retry',
retryId: RETRY_ID,
seq: 6,
time: 12_100,
retryState: 'started',
@@ -809,6 +855,7 @@ describe('MessageItem arms', () => {
view.rerender(
<MessageItem t={t} node={{
kind: 'model-retry',
retryId: RETRY_ID,
seq: 7,
time: 12_100,
retryState: 'started',
@@ -828,6 +875,7 @@ describe('MessageItem arms', () => {
view.rerender(
<MessageItem t={t} node={{
kind: 'model-retry',
retryId: RETRY_ID,
seq: 8,
time: 12_100,
retryState: 'cancelled',
@@ -846,32 +894,6 @@ describe('MessageItem arms', () => {
expect(view.getByRole('status').textContent).toBe('模型请求重试已取消1/2 · 4s')
})
it('synchronizes the countdown when an inactive retry becomes active at the one-second floor', () => {
vi.useFakeTimers()
vi.setSystemTime(10_000)
const node = {
kind: 'model-retry',
seq: 5,
time: 10_000,
retryState: 'scheduled',
turn: 1,
step: 0,
provider: 'mock',
mode: 'normal',
policyKey: 'mock-normal',
retry: 1,
maxRetries: 2,
delayMs: 5_000,
failure: { code: 'TRANSPORT', message: '连接被重置' },
} as const
const view = render(<MessageItem t={t} node={node} />)
expect(view.getByRole('status').textContent).toBe('等待重试模型请求1/2 · 5s')
act(() => { vi.advanceTimersByTime(4_200) })
view.rerender(<MessageItem t={t} node={node} retryActive />)
expect(view.getByRole('status').textContent).toBe('正在重试模型请求1/2 · 1s')
})
})
describe('formatMessageClock', () => {
@@ -932,84 +954,13 @@ describe('small branch tails', () => {
expect(view.getByText('one-liner')).toBeTruthy()
})
it('finalized content messages expose copy / branch / clock; Think-only and streaming omit them', () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
})
const now = new Date()
const time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 24).getTime()
const onFork = vi.fn()
const settled = render(
<AssistantMarkdown
t={t}
blocks={[{ kind: 'text', text: 'answer body' }, { kind: 'reasoning', text: 'hidden' }]}
streaming={false}
time={time}
seq={3}
onFork={onFork}
/>,
)
expect(settled.getByText('14:24')).toBeTruthy()
expect(settled.getByRole('button', { name: '复制' })).toBeTruthy()
expect(settled.getByRole('button', { name: '在新对话中分支' })).toBeTruthy()
fireEvent.click(settled.getByRole('button', { name: '复制' }))
expect(writeText).toHaveBeenCalledWith('answer body')
fireEvent.click(settled.getByRole('button', { name: '在新对话中分支' }))
expect(onFork).toHaveBeenCalledWith(3)
settled.unmount()
const thinkOnly = render(
<AssistantMarkdown
t={t}
blocks={[{ kind: 'reasoning', text: 'only thinking' }]}
streaming={false}
time={time}
/>,
)
expect(thinkOnly.queryByRole('button', { name: '复制' })).toBeNull()
expect(thinkOnly.queryByText('14:24')).toBeNull()
thinkOnly.unmount()
const streaming = render(
<AssistantMarkdown t={t} blocks={[{ kind: 'text', text: 'partial' }]} streaming time={time} />,
)
expect(streaming.queryByRole('button', { name: '复制' })).toBeNull()
expect(streaming.queryByText('14:24')).toBeNull()
})
it('keeps an unavailable branch focusable and explains why without sending a fork', () => {
const onFork = vi.fn()
render(
<AssistantMarkdown
t={t}
blocks={[{ kind: 'text', text: 'answer before a trailing tool row' }]}
streaming={false}
time={1_000}
seq={1}
onFork={onFork}
forkUnavailable
/>,
)
const branch = screen.getByRole('button', { name: '在新对话中分支' }) as HTMLButtonElement
expect(branch.disabled).toBe(false)
expect(branch.getAttribute('aria-disabled')).toBe('true')
const reasonId = branch.getAttribute('aria-describedby')
expect(reasonId).not.toBeNull()
expect(document.getElementById(reasonId!)?.textContent).toBe('仅可从已完成轮次的最后一条消息分支')
fireEvent.click(branch)
expect(onFork).not.toHaveBeenCalled()
fireEvent.focus(branch)
expect(screen.getByRole('tooltip').textContent).toBe('仅可从已完成轮次的最后一条消息分支')
})
it('StatsLine omits the cache-hit segment when no input accounting exists at all', () => {
// Cache hit is null only when all three prompt buckets are zero (pure
// output accounting) — any billed input makes it a real 0%.
const snap = {
nodes: [{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [], usage: { outputTokens: 10 } }],
}
const nodes = [{
kind: 'assistant', seq: 1, time: 1_000, turn: 1, step: 1, blocks: [], usage: { outputTokens: 10 },
}] as const
const snap = { chat: chatSnapshotFixture({ nodes }), nodes }
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
const view = render(
<StatsLine

View File

@@ -0,0 +1,298 @@
import type {
AssistantMessageNode, ChatConversationViewNode, ChatSnapshot, ConversationNode,
ChatLocationNodeIndex, ChatNodeStore, CompactionSummaryNode, ConversationLocationDataStore,
ConversationTurnDataMap, LegacyConversationSlice, PartialAssistant, RunningToolCall,
ToolCallBlock, TurnLocation,
} from '@deepseek-ai/dsh-client-runtime/client'
import { deriveTurnMetrics } from '../src/client/chat/turn-metrics.ts'
const EMPTY: readonly never[] = []
function sameValues<T>(left: readonly T[], right: readonly T[]): boolean {
return left.length === right.length && left.every((value, index) => value === right[index])
}
function nodeSource(node: ChatConversationViewNode): unknown {
if (node.kind === 'assistant-step') {
const data = node.data as ReturnType<typeof assistantData>
return data.finalNode ?? data.blocks
}
if (node.kind === 'tool-call') return (node.data as { readonly root: ToolCallBlock }).root
if (node.kind === 'model-retry') return (node.data as { readonly current: unknown }).current
if (node.kind === 'turn-tail') return (node.data as { readonly seq: number }).seq
return node.data
}
class FixtureNodeStore implements ChatNodeStore {
private byKey = new Map<string, ChatConversationViewNode>()
private list: readonly ChatConversationViewNode[] = EMPTY
get(key: string): ChatConversationViewNode | undefined {
return this.byKey.get(key)
}
values(): readonly ChatConversationViewNode[] {
return this.list
}
replace(candidates: readonly ChatConversationViewNode[]): void {
const next = new Map<string, ChatConversationViewNode>()
const list = candidates.map((candidate) => {
const previous = this.byKey.get(candidate.key)
const node = previous !== undefined
&& previous.kind === candidate.kind
&& previous.anchorSeq === candidate.anchorSeq
&& previous.visibility === candidate.visibility
&& nodeSource(previous) === nodeSource(candidate)
? previous
: candidate
next.set(node.key, node)
return node
})
this.byKey = next
this.list = sameValues(this.list, list) ? this.list : list
}
}
class FixtureLocationIndex implements ChatLocationNodeIndex {
private turns = new Map<number, readonly string[]>()
getTurn(turn: number): readonly string[] {
return this.turns.get(turn) ?? EMPTY
}
getStep(): readonly string[] {
return EMPTY
}
replace(next: ReadonlyMap<number, readonly string[]>): void {
const stable = new Map<number, readonly string[]>()
for (const [turn, keys] of next) {
const previous = this.turns.get(turn) ?? EMPTY
stable.set(turn, sameValues(previous, keys) ? previous : keys)
}
this.turns = stable
}
}
class FixtureTurnDataStore implements ConversationLocationDataStore<ConversationTurnDataMap> {
private readonly values = new Map<string, unknown>()
get<Key extends Extract<keyof ConversationTurnDataMap, string>>(
key: Key,
): Readonly<ConversationTurnDataMap[Key]> | undefined {
return this.values.get(key) as Readonly<ConversationTurnDataMap[Key]> | undefined
}
set<Key extends Extract<keyof ConversationTurnDataMap, string>>(
key: Key,
value: ConversationTurnDataMap[Key],
): void {
this.values.set(key, value)
}
}
function assistantData(node: AssistantMessageNode) {
return {
status: node.interrupted === true ? 'interrupted' as const : 'settled' as const,
turn: node.turn,
step: node.step,
blocks: node.blocks,
time: node.time,
finalNode: node,
}
}
function settledNode(
node: ConversationNode,
turns: ReadonlyMap<number, TurnLocation>,
): ChatConversationViewNode {
const turn = 'turn' in node && typeof node.turn === 'number' ? turns.get(node.turn) : undefined
const base = {
key: `fixture:${node.kind}:${node.seq}`,
id: String(node.seq),
target: 'chat' as const,
anchorSeq: node.seq,
location: turn === undefined
? { kind: 'session' as const }
: { kind: 'turn' as const, turn },
visibility: 'visible' as const,
}
switch (node.kind) {
case 'assistant':
return { ...base, kind: 'assistant-step', data: assistantData(node) }
case 'tool-result':
return { ...base, key: `fixture:tool:${node.callId}`, kind: 'tool-call', data: { root: node } }
case 'model-retry':
return { ...base, key: 'fixture:model-retry', kind: 'model-retry', data: { attempts: [node], current: node } }
default:
return { ...base, kind: node.kind, data: node }
}
}
/** Build the canonical Chat fixture corresponding to one legacy test slice. */
export function chatSnapshotFixture(input: {
readonly nodes?: readonly ConversationNode[]
readonly partial?: PartialAssistant | null
readonly runningCalls?: readonly RunningToolCall[]
readonly turnTimings?: LegacyConversationSlice['turnTimings']
readonly turnEnds?: LegacyConversationSlice['turnEnds']
} = {}, previous?: ChatSnapshot): ChatSnapshot {
const legacy: LegacyConversationSlice = {
nodes: input.nodes ?? EMPTY,
partial: input.partial ?? null,
runningCalls: input.runningCalls ?? EMPTY,
turnTimings: input.turnTimings ?? new Map(),
turnEnds: input.turnEnds ?? new Map(),
}
const turnNumbers = new Set([...legacy.turnTimings.keys(), ...legacy.turnEnds.keys()])
for (const node of legacy.nodes) {
if ('turn' in node && typeof node.turn === 'number') turnNumbers.add(node.turn)
}
if (legacy.partial !== null) turnNumbers.add(legacy.partial.turn)
for (const call of legacy.runningCalls) turnNumbers.add(call.turn)
const turns = new Map<number, TurnLocation>()
const turnData = new Map<number, FixtureTurnDataStore>()
for (const turn of [...turnNumbers].sort((left, right) => left - right)) {
const timing = legacy.turnTimings.get(turn)
const endSeq = legacy.turnEnds.get(turn)
const data = new FixtureTurnDataStore()
turnData.set(turn, data)
turns.set(turn, {
turn,
start: timing === undefined ? undefined : {
type: 'turn/start', seq: Math.max(0, (endSeq ?? 1) - 1), time: timing.startTime, turn,
} as never,
end: timing?.endTime === undefined || endSeq === undefined ? undefined : {
type: 'turn/end', seq: endSeq, time: timing.endTime, turn, reason: 'completed',
} as never,
status: endSeq === undefined ? 'open' : 'closed',
steps: EMPTY,
data,
})
}
const linkedCompactions = new Set<CompactionSummaryNode>()
const nodes = legacy.nodes.flatMap((node): ChatConversationViewNode[] => {
if (node.kind === 'command' && node.name === 'compact') {
const sourceSeq = node.outcome?.kind === 'success' ? node.outcome.sourceEventSeq : undefined
const candidates = sourceSeq === undefined
? []
: legacy.nodes.filter((candidate): candidate is CompactionSummaryNode =>
candidate.kind === 'compaction' && candidate.summaryEventSeq === sourceSeq)
const compaction = candidates.length === 1 ? candidates[0] : undefined
if (node.outcome === null || compaction !== undefined) {
if (compaction !== undefined) linkedCompactions.add(compaction)
const base = settledNode(node, turns)
return [{
...base,
key: `fixture:manual-compaction:${node.commandId}`,
kind: 'manual-compaction',
anchorSeq: compaction?.seq ?? node.seq,
data: { command: node, compaction: compaction ?? null },
}]
}
}
if (node.kind === 'compaction' && linkedCompactions.has(node)) return []
return [settledNode(node, turns)]
})
if (legacy.partial !== null) {
const turn = turns.get(legacy.partial.turn)
nodes.push({
key: `fixture:assistant:${legacy.partial.turn}:${legacy.partial.step}`,
id: `${legacy.partial.turn}:${legacy.partial.step}`,
target: 'chat',
kind: 'assistant-step',
anchorSeq: Number.MAX_SAFE_INTEGER - 1,
location: turn === undefined ? { kind: 'session' } : { kind: 'turn', turn },
visibility: 'visible',
data: {
status: 'running',
turn: legacy.partial.turn,
step: legacy.partial.step,
blocks: legacy.partial.blocks,
time: 0,
},
})
}
for (const call of legacy.runningCalls) {
const turn = turns.get(call.turn)
nodes.push({
key: `fixture:tool:${call.callId}`,
id: call.callId,
target: 'chat',
kind: 'tool-call',
anchorSeq: Number.MAX_SAFE_INTEGER,
location: turn === undefined ? { kind: 'session' } : { kind: 'turn', turn },
visibility: 'visible',
data: { root: call },
})
}
for (const [turnNumber, endSeq] of legacy.turnEnds) {
const turn = turns.get(turnNumber)
const dataStore = turnData.get(turnNumber)
if (turn === undefined || dataStore === undefined) continue
const closing = legacy.nodes
.filter((candidate): candidate is AssistantMessageNode => candidate.kind === 'assistant'
&& candidate.turn === turnNumber
&& candidate.blocks.some(block => block.kind === 'text' && block.text.trim() !== ''))
.map(assistantData)
.at(-1) ?? null
const preceding = nodes.findLast((candidate) => {
const location = candidate.location
return (location.kind === 'turn' || location.kind === 'step')
&& location.turn.turn === turnNumber
})
const metrics = deriveTurnMetrics(legacy.nodes).get(turnNumber)
const tailData = {
turn: turnNumber,
seq: endSeq,
time: turn.end?.time ?? 0,
closing,
branchUnavailable: closing === null
|| preceding?.kind !== 'assistant-step'
|| (preceding.data as ReturnType<typeof assistantData>).finalNode.seq !== closing.finalNode.seq,
...metrics?.ttftMs === undefined ? {} : { ttftMs: metrics.ttftMs },
...metrics?.tokensPerSecond === undefined ? {} : { tokensPerSecond: metrics.tokensPerSecond },
}
dataStore.set('turn-tail', tailData)
nodes.push({
key: `fixture:turn-tail:${turnNumber}`,
id: String(turnNumber),
target: 'chat',
kind: 'turn-tail',
anchorSeq: endSeq,
location: { kind: 'turn', turn },
visibility: 'visible',
data: tailData,
})
}
const store = previous?.nodes instanceof FixtureNodeStore ? previous.nodes : new FixtureNodeStore()
store.replace(nodes)
const byKey = new Map(store.values().map(node => [node.key, node]))
const nextOrder = nodes.map(node => node.key)
const order = previous !== undefined && sameValues(previous.order, nextOrder) ? previous.order : nextOrder
const byTurn = new Map<number, readonly string[]>()
for (const turn of turns.keys()) {
byTurn.set(turn, order.filter((key) => {
const location = byKey.get(key)?.location
return location?.kind === 'turn' && location.turn.turn === turn
|| location?.kind === 'step' && location.turn.turn === turn
}))
}
const locations = previous?.locations instanceof FixtureLocationIndex
? previous.locations
: new FixtureLocationIndex()
locations.replace(byTurn)
const timeline = previous !== undefined
&& previous.legacy.turnTimings === legacy.turnTimings
&& previous.legacy.turnEnds === legacy.turnEnds
? previous.timeline
: { turnOrder: [...turns.keys()], turns }
return {
order,
nodes: store,
locations,
timeline,
legacy,
}
}

View File

@@ -13,6 +13,7 @@ import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import { StatsLine, contextOccupancy, deriveStats, formatDuration, formatTokens, type StatsLineProps } from '../src/client/chat/StatsLine.tsx'
import { en, zh } from '../src/client/locales.ts'
import { chatSnapshotFixture } from './chat-snapshot-fixture.ts'
// Mirrors the real lookup chain (conversation namespace, then common).
const t: StatsLineProps['t'] = makeTranslate(zh, commonZh)
@@ -42,18 +43,39 @@ const assistant = (seq: number, turn: number, usage?: unknown): AssistantMessage
function snapshotBase(): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: chatSnapshotFixture(),
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
}
}
function makeSource(init?: Partial<ConversationSnapshot>) {
let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
const initial = { ...snapshotBase(), ...init }
let snap: ConversationSnapshot = {
...initial,
chat: init?.chat ?? chatSnapshotFixture({
nodes: initial.nodes,
partial: initial.partial,
runningCalls: initial.runningCalls,
turnTimings: initial.turnTimings,
turnEnds: initial.turnEnds,
}),
}
const subs = new Set<() => void>()
return {
set: (next: Partial<ConversationSnapshot>) => {
snap = { ...snap, ...next }
const merged = { ...snap, ...next }
snap = {
...merged,
chat: next.chat ?? (next.nodes === undefined ? snap.chat : chatSnapshotFixture({
nodes: merged.nodes,
partial: merged.partial,
runningCalls: merged.runningCalls,
turnTimings: merged.turnTimings,
turnEnds: merged.turnEnds,
})),
}
for (const fn of [...subs]) fn()
},
source: {

View File

@@ -4,24 +4,33 @@
// ObservableSnapshot fake, no wire or Tool presentation plugin.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Profiler } from 'react'
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
import { useEffect } from 'react'
import type {
AssistantMessageNode, CommandNode, CompactionSummaryNode, ConversationNode, ConversationSnapshot,
ModelRetryNode, RunningToolCall, SessionId, SessionListState, ToolResultNode, TurnErrorNode,
ModelRetryNode, RunningToolCall, SessionId, SessionListState, ToolCallBlock, ToolResultNode, TurnErrorNode,
UserMessageNode, WorkspaceListState,
} from '@deepseek-ai/dsh-client-runtime/client'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { createSnapshotStore, PendingWait } from '@deepseek-ai/dsh-client-runtime/client'
import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
import type { ChatViewSlotProps, SelectionTarget, ToolTreeOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {
ChatNode, ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps, SelectionTarget, UseChatNodeTurnData,
} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import { createChatStore } from '../src/client/stores.ts'
import { ChatView } from '../src/client/chat/ChatView.tsx'
import { zh } from '../src/client/locales.ts'
import { assistantActionsSeqs, assistantBranchSeqs, deriveChatFlow, flowKeys, runningTurnStartTime } from '../src/client/chat/chat-flow.ts'
import { AssistantNodeView } from '../src/client/chat/AssistantNodeView.tsx'
import { CommandNodeView, ManualCompactionNodeView } from '../src/client/chat/CommandNodeView.tsx'
import {
CompactionNodeView, ContextMessageNodeView, RetryNodeView, TurnErrorNodeView,
UnknownNodeView, UserMessageNodeView,
} from '../src/client/chat/MessageItem.tsx'
import { TurnTailNodeView } from '../src/client/chat/TurnTailNodeView.tsx'
import { formatRunDuration } from '../src/client/chat/message-chrome.ts'
import { chatSnapshotFixture } from './chat-snapshot-fixture.ts'
afterEach(() => {
cleanup()
@@ -34,10 +43,11 @@ beforeEach(() => {
})
const SID = 's1' as SessionId
type RoutedChatNodeOwner = ChatNodeOwnerProps & { readonly node: ChatNode }
function snapshotBase(): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: chatSnapshotFixture(), nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
}
@@ -45,11 +55,21 @@ function snapshotBase(): ConversationSnapshot {
/** Scripted snapshot source: set() swaps the top-level object like the real Session. */
function makeSource(init?: Partial<ConversationSnapshot>) {
let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
const initial = { ...snapshotBase(), ...init }
let snap: ConversationSnapshot = {
...initial,
chat: init?.chat ?? chatSnapshotFixture(initial),
}
const subs = new Set<() => void>()
return {
set: (next: Partial<ConversationSnapshot>) => {
snap = { ...snap, ...next }
const merged = { ...snap, ...next }
snap = {
...merged,
chat: Object.hasOwn(next, 'chat') && next.chat !== undefined
? next.chat
: chatSnapshotFixture(merged, snap.chat),
}
for (const fn of [...subs]) fn()
},
source: {
@@ -73,7 +93,8 @@ const assistant = (seq: number, text: string, turn = 1): AssistantMessageNode =>
kind: 'assistant', seq, time: seq * 1_000, turn, step: 1, blocks: [{ kind: 'text', text }],
})
const retry = (seq: number): ModelRetryNode => ({
kind: 'model-retry', seq, time: seq * 1_000, turn: 1, step: 0,
kind: 'model-retry', retryId: 'chat-view-retry' as ModelRetryNode['retryId'],
seq, time: seq * 1_000, turn: 1, step: 0,
retryState: 'scheduled',
provider: 'mock', mode: 'normal', policyKey: 'mock-normal',
retry: 1, maxRetries: 2, delayMs: 450,
@@ -139,25 +160,97 @@ function makeHarness(init?: Partial<ConversationSnapshot>) {
// production; the view reads it through the PropsStore useStore share).
const chat = createChatStore().create()
const t = makeTranslate(zh, commonZh)
const toolOwners: ToolTreeOwnerProps[] = []
const renderSlot = ((key: string, owner: object, opts?: { fallback?: React.ReactNode }) => {
if (key !== 'conversation.chat.tool') return opts?.fallback ?? null
const tool = owner as ToolTreeOwnerProps
toolOwners.push(tool)
// Tool providers own their subtree. The host double carries only the
// semantic anchor required by ChatView's prepend-position contract.
return (
<div
data-testid={`tool-seat-${tool.callId}`}
data-chat-anchor-key={`call:${tool.callId}`}
data-chat-call-id={tool.callId}
>
{tool.toolName || '(unnamed)'}:{tool.callId}
</div>
const toolOwners: Array<{
callId: string
toolName: string
block: ToolCallBlock
selectedCallId: string | undefined
openFile: ChatNodeOwnerProps['openFile']
inspectCall: ChatNodeOwnerProps['inspectCall']
}> = []
const renderCommandSlot = ((_key: string, _owner: object, opts?: { fallback?: React.ReactNode }) =>
opts?.fallback ?? null) as unknown as React.ComponentProps<typeof CommandNodeView>['renderSlot']
const renderTurnTail = ((_key: string, _owner: object) => null) as unknown as
React.ComponentProps<typeof TurnTailNodeView>['renderSlotChain']
const renderTurnTailSlot = (() => null) as unknown as
React.ComponentProps<typeof TurnTailNodeView>['renderSlot']
const renderSlot = ((key: string, owner: object, opts?: {
fallback?: React.ReactNode
hookContext?: unknown
}) => {
if (key !== 'conversation.chat.node') return opts?.fallback ?? null
const nodeOwner = owner as RoutedChatNodeOwner
const nodeKey = opts?.hookContext as string | undefined
const useTurnData: UseChatNodeTurnData = dataKey => props.useSession((snapshot) => {
const location = nodeKey === undefined ? undefined : snapshot.chat.nodes.get(nodeKey)?.location
return location?.kind === 'turn' || location?.kind === 'step'
? location.turn.data.get(dataKey)
: undefined
})
const nodeProps = <Kind extends ChatNode['kind']>(): ChatNodeViewProps<Kind> => (
{ ...props, ...nodeOwner, useTurnData } as unknown as ChatNodeViewProps<Kind>
)
switch (nodeOwner.node.kind) {
case 'user':
case 'steering':
return <UserMessageNodeView {...nodeProps<'user' | 'steering'>()} />
case 'context':
return <ContextMessageNodeView {...nodeProps<'context'>()} />
case 'assistant-step':
return <AssistantNodeView {...nodeProps<'assistant-step'>()} />
case 'command':
return (
<CommandNodeView
{...nodeProps<'command'>()}
renderSlot={renderCommandSlot}
SessionProvider={props.SessionProvider}
/>
)
case 'manual-compaction':
return <ManualCompactionNodeView {...nodeProps<'manual-compaction'>()} />
case 'compaction':
return <CompactionNodeView {...nodeProps<'compaction'>()} />
case 'model-retry':
return <RetryNodeView {...nodeProps<'model-retry'>()} />
case 'turn-error':
return <TurnErrorNodeView {...nodeProps<'turn-error'>()} />
case 'turn-tail':
return (
<TurnTailNodeView
{...nodeProps<'turn-tail'>()}
renderSlot={renderTurnTailSlot}
renderSlotChain={renderTurnTail}
SessionProvider={props.SessionProvider}
/>
)
case 'unknown':
return <UnknownNodeView {...nodeProps<'unknown'>()} />
case 'tool-call': {
const block = nodeOwner.node.data.root
const toolName = 'kind' in block ? block.call?.name ?? '' : block.name
const tool = {
callId: block.callId,
toolName,
block,
selectedCallId: nodeOwner.selectedCallId,
openFile: nodeOwner.openFile,
inspectCall: nodeOwner.inspectCall,
}
toolOwners.push(tool)
return (
<div
data-testid={`tool-seat-${tool.callId}`}
data-chat-anchor-key={`call:${tool.callId}`}
data-chat-call-id={tool.callId}
>
{tool.toolName || '(unnamed)'}:{tool.callId}
</div>
)
}
default:
return opts?.fallback ?? null
}
}) as unknown as ChatViewSlotProps['renderSlot']
const renderSlotChain = ((_key: string, _owner: object, opts?: { fallback?: React.ReactNode }) =>
opts?.fallback ?? null) as unknown as ChatViewSlotProps['renderSlotChain']
// SessionProvider seat arrives with the session-scope child declaration;
// ChatView never invokes it (render-prop pass-through stub).
const SessionProviderStub: ChatViewSlotProps['SessionProvider'] = ({ children }) => <>{children(SID)}</>
@@ -172,7 +265,6 @@ function makeHarness(init?: Partial<ConversationSnapshot>) {
useStore: bindSnapshotSelector(chat),
actions: chat.actions,
renderSlot,
renderSlotChain,
SessionProvider: SessionProviderStub,
openDetails,
openFile,
@@ -180,6 +272,8 @@ function makeHarness(init?: Partial<ConversationSnapshot>) {
inspectCall,
chatScroll,
forkAt,
// Absent-service default; mention tests override with a real resolver.
fileMentions: () => undefined,
// Mirrors the real lookup chain (conversation namespace, then common).
t,
}
@@ -216,149 +310,45 @@ function installScrollMetrics(element: HTMLElement, initialHeight: number, clien
}
}
describe('chat-flow derivation', () => {
it('groups consecutive tool results and keeps stable keys', () => {
const nodes: ConversationNode[] = [
user(1, 'hi'), assistant(2, 'let me look'), toolResult(3, 'a'), toolResult(4, 'b'),
assistant(5, 'found'), toolResult(6, 'c'),
]
const items = deriveChatFlow(nodes)
expect(items.map(i => i.kind)).toEqual(['node', 'node', 'tool-group', 'node', 'tool-group'])
const group = items[2]!
expect(group.kind === 'tool-group' && group.results.map(r => r.callId)).toEqual(['a', 'b'])
expect(flowKeys(items)).toBe('n1|n2|g3|n5|g6')
expect(flowKeys(deriveChatFlow([...nodes, toolResult(7, 'd')]))).toBe('n1|n2|g3|n5|g6')
})
describe('Chat node rendering', () => {
it('reuses one stable row for consecutive retry turns', () => {
const first = retry(2)
const second = { ...retry(3), turn: 2, retry: 2 }
const initial = deriveChatFlow([user(1, 'try'), first])
const updated = deriveChatFlow([user(1, 'try'), first, second])
expect(flowKeys(initial)).toBe('n1|n2')
expect(flowKeys(updated)).toBe('n1|n2')
expect(updated).toHaveLength(2)
expect(updated[1]?.kind === 'node' && updated[1].node).toBe(second)
})
it('folds a successful /compact lifecycle into its explicitly linked checkpoint', () => {
const running = command({
seq: 1,
commandId: 'cmd-compact' as CommandNode['commandId'],
name: 'compact',
outcome: null,
it('threads the injected file-mention vocabulary into the closing prose only', () => {
const wrote = (seq: number, callId: string, path: string): ToolResultNode => ({
...toolResult(seq, callId, 'write'),
callView: {
card: 'diff', title: 'Write', diffs: [{ path, oldText: null, newText: 'x' }], locations: [{ path }],
},
})
expect(flowKeys(deriveChatFlow([user(0, 'before'), running]))).toBe('n0|ccmd-compact')
const settled = {
...running,
outcome: { kind: 'success' as const, text: 'Compacted 16 history items.', sourceEventSeq: 3 },
}
const checkpoint = compaction({ seq: 4, summaryEventSeq: 3 })
const items = deriveChatFlow([user(0, 'before'), settled, user(2, 'injected while compacting'), checkpoint])
expect(flowKeys(items)).toBe('n0|n2|ccmd-compact')
expect(items.at(-1)).toEqual({
kind: 'command-compaction',
key: 'ccmd-compact',
command: settled,
compaction: checkpoint,
const h = makeHarness({
nodes: [
user(1, 'build it'),
assistant(2, 'writing `report.html` now', 1),
wrote(3, 'w', 'site/report.html'),
assistant(4, 'Wrote `report.html`; `notes.md` untouched.', 1),
],
turnEnds: new Map([[1, 4]]),
})
})
it('does not split adjacent tool results around a folded /compact command', () => {
const folded = command({
seq: 2,
commandId: 'cmd-compact' as CommandNode['commandId'],
name: 'compact',
outcome: { kind: 'success', sourceEventSeq: 4 },
// Stub provider mirroring the real service: only produced files resolve.
h.props.fileMentions = owner => ({
resolve: (value) => {
if (value !== 'report.html') return undefined
return {
open: () => { h.openFile(`for-seq-${String(owner.seq)}/site/report.html`) },
label: '打开 site/report.html',
title: 'site/report.html',
}
},
})
const items = deriveChatFlow([
toolResult(1, 'a'),
folded,
toolResult(3, 'b'),
compaction({ seq: 5, summaryEventSeq: 4 }),
])
expect(flowKeys(items)).toBe('g1|ccmd-compact')
expect(
items[0]?.kind === 'tool-group' && items[0].results.map(result => result.callId),
).toEqual(['a', 'b'])
})
it('keeps automatic, unlinked, and ambiguously linked compactions as separate rows', () => {
const automatic = compaction({ seq: 2, summaryEventSeq: 1 })
expect(flowKeys(deriveChatFlow([automatic]))).toBe('n2')
const first = command({
seq: 3,
commandId: 'cmd-a' as CommandNode['commandId'],
name: 'compact',
outcome: { kind: 'success', sourceEventSeq: 9 },
})
const second = command({
seq: 4,
commandId: 'cmd-b' as CommandNode['commandId'],
name: 'compact',
outcome: { kind: 'success', sourceEventSeq: 9 },
})
const ambiguous = compaction({ seq: 10, summaryEventSeq: 9 })
expect(flowKeys(deriveChatFlow([first, second, ambiguous]))).toBe('ccmd-a|ccmd-b|n10')
const sole = command({
seq: 11,
commandId: 'cmd-sole' as CommandNode['commandId'],
name: 'compact',
outcome: { kind: 'success', sourceEventSeq: 12 },
})
const duplicateA = compaction({ seq: 13, summaryEventSeq: 12 })
const duplicateB = compaction({ seq: 14, summaryEventSeq: 12 })
expect(flowKeys(deriveChatFlow([sole, duplicateA, duplicateB]))).toBe('ccmd-sole|n13|n14')
})
it('skips render-nothing assistant nodes so tool runs stay one group', () => {
// A tool-call-only step message (and blank text/reasoning) renders nothing:
// it must not split the run into two groups with an empty line between.
const headsOnly: AssistantMessageNode = {
kind: 'assistant', seq: 4, time: 4_000, turn: 1, step: 2,
blocks: [{ kind: 'tool-call', callId: 'b', name: 'read', argsRaw: '{}' }, { kind: 'text', text: ' \n' }, { kind: 'reasoning', text: '' }],
}
const items = deriveChatFlow([toolResult(3, 'a'), headsOnly, toolResult(5, 'b')])
expect(flowKeys(items)).toBe('g3')
const group = items[0]!
expect(group.kind === 'tool-group' && group.results.map(r => r.callId)).toEqual(['a', 'b'])
// Interrupted and visible-content nodes still render (已停止 marker / prose).
expect(flowKeys(deriveChatFlow([toolResult(3, 'a'), { ...headsOnly, interrupted: true }, toolResult(5, 'b')]))).toBe('g3|n4|g5')
expect(flowKeys(deriveChatFlow([toolResult(3, 'a'), assistant(4, 'found'), toolResult(5, 'b')]))).toBe('g3|n4|g5')
})
it('assistantActionsSeqs keeps only the last content assistant per completed turn', () => {
const thinkOnly: AssistantMessageNode = {
kind: 'assistant', seq: 3, time: 3_000, turn: 1, step: 2,
blocks: [{ kind: 'reasoning', text: 'planning' }],
}
const nodes: ConversationNode[] = [
user(1, 'hi'),
assistant(2, 'looking', 1),
thinkOnly,
toolResult(4, 'a'),
assistant(5, 'done', 1),
user(6, 'again'),
assistant(7, 'second turn', 2),
]
expect([...assistantActionsSeqs(nodes, new Map([[1, 5], [2, 7]]))].sort((a, b) => a - b)).toEqual([5, 7])
// Turn 2 is still producing steps: its latest narration owns nothing, and
// the settled turn 1 keeps its seat.
expect([...assistantActionsSeqs(nodes, new Map([[1, 5]]))]).toEqual([5])
})
it('runningTurnStartTime selects the latest turn/start without a turn/end', () => {
expect(runningTurnStartTime(new Map([
[1, { startTime: 1_000, endTime: 5_000 }],
[2, { startTime: 6_000 }],
]))).toBe(6_000)
expect(runningTurnStartTime(new Map([
[1, { startTime: 1_000, endTime: 5_000 }],
[2, { startTime: 6_000, endTime: 9_000 }],
]))).toBeNull()
const view = render(<h.ChatView {...h.props} />)
// Exactly one live mention: the closing message links, the mid-turn
// narration stays inert code, and the unknown file resolves to nothing.
const mentions = view.container.querySelectorAll('code button')
expect(mentions).toHaveLength(1)
const mention = view.getByRole('button', { name: '打开 site/report.html' })
expect(mention.getAttribute('title')).toBe('site/report.html')
fireEvent.click(mention)
// The vocabulary was built from the closing message's own owner currency.
expect(h.openFile).toHaveBeenCalledWith('for-seq-4/site/report.html')
})
it('formatRunDuration localizes units and floors partial seconds', () => {
@@ -369,24 +359,6 @@ describe('chat-flow derivation', () => {
expect(formatRunDuration(125_000, t)).toBe('2分05秒')
})
it('assistantBranchSeqs keeps only content-assistant tails; user/steering tails own no branch', () => {
const interruptedThink: AssistantMessageNode = {
kind: 'assistant', seq: 4.1, time: 4_100, turn: 1, step: 2,
blocks: [{ kind: 'reasoning', text: 'bad path' }], interrupted: true,
}
const nodes: ConversationNode[] = [
user(1, 'first'),
assistant(2, 'answer before tools'),
toolResult(3, 'a'),
interruptedThink,
user(6, 'second'),
assistant(7, 'clean tail', 2),
user(10, 'user-only tail'),
user(13, 'steering tail'),
]
const seqs = assistantBranchSeqs(nodes, new Map([[1, 5], [2, 8], [3, 11], [4, 14]]))
expect([...seqs]).toEqual([7])
})
})
describe('ChatView', () => {
@@ -403,8 +375,8 @@ describe('ChatView', () => {
const h = makeHarness({ nodes: [user(9, 'first visible'), user(10, 'next visible')], hasMore: true })
const view = render(<h.ChatView {...h.props} />)
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
const first = view.container.querySelector('[data-chat-flow-key="n9"]') as HTMLDivElement
const next = view.container.querySelector('[data-chat-flow-key="n10"]') as HTMLDivElement
const first = view.container.querySelector('[data-chat-flow-key="fixture:user:9"]') as HTMLDivElement
const next = view.container.querySelector('[data-chat-flow-key="fixture:user:10"]') as HTMLDivElement
let firstTop = 100
let nextTop = 300
vi.spyOn(scroller, 'getBoundingClientRect').mockImplementation(
@@ -431,7 +403,7 @@ describe('ChatView', () => {
expect(scroller.scrollTop).toBe(590) // latest 90 + the anchored row's 500px prepend shift
})
it('renders the fixture main line: bubble, narration, grouped tool rows', () => {
it('renders the fixture main line as independently keyed business nodes', () => {
const h = makeHarness({
nodes: [user(1, 'do the thing'), assistant(2, 'running tools'), toolResult(3, 'a'), toolResult(4, 'b')],
})
@@ -444,14 +416,18 @@ describe('ChatView', () => {
key: row.getAttribute('data-chat-flow-key'),
kind: row.getAttribute('data-chat-flow-kind'),
}))).toEqual([
{ key: 'n1', kind: 'user' },
{ key: 'n2', kind: 'assistant' },
{ key: 'g3', kind: 'tool-group' },
{ key: 'fixture:user:1', kind: 'user' },
{ key: 'fixture:assistant:2', kind: 'assistant-step' },
{ key: 'fixture:tool:a', kind: 'tool-call' },
{ key: 'fixture:tool:b', kind: 'tool-call' },
])
expect([...view.container.querySelectorAll('[data-chat-call-id]')].map(row => row.getAttribute('data-chat-call-id')))
.toEqual(['a', 'b'])
expect([...view.container.querySelectorAll('[data-chat-anchor-key]')].map(row => row.getAttribute('data-chat-anchor-key')))
.toEqual(['node:1', 'node:2', 'call:a', 'call:b'])
.toEqual([
'fixture:user:1', 'fixture:assistant:2',
'fixture:tool:a', 'call:a', 'fixture:tool:b', 'call:b',
])
})
it('renders Host-pending steering at the flow tail and hands off to the durable node', () => {
@@ -518,14 +494,13 @@ describe('ChatView', () => {
act(() => {
h.set({ running: false, turnEnds: new Map([[1, 3]]) })
})
// The completed turn's transcript tail is the steering bubble, not the
// narration, so the assistant's branch action stays unavailable and the
// steering bubble still offers none.
// The Turn Tail belongs to the closed Turn, independently of a later
// steering bubble's placement in the Chat list.
const branchButtons = view.getAllByRole('button', { name: '在新对话中分支' })
expect(branchButtons).toHaveLength(1)
expect(branchButtons[0]!.getAttribute('aria-disabled')).toBe('true')
expect(branchButtons[0]!.getAttribute('aria-disabled')).toBeNull()
fireEvent.click(branchButtons[0]!)
expect(h.forkAt).not.toHaveBeenCalled()
expect(h.forkAt).toHaveBeenCalledWith(1)
})
it('keeps a later pending occurrence visible when it reuses a durable MessageId', () => {
@@ -566,7 +541,7 @@ describe('ChatView', () => {
expect(within(disclosure).getByRole('status').textContent).toBe('正在重试模型请求1/2 · 1s')
act(() => {
h.set({ nodes: [user(1, 'try'), retryNode, nextRetry] })
h.set({ nodes: [user(1, 'try'), nextRetry] })
})
expect(within(disclosure).getAllByRole('status')).toHaveLength(1)
expect(view.container.querySelector('details')).toBe(disclosure)
@@ -576,7 +551,6 @@ describe('ChatView', () => {
h.set({
nodes: [
user(1, 'try'),
retryNode,
{ ...nextRetry, retryState: 'started' },
context,
assistant(5, 'done'),
@@ -719,7 +693,7 @@ describe('ChatView', () => {
turnEnds: new Map([[1, 2]]),
})
const view = render(<h.ChatView {...h.props} />)
// One scope per message row; the CSS reveal keys off this attribute.
// The user row and the settled assistant's Turn Tail each own one clock scope.
expect(view.container.querySelectorAll('[data-time-hover-root]')).toHaveLength(2)
})
@@ -746,7 +720,29 @@ describe('ChatView', () => {
expect(h.forkAt.mock.calls).toEqual([[2]])
})
it('keeps branch visible but unavailable when tool and interrupted Think follow the response', () => {
it('disables fork when the indexed Turn has a later steering Node', () => {
const base = chatSnapshotFixture({
nodes: [user(1, 'question'), assistant(2, 'answer')],
turnEnds: new Map([[1, 4]]),
})
const chat = {
...base,
locations: {
getTurn: (turn: number) => turn === 1
? [...base.locations.getTurn(turn), 'fixture:steering:later']
: base.locations.getTurn(turn),
getStep: (turn: number, step: number) => base.locations.getStep(turn, step),
},
}
const h = makeHarness({ chat })
const view = render(<h.ChatView {...h.props} />)
const branch = view.getByRole('button', { name: '在新对话中分支' })
expect(branch.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(branch)
expect(h.forkAt).not.toHaveBeenCalled()
})
it('keeps final content actions but disables branch when Tool and interrupted Think follow it', () => {
const interruptedThink: AssistantMessageNode = {
kind: 'assistant', seq: 4.1, time: 4_100, turn: 1, step: 2,
blocks: [{ kind: 'reasoning', text: 'bad path' }], interrupted: true,
@@ -802,19 +798,13 @@ describe('ChatView', () => {
expect(view.container.querySelectorAll('h1')).toHaveLength(2)
})
it('streaming partial frames re-render only the tail (Profiler count)', () => {
it('streaming partial frames update the tail without replacing a sibling Tool row', () => {
const h = makeHarness({
nodes: [user(1, 'q'), assistant(2, 'old answer'), toolResult(3, 'a')],
})
let renders = 0
const counting = (
<Profiler id="chat" onRender={() => { renders += 1 }}>
<h.ChatView {...h.props} />
</Profiler>
)
const view = render(counting)
const before = renders
const beforeHtml = view.container.querySelector('[class*="toolGroup"]')!.innerHTML
const view = render(<h.ChatView {...h.props} />)
const tool = view.getByTestId('tool-seat-a')
const beforeHtml = tool.innerHTML
act(() => {
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'streaming…' }] } })
})
@@ -822,9 +812,8 @@ describe('ChatView', () => {
h.set({ partial: { turn: 2, step: 1, blocks: [{ kind: 'text', text: 'streaming… more' }] } })
})
expect(view.getByText('streaming… more')).toBeTruthy()
// Each chunk commits exactly one profiler pass (the tail), never a full-tree storm.
expect(renders - before).toBe(2)
expect(view.container.querySelector('[class*="toolGroup"]')!.innerHTML).toBe(beforeHtml)
expect(view.getByTestId('tool-seat-a')).toBe(tool)
expect(tool.innerHTML).toBe(beforeHtml)
})
it('streaming leaves neighbor tool rows and history items at zero re-renders', () => {
@@ -834,8 +823,9 @@ describe('ChatView', () => {
// Count renderSlot invocations: the memo boundary holds when CallRow does
// not re-render, so the row's renderSlot call count freezes during chunks.
let rowRenders = 0
h.props.renderSlot = ((key: string, _owner: object) => {
if (key !== 'conversation.chat.tool') return null
h.props.renderSlot = ((key: string, owner: object) => {
if (key !== 'conversation.chat.node'
|| (owner as RoutedChatNodeOwner).node.kind !== 'tool-call') return null
rowRenders += 1
return <div data-testid="counting-row" />
})
@@ -867,6 +857,54 @@ describe('ChatView', () => {
expect(view.getByRole('status').textContent).toBe('Deep diving...')
})
it('keeps the Tool renderer mounted when a running call settles into log order', () => {
const mounted = vi.fn()
const unmounted = vi.fn()
function StatefulToolNode({ node }: { readonly node: ChatNode<'tool-call'> }) {
useEffect(() => {
mounted()
return () => { unmounted() }
}, [])
const root = node.data.root
return (
<div data-testid="stateful-tool" data-state={'kind' in root ? 'settled' : 'running'}>
{root.callId}
</div>
)
}
const h = makeHarness({
nodes: [user(1, 'q'), assistant(4, 'later')],
runningCalls: [runningCall('r1')],
running: true,
})
h.props.renderSlot = ((key: string, owner: object, opts?: { fallback?: React.ReactNode }) => {
const routed = owner as RoutedChatNodeOwner
return key === 'conversation.chat.node' && routed.node.kind === 'tool-call'
? <StatefulToolNode node={routed.node} />
: opts?.fallback ?? null
}) as ChatViewSlotProps['renderSlot']
const view = render(<h.ChatView {...h.props} />)
const tool = view.getByTestId('stateful-tool')
const row = view.container.querySelector('[data-chat-flow-key="fixture:tool:r1"]')
expect(tool.dataset.state).toBe('running')
expect(mounted).toHaveBeenCalledTimes(1)
act(() => {
h.set({
nodes: [user(1, 'q'), toolResult(3, 'r1'), assistant(4, 'later')],
runningCalls: [],
running: false,
})
})
expect(view.getByTestId('stateful-tool')).toBe(tool)
expect(view.container.querySelector('[data-chat-flow-key="fixture:tool:r1"]')).toBe(row)
expect(tool.dataset.state).toBe('settled')
expect(mounted).toHaveBeenCalledTimes(1)
expect(unmounted).not.toHaveBeenCalled()
})
it('the running clock uses turn/start, ignores steering, and stays out of the live region', () => {
const startTime = Date.now() - 125_000
const trigger: UserMessageNode = { ...user(1, 'go'), time: startTime + 1 }
@@ -891,7 +929,7 @@ describe('ChatView', () => {
expect(status.textContent).toMatch(/^Deep diving\.\.\.2分0\d秒$/)
})
it('hands each ordered root call to the whole-Tool slot', () => {
it('hands each ordered root call to the keyed business-node slot', () => {
const block = toolResult(3, 'a')
const h = makeHarness({ nodes: [block] })
const calls: { key: string; owner: object; entryKey?: string }[] = []
@@ -902,14 +940,14 @@ describe('ChatView', () => {
render(<h.ChatView {...h.props} />)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({
key: 'conversation.chat.tool',
owner: { callId: 'a', toolName: 'bash', selectedCallId: undefined },
key: 'conversation.chat.node',
owner: { node: { kind: 'tool-call' }, selectedCallId: undefined },
entryKey: 'tool-call',
})
const owner = calls[0]?.owner as ToolTreeOwnerProps
expect(owner.block).toBe(block)
const owner = calls[0]?.owner as RoutedChatNodeOwner
expect((owner.node.data as { readonly root: ToolCallBlock }).root).toBe(block)
expect(owner.openFile).toBe(h.openFile)
expect(owner.inspectCall).toBe(h.inspectCall)
expect(calls[0]?.entryKey).toBeUndefined()
})
it('prepend preserves a semantic row; a trailing user node force-scrolls', () => {
@@ -919,7 +957,7 @@ describe('ChatView', () => {
// jsdom has no layout: fake the metrics the anchor math reads.
Object.defineProperty(scroller, 'scrollHeight', { value: 1000, writable: true })
Object.defineProperty(scroller, 'clientHeight', { value: 400, writable: true })
const anchored = view.container.querySelector('[data-chat-flow-key="n5"]') as HTMLDivElement
const anchored = view.container.querySelector('[data-chat-flow-key="fixture:user:5"]') as HTMLDivElement
let anchoredTop = 100
vi.spyOn(anchored, 'getBoundingClientRect').mockImplementation(
() => ({ top: anchoredTop, bottom: anchoredTop + 40 } as DOMRect),
@@ -936,60 +974,6 @@ describe('ChatView', () => {
expect(scroller.scrollTop).toBe(1600)
})
it('uses stable call identity when a prepend changes the tool-group key amid unrelated growth', () => {
const h = makeHarness({ nodes: [toolResult(5, 'late')], hasMore: true })
const view = render(<h.ChatView {...h.props} />)
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
let prepended = false
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.dataset.chatAnchorKey === 'call:late') {
const top = prepended ? 400 : 100
return { top, bottom: top + 40 } as DOMRect
}
return { top: 0, bottom: 200 } as DOMRect
})
try {
Object.defineProperty(scroller, 'scrollHeight', { value: 700, writable: true })
Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true })
readerScroll(scroller, 80)
fireEvent.click(view.getByText('加载更早'))
// Total height grows by 500, but only 300 belongs before the call row.
Object.defineProperty(scroller, 'scrollHeight', { value: 1_200, writable: true })
prepended = true
act(() => { h.set({ nodes: [toolResult(4, 'early'), toolResult(5, 'late')] }) })
expect(scroller.scrollTop).toBe(380)
} finally {
rect.mockRestore()
}
})
it('uses the latest retry identity when prepending an earlier retry changes the flow key', () => {
const h = makeHarness({ nodes: [retry(5)], hasMore: true })
const view = render(<h.ChatView {...h.props} />)
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
let prepended = false
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.dataset.chatAnchorKey === 'node:5') {
const top = prepended ? 400 : 100
return { top, bottom: top + 40 } as DOMRect
}
return { top: 0, bottom: 200 } as DOMRect
})
try {
Object.defineProperty(scroller, 'scrollHeight', { value: 700, writable: true })
Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true })
readerScroll(scroller, 80)
fireEvent.click(view.getByText('加载更早'))
Object.defineProperty(scroller, 'scrollHeight', { value: 1_200, writable: true })
prepended = true
act(() => { h.set({ nodes: [retry(4), retry(5)] }) })
expect(scroller.scrollTop).toBe(380)
expect(view.container.querySelector('[data-chat-flow-key="n4"][data-chat-anchor-key="node:5"]')).not.toBeNull()
} finally {
rect.mockRestore()
}
})
it('back-to-bottom cancels an in-flight paging anchor', () => {
const h = makeHarness({ nodes: [user(9, 'late')], hasMore: true })
const view = render(<h.ChatView {...h.props} />)
@@ -1136,7 +1120,7 @@ describe('ChatView', () => {
() => ({ top: 0, bottom: 500 } as DOMRect),
)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.dataset.chatAnchorKey === 'node:1') {
if (this.dataset.chatAnchorKey === 'fixture:user:1') {
return { top: anchorTop, bottom: anchorTop + 40 } as DOMRect
}
return { top: 0, bottom: 40 } as DOMRect
@@ -1175,12 +1159,12 @@ describe('ChatView', () => {
})
document.body.appendChild(host)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
if (this.dataset.chatAnchorKey === 'node:1') return { top: 300, bottom: 340 } as DOMRect
if (this.dataset.chatAnchorKey === 'fixture:user:1') return { top: 300, bottom: 340 } as DOMRect
return { top: 0, bottom: 500 } as DOMRect
})
try {
const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
h.chatScroll.save({ anchorKey: 'node:1', anchorTop: 80, scrollTop: 1_400 })
h.chatScroll.save({ anchorKey: 'fixture:user:1', anchorTop: 80, scrollTop: 1_400 })
const view = render(<h.ChatView {...h.props} />, { container: host })
expect(host.scrollTop).toBe(1_500)
expect(h.chatScroll.read()).toBeNull()

View File

@@ -0,0 +1,862 @@
import { describe, expect, it } from 'vitest'
import type {
ChatConversationViewNode, ChatSnapshot, ConversationEventInput,
ConversationNodeDefinition, ConversationViewDefinition,
} from '@deepseek-ai/dsh-client-runtime/client'
import { ConversationNodeAssembler } from '@deepseek-ai/dsh-client-runtime/client'
import { assistantDefinition } from '../src/client/conversation-nodes/assistant.ts'
import { chatViewDefinition } from '../src/client/conversation-nodes/chat-snapshot-builder.ts'
import { commandDefinition } from '../src/client/conversation-nodes/command.ts'
import { compactionDefinition } from '../src/client/conversation-nodes/compaction.ts'
import { unknownFallbackDefinition } from '../src/client/conversation-nodes/fallback.ts'
import { nextStepInboxDefinition, nextTurnInboxDefinition } from '../src/client/conversation-nodes/inbox.ts'
import { messageDefinition } from '../src/client/conversation-nodes/message.ts'
import { retryDefinition } from '../src/client/conversation-nodes/retry.ts'
import { toolDefinition } from '../src/client/conversation-nodes/tool.ts'
import { turnErrorDefinition } from '../src/client/conversation-nodes/turn-error.ts'
import { turnTailDefinition } from '../src/client/conversation-nodes/turn-tail.ts'
import type {
AssistantChatData, ManualCompactionChatData, RetryChatData, ToolChatData, TurnTailChatData,
} from '../src/client/contract/chat-nodes.ts'
const DEFINITIONS: readonly ConversationNodeDefinition[] = [
nextTurnInboxDefinition,
nextStepInboxDefinition,
messageDefinition,
assistantDefinition,
toolDefinition,
commandDefinition,
compactionDefinition,
retryDefinition,
turnErrorDefinition,
turnTailDefinition,
]
class TestEventDefinitions {
entries(): readonly ConversationNodeDefinition[] {
return DEFINITIONS
}
fallbackEntry(): ConversationNodeDefinition {
return unknownFallbackDefinition
}
}
class TestViewDefinitions {
entries(): readonly ConversationViewDefinition[] {
return [chatViewDefinition]
}
}
function at(
seq: number,
type: string,
data: unknown,
extra: Record<string, unknown> = {},
): ConversationEventInput {
return {
event: {
seq,
time: 1_700_000_000_000 + seq,
type,
data,
...extra,
} as unknown as ConversationEventInput['event'],
view: undefined,
}
}
function assembler(entries: readonly ConversationEventInput[] = [], hasMore = false): ConversationNodeAssembler {
const value = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
value.replaceWindow(entries, hasMore)
value.flush()
return value
}
function snapshot(value: ConversationNodeAssembler): ChatSnapshot {
const current = value.snapshot('chat') as ChatSnapshot | undefined
if (current === undefined) throw new Error('chat view was not registered')
return current
}
function node(value: ChatSnapshot, kind: string): ChatConversationViewNode | undefined {
return value.nodes.values().find(candidate => candidate.kind === kind)
}
function textMessage(id: string, text: string) {
return {
id,
role: 'user',
content: [{ type: 'text', text }],
source: { kind: 'user' },
}
}
function assistantMessage(id: string, text: string) {
return {
id,
role: 'assistant',
content: [{ type: 'text', text }],
source: { kind: 'model', provider: 'fake', model: 'fake' },
}
}
function toolResult(callId: string, text: string) {
return {
id: `result-${callId}`,
role: 'user',
source: { kind: 'tool', callId },
content: [{
type: 'tool-result',
toolCallId: callId,
content: [{ type: 'text', text }],
isError: false,
}],
}
}
describe('built-in conversation node Definitions', () => {
it('keeps one keyed Assistant node while streaming settles and materializes interruption from Location', () => {
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'assistant/chunk', {
turn: 1,
step: 1,
chunk: { type: 'text-delta', index: 0, text: 'streaming' },
}),
])
const runningSnapshot = snapshot(value)
const running = node(runningSnapshot, 'assistant-step')
expect(running?.data).toMatchObject({ status: 'running', blocks: [{ kind: 'text', text: 'streaming' }] })
const order = runningSnapshot.order
value.append(at(4, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('assistant-1', 'settled'),
}, { surfaceOp: 'append' }))
value.flush()
const settledSnapshot = snapshot(value)
const settled = node(settledSnapshot, 'assistant-step')
expect(settled?.key).toBe(running?.key)
expect(settledSnapshot.order).toBe(order)
expect(settled?.data).toMatchObject({ status: 'settled', blocks: [{ kind: 'text', text: 'settled' }] })
const interruptedValue = assembler([
at(10, 'turn/start', { turn: 2 }),
at(11, 'step/start', { turn: 2, step: 1 }),
at(12, 'assistant/chunk', {
turn: 2,
step: 1,
chunk: { type: 'text-delta', index: 0, text: 'partial' },
}),
at(13, 'step/end', { turn: 2, step: 1 }),
])
const interrupted = node(snapshot(interruptedValue), 'assistant-step')
expect(interrupted?.data).toMatchObject({ status: 'interrupted' })
expect((interrupted?.data as AssistantChatData).finalNode?.interrupted).toBe(true)
const hiddenValue = assembler([
at(20, 'turn/start', { turn: 3 }),
at(21, 'step/start', { turn: 3, step: 1 }),
at(22, 'llm/retry', {
retryId: 'retry-hidden',
turn: 3,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 1,
maxRetries: 2,
delayMs: 10,
failure: { code: 'TRANSPORT', message: 'temporary' },
}),
])
expect(node(snapshot(hiddenValue), 'assistant-step')).toBeUndefined()
const toolOnlyValue = assembler([
at(30, 'turn/start', { turn: 4 }),
at(31, 'step/start', { turn: 4, step: 1 }),
at(32, 'assistant/chunk', {
turn: 4,
step: 1,
chunk: { type: 'tool-call-delta', index: 0, id: 'call-1', name: 'read', argumentsDelta: '' },
}),
at(33, 'assistant/message', {
turn: 4,
step: 1,
message: {
...assistantMessage('assistant-tool-only', ''),
content: [{ type: 'tool-call', id: 'call-1', name: 'read', arguments: '{}' }],
},
}, { surfaceOp: 'append' }),
])
const toolOnlySnapshot = snapshot(toolOnlyValue)
expect(toolOnlySnapshot.order).toEqual([])
expect(node(toolOnlySnapshot, 'assistant-step')?.visibility).toBe('hidden')
expect(toolOnlySnapshot.legacy.nodes).toMatchObject([{
kind: 'assistant',
seq: 33,
timing: { firstTokenTime: 1_700_000_000_032 },
}])
const interruptedToolOnlyValue = assembler([
at(35, 'turn/start', { turn: 5 }),
at(36, 'step/start', { turn: 5, step: 1 }),
at(37, 'assistant/chunk', {
turn: 5,
step: 1,
chunk: { type: 'tool-call-delta', index: 0, id: 'call-2', name: 'read', argumentsDelta: '' },
}),
at(38, 'step/end', { turn: 5, step: 1 }),
])
const interruptedToolOnly = node(snapshot(interruptedToolOnlyValue), 'assistant-step')
expect(interruptedToolOnly?.visibility).toBe('visible')
expect(interruptedToolOnly?.data).toMatchObject({ status: 'interrupted' })
const retryTimingValue = assembler([
at(50, 'turn/start', { turn: 6 }),
at(51, 'step/start', { turn: 6, step: 1 }),
at(52, 'assistant/chunk', {
turn: 6,
step: 1,
chunk: { type: 'text-delta', index: 0, text: 'first attempt' },
}),
at(53, 'llm/retry', {
retryId: 'retry-timing', turn: 6, step: 1, provider: 'fake', mode: 'normal',
policyKey: 'fake-normal', retry: 1, maxRetries: 2, delayMs: 10,
failure: { code: 'TRANSPORT', message: 'temporary' },
}),
at(54, 'assistant/chunk', {
turn: 6,
step: 1,
chunk: { type: 'text-delta', index: 0, text: 'second attempt' },
}),
at(55, 'assistant/message', {
turn: 6,
step: 1,
message: assistantMessage('assistant-retried', 'done'),
}, { surfaceOp: 'append' }),
])
const retryTiming = (node(snapshot(retryTimingValue), 'assistant-step')?.data as AssistantChatData).finalNode
expect(retryTiming?.timing?.firstTokenTime).toBe(1_700_000_000_052)
const partialWindow = assembler([
at(40, 'assistant/chunk', {
turn: 5,
step: 2,
chunk: { type: 'text-delta', index: 0, text: 'loaded partial' },
}),
at(41, 'step/end', { turn: 5, step: 2 }),
], true)
const recovered = node(snapshot(partialWindow), 'assistant-step')
expect(recovered?.data).toMatchObject({
status: 'interrupted',
blocks: [{ kind: 'text', text: 'loaded partial' }],
})
})
it('keeps one keyed Tool node from running through settlement and replays nested dispatch after prepend', () => {
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'tool/call', { turn: 1, step: 1, callId: 'root', name: 'code', arguments: '{}' }),
])
const runningSnapshot = snapshot(value)
const running = node(runningSnapshot, 'tool-call')
expect((running?.data as ToolChatData).root).toMatchObject({ callId: 'root', name: 'code' })
const order = runningSnapshot.order
value.append(at(4, 'tool/result', {
turn: 1,
step: 1,
message: toolResult('root', 'done'),
}, { surfaceOp: 'append' }))
value.flush()
const settledSnapshot = snapshot(value)
const settled = node(settledSnapshot, 'tool-call')
expect(settled?.key).toBe(running?.key)
expect(settledSnapshot.order).toBe(order)
expect((settled?.data as ToolChatData).root).toMatchObject({ kind: 'tool-result', callId: 'root' })
const history = assembler([
at(14, 'tool/code-dispatch-start', {
rootCallId: 'history-root',
parentCallId: 'history-root',
subCallId: 'child',
name: 'read',
arguments: { path: 'README.md' },
}),
at(15, 'tool/code-dispatch', {
rootCallId: 'history-root',
parentCallId: 'history-root',
subCallId: 'child',
name: 'read',
arguments: { path: 'README.md' },
isError: false,
content: [{ type: 'text', text: 'contents' }],
}),
at(16, 'tool/result', {
turn: 2,
step: 1,
message: toolResult('history-root', 'root done'),
}, { surfaceOp: 'append' }),
], true)
const before = node(snapshot(history), 'tool-call')
expect((before?.data as ToolChatData).root.subCalls).toMatchObject([
{ kind: 'tool-result', callId: 'child', call: { name: 'read' } },
])
history.prepend([
at(10, 'turn/start', { turn: 2 }),
at(11, 'step/start', { turn: 2, step: 1 }),
at(13, 'tool/call', {
turn: 2,
step: 1,
callId: 'history-root',
name: 'code',
arguments: '{}',
}),
], false)
history.flush()
const after = node(snapshot(history), 'tool-call')
expect(after?.key).toBe(before?.key)
expect((after?.data as ToolChatData).root.subCalls).toMatchObject([
{ kind: 'tool-result', callId: 'child', call: { name: 'read' } },
])
const firstChild = (after?.data as ToolChatData).root.subCalls[0]
history.append(at(17, 'tool/code-dispatch-start', {
rootCallId: 'history-root',
parentCallId: 'history-root',
subCallId: 'second-child',
name: 'write',
arguments: { path: 'out.txt' },
}))
history.flush()
const withSecondChild = node(snapshot(history), 'tool-call')
expect((withSecondChild?.data as ToolChatData).root.subCalls[0]).toBe(firstChild)
})
it('prepends an older turn without replacing already materialized nodes', () => {
const value = assembler([
at(20, 'turn/start', { turn: 2 }),
at(21, 'user/message', textMessage('newer-user', 'newer'), { surfaceOp: 'append' }),
at(22, 'step/start', { turn: 2, step: 1 }),
at(23, 'assistant/message', {
turn: 2,
step: 1,
message: assistantMessage('newer-assistant', 'newer answer'),
}, { surfaceOp: 'append' }),
at(24, 'step/end', { turn: 2, step: 1 }),
at(25, 'turn/end', { turn: 2, reason: { kind: 'completed' } }),
], true)
const before = snapshot(value)
const existing = before.nodes.get(before.order.find(key => before.nodes.get(key)?.kind === 'assistant-step') ?? '')
const store = before.nodes
value.prepend([
at(10, 'turn/start', { turn: 1 }),
at(11, 'user/message', textMessage('older-user', 'older'), { surfaceOp: 'append' }),
at(12, 'step/start', { turn: 1, step: 1 }),
at(13, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('older-assistant', 'older answer'),
}, { surfaceOp: 'append' }),
at(14, 'step/end', { turn: 1, step: 1 }),
at(15, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
], false)
value.flush()
const after = snapshot(value)
expect(after.nodes).toBe(store)
expect(after.nodes.get(existing?.key ?? '')).toBe(existing)
expect(after.order).toHaveLength(before.order.length + 3)
expect(after.order.map(key => after.nodes.get(key)?.kind)).toEqual([
'user', 'assistant-step', 'turn-tail',
'user', 'assistant-step', 'turn-tail',
])
})
it('appends a later turn without replacing nodes from the completed turn', () => {
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }),
at(3, 'step/start', { turn: 1, step: 1 }),
at(4, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('first-assistant', 'first answer'),
}, { surfaceOp: 'append' }),
at(5, 'step/end', { turn: 1, step: 1 }),
at(6, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
])
const before = snapshot(value)
const oldOrder = before.order
const oldNodes = oldOrder.map(key => before.nodes.get(key))
value.append(at(7, 'turn/start', { turn: 2 }))
value.append(at(8, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }))
value.flush()
const after = snapshot(value)
expect(after.nodes).toBe(before.nodes)
expect(after.order.slice(0, oldOrder.length)).toEqual(oldOrder)
expect(oldOrder.map(key => after.nodes.get(key))).toEqual(oldNodes)
expect(after.order.map(key => after.nodes.get(key)?.kind)).toEqual([
'user', 'assistant-step', 'turn-tail', 'user',
])
})
it('keeps branching unavailable when a tool result follows the closing Assistant', () => {
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('assistant-before-tool', 'running a tool'),
}, { surfaceOp: 'append' }),
at(4, 'tool/call', { turn: 1, step: 1, callId: 'late-tool', name: 'read', arguments: '{}' }),
at(5, 'tool/result', {
turn: 1,
step: 1,
message: toolResult('late-tool', 'done'),
}, { surfaceOp: 'append' }),
at(6, 'step/end', { turn: 1, step: 1 }),
at(7, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
])
const tail = node(snapshot(value), 'turn-tail')?.data as TurnTailChatData
expect(tail.closing?.finalNode.seq).toBe(3)
expect(tail.branchUnavailable).toBe(true)
})
it('replays inbox predecessors after prepend and reclassifies the dependent message as steering', () => {
const value = assembler([
at(3, 'user/message', textMessage('steer-1', 'change direction'), { surfaceOp: 'append' }),
], true)
const before = node(snapshot(value), 'user')
expect(before).toBeDefined()
value.prepend([
at(1, 'agent/inbox/spliced', {
target: 'next-step',
start: 0,
inserted: [textMessage('steer-1', 'change direction')],
}),
at(2, 'agent/inbox/spliced', {
target: 'next-step',
start: 0,
removedCount: 1,
inserted: [],
}),
], false)
value.flush()
const after = node(snapshot(value), 'steering')
expect(after?.key).toBe(before?.key)
expect(after?.data).toMatchObject({ kind: 'steering', messageId: 'steer-1' })
expect(node(snapshot(value), 'user')).toBeUndefined()
})
it('orders claimed steering after the finalized Turn tail', () => {
const steering = textMessage('steer-after-answer', 'change direction')
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('assistant-before-steering', 'initial answer'),
}, { surfaceOp: 'append' }),
at(4, 'agent/inbox/spliced', {
target: 'next-step',
start: 0,
inserted: [steering],
}),
at(5, 'agent/inbox/spliced', {
target: 'next-step',
start: 0,
removedCount: 1,
inserted: [],
}),
at(6, 'user/message', steering, { surfaceOp: 'append' }),
at(7, 'step/end', { turn: 1, step: 1 }),
at(8, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
])
const current = snapshot(value)
const steeringNode = node(current, 'steering')
expect(steeringNode).toBeDefined()
expect(current.locations.getTurn(1).at(-1)).toBe(steeringNode?.key)
})
it('classifies appended producer context from durable source metadata', () => {
const value = assembler([
at(1, 'user/message', {
...textMessage('skill-context', 'follow these instructions'),
source: { kind: 'skill-invocation', name: 'demo-skill', form: 'instructions' },
}, { surfaceOp: 'append' }),
])
expect(node(snapshot(value), 'context')?.data).toMatchObject({
kind: 'context',
provenance: { role: 'inject', label: 'demo-skill' },
form: 'instructions',
})
})
it('keeps replacement copies out of Chat business nodes', () => {
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'user/message', {
...textMessage('replacement-user', 'model-only context'),
source: { kind: 'plugin', plugin: 'foreign' },
}, { surfaceOp: { op: 'replace', start: 1, end: 1 } }),
at(4, 'assistant/message', {
turn: 1,
step: 1,
message: assistantMessage('replacement-assistant', 'rewritten answer'),
}, { surfaceOp: { op: 'replace', start: 2, end: 2 } }),
at(5, 'tool/call', { turn: 1, step: 1, callId: 'root', name: 'read', arguments: '{}' }),
at(6, 'tool/result', {
turn: 1,
step: 1,
message: toolResult('root', 'pruned result'),
}, { surfaceOp: { op: 'replace', start: 3, end: 3 } }),
])
const current = snapshot(value)
expect(node(current, 'user')).toBeUndefined()
expect(node(current, 'context')).toBeUndefined()
expect(node(current, 'assistant-step')).toBeUndefined()
expect((node(current, 'tool-call')?.data as ToolChatData).root).not.toHaveProperty('kind')
})
it('assembles retry chains and keeps manual and automatic compaction ownership separate', () => {
const retry = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'llm/retry', {
retryId: 'retry-1',
turn: 1,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 1,
maxRetries: 2,
delayMs: 10,
failure: { code: 'TRANSPORT', message: 'first' },
}),
at(4, 'llm/retry-started', { retryId: 'retry-1', turn: 1, step: 1, retry: 1 }),
at(5, 'llm/retry', {
retryId: 'retry-1',
turn: 1,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 2,
maxRetries: 2,
delayMs: 20,
failure: { code: 'TRANSPORT', message: 'second' },
}),
at(6, 'step/end', { turn: 1, step: 1 }),
at(7, 'turn/end', {
turn: 1,
reason: { kind: 'error', error: { code: 'TRANSPORT', message: 'failed' } },
}),
])
const retryNode = node(snapshot(retry), 'model-retry')
const retryData = retryNode?.data as RetryChatData
expect(retryData.attempts.map(attempt => attempt.retryState)).toEqual(['started', 'cancelled'])
expect(node(snapshot(retry), 'turn-error')).toBeUndefined()
const compactions = assembler([
at(10, 'command/run', {
commandId: 'command-1',
name: 'compact',
source: { kind: 'user' },
}),
at(11, 'compact/start', {
compactionId: 'manual-1',
sourceCommandId: 'command-1',
turn: null,
}),
at(12, 'compact/summary', {
compactionId: 'manual-1',
sourceCommandId: 'command-1',
summary: [{ type: 'text', text: 'manual summary' }],
shadowedSeqs: [1, 2],
shadowedTokenCount: 100,
}),
at(13, 'user/message', {
...textMessage('manual-checkpoint', 'checkpoint'),
source: {
kind: 'plugin',
plugin: 'compact',
compactionId: 'manual-1',
sourceCommandId: 'command-1',
},
}, { surfaceOp: { op: 'replace', start: 1, end: 2 } }),
at(14, 'compact/end', {
compactionId: 'manual-1',
sourceCommandId: 'command-1',
turn: null,
}),
at(15, 'command/done', {
commandId: 'command-1',
kind: 'success',
sourceEventSeq: 12,
}),
at(20, 'compact/start', { compactionId: 'automatic-1', turn: null }),
at(21, 'compact/summary', {
compactionId: 'automatic-1',
summary: [{ type: 'text', text: 'automatic summary' }],
shadowedSeqs: [3, 4],
shadowedTokenCount: 200,
}),
at(22, 'user/message', {
...textMessage('automatic-checkpoint', 'checkpoint'),
source: { kind: 'plugin', plugin: 'compact', compactionId: 'automatic-1' },
}, { surfaceOp: { op: 'replace', start: 3, end: 4 } }),
at(23, 'compact/end', { compactionId: 'automatic-1', turn: null }),
])
const manual = node(snapshot(compactions), 'manual-compaction')
expect((manual?.data as ManualCompactionChatData).compaction).toMatchObject({
summary: 'manual summary',
summaryEventSeq: 12,
})
const automatic = node(snapshot(compactions), 'compaction')
expect(automatic?.data).toMatchObject({ summary: 'automatic summary', summaryEventSeq: 21 })
expect(snapshot(compactions).nodes.values().filter(candidate => candidate.kind === 'compaction')).toHaveLength(1)
})
it('fills a landed compaction marker when an older page supplies its summary', () => {
const value = assembler([
at(13, 'user/message', {
...textMessage('checkpoint', 'checkpoint'),
source: { kind: 'plugin', plugin: 'compact', compactionId: 'compact-1' },
}, { surfaceOp: { op: 'replace', start: 1, end: 8 } }),
], true)
const before = node(snapshot(value), 'compaction')
expect(before?.data).toMatchObject({ summary: null, summaryEventSeq: null })
value.prepend([
at(9, 'compact/start', { compactionId: 'compact-1', turn: null }),
at(10, 'compact/summary', {
compactionId: 'compact-1',
summary: [
{ type: 'text', text: 'older ' },
{ type: 'image', data: 'ignored' },
{ type: 'text', text: 'summary' },
],
shadowedSeqs: [1, 2, 3],
shadowedTokenCount: 42,
}),
], false)
value.flush()
const after = node(snapshot(value), 'compaction')
expect(after?.key).toBe(before?.key)
expect(after?.data).toMatchObject({
summary: 'older summary',
summaryEventSeq: 10,
shadowedItemCount: 3,
shadowedTokenCount: 42,
})
})
it('renders a historical compaction when its start remains outside the loaded window', () => {
const value = assembler([
at(10, 'compact/summary', {
compactionId: 'compact-windowed',
summary: [{ type: 'text', text: 'loaded summary' }],
shadowedSeqs: [1, 2, 3],
shadowedTokenCount: 42,
}),
at(11, 'user/message', {
...textMessage('checkpoint-windowed', 'checkpoint'),
source: { kind: 'plugin', plugin: 'compact', compactionId: 'compact-windowed' },
}, { surfaceOp: { op: 'replace', start: 1, end: 3 } }),
], true)
expect(node(snapshot(value), 'compaction')?.data).toMatchObject({
summary: 'loaded summary',
summaryEventSeq: 10,
shadowedItemCount: 3,
shadowedTokenCount: 42,
})
})
it('ignores legacy compaction transactions without correlation ids', () => {
const value = assembler([
at(10, 'compact/start', { turn: null }),
at(11, 'compact/end', { turn: null, error: 'This operation was aborted' }),
at(20, 'compact/start', { turn: null }),
at(21, 'compact/summary', {
summary: [{ type: 'text', text: 'legacy summary' }],
shadowedSeqs: [1, 2, 3],
shadowedTokenCount: 42,
}),
at(22, 'user/message', {
...textMessage('legacy-checkpoint', 'checkpoint'),
source: { kind: 'plugin', plugin: 'compact' },
}, { surfaceOp: { op: 'replace', start: 1, end: 3 } }),
at(23, 'compact/end', { turn: null }),
], true)
expect(node(snapshot(value), 'compaction')).toBeUndefined()
})
it('ignores legacy retry and code-dispatch events without correlation ids', () => {
const value = assembler([
at(10, 'llm/retry', {
turn: 1,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 1,
maxRetries: 2,
delayMs: 10,
failure: { code: 'TRANSPORT', message: 'first legacy retry' },
}),
at(11, 'llm/retry-started', { turn: 1, step: 1, retry: 1 }),
at(20, 'llm/retry', {
turn: 2,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 1,
maxRetries: 2,
delayMs: 10,
failure: { code: 'TRANSPORT', message: 'second legacy retry' },
}),
at(30, 'tool/code-dispatch-start', {
parentCallId: 'root',
subCallId: 'child',
name: 'legacy-subcall',
arguments: {},
}),
at(31, 'tool/code-dispatch', {
parentCallId: 'root',
subCallId: 'child',
name: 'legacy-subcall',
arguments: {},
content: [],
}),
], true)
expect(node(snapshot(value), 'model-retry')).toBeUndefined()
expect(node(snapshot(value), 'tool-call')).toBeUndefined()
})
it('suppresses a turn error when the loaded tail contains only a later retry attempt', () => {
const value = assembler([
at(5, 'llm/retry', {
retryId: 'retry-paged',
turn: 1,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 2,
maxRetries: 2,
delayMs: 20,
failure: { code: 'TRANSPORT', message: 'second' },
}),
at(6, 'step/end', { turn: 1, step: 1 }),
at(7, 'turn/end', {
turn: 1,
reason: { kind: 'error', error: { code: 'TRANSPORT', message: 'failed' } },
}),
], true)
expect(node(snapshot(value), 'model-retry')).toBeUndefined()
expect(node(snapshot(value), 'turn-error')).toBeUndefined()
value.prepend([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'llm/retry', {
retryId: 'retry-paged',
turn: 1,
step: 1,
provider: 'fake',
mode: 'normal',
policyKey: 'fake-normal',
retry: 1,
maxRetries: 2,
delayMs: 10,
failure: { code: 'TRANSPORT', message: 'first' },
}),
at(4, 'llm/retry-started', {
retryId: 'retry-paged', turn: 1, step: 1, retry: 1,
}),
], false)
value.flush()
const retry = node(snapshot(value), 'model-retry')
expect((retry?.data as RetryChatData).attempts).toHaveLength(2)
expect(node(snapshot(value), 'turn-error')).toBeUndefined()
})
it('preserves nested Tools and manual compaction evidence when their start events are outside the window', () => {
const value = assembler([
at(12, 'tool/code-dispatch-start', {
rootCallId: 'root', parentCallId: 'root', subCallId: 'child', name: 'read_file', arguments: { path: 'a' },
}),
at(13, 'tool/code-dispatch', {
rootCallId: 'root', parentCallId: 'root', subCallId: 'child', name: 'read_file', arguments: { path: 'a' },
isError: false, content: [{ type: 'text', text: 'child result' }],
}),
at(14, 'tool/result', {
turn: 1,
step: 1,
message: toolResult('root', 'root result'),
}, { surfaceOp: 'append' }),
at(20, 'compact/summary', {
compactionId: 'manual-1',
sourceCommandId: 'command-1',
summary: [{ type: 'text', text: 'manual summary' }],
shadowedSeqs: [1, 2],
shadowedTokenCount: 100,
}),
at(21, 'user/message', {
...textMessage('manual-checkpoint', 'checkpoint'),
source: {
kind: 'plugin',
plugin: 'compact',
compactionId: 'manual-1',
sourceCommandId: 'command-1',
},
}, { surfaceOp: { op: 'replace', start: 1, end: 2 } }),
at(22, 'command/done', {
commandId: 'command-1',
kind: 'success',
sourceEventSeq: 20,
}),
], true)
const tool = node(snapshot(value), 'tool-call')
const root = (tool?.data as ToolChatData).root
expect(root.subCalls).toHaveLength(1)
expect(root.subCalls[0]).toMatchObject({ callId: 'child', kind: 'tool-result' })
const manual = node(snapshot(value), 'manual-compaction')
expect((manual?.data as ManualCompactionChatData)).toMatchObject({
command: { commandId: 'command-1', name: 'compact', outcome: { kind: 'success' } },
compaction: { summary: 'manual summary', summaryEventSeq: 20 },
})
})
})

View File

@@ -3,7 +3,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
import { createSnapshotStore, EMPTY_CHAT_SNAPSHOT } from '@deepseek-ai/dsh-client-runtime/client'
import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
import type { ConversationSnapshot, SessionId, SessionListState, WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client'
import type { SessionProviderComponent } from '@deepseek-ai/dsh-client-ui-slots'
@@ -15,6 +15,7 @@ import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/ch
import { StatsLine } from '../src/client/chat/StatsLine.tsx'
import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx'
import { zh } from '../src/client/locales.ts'
import { chatSnapshotFixture } from './chat-snapshot-fixture.ts'
// Mirrors the real lookup chain (conversation namespace, then common).
const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh)
@@ -40,14 +41,15 @@ const SessionProviderStub: SessionProviderComponent = ({ children }) => children
/** Observe the owner currency without importing the Tool details renderer. */
function renderToolDetailsProbe(owners?: DetailsToolOwnerProps[]): DetailsSlotProps['renderSlot'] {
return (_key, owner) => {
owners?.push(owner as DetailsToolOwnerProps)
owners?.push(owner as unknown as DetailsToolOwnerProps)
return <div data-testid="tool-details-seat" />
}
}
function snapshotBase(): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
}
@@ -69,11 +71,16 @@ describe('render branch tails', () => {
it('StatsLine counts window nodes but drops every token group without a projection', () => {
// Node `usage` is deliberately ignored: billing rides the durable
// tokenUsage projection, so an absent projection leaves counts only.
const nodes = [
{ kind: 'assistant', seq: 1, time: 1, turn: 1, step: 1, blocks: [] },
{ kind: 'assistant', seq: 2, time: 2, turn: 1, step: 2, blocks: [], usage: { inputTokens: 4, outputTokens: 6 } },
{ kind: 'assistant', seq: 3, time: 3, turn: 2, step: 1, blocks: [], usage: { inputTokens: 5 } },
] as const
const snap = {
...snapshotBase(),
chat: chatSnapshotFixture({ nodes }),
nodes: [
{ kind: 'assistant', seq: 1, turn: 1, step: 1, blocks: [] },
{ kind: 'assistant', seq: 2, turn: 1, step: 2, blocks: [], usage: { inputTokens: 4, outputTokens: 6 } },
{ kind: 'assistant', seq: 3, turn: 2, step: 1, blocks: [], usage: { inputTokens: 5 } },
...nodes,
],
}
const source = { getSnapshot: () => snap, subscribe: () => () => {} }
@@ -146,6 +153,7 @@ describe('render branch tails', () => {
}],
}],
}]
snap.chat = chatSnapshotFixture({ runningCalls: snap.runningCalls })
const chat = createChatStore().create()
chat.actions.select({ turnSeq: 9, callId: 'p1:code:1:code:1', toolName: 'read' } satisfies SelectionTarget)
const emptyList = createSnapshotStore<SessionListState>(

View File

@@ -1,13 +1,13 @@
// @vitest-environment jsdom
// InputBar behavior over the machine wiring: Enter-send semantics (IME guard,
// Shift newline, busy Enter policy, Ctrl/Meta steering, repeat suppression), running
// semantics (input stays free; primary turns stop), the machine pending lock,
// semantics (input stays free; continuable children keep Send beside Stop), the machine pending lock,
// decoration backdrop, error/notice strips, and the focus-keeping mousedown.
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
import { createSnapshotStore, EMPTY_CHAT_SNAPSHOT } from '@deepseek-ai/dsh-client-runtime/client'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import type { ClientContext, ConversationSnapshot, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
@@ -35,7 +35,8 @@ const SID = 's1' as SessionId
function snapshotOf(overrides: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
promptError: null, blank: false, subagent: null, lastAgentError: null,
@@ -143,11 +144,14 @@ function bench(over?: BenchOptions) {
}
const view = render(<InputBar {...props} />)
const textarea = view.container.querySelector('textarea')!
const stopping = over?.running === true && over.subagent === undefined
const primaryStops = over?.running === true && over.subagent === undefined
const button = view.container.querySelector<HTMLButtonElement>(
`button[aria-label="${stopping ? '停止生成' : '发送消息'}"]`,
`button[aria-label="${primaryStops ? '停止生成' : '发送消息'}"]`,
)!
return { view, textarea, button, props, sink, shell, wiring: shell, session, stop, slotCalls, menuLauncher }
const interruptButton = view.container.querySelector<HTMLButtonElement>('button[aria-label="停止生成"]')
return {
view, textarea, button, interruptButton, props, sink, shell, wiring: shell, session, stop, slotCalls, menuLauncher,
}
}
describe('Enter semantics', () => {
@@ -222,10 +226,10 @@ describe('Enter semantics', () => {
})
})
describe('running and lock semantics (queue cut 1)', () => {
describe('running and lock semantics', () => {
it('running keeps the input free (typing + Enter queue) while the primary turns stop', () => {
const { textarea, button, stop, sink } = bench({ running: true, draft: '排队消息' })
expect(textarea.disabled).toBe(false) // running no longer locks
expect(textarea.disabled).toBe(false)
fireEvent.change(textarea, { target: { value: '排队消息2' } })
fireEvent.keyDown(textarea, { key: 'Enter' })
expect(sink).toHaveBeenCalledWith('排队消息2', 'queue')
@@ -250,8 +254,8 @@ describe('running and lock semantics (queue cut 1)', () => {
expect(ctrl.sink).toHaveBeenCalledWith('also queue', 'queue')
})
it('running subagent primary admits a follow-up instead of exposing Stop', () => {
const { button, sink, stop } = bench({
it('running continuable subagent keeps Send beside an independent Stop', () => {
const { button, interruptButton, textarea, sink, stop } = bench({
running: true,
draft: '后续消息',
subagent: {
@@ -264,22 +268,53 @@ describe('running and lock semantics (queue cut 1)', () => {
},
})
expect(button.getAttribute('aria-label')).toBe('发送消息')
expect(interruptButton).not.toBeNull()
expect(textarea.disabled).toBe(false)
fireEvent.click(button)
expect(sink).toHaveBeenCalledWith('后续消息', 'queue')
expect(stop).not.toHaveBeenCalled()
fireEvent.click(interruptButton!)
expect(stop).toHaveBeenCalledTimes(1)
})
const empty = bench({
it('parent-offline running continuable locks Send but keeps independent Stop usable', () => {
const { button, interruptButton, textarea, stop, view } = bench({
running: true,
draft: '',
subagent: {
address: {
parentSessionId: 'parent' as SessionId,
childSessionId: SID,
mode: 'continuable',
},
parentAvailable: false,
},
})
expect(textarea.disabled).toBe(true)
expect(textarea.placeholder).toBe('父会话已离线,无法继续发送;仍可停止当前运行')
expect((view.getByLabelText('命令') as HTMLButtonElement).disabled).toBe(true)
expect(button.getAttribute('aria-label')).toBe('发送消息')
expect(button.disabled).toBe(true)
expect(interruptButton?.disabled).toBe(false)
fireEvent.click(interruptButton!)
expect(stop).toHaveBeenCalledTimes(1)
})
it('running one-shot subagent never exposes Stop', () => {
const { button, interruptButton, stop } = bench({
running: true,
draft: '不可停止',
subagent: {
address: {
parentSessionId: 'parent' as SessionId,
childSessionId: SID,
mode: 'one-shot',
},
parentAvailable: true,
},
})
expect(empty.button.disabled).toBe(true)
expect(button.getAttribute('aria-label')).toBe('发送消息')
expect(interruptButton).toBeNull()
expect(stop).not.toHaveBeenCalled()
})
it('keeps both running subagent Enter gestures on Queue transport', () => {
@@ -394,8 +429,8 @@ describe('running and lock semantics (queue cut 1)', () => {
// scrollport element holds both layers.
expect(scroll.contains(textarea)).toBe(true)
expect(scroll.contains(backdrop)).toBe(true)
// The glyph layer carries the draft and nothing else: with one scrollport
// it no longer pads its own height to match a second box's scroll extent.
// The glyph layer carries the draft and nothing else — no height padding
// to a second box's scroll extent.
expect(backdrop.textContent).toBe('line\n'.repeat(40))
})
@@ -624,7 +659,7 @@ describe('decorations', () => {
expect(shell.snapshot.draft).toBe('参考 \uFFFC 内容')
})
it('a lexicon-matched plain token renders the text-ref mark (decision 21)', () => {
it('a lexicon-matched plain token renders the text-ref mark', () => {
const lexicon = new Map<'/' | '@', readonly string[]>([['/', ['fixture-demo']]])
const { view, shell } = bench({ lexicon })
act(() => { shell.setDraft('use /fixture-demo now') })
@@ -636,7 +671,7 @@ describe('decorations', () => {
})
})
describe('insertText (decision 21 scoped event body)', () => {
describe('insertText (scoped event body)', () => {
it('splices plain text over the span and reports success as true', () => {
const { shell } = bench({ draft: '/fix' })
const ok = shell.insertText('/fixture-demo ', { start: 0, end: 4, draftRev: shell.snapshot.draftRev })
@@ -686,13 +721,15 @@ describe('strips and variants', () => {
})
describe('command launcher chrome and control seats', () => {
it('renders the command launcher; the Access chip is absent without the permissions projection; plan/model seats render EMPTY without entries (B ruling)', () => {
it('renders the command launcher; the Access chip is absent without the permissions projection; the control seats render EMPTY without entries', () => {
const { view, slotCalls } = bench()
expect(view.getByLabelText('命令')).toBeTruthy()
// Capability absent (no projection value): the chip renders nothing.
expect(view.queryByLabelText(/^访问模式/)).toBeNull()
// Both seats dispatched, nothing rendered.
expect(slotCalls.map(c => c.key)).toEqual(['conversation.input.plan', 'conversation.input.model'])
// Every seat dispatched, nothing rendered.
expect(slotCalls.map(c => c.key)).toEqual([
'conversation.input.plan', 'conversation.input.model',
])
expect(view.queryByLabelText('Plan mode')).toBeNull()
expect(view.queryByLabelText('Model')).toBeNull()
})

View File

@@ -1,6 +1,6 @@
/**
* InputMachine unit account (design §9.1, eng. plan §3.9-3.12): the submit
* plane carried over from the InputCore era (adjudication, span CAS, drift
* InputMachine unit account: the submit
* plane (adjudication, span CAS, drift
* guard, anti-backwash), plus the occurrence table (shift / whole-chip
* deletion / same-name independence), the self-managed undo log (typing
* coalescing, paste two-stage undo, redo chain), consume-token guards, the
@@ -625,7 +625,7 @@ describe('input-machine: projectClipboard', () => {
})
})
describe('decorations: scanTextRefs (decision 21)', () => {
describe('decorations: scanTextRefs', () => {
const LEX: ReadonlyMap<'/' | '@', readonly string[]> = new Map([
['/', ['commit-helper', 'fixture-demo']],
['@', ['worker-1']],

View File

@@ -1,6 +1,6 @@
// @vitest-environment jsdom
/**
* Impact-matrix projection tests (design §5.2 影响矩阵, row by row): what each
* Impact-matrix projection tests (row by row): what each
* phase projects onto the InputBar — enter routing, visuals (token color /
* hint / pending), edit freedom, and the published currency's claim seat.
* React over jsdom per the client testing discipline; the machine is real.
@@ -8,7 +8,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
import { createSnapshotStore, EMPTY_CHAT_SNAPSHOT } from '@deepseek-ai/dsh-client-runtime/client'
import type { ClientContext, ConversationSnapshot, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import type { SubmitOutcome } from '@deepseek-ai/dsh-client-ui-slash/client'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
@@ -26,7 +26,8 @@ const SID = 's1' as SessionId
/** Standard-props InputBar mount over a real shell (the composer-bar entry shape). */
function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled?: boolean }) {
const session = createSnapshotStore<ConversationSnapshot>({
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: over?.running ?? false, composerPhase: 'active',
removed: over?.disabled ?? false, openState: 'open', openError: null, hasMore: false,
loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
@@ -183,7 +184,7 @@ describe('matrix row: locked (session disabled)', () => {
expect(shell.snapshot.phase).toBe('plain')
})
it('running does NOT lock (queue cut 1): typing and enter-queue stay live', () => {
it('running does NOT lock: typing and enter-queue stay live', () => {
const { textarea, sink } = bench({ running: true })
expect((textarea).disabled).toBe(false)
fireEvent.change(textarea, { target: { value: '排队' } })

View File

@@ -1,17 +1,17 @@
// @vitest-environment jsdom
/**
* Scenario-chain integration (design §8 A/C/D/H/I): the real per-session
* Scenario-chain integration (scenarios A/C/D/H/I): the real per-session
* SlashController pipeline over a real session scope (SessionsService over
* a listed host session) + a command source implementing the decision
* table's relevant cells + the real SessionInput machine (scoped-event
* listeners wired the way the hub does) + the real InputBar. ui-command
* itself is not a dependency of this package; the source below is the
* decision-table contract at the SlashSource seam.
* decision-table contract at the `SlashSource` boundary.
*/
import { Context } from 'cordis'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
import { EMPTY_CHAT_SNAPSHOT, SessionsService } from '@deepseek-ai/dsh-client-runtime/client'
import { SlashService } from '@deepseek-ai/dsh-client-ui-slash/client'
import type { ClientSessionContext, CommandClaim, PickOutcome, SubmitOutcome } from '@deepseek-ai/dsh-client-ui-slash/client'
import { FakeApiClient, ok } from '../../runtime/tests/fake-api.ts'
@@ -34,7 +34,7 @@ interface FakeCommand {
input?: { hint: string }
}
/** T6 decision-table source over an in-memory directory (menu/space/enter columns for leadingInput + execute). */
/** Decision-table source over an in-memory directory (menu/space/enter columns for leadingInput + execute). */
function commandSource(commands: FakeCommand[], execute: (line: string) => Promise<SubmitOutcome>) {
const resolve = (name: string): FakeCommand | undefined => commands.find(c => c.name === name)
const leadingClaim = (desc: FakeCommand): CommandClaim => ({
@@ -112,7 +112,8 @@ async function scopedBench(register?: (slash: SlashService) => void) {
actx.on('slash/input-consume-token', req => shell.consumeToken(req.guard) ? true : undefined)
const wiring = shell
const sessionStore = createSnapshotStore<ConversationSnapshot>({
sessionId, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
promptError: null, blank: false, subagent: null, lastAgentError: null,

View File

@@ -6,6 +6,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { useSyncExternalStore } from 'react'
import { EMPTY_CHAT_SNAPSHOT } from '@deepseek-ai/dsh-client-runtime/client'
import type {
ConversationSnapshot, QueuedMessage, SessionId, SessionListState,
} from '@deepseek-ai/dsh-client-runtime/client'
@@ -32,7 +33,8 @@ function row(id: string, text: string | null, preview = text ?? '[image]'): Queu
function snapshotWith(queue: QueuedMessage[]): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue, running: true, composerPhase: 'active', removed: false, openState: 'open', openError: null,
hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
}
@@ -164,7 +166,11 @@ describe('QueueDock', () => {
expect(view.getByText('remove me')).toBeTruthy()
expect(view.getByText('second')).toBeTruthy()
act(() => { finishUpdate?.() })
expect(updateQueue).toHaveBeenCalledOnce()
await act(async () => {
finishUpdate?.()
await Promise.resolve()
})
await waitFor(() => {
expect(header).toHaveProperty('disabled', false)
expect(header.getAttribute('aria-expanded')).toBe('false')

View File

@@ -95,7 +95,7 @@ describe('selection survives on the store seat', () => {
doomed.actions.select({ turnSeq: 1 })
expect(localStorage.getItem('dsh.conversation.chat.s1')).not.toBeNull()
// TestSessions.remove drives the same public slot lifecycle seam the
// TestSessions.remove drives the same public slot lifecycle contract the
// production SessionsService calls when the scope dies (pruneStoreScope).
await b.runtime.sessions.remove('s1')

View File

@@ -5,7 +5,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
import { createSnapshotStore, EMPTY_CHAT_SNAPSHOT } from '@deepseek-ai/dsh-client-runtime/client'
import type {
ConversationSnapshot, SessionId, SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView,
} from '@deepseek-ai/dsh-client-runtime/client'
@@ -70,7 +70,8 @@ const workspaceState = (items: readonly WorkspaceView[]): WorkspaceListState =>
function conversationSnapshot(overrides: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
return {
sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
sessionId: SID, chat: EMPTY_CHAT_SNAPSHOT,
nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [],
pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
openState: 'open', openError: null, hasMore: false, loadingOlder: false,
promptError: null, blank: false, subagent: null, lastAgentError: null,
@@ -452,6 +453,9 @@ describe('ConversationRoot resident composer', () => {
const chip = b.view.getByRole('button', { name: '选择工作区' })
expect((chip as HTMLButtonElement).disabled).toBe(false)
expect(b.slotCalls).toContain('conversation.hero.workspace')
// The agent-preset chip sits in the same row, for the same reason: both
// choices are only open before the first message.
expect(b.slotCalls).toContain('conversation.hero.agentPreset')
})
it('prompt failure renders the promptError strip (ordinary failure, no transaction UI)', () => {

View File

@@ -86,8 +86,8 @@ describe('TodoPanel', () => {
it('marks every parallel active item, and counts them all in the header', () => {
render(<TodoPanel todos={PARALLEL} t={t} />)
fireEvent.click(screen.getByRole('button', { expanded: false }))
// The old unconditional cap made this list unreachable: three items carry
// the in-progress glyph at once, and the header counts all three.
// An unconditional in-progress cap would make this list unreachable: three
// items carry the in-progress glyph at once, and the header counts all three.
const statuses = screen.getAllByRole('listitem').map(li => li.getAttribute('data-status'))
expect(statuses.filter(s => s === 'in_progress')).toHaveLength(3)
expect(screen.getByText('跑后台构建')).toBeTruthy()