diff --git a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.i18n.yaml index d7e0f75f2d..71c2325bb3 100644 --- a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.md -2026-07-27-trajectory-inspection-ledger.md: cdeaa30ea64f47b0e0110baf566f747a4591a384 -2026-07-27-trajectory-inspection-ledger.zh.md: df2a3d266161a7c1c4444863971f3d177533af8c +2026-07-27-trajectory-inspection-ledger.md: e3fc22234c1df449c99eac90af27de7da0b6f202 +2026-07-27-trajectory-inspection-ledger.zh.md: abf8fd3bcaeabba6061bd415acbe8ddefef7ac79 diff --git a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.md b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.md index cdeaa30ea6..e3fc22234c 100644 --- a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.md +++ b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.md @@ -16,13 +16,16 @@ Trajectory has to make prose, machine payloads, token usage, timing, and nested - Event kind and content form the two stable columns. Role tags align toward the content, nested subtools receive a small indentation, and CSS truncation preserves the available preview width. Token usage and duration stay in the inspector. - Product prose uses the existing sans stack. Turn ids, token counts, durations, tool calls, raw payloads, and other machine data use the existing code stack. - Existing theme tokens own both light and dark rendering. Neutral borders and surfaces form the structure; distinct low-emphasis role hues support scanning without carrying success or failure meaning, while business blue identifies selection, links, and focus. -- The client runtime exposes a read-only history source independent from Session and SessionManager. Each activated source owns its raw entries, paging, live gap repair, and reconnect rebuild; the ordinary conversation snapshot remains the folded Chat projection. Trajectory subscribes to that source, exhausts its paging only while mounted, and lazily derives its event order, context lineage, schema index, and Requests instead of imposing those structures on every conversation consumer. -- Ordinary generation and compaction calls form one chronological Request projection, distinguished by purpose rather than separate collections. Effective prompt state and its change ride the Request that introduced them; compaction and prompt changes are not independent inspection entities. Complete history makes global Request numbering and cumulative usage session-wide rather than tail-window-relative. +- The client runtime exposes a read-only history source independent from Session and SessionManager. Each activated source owns its raw entries, paging, live gap repair, and reconnect rebuild; the ordinary conversation snapshot remains the folded Chat projection. Trajectory opens the source's tail while mounted and requests one older page when the user reaches the loaded range's top, then lazily derives event order, context lineage, schema index, and Requests instead of imposing those structures on every conversation consumer. +- Ordinary generation and compaction calls form one chronological Request projection, distinguished by purpose rather than separate collections. Effective prompt state and its change ride the Request that introduced them; compaction and prompt changes are not independent inspection entities. Request numbering and cumulative usage cover the loaded history window and expand as older pages arrive. - Call schemas come from the active recorded Request header. Keyless snapshot fixtures deliberately replace that catalog with the non-array `{{tools}}` token, which the durable inspection boundary treats as unavailable instead of attempting to project or fabricate schemas. -- Selecting a record or Request opens an inspector inside Trajectory. Tabs and Summary sections follow the selected entity: Markdown messages expose rendered, source, provenance, and hierarchy views; tools add JSON payload/result and schema views; Requests add options, usage, timing, and result navigation. Images render as media rather than serialized data. +- Selecting a record or Request opens an inspector inside Trajectory. Tabs and Summary sections follow the selected entity: Markdown messages expose rendered, source, provenance, and hierarchy views; tools add JSON payload/result and schema views; Requests add options, usage, timing, and result navigation. Scrollable Summary regions keep their scrollbar thumbs transparent until hover or `focus-within`, while retaining the scrollbar reservation and scroll behavior. Images render as media rather than serialized data. - Turn folding removes all rows after its first record and replaces them with a compact step/tool-call count; Assistant folding applies the same interaction to its tool-call descendants. Global controls fold or expand both levels. -- The separate Waterfall tab is removed. A fixed Overview above the ledger projects every record with known `startedAt` onto three semantic timing lanes using its own duration. Finalized Assistant spans divide the recorded interval at the first non-empty token delta, so distinct TTFT and decoding colors retain their actual ratio; incomplete timing falls back to one Assistant color. Hovering for 500 ms exposes exact start/end, total duration, TTFT, and decoding time without relying on the browser's native tooltip delay. Dragging left or right commits an inclusive interval filter: any record whose active interval overlaps either boundary remains visible, records without known timing leave the focused ledger, and clearing the selection restores the full branch. Wheel gestures zoom the time domain. A right-button click clears the interval selection; dragging instead pans an already zoomed viewport without mutating it. The Overview keeps the full time domain while focused so the selection can be resized or cleared without losing orientation. -- Live history updates retain the ledger's bottom position only while the user is already following its tail. Scrolling upward clears that follow state, so streamed chunks and newly appended records do not interrupt inspection of earlier rows. +- A long ledger initially positions the loaded tail at the bottom and mounts only the viewport's row window plus bounded overscan. Request-only separators join the next measurable virtual item, with a terminal separator retaining its own fixed clearance, so the virtualizer never owns a zero-height item. Semantic DOM-safe row keys and ARIA indexes expose identity independently from mount position. A tail with known older history virtualizes immediately even when its loaded projection is below the ordinary row threshold. Stable-key virtualizer anchoring preserves the visible item across prepends and appends; the manual scroll-height fallback applies only when completing pagination disables virtualization. Selection, timeline focus, folding, search, and bottom following address records by stable event or tool-call identity rather than requiring their DOM rows to exist. An explicit loading row covers records until initial positioning finishes and while an older page is pending. The raw window base sequence detects a prepend even when a page adds no surface-visible node. +- The separate Waterfall tab is removed. A fixed Overview above the ledger projects every loaded record with known `startedAt` onto three semantic timing lanes using its own duration. While an older prefix remains unloaded and the viewport includes the loaded domain's start, a neutral ellipsis control covers the truncated edge and loads one earlier page without assigning unknown history a fabricated duration; hovering that control suppresses the ordinary timeline cursor. Finalized Assistant spans divide the recorded interval at the first non-empty token delta, so distinct TTFT and decoding colors retain their actual ratio; incomplete timing falls back to one Assistant color. Hovering for 500 ms exposes exact start/end, total duration, TTFT, and decoding time without relying on the browser's native tooltip delay. Dragging left or right commits an inclusive interval filter: any record whose active interval overlaps either boundary remains visible, records without known timing leave the focused ledger, and clearing the selection restores the full branch. Wheel gestures zoom the time domain. A right-button click clears the interval selection; dragging instead pans an already zoomed viewport without mutating it. The Overview keeps the full time domain while focused so the selection can be resized or cleared without losing orientation. +- Live history updates retain the ledger's bottom position only while the user is already following its tail. Scrolling upward clears that follow state, so streamed chunks and newly appended records do not interrupt inspection of earlier rows. Tail following and virtualizer measurement react to row keys and heights rather than content identity, so text-only stream frames neither discard the measurement cache nor repeat a DOM scroll write. +- Token streaming reuses the finalized history inspection, layout, Request numbering, Overview projection, and search results. A frame appends only the current partial Assistant cells and searches that partial when a query is active; text and reasoning deltas do not re-fold or rescan the loaded prefix, while message completion, tool lifecycle, compaction, rewrites, and other structural events rebuild the affected projections. Before those rebuilds, the inspection ledger drops completed-step token payloads that no projection reads while retaining the first visible token for timing, every usage chunk for accounting, and every chunk from unfinished or interrupted steps; the independent history source retains the raw entries. +- History folding rebases only the loaded surface events into a compact contiguous input for the canonical surface manager, then maps its nodes back to absolute session sequences. Structural events therefore retain canonical replacement validation without replaying token chunks or materializing synthetic events for unloaded sequences. - Trajectory opts into a conversation-owned composer overlay through `data-conversation-composer-overlay`. `ConversationRoot` positions the composer seat and publishes its live height; Trajectory keeps the ledger at full height and reserves that height plus 16 px inside its vertical table and inspector scrollers. Those panes adapt to the available width instead of exposing horizontal scrollbars beneath the overlay. - This local inspector remains independent from the conversation-wide Chat details column. At narrow widths it overlays the ledger and remains dismissible by keyboard or pointer. @@ -32,6 +35,12 @@ Trajectory has to make prose, machine payloads, token usage, timing, and nested **Keep one card per Turn and Step.** Rejected: repeated card chrome reduced the number of visible records and made cross-step comparison slower. +**Mount every projected record in the table.** Rejected: record projection remains useful for search, timing, and navigation, but keeping every row and its descendants in the DOM makes browser rendering scale with the complete session instead of the visible viewport. + +**Exhaust every history page when Trajectory mounts.** Rejected: complete session metrics would be immediately available, but transporting and repeatedly projecting old chunk-heavy pages delays inspection of the current tail. On-demand backward paging makes that cost follow the user's navigation. + +**Rebuild the loaded ledger for every streamed token chunk.** Rejected: virtual rows bound DOM work but do not make repeated history folding cheap. Keeping finalized projections stable makes ordinary deltas proportional to the current partial, while structural events remain the explicit full-rebuild boundary. + **Flatten every record without Turn or Request boundaries.** Rejected: a trajectory is not merely a log stream; those boundaries preserve the causal structure without consuming dedicated rows. **Reuse the global Chat details column.** Rejected: it would couple local inspection to conversation navigation and make a row click unexpectedly change another view's state. @@ -44,4 +53,4 @@ Trajectory has to make prose, machine payloads, token usage, timing, and nested ## Consequences -Trajectory shows more useful records per viewport while retaining Turn and Request orientation. Context rewrites and compactions remain inline with their surrounding history, while a rewind begins a successor branch that inherits only the retained prefix. The floating composer leaves the ledger visible to the viewport edge without covering its final rows or hiding horizontal controls. The main ledger omits token usage and duration so content receives the available width; the local inspector exposes those facts together with full payloads, provenance, schemas, and request timing. The Overview uses recorded start/duration and token-boundary facts without fabricating live elapsed time, and its inclusive focus behavior matches the interaction users already know from Chrome DevTools Network. Focused component tests pin tail following, timing projection, delayed detail disclosure, folding, record and interval selection, entity-specific tabs, and running/error semantics; the assembled Web snapshot pins the ledger, Overview timing details, composer overlay geometry, and inspector through the real client composition. +Trajectory shows more useful records per viewport while retaining Turn and Request orientation. Context rewrites and compactions remain inline with their surrounding history, while a rewind begins a successor branch that inherits only the retained prefix. The floating composer leaves the ledger visible to the viewport edge without covering its final rows or hiding horizontal controls. The main ledger omits token usage and duration so content receives the available width; the local inspector exposes those facts together with full payloads, provenance, schemas, and request timing. The Overview uses recorded start/duration and token-boundary facts without fabricating live elapsed time, and its inclusive focus behavior matches the interaction users already know from Chrome DevTools Network. Tail-first paging bounds initial transport and projection work, virtualization bounds mounted row elements, incremental partial projection removes loaded-history length from ordinary token-frame work, and completed-step chunk compaction makes structural rebuilds proportional to inspection-relevant entries rather than the raw token count. Focused component tests pin tail-first paging, prepend anchoring and identity retention, the virtual window, tail following, content-only streaming without repeated scroll writes, streaming structural sharing, high-sequence window folding, timing projection, delayed detail disclosure, folding, record and interval selection, entity-specific tabs, and running/error semantics. A real-browser long-ledger contract pins stable prepend geometry, bounded mounting, top/middle/bottom reachability, and bounded scroll writes across a paced stream; the assembled Web snapshot pins the ledger, Overview timing details, composer overlay geometry, and inspector through the real client composition. diff --git a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.zh.md b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.zh.md index df2a3d2661..abf8fd3bca 100644 --- a/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-trajectory-inspection-ledger.zh.md @@ -16,13 +16,16 @@ Status: implemented - 事件类型与内容构成两个稳定列。角色标签朝内容侧对齐,嵌套子工具略微缩进,内容预览使用 CSS 截断以适应可用宽度。token 用量和耗时留在检查器中。 - 产品正文使用现有无衬线字体栈。轮次 id、token 数、耗时、工具调用、原始载荷和其他机器数据使用现有代码字体栈。 - 现有主题 token 同时负责亮色和暗色渲染。中性边框与表面构成整体结构;区分度较低的角色色帮助扫读而不表达成功或失败语义,业务蓝色则标识选择状态、链接和焦点。 -- 客户端 runtime 提供独立于 Session 和 SessionManager 的只读历史数据源。每个已激活的数据源自行拥有原始条目、分页、实时缺口修复和重连重建;普通会话快照仍然只是 Chat 所需的折叠投影。Trajectory 订阅该数据源,仅在挂载期间补齐全部历史,并按需派生事件顺序、上下文谱系、schema 索引和请求,避免让所有会话消费者承担这些结构。 -- 普通生成调用与压缩调用形成一条按时间排序的请求投影,以 purpose 区分而不是放入不同集合。生效的提示词状态及其变化附着在引入它们的请求上;压缩和提示词变化都不是独立检查实体。完整历史使全局请求编号和累计用量以整个会话为范围,而不是相对于末尾窗口。 +- 客户端 runtime 提供独立于 Session 和 SessionManager 的只读历史数据源。每个已激活的数据源自行拥有原始条目、分页、实时缺口修复和重连重建;普通会话快照仍然只是 Chat 所需的折叠投影。Trajectory 在挂载期间打开该数据源的尾部,当用户到达已加载范围顶部时请求一页更早的历史,再按需派生事件顺序、上下文谱系、schema 索引和请求,避免让所有会话消费者承担这些结构。 +- 普通生成调用与压缩调用形成一条按时间排序的请求投影,以 purpose 区分而不是放入不同集合。生效的提示词状态及其变化附着在引入它们的请求上;压缩和提示词变化都不是独立检查实体。请求编号和累计用量覆盖已加载的历史窗口,并随更早页面到达而扩展。 - 调用 schema 来自当前生效且已记录的请求头。无密钥快照 fixture(测试前置数据)有意将该目录替换为非数组 token `{{tools}}`,持久化检查边界会将其视为不可用,而不是尝试投影或虚构 schema。 -- 选择记录或请求后,轨迹视图内部会打开检查器,其标签页和概览区域随实体类型变化:Markdown 消息提供渲染、源码、来源和层级视图;工具提供 JSON 载荷/结果和 schema 视图;请求提供选项、用量、计时和结果跳转。图片以媒体形式渲染,而不是显示为序列化数据。 +- 选择记录或请求后,轨迹视图内部会打开检查器,其标签页和概览区域随实体类型变化:Markdown 消息提供渲染、源码、来源和层级视图;工具提供 JSON 载荷/结果和 schema 视图;请求提供选项、用量、计时和结果跳转。可滚动的概述区域默认保持滚动条滑块透明,直到悬停或 `focus-within` 时才显示,同时保留滚动条预留空间和滚动行为。图片以媒体形式渲染,而不是显示为序列化数据。 - 折叠轮次时保留其第一条记录,将后续行替换为紧凑的步骤和工具调用数量;折叠助手时对其工具调用后代应用相同交互。全局控件可以分别折叠或展开这两个层级。 -- 移除独立的 waterfall(瀑布式事件)标签页。固定在记录表上方的 Overview 区域将所有 `startedAt` 已知的记录按各自耗时投影到三条语义计时轨道。已完成的助手时间条以首个非空 token 增量为分界,用不同颜色按真实比例表示 TTFT 与解码时间;计时不完整时退化为单一助手色。悬停 500 ms 后会显示精确起止时刻、总耗时、TTFT 和解码时间,而不依赖浏览器原生 tooltip 的延迟。向左或向右拖动会提交包含边界的区间筛选:任何活动区间与所选区间相交的记录都会保留,计时未知的记录会从聚焦后的记录表中移除,清除选择则恢复完整分支。滚轮手势用于缩放时间域。右键单击会清除区间选择;右键拖动则只会平移已放大的 viewport,不会改变该选区。聚焦后,Overview 区域仍保留完整时间范围,以便在不失去方位的情况下调整或清除选择。 -- 实时历史更新仅在用户已经跟随记录表末尾时保留底部位置。向上滚动会清除跟随状态,因此流式分块和新追加的记录不会打断对旧记录的检查。 +- 长记录表初始时将已加载尾部置于底部,只挂载视口对应的行窗口及有界的额外缓冲行。仅含请求的分隔行并入下一个具备可测高度的虚拟项,末尾分隔行则保留固定留白,因此虚拟化器不会管理零高度项。可安全用于 DOM 的语义行键与 ARIA 索引使标识不依赖挂载位置。只要已知尾部之前仍有更早历史,即使当前已加载投影低于常规行数阈值,也会立即启用虚拟化。基于稳定键的虚拟化器锚定会在向前补页和尾部追加时保留当前可见项;只有分页完成导致虚拟化停用时,才使用手动滚动高度兜底。选择、时间线聚焦、折叠、搜索和末尾跟随均按稳定的事件或工具调用标识定位,不要求对应 DOM 行已存在。初始定位完成前以及更早页面仍在等待时,明确的加载行会遮住真实记录。原始窗口的基准序号即使在一页未增加任何 surface 可见节点时,也能检测到这次向前补页。 +- 移除独立的 waterfall(瀑布式事件)标签页。固定在记录表上方的 Overview 区域将所有 `startedAt` 已知的已加载记录按各自耗时投影到三条语义计时轨道。仍有更早前缀尚未加载且 viewport 包含已加载时间域起点时,中性的省略号控件会遮住截断边缘并加载一页更早历史,而不会为未知历史虚构耗时;悬停在该控件上会隐藏普通的时间线光标。已完成的助手时间条以首个非空 token 增量为分界,用不同颜色按真实比例表示 TTFT 与解码时间;计时不完整时退化为单一助手色。悬停 500 ms 后会显示精确起止时刻、总耗时、TTFT 和解码时间,而不依赖浏览器原生 tooltip 的延迟。向左或向右拖动会提交包含边界的区间筛选:任何活动区间与所选区间相交的记录都会保留,计时未知的记录会从聚焦后的记录表中移除,清除选择则恢复完整分支。滚轮手势用于缩放时间域。右键单击会清除区间选择;右键拖动则只会平移已放大的 viewport,不会改变该选区。聚焦后,Overview 区域仍保留完整时间范围,以便在不失去方位的情况下调整或清除选择。 +- 实时历史更新仅在用户已经跟随记录表末尾时保留底部位置。向上滚动会清除跟随状态,因此流式分块和新追加的记录不会打断对旧记录的检查。末尾跟随与虚拟化器测量仅响应行键和高度,而非内容标识,因此仅含文本的流式帧既不会丢弃测量缓存,也不会重复执行 DOM 滚动写入。 +- token 流式输出会复用已完成历史的检查结果、布局、请求编号、Overview 投影和搜索结果。每个帧只追加当前未完成助手的单元格,并在查询处于激活状态时搜索这部分内容;文本与推理(reasoning)增量不会重新折叠或扫描已加载前缀,而消息完成、工具生命周期、压缩、`rewrite` 及其他结构事件会重建受影响的投影。在这些投影重建前,检查记录表会丢弃已完成步骤中没有任何投影读取的 token 载荷,但会保留首个可见 token 用于计时、保留所有用量分片用于核算,并保留未完成或中断步骤的所有分片;独立历史数据源仍保留原始条目。 +- 历史折叠只把已加载的 surface 事件重新编号为紧凑连续的输入并交给规范 surface manager,再将其节点映射回会话绝对序号。因此,结构事件会保留规范的替换校验,而无需重放 token 分片,也不会为未加载的序号实体化合成事件。 - Trajectory 通过 `data-conversation-composer-overlay` 启用由会话持有的 composer 浮层模式。`ConversationRoot` 负责定位 composer seat 并发布其实时高度;Trajectory 让记录表保持全高,并在记录表与检查器的纵向滚动容器内预留该高度加 16 px。这两个窗格会根据可用宽度自适应,而不会在浮层下方暴露横向滚动条。 - 此局部检查器与会话级 Chat 详情栏相互独立。在窄屏下,检查器会覆盖记录表,并且仍可通过键盘或指针关闭。 @@ -32,6 +35,12 @@ Status: implemented **每个轮次和步骤保留一张卡片。** 不予采纳:重复的卡片框架减少了可见记录数量,并降低了跨步骤比较的速度。 +**在表格中挂载每条投影记录。** 不予采纳:记录投影仍可用于搜索、计时和导航,但把每一行及其后代都保留在 DOM 中,会使浏览器渲染开销随完整会话增长,而非随可见视口增长。 + +**Trajectory 挂载时补齐所有历史页面。** 不予采纳:完整会话指标可以立即获得,但传输并反复投影含大量分片的旧页面会延迟对当前尾部的检查。按需向前分页会让这项成本随用户导航产生。 + +**每收到一个流式 token 分片就重建已加载记录表。** 不予采纳:虚拟行限制了 DOM 工作量,却不会让反复折叠历史变得低廉。保持已完成投影稳定,可以让普通增量的成本只随当前未完成部分增长,而结构事件仍是显式的完整重建边界。 + **不使用轮次或请求边界,将所有记录完全扁平化。** 不予采纳:轨迹并非普通日志流;这些边界无需占用独立行,也能保留因果结构。 **复用全局 Chat 详情栏。** 不予采纳:这会让局部检查与会话导航耦合,还会使行点击意外改变另一个视图的状态。 @@ -44,4 +53,4 @@ Status: implemented ## 后果 -轨迹视图在保留轮次与请求定位的同时,每个视口可以显示更多有效记录。上下文 `rewrite` 与压缩保持在周边历史中的原始位置,`rewind` 则建立仅继承保留前缀的后继分支。浮动 composer 让记录表一直显示到视口边缘,同时不会遮住最后几行,也不会隐藏横向控件。主记录表省略 token 用量和耗时,让内容获得可用宽度;局部检查器展示这些数据以及完整载荷、来源、schema 和请求计时。Overview 区域使用记录的开始时间、耗时与 token 边界数据,而不虚构实时流逝时间,其包含边界的聚焦行为与用户熟悉的 Chrome DevTools Network 交互一致。针对性组件测试锁定末尾跟随、计时投影、延迟展示详情、折叠、记录与区间选择、实体特定标签页和运行/错误语义;组装后的 Web 快照则通过真实客户端组合锁定记录表、Overview 计时详情、composer 浮层几何形状与检查器。 +轨迹视图在保留轮次与请求定位的同时,每个视口可以显示更多有效记录。上下文 `rewrite` 与压缩保持在周边历史中的原始位置,`rewind` 则建立仅继承保留前缀的后继分支。浮动 composer 让记录表一直显示到视口边缘,同时不会遮住最后几行,也不会隐藏横向控件。主记录表省略 token 用量和耗时,让内容获得可用宽度;局部检查器展示这些数据以及完整载荷、来源、schema 和请求计时。Overview 区域使用记录的开始时间、耗时与 token 边界数据,而不虚构实时流逝时间,其包含边界的聚焦行为与用户熟悉的 Chrome DevTools Network 交互一致。尾部优先分页限制初始传输和投影工作量,虚拟化限制已挂载的行元素数量,未完成部分的增量投影让普通 token 帧的工作量不再随已加载历史长度增长,而已完成步骤的分片压缩则让结构重建的工作量与检查所需条目数量成正比,而非与原始 token 数量成正比。针对性组件测试锁定尾部优先分页、向前补页锚定与标识保持、虚拟窗口、末尾跟随、仅含内容的流式输出不会重复写入滚动位置、流式输出的结构共享、高序号窗口折叠、计时投影、延迟展示详情、折叠、记录与区间选择、实体特定标签页和运行/错误语义。真实浏览器中的长记录表契约锁定向前补页时稳定的几何位置、有界挂载、顶部/中部/底部可达性,以及按节奏进行的流式输出中有界的滚动写入;组装后的 Web 快照则通过真实客户端组合锁定记录表、Overview 计时详情、composer 浮层几何形状与检查器。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index abb4c63187..f61278a39f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -46,6 +46,7 @@ External packages that a workspace package resolves at runtime. `scripts/install | [`@opentelemetry/sdk-logs`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 | | [`@shikijs/langs`](https://github.com/shikijs/shiki) | MIT | | [`@standard-schema/spec`](https://github.com/standard-schema/standard-schema) | MIT | +| [`@tanstack/react-virtual`](https://github.com/TanStack/virtual) | MIT | | [`@vscode/ripgrep`](https://github.com/microsoft/vscode-ripgrep) | MIT | | [`anser`](https://github.com/IonicaBizau/anser) | MIT | | [`chokidar`](https://github.com/paulmillr/chokidar) | MIT | diff --git a/apps/web/tests/chat-scroll-fixture.ts b/apps/web/tests/chat-scroll-fixture.ts index 7c9bd50afe..cd156e4c5c 100644 --- a/apps/web/tests/chat-scroll-fixture.ts +++ b/apps/web/tests/chat-scroll-fixture.ts @@ -1,7 +1,7 @@ // Synthetic long-chat history for browser behavior contracts. The fixture is // generated through Session so pagination exercises the same event shapes as -// persisted conversations, while unique markers let tests identify semantic -// rows without depending on CSS-module names or the eventual virtualizer DOM. +// persisted conversations, while unique markers identify semantic rows +// without depending on CSS-module names or virtualizer DOM positions. import { CallId, createAssistantMessage, diff --git a/apps/web/tests/snapshots/navigation-panes/trajectory.expected.md b/apps/web/tests/snapshots/navigation-panes/trajectory.expected.md index 3572409fc0..a9b5dbb982 100644 --- a/apps/web/tests/snapshots/navigation-panes/trajectory.expected.md +++ b/apps/web/tests/snapshots/navigation-panes/trajectory.expected.md @@ -5,7 +5,7 @@ - img - searchbox "Search trajectory" - region "Trajectory timeline": - - tooltip "ASSISTANT {{clock}} → {{clock}} Total 1.5 s · TTFT 368 ms · Decoding 1.2 s" + - tooltip "ASSISTANT {{clock}} → {{clock}} Total 1,542 ms · TTFT 368 ms · Decoding 1,174 ms" - table: - rowgroup: - row "SYSTEM, Initial System Prompt": diff --git a/apps/web/tests/trajectory-virtualization.e2e.ts b/apps/web/tests/trajectory-virtualization.e2e.ts new file mode 100644 index 0000000000..287d38c29d --- /dev/null +++ b/apps/web/tests/trajectory-virtualization.e2e.ts @@ -0,0 +1,309 @@ +// Browser contract for the tail-paged, virtualized Trajectory ledger. The +// scenario proves that semantic row identity survives an older-page prepend, +// DOM mounting stays bounded, and every scroll range remains reachable. +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { StreamChunk } from '@deepseek-ai/dsh-llm' +import type { ReplayEntry } from '@deepseek-ai/dsh-llm-replay' +import { createChatScrollFixture } from './chat-scroll-fixture.ts' +import { + launchWebScaffold, + seedSession, + watchConsole, + webSnapshotMode, + type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const MODE = webSnapshotMode() +const SESSION_ID = 'trajectory-virtualization-e2e' +const FIXTURE = createChatScrollFixture({ + markerPrefix: 'TRAJECTORY_VIRTUAL', + title: 'TRAJECTORY_VIRTUAL long ledger', + turns: 88, +}) +const MAX_MOUNTED_ROWS = 160 +const GEOMETRY_TOLERANCE = 2 +const STREAM_MARKER = 'TRAJECTORY_VIRTUAL_STREAM_FINISHED' +const STREAM_TEXT = Array.from( + { length: 80 }, + (_, index) => `stream fragment ${String(index + 1).padStart(2, '0')} `, +).join('') + STREAM_MARKER + +const STREAM_CHUNKS: StreamChunk[] = [ + { type: 'block-start', index: 0, blockType: 'text' }, + ...Array.from({ length: 80 }, (_, index): StreamChunk => ({ + type: 'text-delta', + index: 0, + text: `stream fragment ${String(index + 1).padStart(2, '0')} `, + })), + { type: 'text-delta', index: 0, text: STREAM_MARKER }, + { type: 'block-end', index: 0, block: { type: 'text', text: STREAM_TEXT } }, + { type: 'usage', usage: { inputTokens: 2_700, outputTokens: 240 } }, + { type: 'finish', reason: { kind: 'stop' } }, +] + +interface ScrollGeometry { + readonly clientHeight: number + readonly scrollHeight: number + readonly scrollTop: number +} + +interface RowAnchor { + readonly key: string + readonly top: number +} + +async function openSeed(page: Page): Promise { + const search = page.getByRole('textbox', { name: 'Search name, keywords...', exact: true }) + await search.fill(FIXTURE.markers.user(1)) + const result = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem') + await expect.poll(() => result.count(), { timeout: 60_000 }).toBe(1) + await result.click() + await page.getByRole('tab', { name: 'Trajectory', exact: true }).waitFor({ timeout: 30_000 }) + await page.getByText(FIXTURE.markers.assistant(FIXTURE.turns), { exact: false }) + .last() + .waitFor({ timeout: 30_000 }) +} + +async function openTrajectory(page: Page): Promise { + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + const pane = page.locator('[data-trajectory-scroll]') + await pane.waitFor({ timeout: 30_000 }) + await page.locator('[data-trajectory-scroll] table[data-scroll-ready="true"]') + .waitFor({ timeout: 30_000 }) +} + +async function logicalRows(page: Page): Promise { + const raw = await page.locator('[data-trajectory-scroll] table').getAttribute('aria-rowcount') + if (raw === null || !/^\d+$/.test(raw)) { + throw new Error(`trajectory table has invalid aria-rowcount ${JSON.stringify(raw)}`) + } + return Number(raw) +} + +async function mountedRows(page: Page): Promise { + return page.locator('[data-trajectory-scroll] tr[data-trajectory-row-key]').count() +} + +async function geometry(page: Page): Promise { + return page.locator('[data-trajectory-scroll]').evaluate(host => ({ + clientHeight: host.clientHeight, + scrollHeight: host.scrollHeight, + scrollTop: host.scrollTop, + })) +} + +async function nextPaint(page: Page): Promise { + await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => { resolve() })) + })) +} + +async function scrollToRatio(page: Page, ratio: number): Promise { + await page.locator('[data-trajectory-scroll]').evaluate((host, value) => { + const maximum = Math.max(0, host.scrollHeight - host.clientHeight) + host.scrollTop = Math.round(maximum * value) + host.dispatchEvent(new Event('scroll')) + }, ratio) + await nextPaint(page) +} + +async function firstVisibleRow(page: Page): Promise { + return page.locator('[data-trajectory-scroll]').evaluate((host) => { + const hostBox = host.getBoundingClientRect() + const rows = [...host.querySelectorAll('tr[data-trajectory-row-key]')] + const row = rows.find((candidate) => { + const box = candidate.getBoundingClientRect() + return candidate.dataset.requestOnly !== 'true' + && box.bottom > hostBox.top + && box.top < hostBox.bottom + }) + const key = row?.dataset.trajectoryRowKey + if (row === undefined || key === undefined) { + throw new Error('trajectory scrollport has no visible semantic row') + } + return { key, top: row.getBoundingClientRect().top - hostBox.top } + }) +} + +async function rowTop(page: Page, key: string): Promise { + return page.locator('[data-trajectory-scroll]').evaluate((host, targetKey) => { + const rows = [...host.querySelectorAll('tr[data-trajectory-row-key]')] + const row = rows.find(candidate => candidate.dataset.trajectoryRowKey === targetKey) + return row === undefined + ? null + : row.getBoundingClientRect().top - host.getBoundingClientRect().top + }, key) +} + +async function loadToFirstTurn(page: Page): Promise { + const marker = FIXTURE.markers.user(1) + for (let attempt = 0; attempt < 12; attempt += 1) { + await scrollToRatio(page, 0) + if (await page.getByText(marker, { exact: false }).count() > 0) return + const before = await logicalRows(page) + await expect.poll(async () => ({ + marker: await page.getByText(marker, { exact: false }).count() > 0, + rows: await logicalRows(page), + }), { timeout: 30_000 }).not.toEqual({ marker: false, rows: before }) + } + throw new Error('trajectory did not reach the first turn after twelve older-page requests') +} + +describe('web e2e: Trajectory virtualization over tail-paged history', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let replayDir: string + + beforeAll(async () => { + replayDir = await mkdtemp(join(tmpdir(), 'dsh-trajectory-virtualization-')) + const replayFixture = join(replayDir, 'session.jsonl') + const replayOverride = join(replayDir, 'replay.override.json') + await writeFile(replayFixture, FIXTURE.log) + await writeFile(replayOverride, JSON.stringify([{ + kind: 'chunks', + chunks: STREAM_CHUNKS, + } satisfies ReplayEntry])) + scaffold = await launchWebScaffold({ + paceMs: 10, + replayFixture, + replayOverride, + }) + await seedSession(scaffold, FIXTURE.log, SESSION_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser, 900) + tripwire = watchConsole(page) + await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await page.getByText('1 session', { exact: true }).waitFor({ timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await rm(replayDir, { recursive: true, force: true }) + }) + + it.skipIf(MODE === 'record')('retains identity on prepend and reaches the bounded virtual range', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-trajectory-virtualization')) + await openSeed(page) + + let held = false + let releaseHistory: () => void = () => {} + let finishHeldRequest: () => void = () => {} + const gate = new Promise((resolve) => { releaseHistory = resolve }) + const heldRequestFinished = new Promise((resolve) => { finishHeldRequest = resolve }) + await page.route('**/api/session.history', async (route) => { + const request = route.request().postDataJSON() as { + method?: string + payload?: { beforeSeq?: number } + } + if (!held && request.method === 'session.history' && request.payload?.beforeSeq !== undefined) { + held = true + await gate + try { + await route.continue() + } finally { + finishHeldRequest() + } + return + } + await route.continue() + }) + + try { + await openTrajectory(page) + const initialRows = await logicalRows(page) + expect(initialRows).toBeGreaterThan(0) + expect(await page.getByText('Initial System Prompt', { exact: true }).count()).toBe(0) + expect(await mountedRows(page)).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) + + await scrollToRatio(page, 0) + await expect.poll(() => held, { timeout: 15_000 }).toBe(true) + const anchor = await firstVisibleRow(page) + const selectedRow = page.locator( + `[data-trajectory-scroll] tr[data-trajectory-row-key=${JSON.stringify(anchor.key)}]`, + ) + await selectedRow.click() + await expect.poll(() => selectedRow.getAttribute('aria-selected'), { timeout: 10_000 }) + .toBe('true') + + releaseHistory() + await expect.poll(() => logicalRows(page), { timeout: 60_000 }).toBeGreaterThan(initialRows) + await nextPaint(page) + await expect.poll(async () => { + const top = await rowTop(page, anchor.key) + return top === null ? Number.POSITIVE_INFINITY : Math.abs(top - anchor.top) + }, { timeout: 15_000 }).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + await expect.poll(() => selectedRow.getAttribute('aria-selected'), { timeout: 10_000 }) + .toBe('true') + expect(await mountedRows(page)).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) + + await loadToFirstTurn(page) + await expect.poll( + () => page.getByText(FIXTURE.markers.user(1), { exact: false }).count(), + { timeout: 10_000 }, + ).toBeGreaterThan(0) + const fullRows = await logicalRows(page) + + await scrollToRatio(page, 0.5) + const middle = await geometry(page) + const maximum = middle.scrollHeight - middle.clientHeight + expect(middle.scrollTop).toBeGreaterThan(maximum * 0.25) + expect(middle.scrollTop).toBeLessThan(maximum * 0.75) + expect(await mountedRows(page)).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) + expect(await mountedRows(page)).toBeLessThan(fullRows) + + await scrollToRatio(page, 1) + await expect.poll(async () => { + const value = await geometry(page) + return value.scrollHeight - value.clientHeight - value.scrollTop + }, { timeout: 10_000 }).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + await expect.poll( + () => page.getByText(FIXTURE.markers.assistant(FIXTURE.turns), { exact: false }).count(), + { timeout: 10_000 }, + ).toBeGreaterThan(0) + expect(await mountedRows(page)).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) + + const trajectoryScroll = page.locator('[data-trajectory-scroll]') + await trajectoryScroll.evaluate((host) => { + const measuredWindow = window as Window & { __trajectoryScrollCalls?: number } + measuredWindow.__trajectoryScrollCalls = 0 + const original = host.scrollTo.bind(host) + const trackedScrollTo = (...args: [ScrollToOptions?] | [number, number]) => { + measuredWindow.__trajectoryScrollCalls = (measuredWindow.__trajectoryScrollCalls ?? 0) + 1 + Reflect.apply(original, host, args) + } + host.scrollTo = trackedScrollTo as typeof host.scrollTo + }) + const settled = scaffold.whenTurnSettled() + const input = page.locator('textarea').first() + await input.fill('Stream one deterministic response while Trajectory remains visible.') + await input.press('Enter') + await settled + await page.getByText('stream fragment 01', { exact: false }).waitFor({ timeout: 30_000 }) + await nextPaint(page) + const streamingScrollCalls = await trajectoryScroll.evaluate(() => { + return (window as Window & { __trajectoryScrollCalls?: number }) + .__trajectoryScrollCalls ?? 0 + }) + expect(streamingScrollCalls).toBeLessThanOrEqual(5) + expect(await mountedRows(page)).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) + expect({ + pageErrors: tripwire.pageErrors, + warnings: tripwire.warnings, + }).toEqual({ pageErrors: [], warnings: [] }) + } finally { + releaseHistory() + if (held) await heldRequestFinished + await page.unroute('**/api/session.history') + } + }, 180_000) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 49870a42cf..6fe1fe20ac 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -31,6 +31,8 @@ "tests/plan-review.e2e.ts", "tests/steering.e2e.ts", "tests/navigation-panes.e2e.ts", + "tests/chat-scroll-fixture.ts", + "tests/trajectory-virtualization.e2e.ts", "tests/lifecycle-chrome.e2e.ts", "tests/details-session-lifecycle.e2e.ts", "tests/settings-chrome.e2e.ts", diff --git a/docs/core-data-structures/session.i18n.yaml b/docs/core-data-structures/session.i18n.yaml index e66b9dcd8c..a19508682f 100644 --- a/docs/core-data-structures/session.i18n.yaml +++ b/docs/core-data-structures/session.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/core-data-structures/session.md -session.md: c5491b8d6b44c0a86ce5804320533925a0e6e287 -session.zh.md: 3a713c77e972096cf95223701e8aff4cb9d0ff87 +session.md: e6cc05179acd03e2e4564e4690ed2a119ae6d35e +session.zh.md: 0ed5fe99546681ff003e761eabb835e98edf19d5 diff --git a/docs/core-data-structures/session.md b/docs/core-data-structures/session.md index c5491b8d6b..e6cc05179a 100644 --- a/docs/core-data-structures/session.md +++ b/docs/core-data-structures/session.md @@ -311,6 +311,8 @@ The same provenance distinction applies here: only `assistant/message` may carry `Session.surface` returns the session's stable `SessionSurface` view. The same incremental manager validates append candidates before commit and advances this projection from committed events; callers can observe membership and replacement generation but cannot invoke validation. +`SurfaceManager(log, baseSeq?)` can instead fold a contiguous loaded window whose first event has the absolute sequence `baseSeq`. Every event remains contiguous in that absolute sequence space, and a replacement that crosses the window head fails because its declared range is absent. + ```ts type-equiv /** Readonly live projection of the message-producing session events. */ interface SessionSurface { diff --git a/docs/core-data-structures/session.zh.md b/docs/core-data-structures/session.zh.md index 3a713c77e9..0ed5fe9954 100644 --- a/docs/core-data-structures/session.zh.md +++ b/docs/core-data-structures/session.zh.md @@ -313,6 +313,8 @@ interface SurfaceIntent { `Session.surface` 返回会话稳定的 `SessionSurface` 视图。同一个增量管理器在提交前校验追加候选事件,并根据已提交事件推进该投影;调用方可以观察成员关系和替换代次,但不能调用校验。 +`SurfaceManager(log, baseSeq?)` 也可以折叠一个连续的已加载窗口,其第一个事件的绝对序号为 `baseSeq`。每个事件在该绝对序号空间中仍保持连续;如果替换跨过窗口头部,由于其声明的范围并不存在,该替换会失败。 + ```ts type-equiv /** Readonly live projection of the message-producing session events. */ interface SessionSurface { diff --git a/packages/client/runtime/README.i18n.yaml b/packages/client/runtime/README.i18n.yaml index 7bd8051cad..941bff5af7 100644 --- a/packages/client/runtime/README.i18n.yaml +++ b/packages/client/runtime/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/runtime/README.md -README.md: 542d6e5bacf7842533339f4cbbeeddd35df8be79 -README.zh.md: 8a0f10952eccad4df546c122c0365b027e94d7c0 +README.md: e55587202dfdd8b2d3e7e707507ebe041769b7c5 +README.zh.md: 0d5092074592d49807d06e1bb70fc64fc2d6dcf4 diff --git a/packages/client/runtime/README.md b/packages/client/runtime/README.md index 542d6e5bac..e55587202d 100644 --- a/packages/client/runtime/README.md +++ b/packages/client/runtime/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects and the Chat-facing list, scope, and event-window state; SessionHistoryService lazily owns independent raw-history ledgers for inspection consumers; WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into the Session, Workspace, and activated history owners without routing inspection state through Session or SessionManager, and bridges the registry-invalidation frames to typed ctx events (`commands/changed`, `settings/changed`, `credentials/changed`, `models/changed`) so surface caches refetch without touching the stream. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions. +Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects and the Chat-facing list, scope, and event-window state; SessionHistoryService lazily owns independent raw-history ledgers for inspection consumers, loading the current tail first and prepending one older page only when its consumer requests it. Each history snapshot exposes the raw window's absolute base sequence so a consumer detects a prepend even when the page adds no surface-visible node. WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into the Session, Workspace, and activated history owners without routing inspection state through Session or SessionManager, and bridges the registry-invalidation frames to typed ctx events (`commands/changed`, `settings/changed`, `credentials/changed`, `models/changed`) so surface caches refetch without touching the stream. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions. ## Workspace and Session lists diff --git a/packages/client/runtime/README.zh.md b/packages/client/runtime/README.zh.md index 8a0f10952e..0d50920745 100644 --- a/packages/client/runtime/README.zh.md +++ b/packages/client/runtime/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象以及 Chat 所需的列表、scope 和事件窗口状态;SessionHistoryService 为检查类消费方惰性拥有彼此独立的原始历史账本;WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session、Workspace 和已激活的历史数据所有者,不让检查状态经过 Session 或 SessionManager,并把注册表失效帧桥接为类型化 ctx 事件(`commands/changed`、`settings/changed`、`credentials/changed`、`models/changed`),使各表面缓存无需触碰流即可重拉。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent(智能体)和 cwd);客户端不持有任何实体化之前的会话状态——agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。契约:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。 +客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象以及 Chat 所需的列表、scope 和事件窗口状态;SessionHistoryService 为检查类消费方惰性拥有彼此独立的原始历史账本,先加载当前尾部,并仅在消费方请求时向前补入一页更早历史。每份历史快照都会公开原始窗口的绝对基准序号,因此即使该页没有新增任何 surface 可见节点,消费方仍能检测到向前补页。WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session、Workspace 和已激活的历史数据所有者,不让检查状态经过 Session 或 SessionManager,并把注册表失效帧桥接为类型化 ctx 事件(`commands/changed`、`settings/changed`、`credentials/changed`、`models/changed`),使各表面缓存无需触碰流即可重拉。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent(智能体)和 cwd);客户端不持有任何实体化之前的会话状态——agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。契约:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。 ## Workspace 与 Session 列表 diff --git a/packages/client/runtime/src/client/contract/session-history.ts b/packages/client/runtime/src/client/contract/session-history.ts index 2b6679fd05..a48e89585e 100644 --- a/packages/client/runtime/src/client/contract/session-history.ts +++ b/packages/client/runtime/src/client/contract/session-history.ts @@ -9,6 +9,8 @@ export interface SessionHistorySnapshot { state: 'cold' | 'loading' | 'ready' | 'error' error: RpcError | null hasMore: boolean + /** Absolute sequence of the first loaded raw event, or zero for an empty window. */ + baseSeq: number inspection: SessionHistoryInspection } @@ -17,11 +19,17 @@ export interface SessionHistoryFace extends ObservableSnapshot { readonly sessionId: SessionId /** - * Load the tail and exhaust every available older page. - * @param signal - Consumer lifetime; abort is observed between page requests. - * @returns When the available ledger is complete or stops advancing. + * Load the current tail without reading older pages. + * @param signal - Consumer lifetime. + * @returns When the tail is ready or loading fails. */ - loadAll(signal?: AbortSignal): Promise + loadTail(signal?: AbortSignal): Promise + /** + * Prepend one older page when the current window has a predecessor. + * @param signal - Consumer lifetime. + * @returns Whether the loaded window advanced. + */ + loadOlder(signal?: AbortSignal): Promise } /** Runtime service resolving independent history sources. */ diff --git a/packages/client/runtime/src/client/session-history/history-fold.ts b/packages/client/runtime/src/client/session-history/history-fold.ts index c4bc6ed9b5..1a1d2a0f95 100644 --- a/packages/client/runtime/src/client/session-history/history-fold.ts +++ b/packages/client/runtime/src/client/session-history/history-fold.ts @@ -49,18 +49,10 @@ function assistantStepKey(turn: number, step: number): string { return `${turn}\u0000${step}` } -// Trajectory owns surface-window reconstruction so its immutable ledger does -// not depend on Chat's live fold adapter or Session's mutable state. -/* jscpd:ignore-start */ -function paddingEvent(seq: number): SessionEvent { - return { type: 'noop/padding', seq, time: 0, data: {} } as unknown as SessionEvent -} - function replacementCrossesWindowHead(event: SessionEvent, baseSeq: number): boolean { if (!isSurfaceEvent(event) || event.surfaceOp === 'append') return false return event.surfaceOp.start < baseSeq || event.surfaceOp.end < baseSeq } -/* jscpd:ignore-end */ function contextOriginKind(event: SessionEvent | undefined): ConversationContextOriginKind { if (event?.type !== 'user/message') return 'rewrite' @@ -84,27 +76,63 @@ function isTokenDelta(chunk: SessionEvent<'assistant/chunk'>['data']['chunk']): } } -function foldContexts(events: readonly SessionEvent[]): readonly FoldedContext[] { +function foldContexts( + events: readonly SessionEvent[], +): readonly FoldedContext[] { const replay: SessionEvent[] = [] + const originalSeqs: number[] = [] + const rebasedSeqByOriginal = new Map() const surface = new SurfaceManager(replay) const contexts: FoldedContext[] = [] let generation = 0 let originSeq: number | undefined + const originalNodes = () => surface.nodes.map((seq) => { + const original = originalSeqs[seq] + if (original === undefined) throw new Error(`rebased surface seq ${seq} has no origin`) + return original + }) for (const event of events) { - if (isSurfaceEvent(event) && event.surfaceOp !== 'append') { + if (!isSurfaceEvent(event)) continue + if (event.surfaceOp !== 'append') { contexts.push({ generation, - nodes: [...surface.nodes], + nodes: originalNodes(), ...(originSeq === undefined ? {} : { originSeq }), }) generation++ originSeq = event.seq } - replay.push(event) + const rebasedSeq = replay.length + const { + sourceEventSeqs: rawSources, + ...eventWithoutSources + } = event as SessionEvent & { sourceEventSeqs?: readonly number[] } + const mappedSourceEventSeqs = rawSources?.flatMap((seq) => { + const rebased = rebasedSeqByOriginal.get(seq) + return rebased === undefined ? [] : [rebased] + }) + const sourceEventSeqs = mappedSourceEventSeqs?.length === 0 + ? undefined + : mappedSourceEventSeqs + const surfaceOp = event.surfaceOp === 'append' + ? event.surfaceOp + : { + ...event.surfaceOp, + start: rebasedSeqByOriginal.get(event.surfaceOp.start) ?? event.surfaceOp.start, + end: rebasedSeqByOriginal.get(event.surfaceOp.end) ?? event.surfaceOp.end, + } + originalSeqs.push(event.seq) + rebasedSeqByOriginal.set(event.seq, rebasedSeq) + replay.push({ + ...eventWithoutSources, + seq: rebasedSeq, + surfaceOp, + ...(sourceEventSeqs === undefined ? {} : { sourceEventSeqs }), + } as SessionEvent) } contexts.push({ generation, - nodes: [...surface.nodes], + nodes: originalNodes(), ...(originSeq === undefined ? {} : { originSeq }), }) return contexts @@ -332,10 +360,7 @@ export function projectConversationHistory( ): ConversationHistoryProjection { const events = entries.map(entry => entry.event) const baseSeq = events[0]?.seq ?? 0 - const padded = [ - ...Array.from({ length: baseSeq }, (_, seq) => paddingEvent(seq)), - ...events, - ] + const eventsBySeq = new Map(events.map(event => [event.seq, event])) const callIndex = new Map() const resultViews = new Map() const assistantSteps = new Map() @@ -405,7 +430,7 @@ export function projectConversationHistory( const materialize = (seq: number): ConversationNode | undefined => { const cached = nodeCache.get(seq) if (cached !== undefined) return cached - const event = padded[seq] + const event = eventsBySeq.get(seq) if (event === undefined || !isSurfaceEligibleType(event.type)) return const node = materializeNode( event, @@ -431,7 +456,7 @@ export function projectConversationHistory( }] } else { try { - contexts = foldContexts(padded).map((context): ConversationContext => { + contexts = foldContexts(events).map((context): ConversationContext => { const nodes = context.nodes.flatMap((seq) => { const node = materialize(seq) return node === undefined ? [] : [node] @@ -444,7 +469,7 @@ export function projectConversationHistory( nodes, } } - const originEvent = padded[context.originSeq] + const originEvent = eventsBySeq.get(context.originSeq) return { id: context.generation, parentId: context.generation - 1, diff --git a/packages/client/runtime/src/client/session-history/source.ts b/packages/client/runtime/src/client/session-history/source.ts index 8b9e6b5093..44e760b2b2 100644 --- a/packages/client/runtime/src/client/session-history/source.ts +++ b/packages/client/runtime/src/client/session-history/source.ts @@ -6,7 +6,9 @@ import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api' import type { SessionHistoryFace, SessionHistorySnapshot, } from '../contract/session-history.ts' -import { createHistoryInspection } from '../sessions/history.ts' +import { + compactHistoryInspectionEntries, createHistoryInspection, +} from '../sessions/history.ts' import { Notifier } from '../sessions/notifier.ts' import { isVisibleAssistantChunk, PartialAccumulator } from '../sessions/partial.ts' @@ -18,7 +20,8 @@ function isAborted(signal: AbortSignal | undefined): boolean { /** Independent raw-history owner used only by inspection consumers. */ export class SessionHistorySource implements SessionHistoryFace { - private entries: readonly HistoryEntry[] = [] + private entries: HistoryEntry[] = [] + private inspectionEntries: readonly HistoryEntry[] = [] private baseSeq = 0 private hasMore = false private state: SessionHistorySnapshot['state'] = 'cold' @@ -36,7 +39,6 @@ export class SessionHistorySource implements SessionHistoryFace { value: SessionHistorySnapshot['inspection'] } | null = null private streamPublishToken: object | null = null - private streamBaseInspection: SessionHistorySnapshot['inspection'] | null = null private streamPartial: PartialAccumulator | null = null private snapshotCache: SessionHistorySnapshot private readonly notifier = new Notifier(() => { @@ -73,37 +75,29 @@ export class SessionHistorySource implements SessionHistoryFace { } /** - * Load the tail and exhaust all available older pages. + * Load the current tail without reading older pages. * @param signal - Consumer lifetime. - * @returns When paging completes, fails to advance, or is aborted. + * @returns When the tail is ready or loading fails. */ - async loadAll(signal?: AbortSignal): Promise { - if (signal?.aborted === true) return + async loadTail(signal?: AbortSignal): Promise { + if (isAborted(signal)) return this.trackConsumer(signal) await this.open() - while ( - !isAborted(signal) - && this.state === 'ready' - && this.hasMore - ) { - const previousBaseSeq = this.baseSeq - await this.loadOlder() - if (isAborted(signal) || this.baseSeq === previousBaseSeq) return - } } - /** Rebuild and page for whichever mounted consumers survive a reconnect. */ - private async loadForConsumers(): Promise { + /** + * Prepend one older page when the current window has a predecessor. + * @param signal - Consumer lifetime. + * @returns Whether the loaded window advanced. + */ + async loadOlder(signal?: AbortSignal): Promise { + if (isAborted(signal)) return false + this.trackConsumer(signal) await this.open() - while ( - this.hasConsumer() - && this.state === 'ready' - && this.hasMore - ) { - const previousBaseSeq = this.baseSeq - await this.loadOlder() - if (!this.hasConsumer() || this.baseSeq === previousBaseSeq) return - } + if (isAborted(signal)) return false + const previousBaseSeq = this.baseSeq + await this.loadOlderPage() + return this.baseSeq !== previousBaseSeq } /** @@ -144,12 +138,13 @@ export class SessionHistorySource implements SessionHistoryFace { this.liveBuffer = [] this.subscribedLastSeq = null this.entries = [] + this.inspectionEntries = [] this.baseSeq = 0 this.hasMore = false this.state = 'cold' this.error = null this.publishDirtyNow() - void this.loadForConsumers() + void this.open() } /** Stop future refresh work after the host removes the session. */ @@ -161,7 +156,6 @@ export class SessionHistorySource implements SessionHistoryFace { this.olderPromise = null this.liveBuffer = [] this.streamPublishToken = null - this.streamBaseInspection = null this.streamPartial = null } @@ -234,7 +228,7 @@ export class SessionHistorySource implements SessionHistoryFace { } } - private loadOlder(): Promise { + private loadOlderPage(): Promise { if (this.olderPromise !== null) return this.olderPromise if (this.state !== 'ready' || !this.hasMore) return Promise.resolve() const generation = this.generation @@ -260,6 +254,7 @@ export class SessionHistorySource implements SessionHistoryFace { return } this.entries = [...older, ...this.entries] + this.inspectionEntries = compactHistoryInspectionEntries([...this.entries]) this.baseSeq = older[0]?.event.seq ?? this.baseSeq this.hasMore = result.value.hasMore } catch (error) { @@ -291,6 +286,7 @@ export class SessionHistorySource implements SessionHistoryFace { this.entries = [...prefix, ...tail] } this.baseSeq = this.entries[0]?.event.seq ?? 0 + this.inspectionEntries = compactHistoryInspectionEntries([...this.entries]) const buffered = this.liveBuffer this.liveBuffer = [] for (const entry of buffered) this.appendLive(entry) @@ -324,7 +320,11 @@ export class SessionHistorySource implements SessionHistoryFace { private appendLive(entry: HistoryEntry): void { const tailSeq = this.tailSeq() if (tailSeq !== null && entry.event.seq <= tailSeq) return - this.entries = [...this.entries, entry] + this.entries.push(entry) + this.inspectionEntries = [...this.inspectionEntries, entry] + if (entry.event.type === 'assistant/message') { + this.inspectionEntries = compactHistoryInspectionEntries(this.inspectionEntries) + } } /** Append a chunk against the cached finalized projection; false means no visible publish. */ @@ -336,11 +336,10 @@ export class SessionHistorySource implements SessionHistoryFace { if (!isVisibleAssistantChunk(chunk.type)) { const inspection = this.currentInspection() this.appendLive(entry) - this.inspectionCache = { entries: this.entries, value: inspection } + this.inspectionCache = { entries: this.inspectionEntries, value: inspection } return false } - const base = this.streamBaseInspection ?? this.currentInspection() - this.streamBaseInspection = base + const base = this.currentInspection() if ( this.streamPartial === null || this.streamPartial.turn !== turn @@ -356,7 +355,7 @@ export class SessionHistorySource implements SessionHistoryFace { this.streamPartial.push(chunk) this.appendLive(entry) this.inspectionCache = { - entries: this.entries, + entries: this.inspectionEntries, value: { ...base, partial: this.streamPartial.toPartial() }, } return true @@ -382,7 +381,6 @@ export class SessionHistorySource implements SessionHistoryFace { /** Publish structural changes immediately and invalidate an older scheduled stream publish. */ private publishDirtyNow(): void { this.streamPublishToken = null - this.streamBaseInspection = null this.streamPartial = null this.notifier.markDirty() } @@ -415,14 +413,15 @@ export class SessionHistorySource implements SessionHistoryFace { state: this.state, error: this.error, hasMore: this.hasMore, + baseSeq: this.baseSeq, inspection: this.currentInspection(), } } /** Inspection pinned to the source's current immutable entry array. */ private currentInspection(): SessionHistorySnapshot['inspection'] { - if (this.inspectionCache?.entries !== this.entries) { - const entries = this.entries + if (this.inspectionCache?.entries !== this.inspectionEntries) { + const entries = this.inspectionEntries this.inspectionCache = { entries, value: createHistoryInspection(() => entries), diff --git a/packages/client/runtime/src/client/sessions/history.ts b/packages/client/runtime/src/client/sessions/history.ts index 520503a561..fbf7b08f3d 100644 --- a/packages/client/runtime/src/client/sessions/history.ts +++ b/packages/client/runtime/src/client/sessions/history.ts @@ -7,6 +7,24 @@ import type { ConversationContext } from './conversation-context.ts' import { projectConversationHistory } from '../session-history/history-fold.ts' import { inspectRequests, type RequestView } from './request-inspection.ts' +function assistantStepKey(turn: number, step: number): string { + return `${turn}\u0000${step}` +} + +function isFirstTokenCandidate(entry: HistoryEntry): boolean { + const event = entry.event + if (event.type !== 'assistant/chunk') return false + switch (event.data.chunk.type) { + case 'text-delta': + case 'reasoning-delta': + return event.data.chunk.text !== '' + case 'tool-call-delta': + return event.data.chunk.argumentsDelta !== '' || event.data.chunk.name !== undefined + default: + return false + } +} + /** Lazily derived inspection data for one immutable session-history window. */ export interface SessionHistoryInspection { eventNodes: readonly ConversationNode[] @@ -19,6 +37,47 @@ export interface SessionHistoryInspection { codeDispatches: ReadonlyMap } +/** + * Remove completed-step token payloads that no inspection projection reads. + * The first visible token preserves timing, usage chunks preserve accounting, + * and unfinished steps retain every chunk for live or interrupted content. + * @param entries - Contiguous raw history entries in sequence order. + * @returns A projection-equivalent, usually much smaller entry ledger. + */ +export function compactHistoryInspectionEntries( + entries: readonly HistoryEntry[], +): readonly HistoryEntry[] { + const completedSteps = new Set() + for (const { event } of entries) { + if (event.type === 'assistant/message') { + completedSteps.add(assistantStepKey(event.data.turn, event.data.step)) + } + } + + const firstTokenSteps = new Set() + const compacted: HistoryEntry[] = [] + let changed = false + for (const entry of entries) { + const event = entry.event + if (event.type !== 'assistant/chunk') { + compacted.push(entry) + continue + } + const key = assistantStepKey(event.data.turn, event.data.step) + if (!completedSteps.has(key) || event.data.chunk.type === 'usage') { + compacted.push(entry) + continue + } + if (isFirstTokenCandidate(entry) && !firstTokenSteps.has(key)) { + firstTokenSteps.add(key) + compacted.push(entry) + } else { + changed = true + } + } + return changed ? compacted : entries +} + /** * Create a lazy inspection projection over an immutable history window. * Conversation consumers retain the cheap wrapper; only Trajectory snapshots diff --git a/packages/client/runtime/src/client/sessions/request-inspection.ts b/packages/client/runtime/src/client/sessions/request-inspection.ts index 49ff8d974f..499b9acab1 100644 --- a/packages/client/runtime/src/client/sessions/request-inspection.ts +++ b/packages/client/runtime/src/client/sessions/request-inspection.ts @@ -94,7 +94,8 @@ export interface RequestInspectionSnapshot { /** * Derive the request-centric read model from one immutable history window. * Compaction participates as a request purpose rather than a parallel - * top-level collection. + * top-level collection. A leading resume/change header exposes its prompt but + * cannot project a change until the preceding header enters the window. * @param entries - Contiguous raw session history. * @returns Requests and call-time schemas derived from that history. */ @@ -218,6 +219,7 @@ function promptChange( prompt: ConversationPromptSnapshot, event: SessionEvent<'request/header'>, ): RequestPromptChange | undefined { + if (previous === undefined && event.data.reason !== 'initial') return const systemChanged = previous !== undefined && previous.system !== prompt.system const toolsChanged = previous !== undefined && JSON.stringify(previous.tools) !== JSON.stringify(prompt.tools) diff --git a/packages/client/runtime/tests/history-fold.spec.ts b/packages/client/runtime/tests/history-fold.spec.ts index 0c5421e491..57f498b926 100644 --- a/packages/client/runtime/tests/history-fold.spec.ts +++ b/packages/client/runtime/tests/history-fold.spec.ts @@ -2,12 +2,45 @@ import { createMessage } from '@deepseek-ai/dsh-llm' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { describe, expect, it } from 'vitest' import { projectConversationHistory } from '../src/client/session-history/history-fold.ts' +import { compactHistoryInspectionEntries } from '../src/client/sessions/history.ts' +import { inspectRequests } from '../src/client/sessions/request-inspection.ts' import { ev } from './event-script.ts' const at = (seq: number, event: Record): SessionEvent => ({ seq, time: 1_700_000_000_000 + seq, ...event }) as unknown as SessionEvent describe('projectConversationHistory', () => { + it('projects a high-sequence history window without synthesizing its unloaded prefix', () => { + const baseSeq = 400_000 + const events = [ + ev.user(baseSeq, 'loaded tail'), + at(baseSeq + 1, { + type: 'assistant/message', + surfaceOp: { op: 'replace', start: baseSeq, end: baseSeq }, + sourceEventSeqs: [baseSeq], + data: { + turn: 80, + step: 1, + message: createMessage({ + role: 'assistant', + content: [{ type: 'text', text: 'tail summary' }], + source: { kind: 'model', provider: 'fake', model: 'fake' }, + }), + }, + }), + ] + + const projection = projectConversationHistory(events.map(event => ({ event }))) + expect(projection.eventNodes.map(node => node.seq)).toEqual([baseSeq, baseSeq + 1]) + expect(projection.contexts.map(context => ({ + originSeq: context.originSeq, + nodes: context.nodes.map(node => node.seq), + }))).toEqual([ + { originSeq: undefined, nodes: [baseSeq] }, + { originSeq: baseSeq + 1, nodes: [baseSeq + 1] }, + ]) + }) + it('projects frozen surface generations without widening the core live surface', () => { const events = [ ev.user(0, 'a'), @@ -91,4 +124,35 @@ describe('projectConversationHistory', () => { requestConfig: { provider: 'fake', model: 'first' }, }) }) + + it('drops completed token payloads without changing inspection projections', () => { + const events = [ + ev.user(0, 'before'), + ev.stepStart(1, 1, 0), + ev.chunkStart(2, 1), + ev.chunkText(3, 1, ''), + ev.chunkText(4, 1, 'first'), + ev.chunkText(5, 1, ' discarded'), + at(6, { type: 'assistant/chunk', data: { + turn: 1, + step: 0, + chunk: { type: 'usage', usage: { inputTokens: 4, outputTokens: 2 } }, + } }), + ev.assistant(7, 1, 'first discarded'), + ev.compactSummary(8, 'summary', 0, 7), + ev.compactCheckpoint(9, 8, 0, 7), + ev.stepStart(10, 2, 0), + ev.chunkStart(11, 2), + ev.chunkText(12, 2, 'interrupted'), + ev.turnEnd(13, 2, 'aborted'), + ] + const raw = events.map(event => ({ event })) + const compacted = compactHistoryInspectionEntries(raw) + + expect(compacted.map(entry => entry.event.seq)).toEqual([ + 0, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, + ]) + expect(projectConversationHistory(compacted)).toEqual(projectConversationHistory(raw)) + expect(inspectRequests(compacted)).toEqual(inspectRequests(raw)) + }) }) diff --git a/packages/client/runtime/tests/request-inspection.spec.ts b/packages/client/runtime/tests/request-inspection.spec.ts index f354d14654..bb7f6e1a9a 100644 --- a/packages/client/runtime/tests/request-inspection.spec.ts +++ b/packages/client/runtime/tests/request-inspection.spec.ts @@ -85,6 +85,56 @@ describe('inspectRequests', () => { expect(snapshot.callSchemas.get('call-1')?.name).toBe('read') }) + it('does not promote a truncated resume or change header to the initial prompt', () => { + for (const reason of ['resume', 'change'] as const) { + const snapshot = inspectRequests(entriesOf([ + at(10, 'step/start', { turn: 3, step: 1 }), + at(11, 'request/header', { + reason, + header: { + config: { provider: 'fake', model: 'model' }, + system: 'tail-window prompt', + }, + }), + ])) + + expect(snapshot.requests[0]).toMatchObject({ + purpose: 'assistant', + prompt: { system: 'tail-window prompt' }, + }) + expect(snapshot.requests[0]).not.toHaveProperty('promptChange') + } + }) + + it('classifies a prompt change once the preceding header is loaded', () => { + const snapshot = inspectRequests(entriesOf([ + at(0, 'step/start', { turn: 1, step: 1 }), + at(1, 'request/header', { + reason: 'initial', + header: { + config: { provider: 'fake', model: 'model' }, + system: 'before', + }, + }), + at(2, 'step/start', { turn: 1, step: 2 }), + at(3, 'request/header', { + reason: 'change', + header: { + config: { provider: 'fake', model: 'model' }, + system: 'after', + }, + }), + ])) + + expect(snapshot.requests[1]).toMatchObject({ + promptChange: { + seq: 3, + kind: 'system', + previous: { system: 'before' }, + }, + }) + }) + it('preserves a standalone compaction owner without widening assistant turns', () => { const snapshot = inspectRequests(entriesOf([ at(0, 'compact/start', { turn: null }), diff --git a/packages/client/runtime/tests/session-history-source.spec.ts b/packages/client/runtime/tests/session-history-source.spec.ts index bcf25cd933..2bc0aa87af 100644 --- a/packages/client/runtime/tests/session-history-source.spec.ts +++ b/packages/client/runtime/tests/session-history-source.spec.ts @@ -16,7 +16,7 @@ function histResponse(events: SessionEvent[], hasMore = false) { } describe('SessionHistorySource', () => { - it('loads every older page without changing a Chat session', async () => { + it('loads the tail first and prepends older pages on demand', async () => { const pages = [ plainTurn(0, 0, '最早问', '最早答'), plainTurn(6, 1, '中间问', '中间答'), @@ -30,10 +30,21 @@ describe('SessionHistorySource', () => { } const source = new SessionHistorySource(SID, api) - await source.loadAll() + await source.loadTail() + + expect(api.callsOf('session.history')).toHaveLength(1) + expect(source.getSnapshot().hasMore).toBe(true) + expect(source.getSnapshot().baseSeq).toBe(12) + expect(source.getSnapshot().inspection.eventNodes.map(node => node.seq)) + .toEqual([13, 15]) + + expect(await source.loadOlder()).toBe(true) + expect(await source.loadOlder()).toBe(true) + expect(await source.loadOlder()).toBe(false) expect(api.callsOf('session.history')).toHaveLength(3) expect(source.getSnapshot().hasMore).toBe(false) + expect(source.getSnapshot().baseSeq).toBe(0) expect(source.getSnapshot().inspection.eventNodes.map(node => node.seq)) .toEqual([1, 3, 7, 9, 13, 15]) }) @@ -42,7 +53,7 @@ describe('SessionHistorySource', () => { const api = new FakeApiClient() api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答')) const source = new SessionHistorySource(SID, api) - await source.loadAll() + await source.loadTail() const before = source.getSnapshot() source.handleMuxFrame({ @@ -60,7 +71,7 @@ describe('SessionHistorySource', () => { const api = new FakeApiClient() api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答')) const source = new SessionHistorySource(SID, api) - await source.loadAll() + await source.loadTail() const frames: FrameRequestCallback[] = [] vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frames.push(callback) @@ -132,13 +143,14 @@ describe('SessionHistorySource', () => { })) const source = new SessionHistorySource(SID, api) - await source.loadAll() + await source.loadTail() + expect(await source.loadOlder()).toBe(false) expect(api.callsOf('session.history')).toHaveLength(2) expect(source.getSnapshot().hasMore).toBe(true) }) - it('observes consumer cancellation between older pages', async () => { + it('finishes an already started older page after consumer cancellation', async () => { const middle = deferred>>() const olderStarted = deferred() const api = new FakeApiClient() @@ -151,7 +163,8 @@ describe('SessionHistorySource', () => { } const source = new SessionHistorySource(SID, api) const controller = new AbortController() - const complete = source.loadAll(controller.signal) + await source.loadTail(controller.signal) + const complete = source.loadOlder(controller.signal) await olderStarted.promise controller.abort() middle.resolve(ok({ @@ -159,7 +172,7 @@ describe('SessionHistorySource', () => { hasMore: true, })) - await complete + expect(await complete).toBe(true) expect(api.callsOf('session.history')).toHaveLength(2) expect(source.getSnapshot().hasMore).toBe(true) diff --git a/packages/client/ui-trajectory/README.i18n.yaml b/packages/client/ui-trajectory/README.i18n.yaml index 5ef1a8eb68..83f0b0b2e5 100644 --- a/packages/client/ui-trajectory/README.i18n.yaml +++ b/packages/client/ui-trajectory/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-trajectory/README.md -README.md: 771e1a68e8027f02f20b17f78d0a8dd48d2d5bff -README.zh.md: ceb4d696e5fda117afff89cf9cd0a5426dfed2be +README.md: 2c737fe2d04df518e7d32d07aaede714a7a3566d +README.zh.md: 738d6cafa0c6d44f05fecec01d565da91ef433e8 diff --git a/packages/client/ui-trajectory/README.md b/packages/client/ui-trajectory/README.md index 771e1a68e8..2c737fe2d0 100644 --- a/packages/client/ui-trajectory/README.md +++ b/packages/client/ui-trajectory/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Trajectory renders a turn-aware event ledger with selectable User, Assistant, Tool, and nested Subtool records. Thick rules mark Turn boundaries, compact inline markers identify Steps, and the main ledger keeps only index, event, and content; selection opens a local inspector for token usage, duration, Input, Output, and Timing. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. 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, while clearing the selection restores the full branch. Wheel gestures zoom the time domain. A right-button click clears the selected interval, while a right-button drag pans an already zoomed viewport without changing it. Streaming updates keep the ledger pinned only when it was already at the bottom, so reading earlier records suspends tail following. Trajectory asks the conversation shell to float the composer over the full-height ledger, while its responsive vertical scrollers reserve the composer's live height so final rows remain reachable. The runtime's independent history source supplies raw context lineage and projects cancellation-frozen Assistant and Tool records, so Trajectory neither reads nor changes the Chat conversation snapshot. The package remains a pure-consumer plugin (registers one view tab into the conversation's `'conversation.view'` slot ring, provides no service, declares no Context merge). Contract: api-contracts v3 §8. +Trajectory renders a turn-aware event ledger with selectable User, Assistant, Tool, and nested Subtool records. Thick rules mark Turn boundaries, compact inline markers identify Steps, and the main ledger keeps only index, event, and content; selection opens a local inspector for token usage, duration, Input, Output, and Timing. Scrollable Summary regions keep their scrollbar thumbs transparent until the region is hovered or contains keyboard focus, without changing the reserved scroll geometry. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. Long ledgers open at the current tail, load one older page when the user reaches the loaded range's top, and mount only the visible row window plus a small overscan; request-only separators share the next measurable virtual item, while semantic row keys and ARIA indexes survive prepends. Selection, timeline navigation, folding, search, and Request totals cover the currently loaded window. The ledger covers records with an explicit loading row until the initial tail is positioned and while an older page is pending. A fixed Overview above the ledger projects real record start/duration timing from left to right; when earlier records remain unloaded and the viewport includes the loaded domain's start, a neutral ellipsis control identifies the omitted prefix and loads one earlier page without assigning unknown history fabricated duration. 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, while clearing the selection restores the full branch. Wheel gestures zoom the time domain. A right-button click clears the selected interval, while a right-button drag pans an already zoomed viewport without changing it. The initial view and streaming updates stay at the tail; scrolling upward suspends following so new records do not interrupt inspection of earlier rows. Content-only stream frames preserve virtual row keys and heights, reuse measurements, and do not issue repeated tail-scroll writes. Completed replies retain only the first visible token and usage chunks in the inspection projection, while unfinished and interrupted replies retain every chunk; the independent source keeps the raw history unchanged. Trajectory asks the conversation shell to float the composer over the full-height ledger, while its responsive vertical scrollers reserve the composer's live height so final rows remain reachable. The runtime's independent history source supplies raw context lineage and projects cancellation-frozen Assistant and Tool records, so Trajectory neither reads nor changes the Chat conversation snapshot. The package remains a pure-consumer plugin (registers one view tab into the conversation's `'conversation.view'` slot ring, provides no service, declares no Context merge). Contract: api-contracts v3 §8. ## Model Experience diff --git a/packages/client/ui-trajectory/README.zh.md b/packages/client/ui-trajectory/README.zh.md index ceb4d696e5..738d6cafa0 100644 --- a/packages/client/ui-trajectory/README.zh.md +++ b/packages/client/ui-trajectory/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -Trajectory 渲染按轮次组织的事件记录表,其中可选择用户、助手、工具和嵌套子工具记录。较粗的分割线标示轮次边界,紧凑的行内标记标识步骤,主记录表仅保留索引、事件和内容;选择记录则会打开局部检查器,查看 token 用量、耗时、输入、输出和计时。独立运行的压缩(compaction)请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。固定在记录表上方的 Overview 区域从左到右投影记录的真实开始时间与耗时;助手时间条会区分记录到的 TTFT 与解码时间,悬停 500 ms 后可查看精确时刻和耗时详情。拖选一个区间会将记录表聚焦到活动区间与该闭区间有重叠的所有记录,清除选择则恢复完整分支。滚轮手势用于缩放时间域。右键单击会清除所选区间;在已放大的 viewport 上按住右键拖动则只会平移视图,不会改变该区间。仅当记录表在流式更新前已经位于底部时,更新才会保持贴底;向上阅读旧记录会暂停跟随。Trajectory 要求会话壳将 composer 作为浮层置于全高记录表上方;其响应式纵向滚动容器会预留 composer 的实时高度,确保仍可滚动到最后几行。运行时的独立历史数据源提供原始上下文谱系,并投影因取消而冻结的助手和工具记录,因此 Trajectory 既不读取也不改变 Chat 会话快照。该包保持为纯消费方插件(向会话的 `'conversation.view'` slot 环注册一个视图标签页,不提供服务,也不声明 Context 合并)。契约:api-contracts v3 §8。 +Trajectory 渲染按轮次组织的事件记录表,其中可选择用户、助手、工具和嵌套子工具记录。较粗的分割线标示轮次边界,紧凑的行内标记标识步骤,主记录表仅保留索引、事件和内容;选择记录则会打开局部检查器,查看 token 用量、耗时、输入、输出和计时。可滚动的概述区域默认保持滚动条滑块透明,直到鼠标悬停该区域或其中包含键盘焦点时才显示,同时不改变滚动条预留的几何空间。独立运行的压缩(compaction)请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。长记录表打开时定位于当前尾部,用户到达已加载范围顶部时加载一页更早的历史,并且只挂载可见行窗口和少量额外缓冲行;仅含请求的分隔行并入下一个具备可测高度的虚拟项,语义行键和 ARIA 索引在向前补页后保持不变。选择、时间线导航、折叠、搜索和请求汇总只覆盖当前已加载的窗口。初始尾部完成定位前以及更早页面仍在等待时,记录表会用明确的加载行遮住真实记录。固定在记录表上方的 Overview 区域从左到右投影记录的真实开始时间与耗时;仍有更早记录未加载且 viewport 包含已加载时间域起点时,中性的省略号控件会标识被省略的前缀,并可加载一页更早历史,而不会为未知部分虚构耗时。助手时间条会区分记录到的 TTFT 与解码时间,悬停 500 ms 后可查看精确时刻和耗时详情。拖选一个区间会将记录表聚焦到活动区间与该闭区间有重叠的所有记录,清除选择则恢复完整分支。滚轮手势用于缩放时间域。右键单击会清除所选区间;在已放大的 viewport 上按住右键拖动则只会平移视图,不会改变该区间。初始视图和流式更新都会停留在尾部;向上滚动会暂停跟随,因此新记录不会打断对旧记录的检查。仅含内容更新的流式帧会保持虚拟行的键和高度不变、复用测量结果,并且不会重复写入末尾滚动位置。已完成的回复在检查投影中仅保留首个可见 token 和用量分片,未完成及中断的回复则保留所有分片;独立数据源中的原始历史保持不变。Trajectory 要求会话壳将 composer 作为浮层置于全高记录表上方;其响应式纵向滚动容器会预留 composer 的实时高度,确保仍可滚动到最后几行。运行时的独立历史数据源提供原始上下文谱系,并投影因取消而冻结的助手和工具记录,因此 Trajectory 既不读取也不改变 Chat 会话快照。该包保持为纯消费方插件(向会话的 `'conversation.view'` slot 环注册一个视图标签页,不提供服务,也不声明 Context 合并)。契约:api-contracts v3 §8。 ## 模型体验 diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index 576b561711..f56a9825ce 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -35,6 +35,7 @@ }, "license": "BSD-3-Clause", "dependencies": { + "@tanstack/react-virtual": "^3.14.9", "diff": "^9.0.0" }, "peerDependencies": { @@ -42,7 +43,8 @@ "@deepseek-ai/dsh-invariants": "^0.0.1", "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "devDependencies": { "@deepseek-ai/dsh-client-runtime": "workspace:^", @@ -51,8 +53,10 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@types/react": "~18.3.1", + "@types/react-dom": "~18.3.0", "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "files": [ "lib/index.js", diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.module.css b/packages/client/ui-trajectory/src/client/TrajectoryTable.module.css index 69d9d620e3..b1d9be9930 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.module.css +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.module.css @@ -13,6 +13,7 @@ } .tablePane { + position: relative; flex: 1; min-width: 0; overflow-x: hidden; @@ -21,6 +22,53 @@ container: trajectory-table / inline-size; } +.historyLoading { + position: sticky; + z-index: 5; + top: 0; + height: 0; + overflow: visible; + pointer-events: none; +} + +.historyLoadingBar { + display: flex; + width: 100%; + height: 30px; + align-items: center; + justify-content: center; + gap: 6px; + box-sizing: border-box; + border-bottom: 1px solid var(--dsw-alias-border-l2); + background: var(--dsw-alias-bg-layer-1); + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xxs-12); +} + +.historyLoadingSpinner { + width: 10px; + height: 10px; + box-sizing: border-box; + border: 1.5px solid var(--dsw-alias-border-l2); + border-top-color: var(--dsw-alias-state-business-primary); + border-radius: 50%; + animation: history-loading-spin 700ms linear infinite; +} + +.table:not([data-scroll-ready='true']) { + visibility: hidden; +} + +@keyframes history-loading-spin { + to { transform: rotate(360deg); } +} + +@media (prefers-reduced-motion: reduce) { + .historyLoadingSpinner { + animation: none; + } +} + .table { --trajectory-turn-accent: color-mix( in srgb, @@ -79,7 +127,17 @@ white-space: nowrap; } -.table tbody tr:not([data-collapsed-summary]) { +.table tbody .virtualSpacer { + pointer-events: none; +} + +.table tbody .virtualSpacer td { + height: var(--trajectory-virtual-spacer-height); + padding: 0; + border: 0; +} + +.table tbody tr:not([data-collapsed-summary]):not([data-virtual-spacer]) { cursor: default; outline: none; transition: @@ -91,7 +149,7 @@ opacity: 0.24; } -.table tbody tr:not([data-collapsed-summary]):not([data-selected='true']):hover { +.table tbody tr:not([data-collapsed-summary]):not([data-virtual-spacer]):not([data-selected='true']):hover { background: var(--dsw-alias-interactive-bg-hover); } @@ -106,7 +164,7 @@ border-bottom: 0; } -.table tbody tr[data-request-only='true']:last-child td { +.table tbody tr[data-terminal-request-boundary='true'] td { /* Retain the lower half of the 16px boundary marker at the table's end. */ height: 9px; } @@ -620,6 +678,10 @@ white-space: nowrap; } +.toolCallOnly { + color: var(--dsw-alias-label-tertiary); +} + .table tbody tr[data-collapsed-summary='turn'] td, .table tbody tr[data-collapsed-summary='assistant'] td { height: 20px; @@ -936,6 +998,17 @@ overflow: auto; } +.summaryScrollRegion { + --dsh-scrollbar-thumb: transparent; + --dsh-scrollbar-thumb-hover: transparent; +} + +.summaryScrollRegion:hover, +.summaryScrollRegion:focus-within { + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); +} + .compactedSummary .markdownPayload { padding-right: 18px; } @@ -1023,7 +1096,6 @@ margin: 0; overflow: hidden; color: var(--dsw-alias-label-primary); - font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; } @@ -1033,7 +1105,6 @@ color: inherit; cursor: pointer; font: inherit; - font-variant-numeric: tabular-nums; user-select: text; } diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx index 6f37c852c5..9cef2dccfb 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { CSSProperties, ReactNode } from 'react' +import { useVirtualizer } from '@tanstack/react-virtual' import { IconChevronRightOutline14, IconSettingsOutline16, @@ -18,11 +19,19 @@ import type { import type { AssistantMetricDetail, TrajectoryCellKind, TrajectoryCellProps, TrajectorySourceBlock, } from './trajectory-record.ts' -import { formatElapsedSeconds } from './trajectory-record.ts' +import { formatElapsedSeconds, trajectoryRecordId } from './trajectory-record.ts' +import { + groupTrajectoryVirtualRows, trajectoryVirtualRecordKey, +} from './trajectory-virtual-rows.ts' +import type { TrajectoryVirtualRow } from './trajectory-virtual-rows.ts' import { trajectoryPreviewText, type TrajectoryTurnModel } from './layout.ts' import css from './TrajectoryTable.module.css' const BOTTOM_FOLLOW_THRESHOLD_PX = 2 +const OLDER_LOAD_THRESHOLD_PX = 48 +const VIRTUALIZATION_THRESHOLD = 100 +const VIRTUAL_OVERSCAN_ROWS = 12 +const VIRTUAL_INITIAL_VIEWPORT_HEIGHT_PX = 600 const KIND_LABEL: Record = { system: 'SYSTEM', @@ -117,6 +126,30 @@ interface TableRecord { collapsedSummaryKind?: 'turn' | 'assistant' } +interface VirtualRowStructure { + height: number + key: string +} + +function useStableVirtualRowStructure( + rows: readonly TrajectoryVirtualRow[], +): readonly VirtualRowStructure[] { + const cache = useRef<{ + rows: readonly TrajectoryVirtualRow[] + structure: readonly VirtualRowStructure[] + }>({ rows: [], structure: [] }) + if (cache.current.rows === rows) return cache.current.structure + const structure = cache.current.structure.length === rows.length + && rows.every((row, index) => { + const previous = cache.current.structure[index] + return previous?.key === row.key && previous.height === row.height + }) + ? cache.current.structure + : rows.map(row => ({ key: row.key, height: row.height })) + cache.current = { rows, structure } + return structure +} + type DetailTab = | 'system-prompt' | 'tools' @@ -150,9 +183,8 @@ interface ToolCallTextParts { interface SelectedRequest { turn: number | null - section: number - number: number group: string + seq?: number } interface DetailsResizeDrag { @@ -195,6 +227,16 @@ type RequestBoundaryStyle = CSSProperties & { '--request-boundary-offset': string } +type VirtualSpacerStyle = CSSProperties & { + '--trajectory-virtual-spacer-height': string +} + +interface OlderLoadAnchor { + readonly historyStartSeq: number | undefined + readonly scrollHeight: number + readonly scrollTop: number +} + function clampDetailsWidth(width: number, splitWidth: number): number { const maxWidth = Math.max( DETAILS_MIN_WIDTH, @@ -228,6 +270,15 @@ function formatStartedAt(timestamp: number | null): string { return `${day} ${time}` } +/** Whether a click lands on an active text selection and should keep it. */ +function clickSelectsText(target: Node): boolean { + const selection = window.getSelection() + return selection !== null + && !selection.isCollapsed + && selection.rangeCount > 0 + && selection.getRangeAt(0).intersectsNode(target) +} + function StartedAtValue({ timestamp }: { timestamp: number | null }) { const [showUnix, setShowUnix] = useState(false) if (timestamp === null || !Number.isFinite(timestamp)) return
Not available
@@ -238,13 +289,7 @@ function StartedAtValue({ timestamp }: { timestamp: number | null }) { className={css.timestampToggle} title={showUnix ? 'Show local time' : 'Show Unix timestamp'} onClick={(event) => { - const selection = window.getSelection() - if ( - selection !== null - && !selection.isCollapsed - && selection.rangeCount > 0 - && selection.getRangeAt(0).intersectsNode(event.currentTarget) - ) return + if (clickSelectsText(event.currentTarget)) return setShowUnix(current => !current) }} > @@ -302,6 +347,8 @@ export interface TrajectoryTableProps { requestNumbers?: readonly TrajectoryRequestNumber[] /** Grouped records in display order. */ turns: readonly TrajectoryTurnModel[] + /** In-flight cells whose content replaces the matching structural record index. */ + streamingCells?: readonly TrajectoryCellProps[] /** Record indexes emphasized by the active timeline focus. */ timelineFocusIndexes?: ReadonlySet | null /** Record indexes retained by the active live search, or null without a query. */ @@ -312,16 +359,26 @@ export interface TrajectoryTableProps { onRecordSelect?: (index: number) => void /** One externally requested record selection; a new object repeats the request. */ recordSelection?: { readonly index: number } | null + /** One externally requested record focus without changing inspector selection. */ + recordFocus?: { readonly index: number } | null + /** Whether the initial history tail is still loading. */ + historyLoading?: boolean + /** First loaded raw event, used to preserve scroll position after prepending a page. */ + historyStartSeq?: number | undefined + /** Whether one older history page can be requested. */ + hasOlderRecords?: boolean + /** Load one older history page. */ + onLoadOlder?: () => Promise /** Clear selection state owned by the ledger host. */ onClearSelection?: () => void /** Turn ids whose rows after the first are folded into a summary. */ collapsedTurns: ReadonlySet /** Toggle one turn between folded and expanded. */ onToggleTurn: (turn: number) => void - /** Assistant record indexes whose tool calls are folded. */ - collapsedAssistants: ReadonlySet + /** Stable Assistant record ids whose tool calls are folded. */ + collapsedAssistants: ReadonlySet /** Toggle tool calls under one assistant record. */ - onToggleAssistant: (index: number) => void + onToggleAssistant: (id: string) => void /** One-shot cross-view inspect: open and scroll to this call's record. */ inspectCallId?: string | null /** Acknowledge a consumed (or unresolvable) inspect request. */ @@ -492,7 +549,6 @@ function collapseTurnRecords( records: readonly TableRecord[], collapsedTurns: ReadonlySet, ): TableRecord[] { - if (collapsedTurns.size === 0) return [...records] const recordsByTurn = new Map() for (const record of records) { if (record.turn === null) continue @@ -550,15 +606,17 @@ function summarizeAssistantTools(records: readonly TableRecord[]): string { function collapseAssistantRecords( records: readonly TableRecord[], - collapsedAssistants: ReadonlySet, + collapsedAssistants: ReadonlySet, ): TableRecord[] { - if (collapsedAssistants.size === 0) return [...records] const out: TableRecord[] = [] for (let i = 0; i < records.length; i++) { const record = records[i] if (record === undefined) continue out.push(record) - if (record.cell.kind !== 'message' || !collapsedAssistants.has(record.cell.index)) continue + if ( + record.cell.kind !== 'message' + || !collapsedAssistants.has(trajectoryRecordId(record.cell)) + ) continue const calls: TableRecord[] = [] for (let j = i + 1; j < records.length; j++) { const candidate = records[j] @@ -1335,7 +1393,7 @@ function RequestTiming({
Started
-
Duration
+
Duration
{formatElapsedSeconds(null)}
) } @@ -1519,7 +1577,12 @@ function OverviewSection({ -
{children}
+
+ {children} +
) } @@ -1533,11 +1596,17 @@ function OverviewSection({ export function TrajectoryTable({ requestNumbers: sessionRequestNumbers, turns, + streamingCells = [], timelineFocusIndexes = null, searchMatchIndexes = null, onSelectedIndexChange, onRecordSelect, recordSelection = null, + recordFocus = null, + historyLoading = false, + historyStartSeq, + hasOlderRecords = false, + onLoadOlder, onClearSelection, collapsedTurns, onToggleTurn, @@ -1546,7 +1615,7 @@ export function TrajectoryTable({ inspectCallId = null, onInspectApplied, }: TrajectoryTableProps) { - const [selectedIndex, setSelectedIndex] = useState(null) + const [selectedRecordId, setSelectedRecordId] = useState(null) const [selectedRequest, setSelectedRequest] = useState(null) const [activeTab, setActiveTab] = useState('overview') const [thinkingExpanded, setThinkingExpanded] = useState(false) @@ -1554,20 +1623,116 @@ export function TrajectoryTable({ const [toolRequestOffset, setToolRequestOffset] = useState(null) const detailsResizeDrag = useRef(null) const appliedRecordSelection = useRef(null) + const appliedRecordFocus = useRef(null) const tabHistory = useRef>(new Set(['overview'])) + const rootRef = useRef(null) + const tablePaneRef = useRef(null) + const followsTableTail = useRef(false) + const tableScrollInitialized = useRef(false) + const [tableScrollReady, setTableScrollReady] = useState(false) + const pendingScrollRecordId = useRef(null) + const loadingOlder = useRef(false) + const [olderLoading, setOlderLoading] = useState(false) + const olderLoadAnchor = useRef(null) + const allRecords = useMemo(() => flattenRecords(turns), [turns]) + const streamingCellsByIndex = useMemo( + () => new Map(streamingCells.map(cell => [cell.index, cell])), + [streamingCells], + ) + const currentRecord = useCallback((record: TableRecord): TableRecord => { + const cell = streamingCellsByIndex.get(record.cell.index) + return cell === undefined ? record : { ...record, cell } + }, [streamingCellsByIndex]) + const selectedTemplate = useMemo(() => selectedRecordId === null + ? undefined + : allRecords.find(record => trajectoryRecordId(record.cell) === selectedRecordId), + [allRecords, selectedRecordId]) + const selected = selectedTemplate === undefined + ? undefined + : currentRecord(selectedTemplate) + const selectedIndex = selected?.cell.index ?? null useEffect(() => { onSelectedIndexChange?.(selectedIndex) }, [onSelectedIndexChange, selectedIndex]) - const allRecords = useMemo(() => flattenRecords(turns), [turns]) - const requestNumbers = indexRequestNumbers(allRecords, sessionRequestNumbers) - const records = searchMatchIndexes === null - ? collapseAssistantRecords( - collapseTurnRecords(allRecords, collapsedTurns), - collapsedAssistants, - ) - : filterRecords(allRecords, searchMatchIndexes) - const requestBoundaryRuns = indexRequestBoundaryRuns(records) - const selected = allRecords.find(record => record.cell.index === selectedIndex) + const requestNumbers = useMemo( + () => indexRequestNumbers(allRecords, sessionRequestNumbers), + [allRecords, sessionRequestNumbers], + ) + const records = useMemo(() => { + if (searchMatchIndexes !== null) return filterRecords(allRecords, searchMatchIndexes) + const turnRecords = collapsedTurns.size === 0 + ? allRecords + : collapseTurnRecords(allRecords, collapsedTurns) + return collapsedAssistants.size === 0 + ? turnRecords + : collapseAssistantRecords(turnRecords, collapsedAssistants) + }, [allRecords, collapsedAssistants, collapsedTurns, searchMatchIndexes]) + const projectedVirtualRows = useMemo( + () => groupTrajectoryVirtualRows(records), + [records], + ) + const virtualRowStructure = useStableVirtualRowStructure(projectedVirtualRows) + const virtualizationEnabled = hasOlderRecords + || records.length > VIRTUALIZATION_THRESHOLD + const estimateVirtualRowSize = useCallback( + (index: number) => virtualRowStructure[index]?.height ?? 30, + [virtualRowStructure], + ) + const getVirtualRowKey = useCallback( + (index: number) => virtualRowStructure[index]?.key ?? index, + [virtualRowStructure], + ) + const getTableScrollElement = useCallback(() => tablePaneRef.current, []) + const rowVirtualizer = useVirtualizer({ + count: virtualizationEnabled ? virtualRowStructure.length : 0, + enabled: virtualizationEnabled, + estimateSize: estimateVirtualRowSize, + getItemKey: getVirtualRowKey, + getScrollElement: getTableScrollElement, + initialRect: { width: 0, height: VIRTUAL_INITIAL_VIEWPORT_HEIGHT_PX }, + anchorTo: 'end', + overscan: VIRTUAL_OVERSCAN_ROWS, + scrollEndThreshold: BOTTOM_FOLLOW_THRESHOLD_PX, + }) + const virtualIndexByRecordId = useMemo(() => { + const indexes = new Map() + for (const [virtualIndex, row] of projectedVirtualRows.entries()) { + for (const entry of row.entries) { + if (entry.record.collapsedSummary === undefined) { + indexes.set(trajectoryRecordId(entry.record.cell), virtualIndex) + } + } + } + return indexes + }, [projectedVirtualRows]) + const virtualItems = virtualizationEnabled ? rowVirtualizer.getVirtualItems() : [] + const virtualTop = virtualItems[0]?.start ?? 0 + const virtualBottom = virtualItems.length === 0 + ? 0 + : Math.max(0, rowVirtualizer.getTotalSize() - (virtualItems.at(-1)?.end ?? 0)) + const renderedRecords = virtualizationEnabled + ? virtualItems.flatMap((item) => { + const row = projectedVirtualRows[item.index] + if (row === undefined) return [] + return row.entries.map((entry, entryIndex) => ({ + record: currentRecord(entry.record), + position: entry.logicalIndex, + terminalRequestBoundary: + entry.record.cell.requestOnly === true + && row.entries.at(-1)?.record.cell.requestOnly === true + && entryIndex === row.entries.length - 1, + })) + }) + : records.map((record, position) => ({ + record: currentRecord(record), + position, + terminalRequestBoundary: + record.cell.requestOnly === true && position === records.length - 1, + })) + const requestBoundaryRuns = useMemo( + () => indexRequestBoundaryRuns(records), + [records], + ) const selectedPrompt = selected?.cell.kind === 'system' ? selected.cell.promptDetail : undefined @@ -1576,20 +1741,25 @@ export function TrajectoryTable({ : undefined const promptSelected = selectedPrompt !== undefined const selectedState = selected === undefined ? undefined : stateOf(selected) - const selectedRequestRecords = selectedRequest === null + const selectedRequestRecordTemplates = useMemo(() => selectedRequest === null ? [] : allRecords.filter(record => record.turn === selectedRequest.turn - && record.section === selectedRequest.section && record.group === selectedRequest.group, - ) + ), [allRecords, selectedRequest]) + const selectedRequestRecords = selectedRequestRecordTemplates.map(currentRecord) const selectedRequestAssistant = selectedRequestRecords.find( record => record.cell.kind === 'message', ) const selectedRequestAnchor = selectedRequestAssistant ?? selectedRequestRecords[0] + const selectedRequestNumber = selectedRequest === null + ? undefined + : requestNumbers.get(requestKey(selectedRequest.turn, selectedRequest.group)) const selectedRequestInfo = selectedRequest === null ? undefined - : sessionRequestNumbers?.find(request => request.number === selectedRequest.number) + : sessionRequestNumbers?.find(request => selectedRequest.seq === undefined + ? request.turn === selectedRequest.turn && request.group === selectedRequest.group + : request.seq === selectedRequest.seq) const selectedRequestState: RecordState | undefined = selectedRequest === null ? undefined : selectedRequestInfo?.status @@ -1605,9 +1775,12 @@ export function TrajectoryTable({ const selectedRequestSubtoolCalls = selectedRequestRecords.filter( record => record.cell.kind === 'subtool', ).length - const selectedRequestResult = selectedRequestInfo?.resultSeq === undefined + const selectedRequestResultTemplate = selectedRequestInfo?.resultSeq === undefined ? selectedRequestAssistant : allRecords.find(record => record.cell.sourceSeq === selectedRequestInfo.resultSeq) + const selectedRequestResult = selectedRequestResultTemplate === undefined + ? undefined + : currentRecord(selectedRequestResultTemplate) const selectedRequestUsage = selectedRequestInfo?.usage ?? ( selectedRequestAssistant === undefined ? undefined @@ -1633,7 +1806,9 @@ export function TrajectoryTable({ selectedRequestInfo?.cumulativeUsage ?? selectedRequestUsage const selectedRequestOptions = selectedRequestInfo?.requestConfig const activeTurn = selectedRequest === null ? selected?.turn : selectedRequest.turn - const activeSection = selectedRequest === null ? selected?.section : selectedRequest.section + const activeSection = selectedRequest === null + ? selected?.section + : selectedRequestRecords[0]?.section const selectedTabs = selectedRequest !== null ? REQUEST_TABS.filter(tab => tab.id !== 'options' || selectedRequestOptions !== undefined) : selected === undefined ? [] : detailTabs(selected) @@ -1645,13 +1820,17 @@ export function TrajectoryTable({ const selectedAssistantRequest = selected?.cell.kind === 'message' ? requestNumbers.get(requestKey(selected.turn, selected.group)) : undefined + const selectedAssistantRequestInfo = selectedAssistantRequest === undefined + ? undefined + : sessionRequestNumbers?.find(request => request.number === selectedAssistantRequest) const selectedAssistantRequestTarget: SelectedRequest | undefined = selected !== undefined && selectedAssistantRequest !== undefined ? { turn: selected.turn, - section: selected.section, - number: selectedAssistantRequest, group: selected.group, + ...(selectedAssistantRequestInfo?.seq === undefined + ? {} + : { seq: selectedAssistantRequestInfo.seq }), } : undefined const hasSelectedHierarchy = selectedAssistantRequestTarget !== undefined @@ -1670,7 +1849,7 @@ export function TrajectoryTable({ } const clearInspectorSelection = () => { - setSelectedIndex(null) + setSelectedRecordId(null) setSelectedRequest(null) } @@ -1683,7 +1862,7 @@ export function TrajectoryTable({ const record = allRecords.find(candidate => candidate.cell.index === index) onRecordSelect?.(index) setSelectedRequest(null) - setSelectedIndex(index) + setSelectedRecordId(record === undefined ? null : trajectoryRecordId(record.cell)) if (record === undefined) return const tabs = detailTabs(record) const available = new Set(tabs.map(tab => tab.id)) @@ -1697,13 +1876,25 @@ export function TrajectoryTable({ ) return appliedRecordSelection.current = recordSelection selectRecord(recordSelection.index) - }, [recordSelection, selectRecord]) + const record = allRecords.find(candidate => candidate.cell.index === recordSelection.index) + pendingScrollRecordId.current = record === undefined + ? null + : trajectoryRecordId(record.cell) + }, [allRecords, recordSelection, selectRecord]) + useEffect(() => { + if (recordFocus === null || appliedRecordFocus.current === recordFocus) return + appliedRecordFocus.current = recordFocus + const record = allRecords.find(candidate => candidate.cell.index === recordFocus.index) + pendingScrollRecordId.current = record === undefined + ? null + : trajectoryRecordId(record.cell) + }, [allRecords, recordFocus]) const selectRequest = ( request: SelectedRequest, tab: 'overview' | 'timing' = 'overview', ) => { - setSelectedIndex(null) + setSelectedRecordId(null) setSelectedRequest(request) activateTab(tab) } @@ -1716,12 +1907,13 @@ export function TrajectoryTable({ const candidate = allRecords[i] if (candidate === undefined || candidate.turn !== target.turn) break if (candidate.cell.kind !== 'message') continue - if (collapsedAssistants.has(candidate.cell.index)) onToggleAssistant(candidate.cell.index) + const assistantId = trajectoryRecordId(candidate.cell) + if (collapsedAssistants.has(assistantId)) onToggleAssistant(assistantId) break } } setSelectedRequest(null) - setSelectedIndex(target.cell.index) + setSelectedRecordId(trajectoryRecordId(target.cell)) activateTab('overview') } @@ -1734,11 +1926,6 @@ export function TrajectoryTable({ // open its summary, and remember the row to scroll once the un-collapsed // ledger has rendered. Not-found leaves the request pending (`turns` in the // deps retries as history pages in); the ack clears the store field. - const rootRef = useRef(null) - const tablePaneRef = useRef(null) - const followsTableTail = useRef(false) - const tableScrollInitialized = useRef(false) - const pendingScrollIndex = useRef(null) const openRecordSummaryRef = useRef(openRecordSummary) openRecordSummaryRef.current = openRecordSummary useEffect(() => { @@ -1746,61 +1933,213 @@ export function TrajectoryTable({ const target = flattenRecords(turns).find(record => record.cell.callId === inspectCallId) if (target === undefined) return openRecordSummaryRef.current(target) - pendingScrollIndex.current = target.cell.index + pendingScrollRecordId.current = trajectoryRecordId(target.cell) onInspectApplied?.() }, [inspectCallId, turns, onInspectApplied]) useEffect(() => { - const index = pendingScrollIndex.current - if (index === null) return - const row = rootRef.current - ?.querySelector(`tr[data-record-index="${index}"]`) - if (row === undefined || row === null) return - pendingScrollIndex.current = null + const id = pendingScrollRecordId.current + if (id === null) return + const position = records.findIndex(record => + trajectoryRecordId(record.cell) === id && record.collapsedSummary === undefined) + if (position === -1) return + if (virtualizationEnabled) { + const virtualIndex = virtualIndexByRecordId.get(id) + if (virtualIndex === undefined) return + pendingScrollRecordId.current = null + followsTableTail.current = false + rowVirtualizer.scrollToIndex(virtualIndex, { behavior: 'smooth', align: 'center' }) + return + } + pendingScrollRecordId.current = null + followsTableTail.current = false + const recordIndex = records[position]?.cell.index + const row = recordIndex === undefined + ? null + : rootRef.current?.querySelector(`tr[data-record-index="${recordIndex}"]`) /* v8 ignore next -- jsdom lacks scrollIntoView; browsers always have it. */ - if (typeof row.scrollIntoView === 'function') { + if (row !== undefined && row !== null && typeof row.scrollIntoView === 'function') { row.scrollIntoView({ behavior: 'smooth', block: 'center' }) } - }) + }, [records, rowVirtualizer, virtualIndexByRecordId, virtualizationEnabled]) + useEffect(() => { + if (timelineFocusIndexes === null || timelineFocusIndexes.size === 0) return + const focusedPositions = records.flatMap((record, position) => + record.collapsedSummary === undefined + && record.cell.requestOnly !== true + && timelineFocusIndexes.has(record.cell.index) + ? [position] + : []) + const first = focusedPositions.at(0) + const last = focusedPositions.at(-1) + if (first === undefined || last === undefined) return + if (!virtualizationEnabled) { + const ledger = rootRef.current + if (ledger === null) return + const focusedRows = [ + ...ledger.querySelectorAll('tr[data-timeline-focus="inside"]'), + ] + const firstRow = focusedRows.at(0) + const lastRow = focusedRows.at(-1) + if (firstRow === undefined || lastRow === undefined) return + const focusHeight = + lastRow.getBoundingClientRect().bottom - firstRow.getBoundingClientRect().top + const target = focusHeight > ledger.clientHeight + ? firstRow + : focusedRows[Math.floor((focusedRows.length - 1) / 2)] + /* v8 ignore next -- jsdom lacks scrollIntoView; browsers always have it. */ + if (target !== undefined && typeof target.scrollIntoView === 'function') { + followsTableTail.current = false + target.scrollIntoView({ + behavior: 'smooth', + block: focusHeight > ledger.clientHeight ? 'start' : 'center', + }) + } + return + } + const focusedVirtualIndexes = [...new Set(focusedPositions.flatMap((position) => { + const record = records[position] + if (record === undefined) return [] + const virtualIndex = virtualIndexByRecordId.get(trajectoryRecordId(record.cell)) + return virtualIndex === undefined ? [] : [virtualIndex] + }))].sort((left, right) => left - right) + const firstVirtual = focusedVirtualIndexes.at(0) + const lastVirtual = focusedVirtualIndexes.at(-1) + if (firstVirtual === undefined || lastVirtual === undefined) return + const paneHeight = tablePaneRef.current?.clientHeight ?? 0 + const focusHeight = projectedVirtualRows + .slice(firstVirtual, lastVirtual + 1) + .reduce((height, row) => height + row.height, 0) + followsTableTail.current = false + rowVirtualizer.scrollToIndex( + focusHeight > paneHeight + ? firstVirtual + : focusedVirtualIndexes[Math.floor((focusedVirtualIndexes.length - 1) / 2)] + ?? firstVirtual, + { + behavior: 'smooth', + align: focusHeight > paneHeight ? 'start' : 'center', + }, + ) + }, [ + projectedVirtualRows, + records, + rowVirtualizer, + timelineFocusIndexes, + virtualIndexByRecordId, + virtualizationEnabled, + ]) + const requestOlder = useCallback((pane: HTMLDivElement) => { + if ( + !hasOlderRecords + || onLoadOlder === undefined + || loadingOlder.current + || pane.scrollTop > OLDER_LOAD_THRESHOLD_PX + ) return + loadingOlder.current = true + setOlderLoading(true) + olderLoadAnchor.current = { + historyStartSeq, + scrollHeight: pane.scrollHeight, + scrollTop: pane.scrollTop, + } + void onLoadOlder().then((advanced) => { + if (!advanced) olderLoadAnchor.current = null + }).finally(() => { + loadingOlder.current = false + setOlderLoading(false) + }) + }, [hasOlderRecords, historyStartSeq, onLoadOlder]) useLayoutEffect(() => { const pane = tablePaneRef.current if (pane === null) return - if (!tableScrollInitialized.current) { - tableScrollInitialized.current = true - followsTableTail.current = - pane.scrollHeight - pane.clientHeight - pane.scrollTop - <= BOTTOM_FOLLOW_THRESHOLD_PX + const anchor = olderLoadAnchor.current + if (anchor !== null && anchor.historyStartSeq !== historyStartSeq) { + if (!virtualizationEnabled) { + pane.scrollTop = anchor.scrollTop + pane.scrollHeight - anchor.scrollHeight + } + olderLoadAnchor.current = null + followsTableTail.current = false return } - if (followsTableTail.current) pane.scrollTop = pane.scrollHeight - }, [turns]) + if (!tableScrollInitialized.current) { + if (historyLoading) return + tableScrollInitialized.current = true + followsTableTail.current = true + if (virtualizationEnabled) rowVirtualizer.scrollToEnd({ behavior: 'auto' }) + else pane.scrollTop = pane.scrollHeight + setTableScrollReady(true) + return + } + if (!followsTableTail.current) return + if (virtualizationEnabled) rowVirtualizer.scrollToEnd({ behavior: 'auto' }) + else pane.scrollTop = pane.scrollHeight + }, [ + historyLoading, + historyStartSeq, + rowVirtualizer, + virtualRowStructure, + virtualizationEnabled, + ]) + + const loadingLabel = olderLoading + ? 'Loading earlier history…' + : 'Loading trajectory…' + const showLoading = historyLoading || olderLoading || !tableScrollReady return (
{ const pane = event.currentTarget followsTableTail.current = pane.scrollHeight - pane.clientHeight - pane.scrollTop <= BOTTOM_FOLLOW_THRESHOLD_PX + requestOlder(pane) }} onClick={(event) => { if (event.target === event.currentTarget) clearAllSelections() }} > - + {showLoading && ( +
+ + +
+ )} +
- {records.map((record) => { + {virtualTop > 0 && ( + + + )} + {renderedRecords.map(({ record, position, terminalRequestBoundary }) => { const displayText = recordDisplayText(record.cell) + const toolCallOnly = isToolCallOnly(record.cell) const toolCallText = toolCallTextParts(record.cell.kind, displayText) - const listDisplayText = toolCallText === undefined - ? displayText - : [toolCallText.name, toolCallText.args].filter(Boolean).join(' ') + const listDisplayText = toolCallOnly + ? '(tool call only)' + : toolCallText === undefined + ? displayText + : [toolCallText.name, toolCallText.args].filter(Boolean).join(' ') const isCollapsedSummary = record.collapsedSummary !== undefined const isRequestOnly = record.cell.requestOnly === true const isInitialSystem = record.cell.kind === 'system' @@ -1824,15 +2163,15 @@ export function TrajectoryTable({ : `Request #${request}${requestInfo?.purpose === 'compaction' ? ' · Compaction' : ''}` const requestSelected = request !== undefined && selectedRequest?.turn === record.turn - && selectedRequest.section === record.section - && selectedRequest.number === request + && selectedRequest.group === record.group const sectionActive = record.turn === null ? activeSection === record.section : activeTurn === record.turn return ( { if (record.collapsedSummaryKind === 'turn' && record.turn !== null) { onToggleTurn(record.turn) - } else onToggleAssistant(record.cell.index) + } else onToggleAssistant(trajectoryRecordId(record.cell)) } : () => { selectRecord(record.cell.index) }} onDoubleClick={(event) => { @@ -1875,7 +2217,7 @@ export function TrajectoryTable({ && assistantToolCalls(allRecords, record.cell.index).length > 0 ) { event.preventDefault() - onToggleAssistant(record.cell.index) + onToggleAssistant(trajectoryRecordId(record.cell)) return } if (!record.turnStart) return @@ -1894,7 +2236,7 @@ export function TrajectoryTable({ if (isCollapsedSummary) { if (record.collapsedSummaryKind === 'turn' && record.turn !== null) { onToggleTurn(record.turn) - } else onToggleAssistant(record.cell.index) + } else onToggleAssistant(trajectoryRecordId(record.cell)) return } selectRecord(record.cell.index) @@ -1917,9 +2259,8 @@ export function TrajectoryTable({ event.stopPropagation() selectRequest({ turn: record.turn, - section: record.section, - number: request, group: record.group, + ...(requestInfo?.seq === undefined ? {} : { seq: requestInfo.seq }), }) }} onDoubleClick={(event) => { event.stopPropagation() }} @@ -2013,8 +2354,8 @@ export function TrajectoryTable({ : `${listDisplayText} → ${record.cell.result}`} > - {isToolCallOnly(record.cell) - ? null + {toolCallOnly + ? (tool call only) : toolCallText === undefined ? listDisplayText || '—' : ( @@ -2047,6 +2388,16 @@ export function TrajectoryTable({ ) })} + {virtualBottom > 0 && ( + + + )}
@@ -2141,7 +2492,7 @@ export function TrajectoryTable({ <>