fix(web): align trajectory request lifecycle states
This commit is contained in:
1 parent
0f4549c64d
commit
37c2fa40ac
16 files changed
+294
-35
No files matched your search
@@ -18,6 +18,7 @@ const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/ui.e
|
||||
const TRAJECTORY_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/trajectory.expected.md', import.meta.url))
|
||||
const CODE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/code.expected.md', import.meta.url))
|
||||
const PREPARING_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/preparing.expected.md', import.meta.url))
|
||||
const REQUEST_LIFECYCLE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/request-lifecycle.expected.md', import.meta.url))
|
||||
const MODE = webSnapshotMode()
|
||||
|
||||
// Elicits the successful and failed sub-rows this scenario asserts.
|
||||
@@ -31,6 +32,7 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => {
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
const sessionEvents: SessionEvent[] = []
|
||||
let releasePreparation: (() => void) | undefined
|
||||
const requestStates: string[] = []
|
||||
|
||||
beforeAll(async () => {
|
||||
scaffold = await launchWebScaffold({
|
||||
@@ -62,7 +64,11 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => {
|
||||
await input.waitFor({ timeout: 10_000 })
|
||||
const settled = scaffold.whenTurnSettled()
|
||||
const gate = Promise.withResolvers<undefined>()
|
||||
const waiting = Promise.withResolvers<undefined>()
|
||||
const start = Promise.withResolvers<undefined>()
|
||||
const dispose = scaffold.ctx.on('llm/stream', async function* (_options, next) {
|
||||
waiting.resolve(undefined)
|
||||
await start.promise
|
||||
let held = false
|
||||
for await (const chunk of next()) {
|
||||
yield chunk
|
||||
@@ -72,11 +78,21 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => {
|
||||
}
|
||||
}
|
||||
}, { prepend: true })
|
||||
releasePreparation = () => { gate.resolve(undefined); dispose() }
|
||||
releasePreparation = () => { start.resolve(undefined); gate.resolve(undefined); dispose() }
|
||||
const observePreparation = async () => {
|
||||
try {
|
||||
await input.fill(PROMPT)
|
||||
await input.press('Enter')
|
||||
await waiting.promise
|
||||
await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
|
||||
const request = page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true })
|
||||
await request.click()
|
||||
const panel = page.getByRole('tabpanel')
|
||||
await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor()
|
||||
expect(await panel.getByRole('button', { name: 'Assistant Message', exact: true }).count()).toBe(0)
|
||||
requestStates.push('# Waiting for output', await panel.locator('dl').first().ariaSnapshot())
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).click()
|
||||
start.resolve(undefined)
|
||||
const row = page.locator('[data-chat-call-id] [data-state="preparing"]').first()
|
||||
await row.waitFor({ state: 'attached', timeout: 30_000 })
|
||||
await expandOwningTurnProcess(page, row)
|
||||
@@ -88,11 +104,27 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => {
|
||||
expect(await row.locator('pre').count()).toBe(0)
|
||||
const group = row.locator('xpath=ancestor::*[@data-chat-group-key][1]')
|
||||
await compareOrRefreshGolden(PREPARING_EXPECTED, await group.ariaSnapshot(), MODE)
|
||||
await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
|
||||
const assistant = page.locator('tr[data-kind="message"][data-running="true"]').first()
|
||||
await assistant.click()
|
||||
await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor()
|
||||
expect(await panel.getByText('Completed', { exact: true }).count()).toBe(0)
|
||||
requestStates.push('# Streaming assistant', await panel.locator('dl').first().ariaSnapshot())
|
||||
await panel.getByRole('button', { name: 'Request Timing', exact: true }).click()
|
||||
expect(await panel.getByText('Not recorded', { exact: true }).count()).toBe(0)
|
||||
expect(await panel.locator('dt').filter({ hasText: /^Started$/ }).locator('..').getByRole('button').count()).toBe(1)
|
||||
await request.click()
|
||||
await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor()
|
||||
requestStates.push('# Streaming request', await panel.locator('dl').first().ariaSnapshot())
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).click()
|
||||
} finally {
|
||||
releasePreparation?.()
|
||||
}
|
||||
}
|
||||
const [sessionId] = await Promise.all([settled, observePreparation()])
|
||||
expect(sessionEvents.filter(event => event.type === 'turn/end')).toMatchObject([
|
||||
{ data: { reason: { kind: 'completed' } } },
|
||||
])
|
||||
await expect.poll(() => page.locator('[data-state="preparing"]').count(), { timeout: 15_000 }).toBe(0)
|
||||
if (MODE === 'record') {
|
||||
await recordFixture(scaffold, sessionId, FIXTURE)
|
||||
@@ -128,6 +160,19 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => {
|
||||
expect(bashContent.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('CODE_ROUND_OK')
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('settles the request and assistant after the held stream resumes', async () => {
|
||||
await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
|
||||
await page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true }).click()
|
||||
const panel = page.getByRole('tabpanel')
|
||||
await panel.getByText('Completed', { exact: true }).waitFor()
|
||||
requestStates.push('# Settled request', await panel.locator('dl').first().ariaSnapshot())
|
||||
await panel.getByRole('button', { name: 'Assistant Message', exact: true }).click()
|
||||
await panel.getByText('Completed', { exact: true }).waitFor()
|
||||
requestStates.push('# Settled assistant', await panel.locator('dl').first().ariaSnapshot())
|
||||
await compareOrRefreshGolden(REQUEST_LIFECYCLE_EXPECTED, requestStates.join('\n\n'), MODE)
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).click()
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('renders the code parent row with always-visible nested sub-rows', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-ptc-rows'))
|
||||
await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
en: 4bd17d05b8385675
|
||||
zh: 5174e27f754f2a03
|
||||
/deepseek-ai-dsh-client-ui-trajectory/use-this-package/inspecting-records:
|
||||
en: 5d4c2ccb73bcc71d
|
||||
zh: f15664c3f1b28d9d
|
||||
en: 47a780b8fb4aa73b
|
||||
zh: 972f4c28ecb4efc7
|
||||
/deepseek-ai-dsh-client-ui-trajectory/use-this-package/the-timing-overview:
|
||||
en: 0331f90cbd904862
|
||||
zh: bdc2d4ed1c3c1f5e
|
||||
en: 0f4ee2189324ac06
|
||||
zh: 12e76fed22c09bc1
|
||||
/deepseek-ai-dsh-client-ui-trajectory/understand-the-implementation:
|
||||
en: 74cc8fc87241da34
|
||||
zh: cd72ff9c0fdd2575
|
||||
|
||||
@@ -35,11 +35,13 @@ Selection, timeline navigation, folding, and search cover the React-visible wind
|
||||
|
||||
Summary and Preview share one ordered attachment list after the message text, preserving repeated references. Each row shows a contained image thumbnail or file-type icon, the recorded filename (a localized numbered label for unnamed images), and recorded size, type, and image dimensions where available. Zero-byte files retain their size, and truncated filenames expose the full name in a tooltip. Images open the existing lightbox. Raw keeps content-block order and unrendered text, with images and files in initially collapsed disclosures containing their complete recorded fields.
|
||||
|
||||
Requests remain pending while awaiting output, streaming, or retrying. A request without assistant output has no result link; interrupted output remains inspectable and both the request and assistant record show failure, including when the Step start is outside the loaded history. A completed model response does not imply that its tools or turn have finished.
|
||||
|
||||
Thinking in the inspector uses compact Markdown at the inspector's fixed 13px size and 20px line height, independent of the content-size setting. Headings add bold weight without increasing size or line height. Assistant output keeps its regular Markdown typography.
|
||||
|
||||
### The timing overview
|
||||
|
||||
Historical replies retain TTFT, generation duration, and throughput when their recorded streams contain token timestamps. TTFT measures from the Step start to its first token, including output from an earlier retry attempt; an unloaded Step start or a stream without tokens leaves the corresponding metric unavailable.
|
||||
Streaming replies retain their known start time and TTFT. After settlement, token timestamps provide generation duration; throughput also requires recorded usage. Historical replies retain the same recorded timing. TTFT measures from the Step start to its first token, including output from an earlier retry attempt; an unloaded Step start or a stream without tokens leaves the corresponding metric unavailable.
|
||||
|
||||
A fixed Overview above the ledger projects real record start/duration timing from left to right; Assistant spans divide recorded TTFT from decoding, and a 500 ms hover reveals exact clock and duration details. Dragging an interval focuses the ledger on every record active at any point in that inclusive range; wheel gestures zoom the time domain; a right-button click clears the selected interval, and a right-button drag pans an already zoomed viewport. The initial view and streaming updates stay at the tail; scrolling upward suspends following so new records do not interrupt inspection of earlier rows.
|
||||
|
||||
|
||||
@@ -35,11 +35,13 @@ Trajectory 标签页让你以按轮次组织的事件记录表和交互式时间
|
||||
|
||||
概述与预览共用正文之后的有序附件列表,保留重复引用。每行展示完整缩放的图片缩略图或文件类型图标、已记录的文件名(未命名图片使用本地化的编号名称),以及可用的已记录大小、类型和图片尺寸。零字节文件保留大小显示,截断的文件名通过提示显示完整名称。图片打开现有灯箱。原始内容保留内容块顺序和未渲染文本,图片与文件使用默认折叠的展开项,包含完整的已记录字段。
|
||||
|
||||
请求在等待输出、流式生成或重试期间保持等待状态。尚无助手输出的请求不提供结果链接;中断的输出仍可检查,请求和助手记录都显示失败,即使步骤起点位于已加载历史之外。模型回复完成并不表示其工具或轮次已经结束。
|
||||
|
||||
检查器中的思考内容使用紧凑 Markdown,沿用检查器固定的 13px 字号和 20px 行高,不受内容字号设置影响。标题只加粗,不放大字号或行高。助手输出保留常规 Markdown 排版。
|
||||
|
||||
### 时间概览
|
||||
|
||||
当记录的流包含 token 时间戳时,历史回复会保留 TTFT、生成耗时与吞吐量。TTFT 从步骤开始计量到首个 token,包括更早重试尝试中的输出;步骤起点尚未加载或流中没有 token 时,对应指标保持不可用。
|
||||
流式回复保留已知的开始时间与 TTFT。回复结束后,token 时间戳用于计算生成耗时;吞吐量还需要已记录的用量。历史回复保留相同的已记录计时。TTFT 从步骤开始计量到首个 token,包括更早重试尝试中的输出;步骤起点尚未加载或流中没有 token 时,对应指标保持不可用。
|
||||
|
||||
固定在记录表上方的 Overview 区域从左到右投影记录的真实开始时间与耗时;助手时间条区分记录到的 TTFT 与解码时间,悬停 500 ms 后可查看精确时刻与耗时详情。拖选区间会把记录表聚焦到该闭区间内任何时刻处于活动的记录;滚轮手势用于缩放时间域;右键单击会清除所选区间,在已放大的视口上按住右键拖动则会平移。初始视图与流式更新都停留在尾部;向上滚动会暂停跟随,因此新记录不会打断对旧记录的检查。
|
||||
|
||||
|
||||
@@ -2258,7 +2258,7 @@ export function TrajectoryTable({
|
||||
), [allRecords, selectedRequestInfo])
|
||||
const selectedRequestRecords = selectedRequestRecordTemplates.map(currentRecord)
|
||||
const selectedRequestAssistant = selectedRequestRecords.find(
|
||||
record => record.cell.kind === 'message',
|
||||
record => record.cell.kind === 'message' && record.cell.requestOnly !== true,
|
||||
)
|
||||
const selectedRequestAnchor = selectedRequestAssistant ?? selectedRequestRecords[0]
|
||||
const selectedRequestNumber = selectedRequestInfo?.number
|
||||
|
||||
@@ -256,18 +256,21 @@ export function TrajectoryView({
|
||||
const provider = request?.providerMetadata?.provider ?? node?.providerMetadata?.provider
|
||||
const model = request?.providerMetadata?.model ?? node?.providerMetadata?.model
|
||||
const requestConfig = request?.requestConfig ?? node?.requestConfig
|
||||
const startedAt = request?.startedAt ?? node?.timing?.stepStartTime
|
||||
const completedAt = request === undefined ? node?.time : request.completedAt
|
||||
const resultSeq = request?.resultSeq ?? node?.seq
|
||||
numbered.push({
|
||||
seq: entry.seq,
|
||||
turn,
|
||||
step,
|
||||
group: t('group.step', { step }),
|
||||
number: index + 1,
|
||||
...(request?.status === undefined ? {} : { status: request.status }),
|
||||
...(request?.startedAt === undefined ? {} : { startedAt: request.startedAt }),
|
||||
...(request?.completedAt === undefined ? {} : { completedAt: request.completedAt }),
|
||||
status: request?.status ?? (node?.interrupted === true ? 'error' : 'complete'),
|
||||
...(startedAt == null ? {} : { startedAt }),
|
||||
...(completedAt === undefined ? {} : { completedAt }),
|
||||
...(request?.error === undefined ? {} : { error: request.error }),
|
||||
...(request?.errorCode === undefined ? {} : { errorCode: request.errorCode }),
|
||||
...(request?.resultSeq === undefined ? {} : { resultSeq: request.resultSeq }),
|
||||
...(resultSeq === undefined ? {} : { resultSeq }),
|
||||
...(request?.retry === undefined ? {} : { retry: request.retry }),
|
||||
...(request?.maxRetries === undefined ? {} : { maxRetries: request.maxRetries }),
|
||||
...(request?.retryDelayMs === undefined
|
||||
@@ -331,14 +334,17 @@ export function TrajectoryView({
|
||||
runningCalls, requests, inspection.systemPrompts, callSchemas, t,
|
||||
])
|
||||
const timelinePartialSignature = partialStructureSignature(partial)
|
||||
const partialStartTime = partial?.timing?.stepStartTime
|
||||
const partialFirstTokenTime = partial?.timing?.firstTokenTime
|
||||
const timelinePartial = useMemo<TrajectorySnapshot['partial']>(() => partial === null
|
||||
? null
|
||||
: {
|
||||
turn: partial.turn,
|
||||
step: partial.step,
|
||||
blocks: partial.blocks.map(block => timelineBlock(block)),
|
||||
...(partial.timing === undefined ? {} : { timing: partial.timing }),
|
||||
},
|
||||
[partialStep, partialTurn, timelinePartialSignature])
|
||||
[partialStep, partialTurn, timelinePartialSignature, partialStartTime, partialFirstTokenTime])
|
||||
const timelineTurns = useMemo(
|
||||
() => appendTrajectoryPartialLayout(finalized.turns, timelinePartial, finalized.lastIndex, t),
|
||||
[finalized, timelinePartial, t],
|
||||
|
||||
@@ -517,7 +517,7 @@ export function deriveTrajectoryLayout(
|
||||
callStartById,
|
||||
callById,
|
||||
t,
|
||||
{ streaming: true },
|
||||
{ streaming: true, timing: partial.timing },
|
||||
), t)
|
||||
if (partial.step > 0) pushStep(partial.turn, partial.step, laidList)
|
||||
else for (const laid of laidList) pushMessage(partial.turn, laid)
|
||||
@@ -731,14 +731,15 @@ function expandAssistant(
|
||||
callStarts: ReadonlyMap<string, number>,
|
||||
calls: ReadonlyMap<string, ToolCallBlock>,
|
||||
t: TrajectoryTranslate,
|
||||
opts?: { streaming?: boolean },
|
||||
opts?: { streaming?: boolean; timing?: NonNullable<TrajectorySnapshot['partial']>['timing'] },
|
||||
): LaidCell[] {
|
||||
if (opts?.streaming === true && node.blocks.length === 0) return []
|
||||
const out: LaidCell[] = []
|
||||
let index = startIndex - 1
|
||||
const usage = node.usage as UsageLike | undefined
|
||||
const streaming = opts?.streaming === true
|
||||
const recordedStart = finiteTime(node.timing?.stepStartTime)
|
||||
const timing = opts?.timing ?? node.timing
|
||||
const recordedStart = finiteTime(timing?.stepStartTime)
|
||||
const messageDuration = streaming
|
||||
? null
|
||||
: durationSeconds(node.time, recordedStart ?? prevAbsTime)
|
||||
@@ -767,14 +768,15 @@ function expandAssistant(
|
||||
...(messageText !== '' ? { outputDetail: messageText } : {}),
|
||||
...(thinkingText !== '' ? { thinkingDetail: thinkingText } : {}),
|
||||
sourceBlocks: node.blocks.map(block => assistantSourceBlock(block)),
|
||||
...(node.interrupted === true ? { isError: true } : {}),
|
||||
timeSeconds: messageDuration,
|
||||
startedAt: recordedStart,
|
||||
}
|
||||
attachUsage(message, usage)
|
||||
message.assistantMetrics = {
|
||||
timingRecorded: node.timing !== undefined,
|
||||
stepStartTime: node.timing?.stepStartTime ?? null,
|
||||
firstTokenTime: node.timing?.firstTokenTime ?? null,
|
||||
timingRecorded: timing !== undefined,
|
||||
stepStartTime: timing?.stepStartTime ?? null,
|
||||
firstTokenTime: timing?.firstTokenTime ?? null,
|
||||
completedTime: streaming ? null : finiteTime(node.time),
|
||||
usageProvided: usage !== undefined,
|
||||
outputTokens: Number.isFinite(usage?.outputTokens) ? usage?.outputTokens ?? null : null,
|
||||
|
||||
@@ -2,12 +2,13 @@ import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
AssistantBlock, AssistantMessageNode, ConversationLocation,
|
||||
ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,
|
||||
PartialAssistant, RequestView,
|
||||
RequestView,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { StreamChunk } from '@deepseek-ai/dsh-llm'
|
||||
import { assistantStreamFirstTokenTime } from '@deepseek-ai/dsh-llm/assistant-stream'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
|
||||
import { trajectoryNode } from './trajectory-definition-common.ts'
|
||||
import type { TrajectoryPartialAssistant } from './trajectory-contract.ts'
|
||||
import {
|
||||
displayFailure, emptyAssistantBlock, isTokenDelta, toAssistantBlock, toAssistantBlocks,
|
||||
} from './trajectory-event-projection.ts'
|
||||
@@ -37,7 +38,6 @@ interface AssistantState {
|
||||
readonly startSeq: number
|
||||
readonly startTime: number
|
||||
readonly started: boolean
|
||||
readonly sawChunk: boolean
|
||||
readonly blocks: readonly (AssistantBlock | undefined)[]
|
||||
readonly visibleBlocks: number
|
||||
readonly firstVisibleSeq: number | undefined
|
||||
@@ -62,7 +62,6 @@ function initialState(
|
||||
startSeq,
|
||||
startTime,
|
||||
started,
|
||||
sawChunk: false,
|
||||
blocks: [],
|
||||
visibleBlocks: 0,
|
||||
firstVisibleSeq: undefined,
|
||||
@@ -121,7 +120,7 @@ function updateChunk(
|
||||
time: number,
|
||||
): AssistantState {
|
||||
if (chunk.type === 'usage') {
|
||||
return { ...state, sawChunk: true, usage: addUsage(state.usage, chunk.usage) }
|
||||
return { ...state, usage: addUsage(state.usage, chunk.usage) }
|
||||
}
|
||||
const blocks = [...state.blocks]
|
||||
let changedIndex = -1
|
||||
@@ -173,14 +172,13 @@ function updateChunk(
|
||||
blocks[chunk.index] = toAssistantBlock(chunk.block)
|
||||
break
|
||||
default:
|
||||
return { ...state, sawChunk: true }
|
||||
return state
|
||||
}
|
||||
const visibleBlocks = state.visibleBlocks
|
||||
- Number(previousVisible)
|
||||
+ Number(blockIsVisible(blocks[changedIndex]))
|
||||
return {
|
||||
...state,
|
||||
sawChunk: true,
|
||||
blocks,
|
||||
visibleBlocks,
|
||||
...(visibleBlocks > 0 && state.firstVisibleSeq === undefined
|
||||
@@ -211,7 +209,6 @@ function settleMessage(
|
||||
const blocks = toAssistantBlocks(event.data.message.content)
|
||||
return {
|
||||
...settleTiming(state, event),
|
||||
sawChunk: false,
|
||||
blocks,
|
||||
visibleBlocks: countVisibleBlocks(blocks),
|
||||
final: match,
|
||||
@@ -300,9 +297,9 @@ function assistantRequest(
|
||||
boundary: { seq: number; time: number } | undefined,
|
||||
): Extract<RequestView, { purpose: 'assistant' }> | undefined {
|
||||
if (!state.started) return undefined
|
||||
const status = node !== undefined && node.interrupted !== true
|
||||
? 'complete'
|
||||
: state.retry !== undefined || boundary !== undefined ? 'error' : 'running'
|
||||
const status = node !== undefined
|
||||
? node.interrupted === true ? 'error' : 'complete'
|
||||
: boundary !== undefined ? 'error' : 'running'
|
||||
return {
|
||||
purpose: 'assistant',
|
||||
startSeq: state.startSeq,
|
||||
@@ -399,8 +396,16 @@ const trajectoryAssistantDefinition: ConversationNodeDefinition<AssistantState>
|
||||
if (state === undefined) return null
|
||||
const node = finalNode(state, context)
|
||||
const boundary = closedBoundary(context)
|
||||
const partial: PartialAssistant | null = node === undefined && boundary === undefined && state.sawChunk
|
||||
? { turn: state.turn, step: state.step, blocks: compactBlocks(state.blocks) }
|
||||
const partial: TrajectoryPartialAssistant | null = node === undefined && boundary === undefined && state.blocks.length > 0
|
||||
? {
|
||||
turn: state.turn,
|
||||
step: state.step,
|
||||
blocks: compactBlocks(state.blocks),
|
||||
timing: {
|
||||
stepStartTime: state.started ? state.startTime : null,
|
||||
firstTokenTime: state.firstTokenTime ?? null,
|
||||
},
|
||||
}
|
||||
: null
|
||||
const request = assistantRequest(state, node, boundary)
|
||||
if (node === undefined && partial === null && request === undefined) return null
|
||||
|
||||
@@ -14,6 +14,11 @@ export interface TrajectoryRequestHeaderState {
|
||||
readonly location: ConversationLocation
|
||||
}
|
||||
|
||||
/** In-flight assistant output with the loaded Step start and first token timestamps. */
|
||||
export interface TrajectoryPartialAssistant extends PartialAssistant {
|
||||
readonly timing?: Pick<NonNullable<AssistantMessageNode['timing']>, 'stepStartTime' | 'firstTokenTime'>
|
||||
}
|
||||
|
||||
/** One independently assembled contribution to the legacy Trajectory ledger. */
|
||||
export type TrajectoryContribution =
|
||||
| { readonly kind: 'system-prompt'; readonly prompt: SystemPromptNode }
|
||||
@@ -24,7 +29,7 @@ export type TrajectoryContribution =
|
||||
| {
|
||||
readonly kind: 'assistant'
|
||||
readonly node?: AssistantMessageNode
|
||||
readonly partial: PartialAssistant | null
|
||||
readonly partial: TrajectoryPartialAssistant | null
|
||||
readonly request?: Extract<RequestView, { purpose: 'assistant' }>
|
||||
}
|
||||
| {
|
||||
@@ -68,7 +73,7 @@ export interface TrajectorySnapshot {
|
||||
readonly eventLocations: ReadonlyMap<number, ConversationLocation>
|
||||
readonly requests: readonly RequestView[]
|
||||
readonly callSchemas: ReadonlyMap<string, ConversationPromptSnapshot['tools'][number]>
|
||||
readonly partial: PartialAssistant | null
|
||||
readonly partial: TrajectoryPartialAssistant | null
|
||||
readonly runningCalls: readonly RunningToolCall[]
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ export interface TrajectoryCellProps extends HTMLAttributes<HTMLDivElement> {
|
||||
callId?: string
|
||||
/** Recorded tool name; independent of the display summary. */
|
||||
toolName?: string
|
||||
/** Tool-only result failure state. */
|
||||
/** Failed operation or interrupted assistant output. */
|
||||
isError?: boolean
|
||||
/** Own duration in seconds, or `null` when no duration is known. */
|
||||
timeSeconds: number | null
|
||||
|
||||
@@ -172,6 +172,67 @@ function systemMessage(text: string) {
|
||||
}
|
||||
|
||||
describe('Trajectory conversation Definitions', () => {
|
||||
it('publishes a waiting request before any stream output arrives', () => {
|
||||
const value = assembler([at(1, 'turn/start', { turn: 1 })])
|
||||
expect(value.append(at(2, 'step/start', { turn: 1, step: 1 }))).toBe('immediate')
|
||||
value.flush()
|
||||
expect(snapshot(value)).toMatchObject({
|
||||
eventNodes: [],
|
||||
partial: null,
|
||||
requests: [{ status: 'running', startedAt: 1_700_000_000_002, completedAt: null }],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a retrying request running until its response settles', () => {
|
||||
const value = 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: 'test', mode: 'normal',
|
||||
policyKey: 'test-normal', retry: 1, maxRetries: 2, delayMs: 25,
|
||||
failure: { code: 'TRANSPORT', message: 'temporary failure' },
|
||||
}),
|
||||
])
|
||||
expect(snapshot(value).requests).toMatchObject([{ status: 'running', completedAt: null, retry: 1 }])
|
||||
value.append(at(4, 'assistant/live-chunk', {
|
||||
turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'recovered' },
|
||||
}))
|
||||
value.flush()
|
||||
expect(snapshot(value).requests).toMatchObject([{ status: 'running', completedAt: null }])
|
||||
value.append(at(5, 'assistant/message', {
|
||||
turn: 1, step: 1, message: assistantMessage('recovered', 'recovered'),
|
||||
}))
|
||||
value.flush()
|
||||
expect(snapshot(value).requests).toMatchObject([{
|
||||
status: 'complete', completedAt: 1_700_000_000_005, resultSeq: 5,
|
||||
}])
|
||||
})
|
||||
|
||||
it('retains the waiting request when chunks have no assistant blocks', () => {
|
||||
const current = snapshot(assembler([
|
||||
at(1, 'turn/start', { turn: 1 }),
|
||||
at(2, 'step/start', { turn: 1, step: 1 }),
|
||||
at(3, 'assistant/live-chunk', {
|
||||
turn: 1, step: 1, chunk: { type: 'usage', usage: { inputTokens: 10, outputTokens: 0 } },
|
||||
}),
|
||||
]))
|
||||
expect(current.partial).toBeNull()
|
||||
expect(current.requests).toMatchObject([{ status: 'running', usage: { inputTokens: 10, outputTokens: 0 } }])
|
||||
})
|
||||
|
||||
it('settles an interrupted response before the step closes', () => {
|
||||
const current = snapshot(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('interrupted', 'cut short'), interrupted: true,
|
||||
}),
|
||||
]))
|
||||
expect(current.requests).toMatchObject([{
|
||||
status: 'error', completedAt: 1_700_000_000_003, resultSeq: 3,
|
||||
}])
|
||||
})
|
||||
|
||||
it('addresses tool-call inspection with the persisted call identity', () => {
|
||||
expect(trajectoryViewDefinition.toolCallFocus?.('call-1')).toBe('call-1')
|
||||
})
|
||||
@@ -218,6 +279,10 @@ describe('Trajectory conversation Definitions', () => {
|
||||
])
|
||||
|
||||
expect(snapshot(value).partial?.blocks).toEqual([{ kind: 'text', text: 'first attempt' }])
|
||||
expect(snapshot(value).partial?.timing).toEqual({
|
||||
stepStartTime: 1_700_000_000_002,
|
||||
firstTokenTime: 1_700_000_000_003,
|
||||
})
|
||||
expect(snapshot(value).requests).toMatchObject([{
|
||||
purpose: 'assistant',
|
||||
status: 'running',
|
||||
|
||||
@@ -76,6 +76,20 @@ describe('TrajectoryTurn', () => {
|
||||
})
|
||||
|
||||
describe('deriveTrajectoryLayout', () => {
|
||||
it('marks an interrupted assistant as failed while retaining its output', () => {
|
||||
const turns = deriveTrajectoryLayout({
|
||||
nodes: [{
|
||||
kind: 'assistant', seq: 3, time: 3_000, turn: 1, step: 1,
|
||||
blocks: [{ kind: 'text', text: 'cut short' }], interrupted: true,
|
||||
}],
|
||||
partial: null,
|
||||
runningCalls: [],
|
||||
})
|
||||
expect(turns[0]?.groups[0]?.cells).toMatchObject([{
|
||||
kind: 'message', isError: true, outputDetail: 'cut short',
|
||||
}])
|
||||
})
|
||||
|
||||
it.each(['tool-addition', 'tool-removal'] as const)('names a single %s without detail content', (type) => {
|
||||
const nodes: ConversationNode[] = [{
|
||||
kind: 'context', seq: 1, time: 1_000,
|
||||
@@ -165,6 +179,7 @@ describe('deriveTrajectoryLayout', () => {
|
||||
turn: 2,
|
||||
step: 1,
|
||||
blocks: [{ kind: 'reasoning' as const, text: 'streaming' }],
|
||||
timing: { stepStartTime: 3_000, firstTokenTime: 3_200 },
|
||||
}
|
||||
const request = {
|
||||
purpose: 'assistant', startSeq: 3, turn: 2, step: 1,
|
||||
@@ -188,6 +203,13 @@ describe('deriveTrajectoryLayout', () => {
|
||||
text: '',
|
||||
previewMarkdown: 'streaming',
|
||||
timeSeconds: null,
|
||||
startedAt: 3_000,
|
||||
assistantMetrics: {
|
||||
timingRecorded: true,
|
||||
stepStartTime: 3_000,
|
||||
firstTokenTime: 3_200,
|
||||
completedTime: null,
|
||||
},
|
||||
}])
|
||||
expect(streamed[1]?.groups[0]?.cells[0]?.requestOnly).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -873,6 +873,25 @@ describe('TrajectoryTable', () => {
|
||||
expect(errorResult.closest('[class*="errorPayload"]')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('does not expose a request placeholder as a completed assistant result', () => {
|
||||
const turns = deriveTrajectoryLayout({
|
||||
nodes: [], partial: null, runningCalls: [],
|
||||
requests: [{
|
||||
purpose: 'assistant', startSeq: 2, turn: 1, step: 1,
|
||||
startedAt: 2_000, completedAt: null, status: 'running',
|
||||
}],
|
||||
}, t)
|
||||
render(<TrajectoryTable turns={turns} requestNumbers={[{
|
||||
turn: 1, step: 1, seq: 2, group: 'Step 1', number: 1,
|
||||
status: 'running', startedAt: 2_000, completedAt: null,
|
||||
}]} {...FOLD_PROPS} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Request #1' }))
|
||||
expect(screen.getByText('Pending')).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'Assistant Message' })).toBeNull()
|
||||
expect(screen.queryByText('Completed')).toBeNull()
|
||||
})
|
||||
|
||||
it('marks failed requests and lays coincident request markers left to right', () => {
|
||||
const turns: readonly TrajectoryTurnModel[] = [
|
||||
{
|
||||
|
||||
@@ -1324,6 +1324,28 @@ describe('timeline projection', () => {
|
||||
})
|
||||
|
||||
describe('TrajectoryView state', () => {
|
||||
it.each([
|
||||
{ interrupted: true, status: '失败' },
|
||||
{ interrupted: false, status: '已完成' },
|
||||
])('uses the settled response status when the Step start is unloaded: $status', ({ interrupted, status }) => {
|
||||
const nodes: LegacyConversationSlice['nodes'] = [{
|
||||
kind: 'assistant', seq: 10, time: 10_000, turn: 2, step: 3,
|
||||
blocks: [{ kind: 'text', text: 'loaded response' }],
|
||||
...(interrupted ? { interrupted: true } : {}),
|
||||
}]
|
||||
render(<TrajectoryView
|
||||
{...standaloneProps(nodes)}
|
||||
{...standaloneHistory(historySnapshot(nodes))}
|
||||
{...standaloneDuration()}
|
||||
/>)
|
||||
fireEvent.click(screen.getByRole('row', { name: /loaded response/ }))
|
||||
expect(within(screen.getByRole('tabpanel')).getByText(status)).toBeTruthy()
|
||||
fireEvent.click(within(screen.getByRole('table')).getByRole('button', { name: '请求 #1' }))
|
||||
expect(within(screen.getByRole('tabpanel')).getByText(status)).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: '助手消息' }))
|
||||
expect(within(screen.getByRole('tabpanel')).getByText(status)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('reveals resident history one bounded page at a time', async () => {
|
||||
const nodes: LegacyConversationSlice['nodes'] = Array.from({ length: 5_000 }, (_, index) => ({
|
||||
kind: 'user' as const,
|
||||
|
||||
@@ -1594,7 +1594,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.trajectory.images\', () => ctx.slots.register(\n { name: \'conversation.trajectory.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-trajectory/src/client/trajectory-contract.ts:98',
|
||||
source: 'packages/client/ui-trajectory/src/client/trajectory-contract.ts:103',
|
||||
},
|
||||
{
|
||||
key: 'conversation.view',
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Waiting for output
|
||||
|
||||
- term: Status
|
||||
- definition: Pending
|
||||
- term: Provider
|
||||
- definition: deepseek-official
|
||||
- term: Model
|
||||
- definition: deepseek-v4-flash
|
||||
- term: Tool calls
|
||||
- definition: "0"
|
||||
|
||||
# Streaming assistant
|
||||
|
||||
- term: Source
|
||||
- definition:
|
||||
- 'button "Request #1"'
|
||||
- term: Status
|
||||
- definition: Pending
|
||||
- term: Tokens
|
||||
- definition: —
|
||||
|
||||
# Streaming request
|
||||
|
||||
- term: Status
|
||||
- definition: Pending
|
||||
- term: Provider
|
||||
- definition: deepseek-official
|
||||
- term: Model
|
||||
- definition: deepseek-v4-flash
|
||||
- term: Tool calls
|
||||
- definition: "1"
|
||||
- term: Result
|
||||
- definition:
|
||||
- button "Assistant Message"
|
||||
|
||||
# Settled request
|
||||
|
||||
- term: Status
|
||||
- definition: Completed
|
||||
- term: Provider
|
||||
- definition: deepseek-official
|
||||
- term: Model
|
||||
- definition: deepseek-v4-flash
|
||||
- term: Tool calls
|
||||
- definition: "1"
|
||||
- term: Subtool calls
|
||||
- definition: "2"
|
||||
- term: Result
|
||||
- definition:
|
||||
- button "Assistant Message"
|
||||
|
||||
# Settled assistant
|
||||
|
||||
- term: Source
|
||||
- definition:
|
||||
- 'button "Request #1"'
|
||||
- term: Status
|
||||
- definition: Completed
|
||||
- term: Tokens
|
||||
- definition: 235 tok
|
||||
- term: Reasoning
|
||||
- definition: 75 tok
|
||||
- term: Content
|
||||
- definition: 160 tok
|
||||
Reference in new issue
Block a user