深入理解 DeepSeek Harness · 第 7 篇
流式输出:从模型 token 到 UI 帧
前情回顾
第 6 篇把持久事实讲完:追加日志、投影重建、fork 与迁移链。本篇处理另一半——那些不落盘却又必须实时到达浏览器的流式帧。边界在第 3 篇已经立过:持久(durable)事件可重放,实时(live)事件只在进程内传播。
本章要回答的问题
模型吐出的 chunk(增量片段)如何同时满足「UI 立刻看到」和「历史可重建」?agent/assistant-stream 的三帧协议带什么字段、按什么顺序?为什么前端拿到的序号是小数?UI 为什么只把 delta(增量)当作动画帧(animation-frame),而不是展开已经结算的完整流?
你会学到什么 / 先验知识
你会看懂无损压缩的 attempt(一次模型尝试)记录、增量累加器、process-local(进程内)的 start/chunk/end 三帧、Web Session-follow(会话跟随)适配器的小数序号与 rebaseline(重定基线),以及 Chat / Trajectory 的 delta 渲染约束。先验是第 6 篇的 assistant/message 与 assistant/attempt 区分。
核心概念:持久结算 + 实时帧,两条轨
[文档] docs/architecture.md:112 给出边界:agent/assistant-stream 发布进程内的 start、临时 chunk、end 帧;循环在提交 end frame 之前,把完整压缩流作为一条消息或只记日志的 attempt 落盘;Web Session-follow 适配器是该 live 事件唯一的远端消费者。
五个术语先定死:process-local 指只在当前进程内传播、不落盘也不发远端;Session-follow 是 Web 端跟随某会话 live 事件流、把进程内帧转成浏览器可见条目的适配器;packed run(压缩片段序列)指同类型连续 chunk 压缩后的记录,即除原始 chunk 外的三种记录(packages/llm/llm/src/assistant-stream.ts:45-46);pending 是暂存「已跟随到、等待匹配 durable 结算」的 Map(client/sessions/assistant-stream.ts:47,113-117);publishedSeqs 是已发布事件的 seq 集合,用于去重(同文件 :48,77)。
graph LR
A[模型 chunk] --> B[AssistantStreamAccumulator<br/>增量压缩]
B --> C[持久结算<br/>assistant/message 或 assistant/attempt<br/>内嵌完整无损流]
A --> D[live 三帧<br/>start[attemptId/revision/turn/step]<br/>chunk[index/time/chunk]<br/>end[index/outcome]]
D --> E[Web Session-follow<br/>小数 seq + rebaseline]
E --> F[Chat / Trajectory<br/>delta 动画帧]
C -. 重放历史 .-> F
两条轨的汇合点在 UI:持久轨提供「结算后的事实」,实时轨提供「正在发生的过程」。前端必须同时消费两者,且不能把过程误当成事实。
源码走读:五处证据
证据一:压缩记录是无损的。 [源码] packages/llm/llm/src/assistant-stream.ts:18-46:
/** Lossless compact records embedded in durable Assistant attempt events. */ export type AssistantStreamRecord = | { readonly type: 'text-chunks' readonly time0: number readonly index: number readonly dt: readonly number[] readonly texts: readonly string[] } | { readonly type: 'reasoning-chunks' readonly time0: number readonly index: number readonly dt: readonly number[] readonly texts: readonly string[] } | { readonly type: 'tool-call-chunks' readonly time0: number readonly index: number readonly dt: readonly number[] readonly id: ToolCallId readonly name?: string readonly args: readonly string[] } | { readonly type: 'chunk'; readonly time: number; readonly chunk: StreamChunk } /** One packed delta run: every compact record except a raw `chunk`. */ export type AssistantStreamRun = Exclude<AssistantStreamRecord, { type: 'chunk' }>
三种打包记录用 time0 加 dt(相邻时间差)重建每个 chunk 的原始时刻,texts / args 保留原文;第四种 chunk 是永不打包的 chunk 类型(block-start / block-end / usage / finish,以及空 id 或空 name 的 tool-call delta,assistant-stream.ts:48-52,167-172)保留的原始块。注释里的「lossless」不是营销词——dt + texts 能精确还原时间与内容;[推演] 这样打包省掉的是每条 chunk 重复的事件信封,而不是合并 token 边界(docs/subsystems/llm-streaming.md:224)。
证据二:累加器不保留第二份原始列表。 [源码] packages/llm/llm/src/assistant-stream.ts:98-127(节选主要分支):
/** Incrementally compacts one attempt without retaining a second raw-chunk list. */ export class AssistantStreamAccumulator { private readonly records: MutableRecord[] = [] /** * Add one timed chunk to the compact attempt stream. * @param value - model chunk and its original Session timestamp. * @returns a detached immutable copy for assembly and live publication. */ push(value: TimedStreamChunk): TimedStreamChunk { const time = safeTime(value.time) const chunk = snapshotChunk(value.chunk) const timed = deepFreeze({ time, chunk }) const previous = this.records.at(-1) switch (chunk.type) { case 'text-delta': case 'reasoning-delta': { safeIndex(chunk.index, chunk.type) if (typeof chunk.text !== 'string') throw new TypeError(`${chunk.type} text must be a string`) const type = chunk.type === 'text-delta' ? 'text-chunks' : 'reasoning-chunks' const gap = previous !== undefined && previous.type === type ? safeGap(previous.lastTime, time) : undefined if (previous !== undefined && previous.type === type && previous.index === chunk.index && gap !== undefined) { previous.dt.push(gap) previous.texts.push(chunk.text) previous.lastTime = time } else { this.records.push({ type, time0: time, index: chunk.index, dt: [], texts: [chunk.text], lastTime: time }) } return timed }
push 每次返回一份冻结的 timed 副本给组装与 live 发布,内部只维护压缩记录:同类型、同 index、时间差安全时继续往当前记录的 dt/texts 追加,否则新开一条同类型压缩记录。注意 safeGap 返回 undefined 时走的也是新开记录,不是退化成原始 chunk——原始 chunk 只留给永不打包的类型。这就是「只有一份流」的实现。
证据三:三帧的生产者与顺序约束。 [源码] packages/core/agent-loop/src/assistant-stream.ts:49-72 与 :79-98:
/** Publish the opening marker before the first delivered chunk. */ start(): void { this.emit({ type: 'start', attemptId: this.attemptId, revision: this.nextRevision(), turn: this.turn, step: this.step, }) } /** Snapshot one chunk once, then feed durable compaction, assembly, and live publication. */ push(chunk: StreamChunk): void { const timed = this.accumulator.push({ time: Date.now(), chunk }) this.assembler.push(timed.chunk) this.emit({ type: 'chunk', attemptId: this.attemptId, revision: this.nextRevision(), index: this.index++, time: timed.time, chunk: timed.chunk, }) }
settle( eventType: 'assistant/message' | 'assistant/attempt', append: () => SessionSeq, ): void { let seq: SessionSeq try { seq = append() } catch (error: unknown) { this.abandon() throw error } this.terminal = true this.emit({ type: 'end', attemptId: this.attemptId, revision: this.nextRevision(), index: this.index, outcome: { kind: 'committed', eventType, seq }, }) }
三帧契约可以列成表:
| 帧 | 关键字段 | 顺序约束 |
|---|---|---|
start | attemptId、revision、turn、step | 早于第一个 chunk 发布(:49-58) |
chunk | attemptId、revision、index、time、chunk | index 由 this.index++ 递增;每帧 nextRevision()(:60-72) |
end | attemptId、revision、index、outcome | settle() 先 append() 再发 end,outcome: { kind: 'committed', eventType, seq };无法提交时 abandon() 发 { kind: 'abandoned' }(:79-110) |
消费端是 packages/api/session-controller/src/client/sessions/assistant-stream.ts:131-196 的 acceptFrame switch:它按帧类型更新 activeAttempt、校验 index,并决定返回 transient、publication 还是 rebaseline。
证据四:Web 适配器用小数序号把 transient 插在 durable 之间。 [源码] packages/api/session-controller/src/client/sessions/assistant-stream.ts:44-50 给出状态:durableCursor = -1、transientInGap = 0、pending Map 与 publishedSeqs 集合。:80-97 在重连基线里重建 transient 时这样生成序号:
for (const [index, member] of expandAssistantStream( opening.stream as unknown as readonly AssistantStreamRecord[], ).entries()) { this.transientInGap += 1 visible.push({ type: 'transient', event: { type: 'assistant/live-chunk', seq: this.durableCursor + 1 - 1 / (this.transientInGap + 1), time: member.time, data: { attemptId: opening.attemptId, turn: opening.turn, step: opening.step, chunk: member.chunk, }, }, })
实时 chunk 走同一套序号(client/sessions/assistant-stream.ts:143-167):第一个 transient 是 durableCursor + 0.5,第二个是 + 0.667,永远小于下一条 durable 事件的整数 seq,于是按 seq 排序时过程帧自然排在「当前持久边界」与「下一条持久事件」之间。重定基线的触发条件要按源码逐条对:index 不连续(:149、:176)、start 时已有活跃/保留 attempt 或 pending 未清(:133)、pending 缺匹配或类型不符(:186)、durable seq 撞上 pending(:115)——这些返回 rebaseline。而 attemptId 不匹配 是另一回事::148 与 :172 直接 return undefined,静默忽略该帧,交给持久结算发布。
证据五:UI 只把 delta 作为动画帧。 [源码] packages/client/ui-chat/src/client/conversation-nodes/assistant.ts:303-337:
/** Per-step Assistant lifecycle; materialized keys survive cleared stream content as hidden Nodes. */ export const assistantDefinition: ConversationNodeDefinition<AssistantState> = { kind: 'assistant-step', target: 'chat', match: (event) => { if (event.type === 'step/start') return { id: `${event.data.turn}:${event.data.step}`, role: 'start' } if (event.type === 'assistant/live-chunk' || (event.type === 'assistant/message' && event.surfaceOp === 'append')) { return { id: `${event.data.turn}:${event.data.step}`, role: 'update' } } if (event.type === 'llm/retry') { return { id: `${event.data.turn}:${event.data.step}`, role: 'update' } } return null }, start: (_context, match) => { if (match.event.type !== 'step/start') throw new Error('assistant-step start requires step/start') return initialState(match.event.data.turn, match.event.data.step) }, update: (context, match) => { if (match.event.type === 'assistant/live-chunk') { return updateChunk(context.state, match.event.data.chunk, match.event.seq, match.event.time) } if (match.event.type === 'assistant/message') return settleMessage(context.state, match, match.event) if (match.event.type === 'llm/retry') { return resetForRetry(context.state) } return context.state }, publication: (match) => { if (match.event.type === 'step/start') return 'none' if (match.event.type !== 'assistant/live-chunk') return 'immediate' const type = match.event.data.chunk.type return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame' },
update 对 live chunk 只做 updateChunk,对 assistant/message 才 settleMessage。publication 更直白:普通 delta 是动画帧(animation-frame),usage / finish 不发布,已结算消息 immediate。Trajectory 侧的折叠同理——[源码] packages/client/ui-trajectory/src/client/trajectory-assistant-definition.ts:334-393 也只把 delta 作为动画帧,不展开已结算流(docs/architecture.md:132 明确说两侧都不展开)。
设计取舍
① 为什么流式是 live 事件而不是 durable 事件? 因为原始 chunk 数量巨大且大多是过程性的;把它们写进日志会让历史膨胀,而重放时不需要逐帧重现。代价是必须维护 dual-track 对账:rebaseline 的那些分支(client/sessions/assistant-stream.ts:115,133,149,176,186)就是为此存在的。
② 为什么压缩用 time0 + dt 而不是绝对时间数组? 因为时间差通常是小整数,而且省掉的是每条 chunk 重复的事件信封;dt 精确、不合并 token 边界。代价是累加器要多维护 lastTime 与前一条记录的类型判断;safeGap 失败时结束当前 run、新开一条同类型记录(assistant-stream.ts:118-125),而不是退化成原始块。
③ 为什么 UI 用动画帧(animation-frame)而不是直接渲染结算消息? 结算消息携带完整无损压缩流与组装后的内容(docs/architecture.md:132),但 Chat / Trajectory 不把它展开成逐 delta 对象用于动画展示;逐 token 的视觉过程需要 delta,而 delta 不能当作事实缓存,否则重连后会与持久历史打架。代价是 UI 必须区分「动画态」与「结算态」两套更新路径。
常见误解
「前端直接订阅模型的原始流。」 不是。它消费的是带小数 seq 的 assistant/live-chunk 帧;data.chunk 虽是快照后的原始 chunk,但被包进了对账帧里,随时可能 rebaseline 回持久事实。
「assistant/attempt 会进入模型历史。」 不会。它是只记日志的失败/重试/取消/流错误尝试,不增加模型历史(docs/architecture.md:132);只有 assistant/message 才进入。
「end frame 一到就可以把流当事实。」 不是。end 只携带 outcome.seq,前端 acceptFrame('end') 要拿它去 pending 对账(client/sessions/assistant-stream.ts:183-194),失配就 rebaseline;abandoned 时根本没有 durable 提交,transient 必须丢弃。durable-before-end 说明的是「事实先落、end 只是尾帧通知」,而不是「end 即事实」。
小结
模型 chunk 经 AssistantStreamAccumulator 增量压缩为无损记录(packages/llm/llm/src/assistant-stream.ts:18-46、:98-127),三帧由 AgentStreamAttempt 发布:start 带身份与轮次、chunk 带递增 index、end 携带持久化结果或 abandoned(packages/core/agent-loop/src/assistant-stream.ts:49-110)。持久侧提交为 assistant/message 或 assistant/attempt,实时侧由 Web Session-follow 用 durableCursor + 1 - 1/(transientInGap+1) 的小数 seq 把过程帧排在持久边界之间、失配时 rebaseline(packages/api/session-controller/src/client/sessions/assistant-stream.ts:44-50、:80-97、:143-167)。UI 只把 delta 当动画帧——因为结算消息虽携带完整流,却不展开为逐 delta 对象,逐 token 过程必须靠 transient(packages/client/ui-chat/src/client/conversation-nodes/assistant.ts:303-337)。
代价落在三处:dual-track 对账、lastTime 与打包判断的额外状态、UI 两套更新路径。第 8 篇回到工具管线,看一次工具调用从 schema 注入到结果落日志的完整链路。
思考题
- 在
packages/api/session-controller/src/client/sessions/assistant-stream.ts:88找到小数 seq 公式。若改用整数递增序号,前端按 seq 排序时会遇到什么问题?为什么分母是transientInGap + 1而不是transientInGap? - 在
packages/llm/llm/src/assistant-stream.ts:118-125找到safeGap返回 undefined 的分支。此时累加器新开的是什么记录?如果改成「退化成原始chunk」,压缩后的 attempt 事件会丢掉什么性质? - 在
packages/client/ui-chat/src/client/conversation-nodes/assistant.ts:332-337的publication()中,usage与finish类型的 chunk 返回none。结合packages/llm/llm/src/assistant-stream.ts:167-172(这两种类型从不打包),说明如果把usage也当animation-frame发布,用户会看到什么?