From 0a228f0a6affd854133bd02a2c1cf5657cf13532 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:53:11 +0800 Subject: [PATCH] feat(ui-chat): load earlier history with explicit consumption intent --- ...chat-history-consumption-details.i18n.yaml | 34 +++ ...-11-06-chat-history-consumption-details.md | 101 +++++++++ ...-06-chat-history-consumption-details.zh.md | 101 +++++++++ ...6-11-06-chat-history-consumption.i18n.yaml | 31 +++ .../2026-11-06-chat-history-consumption.md | 74 ++++++ .../2026-11-06-chat-history-consumption.zh.md | 74 ++++++ .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- .../src/client/contract/session.ts | 18 +- .../src/client/contract/snapshot.ts | 5 + .../src/client/sessions/session.ts | 151 ++++++++++--- .../tests/session.client.spec.ts | 212 +++++++++++++++++- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 4 +- packages/client/ui-chat/README.zh.md | 4 +- packages/client/ui-chat/src/client/apply.ts | 3 +- .../src/client/chat/ChatView.module.css | 17 ++ .../ui-chat/src/client/chat/ChatView.tsx | 31 ++- .../ui-chat/src/client/chat/flow-motion.ts | 3 + .../src/client/chat/use-chat-navigation.ts | 137 +++++++++-- .../src/client/chat/use-chat-scroll.ts | 54 +++-- .../src/client/chat/use-chat-viewport.ts | 209 +++++++++++++++-- .../ui-chat/src/client/contract/slots.ts | 3 + packages/client/ui-chat/src/client/locale.ts | 32 +++ .../tests/apply-inject.client.spec.tsx | 2 +- .../tests/chat-history-intent.client.spec.ts | 117 ++++++++++ .../ui-chat/tests/chat-scroll.client.spec.tsx | 18 +- .../ui-chat/tests/chat-view.client.spec.tsx | 173 ++++++++++---- .../tests/chat-viewport.client.spec.ts | 130 +++++++++++ .../conversation-registry.client.spec.ts | 3 +- .../tests/queue-dock.client.spec.tsx | 2 +- .../schedule-catalog-action.client.spec.tsx | 2 +- .../tests/ui-session.client.spec.ts | 2 +- .../ui-trajectory/tests/views.client.spec.tsx | 2 +- .../tests/plan-review-panel.client.spec.tsx | 2 +- .../user-questions-composer.client.spec.tsx | 2 +- .../src/client/api-catalog.ts | 4 +- .../src/client/slot-catalog.ts | 24 +- .../tests/quote-selection.client.spec.tsx | 2 +- .../client-runtime/src/fixtures.ts | 2 +- .../client-runtime/src/sessions.ts | 8 + 42 files changed, 1625 insertions(+), 180 deletions(-) create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md create mode 100644 packages/client/ui-chat/tests/chat-history-intent.client.spec.ts diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml new file mode 100644 index 0000000000..4d1f5caf20 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption-details.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md +/agent-note-chat-history-consumption-classes-and-interactions: + en: 69ce0866b2608208 + zh: 55fdeded5d7a4779 +/agent-note-chat-history-consumption-classes-and-interactions/problem: + en: edaa7ca0e55a9c33 + zh: 33d2b5ac07760988 +/agent-note-chat-history-consumption-classes-and-interactions/proposal: + en: 5e5553981c48d0e2 + zh: 1195ac8d64180451 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/owners-and-interfaces: + en: 58f6f76fd263cafb + zh: 13ac0a6259d30cda +/agent-note-chat-history-consumption-classes-and-interactions/proposal/data-lifetimes: + en: ffdbe0e796463624 + zh: f10bd2ced5748017 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/consumption-intent-and-wakeups: + en: 993c2985bf6f3c8f + zh: 8f88fb46584fb272 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads: + en: 2439cd4cb6a81bc4 + zh: 63b8c83897a88d2c +/agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered: + en: 1b9b8eb12ee5dbd7 + zh: e4ecc3cdc3375438 +/agent-note-chat-history-consumption-classes-and-interactions/acceptance-criteria: + en: 8a51c549570a5e0d + zh: eb7b3c27b9dcd98c +/agent-note-chat-history-consumption-classes-and-interactions/risks: + en: aee9f541d058818b + zh: 74e4b6098b9f4b46 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md new file mode 100644 index 0000000000..ccc137d86b --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md @@ -0,0 +1,101 @@ +# Agent Note: Chat history consumption classes and interactions + +Status: proposed + +English | [中文](2026-11-06-chat-history-consumption-details.zh.md) + +## Problem + +Session owns a history page's network lifetime, while Chat owns whether that page can safely enter the current view. Two-phase loading must reuse existing publication and scrolling capabilities without copying business data, consumption intent, and DOM preservation state into one owner. + +## Proposal + +[History prefetch and safe consumption](2026-11-06-chat-history-consumption.md) defines user-visible behavior and trade-offs. This note defines class interactions and lifetimes without adding an independent scroll animation or React commit manager. + +### Owners and interfaces + +| Owner | Data and operations | +|---|---| +| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` prepares and optionally consumes a page; `consumeOlder()` synchronously publishes a valid staged page; `historyLoadStatus` is idle/loading/pendingConsumption/error, and `loadingOlder` derives from loading, including Turn jumps | +| Session request record | Holds generation, starting cursor, page entries, hasMore, Promise, and consumption/invalidation flags; staging does not advance the visible window cursor | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; waits or falls back by blocker; only manual consumption registers a fold-completion callback | +| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | Reads internal input/motion state and scrollTop, returns a blocker or native/preserve/prepend, and performs distance measurement and existing anchor algorithms | +| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | Connects existing reading, scroll, content, and size notifications to consumption checks and settles a pending one-shot correction during commit handling | +| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | Requests and consumes through injected callbacks and reads state through useSession; renders a fixed-height history control without retaining Session history data or accumulating historyWasPartial | + +```text +ChatNavigation.checkHistory + ├─ pendingConsumption + intent=none → retain page until clicked + ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain consumption intent + │ ├─ motion/pointer/unavailable → auto falls back, manual waits + │ ├─ native → consumeOlder + │ ├─ prepend → capture paging position → consumeOlder → correct once after commit + │ └─ preserve → beginPreserving → consumeOlder + ├─ loading → no duplicate request + ├─ error → wait for explicit retry + └─ idle + hasMore + (manual intent or near top without following) → request a page + +Session.loadOlder + → prepareOlder reuses or creates the request + → await the captured request Promise + → consumeOlder when request identity remains valid and consumption is not deferred + +Session.prepareOlder + → network prepend → capture the page without publishing eventSource + → validate progress → pendingConsumption or error + +Session.consumeOlder + → check generation/cursor/consuming + → synchronous eventSource.prepend → existing Conversation merge and flush + → clear the request record and publish final status +``` + +### Data lifetimes + +`isOpen` means only that Session `openState === 'open'`; it is independent of whether a page is `pendingConsumption`. `historyWasPartial` is monotonic for one Client Session instance: once its visible window has `hasMore=true`, the fact remains until the instance ends, across component remounts and reconnects, without entering the persistent log. + +`prepareOlder()` returns an existing request or creates one, and `loadOlder()` rechecks identity after awaiting that captured request Promise. An obsolete Promise cannot consume a newer page. A default call consumes the prepared page; `deferConsumption` retains a valid nonempty page, while an empty terminal page can immediately confirm exhaustion. Consumption retains the request record and sets `consuming` to prevent synchronous subscriber reentry without borrowing the network loading state. + +An ordinary request captures the transport page first. It can be consumed only after the request succeeds and its cursor advances, or an empty page explicitly confirms exhaustion. Failures and empty pages that still claim more history enter error without automatic retry. Window replacement, reconnect, and disposal invalidate old pages; when an in-flight request may have advanced the transport cursor, the existing stream restart restores a baseline before another page is allowed. + +`loadThrough(seq)` is explicit navigation: it first adopts a staged page and then uses existing Turn-aligned paging. An ordinary in-flight request remains exclusive, and the caller continues after it settles. A jump publishes its successful prefix once at completion or a later failure, without delaying live appends. `loadingOlder` always equals `historyLoadStatus === 'loading'`. + +### Consumption intent and wakeups + +An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Motion, pointer, or unavailable positioning returns auto to none; touch and inner-scroll retain auto. Manual intent waits through these blockers rather than treating deferral as success. + +Prefetch reuses the existing 500ms reading sample, scrollend, content commits, and size notifications, coalescing them into one rAF check. It uses no IntersectionObserver or additional sample timer and measures nothing in the raw scroll event. Only a ResizeObserver entry for the scroller itself refreshes cached clientHeight during the callback's read phase; column growth does not reread viewport height. Once internal state permits an automatic request, it reads the history control's distance from the viewport and compares it with two cached viewport heights. + +`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained intent; fold-completion callbacks are registered only for manual intent. Without consumption intent, these notifications do not revive an abandoned automatic page. + +### Shared anchors and layout reads + +At `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`. + +Persistent preservation restores the captured screen position. One-shot correction retains inner and outer scrolling since capture and compensates only layout displacement; it neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. + +Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence. + +## Alternatives considered + +**Pause publication globally in Conversation.** That also blocks live tail output and expands the cross-view impact. + +**Retain a complete window snapshot in Chat.** That copies business data and can overwrite messages received while waiting. + +**Store separate coordinates and continuously track the first row for one-shot correction.** That duplicates existing paging anchors and can expand scroll ownership; share the position record and calculations while keeping lifetimes separate. + +## Acceptance criteria + +- Default single-stage calls, deferred consumption, and Turn jumps coexist; an old request cannot consume or overwrite a new one. +- Ordinary events do not revive automatic fallback; touch/inner-scroll continuation, manual completion, and unmount cleanup have focused verification. +- One-shot correction does not register persistent observation or undo intervening reader movement; existing persistent and inner preservation do not regress. +- Distance checks use cached viewport height; raw scroll listeners and consumption admission perform no layout reads. + +## Risks + +**Known issue: `preserveMovement` cannot distinguish native anchoring from reader input.** The shared correction adds changes in the outer and inner scroll positions since capture. A deterministic geometry model confirms duplicate compensation when the browser has already anchored the same prepend: an outer `scrollTop` of `0.5`, or outer `0` with inner `40`, enters the one-shot path and treats the native adjustment as movement to preserve. The resulting additional displacement is an algorithmic limitation, not evidence that every browser exhibits it. Code remains unchanged for this report-only finding; independent actual-browser verification is pending. + +Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual intent can still wait if usable positioning never becomes available; actual views need cancellation, reconnect, and anchorless-structure verification. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build. + +Reports must identify source/artifact versions, real or synthetic inputs, missing conditions, and cleanup results. V8 function or range hits are not TypeScript line/branch percentages; earlier iteration recordings, Chrome/Safari manual feedback, or a successful build do not establish a complete matrix pass for this proposal. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md new file mode 100644 index 0000000000..104b65e5a6 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md @@ -0,0 +1,101 @@ +# Agent Note: Chat 历史消费的类与交互 + +Status: proposed + +[English](2026-11-06-chat-history-consumption-details.md) | 中文 + +## Problem + +历史页的网络生命周期属于 Session,能否安全进入当前页面属于 Chat。两阶段加载需要复用现有事件发布与滚动能力,不能把业务数据、消费意图和 DOM 保位状态复制到同一个所有者。 + +## Proposal + +用户可见行为与取舍由[历史预取与安全消费](2026-11-06-chat-history-consumption.zh.md)定义。本文规定类之间的调用与生命周期,不增加独立的滚动动画或 React 提交管理。 + +### 所有者与接口 + +| 所有者 | 数据与操作 | +|---|---| +| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` 准备并按选项消费一页;`consumeOlder()` 同步发布有效暂存页;`historyLoadStatus` 表达 idle/loading/pendingConsumption/error,`loadingOlder` 从 loading 派生并包含 Turn 跳转 | +| Session 请求记录 | 保存 generation、请求前游标、页内容、hasMore、Promise 与消费/失效标记;缓存页不提前改变可见窗口游标 | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;按阻塞原因等待或退回按钮;仅手动消费注册折叠结束通知 | +| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | 读取内部输入/动画状态与 scrollTop,报告阻塞原因或 native/preserve/prepend;执行距离测量和已有锚点算法 | +| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | 把既有阅读、滚动、内容及尺寸通知接到消费检查;在提交阶段结算待执行的一次补偿 | +| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | 通过注入回调请求/消费,通过 useSession 读取状态;固定高度显示历史控件,不保存 Session 历史数据或累计 historyWasPartial | + +```text +ChatNavigation.checkHistory + ├─ pendingConsumption + intent=none → retain page until clicked + ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain consumption intent + │ ├─ motion/pointer/unavailable → auto falls back, manual waits + │ ├─ native → consumeOlder + │ ├─ prepend → capture paging position → consumeOlder → correct once after commit + │ └─ preserve → beginPreserving → consumeOlder + ├─ loading → no duplicate request + ├─ error → wait for explicit retry + └─ idle + hasMore + (manual intent or near top without following) → request a page + +Session.loadOlder + → prepareOlder reuses or creates the request + → await the captured request Promise + → consumeOlder when request identity remains valid and consumption is not deferred + +Session.prepareOlder + → network prepend → capture the page without publishing eventSource + → validate progress → pendingConsumption or error + +Session.consumeOlder + → check generation/cursor/consuming + → synchronous eventSource.prepend → existing Conversation merge and flush + → clear the request record and publish final status +``` + +### 数据生命周期 + +`isOpen` 只表达会话 `openState === 'open'`,与某页是否 `pendingConsumption` 无关。`historyWasPartial` 是客户端 Session 实例的单调事实:可见窗口曾有 `hasMore=true` 后保留到实例结束,不随组件重挂载或重连清除,不写持久化日志。 + +`prepareOlder()` 返回已有请求或创建一个请求,`loadOlder()` 等待捕获的请求 Promise 后再核对身份。旧 Promise 完成不能消费随后创建的新页。默认调用消费准备好的页;`deferConsumption` 保留有效非空页,终态空页可以直接确认耗尽。消费期间保持请求记录并设置 `consuming`,阻止同步订阅者重入,不借用网络 loading 状态。 + +普通请求先捕获传输返回页,只有请求成功且游标前进,或空页明确表示耗尽时才能消费。失败或空页仍声称有更多则进入 error,不自动重试。窗口替换、重连和销毁使旧页失效;如果在途请求可能已推进传输游标,现有流重启先恢复基线,再允许下一页。 + +`loadThrough(seq)` 是显式导航:先采用已有待消费页,再沿既有 Turn 对齐规则加载;普通请求在途时保持互斥,由调用方在其结算后继续。跳转的成功前缀在完成或后续失败时一次发布,实时追加不等待它。`loadingOlder` 始终等价于 `historyLoadStatus === 'loading'`。 + +### 消费意图与唤醒 + +自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。motion、pointer 或 unavailable 使 auto 退回 none;touch 与 inner-scroll 保留 auto。manual 在这些阻塞下继续等待,不把暂缓当成成功。 + +历史预取复用已有 500ms 阅读采样、scrollend、内容提交和尺寸通知,并合并为一次 rAF 检查。不使用 IntersectionObserver,不新增采样计时器,不在原始 scroll 事件中测量。仅 scroller 自身的 ResizeObserver 条目在回调读阶段更新 clientHeight 缓存,column 增长不重新读取视口高度。内部状态允许自动请求时,读取历史控件相对视口的位置,与缓存的两屏高度比较。 + +`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的意图;折叠结束回调只为 manual 注册。没有消费意图时这些通知不恢复已经放弃的自动页。 + +### 锚点复用与布局读取 + +顶部 `scrollTop ≤ 0.5` 使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。 + +持续保位恢复采集时的屏幕位置。一次补偿保留采集后发生的内外层滚动,只抵消布局位移;它不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 + +距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。 + +## Alternatives considered + +**在 Conversation 全局暂停发布。** 会同时阻止尾部实时输出,扩大跨视图影响。 + +**在 Chat 保存完整窗口快照。** 复制业务数据,消费时可能覆盖等待期间的新消息。 + +**为一次补偿另存坐标并持续追踪首行。** 与既有分页锚点重复,并可能扩大滚动控制;共享位置记录和计算,只区分生命周期。 + +## Acceptance criteria + +- 默认单阶段调用、延迟消费及 Turn 跳转共存,旧请求不能消费或覆盖新请求。 +- auto 回退不会被普通事件恢复;触摸与内层滚动续接、manual 完成承诺和卸载清理都有定向验证。 +- 一次补偿不注册持续观察、不撤销期间的读者滚动;既有持续保位和内层补偿不退化。 +- 距离读取使用缓存视口高度;原始滚动监听与消费准入不读取布局。 + +## Risks + +**已知问题:`preserveMovement` 无法区分原生锚定与读者输入。** 共享补偿计算会加上采集后内外层滚动位置的变化。确定性的几何模型已确认:浏览器已为同一次前插完成锚定时,外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40`,会进入一次补偿路径,把原生调整当成需要保留的移动,从而重复补偿。产生的额外位移是算法限制,不代表所有浏览器都会复现。本问题按仅报告处理,代码不变;独立真实浏览器验证仍待完成。 + +显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动操作若永远得不到可用定位条件仍可能等待;实际页面应验证取消、重连和无锚点结构。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。 + +验收报告应列明源码/产物版本、真实或合成输入、未覆盖条件以及清理结果。V8 函数或区间命中不等于 TypeScript 行/分支百分比;早期迭代的录像、Chrome/Safari 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml new file mode 100644 index 0000000000..85c5633b69 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md +/agent-note-chat-history-prefetch-and-safe-consumption: + en: b0bb85f8780edc41 + zh: f3576c234a2f1a99 +/agent-note-chat-history-prefetch-and-safe-consumption/problem: + en: fbdf714be9ea6c90 + zh: d9b6c07347812fc1 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal: + en: bda6c4b3dfff143e + zh: 4316f6dec6adaa50 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/manual-and-automatic-loading: + en: 2cbfd8cc05037895 + zh: 024968506e2ac994 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation: + en: 1afb940b9b2a2fcc + zh: 8201614a80598e5b +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions: + en: dd4eeadd2fccab4b + zh: e05d53e63cc44ddf +/agent-note-chat-history-prefetch-and-safe-consumption/alternatives-considered: + en: 7c6d9d470c5b5c93 + zh: dc12846ee0f56aae +/agent-note-chat-history-prefetch-and-safe-consumption/acceptance-criteria: + en: b3005052df98ab10 + zh: c4bdf2bed8d23550 +/agent-note-chat-history-prefetch-and-safe-consumption/risks: + en: 2016c51019518572 + zh: e31e4e4ac09a2c5d diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md new file mode 100644 index 0000000000..bfe932f77b --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md @@ -0,0 +1,74 @@ +# Agent Note: Chat history prefetch and safe consumption + +Status: proposed + +English | [中文](2026-11-06-chat-history-consumption.zh.md) + +## Problem + +With only a Load earlier button, readers must reach the beginning of loaded history before clicking. Prefetch can reduce interruption, but a request that starts in a suitable state can return during touch dragging, a navigation change, or a fold animation. History prepending must not change the existing fold driver or simulate momentum. + +## Proposal + +Separate requesting history from consuming it. The Client Session retains at most one unconsumed page, and Chat decides whether and when to publish it. It retains the new page rather than an old window snapshot, so waiting does not block streaming at the tail. Class ownership and calls are described in the [technical details](2026-11-06-chat-history-consumption-details.md). + +### Manual and automatic loading + +A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. A temporary blocker does not complete the click; the operation ends with effective consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent. + +Automatic loading requests history after the reader leaves tail following and comes within two viewport heights of the history control. It reuses the existing 500ms reading sample, scroll completion, content commits, and size notifications, without another polling loop or IntersectionObserver. Detection can therefore wait until the next existing sample. + +A cached page and an intent to continue automatically are separate facts. Automatic loading falls back to a button on occasional conflicts instead of waiting for every state to recover. Touch and actual inner scrolling retain continuation so mobile readers need not click after every finger release. + +| State when data is ready | Automatic intent | Manual intent | +|---|---|---| +| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume with native browser anchoring | +| Stationary reading away from the top | Consume with existing reading preservation | Consume with existing reading preservation | +| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Reuse the paging anchor and correct once after prepend | +| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Retain intent until completion | +| A finger held down or actual inner scrolling | Retain intent and continue afterward | Retain intent and continue afterward | +| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Retain intent until usable | +| Tail following resumes after automatic prefetch | Keep the page and cancel automatic consumption | The click has paused tail following | +| Streaming continues at the tail | Does not itself block consumption | Does not itself block consumption | + +After fallback, scrolling, animation completion, and content notifications cannot reactivate that cached page; only a click or explicit navigation can adopt it. Requests and unconsumed pages remain mutually exclusive: no duplicate request for a cached page and no timeout that forces insertion. + +### Position and status presentation + +The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. A prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; persistent preservation elsewhere retains its existing lifetime. Reader movement during the correction interval is preserved rather than restoring the position from request time. + +The history control keeps the same height across states. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row. + +### Scope and retained decisions + +Do not add `flushSync` or change Conversation publication cadence, fold-batch targets, or ScrollFollow policy. Consumption admission reads only internal state and `scrollTop`; DOM geometry reads belong to distance confirmation and position correction. Do not add an independent persistent head-anchor controller, `batchShift`, or a per-frame compensator. + +[One fold motion](../../implemented/architecture/2026-10-13-chat-single-fold-motion.md) and [group-tree exchanges](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.md) retain ownership of folding and grouping decisions; this proposal does not supersede them. + +## Alternatives considered + +**Prepend every response immediately and compensate continuously.** That makes pagination take over existing motion; this design corrects once at the top and waits or falls back on conflicts. + +**Automatically wait for every unsafe state to recover.** That adds coordination obligations for occasional animations, navigation, and automatic continuation; retain touch continuation and manual completion, but return other automatic conflicts to the button. + +**Remove staging entirely or discard conflicting pages.** Conflicts can start during a request, and the transport history cursor may already have advanced; retaining one page is simpler than rolling back that cursor. + +**Disable loading whenever a Turn is running.** Readers still need history during long replies, so execution state cannot replace the current presentation conditions. + +**Separate IO prefetch wakeups and React synchronous-commit control.** Reuse existing sampling and publication, accepting sample latency; do not add commit scheduling without evidence of a concrete failure. + +## Acceptance criteria + +- Requests, staging, and consumption never duplicate a page request; tail streaming continues. +- Ordinary events do not revive automatic fallback; touch, inner scrolling, and manual clicks retain their specified continuation. +- Stationary and top-edge prepends preserve old content position; ordinary momentum consumption adds no outer JS scroll write. +- Failure, no progress, exhaustion, reconnect, and explicit navigation have defined outcomes without request loops or stale-page consumption. +- Control states have equal height; existing fold-driver behavior is retained, and browser evidence identifies the current build, simulated inputs, and missing cases. + +## Risks + +**Known issue: duplicate anchoring compensation.** A deterministic geometry-model reproduction shows that one-shot correction can count native anchoring for the same page as reader movement and compensate twice: this occurs with an outer `scrollTop` of `0.5`, or with outer `0` and inner `40` when native anchoring has already moved the inner position. The algorithm is therefore not universally safe. This issue is recorded without a code fix; independent verification in actual browsers is pending. The mechanism is detailed in the [technical risks](2026-11-06-chat-history-consumption-details.md#risks). + +CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. A stationary manual operation that can never obtain an anchor retains its completion intent and needs coverage for that structure. + +Audit and measurement are ongoing, so this record remains proposed. Earlier Chrome/Safari manual feedback and headless results from different iterations do not establish a complete matrix pass for the final source; actual scrollbar dragging, same-document reconnect, cross-platform input, and exceptional cleanup paths require separately attributed evidence. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md new file mode 100644 index 0000000000..31787a81b7 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md @@ -0,0 +1,74 @@ +# Agent Note: Chat 历史预取与安全消费 + +Status: proposed + +[English](2026-11-06-chat-history-consumption.md) | 中文 + +## Problem + +只提供“加载更早”按钮时,读者必须到达已加载历史的开头再点击。提前请求可以减少中断,但请求发出时适合加载,不代表返回时适合前插:读者可能开始触摸拖动、切换导航目标,或者遇到折叠动画。分页不应为了前插历史改变已有折叠驱动或模拟惯性。 + +## Proposal + +将历史请求与消费分开。客户端 Session 最多保留一页未消费的数据,Chat 决定是否以及何时发布它。数据保存为新页而不是旧窗口快照,所以等待不阻止尾部流式输出。类与调用关系见[技术细节](2026-11-06-chat-history-consumption-details.zh.md)。 + +### 手动与自动加载 + +手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。暂时不安全不算点击完成;该操作以有效消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。 + +自动加载在读者离开底部跟随、进入距历史控件两屏以内时请求。它复用已有 500ms 阅读采样及滚动结束、内容提交、尺寸通知,不新增轮询或 IntersectionObserver。代价是发现进入预取范围可能延后至下一次已有采样。 + +缓存是否存在与是否需要自动续接是两个事实。自动操作在低频冲突下退回按钮,不承诺等所有状态恢复;触摸与实际内层滚动仍保留续接,避免要求手机用户每次松手后再点击。 + +| 数据就绪时的状态 | 自动意图 | 手动意图 | +|---|---|---| +| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 浏览器原生锚定,消费 | +| 非顶部静止阅读 | 既有阅读保位,消费 | 既有阅读保位,消费 | +| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 复用分页锚点,前插后补偿一次 | +| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 保留意图,等待结束 | +| 手指按住或实际内层滚动 | 保留意图,结束后继续 | 保留意图,结束后继续 | +| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 保留意图,等待可用 | +| 自动预取后恢复底部跟随 | 保留缓存,取消自动消费 | 点击已暂停底部跟随 | +| 底部继续流式输出 | 本身不阻止消费 | 本身不阻止消费 | + +退回按钮后,滚动、动画结束和内容通知都不能重新激活该缓存页;只有点击或显式导航可以采用它。请求和待消费页仍然互斥,不为缓存页重复请求,也不超时强行插入。 + +### 位置与状态展示 + +会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;非顶部持续保位保持原生命周期。补偿期间发生的用户滚动保留,不把读者拉回请求发出时的位置。 + +历史控件各状态保持同高。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。 + +### 范围与既有决策 + +不新增 `flushSync`,不改变 Conversation 发布节奏、折叠批次目标或 ScrollFollow 的跟随策略。消费准入只读内部状态和 `scrollTop`;DOM 几何读取留在距离确认和位置补偿处。不新增独立的持续开头锚点控制器、`batchShift` 或每帧补偿器。 + +[单一折叠运动](../../implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md)与[分组树交互段](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md)仍拥有折叠和分组决策,本提案不取代它们。 + +## Alternatives considered + +**任意状态下数据到达即前插,再持续补偿。** 需要分页接管已有运动;本方案只在顶部补偿一次,冲突时等待或退回按钮。 + +**所有不安全状态都自动等待恢复。** 增加低频动画、导航与自动续接的协调义务;保留触摸续接和手动完成,其他自动冲突退回按钮。 + +**完全取消暂存或直接丢弃冲突页。** 请求途中仍可能发生冲突,而且传输历史游标可能已经前移;保留一页比回滚游标更直接。 + +**运行中的 Turn 禁止加载。** 长回复期间仍需阅读历史,运行状态不能代替当前界面的消费条件。 + +**独立 IO 预取唤醒与 React 同步提交控制。** 复用已有采样和发布路径,接受采样延迟;没有具体失败证据时不增加提交调度机制。 + +## Acceptance criteria + +- 请求、暂存与消费期间不重复取页;尾部流式继续更新。 +- 自动退回按钮后不会被普通事件恢复;触摸、内层滚动和手动点击保留约定的续接。 +- 静止和顶部前插保持旧内容位置;普通惯性消费不新增 JS 外层滚动写入。 +- 页面失败、无进展、到头、重连和显式导航均有明确结果,不循环请求或消费过期页。 +- 控件各状态同高;既有折叠驱动保持行为,真实浏览器验收区分当前构建、输入模拟和未覆盖情况。 + +## Risks + +**已知问题:锚定重复补偿。** 确定性的几何模型复现表明,一次补偿可能把同一页已经发生的原生锚定当作读者移动,再补偿一次:外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40` 且原生锚定已移动内层位置时会出现。该算法因此不能视为普遍安全。本问题仅记录,不修改代码;独立的真实浏览器验证仍待完成。机制见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。 + +原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。静止手动消费若始终无法获得锚点,完成意图仍会等待,需要覆盖该特殊结构。 + +审计与测量尚在进行,本记录保持 proposed。此前 Chrome/Safari 手工反馈和不同迭代的 headless 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 3d31867b67..94482498be 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 9cac36e3c0a32959 - zh: 37c42cc3edafa798 + en: 50fa3dd0a2ce79c8 + zh: 88bd7ea6058d2122 /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index b430594b0e..f414ce78ef 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -70,7 +70,7 @@ Fork copies the exact inclusive event prefix selected by `atSeq`, including a cu A resume blocked by an existing write handle returns `session/writer-held` with the Session id; other resume failures retain `gateway/internal`. -`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` publishes one Host-selected page directly. +`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` prepares and consumes one Host-selected page; `{ deferConsumption: true }` retains that page until `consumeOlder()` publishes it synchronously. A retained page blocks another ordinary request without blocking live events. `historyLoadStatus` distinguishes `idle`, `loading`, `pendingConsumption`, and `error`; `loadingOlder` is derived from `loading`, including Turn jumps. Failures and pages without progress permit explicit retry rather than claiming exhaustion. `historyWasPartial` remembers an incomplete visible window for the Client Session lifetime, including reconnects, without persisting presentation state. The Client's initial `follow`, reconnect openings, and `loadOlder()` request at least 50 append-origin `user/message` and `assistant/message` events and cross at least two `turn/start` events, including the partial Turn at the loaded window's beginning. The Host stops at the first Turn start satisfying both minima, or at 500 counted messages or history exhaustion, whichever comes first. Steering does not add a Turn boundary. Intervening events accompany the page without counting toward the message budget. The optional `turnWindow` on page and follow requests supplies these minima under `maxMessages`. `loadThrough()` uses the same rules with a 200-message minimum per page; the 500-message cap does not limit the whole jump. Requests without `turnWindow` retain message-aligned paging. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 314ec58840..2a83f4504d 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -70,7 +70,7 @@ Fork 将 `atSeq` 选定的含边界事件前缀(包括开放轮次内的截点 恢复会话时若已有写句柄占用,返回 `session/writer-held`,并携带会话 id;其他恢复失败仍返回 `gateway/internal`。 -`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 直接发布 Host 选取的一页结果。 +`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 准备并消费 Host 选取的一页;传入 `{ deferConsumption: true }` 时保留这一页,直到 `consumeOlder()` 同步发布。暂存页阻止重复普通请求,但不阻止实时事件。`historyLoadStatus` 区分 `idle`、`loading`、`pendingConsumption` 和 `error`;`loadingOlder` 从 `loading` 派生,包含 Turn 跳转。失败和无进展页面允许明确重试,不伪装成历史耗尽。`historyWasPartial` 在客户端 Session 生命周期内记住可见窗口曾不完整,重连保留,但不持久化呈现状态。 Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 append 方式追加的 `user/message` 和 `assistant/message` 事件,并向前跨过至少两个 `turn/start`,其中包含已加载窗口开头尚未补齐的轮次。Host 在首次同时满足两个下限的轮次开头停止;若先达到 500 条计数消息或历史已耗尽,则立即返回。Steering 不增加轮次分界。区间内的其他事件随页返回,但不计入消息预算。分页和 follow 请求可选的 `turnWindow` 在 `maxMessages` 上限内指定这两个下限。`loadThrough()` 复用相同规则,仅将每页消息数下限设为 200;500 条上限不限制整次跳转。不带 `turnWindow` 的请求保留按消息对齐的分页方式。 diff --git a/packages/api/session-controller/src/client/contract/session.ts b/packages/api/session-controller/src/client/contract/session.ts index 9233ac84cb..ce060ec4aa 100644 --- a/packages/api/session-controller/src/client/contract/session.ts +++ b/packages/api/session-controller/src/client/contract/session.ts @@ -4,8 +4,8 @@ * ObservableSnapshot half), and orchestration code calls the behavior verbs * below — nothing else. Widening this interface is the explicit act of * widening what features may do to a session (and what every test fixture - * must stub); implementation-internal entry points (history staging, wire-frame - * dispatch) stay on the class, invisible out here. + * must stub); implementation-internal wire-frame dispatch stays on the class, + * invisible out here. */ import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' @@ -132,10 +132,18 @@ export interface ISession { /** * Extend history by at least 50 messages and two Turn starts, including a * partial Turn at the window's beginning. Stop at 500 messages or history - * exhaustion even when those minima cannot be met. Publish one prepend. - * @returns completion; failures land in snapshot.openState/loadingOlder. + * exhaustion even when those minima cannot be met. At most one page may be + * loading or awaiting consumption; live events remain independently visible. + * @param options - deferConsumption keeps the page unpublished until consumeOlder; omitted consumes before completion. + * @returns request completion; failures and no progress set snapshot.historyLoadStatus to error. */ - loadOlder(): Promise + loadOlder(options?: { deferConsumption?: boolean }): Promise + /** + * Publish the prepared page synchronously if its generation and starting cursor still match. + * A terminal empty page may publish hasMore=false; an invalidated page is discarded. + * @returns whether a prepared page was published; false while loading, absent, or invalidated. + */ + consumeOlder(): boolean /** * Page history backwards until the window covers `seq` (inclusive) — the * turn-jump loader. Repeated calls while a jump is paging lower its shared diff --git a/packages/api/session-controller/src/client/contract/snapshot.ts b/packages/api/session-controller/src/client/contract/snapshot.ts index 4912d19b16..b6ba71b907 100644 --- a/packages/api/session-controller/src/client/contract/snapshot.ts +++ b/packages/api/session-controller/src/client/contract/snapshot.ts @@ -78,7 +78,12 @@ export interface SessionSnapshot { readonly openState: OpenState readonly openError: RemoteFailure | null readonly hasMore: boolean + /** This Client Session has exposed an incomplete history window; remains true across replacements. */ + readonly historyWasPartial: boolean + /** Whether historyLoadStatus is loading, including Turn-jump requests. */ readonly loadingOlder: boolean + /** History request status; pendingConsumption retains an unpublished ordinary page. */ + readonly historyLoadStatus: 'idle' | 'loading' | 'pendingConsumption' | 'error' readonly promptError: PromptError | null readonly blank: boolean readonly lastAgentError: string | null diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index e74dd84422..60194de5eb 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -67,6 +67,16 @@ interface PendingHistory { readonly pages: (readonly SessionEventLikeEntry[])[] } +interface OlderHistoryRequest { + readonly generation: number + readonly beforeSeq: SessionLogOffset + page: { readonly entries: readonly SessionEventLikeEntry[]; readonly hasMore: boolean } | null + invalidated: boolean + recovering: boolean + consuming: boolean + promise?: Promise +} + /** Manager-owned observers of a Session object's local state edges. */ export interface SessionOptions { /** Catalog-discovered address selecting non-activating subagent transport. */ @@ -95,13 +105,16 @@ export class Session implements SessionFace { // ---- Window and derived state (all private; the snapshot is the only read API) ---- private baseSeq = SessionLogOffset(0) private hasMore = false + private historyWasPartial = false private openState: OpenState = 'cold' private openError: RemoteFailure | null = null private openPromise: Promise | null = null /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale * passes drop all writes once the generation moves on. */ private openGeneration = 0 - private loadingOlder = false + private get loadingOlder(): boolean { return this.historyLoadStatus === 'loading' } + private historyLoadStatus: SessionSnapshot['historyLoadStatus'] = 'idle' + private olderRequest: OlderHistoryRequest | null = null /** Shared low-water target of the running jump loop; null when no jump is paging. */ private jumpTargetSeq: SessionSeq | null = null /** The running jump loop's completion, shared by retargeting callers. */ @@ -415,30 +428,95 @@ export class Session implements SessionFace { return promise } - /** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */ - async loadOlder(): Promise { - if (this.openState !== 'open' || !this.hasMore || this.loadingOlder) return + /** @inheritdoc */ + async loadOlder(options?: { deferConsumption?: boolean }): Promise { + const request = this.prepareOlder() + await request?.promise + if (request !== null && this.olderRequest === request + && (!options?.deferConsumption || request.page?.entries.length === 0)) this.consumeOlder() + } + + private prepareOlder(): OlderHistoryRequest | null { + if (this.olderRequest !== null) return this.olderRequest const events = this.events - if (events === undefined) return - this.loadingOlder = true + if (this.openState !== 'open' || !this.hasMore || this.loadingOlder || events === undefined) return null + const request: OlderHistoryRequest = { + generation: this.openGeneration, + beforeSeq: this.baseSeq, + page: null, + invalidated: false, + recovering: false, + consuming: false, + } + this.olderRequest = request + this.historyLoadStatus = 'loading' this.notifier.markDirty() - try { - await events.prepend({ - beforeSeq: this.baseSeq, - ...HISTORY_PAGE_OPTIONS, - }) - } catch (error) { - if (!isRemoteFailure(error)) { - console.error('[session-controller] loadOlder failed:', error) + request.promise = (async () => { + try { + await events.prepend({ beforeSeq: request.beforeSeq, ...HISTORY_PAGE_OPTIONS }) + if (this.olderRequest !== request) return + if (request.invalidated || request.generation !== this.openGeneration || request.beforeSeq !== this.baseSeq) return + const page = request.page + const first = page?.entries[0] + this.historyLoadStatus = page === null || (first === undefined ? page.hasMore : first.event.seq >= request.beforeSeq) + ? 'error' : 'pendingConsumption' + } catch (error) { + if (this.olderRequest !== request) return + request.page = null + this.historyLoadStatus = 'error' + if (!isRemoteFailure(error)) console.error('[session-controller] loadOlder failed:', error) + } finally { + if (this.olderRequest === request) { + if (request.invalidated && this.events === events) { + // A replacement restores the transport cursor before another page uses the visible window. + request.recovering = true + this.historyLoadStatus = 'loading' + events.restart() + } else if (this.historyLoadStatus === 'error') this.olderRequest = null + this.notifier.markDirty() + } } + })() + return request + } + + /** @inheritdoc */ + consumeOlder(): boolean { + const request = this.olderRequest + if (request === null || request.consuming || this.historyLoadStatus !== 'pendingConsumption' || request.page === null) return false + if (this.openState !== 'open' || request.invalidated || request.generation !== this.openGeneration + || request.beforeSeq !== this.baseSeq) { + this.clearOlderHistory() + return false + } + const page = request.page + // Retain the request through synchronous feed notification so subscribers cannot reenter consumption. + request.consuming = true + try { + this.prependWindow(page.entries, page.hasMore) + return true + } catch (error) { + if (this.olderRequest === request) this.historyLoadStatus = 'error' + throw error } finally { - this.loadingOlder = false + if (this.olderRequest === request) { + this.olderRequest = null + if (this.historyLoadStatus !== 'error') this.historyLoadStatus = 'idle' + } this.notifier.markDirty() } } + private clearOlderHistory(): void { + this.olderRequest = null + this.historyLoadStatus = this.pendingHistory === null ? 'idle' : 'loading' + this.notifier.markDirty() + } + /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */ loadThrough(seq: SessionSeq): Promise { + this.consumeOlder() + if (this.olderRequest !== null) return Promise.resolve() if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve() if (this.jumpPromise !== null) { // Retarget the running loop to the lowest requested seq. @@ -459,7 +537,7 @@ export class Session implements SessionFace { } this.pendingHistory = pending this.jumpTargetSeq = seq - this.loadingOlder = true + this.historyLoadStatus = 'loading' this.notifier.markDirty() // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the // stream generation; this pass then stops instead of paging the new @@ -467,27 +545,35 @@ export class Session implements SessionFace { const generation = this.openGeneration this.jumpPromise = (async () => { try { - while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { + while (this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { if (generation !== this.openGeneration) return const before = pending.beforeSeq await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS }) + if (generation !== this.openGeneration || this.pendingHistory !== pending) return // No-progress guard: an empty or dropped page that still claims more // history must end the loop, not spin it. - if (pending.beforeSeq >= before) return + if (pending.beforeSeq >= before) { + if (pending.hasMore) this.historyLoadStatus = 'error' + return + } + if (!pending.hasMore) return } } catch (error) { + if (generation === this.openGeneration && this.pendingHistory === pending) this.historyLoadStatus = 'error' if (!isRemoteFailure(error)) { console.error('[session-controller] loadThrough failed:', error) } } finally { - this.jumpTargetSeq = null - this.jumpPromise = null - this.pendingHistory = null - this.loadingOlder = false - if (generation === this.openGeneration && pending.pages.length > 0) { - this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + if (this.pendingHistory === pending) { + this.jumpTargetSeq = null + this.jumpPromise = null + this.pendingHistory = null + if (this.historyLoadStatus === 'loading') this.historyLoadStatus = 'idle' + if (generation === this.openGeneration && pending.pages.length > 0) { + this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + } + this.notifier.markDirty() } - this.notifier.markDirty() } })() return this.jumpPromise @@ -499,6 +585,7 @@ export class Session implements SessionFace { async resync(): Promise { if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open) this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -606,6 +693,7 @@ export class Session implements SessionFace { else this.retireFailedSubmission(requestId) } this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -655,7 +743,9 @@ export class Session implements SessionFace { ) return case 'prepend': - this.prependWindow(change.entries, change.hasMore) + if (this.olderRequest !== null) { + this.olderRequest.page = { entries: change.entries, hasMore: change.hasMore } + } else this.prependWindow(change.entries, change.hasMore) return case 'append': this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry)) @@ -676,8 +766,13 @@ export class Session implements SessionFace { // attempts makes a held notification reopen follow once for an atomic // page/baseline pair instead of applying it to an unrelated repair cut. const visible = this.assistantStream.replace(entries, assistantStream) + if (this.olderRequest !== null && this.loadingOlder && !this.olderRequest.recovering) { + this.olderRequest.invalidated = true + this.olderRequest.page = null + } else this.clearOlderHistory() this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0) this.hasMore = hasMore + this.historyWasPartial ||= hasMore if (this.pendingHistory !== null) { this.pendingHistory.beforeSeq = this.baseSeq this.pendingHistory.hasMore = hasMore @@ -745,6 +840,7 @@ export class Session implements SessionFace { } this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq) this.hasMore = hasMore + this.historyWasPartial ||= hasMore this.eventSource.prepend(entries, hasMore) } @@ -892,6 +988,7 @@ export class Session implements SessionFace { if (generation !== this.openGeneration || this.events !== events) return if (!isRemoteFailure(error)) throw error this.openGeneration++ + this.clearOlderHistory() this.events = undefined this.openPromise = null this.openState = 'error' @@ -917,7 +1014,9 @@ export class Session implements SessionFace { openState: this.openState, openError: this.openError, hasMore: this.hasMore, + historyWasPartial: this.historyWasPartial, loadingOlder: this.loadingOlder, + historyLoadStatus: this.historyLoadStatus, promptError: this.promptError, blank: this.blankBit, lastAgentError: this.lastAgentError, diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index e118ef29e5..6c6d308fe9 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -199,6 +199,194 @@ describe('paging', () => { expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) }) + it('stages one page without hiding live events and consumes it once', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + await session.loadOlder({ deferConsumption: true }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + await pushEvent(mock, ev.turnStart(SessionSeq(12), 2)) + const consumeStates: { status: string; loading: boolean }[] = [] + const stop = session.eventSource.subscribe(() => { + session.handleRunning(true) + const snapshot = session.getSnapshot() + consumeStates.push({ status: snapshot.historyLoadStatus, loading: snapshot.loadingOlder }) + expect(session.consumeOlder()).toBe(false) + void session.loadOlder({ deferConsumption: true }) + }) + try { + expect(session.consumeOlder()).toBe(true) + } finally { + stop() + } + expect(consumeStates).toEqual([{ status: 'pendingConsumption', loading: false }]) + expect(session.consumeOlder()).toBe(false) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq).concat(SessionSeq(12))) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', hasMore: false }) + }) + + it('joins a deferred request for default consumption without requesting another page', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + const gate = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(gate.promise) + await session.open() + const preparing = session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) + const consuming = session.loadOlder() + gate.resolve(history(older)) + await Promise.all([preparing, consuming]) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('default loading consumes an already prepared page without another request', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadOlder() + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('does not consume a newer prepared page when an obsolete default request completes', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + const obsolete = Promise.withResolvers() + const prepend = vi.spyOn(SessionEventStream.prototype, 'prepend').mockImplementationOnce(() => obsolete.promise) + const loading = session.loadOlder() + try { + await session.resync() + await session.loadOlder({ deferConsumption: true }) + obsolete.resolve(undefined) + await loading + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + expect(session.consumeOlder()).toBe(true) + } finally { + obsolete.resolve(undefined) + await loading + prepend.mockRestore() + } + }) + + it('retains partial-history knowledge across exhaustion and replacement only for the same Session instance', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const complete = [...older, ...newer] + const session = await sessionBench(mock, start, SID) + expect(session.getSnapshot().historyWasPartial).toBe(false) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + expect(session.getSnapshot().historyWasPartial).toBe(true) + await session.loadOlder() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.stream(FOLLOW, followScript(history(complete, false))) + await session.resync() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace complete window')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(3) }) + await mock.streams.drained(FOLLOW) + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + const client = await start() + const fresh = new Session(SID, client.ctx.remote) + onTestFinished(() => fresh.dispose()) + expect(fresh.getSnapshot().historyWasPartial).toBe(false) + await fresh.open() + expect(fresh.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: false }) + }) + + it('reports no progress and allows an explicit retry to confirm exhaustion', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, 'new', 'answer'), true))) + mock.remote.session.page.mockImplementation(pageRule(history([], true))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) + expect(session.consumeOlder()).toBe(false) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(mock.log.requests(PAGE)).toHaveLength(2) + }) + + it('consumes a staged page before a turn jump fetches the remaining history', async ({ mock, start }) => { + const oldest = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const middle = plainTurn(SessionSeq(6), 1, 'middle', 'answer') + const newest = plainTurn(SessionSeq(12), 2, 'newest', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(request => history( + request.beforeSeq === 12 ? middle : oldest, request.beforeSeq === 12, + ))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadThrough(SessionSeq(0)) + expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) + expect((mock.log.requests(PAGE) as SessionPageRequest[]).map(request => request.beforeSeq)).toEqual([12, 6]) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + }) + + it('invalidates a staged page when the event window is replaced', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.resync() + expect(session.consumeOlder()).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + }) + + it('repairs the transport cursor when follow replaces a window during an older request', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + const page = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(page.promise) + await session.open() + const loading = session.loadOlder({ deferConsumption: true }) + await vi.waitFor(() => { expect(mock.log.requests(PAGE)).toHaveLength(1) }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace while paging')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(2) }) + await mock.streams.drained(FOLLOW) + page.resolve(history(older)) + await loading + await vi.waitFor(() => { + expect(mock.log.requests(FOLLOW)).toHaveLength(3) + expect(session.getSnapshot().historyLoadStatus).toBe('idle') + }) + expect(session.consumeOlder()).toBe(false) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.loadOlder() + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + }) + it('installs a page without interpreting business replacement metadata', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history([ @@ -218,7 +406,7 @@ describe('paging', () => { } }) - it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async ({ mock, start }) => { + it('reports a discontinuous older page without claiming history exhaustion', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(10), 1, '新', '页'), true))) mock.remote.session.page.mockImplementation(pageRule(history(plainTurn(SessionSeq(0), 0, '断', '层'), true))) // tail seq 5, but baseSeq is 10 → hole @@ -229,7 +417,7 @@ describe('paging', () => { await session.loadOlder() const snapshot = session.getSnapshot() expect(session.eventSource.getSnapshot().entries).toEqual(windowBefore.entries) - expect(snapshot.hasMore).toBe(false) + expect(snapshot).toMatchObject({ hasMore: true, historyLoadStatus: 'error' }) } finally { errorSpy.mockRestore() } @@ -247,11 +435,11 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(request => (request.beforeSeq === 12 ? history(middle, true) : history(oldest)))) mock.remote.session.page.mockReturnValueOnce(gate.promise) const jump = session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(true) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) gate.resolve(history(middle, true)) await jump const snapshot = session.getSnapshot() - expect(snapshot.loadingOlder).toBe(false) + expect(snapshot).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) expect(mock.log.requests(PAGE)).toMatchObject([ { beforeSeq: 12, maxMessages: 500, turnWindow: { minMessages: 200, minTurns: 2 } }, @@ -325,7 +513,7 @@ describe('paging', () => { expect(changed).toHaveBeenCalledOnce() expect(eventSeqs(session)).toEqual([...middle, ...newest].map(event => event.seq)) - expect(session.getSnapshot()).toMatchObject({ loadingOlder: false, hasMore: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) }) it('discards buffered jump pages when the Session replaces its stream', async ({ mock, start }) => { @@ -430,7 +618,19 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(history([], true))) // empty page still claiming more history await session.open() await session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + + it('loadThrough treats a terminal empty page as exhaustion rather than an error', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const newest = plainTurn(SessionSeq(12), 2, 'x', 'y') + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.open() + await session.loadThrough(SessionSeq(0)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(eventSeqs(session)).toEqual(newest.map(event => event.seq)) expect(mock.log.requests(PAGE)).toHaveLength(1) }) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 2e047aefad..b17f85460e 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,8 +36,8 @@ en: e2b02942a55fb669 zh: a38bbee0cc69ae4e /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: dd4e69828096c3a0 - zh: 2a9bc370f44efcd7 + en: a8e5c51345ef61b9 + zh: 0e65169b79504da8 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 562ed7ebef..8df3db6b32 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -184,7 +184,9 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatViewport` owns turn-aware DOM reads, clamped writes, native events, and one retained paging anchor. For Load older, Node and Group seats mark eligible anchors from their existing disclosure state. The viewport selects the first nonempty, unhidden marker in transcript order without hit testing or geometry-based search, then measures that element and its scroll containers. It compensates the anchor's capped group first, then gives the remaining displacement to the transcript scrollport. An inner compensation write cancels that group's animation through its bound controller and pauses following; reader scrolling back to the bottom resumes it. Commits and later content resizes reuse that anchor; a remounted row is resolved by the same semantic key. Compensation stays within the actual scroll ranges without adding bottom space. -`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it; while a page is still loading, `scrollend` captures the reader's new position. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. +`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it. A deferred history request captures its anchor at consumption rather than at request time. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. + +History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and inner scrolling retain automatic intent until release; active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation. Stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. At scrollTop ≤ 0.5, the first paging anchor supplies one content-displacement correction that retains intervening reader movement and then releases immediately. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 7696d53951..c2144fd861 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -184,7 +184,9 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatViewport` 负责识别轮次的 DOM 读取、限制范围后的写入、原生事件及一个持续保留的分页锚点。加载更早时,Node 与 Group 容器根据已有开合状态标记可选锚点。视口按正文顺序选择第一个非空、未隐藏的标记,不做命中测试或按几何位置搜索,再测量该元素及其滚动容器。先补偿锚点所在的限高组,再把剩余位移交给整段文本的滚动区域。内层补偿写入通过该组绑定的控制器取消动画并暂停跟随,读者滚回底部后恢复。提交和后续内容尺寸变化复用该锚点;消息行重挂载时按同一语义 key 重新定位。补偿限于实际可滚动范围,不增加底部空白。 -`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点;分页仍在加载时,`scrollend` 会记录读者的新位置。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 +`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点。延迟消费的历史请求在消费时采集锚点,不在发请求时采集。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 + +历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和内层滚动保留自动意图至释放;动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。明确点击保留意图,直到消费、到头、失败或被新导航取代。静止消费使用保位,普通外层滚动使用浏览器锚定;scrollTop ≤ 0.5 时用首条分页锚点补偿一次内容位移,保留期间的读者滚动,随后立即释放。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 084e45e414..7e4a3a5f01 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -287,7 +287,8 @@ export function apply(ctx: Context): void { window.open(url, '_blank', 'noopener,noreferrer') } }, - loadOlder: () => { void session.loadOlder() }, + loadOlder: () => { void session.loadOlder({ deferConsumption: true }) }, + consumeOlder: () => session.consumeOlder(), loadThrough: seq => session.loadThrough(seq), loadImage: Object.assign( (attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment), diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 9929770b35..1f84e97842 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -37,6 +37,11 @@ container-type: inline-size; } +.scroll, +:global([data-conversation-scroll]):has(.root) { + overscroll-behavior-y: none; +} + .root[data-chat-following-tail] .scroll, :global([data-conversation-scroll]):has(.root[data-chat-following-tail]) { overflow-anchor: none; @@ -318,11 +323,15 @@ } .older { + overflow-anchor: none; display: flex; justify-content: center; } .older button { + display: grid; + line-height: 18px; + white-space: nowrap; border: none; border-radius: var(--dsw-radius-sm); padding: 4px 12px; @@ -332,6 +341,14 @@ cursor: pointer; } +.older button > span { + grid-area: 1 / 1; +} + +.historyHidden { + visibility: hidden; +} + .older button:disabled { cursor: default; opacity: 0.6; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 48e081bfa8..8fa10ca0ec 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -63,7 +63,7 @@ const MOTION_TAIL_MS = 800 export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu, - loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, + loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag, }: ChatViewSlotProps) { const { getTriggerProps } = useContextMenu() @@ -136,6 +136,8 @@ export function ChatView({ const openError = useSession(s => s.openError) const hasMore = useSession(s => s.hasMore) const loadingOlder = useSession(s => s.loadingOlder) + const historyLoadStatus = useSession(s => s.historyLoadStatus) + const historyWasPartial = useSession(s => s.historyWasPartial) const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null) const [fileOpenBusy, setFileOpenBusy] = useState(false) // Close/retry must ignore a settlement that started before the latest @@ -211,8 +213,9 @@ export function ChatView({ const steeringId = latestSteering?.source.kind === 'user' && 'rpcId' in latestSteering.source ? latestSteering.source.rpcId : latestSteering?.id ?? null const scroll = useChatScroll({ - ready: openState === 'open', - order, firstSeq, lastKey, running, loadingOlder, hasMore, chatScroll, loadOlder, loadThrough, deferCompletedTurns, + isOpen: openState === 'open', + order, firstSeq, lastKey, running, loadingOlder, historyLoadStatus, hasMore, chatScroll, + loadOlder, consumeOlder, loadThrough, deferCompletedTurns, lastIsUser: lastKey !== null && nodeStore.get(lastKey)?.kind === 'user', steeringId, submissionId: visibleSubmissions.at(-1)?.requestId ?? null, @@ -247,10 +250,24 @@ export function ChatView({ {t('chat.loadError', { message: openError.message, code: openError.code })} )} - {hasMore && ( -
-
)} diff --git a/packages/client/ui-chat/src/client/chat/flow-motion.ts b/packages/client/ui-chat/src/client/chat/flow-motion.ts index b34c1f2645..7deddd0e9a 100644 --- a/packages/client/ui-chat/src/client/chat/flow-motion.ts +++ b/packages/client/ui-chat/src/client/chat/flow-motion.ts @@ -72,6 +72,8 @@ export interface InputFoldDriver { /** Animation lifetime and fold coordination for one viewport. */ export interface FlowMotion extends FlowMotionRows { + /** @returns whether owned transitions or a scheduled, running, or settling batch remain active. */ + active(): boolean /** @returns whether a row owned by this viewport is closing. */ foldActive(): boolean /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */ @@ -494,6 +496,7 @@ export function createFlowMotion( return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, cancelInput, resumeInput, clear, hideNow, + active: () => running.size > 0 || batchScheduled || batch || settling, inputActive: () => batch || (batchScheduled && [...boxes.values()].some(box => box.closing && batchMember(box))), } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts index 84e2b3ec77..3d5dbed544 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts @@ -1,5 +1,6 @@ /** Turn jumps and history-prepend anchoring, independent of DOM measurement. */ import { useLayoutEffect, useState } from 'react' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionSeq } from '@deepseek-ai/dsh-session/types' import type { ChatNode } from '../contract/chat-nodes.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -8,10 +9,12 @@ import type { ChatReading, ReadingSample } from './use-chat-reading.ts' import type { ChatViewport } from './use-chat-viewport.ts' /** History availability and loading operations for the committed Chat window. */ -export interface ChatNavigationInput extends Pick { +export interface ChatNavigationInput extends Pick { readonly firstSeq: ChatNode['anchorSeq'] | null readonly hasMore: boolean readonly loadingOlder: boolean + readonly historyLoadStatus: SessionSnapshot['historyLoadStatus'] + readonly isOpen: boolean } interface TurnJump { @@ -22,23 +25,34 @@ interface TurnJump { repageHead: ChatNavigationInput['firstSeq'] } +type HistoryIntent = 'none' | 'auto' | 'manual' + /** Owns one replaceable turn jump and the anchor retained while history loads. */ export class ChatNavigation { private jump: TurnJump | null = null private settleFrame: number | null = null + private historyFrame: number | null = null + private stopFoldWait: (() => void) | null = null + private historyIntent: HistoryIntent = 'none' + private historyRequested = false constructor( private readonly viewport: ChatViewport, private readonly reading: ChatReading, private input: ChatNavigationInput, private readonly onBusyTurn: (turn: number | null) => void, + private readonly onHistoryIntent: (intent: HistoryIntent) => void = () => {}, ) {} /** * Adopt committed history availability without starting a request. * @param input - history state from the latest committed render. */ - setInput(input: ChatNavigationInput): void { this.input = input } + setInput(input: ChatNavigationInput): void { + this.input = input + this.historyRequested = false + if (!input.isOpen || input.historyLoadStatus === 'error' || !input.hasMore) this.setHistoryIntent('none') + } /** Cancel navigation when opening a Chat view. */ reset(): void { @@ -48,10 +62,21 @@ export class ChatNavigation { /** Cancel local callbacks; late history completions cannot revive a task. */ dispose(): void { this.clearTask() + if (this.historyFrame !== null) cancelAnimationFrame(this.historyFrame) + this.historyFrame = null + this.stopFoldWait?.() + this.stopFoldWait = null } /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */ cancel(): void { + this.setHistoryIntent('none') + this.clearTask() + this.onBusyTurn(null) + } + + /** Release a jump after reader input without cancelling an accepted history click. */ + readerInteracted(): void { this.clearTask() this.onBusyTurn(null) } @@ -60,6 +85,7 @@ export class ChatNavigation { this.cancelFrame() this.jump = null this.viewport.stopPreserving() + this.viewport.cancelHistoryPrepend() } /** @@ -90,12 +116,99 @@ export class ChatNavigation { this.request(jump) } - /** Request one older page while retaining the current semantic position. */ + /** Request and consume one page, retaining the click until success, exhaustion, or failure. */ readonly loadEarlier = (): void => { this.cancel() - this.viewport.beginPaging() + this.setHistoryIntent('manual') this.reading.pauseFollowing() - this.input.loadOlder() + if (this.input.historyLoadStatus === 'error') { + this.historyRequested = true + this.input.loadOlder() + } else this.requestHistoryCheck() + } + + private setHistoryIntent(intent: HistoryIntent): void { + if (intent === this.historyIntent) return + this.historyIntent = intent + if (intent !== 'manual') { + this.stopFoldWait?.() + this.stopFoldWait = null + } + this.onHistoryIntent(intent) + } + + /** Coalesce event-driven checks; waiting never schedules its own next frame. */ + requestHistoryCheck(): void { + if (!this.input.isOpen || this.input.historyLoadStatus === 'error') return + if (this.historyIntent === 'none' && (this.input.historyLoadStatus !== 'idle' + || !this.input.hasMore || this.reading.followingTail)) return + if (this.historyFrame !== null || typeof requestAnimationFrame !== 'function') return + this.historyFrame = requestAnimationFrame(() => { + this.historyFrame = null + this.checkHistory() + }) + } + + private checkHistory(): void { + const input = this.input + if (!input.isOpen || this.jump !== null || this.historyRequested || input.loadingOlder) return + if (input.historyLoadStatus === 'error') return + if (input.historyLoadStatus === 'pendingConsumption') { + if (this.historyIntent === 'none') return + if (this.reading.followingTail && this.historyIntent === 'auto') { + this.setHistoryIntent('none') + return + } + const mode = this.viewport.historyConsumption() + switch (mode) { + case 'touch': + case 'inner-scroll': + return + case 'motion': + case 'pointer': + case 'unavailable': + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + else if (mode === 'motion' && this.viewport.motion.foldActive()) { + this.stopFoldWait ??= this.viewport.motion.onFoldIdle(() => { + this.stopFoldWait = null + this.requestHistoryCheck() + }) + } + return + case 'prepend': + if (!this.viewport.beginHistoryPrepend() && input.firstSeq !== null) { + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + return + } + break + case 'preserve': + case 'native': + break + } + if (mode === 'preserve') { + this.viewport.beginPreserving() + if (!this.viewport.preserving) this.viewport.beginPaging() + if (!this.viewport.preserving && input.firstSeq !== null) { + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + return + } + this.reading.pauseFollowing() + } + this.historyRequested = true + const consumed = input.consumeOlder() + if (consumed) this.setHistoryIntent('none') + else { + this.historyRequested = false + if (mode === 'preserve') this.viewport.stopPreserving() + if (mode === 'prepend') this.viewport.cancelHistoryPrepend() + } + return + } + if (!input.hasMore || this.historyIntent !== 'manual' && (this.reading.followingTail + || !this.viewport.confirmHistoryStart())) return + if (this.historyIntent === 'none') this.setHistoryIntent('auto') + this.historyRequested = true + input.loadOlder() } /** @@ -120,13 +233,6 @@ export class ChatNavigation { return true } - /** Retarget a still-loading page only after inner or outer reader scrolling ends. */ - readerSettled(): void { - if (this.input.loadingOlder && this.jump === null && !this.viewport.preserving && !this.reading.followingTail) { - this.viewport.beginPreserving() - } - } - /** Land, retry, or complete the current jump against the committed window. */ reconcile(): void { const jump = this.jump @@ -197,10 +303,11 @@ export class ChatNavigation { */ export function useChatNavigation( viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput, -): { navigation: ChatNavigation; busyTurn: number | null } { +): { navigation: ChatNavigation; busyTurn: number | null; historyPending: boolean; historyProcessing: boolean } { const [busyTurn, setBusyTurn] = useState(null) - const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn)) + const [historyIntent, setHistoryIntent] = useState('none') + const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn, setHistoryIntent)) useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input]) useLayoutEffect(() => () => { navigation.dispose() }, [navigation]) - return { navigation, busyTurn } + return { navigation, busyTurn, historyPending: historyIntent === 'manual', historyProcessing: historyIntent !== 'none' } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts index 7924a33e3f..c8254dc626 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts @@ -1,5 +1,5 @@ /** Composes viewport operations, reading policy, and history navigation for Chat. */ -import { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react' +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react' import type { TranscriptViewMode } from '../../chat-settings.ts' import type { ChatSnapshot } from '../contract/snapshot.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -11,7 +11,6 @@ import type { FlowMotionRows } from './flow-motion.ts' /** Committed content and Session operations used to reconcile scroll ownership. */ export interface ChatScrollInput extends ChatNavigationInput { readonly chatScroll: ChatViewSlotProps['chatScroll'] - readonly ready: boolean readonly order: readonly string[] readonly lastKey: string | null readonly lastIsUser: boolean @@ -33,12 +32,16 @@ interface ChatScrollState extends ChatReadingState { readonly busyTurn: number | null readonly navigateToTurn: ChatNavigation['navigateToTurn'] readonly loadEarlier: ChatNavigation['loadEarlier'] + readonly historyInputHeld: boolean + readonly historyProcessing: boolean + readonly historyPending: boolean + readonly historyEdgeRef: (element: HTMLDivElement | null) => void readonly returnToBottom: () => void readonly motion: FlowMotionRows } /** - * Coordinate scroll policy after Chat content commits. Initial history must be ready + * Coordinate scroll policy after Chat content commits. Initial history must be available * before automatic scroll or resize handling can initialize reading state and fold motion. * New submitted input supersedes pending reader sampling. * @param input - current Chat content, scroll memory, and history operations. @@ -46,15 +49,17 @@ interface ChatScrollState extends ChatReadingState { */ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const { - ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, - deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough, transcriptView, + isOpen, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, + deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, historyLoadStatus, + loadOlder, consumeOlder, loadThrough, transcriptView, } = input const { viewport, listRef, columnRef } = useChatViewport() + const [historyInputHeld, setHistoryInputHeld] = useState(false) const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null) const navigationInput = useMemo(() => ({ - firstSeq, loadingOlder, hasMore, loadOlder, loadThrough, - }), [firstSeq, loadingOlder, hasMore, loadOlder, loadThrough]) - const { navigation, busyTurn } = useChatNavigation(viewport, reading, navigationInput) + firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough, + }), [firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough]) + const { navigation, busyTurn, historyPending, historyProcessing } = useChatNavigation(viewport, reading, navigationInput) const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({ input, applied: null, opened: false, }) @@ -64,7 +69,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const processContent = useCallback(() => { const current = content.current.input - if (!current.ready && !content.current.opened) return + if (!current.isOpen && !content.current.opened) return const previous = content.current.applied const steeringInput = current.steeringId !== null && current.steeringId !== previous?.steeringId && current.steeringId !== previous?.submissionId @@ -73,7 +78,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey) || steeringInput || submissionInput if (reading.pending && !ownInput) return content.current.applied = current - if (current.ready && !content.current.opened) { + if (current.isOpen && !content.current.opened) { content.current.opened = true navigation.reset() reading.restore() @@ -92,7 +97,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { navigation.reconcile() return } - const tipChanged = previous === null || current.ready !== previous.ready + const tipChanged = previous === null || current.isOpen !== previous.isOpen || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey || current.order.length !== previous.order.length || current.running !== previous.running || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId @@ -112,12 +117,17 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { }, scrollEnd: (outer) => { reading.onScrollEnd(outer) - navigation.readerSettled() + navigation.requestHistoryCheck() + }, + interact: () => { navigation.readerInteracted() }, + history: () => { + setHistoryInputHeld(viewport.historyInputHeld) + if (content.current.opened) navigation.requestHistoryCheck() }, - interact: () => { navigation.cancel() }, intent: () => { cancelPendingFollow(); reading.interruptFollow() }, resize: () => { if (!content.current.opened) return + navigation.requestHistoryCheck() if (navigation.contentCommitted()) { navigation.reconcile() return @@ -129,6 +139,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const disconnectReading = reading.connect((sample) => { navigation.readerSampled(sample) processContent() + navigation.requestHistoryCheck() }) return () => { disconnectViewport() @@ -141,7 +152,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { useLayoutEffect(() => { const previous = content.current.input content.current.input = { - ready, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, + order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, ...navigationInput, } if (!deferCompletedTurns) { @@ -149,13 +160,18 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { reading.interruptFollow() } viewport.updateTurns(loadedTurns) - const layoutChanged = previous.order !== order || previous.ready !== ready - if (layoutChanged) viewport.invalidate() + const layoutChanged = previous.order !== order || previous.isOpen !== isOpen + if (layoutChanged) { + const landing = viewport.finishHistoryPrepend() + if (landing !== null) reading.preservePosition(landing) + viewport.invalidate() + } viewport.reclaimBelow() processContent() if (layoutChanged && content.current.opened) reading.refreshActiveTurn() + if (content.current.opened) navigation.requestHistoryCheck() }, [ - viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser, + viewport, reading, processContent, navigationInput, isOpen, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, cancelPendingFollow, ]) @@ -182,6 +198,10 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { listRef, columnRef, ...state, busyTurn, motion: viewport.motion, navigateToTurn: navigation.navigateToTurn, loadEarlier: navigation.loadEarlier, + historyPending, + historyProcessing, + historyInputHeld, + historyEdgeRef: viewport.setHistoryEdge, returnToBottom, } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index b0dbf7528a..98c6ac2186 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -26,6 +26,8 @@ interface ViewportEvents { interact: () => void /** Any reading gesture, before paging ownership is consulted. */ intent?: () => void + /** Recheck a prepared history page after an input or transition settles. */ + history?: () => void } interface ViewportElements { @@ -65,7 +67,7 @@ interface ClosingLayout { interface PagingPosition { readonly row: HTMLElement readonly position: ChatScrollPosition - readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null + readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number; readonly scrollTop: number } | null } const READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const @@ -79,7 +81,13 @@ export class ChatViewport { private turns: ReturnType = [] private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null } private paging: PagingPosition | null = null + private historyPrepend: PagingPosition | null = null private reader: FoldReader | null = null + private historyEdge: HTMLElement | null = null + private historyHeight = 0 + private historyScrolling = new Set() + private historyPointer = false + private historyTouch = false /** Rows measured before an instant close; see {@link ChatViewport.keepAboveClosing}. */ private closing: ClosingLayout | null = null /** Discards a closing measurement that no size observation consumed by the end of its frame. */ @@ -114,18 +122,26 @@ export class ChatViewport { const elements = { list, column, scroller, composer, spacer } this.elements = elements if (spacer !== null) spacer.style.height = '' + scroller.addEventListener('scroll', this.onHistoryScroll, { passive: true, capture: true }) + scroller.addEventListener('pointerdown', this.onHistoryPointerDown, { passive: true, capture: true }) + scroller.addEventListener('touchstart', this.onHistoryTouch, { passive: true, capture: true }) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller.ownerDocument.addEventListener(type, this.onHistoryRelease, true) + } scroller.addEventListener('scroll', this.onScroll, { passive: true }) scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true }) for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true }) if (typeof ResizeObserver !== 'undefined') { - this.observer = new ResizeObserver(() => { + this.observer = new ResizeObserver((entries) => { if (this.elements !== elements) return // Read while layout is still clean, before this callback writes room or scroll positions. Those writes // leave the content height unchanged, so it is also the content this frame paints. + if (entries.some(entry => entry.target === elements.scroller)) this.historyHeight = elements.scroller.clientHeight this.settledContent = elements.scroller.scrollHeight - this.spacerHeight() this.keepAboveClosing() this.reclaimBelow() this.invalidate() + this.pruneHistoryScrolling() this.events?.resize() }) this.observer.observe(column) @@ -136,10 +152,22 @@ export class ChatViewport { /** Disconnect DOM resources and clear observations for the detached view. */ detach(): void { + this.historyPrepend = null this.stopPreserving() this.motion.clear() if (this.elements !== null) this.elements.scroller.style.overflowAnchor = '' this.dropClosing() + const scroller = this.elements?.scroller + scroller?.removeEventListener('scroll', this.onHistoryScroll, true) + scroller?.removeEventListener('pointerdown', this.onHistoryPointerDown, true) + scroller?.removeEventListener('touchstart', this.onHistoryTouch, true) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller?.ownerDocument.removeEventListener(type, this.onHistoryRelease, true) + } + this.historyHeight = 0 + this.historyScrolling.clear() + this.historyPointer = false + this.historyTouch = false this.elements?.scroller.removeEventListener('scroll', this.onScroll) this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true) for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true) @@ -772,10 +800,14 @@ export class ChatViewport { /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */ beginPaging(): void { this.stopPreserving() - const row = this.elements?.list.querySelector( + const row = this.pagingAnchor() + if (row !== null) this.retain(row) + } + + private pagingAnchor(): HTMLElement | null { + return this.elements?.list.querySelector( '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)', - ) - if (row != null) this.retain(row) + ) ?? null } /** @@ -790,18 +822,17 @@ export class ChatViewport { this.retain(row, position) } - private retain(row: HTMLElement, position?: ChatScrollPosition, groupTop?: number): PagingPosition | null { + private measurePaging(row: HTMLElement, position?: ChatScrollPosition, previousGroup?: PagingPosition['group']): PagingPosition | null { const elements = this.elements const key = row.dataset.chatAnchorKey if (elements === null || key === undefined) return null - const previous = this.paging?.group - if (previous != null) this.observer?.unobserve(previous.content) const top = row.getBoundingClientRect().top const body = row.closest('[data-step-process-body]') const content = body?.querySelector('[data-step-process-content]') const group = body === null || content == null ? null - : { body, content, top: groupTop ?? top - body.getBoundingClientRect().top } - this.paging = { + : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top, + scrollTop: previousGroup?.body === body ? previousGroup.scrollTop : body.scrollTop } + return { row, group, position: position ?? { anchorKey: key, @@ -809,8 +840,19 @@ export class ChatViewport { scrollTop: elements.scroller.scrollTop, }, } - if (group !== null) this.observer?.observe(group.content) - return this.paging + } + + private retain(row: HTMLElement, position?: ChatScrollPosition): PagingPosition | null { + const paging = this.measurePaging(row, position) + if (paging === null) return null + this.retainPaging(paging) + return paging + } + + private retainPaging(paging: PagingPosition): void { + this.stopPreserving() + this.paging = paging + if (paging.group !== null) this.observer?.observe(paging.group.content) } /** Release paging ownership and its content-size observation. */ @@ -832,28 +874,39 @@ export class ChatViewport { * @returns the actual landing, or null when no visible retained row remains. */ preserve(): ViewportLanding | null { - let paging = this.paging + const paging = this.resolvePaging(this.paging) + if (paging === null) { + this.stopPreserving() + return null + } + if (paging !== this.paging) this.retainPaging(paging) + return this.applyPaging(paging, false) + } + + private resolvePaging(paging: PagingPosition | null): PagingPosition | null { const elements = this.elements if (paging === null || elements === null) return null if (!elements.list.contains(paging.row)) { // Segmentation can remount the same semantic row under another group. const replacement = this.anchor(paging.position.anchorKey) - if (replacement === null) { - this.stopPreserving() - return null - } - paging = this.retain(replacement, paging.position, paging.group?.top) + if (replacement === null) return null + paging = this.measurePaging(replacement, paging.position, paging.group) if (paging === null) return null } + return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging + } + + /** Content correction includes reader movement since capture; screen preservation restores the captured position. */ + private applyPaging(paging: PagingPosition, preserveMovement: boolean): ViewportLanding | null { + const elements = this.elements + if (elements === null) return null const { row, group, position } = paging - if (row.closest('[hidden]') !== null || row.matches(':empty')) { - this.stopPreserving() - return null - } + let innerMovement = 0 if (group !== null && group.body.contains(row)) { const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top const metrics = scrollMetrics(group.body) - const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top)) + if (preserveMovement) innerMovement = metrics.top - group.scrollTop + const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top + innerMovement)) if (metrics.top !== target) { const follow = ScrollFollow.forElement(group.body) if (follow === undefined) group.body.scrollTop = target @@ -866,7 +919,8 @@ export class ChatViewport { const metrics = this.metrics() if (metrics === null) return null const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top - const target = metrics.top + top - position.anchorTop + const movement = preserveMovement ? metrics.top - position.scrollTop + innerMovement : 0 + const target = metrics.top + top - position.anchorTop + movement return this.write(target, metrics, null, { key: position.anchorKey, top }) } @@ -919,6 +973,111 @@ export class ChatViewport { return landing } + /** + * Track the history control for request-distance checks. + * @param element - stable history control, or null when its view unmounts. + */ + readonly setHistoryEdge = (element: HTMLDivElement | null): void => { + this.historyEdge = element + } + + private pruneHistoryScrolling(): void { + for (const target of this.historyScrolling) { + if (!(target instanceof HTMLElement) || this.elements?.scroller.contains(target) !== true) { + this.historyScrolling.delete(target) + } + } + } + + /** + * Confirm the actual history distance immediately before an automatic request. + * @returns whether the control is within two viewport heights. + */ + confirmHistoryStart(): boolean { + const scroller = this.elements?.scroller + if (scroller === undefined || this.historyEdge === null || this.historyHeight <= 0) return false + const distance = scroller.getBoundingClientRect().top - this.historyEdge.getBoundingClientRect().bottom + return distance <= this.historyHeight * 2 + } + + /** + * Expose held input to history status copy. + * @returns whether a touch or pointer remains down. + */ + get historyInputHeld(): boolean { return this.historyTouch || this.historyPointer } + + /** + * Expose reader activity that prevents stationary preservation. + * @returns whether input is held or scrolling has not ended. + */ + get historyReaderActive(): boolean { + this.pruneHistoryScrolling() + return this.historyTouch || this.historyPointer || this.historyScrolling.size > 0 + } + + /** + * Select consumption behavior from current input and motion state. + * @returns the blocker or positioning path for a prepared page. + */ + historyConsumption(): 'motion' | 'touch' | 'pointer' | 'inner-scroll' | 'unavailable' | 'native' | 'preserve' | 'prepend' { + const elements = this.elements + if (elements === null) return 'unavailable' + if (this.motion.active() || this.reader?.follow.animating) return 'motion' + if (this.historyTouch) return 'touch' + if (this.historyPointer) return 'pointer' + if (this.historyScrolling.size === 0) return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'preserve' + if (this.historyScrolling.size !== 1 || !this.historyScrolling.has(elements.scroller)) return 'inner-scroll' + if (this.preserving || typeof CSS === 'undefined' || !CSS.supports('overflow-anchor', 'auto')) return 'unavailable' + return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'native' + } + + /** + * Capture one top-edge prepend anchor without acquiring continuous scroll ownership. + * @returns whether an old paging row was captured. + */ + beginHistoryPrepend(): boolean { + const row = this.pagingAnchor() + this.historyPrepend = row === null ? null : this.measurePaging(row) + return this.historyPrepend !== null + } + + /** Clear an unapplied one-shot correction when its page was not consumed. */ + cancelHistoryPrepend(): void { this.historyPrepend = null } + + /** + * Correct a committed prepend once, then release positioning ownership. + * @returns the compensated landing for reading memory, or null when no anchor remains. + */ + finishHistoryPrepend(): ViewportLanding | null { + const pending = this.historyPrepend + this.historyPrepend = null + const paging = this.resolvePaging(pending) + return paging === null ? null : this.applyPaging(paging, true) + } + + private readonly onHistoryScroll = (event: Event): void => { + if (event.target === this.elements?.scroller || event.target instanceof HTMLElement + && event.target.hasAttribute('data-step-process-body')) { + this.historyScrolling.add(event.target) + } + } + + private readonly onHistoryPointerDown = (): void => { + this.historyPointer = true + this.events?.history?.() + } + private readonly onHistoryTouch = (): void => { + this.historyTouch = true + this.events?.history?.() + } + private readonly onHistoryRelease = (event: Event): void => { + if (event.type === 'pointerup' || event.type === 'pointercancel') this.historyPointer = false + if (event.type === 'touchend' || event.type === 'touchcancel') { + this.historyTouch = typeof TouchEvent !== 'undefined' && event instanceof TouchEvent && event.touches.length > 0 + } + this.events?.history?.() + } + private readonly onScroll = (event: Event): void => { if (this.elements === null || event.target !== this.elements.scroller) return if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return @@ -932,6 +1091,8 @@ export class ChatViewport { } private readonly onScrollEnd = (event: Event): void => { + if (event.target !== null) this.historyScrolling.delete(event.target) + this.events?.history?.() if (event.target === this.elements?.scroller) { this.events?.scrollEnd(true) this.reclaimBelow() diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index ed89452f50..676bb3fb2d 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -347,7 +347,10 @@ export interface ChatViewInjected { /** Open one HTTP(S) message link at the selected destination, using an external tab if Sidebar Browser is unavailable. */ openExternalLink: (url: string) => void openFile: (path: string, options?: OpenFileOptions) => Promise + /** Prepare one older page without publishing it. */ loadOlder: () => void + /** Consume the prepared page synchronously; false when none is ready. */ + consumeOlder: () => boolean /** Jump loader: page history back through seq; resolves when the window covers it. */ loadThrough: (seq: SessionSeq) => Promise loadImage: MessageImageLoader diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 0b2bc2151d..4d22cff80e 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -92,6 +92,10 @@ export const zh = { 'chat.loadingHistory': '载入历史…', 'chat.loadError': '历史加载失败:{message}({code})', 'chat.loadOlder': '加载更早', + 'chat.loadingOlder': '正在加载', + 'chat.processingOlder': '正在处理', + 'chat.retryOlder': '重新加载', + 'chat.historyStart': '已到会话开头', 'chat.toBottom': '回到底部', 'chat.deepDiving': '深度求索中', 'chat.deepDivingFor': '深度求索中,用时 {duration} ···', @@ -302,6 +306,10 @@ export const en = { 'chat.loadingHistory': 'Loading history…', 'chat.loadError': 'Failed to load history: {message} ({code})', 'chat.loadOlder': 'Load earlier', + 'chat.loadingOlder': 'Loading earlier', + 'chat.processingOlder': 'Processing', + 'chat.retryOlder': 'Retry loading', + 'chat.historyStart': 'Start of conversation', 'chat.toBottom': 'Back to bottom', 'chat.deepDiving': 'Deep diving', 'chat.deepDivingFor': 'Deep diving for {duration} ···', @@ -509,6 +517,10 @@ export const ja = { 'chat.loadingHistory': '履歴を読み込み中…', 'chat.loadError': '履歴の読み込みに失敗しました: {message}({code})', 'chat.loadOlder': '以前を読み込む', + 'chat.loadingOlder': '読み込み中', + 'chat.processingOlder': '処理中', + 'chat.retryOlder': '再読み込み', + 'chat.historyStart': '会話の先頭です', 'chat.toBottom': '最下部へ戻る', 'chat.deepDiving': '深掘り中', 'chat.deepDivingFor': '{duration} の間深く分析中 ···', @@ -716,6 +728,10 @@ export const es = { 'chat.loadingHistory': 'Cargando historial…', 'chat.loadError': 'No se pudo cargar el historial: {message} ({code})', 'chat.loadOlder': 'Cargar antes', + 'chat.loadingOlder': 'Cargando anteriores', + 'chat.processingOlder': 'Procesando', + 'chat.retryOlder': 'Reintentar carga', + 'chat.historyStart': 'Inicio de la conversación', 'chat.toBottom': 'Volver al fondo', 'chat.deepDiving': 'Razonamiento profundo', 'chat.deepDivingFor': 'Razonando a fondo durante {duration} ···', @@ -923,6 +939,10 @@ export const fr = { 'chat.loadingHistory': "Chargement de l'historique…", 'chat.loadError': "Échec du chargement de l'historique : {message} ({code})", 'chat.loadOlder': 'Charger plus tôt', + 'chat.loadingOlder': 'Chargement en cours', + 'chat.processingOlder': 'Traitement en cours', + 'chat.retryOlder': 'Réessayer', + 'chat.historyStart': 'Début de la conversation', 'chat.toBottom': 'Retour en bas', 'chat.deepDiving': 'Réflexion approfondie', 'chat.deepDivingFor': 'Réflexion approfondie depuis {duration} ···', @@ -1130,6 +1150,10 @@ export const de = { 'chat.loadingHistory': 'Verlauf wird geladen…', 'chat.loadError': 'Fehler beim Laden des Verlaufs: {message} ({code})', 'chat.loadOlder': 'Früher laden', + 'chat.loadingOlder': 'Wird geladen', + 'chat.processingOlder': 'Wird verarbeitet', + 'chat.retryOlder': 'Erneut laden', + 'chat.historyStart': 'Anfang der Unterhaltung', 'chat.toBottom': 'Zurück nach unten', 'chat.deepDiving': 'Gründliches Nachdenken', 'chat.deepDivingFor': 'Gründliches Nachdenken seit {duration} ···', @@ -1337,6 +1361,10 @@ export const ru = { 'chat.loadingHistory': 'Загрузка истории…', 'chat.loadError': 'Не удалось загрузить историю: {message} ({code})', 'chat.loadOlder': 'Загрузить раньше', + 'chat.loadingOlder': 'Загрузка истории', + 'chat.processingOlder': 'Обработка', + 'chat.retryOlder': 'Повторить загрузку', + 'chat.historyStart': 'Начало разговора', 'chat.toBottom': 'Вернуться к низу', 'chat.deepDiving': 'Глубокое размышление', 'chat.deepDivingFor': 'Глубокое размышление в течение {duration} ···', @@ -1544,6 +1572,10 @@ export const pt = { 'chat.loadingHistory': 'Carregando histórico…', 'chat.loadError': 'Falha ao carregar o histórico: {message} ({code})', 'chat.loadOlder': 'Carregar mais cedo', + 'chat.loadingOlder': 'Carregando anteriores', + 'chat.processingOlder': 'Processando', + 'chat.retryOlder': 'Tentar novamente', + 'chat.historyStart': 'Início da conversa', 'chat.toBottom': 'De volta ao fundo', 'chat.deepDiving': 'Raciocínio profundo', 'chat.deepDivingFor': 'Raciocínio profundo há {duration} ···', diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 8ee48b8f65..352e5d5042 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -253,7 +253,7 @@ describe('Chat inject API', () => { const b = await bench() const { injected } = b.chatViewApi(b.rootReference) injected.loadOlder() - expect(b.session.loadOlder).toHaveBeenCalledOnce() + expect(b.session.loadOlder).toHaveBeenCalledExactlyOnceWith({ deferConsumption: true }) void injected.loadThrough(SessionSeq(42)) expect(b.session.loadThrough).toHaveBeenCalledWith(42) diff --git a/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts new file mode 100644 index 0000000000..1ce525374b --- /dev/null +++ b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts @@ -0,0 +1,117 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SessionSeq } from '@deepseek-ai/dsh-session/types' +import { ChatNavigation, type ChatNavigationInput } from '../src/client/chat/use-chat-navigation.ts' +import { ChatReading } from '../src/client/chat/use-chat-reading.ts' +import { ChatViewport } from '../src/client/chat/use-chat-viewport.ts' +import { ScrollFollow } from '../src/client/chat/use-scroll-follow.ts' + +function fixture() { + const viewport = new ChatViewport() + vi.spyOn(viewport, 'confirmHistoryStart').mockReturnValue(true) + const mode = vi.spyOn(viewport, 'historyConsumption').mockReturnValue('native') + const reading = new ChatReading(viewport, { read: () => null, save: () => {} }, { + initialized: true, followingTail: false, activeTurn: 1, + }, () => {}, new ScrollFollow(false, 24)) + const loadOlder = vi.fn() + const consumeOlder = vi.fn(() => true) + const onIntent = vi.fn() + let input: ChatNavigationInput = { + isOpen: true, firstSeq: SessionSeq(20), hasMore: true, loadingOlder: false, + historyLoadStatus: 'idle', loadOlder, consumeOlder, loadThrough: async () => {}, + } + const navigation = new ChatNavigation(viewport, reading, input, () => {}, onIntent) + const check = () => { + navigation.requestHistoryCheck() + vi.advanceTimersByTime(20) + } + const ready = () => { + input = { ...input, historyLoadStatus: 'pendingConsumption' } + navigation.setInput(input) + } + return { viewport, navigation, reading, mode, loadOlder, consumeOlder, onIntent, check, ready } +} + +beforeEach(() => { vi.useFakeTimers() }) +afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() }) + +describe('history consumption intent', () => { + it.each(['motion', 'pointer', 'unavailable'] as const)('leaves an automatic page for a click after %s', (blocker) => { + const h = fixture() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.mode.mockReturnValue('native') + h.ready() + h.check() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it.each(['touch', 'inner-scroll'] as const)('continues automatic consumption after %s ends', (blocker) => { + const h = fixture() + h.check() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('auto') + expect(h.consumeOlder).not.toHaveBeenCalled() + h.mode.mockReturnValue('native') + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it('retains an explicit click until the fold ends without requesting the cached page again', () => { + const h = fixture() + h.ready() + h.mode.mockReturnValue('motion') + vi.spyOn(h.viewport.motion, 'foldActive').mockReturnValue(true) + let idle: (() => void) | undefined + const stop = vi.fn() + vi.spyOn(h.viewport.motion, 'onFoldIdle').mockImplementation((callback) => { idle = callback; return stop }) + h.navigation.loadEarlier() + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('manual') + expect(h.loadOlder).not.toHaveBeenCalled() + expect(h.consumeOlder).not.toHaveBeenCalled() + h.mode.mockReturnValue('native') + idle?.() + vi.advanceTimersByTime(20) + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it('joins a pending automatic request when clicked and consumes once after it returns', () => { + const h = fixture() + h.check() + h.navigation.loadEarlier() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.navigation.dispose() + }) + + it('does not consume a cached page on a fresh view until clicked', () => { + const h = fixture() + h.ready() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) +}) diff --git a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx index f0555f7fff..885b16e72c 100644 --- a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx @@ -36,7 +36,7 @@ function ScrollHarness({ input, onMotion }: { function mountScroll(deferCompletedTurns = true, initial: Partial = {}) { let input: ChatScrollInput = { - ready: true, + isOpen: true, order: [], firstSeq: null, lastKey: null, @@ -49,7 +49,7 @@ function mountScroll(deferCompletedTurns = true, initial: Partial false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, @@ -116,9 +116,9 @@ function mountRows(heights: readonly number[]) { } vi.stubGlobal('ResizeObserver', Observer) const input: ChatScrollInput = { - ready: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: false, - transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } const view = render( { callbacks.motion = motion }} @@ -287,9 +287,9 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea let motion: FlowMotionRows | undefined const onMotion = (value: FlowMotionRows): void => { motion = value } let input: ChatScrollInput = { - ready: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: true, - transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) @@ -328,7 +328,7 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea offsetHeight: { get: contentHeight }, getBoundingClientRect: { value: () => ({ top: -top, bottom: contentHeight() - top, height: contentHeight() }) }, }) - input = { ...input, ready: true } + input = { ...input, isOpen: true } view.rerender() top = test.top scrollTo.mockClear() @@ -495,7 +495,7 @@ it('keeps one active fold when the local echo becomes its durable input', async describe('Chat scroll collapse timing', () => { it.each(['resize', 'scroll', 'history', 'input', 'preference'] as const)( 'waits for initial history before initializing a running view after %s', (change) => { - const h = mountScroll(true, { ready: false, running: true }) + const h = mountScroll(true, { isOpen: false, running: true }) expect(h.scroller.dataset.initialized).toBe('false') if (change === 'resize') h.resize() else if (change === 'scroll') fireEvent.scroll(h.scroller) @@ -506,7 +506,7 @@ describe('Chat scroll collapse timing', () => { expect(h.scroller.scrollTop).toBe(0) expect(h.scrollTo).not.toHaveBeenCalled() - h.update({ ready: true }) + h.update({ isOpen: true }) expect(h.scroller.dataset.initialized).toBe('true') expect(h.scroller.scrollTop).toBe(600) expect(h.scrollTo).not.toHaveBeenCalled() diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 37011ab8bb..0d66887de6 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -107,6 +107,8 @@ function sessionSnapshot(overrides: Partial = {}): TestSess openError: null, hasMore: false, loadingOlder: false, + historyLoadStatus: 'idle', + historyWasPartial: overrides.hasMore ?? false, promptError: null, blank: false, subagent: null, @@ -421,7 +423,22 @@ function makeHarness( const openFile = vi.fn<(path: string) => Promise>().mockResolvedValue(undefined) const openUserFile = vi.fn<(path: string) => void>() const renderUserContent = createUserContentFixture({ openFile: openUserFile }) - const loadOlder = vi.fn() + let preparedOlder: (() => void) | null = null + const loadOlder = vi.fn(() => { + session.set({ loadingOlder: true, historyLoadStatus: 'loading' }) + }) + const consumeOlder = vi.fn(() => { + if (preparedOlder === null) return false + const consume = preparedOlder + preparedOlder = null + consume() + session.set({ loadingOlder: false, historyLoadStatus: 'idle' }) + return true + }) + const prepareOlder = (consume: () => void) => { + preparedOlder = consume + session.set({ loadingOlder: false, historyLoadStatus: 'pendingConsumption' }) + } const loadThrough = vi.fn<(seq: number) => Promise>().mockResolvedValue(undefined) // Mutable outline holder: tests swap the value and drive a re-render via set(). let outlineValue: unknown @@ -555,6 +572,7 @@ function makeHarness( openFile, openExternalLink: vi.fn(), loadOlder, + consumeOlder, loadThrough, loadImage: vi.fn(() => Promise.reject(new Error('not used'))), chatScroll, @@ -584,7 +602,7 @@ function makeHarness( return { set, setSession: session.set, setChat: chatSource.set, ChatView, props, setConnection: (state: ConnectionState) => { connection.set(state) }, - openFile, openUserFile, loadOlder, loadThrough, openView, + openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, fenceCalls, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, @@ -643,6 +661,11 @@ function readerScroll(element: HTMLElement, top: number): void { fireEvent(element, new Event('scrollend')) } +/** Let the public history scheduler run one frame, including React's commit of its updates. */ +async function historyFrame(): Promise { + await act(async () => { await new Promise(resolve => requestAnimationFrame(() => { resolve() })) }) +} + function turnProcessControl(container: HTMLElement): HTMLButtonElement | null { return container.querySelector('[data-turn-process]') } @@ -1537,6 +1560,19 @@ describe('ChatView', () => { await act(async () => { releaseJump?.() }) }) + it('keeps the history start marker across remounts from the Session fact', () => { + const h = makeHarness({ nodes: [user(1, 'prompt'), assistant(2, 'answer')] }, { + hasMore: false, historyWasPartial: true, + }) + const first = render() + expect(first.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + first.unmount() + const second = render() + expect(second.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + act(() => { h.setSession({ historyWasPartial: false }) }) + expect(second.queryByRole('button', { name: '已到会话开头' })).toBeNull() + }) + it('holds a jump issued while a plain pull owns the pager and resumes it when the pull settles', async () => { const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)] const h = makeHarness({ nodes: later }, { hasMore: true, loadingOlder: true }) @@ -1642,7 +1678,7 @@ describe('ChatView', () => { expect(h.toolOwners[0]).toMatchObject({ callId: 'w1', toolName: '' }) }) - it('prepend keeps the reader\'s latest pending-request scroll position anchored', () => { + it('prepend keeps the reader\'s latest pending-request scroll position anchored', async () => { const h = makeHarness( { nodes: [user(9, 'first visible'), user(10, 'next visible')] }, { hasMore: true }, @@ -1666,17 +1702,19 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) - act(() => { h.set({ loadingOlder: true }) }) + await historyFrame() // The reader moves after the request starts; this, not the click-time // row, is the intent the arriving page must preserve. firstTop = -200 nextTop = 60 readerScroll(scroller, 90) - Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) - nextTop = 560 - act(() => { - h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')], loadingOlder: false }) - }) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) + nextTop = 560 + h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(590) // latest 90 + the anchored row's 500px prepend shift }) @@ -1685,7 +1723,7 @@ describe('ChatView', () => { { mode: 'detailed', anchor: 'group' }, { mode: 'compact', anchor: 'node' }, { mode: 'standard', anchor: 'node' }, { mode: 'detailed', anchor: 'node' }, ] as const)( - 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', ({ mode, anchor }) => { + 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', async ({ mode, anchor }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [tool(4, 'retained'), assistant(6, 'answer', 1, 2)], turnEnds: new Map([[1, 7]]) } let source = chatSnapshotFixture(initial) @@ -1726,14 +1764,17 @@ describe('ChatView', () => { expect(pinned.hasAttribute('data-chat-paging-anchor')).toBe(true) expect(controlSeat.hasAttribute('data-chat-paging-anchor')).toBe(false) expect(group.hasAttribute('data-chat-paging-anchor')).toBe(anchor !== 'node') - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { paged = true source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier'), steering(2, 'historical direction', 1), tool(3, 'before-retained'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(pinned.getBoundingClientRect().top).toBe(expectedTop) expect(scroller.scrollTop).toBe(expectedScroll) @@ -1757,7 +1798,7 @@ describe('ChatView', () => { { mode: 'compact', hasProcess: false, hasSteering: true }, { mode: 'standard', hasProcess: false, hasSteering: true }, { mode: 'detailed', hasProcess: false, hasSteering: true }, - ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', ({ mode, hasProcess, hasSteering }) => { + ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', async ({ mode, hasProcess, hasSteering }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [ @@ -1801,13 +1842,16 @@ describe('ChatView', () => { expect(control.hasAttribute('data-chat-paging-anchor')).toBe(false) fireEvent.click(view.getByText('加载更早')) - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier-work'), steering(2, 'earlier direction', 1), tool(3, 'following-work'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() const steer = view.container.querySelector('[data-chat-node-key="fixture:steering:2"]')! const rows = visibleRows() @@ -1854,7 +1898,7 @@ describe('ChatView', () => { } }) - it('anchors the first transcript row for paging regardless of the viewport reading line', () => { + it('anchors the first transcript row for a prepared page consumed at the top without reading hit tests', async () => { const originalHitTest = Object.getOwnPropertyDescriptor(document, 'elementsFromPoint') const nodes = Array.from({ length: 16 }, (_, index) => user(20 + index, `row ${String(index)}`)) const h = makeHarness( @@ -1873,13 +1917,13 @@ describe('ChatView', () => { vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => { rowRectCalls += 1 const shift = prepended ? (index === 8 ? 400 : 500) : 0 - const top = 20 + (index - 8) * 60 + shift + const top = 20 + index * 60 + shift - scroller.scrollTop return { top, bottom: top + 40 } as DOMRect }) }) Object.defineProperty(scroller, 'scrollHeight', { value: 800, writable: true }) Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) - readerScroll(scroller, 50) + readerScroll(scroller, 0) const hitTest = vi.fn((_x: number, _y: number): Element[] => []) Object.defineProperty(document, 'elementsFromPoint', { @@ -1890,14 +1934,19 @@ describe('ChatView', () => { rowRectCalls = 0 fireEvent.click(view.getByText('加载更早')) expect(hitTest).not.toHaveBeenCalled() - expect(rowRectCalls).toBe(1) - - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - prepended = true - act(() => { + expect(rowRectCalls).toBe(0) + await historyFrame() + act(() => { h.prepareOlder(() => { + expect(hitTest).not.toHaveBeenCalled() + expect(rowRectCalls).toBe(1) + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + prepended = true h.setChat({ nodes: [assistant(2, 'older'), ...nodes] }) - }) - expect(scroller.scrollTop).toBe(550) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(scroller.scrollTop).toBe(500) + expect(rows[0]!.getBoundingClientRect().top).toBe(20) expect(h.chatScroll.read()?.anchorKey).toBe('fixture:user:20') } finally { if (originalHitTest !== undefined) { @@ -4060,7 +4109,7 @@ describe('ChatView', () => { expect(screen.queryByRole('dialog')).toBeNull() }) - it('prepend preserves a semantic row; a trailing user node force-scrolls', () => { + it('prepend preserves a semantic row; a trailing user node force-scrolls', async () => { const h = makeHarness( { nodes: [user(5, 'later'), assistant(6, 'a')] }, { hasMore: true }, @@ -4076,13 +4125,15 @@ describe('ChatView', () => { () => ({ top: anchoredTop, bottom: anchoredTop + 40 } as DOMRect), ) readerScroll(scroller, 80) - // Arm the paging anchor, then deliver an older page (head seq decreases). fireEvent.click(view.getByText('加载更早')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) - anchoredTop = 700 - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) + anchoredTop = 700 h.setChat({ nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a')] }) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(680) // reader offset 80 + the anchored row's 600px shift // A new trailing user bubble (own words) force-scrolls to the bottom. act(() => { @@ -4093,7 +4144,45 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(1200) }) - it('back-to-bottom cancels an in-flight paging anchor', () => { + it('restores a one-shot prepend landing after immediate remount before scroll delivery', async () => { + const host = document.createElement('div') + host.dataset.conversationScroll = '' + document.body.append(host) + let paged = false + Object.defineProperties(host, { + clientHeight: { value: 200 }, + scrollHeight: { get: () => paged ? 1200 : 200 }, + }) + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this === host) return new DOMRect(0, 0, 500, 200) + const offset = this.dataset.chatAnchorKey === 'fixture:user:5' ? 20 + (paged ? 200 : 0) : 0 + return new DOMRect(0, offset - host.scrollTop, 500, 40) + }) + try { + const h = makeHarness({ nodes: [user(5, 'retained prompt'), assistant(6, 'answer')] }, { hasMore: true }) + const view = render(, { container: host }) + expect(host.scrollTop).toBe(0) + expect(h.chatScroll.read()).toBeNull() + fireEvent.click(view.getByRole('button', { name: '加载更早' })) + await historyFrame() + act(() => { h.prepareOlder(() => { + paged = true + h.setChat({ nodes: [user(1, 'earlier'), assistant(2, 'old answer'), user(5, 'retained prompt'), assistant(6, 'answer')] }) + }) }) + await historyFrame() + expect(host.scrollTop).toBe(200) + // A navigation can remove the view before the browser delivers the scroll caused by compensation. + view.rerender(
) + host.scrollTop = 0 + view.rerender() + expect(host.scrollTop).toBe(200) + expect(h.chatScroll.read()).toMatchObject({ anchorKey: 'fixture:user:5', anchorTop: 20, scrollTop: 200 }) + } finally { + host.remove() + } + }) + + it('back-to-bottom cancels pending history consumption without reviving it when the page arrives', async () => { const h = makeHarness({ nodes: [user(9, 'late')] }, { hasMore: true }) const view = render() const scroller = view.container.querySelector('[data-chat-flow]')!.parentElement as HTMLDivElement @@ -4101,10 +4190,16 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) + await historyFrame() fireEvent.click(view.getByLabelText('回到底部')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - act(() => { h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) }) - expect(scroller.scrollTop).toBe(1_100) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(scroller.scrollTop).toBe(600) + expect(view.queryByText('older')).toBeNull() expect(h.chatScroll.read()).toBeNull() }) @@ -4598,13 +4693,15 @@ describe('ChatView', () => { } }) - it('paging button loads older and shows its busy label', () => { + it('paging button schedules an older request and shows its loading label', async () => { const h = makeHarness({ nodes: [user(5, 'later')] }, { hasMore: true }) const view = render() fireEvent.click(view.getByText('加载更早')) + expect(h.loadOlder).not.toHaveBeenCalled() + expect(view.getByRole('button', { name: '正在处理' }).hasAttribute('disabled')).toBe(true) + await historyFrame() expect(h.loadOlder).toHaveBeenCalledTimes(1) - act(() => { h.setSession({ loadingOlder: true }) }) - expect(view.getByText('加载中…')).toBeTruthy() + expect(view.getByRole('button', { name: '正在加载' }).hasAttribute('disabled')).toBe(true) }) it('shows open error and loading states', () => { diff --git a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts index def772efb8..6149f9a89d 100644 --- a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts @@ -48,6 +48,100 @@ function fixture() { return { column, viewport, group, row, prepend: (height: number) => { prependedHeight += height } } } +it('updates history distance only from scrollport size observations before layout writes', () => { + let resize: ResizeObserverCallback | undefined + class Observer implements ResizeObserver { + constructor(callback: ResizeObserverCallback) { resize = callback } + observe(): void {} + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', Observer) + onTestFinished(() => { vi.unstubAllGlobals() }) + const h = fixture() + const edge = document.createElement('div') + h.column.prepend(edge) + const height = vi.fn(() => 300) + Object.defineProperty(h.column, 'clientHeight', { configurable: true, get: height }) + h.viewport.setHistoryEdge(edge) + expect(height).not.toHaveBeenCalled() + let afterWrite = false + vi.spyOn(h.viewport, 'reclaimBelow').mockImplementation(() => { afterWrite = true }) + height.mockImplementation(() => { + if (afterWrite) throw new Error('height read after a layout writer') + return 300 + }) + const entry: ResizeObserverEntry = { target: h.column, contentRect: new DOMRect(), + borderBoxSize: [], contentBoxSize: [], devicePixelContentBoxSize: [] } + const notify = resize + const observer = new Observer(() => {}) + notify?.([entry], observer) + height.mockClear() + notify?.([], observer) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -600, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(true) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -700, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(false) + expect(height).not.toHaveBeenCalled() +}) + +it('uses the first paging anchor for one-shot history prepending without reading-position lookup', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + const scrollerRect = vi.spyOn(h.column, 'getBoundingClientRect') + const capture = vi.spyOn(h.viewport, 'capturePosition') + const query = vi.spyOn(h.column, 'querySelector') + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(capture).not.toHaveBeenCalled() + expect(query).toHaveBeenCalledTimes(1) + expect(scrollerRect).toHaveBeenCalledTimes(1) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(row.getBoundingClientRect().top).toBe(0) + h.prepend(30) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) +}) + +it('uses a collapsed group paging anchor when no ordinary content row is visible', () => { + const h = fixture() + const group = h.row(h.column, 'group', 0) + group.dataset.chatGroupKey = 'group' + const body = document.createElement('div') + body.hidden = true + group.append(body) + h.row(body, 'hidden-member', 20) + expect(h.viewport.capturePosition()).toBeNull() + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(group.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('keeps reader movement during a one-shot prepend without retaining paging ownership', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(145) + expect(row.getBoundingClientRect().top).toBe(-25) + expect(h.viewport.preserving).toBe(false) +}) + +it('does not prepare a correction when no paging anchor exists', () => { + const h = fixture() + expect(h.viewport.beginHistoryPrepend()).toBe(false) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(0) +}) + it.each([ { count: 64, slot: false }, { count: 4096, slot: false }, { count: 64, slot: true }, { count: 4096, slot: true }, @@ -440,6 +534,42 @@ it.each([ expect(h.row.getBoundingClientRect().top).toBe(top) }) +it('applies one-shot inner compensation without subscribing or undoing reader movement', () => { + const h = nestedFixture(600, 400) + h.scroller.scrollTop = 80 + h.body.scrollTop = 40 + const screenTop = h.row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + expect(h.observed.has(h.content)).toBe(false) + h.body.scrollTop = 60 + h.scroller.scrollTop = 90 + h.prepend(200) + h.viewport.finishHistoryPrepend() + expect(h.body.scrollTop).toBe(260) + expect(h.scroller.scrollTop).toBe(90) + expect(h.row.getBoundingClientRect().top).toBe(screenTop - 30) + expect(h.observed.has(h.content)).toBe(false) + h.prepend(20) + h.resize() + expect(h.body.scrollTop).toBe(260) + expect(h.scroller.scrollTop).toBe(90) +}) + +it('resolves a remounted one-shot anchor without entering retained paging', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + row.remove() + const replacement = h.row(h.column, 'old', 0) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(145) + expect(replacement.getBoundingClientRect().top).toBe(-25) + expect(h.viewport.preserving).toBe(false) +}) + it('gives paging compensation priority over an active inner follow animation', () => { const h = nestedFixture(600, 400) const follow = new ScrollFollow(true, 1) diff --git a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts index 9a53949566..9685b65f12 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -39,7 +39,7 @@ function sessionSnapshot(): SessionSnapshot { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: true, lastAgentError: null, @@ -62,6 +62,7 @@ function fakeSession(): SessionFace { cancel: () => Promise.reject(new Error('unused fake Session operation')), rename: () => Promise.reject(new Error('unused fake Session operation')), loadOlder: () => Promise.reject(new Error('unused fake Session operation')), + consumeOlder: () => { throw new Error('unused fake Session operation') }, loadThrough: () => Promise.reject(new Error('unused fake Session operation')), command: () => Promise.reject(new Error('unused fake Session operation')), } diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 8a116a9a15..713c74df88 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -56,7 +56,7 @@ interface TestSnapshot extends SessionSnapshot { function snapshotWith(queue: UserMessage[], nextStep: UserMessage[] = []): TestSnapshot { return { sessionId: SID, running: true, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, + hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, subagent: null, pendingSubmissions: [], lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false, testInbox: { 'next-turn': queue, 'next-step': nextStep }, diff --git a/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx b/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx index b6885853b4..8d670df9da 100644 --- a/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx +++ b/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx @@ -117,7 +117,7 @@ function sessionSnapshot(openState: SessionSnapshot['openState']): SessionSnapsh openState, openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-session/tests/ui-session.client.spec.ts b/packages/client/ui-session/tests/ui-session.client.spec.ts index c12901a0d8..6afbe4be49 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -96,7 +96,7 @@ function createSessionsBench(ctx: Context): SessionsBench { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index c6dfd004d4..e0ee44c80a 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -126,7 +126,7 @@ function sessionSnapshot(nodes: LegacyConversationSlice['nodes']): SessionSnapsh openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: nodes.length === 0, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx index 41e0e6902f..31b9296885 100644 --- a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx @@ -43,7 +43,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx index b3fdffda6b..3e924b4576 100644 --- a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx @@ -49,7 +49,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 1d444f3c2f..4884a2c208 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -677,7 +677,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ISession', - declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(): Promise;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', + declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(options?: {\n deferConsumption?: boolean;\n }): Promise;\n consumeOlder(): boolean;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', }, { name: 'ISessions', @@ -969,7 +969,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionSnapshot', - declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly loadingOlder: boolean;\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', + declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly historyWasPartial: boolean;\n readonly loadingOlder: boolean;\n readonly historyLoadStatus: \'idle\' | \'loading\' | \'pendingConsumption\' | \'error\';\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', }, { name: 'SessionStandardProps', diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 41f4010684..a882ea0ca9 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -278,7 +278,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:495', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:498', }, { key: 'conversation.chat.commandview', @@ -332,7 +332,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:477', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:480', }, { key: 'conversation.chat.flow', @@ -379,7 +379,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:436', }, { key: 'conversation.chat.markdown.fence', @@ -445,7 +445,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'wraps-owner-content', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.markdown.fence\', () => ctx.slots.register(\n { name: \'conversation.chat.markdown.fence\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:430', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', }, { key: 'conversation.chat.message.images', @@ -492,7 +492,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:469', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:472', }, { key: 'conversation.chat.node', @@ -564,7 +564,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:445', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:448', }, { key: 'conversation.chat.reasoning.body', @@ -608,7 +608,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:483', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:486', }, { key: 'conversation.chat.text-interaction', @@ -660,7 +660,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.text-interaction\', () => ctx.slots.register(\n { name: \'conversation.chat.text-interaction\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:428', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:431', }, { key: 'conversation.chat.turnTail', @@ -727,7 +727,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:489', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:492', }, { key: 'conversation.chat.user.before', @@ -777,7 +777,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.before\', () => ctx.slots.register(\n { name: \'conversation.chat.user.before\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:459', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:462', }, { key: 'conversation.chat.user.images', @@ -824,7 +824,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:471', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:474', }, { key: 'conversation.composer', @@ -4116,7 +4116,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:503', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:506', }, { key: 'sidebar', diff --git a/packages/session/message-quotes/tests/quote-selection.client.spec.tsx b/packages/session/message-quotes/tests/quote-selection.client.spec.tsx index 656f8909e3..d848a09db7 100644 --- a/packages/session/message-quotes/tests/quote-selection.client.spec.tsx +++ b/packages/session/message-quotes/tests/quote-selection.client.spec.tsx @@ -14,7 +14,7 @@ function props(enabled = true, subagent: SessionSnapshot['subagent'] = null) { const value = { trigger: 'selection', dismiss: vi.fn(), readText: vi.fn((): string | null => 'Hello world'), clearSelection: vi.fn(), - inputActions, useSession: selector => selector({ sessionId: SessionId('quote-selection'), pendingSubmissions: [], running: false, removed: !enabled, openState: 'open', openError: null, hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent, lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false }), + inputActions, useSession: selector => selector({ sessionId: SessionId('quote-selection'), pendingSubmissions: [], running: false, removed: !enabled, openState: 'open', openError: null, hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, subagent, lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false }), t: () => 'Quote text', } as Props return { value, inputActions } diff --git a/packages/test-support/client-runtime/src/fixtures.ts b/packages/test-support/client-runtime/src/fixtures.ts index 21f4abef40..c103792d55 100644 --- a/packages/test-support/client-runtime/src/fixtures.ts +++ b/packages/test-support/client-runtime/src/fixtures.ts @@ -74,7 +74,7 @@ export function sessionSnapshot(sessionId: SessionId): SessionSnapshot { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index a9fadfe91b..0d5d70d0e2 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -162,6 +162,14 @@ export class FixtureSession implements SessionFace { throw new Error(`test session "${this.sessionId}": loadOlder is not stubbed — supply it on the fixture's session face`) } + /** + * Fail-loud stub; supply `consumeOlder` on the fixture's session face to exercise it. + * @returns never — always throws. + */ + consumeOlder(): never { + throw new Error(`test session "${this.sessionId}": consumeOlder is not stubbed — supply it on the fixture's session face`) + } + /** * Fail-loud stub; supply `loadThrough` on the fixture's session face to exercise it. * @returns never — always throws.