From 4f9ee56b8a062a321be51979a3c1395c8c4ba57c Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:12:52 +0800 Subject: [PATCH 1/9] feat(client): retain recent sessions and skip conversation folding while unrendered --- ...-09-15-client-session-references.i18n.yaml | 4 +- .../2026-09-15-client-session-references.md | 4 +- ...2026-09-15-client-session-references.zh.md | 4 +- ...n-retain-facets-and-recent-views.i18n.yaml | 34 ++ ...-session-retain-facets-and-recent-views.md | 120 +++++++ ...ssion-retain-facets-and-recent-views.zh.md | 120 +++++++ .../conversation-and-session.md | 2 +- .../conversation-and-session.zh.md | 2 +- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 4 +- packages/api/session-controller/README.zh.md | 4 +- .../src/client/contract/sessions.ts | 9 +- .../session-controller/src/client/index.ts | 9 + .../src/client/sessions/facets.ts | 85 +++++ .../src/client/sessions/service.ts | 38 ++- .../tests/reference-ownership.client.spec.ts | 49 +++ packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- packages/client/ui-chat/src/client/apply.ts | 35 +- .../tests/apply-inject.client.spec.tsx | 3 + .../ui-chat/tests/fence-slot.client.spec.tsx | 2 +- .../tests/quota-notice.client.spec.tsx | 29 ++ .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 4 +- packages/client/ui-conversation/README.zh.md | 4 +- .../src/client/conversation/assembler.ts | 9 +- .../src/client/conversation/assembly.ts | 105 +++++- .../tests/apply-inject.client.spec.tsx | 4 +- .../tests/assembly-surfaces.client.spec.tsx | 2 +- .../conversation-registry.client.spec.ts | 307 +++++++++++++++++- .../tests/acknowledge.client.spec.ts | 5 +- .../tests/status-controller.client.spec.ts | 2 +- .../tests/ui-session.client.spec.ts | 2 + .../tests/document-seat.client.spec.tsx | 2 +- .../src/client/session-view.ts | 2 +- .../tests/seat.client.spec.tsx | 4 +- .../src/client/sidebar-chat/index.tsx | 2 +- .../tests/sidebar-chat.client.spec.tsx | 2 +- .../tests/assembly-surfaces.client.spec.tsx | 2 +- .../tests/chat-ptc-subcalls.client.spec.tsx | 2 +- .../tests/toolview-slot.client.spec.tsx | 2 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 + packages/client/ui-workspace/README.zh.md | 2 + .../client/ui-workspace/src/client/index.ts | 2 + .../ui-workspace/src/client/navigation.ts | 13 +- .../ui-workspace/src/client/recent-views.ts | 146 +++++++++ .../ui-workspace/tests/apply.client.spec.ts | 4 +- .../tests/recent-views.client.spec.ts | 190 +++++++++++ .../tests/rename-assembly.client.spec.tsx | 6 +- .../tests/workspaces-service.client.spec.ts | 139 ++++++-- .../src/client/api-catalog.ts | 12 +- .../client-runtime/src/sessions.ts | 25 +- .../tests/runtime.client.spec.tsx | 6 + 55 files changed, 1478 insertions(+), 108 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md create mode 100644 .agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md create mode 100644 packages/api/session-controller/src/client/sessions/facets.ts create mode 100644 packages/client/ui-workspace/src/client/recent-views.ts create mode 100644 packages/client/ui-workspace/tests/recent-views.client.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml index 6826d6a497..ef4816a697 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.i18n.yaml @@ -15,8 +15,8 @@ en: 9ff7f15985d06986 zh: fe27ef687594c124 /agent-note-client-session-references-reference-sources-and-ui-status/decision/addresses-bindings-and-references: - en: 3743abc8bca00348 - zh: d79e6a9311f0a2fe + en: 21659869e0d90071 + zh: 6a011076cf6676ca /agent-note-client-session-references-reference-sources-and-ui-status/decision/acquisition-failure-and-release: en: 84e9528d4f995460 zh: f79f197d3dfbe8e9 diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md index 6a7c15ad86..85e4c5401c 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.md @@ -52,7 +52,9 @@ The [blank Session decision](2026-09-17-process-local-blank-sessions.md) owns cr | `sessions.sessionOf(ctx)` | Returns the matching live Session face or `undefined`; an ended Context cannot resolve to a same-id replacement | | `sessions.create(...)` / `sessions.fork(...)` | Existing Host operations returning a Session identity; retaining and displaying it remain explicit | -`SessionRetainOptions` contains required `source: SessionReferenceSource` and optional `signal: AbortSignal`. Both acquisition methods accept `target: SessionTarget` and these options. Source keys are consumer-defined and declaration-merge extensible; there is no runtime source-registration protocol or default main-view source. A source is a usage label, not another Session address or a permission to act on it. +`SessionRetainOptions` contains required `source: SessionReferenceSource`, optional `facets`, and optional `signal: AbortSignal`. Both acquisition methods accept `target: SessionTarget` and these options. Source keys are consumer-defined and declaration-merge extensible; there is no runtime source-registration protocol or default main-view source. A source is a usage label, not another Session address or a permission to act on it. + +[Session retain facets and recent views](2026-11-15-session-retain-facets-and-recent-views.md) owns `facets`, the independently counted parts a reference keeps beyond its history stream, and the `recentViews` source. ### Acquisition, failure, and release diff --git a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md index 167dbac7b9..fa38ddcef7 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md @@ -52,7 +52,9 @@ Client Session 对象、Agent 作用域的 Client Context、引用、使用方 | `sessions.sessionOf(ctx)` | 返回匹配的活跃 Session 接口或 `undefined`;已结束的 Context 不能解析为同 ID 替代代 | | `sessions.create(...)` / `sessions.fork(...)` | 既有 Host 操作,返回 Session 身份;持有与展示仍需显式执行 | -`SessionRetainOptions` 包含必填 `source: SessionReferenceSource` 与可选 `signal: AbortSignal`。两个获取方法均接受 `target: SessionTarget` 和这些 options。来源键由使用方定义,通过声明合并扩展;不提供运行时来源注册协议,也不默认使用主视图来源。来源是使用标签,不是另一种 Session 地址,也不授予操作权限。 +`SessionRetainOptions` 包含必填 `source: SessionReferenceSource`、可选 `facets` 与可选 `signal: AbortSignal`。两个获取方法均接受 `target: SessionTarget` 和这些 options。来源键由使用方定义,通过声明合并扩展;不提供运行时来源注册协议,也不默认使用主视图来源。来源是使用标签,不是另一种 Session 地址,也不授予操作权限。 + +[Session retain 子要素与最近访问会话](2026-11-15-session-retain-facets-and-recent-views.zh.md) 负责 `facets`,即引用在历史流之外独立计数保活的部分,以及 `recentViews` 来源。 ### 获取、失败与释放 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml new file mode 100644 index 0000000000..54d281d0d2 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-15-session-retain-facets-and-recent-views.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/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +/agent-note-session-retain-facets-and-recently-viewed-sessions: + en: 903aecad7bc8a610 + zh: 17f8f0c420035cc1 +/agent-note-session-retain-facets-and-recently-viewed-sessions/problem: + en: 455344d0dc6aec78 + zh: cd0b86cc1cd2cbe7 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision: + en: c78a249d157157ea + zh: bca420c14a3c8da7 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/session-retain-and-facets: + en: a492378a57ed4222 + zh: d4fec0ebcff7e502 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-conversation-facet: + en: 63d96b2b1c8583e2 + zh: 2b83f63aa8c74714 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/reference-sources-and-facets: + en: 9025a3a0380dbcc0 + zh: 9eba187f235dc045 +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/recently-viewed-sessions-recentviews: + en: 4534183f258404ae + zh: 4168dc2de669b3bd +/agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: + en: f38a402ebd80a0db + zh: c1d7daa160a3b38e +/agent-note-session-retain-facets-and-recently-viewed-sessions/consequences: + en: e36a70328e1cb0ea + zh: b291b0dc56ea52bd +/agent-note-session-retain-facets-and-recently-viewed-sessions/testing: + en: 2b263d91908a0354 + zh: 9c354292c61cf6d9 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md new file mode 100644 index 0000000000..53b4d0686b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -0,0 +1,120 @@ +# Agent Note: Session retain facets and recently viewed Sessions + +Status: implemented + +English | [中文](2026-11-15-session-retain-facets-and-recent-views.zh.md) + +## Problem + +When the Web Client main view switched away from a Session, it released that Session's `mainView` reference. Once the reference count reached zero, the Client disposed the Session's binding, event window, and Conversation assembly state, so returning to it pulled history again. + +Keeping a Session alive is inexpensive: the event window only appends, the stream shares the one Gateway WebSocket, and Host-side subscriptions are passive. The cost lies in derived computation. [`BoundConversation`](../../../../packages/client/ui-conversation/src/client/conversation/assembly.ts) subscribed to the event window when constructed; afterwards every event, including every `assistant/live-chunk`, passed through Definition `match`/`update` folding and rAF-batched publication whether or not the Session was rendered. A retained background Session that keeps running would keep paying that cost. + +The retain interface could only express retaining or releasing the whole Session; it could not express receiving data without derived computation. + +## Decision + +This decision extends [Client Session references](2026-09-15-client-session-references.md) without superseding it: references, source counts, and `ready` semantics are unchanged, and `SessionRetainOptions` carries facets. + +### Session retain and facets + +A Session retain always keeps the binding, scope, history connection, and event window alive. The connection is mandatory and is not a facet. + +A facet is a part retained beyond that baseline, and each facet is counted independently. A reference declares the facets it retains through its options when it is created: + +```ts ignore-check +// session-controller/client: declares no facets +export interface SessionRetainFacetMap {} +export type SessionRetainFacet = Extract + +export interface SessionRetainOptions { + readonly source: SessionReferenceSource + /** Parts kept alive beyond the Session's history stream; an absent key is not retained. */ + readonly facets?: Readonly>> + readonly signal?: AbortSignal | undefined +} + +export interface SessionBinding { + // existing members unchanged + /** Whether any live reference retains `facet`; identity-stable per binding and facet. */ + facet(facet: SessionRetainFacet): ObservableSnapshot +} +``` + +| Rule | Behavior | +|---|---| +| Declaration | The owning package adds a facet to `SessionRetainFacetMap` through declaration merging; the Controller assigns no meaning to any facet | +| Omission | An absent key is not retained; facets have no default | +| Immutability | A reference's facet set is fixed at creation; changing the set retains a new reference before releasing the old one | +| Counting | [`RetainedFacets`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet for each generation; a change between zero and nonzero notifies `binding.facet(name)` observers synchronously, before `retainInfo` and list observers hear the same change; retiring the generation ends every facet | +| Dependencies | The Controller does not validate dependencies between facets; callers are responsible | +| `using()` | Signature unchanged; a borrowed reference serves one operation, and callers omit `facets` | +| `retainAgentScope` | Retains no facets | + +### The `conversation` facet + +`ui-conversation` declares `conversation`: Conversation assembly of the event window and materialization of its views. + +- `BoundConversation` remains one per binding, and its `snapshot`, `openTurn`, and `target(t)` sources keep stable identities. `UiConversation.binding()` registers the binding's disposal on the Session scope before the binding starts following, and a failed initial fold disposes the binding so the next resolution starts afresh. +- When the facet **starts** being retained, the binding first subscribes to the event window, then resumes in one step: the first fold, or a registry change made while not following, rebuilds the current window once; otherwise contiguous changes received meanwhile apply through the incremental assembler and a revision gap rebuilds the whole window. Any pending rAF is then cancelled and the binding publishes once synchronously, also after that fold fails. A view activated while not following is built from the last folded state and catches up on resume. +- When the facet **stops** being retained, the binding unsubscribes from the event window and cancels a pending rAF. The last published snapshot remains readable but no longer updates. While old DOM is still mounted during a switch, its components read that snapshot. A feed dispatch already in progress checks whether the binding still follows, so a release during that dispatch stops folding immediately. +- Calling `uiConversation.binding()` while the facet is not retained returns the unretained binding, which reads the last or empty snapshot without throwing. +- Two computations follow the `conversation` facet: `BoundConversation` and the [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) quota listener, which neither publishes nor replays notices for failures received while the facet is not retained. Other state on `binding.ctx` that events do not drive (input shell, command popups, historical image URLs, agent preset seat) keeps its existing lifetime. + +### Reference sources and facets + +| Source | Owning package | `facets` | +|---|---|---| +| `mainView` | declared by ui-session, retained by ui-workspace | `{ conversation: true }` | +| `sidebarView` | ui-sidebar-right | `{ conversation: true }` | +| `sidebarChat` | ui-subagent | `{ conversation: true }` | +| `recentViews` | ui-workspace | omitted | +| `using()` callers and `gateway` | their own packages | omitted | +| Test fixture default | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | + +### Recently viewed Sessions: `recentViews` + +ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) owns a [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts) list whose entries each hold one `recentViews` reference. + +| Rule | Behavior | +|---|---| +| Order | After the new `mainView` reference exists, navigation first releases the new main Session's recent entry, then retains the previous main Session as a recent view, then releases the previous `mainView` reference; the previous Session's reference count never reaches zero, and reselecting the current Session leaves the list unchanged | +| Entry | Leaving retains a new `recentViews` reference before releasing any earlier entry for the same Session and inserts it into the list current after retention returns, because retention publishes the Session list synchronously and may reconcile or dispose the list meanwhile | +| Blank | A Session still blank when the main view leaves it does not enter | +| Failure | A failed retention is reported to the console and leaves the Session to be released as without recent views; navigation continues | +| Exit | A removed or archived Session leaves when the Session or Workspace list changes | +| Attention | A Session that is running, awaits the user, or has an unread completion, as the unified Session UI status reports, is neither counted nor evicted; once it is read and idle it counts again | +| Limit | 10 counted Sessions, excluding the current Session; a module constant with a `TODO` until the Client supports configuration | +| Eviction | Beyond the limit, the least recently left unpinned Session is evicted first, then the least recently left pinned one; the list is checked again whenever the Session list, Workspace list, or Session UI status changes | +| Disposal | Plugin disposal unsubscribes from both lists and the status and releases every reference | + +## Alternatives considered + +**Decide following by subscriber count.** `BoundConversation` would fold only while subscribed and catch up synchronously on cold reads. React renders before it subscribes, so following would depend on read-time catch-up to avoid a stale first frame, and whether computation runs would follow incidental subscription timing rather than the owner's intent. + +**Split reference sources into render and hold classes.** This expresses only one switch; an independently counted part such as a draft would need another classification. + +**Owner-declared facet defaults at runtime.** This requires a Controller runtime registry plus recounting across load order and HMR, while the rule that an omitted facet is not retained suffices. + +**Make `events` a facet.** A Session without its connection can do nothing, and the only connection-free use, the Gateway, already has its own internal entry. + +**Keep background Session DOM.** React 18 has no ``; K hidden subtrees pay layout, memory, and subscription costs and conflict with the single-Session `session-maybe` binding. + +**Keep folding while unretained and only defer publication.** The `match`/`update` cost of stream chunks remains. + +**Compute a bespoke difference between the folded inputs and the window.** One attempt can start, stream, and settle entirely while unretained, which makes such difference logic error-prone; resumption instead reuses the assembler's existing contiguous-change and gap-rebuild paths. + +## Consequences + +- A background Session switches back without a history request, while it performs no Conversation folding until it is shown again. +- An unretained Session keeps the memory of its last assembly until it is shown again or its binding retires. +- Returning to a Session that ran in the background pays one catch-up fold, at most equal to the post-open fold of a fresh opening, without a network request. +- A rendering owner that omits `conversation: true` sees an unretained stale or empty snapshot without an error. +- `SessionRetainOptions` and `SessionBinding` are pre-stable public interfaces; every consumer and the test fixture changed together. + +## Testing + +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) covers per-facet counting, notifications only at zero transitions, and facets ending with the generation and root disposal. +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) covers zero folding while unretained, one synchronous publication on resume, equality with continuous following, activation and registry changes while not following, a release during an in-progress dispatch, an interrupted rAF publication, a failed resumption, and a failed initial fold leaving no subscription. +- [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) covers quota notices publishing only while the facet is retained. +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) and [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) cover the attention and pin rules, synchronous re-entrancy during retention, the navigation order at the limit, list-driven reconciliation, and returning to a recent view through the same generation without reopening history. diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md new file mode 100644 index 0000000000..64ed9b846d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -0,0 +1,120 @@ +# Agent Note: Session retain 子要素与最近访问会话 + +Status: implemented + +[English](2026-11-15-session-retain-facets-and-recent-views.md) | 中文 + +## 问题 + +Web Client 的主视图切走一个 Session 时,会释放该 Session 的 `mainView` 引用。引用计数归零后,Client 销毁该 Session 的 binding、事件窗口和 Conversation 折叠状态,切回时只能重新拉取历史。 + +保住 Session 本身代价不高:事件窗口只追加,数据流复用同一条 Gateway WebSocket,Host 侧订阅是被动的。真正的开销在派生计算。[`BoundConversation`](../../../../packages/client/ui-conversation/src/client/conversation/assembly.ts) 在构造时就订阅事件窗口,此后不论 Session 是否被渲染,每个事件(包括每个 `assistant/live-chunk`)都要经过 Definition 的 `match`/`update` 折叠,并按 rAF 合批发布。被保住的后台 Session 只要仍在运行,就会一直付出这笔计算。 + +retain 接口只能表达保住或释放整个 Session,无法表达「只收数据,不做派生计算」。 + +## 决策 + +本决策扩展 [Client Session 引用](2026-09-15-client-session-references.zh.md),但不取代它:引用、来源计数和 `ready` 语义不变,`SessionRetainOptions` 携带子要素。 + +### Session retain 与子要素 + +Session retain 始终保活 binding、作用域、历史连接和事件窗口。连接是强制的,不作为子要素。 + +子要素(facet)是在此基础上另外保留的部分,每个子要素单独计数。引用在创建时通过 options 声明要保留哪些子要素: + +```ts ignore-check +// session-controller/client: declares no facets +export interface SessionRetainFacetMap {} +export type SessionRetainFacet = Extract + +export interface SessionRetainOptions { + readonly source: SessionReferenceSource + /** Parts kept alive beyond the Session's history stream; an absent key is not retained. */ + readonly facets?: Readonly>> + readonly signal?: AbortSignal | undefined +} + +export interface SessionBinding { + // existing members unchanged + /** Whether any live reference retains `facet`; identity-stable per binding and facet. */ + facet(facet: SessionRetainFacet): ObservableSnapshot +} +``` + +| 规则 | 行为 | +|---|---| +| 声明方式 | 子要素由其 owner 包通过声明合并加入 `SessionRetainFacetMap`;Controller 不赋予任何子要素含义 | +| 缺省 | 未写的键不保留;子要素没有默认值 | +| 不可变 | 一条引用的子要素集合在创建时固定;更换集合时先 retain 新引用,再 release 旧引用 | +| 计数 | [`RetainedFacets`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 为每个 generation 的每个子要素各记一个计数;计数在零与非零之间变化时同步通知 `binding.facet(name)` 的观察者,早于 `retainInfo` 与列表观察者收到同一变化;generation 退役时结束全部子要素 | +| 依赖 | Controller 不校验子要素之间的依赖,由调用方负责 | +| `using()` | 签名不变;借出的引用只服务一次操作,调用方不写 `facets` | +| `retainAgentScope` | 不保留任何子要素 | + +### `conversation` 子要素 + +`ui-conversation` 声明 `conversation`:对事件窗口做 Conversation 折叠并物化其视图。 + +- `BoundConversation` 仍然每个 binding 一个,其 `snapshot`、`openTurn` 和 `target(t)` 数据源保持对象标识稳定。`UiConversation.binding()` 先在 Session 作用域上登记该绑定的清理,再让绑定开始跟随;首次折叠失败时清理该绑定,下次解析重新开始。 +- 子要素**开始**被保留时,绑定先订阅事件窗口,再一步完成恢复:首次折叠或未跟随期间发生的注册表变化会按当前窗口整窗重建一次;否则期间收到的连续变化走增量 assembler,revision 出现缺口时整窗重建。随后取消待发的 rAF 并同步发布一次,这次折叠失败时也是如此。未跟随期间激活的视图基于上一次折叠结果建立,并在恢复时补齐。 +- 子要素**停止**被保留时,绑定退订事件窗口并取消待发的 rAF。最后一次发布的快照仍可读取,但不再更新。切换过程中旧 DOM 尚未卸载时,其组件读到的就是这份快照。正在进行的事件分发会检查绑定是否仍在跟随,因此分发中途的释放会立即停止折叠。 +- 子要素未被保留时调用 `uiConversation.binding()`,得到的是未被保留的绑定,读取上一次或空的快照,不会抛错。 +- 跟随 `conversation` 子要素的计算有两项:`BoundConversation` 与 [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) 的 quota 监听;后者对子要素未被保留期间收到的失败既不发布也不补发提示。`binding.ctx` 上其他不由事件驱动的状态(输入 shell、命令弹层、历史图片 URL、agent preset seat)保持原有生命周期。 + +### 引用来源与子要素 + +| 来源 | 所属包 | `facets` | +|---|---|---| +| `mainView` | ui-session 声明,ui-workspace 调用 | `{ conversation: true }` | +| `sidebarView` | ui-sidebar-right | `{ conversation: true }` | +| `sidebarChat` | ui-subagent | `{ conversation: true }` | +| `recentViews` | ui-workspace | 不写 | +| `using()` 调用方与 `gateway` | 各自的包 | 不写 | +| 测试替身默认值 | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | + +### 最近访问会话 `recentViews` + +ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) 持有一个 [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts) 列表,每一项持有一条 `recentViews` 引用。 + +| 规则 | 行为 | +|---|---| +| 顺序 | 新的 `mainView` 引用就绪后,导航先释放新主 Session 的最近访问项,再把上一个主 Session 保留为最近访问会话,最后释放上一个 `mainView` 引用;上一个 Session 的引用计数不会归零,重复选中当前 Session 时列表保持不变 | +| 入队 | 离开时先 retain 新的 `recentViews` 引用,再释放同一 Session 的旧项,并插入 retain 返回时的当前列表,因为 retain 会同步发布 Session 列表,期间可能触发对账或释放本列表 | +| 空白 | 离开时仍是空白的 Session 不入队 | +| 失败 | retain 失败时报告到控制台,该 Session 按没有最近访问时的方式释放,导航继续 | +| 出队 | Session 或 Workspace 列表变化时,被移除或归档的 Session 出队 | +| 关注 | 统一 Session UI 状态显示为运行中、等待用户或完成未读的 Session 既不计数也不淘汰;读过且空闲后重新计数 | +| 上限 | 计数的 Session 最多 10 个,不含当前 Session;用模块常量加 `TODO` 写死,等 Client 支持配置后再改 | +| 淘汰 | 超出上限时先淘汰最早离开的未置顶 Session,再淘汰最早离开的置顶 Session;Session 列表、Workspace 列表或 Session UI 状态变化时都会重新检查 | +| 卸载 | 插件卸载时退订两个列表与状态,并释放全部引用 | + +## 备选方案 + +**按订阅数决定是否跟随。** `BoundConversation` 只在有订阅时折叠,冷态读取时同步补齐。React 先渲染后订阅,跟随要靠读取时补齐来避免首帧陈旧,而且是否计算取决于偶然的订阅时序,而不是持有方的意图。 + +**把引用来源分成 render 与 hold 两类。** 这只能表达一个开关;草稿这类独立计数的部分还需要另一种分类。 + +**由子要素 owner 在运行时声明默认值。** 这需要 Controller 维护运行时注册表,并在加载顺序与 HMR 下重新计数;而「未写即不保留」的规则已经足够。 + +**把 `events` 也作为子要素。** 没有连接的 Session 什么也做不了;唯一不需要连接的 Gateway 已经有独立的内部入口。 + +**保留后台 Session 的 DOM。** React 18 没有 ``;K 个隐藏子树要付出布局、内存和订阅成本,还与 `session-maybe` 只绑定一个 Session 的设计冲突。 + +**未被保留时继续折叠,只推迟发布。** 流式块的 `match`/`update` 成本仍然存在。 + +**自行计算已折叠输入与窗口之间的差集。** 未被保留期间,一次 attempt 可能从开始、流式到 settle 全部完成,这类差集逻辑容易出错;恢复改为复用 assembler 现有的连续变化路径与缺口重建路径。 + +## 后果 + +- 后台 Session 切回时无需历史请求,而在再次显示之前不做任何 Conversation 折叠。 +- 未被保留的 Session 保留其最后一次折叠的内存,直到再次显示或其 binding 退役。 +- 切回在后台运行过的 Session 要付出一次补折,最多等同于新打开时的一次打开后折叠,但不走网络。 +- 漏写 `conversation: true` 的渲染方会看到未被保留的陈旧或空快照,不会报错。 +- `SessionRetainOptions` 与 `SessionBinding` 是 pre-stable 公开接口;所有消费方和测试替身已一同修改。 + +## 测试 + +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) 覆盖按子要素计数、只在零值变化时通知,以及子要素随 generation 退役与根释放结束。 +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) 覆盖未被保留时零折叠、恢复时同步发布一次、与持续跟随结果一致、未跟随期间的激活与注册表变化、分发中途的释放、被打断的 rAF 发布、恢复失败,以及首次折叠失败不残留订阅。 +- [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) 覆盖 quota 提示只在子要素被保留时发布。 +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) 与 [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) 覆盖关注与置顶规则、retain 期间的同步重入、达到上限时的导航顺序、由列表变化驱动的对账,以及经由同一 generation 切回最近访问会话且不重新打开历史。 diff --git a/docs/defensive-patterns/conversation-and-session.md b/docs/defensive-patterns/conversation-and-session.md index f8e4d74daa..de9f4e8f07 100644 --- a/docs/defensive-patterns/conversation-and-session.md +++ b/docs/defensive-patterns/conversation-and-session.md @@ -97,7 +97,7 @@ class SidebarSessionView implements Disposable { private readonly reference: SessionReference constructor(readonly id: SessionId, sessions: ISessions) { - this.reference = sessions.retain(id, { source: 'sidebarView' }) + this.reference = sessions.retain(id, { source: 'sidebarView', facets: { conversation: true } }) void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) } diff --git a/docs/defensive-patterns/conversation-and-session.zh.md b/docs/defensive-patterns/conversation-and-session.zh.md index be3696f759..4a774eb57e 100644 --- a/docs/defensive-patterns/conversation-and-session.zh.md +++ b/docs/defensive-patterns/conversation-and-session.zh.md @@ -97,7 +97,7 @@ class SidebarSessionView implements Disposable { private readonly reference: SessionReference constructor(readonly id: SessionId, sessions: ISessions) { - this.reference = sessions.retain(id, { source: 'sidebarView' }) + this.reference = sessions.retain(id, { source: 'sidebarView', facets: { conversation: true } }) void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) } diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 45a394a4cb..a8c92e0fbb 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4f2f2a5276b40d4e zh: 926bb7fc609b971a /session-controller/client-references: - en: e8979a803ec3e194 - zh: c567efcd971728ba + en: e846adfc18abf85c + zh: 973e2204caf4930c /session-controller/session-media-references: en: 954923654eebe2dc zh: 6bd9a7d2ea965aed diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 0f29500a35..e82f77558c 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -85,9 +85,9 @@ The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads onc ## Client references -`sessions.retain(target, { source, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. +`sessions.retain(target, { source, facets?, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. -References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. +References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. Every reference keeps the history stream; `facets` names owner-declared parts beyond it, such as `conversation`, that the reference also keeps alive. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `binding.facet(name)` reports whether any live reference retains it, reading `false` after the generation ends. The Controller counts facets without interpreting them or their dependencies. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 13ab264e71..c4425a49f2 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -85,9 +85,9 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 ## Client 引用 -`sessions.retain(target, { source, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 +`sessions.retain(target, { source, facets?, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 -引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 +引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活历史流;`facets` 指明在此之外由 owner 声明、该引用同时保活的部分,例如 `conversation`。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`binding.facet(name)` 报告是否有存活引用保留该子要素,generation 结束后读为 `false`。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 ## 会话媒体引用 diff --git a/packages/api/session-controller/src/client/contract/sessions.ts b/packages/api/session-controller/src/client/contract/sessions.ts index c1fede0937..2e8c43252d 100644 --- a/packages/api/session-controller/src/client/contract/sessions.ts +++ b/packages/api/session-controller/src/client/contract/sessions.ts @@ -14,7 +14,7 @@ import type { SessionSearchResultItem } from '../sessions/manager.ts' import type { SessionBinding, SessionListState } from '../sessions/service.ts' import type { SessionFace } from './session.ts' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { SessionReferenceSource } from '../index.ts' +import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts' export type { AgentContext } from '../scope.ts' @@ -32,9 +32,14 @@ export interface SessionReference extends Disposable { release(): void } -/** Consumer identity and optional cancellation of one acquisition waiter. */ +/** Consumer identity, retained facets, and optional cancellation of one acquisition waiter. */ export interface SessionRetainOptions { readonly source: SessionReferenceSource + /** + * Facets this reference keeps alive beyond the history stream every reference retains. + * A facet is retained only when its key is `true`; the set is fixed for the reference's lifetime. + */ + readonly facets?: Readonly>> | undefined readonly signal?: AbortSignal | undefined } diff --git a/packages/api/session-controller/src/client/index.ts b/packages/api/session-controller/src/client/index.ts index b9600f36a6..4a4551d408 100644 --- a/packages/api/session-controller/src/client/index.ts +++ b/packages/api/session-controller/src/client/index.ts @@ -87,6 +87,15 @@ export interface SessionReferenceSourceMap { /** Declaration-merge-extensible labels carried by independent Client references. */ export type SessionReferenceSource = Extract +/** + * Owner-declared parts of a retained Session beyond its history stream, each counted independently. + * Owners extend it by augmenting this package's canonical `/client` module specifier; the Controller assigns no meaning to a key. + */ +export interface SessionRetainFacetMap {} + +/** Declaration-merge-extensible facet names a reference may retain. */ +export type SessionRetainFacet = Extract + declare module '@deepseek-ai/cordis' { interface Context { /** Client Session object layer and Agent scope owner. */ diff --git a/packages/api/session-controller/src/client/sessions/facets.ts b/packages/api/session-controller/src/client/sessions/facets.ts new file mode 100644 index 0000000000..9556daef62 --- /dev/null +++ b/packages/api/session-controller/src/client/sessions/facets.ts @@ -0,0 +1,85 @@ +/** Per-generation reference counts of owner-declared retained facets. */ +import { notifySubscribers, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionRetainOptions } from '../contract/sessions.ts' +import type { SessionRetainFacet } from '../index.ts' + +interface FacetCount { + count: number + readonly listeners: Set<() => void> + readonly source: ObservableSnapshot +} + +/** + * The facet keys a retain request sets to `true`. + * @param facets - the request's facet record. + * @returns the facets one reference retains for its lifetime. + */ +export function heldFacets(facets: SessionRetainOptions['facets']): readonly SessionRetainFacet[] { + if (facets === undefined) return [] + return (Object.keys(facets) as SessionRetainFacet[]).filter(facet => facets[facet] === true) +} + +/** Facet counts of one live Client generation; observers are notified only when a facet starts or stops being retained. */ +export class RetainedFacets { + private readonly counts = new Map() + + /** + * Observe one facet of this generation. + * @param facet - owner-declared facet name. + * @returns the identity-stable source reading whether any live reference retains `facet`. + */ + source(facet: SessionRetainFacet): ObservableSnapshot { + return this.entry(facet).source + } + + /** + * Count one new reference for each of its facets. + * @param facets - facets one new reference retains. + */ + retain(facets: readonly SessionRetainFacet[]): void { + for (const facet of facets) this.shift(facet, 1) + } + + /** + * Uncount one released reference from each of its facets. + * @param facets - facets of one released reference. + */ + release(facets: readonly SessionRetainFacet[]): void { + for (const facet of facets) this.shift(facet, -1) + } + + /** End every facet when the generation retires. */ + releaseAll(): void { + for (const entry of this.counts.values()) { + if (entry.count === 0) continue + entry.count = 0 + notifySubscribers(entry.listeners, '[session-controller] retained facet') + } + } + + private shift(facet: SessionRetainFacet, delta: 1 | -1): void { + const entry = this.entry(facet) + const wasHeld = entry.count > 0 + entry.count += delta + if (wasHeld !== entry.count > 0) notifySubscribers(entry.listeners, '[session-controller] retained facet') + } + + private entry(facet: SessionRetainFacet): FacetCount { + const existing = this.counts.get(facet) + if (existing !== undefined) return existing + const listeners = new Set<() => void>() + const created: FacetCount = { + count: 0, + listeners, + source: { + getSnapshot: () => created.count > 0, + subscribe: (listener) => { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + }, + } + this.counts.set(facet, created) + return created + } +} diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index 86b1ad4757..9bc379be2e 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -15,8 +15,9 @@ import type { SessionFace } from '../contract/session.ts' import type { AgentContext, ISessions, SessionReference, SessionRetainInfo, SessionRetainOptions, SessionTarget, } from '../contract/sessions.ts' -import type { SessionReferenceSource } from '../index.ts' +import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts' import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from '../scope.ts' +import { heldFacets, RetainedFacets } from './facets.ts' import { SessionManager } from './manager.ts' import type { SessionRemotes } from './remotes.ts' import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts' @@ -109,6 +110,14 @@ export interface SessionBinding { /** Contiguous event window reserved for Conversation assembly. */ readonly eventSource: SessionEventSource readonly ctx: AgentContext + /** + * Observe whether any live reference retains one facet of this generation. + * @param facet - owner-declared facet name. + * @returns an identity-stable source per binding and facet; it reads false once the generation ends. + * Observers run synchronously inside `retain()` and `release()`, before `retainInfo` and list + * observers hear the same change, and must not release the Session's last reference from that callback. + */ + facet(facet: SessionRetainFacet): ObservableSnapshot } // Scope primitives live in ../scope.ts (the client mirror of host @@ -173,6 +182,7 @@ interface ScopeRecord { binding: SessionBinding session: Session retention: SessionRetainInfo + readonly facets: RetainedFacets live: boolean } @@ -286,6 +296,7 @@ export class ClientSessions implements ISessions { for (const [, record] of scopes) { record.live = false record.session.unbindScope() + record.facets.releaseAll() } const managerDisposal = this.manager.dispose() for (const [id, record] of scopes) { @@ -299,11 +310,11 @@ export class ClientSessions implements ISessions { } retain(target: SessionTarget, options: SessionRetainOptions): SessionReference { - const { source, signal } = options + const { source, signal, facets } = options signal?.throwIfAborted() if (this.closed) throw new Error('Session Controller is disposed') const id = this.manager.resolveTarget(target) - const reference = this.retainScope(id, source) + const reference = this.retainScope(id, source, heldFacets(facets)) try { reference.attachOpening(this.manager.get(id).open(), signal) return reference @@ -517,7 +528,7 @@ export class ClientSessions implements ISessions { */ retainAgentScope(id: SessionId): SessionReference { if (this.closed) throw new Error('Session Controller is disposed') - return this.retainScope(id, 'gateway') + return this.retainScope(id, 'gateway', []) } /** @@ -559,15 +570,21 @@ export class ClientSessions implements ISessions { return this.scopes.get(id)?.binding } - private retainScope(id: SessionId, source: SessionReferenceSource): ClientSessionReference { + private retainScope( + id: SessionId, + source: SessionReferenceSource, + facets: readonly SessionRetainFacet[], + ): ClientSessionReference { const record = this.scopes.get(id) ?? this.materializeScope(id) const previous = record.retention record.retention = Object.freeze({ referenceCount: previous.referenceCount + 1, retainedBy: freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), }) + record.facets.retain(facets) const reference = new ClientSessionReference(id, record, () => { if (!record.live) return + record.facets.release(facets) const count = record.retention.referenceCount - 1 const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources @@ -607,6 +624,7 @@ export class ClientSessions implements ISessions { record.live = false if (this.scopes.get(id) === record) this.scopes.delete(id) record.session.unbindScope() + record.facets.releaseAll() const sessionDisposal = this.manager.drop(id, record.session) this.projectList() this.publishRetention(id) @@ -620,13 +638,21 @@ export class ClientSessions implements ISessions { // The Session owns its scoped dispatch point (host Agent.loopCtx mirror); // mint and bind are one step so a live scope record implies a bound actx. session.bindScope(ctx) - const binding: SessionBinding = { sessionId: id, session, eventSource: session.eventSource, ctx } + const facets = new RetainedFacets() + const binding: SessionBinding = { + sessionId: id, + session, + eventSource: session.eventSource, + ctx, + facet: facet => facets.source(facet), + } const record: ScopeRecord = { fiber, ctx, binding, session, retention: EMPTY_RETAIN_INFO, + facets, live: true, } this.scopes.set(id, record) diff --git a/packages/api/session-controller/tests/reference-ownership.client.spec.ts b/packages/api/session-controller/tests/reference-ownership.client.spec.ts index b3813bafd3..b5327c9251 100644 --- a/packages/api/session-controller/tests/reference-ownership.client.spec.ts +++ b/packages/api/session-controller/tests/reference-ownership.client.spec.ts @@ -17,6 +17,10 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { referenceTestView: unknown referenceTestWork: unknown } + interface SessionRetainFacetMap { + referenceTestFacet: unknown + referenceTestOtherFacet: unknown + } } const viewSource: SessionReferenceSource = 'referenceTestView' @@ -284,6 +288,51 @@ describe('Client reference sources', () => { }) }) +describe('Client retained facets', () => { + it('counts each facet across references and notifies only when its retention starts or stops', async ({ mock, start }) => { + const b = await bench(mock, start) + using plain = b.svc.retain(ID, { source: workSource }) + const facet = plain.binding.facet('referenceTestFacet') + const other = plain.binding.facet('referenceTestOtherFacet') + expect(plain.binding.facet('referenceTestFacet')).toBe(facet) + const changed = vi.fn() + const stop = facet.subscribe(changed) + expect(facet.getSnapshot()).toBe(false) + const first = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true, referenceTestOtherFacet: false } }) + const second = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) + expect(facet.getSnapshot()).toBe(true) + expect(other.getSnapshot()).toBe(false) + expect(changed).toHaveBeenCalledTimes(1) + first.release() + first.release() + expect(facet.getSnapshot()).toBe(true) + expect(changed).toHaveBeenCalledTimes(1) + second.release() + expect(facet.getSnapshot()).toBe(false) + expect(changed).toHaveBeenCalledTimes(2) + stop() + }) + + it('ends retained facets with the generation, including through root disposal', async ({ mock, start }) => { + const b = await bench(mock, start) + const reference = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) + const facet = reference.binding.facet('referenceTestFacet') + const changed = vi.fn() + facet.subscribe(changed) + reference.release() + expect(facet.getSnapshot()).toBe(false) + const replacement = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) + const replacementFacet = replacement.binding.facet('referenceTestFacet') + expect(replacementFacet).not.toBe(facet) + const replacementChanged = vi.fn() + replacementFacet.subscribe(replacementChanged) + await b.ctx.fiber.dispose() + expect(replacementFacet.getSnapshot()).toBe(false) + expect(replacementChanged).toHaveBeenCalledTimes(1) + expect(changed).toHaveBeenCalledTimes(1) + }) +}) + describe('ClientSessions.using', () => { it('awaits callback settlement before releasing and returns its result', async ({ mock, start }) => { const b = await bench(mock, start) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 2344d9a693..505a358bbf 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8ca277dc7fed699f zh: 167478dba50f3904 /deepseek-ai-dsh-client-ui-chat/command-and-failure-rows: - en: 30878be703edac57 - zh: 16b84188c8660850 + en: 384a3d7363818b34 + zh: feebd24a46446644 /deepseek-ai-dsh-client-ui-chat/inherited-history-divider: en: a191f90e9a64f6fe zh: 8e91b8660f9baa18 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index fabe865fc0..75197e7e97 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -70,7 +70,7 @@ Text and reasoning contribute to Assistant visibility only when they contain a n Subagent result notices use the Users icon and show only the localized execution outcome in their heading, without a task description or child ID. Completed means that execution ended normally, not that its output passed validation. Historical notices without a readable outcome retain the generic title; unfamiliar outcomes display “Subagent run ended unexpectedly”. Expanded notices preserve their original model-facing body. -Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions this Client has bound and materialized publish; quota failures in Sessions it never opened do not. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. +Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions whose `conversation` retain facet a rendering reference currently holds publish; quota failures in Sessions this Client never opened, or that occur while a Session is kept only as a recent view, do not, and resuming the facet does not replay them. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The assistant-node Slot obtains `useContextMenu` directly and passes a file-path adapter to the optional mention service; intermediate flow and node owners carry no menu callbacks. Paths resolve against the originating Session’s current working directory when the gesture begins. Menus retain that captured path and line even if focus changes. Undeclared plugin links keep native behavior. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 813f1d3234..a5693880ce 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -70,7 +70,7 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node, 子智能体结果通知使用 Users 图标,标题仅显示本地化的执行状态,不附加任务描述或子智能体 ID。完成表示执行正常结束,不表示输出已通过验证。历史通知没有可读取的结束状态时保留通用标题;未知状态显示“子智能体异常结束”。展开后的通知保留原始模型可见正文。 -通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有本 Client 已绑定并已物化的 Session 会发布提示;它从未打开的 Session 中的欠费不会发布。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 +通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有当前被渲染方引用保留了 `conversation` retain 子要素的 Session 会发布提示;本 Client 从未打开的 Session,以及仅作为最近访问会话保留期间发生的欠费都不会发布,恢复保留后也不补发。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目标。助手节点 Slot 直接获取 `useContextMenu`,向可选的文件引用服务传入路径适配函数;消息流和节点中间层不再携带菜单回调。手势发生时按原始 Session 的当前工作目录解析路径,菜单保留捕获的路径和行号,不受焦点变化影响。未声明的插件链接保留原生行为。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 56bb503a9a..93139e5335 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -105,18 +105,31 @@ export function apply(ctx: Context): void { // replacement or paging never does, because an old failure scrolling // back into view is not news. const dispose = binding.ctx.effect(() => { - const stop = binding.eventSource.subscribe(() => { - const { change } = binding.eventSource.getSnapshot() - if (change.kind !== 'append') return - for (const { event } of change.entries) { - if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue - const { code } = event.data.reason.error - if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue - quotaNotice.set({ code, seq: ++quotaNoticeSeq }) - } - }) + // Live quota failures are reported only while a rendering reference retains the Session's Conversation. + const retained = binding.facet('conversation') + let stopEvents = (): void => {} + const follow = (): void => { + stopEvents() + stopEvents = () => {} + if (!retained.getSnapshot()) return + stopEvents = binding.eventSource.subscribe(() => { + // A dispatch in progress keeps calling copied listeners after unsubscription. + if (!retained.getSnapshot()) return + const { change } = binding.eventSource.getSnapshot() + if (change.kind !== 'append') return + for (const { event } of change.entries) { + if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue + const { code } = event.data.reason.error + if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue + quotaNotice.set({ code, seq: ++quotaNoticeSeq }) + } + }) + } + const stopRetained = retained.subscribe(follow) + follow() return () => { - stop() + stopRetained() + stopEvents() chatSources.delete(binding) quotaSubscriptions.delete(dispose) } 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 5efab8c1d9..8e9595985c 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -47,6 +47,7 @@ type ChatActions = ChatInstance['actions'] function sessionFakeFor() { return { loadOlder: vi.fn(() => Promise.resolve()), + consumeOlder: vi.fn(() => true), loadThrough: vi.fn(() => Promise.resolve()), readAttachment: vi.fn(() => Promise.resolve({ ok: true, @@ -257,6 +258,8 @@ describe('Chat inject API', () => { const { injected } = b.chatViewApi(b.rootReference) injected.loadOlder() expect(b.session.loadOlder).toHaveBeenCalledExactlyOnceWith({ deferConsumption: true }) + expect(injected.consumeOlder()).toBe(true) + expect(b.session.consumeOlder).toHaveBeenCalledOnce() void injected.loadThrough(SessionSeq(42)) expect(b.session.loadThrough).toHaveBeenCalledWith(42) diff --git a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx index 0464c6d74a..a9afd62ab7 100644 --- a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx +++ b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx @@ -92,7 +92,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) { runtime.remote.provideNamespaces({ session: { openWorkspacePath: vi.fn() } }) let mainReference: ReturnType | undefined const openSession = (id: SessionId): void => { - const next = runtime.sessions.retain(id, { source: 'mainView' }) + const next = runtime.sessions.retain(id, { source: 'mainView', facets: { conversation: true } }) mainReference?.release() mainReference = next } diff --git a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx index 95775d73f5..23ce7c88f1 100644 --- a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx +++ b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx @@ -126,6 +126,35 @@ describe('frame-wide quota notices', () => { expect(notice.getSnapshot()?.seq).not.toBe(first) }) + it('publishes only while a reference retains the Session Conversation', async () => { + const b = await bench() + await b.runtime.sessions.add({ id: SID }) + const background = b.runtime.sessions.retain(SID, { source: 'testFixture' }) + references.push(background) + b.sourceDescriptor.resolve(background.binding) + const notice = noticeFace(b.runtime).hooks.notice + await b.runtime.sessions.appendEvent(SID, quotaEntry(0, 'QUOTA')) + expect(notice.getSnapshot()).toBeNull() + const rendered = b.runtime.sessions.retain(SID) + references.push(rendered) + await b.runtime.sessions.appendEvent(SID, quotaEntry(1, 'ACCOUNT_QUOTA')) + expect(notice.getSnapshot()).toMatchObject({ code: 'ACCOUNT_QUOTA' }) + }) + + it('stops publishing within the dispatch that released the Session Conversation', async () => { + const b = await bench() + await b.runtime.sessions.add({ id: SID }) + const background = b.runtime.sessions.retain(SID, { source: 'testFixture' }) + references.push(background) + const rendered = b.runtime.sessions.retain(SID) + const stopReleaser = background.binding.eventSource.subscribe(() => { rendered.release() }) + b.sourceDescriptor.resolve(background.binding) + const notice = noticeFace(b.runtime).hooks.notice + await b.runtime.sessions.appendEvent(SID, quotaEntry(0, 'QUOTA')) + expect(notice.getSnapshot()).toBeNull() + stopReleaser() + }) + it('never publishes for history replacement or paging, or for other failures', async () => { const b = await bench() await attach(b.runtime, b.sourceDescriptor) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 75ca98c66f..07d4843e4e 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -15,8 +15,8 @@ en: eef4f18c3972ccc4 zh: 6be65c6ac84ce497 /deepseek-ai-dsh-client-ui-conversation/conversation-assembly: - en: ef43c4f149195939 - zh: 49fc6c83fd3a05ce + en: 541e9f117a5ef93b + zh: f6ad83efa7d9783f /deepseek-ai-dsh-client-ui-conversation/sent-user-text: en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 77ceba77ae..bc818a566c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -30,7 +30,9 @@ Desktop product events use the optional [product analytics service](../product-a `UiConversation.events` is the single registry for event Definitions, and `UiConversation.views` is the single registry for target snapshot builders. Both registries reject duplicate keys, preserve registration order, return idempotent disposers, and rebuild existing bindings when their contribution roster changes. `UiConversation.binding(bindingOrSessionId)` returns one identity-stable Conversation binding for the current Session Controller binding. It does not open another event source. A View Definition may declare `toolCallFocus` to translate a tool-call id into its focus identity. Conversation supplies an Inspect callback only while such a target has a visible View entry; Chat consumes this callback without selecting a target. -`ConversationBinding.openTurn` is an identity-stable, read-only source of the latest turn number when its start is loaded and it remains open, or `undefined` otherwise. Observed turn changes publish synchronously even when no View is active. Fixed stop input reads this source alongside Session running and pending-interaction state. Unloading the Session binding detaches its event-source subscription. +`ConversationBinding.openTurn` is an identity-stable, read-only source of the latest turn number when its start is loaded and it remains open, or `undefined` otherwise. While the `conversation` retain facet is held, observed turn changes publish synchronously even when no View is active. Fixed stop input reads this source alongside Session running and pending-interaction state. Unloading the Session binding detaches its event-source subscription. + +The package declares the `conversation` retain facet. A binding follows its event source only while some Session reference retains that facet, which rendering owners such as the main view and Sidebar views request. While it is not retained, the Session still receives events but the binding neither folds nor publishes: readers see the last published snapshot, and target activations and registry rebuilds wait. When retention resumes, the binding folds the events received meanwhile, rebuilding from the complete window after a gap, and publishes once. The adapter passes each `SessionEventLikeEntry` directly to the assembler. Its outer `type` distinguishes durable events from Client-only transient events, while its inner `event` always exposes `type`, `seq`, `time`, and `data`; Definitions receive that inner `SessionEventLike`. Replacement windows may include both entry variants, while historical prepends carry durable entries and live appends may carry either. Definitions use the same match/start/update interface for durable and transient events. The earliest loaded start initializes State; every later Match, including another start for that identity, updates it. Definitions that do not consume Assistant deltas return `null` for `assistant/live-chunk`. Replacement windows and revision gaps rebuild from the complete loaded window; contiguous append, prepend, and Assistant-settlement revisions use incremental assembly. Settlement removes only the named attempt's transient matches, applies its optional durable entry, and recomputes the affected Contexts from their remaining earliest start, refreshing predecessor indexes and dependents without replacing unrelated target nodes. A Context with no remaining start has no State. Its key and previously published nodes remain available to later evidence until a full window rebuild; the owning Definition may hide those nodes. The assembler owns Context matching, Turn/Step locations, target node materialization, target activity, and stable target sources. `ConversationSnapshot` contains only target-neutral views and active-target facts; Session lifecycle state remains in `SessionSnapshot`. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 2f10f02b7c..70151a12f6 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -30,7 +30,9 @@ kind: "package-reference" `UiConversation.events` 是 event Definition 的唯一 registry,`UiConversation.views` 是 target snapshot builder 的唯一 registry。两者都拒绝重复 key、保持注册顺序、返回幂等 disposer,并在 contribution roster 变化时重建现有 binding。`UiConversation.binding(bindingOrSessionId)` 为当前 Session Controller binding 返回 identity 稳定的 Conversation binding,不会另开事件源。 View Definition 可以声明 `toolCallFocus`,将工具调用 id 转换为自身的焦点标识。仅当此目标拥有可见的 View 条目时,Conversation 才提供 Inspect 回调;Chat 直接使用回调,不选择目标。 -`ConversationBinding.openTurn` 是对象标识稳定的只读来源:最新轮次的开始事件已加载且尚未结束时提供其编号,否则为 `undefined`。观察到的轮次变化同步发布,即使没有活动视图也是如此。固定停止输入同时读取这个来源、会话运行状态和待处理交互状态。卸载会话绑定会解除其事件源订阅。 +`ConversationBinding.openTurn` 是对象标识稳定的只读来源:最新轮次的开始事件已加载且尚未结束时提供其编号,否则为 `undefined`。在 `conversation` retain 子要素被保留期间,观察到的轮次变化同步发布,即使没有活动视图也是如此。固定停止输入同时读取这个来源、会话运行状态和待处理交互状态。卸载会话绑定会解除其事件源订阅。 + +本包声明 `conversation` retain 子要素。只有当某个 Session 引用保留该子要素时,绑定才跟随其事件源;主视图和侧栏视图等渲染方会请求它。未被保留时,Session 仍接收事件,但绑定既不折叠也不发布:读取方看到最后一次发布的快照,目标激活与注册表重建也会等待。恢复保留后,绑定折叠期间收到的事件(出现缺口时从完整窗口重建),并发布一次。 适配器把每个 `SessionEventLikeEntry` 直接交给 assembler。外层 `type` 区分持久事件与 Client-only transient event,内部 `event` 则统一公开 `type`、`seq`、`time` 与 `data`;Definition 接收这个内部 `SessionEventLike`。replacement window 可以包含两种 entry,历史 prepend 携带持久 entry,实时 append 则可以携带任一种。持久与瞬态事件使用同一组 match/start/update 接口。当前最早的 start 初始化 State;后续所有 Match,包括同一身份的其他 start,都用于更新。不消费 Assistant delta 的 Definition 对 `assistant/live-chunk` 返回 `null`。replace window 或 revision 断档从完整已加载窗口重建;连续 revision 的 append、prepend 与 Assistant settlement 使用增量组装。settlement 只删除具名 attempt 的 transient match,应用可选持久 entry,并从剩余最早的 start 重算受影响的 Context,刷新前序索引及 dependent,不替换无关 target node。没有剩余 start 的 Context 不保留 State,但其 key 和已发布节点仍保留,供后续证据复用,直到完整窗口重建;所属 Definition 可以隐藏这些节点。assembler 拥有 Context 匹配、Turn/Step location、target node 物化、target activity 和稳定 target source。`ConversationSnapshot` 只包含与 target 无关的 View 与 active-target 事实;Session lifecycle 状态仍属于 `SessionSnapshot`。 diff --git a/packages/client/ui-conversation/src/client/conversation/assembler.ts b/packages/client/ui-conversation/src/client/conversation/assembler.ts index ab1ab05f7b..5398debee0 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembler.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembler.ts @@ -378,11 +378,16 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore /** * Rebuild against the current Registry set after a low-frequency plugin change. + * @param entries - complete window to rebuild from; omitted replays the loaded inputs. + * @param hasMore - whether older history remains outside `entries`. * @returns immediate publication request. */ - rebuildRegistry(): ConversationPublication { + rebuildRegistry( + entries: readonly SessionEventLikeEntry[] = this.sortedInputs(), + hasMore: boolean = this.hasMore, + ): ConversationPublication { this.resetViewBuilders() - return this.replaceWindow(this.sortedInputs(), this.hasMore) + return this.replaceWindow(entries, hasMore) } /** diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 233a72e23f..748a129258 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -27,16 +27,31 @@ import { ConversationGroupRegistry } from './group-registry.ts' import { ConversationInteractionRegistry } from './interaction-registry.ts' import { UserTextRegistry } from './user-text-registry.ts' -/** Observable faces published for one Session's Conversation assembly. */ +declare module '@deepseek-ai/dsh-api-session-controller/client' { + interface SessionRetainFacetMap { + /** + * Conversation assembly of the Session's event window. While no reference retains it, the + * Session still receives events but its Conversation binding neither folds nor publishes; + * readers see the last published snapshot until retention resumes and folds the window once. + */ + conversation: unknown + } +} + +/** + * Observable faces published for one Session's Conversation assembly. Every face follows the + * Session only while a reference retains the `conversation` facet. + */ export interface ConversationBinding { readonly snapshot: ObservableSnapshot /** * Identity-stable source of the latest turn number, undefined unless its start is loaded and it remains open. - * Turn changes publish synchronously, including without an active View. + * Turn changes publish synchronously while the facet is retained, including without an active View. */ readonly openTurn: ObservableSnapshot /** - * Add one selected target to the Session's monotonic active set. + * Add one selected target to the Session's monotonic active set; while the facet is not retained, + * the target's view is built from the last folded state and catches up when retention resumes. * @param target - registered or subsequently registered Conversation target. */ activate(target: string): void @@ -59,19 +74,34 @@ class BoundConversation implements ConversationBinding { private readonly targetSources = new Map>() private revision = -1 private frame: number | undefined + private following = false + /** Resuming rebuilds the whole window: set until the first fold and by registry changes while not following. */ + private stale = true private disposeFeed: () => void = () => {} + private disposeRetained: () => void = () => {} + /** + * @param feed - the Session's contiguous event window. + * @param assembler - this binding's Node assembler. + * @param retained - whether any reference retains the `conversation` facet; assembly follows the feed only while true. + */ constructor( - feed: SessionEventSource, + private readonly feed: SessionEventSource, private readonly assembler: ConversationNodeAssembler, + private readonly retained: ObservableSnapshot, ) { this.viewStore = assembler this.snapshot = createSnapshotStore(this.currentSnapshot()) this.openTurn = createSnapshotStore(assembler.openTurn()) - this.replace(feed.getSnapshot()) - this.disposeFeed = feed.subscribe(() => { - this.accept(feed.getSnapshot()) - }) + } + + /** + * Begin following facet retention; the owner registers this binding's disposal first, + * so subscriptions acquired before a failed initial fold still have an owner. + */ + start(): void { + this.disposeRetained = this.retained.subscribe(() => { this.follow(this.retained.getSnapshot()) }) + this.follow(this.retained.getSnapshot()) } target>( @@ -97,13 +127,62 @@ class BoundConversation implements ConversationBinding { this.publishing(() => this.assembler.activateTarget(target)) } - rebuild(): void { this.publish(this.assembler.rebuildRegistry()) } + rebuild(): void { + if (!this.following) { + this.stale = true + return + } + this.publish(this.assembler.rebuildRegistry()) + } dispose(): void { + this.following = false + this.disposeRetained() this.cancelFrame() this.disposeFeed() } + /** + * Start or stop following the feed. Stopping keeps the last published snapshot readable. + * Resuming subscribes first, so a failed catch-up is repaired by the next window change. + */ + private follow(retained: boolean): void { + if (retained === this.following) return + this.following = retained + if (!retained) { + this.disposeFeed() + this.disposeFeed = () => {} + this.cancelFrame() + return + } + // A dispatch already in progress keeps a copy of its listeners, so the callback checks + // whether the binding still follows rather than relying on unsubscription alone. + this.disposeFeed = this.feed.subscribe(() => { + if (this.following) this.accept(this.feed.getSnapshot()) + }) + this.resume() + } + + /** + * Fold the window changes received while not following and publish once synchronously: a stale + * binding rebuilds the whole window, otherwise contiguous changes fold incrementally and a gap rebuilds. + */ + private resume(): void { + const window = this.feed.getSnapshot() + try { + if (this.stale) { + this.stale = false + this.revision = window.revision + this.assembler.rebuildRegistry(window.entries, window.hasMore) + } else { + this.accept(window) + } + } finally { + this.cancelFrame() + this.publishing(() => this.assembler.flush()) + } + } + private replace(window: SessionEventWindow): void { this.revision = window.revision this.publish(this.assembler.replaceWindow(window.entries, window.hasMore)) @@ -269,6 +348,7 @@ export class UiConversation extends Service { const binding = new BoundConversation( owner.eventSource, new ConversationNodeAssembler(this.events, this.views, this.groups), + owner.facet('conversation'), ) const record: BindingRecord = { source: owner, binding, disposeScope: () => {} } this.bindings.set(owner, record) @@ -277,6 +357,13 @@ export class UiConversation extends Service { 'ui-conversation binding', ) record.disposeScope = () => { void disposeScope() } + try { + binding.start() + } catch (error: unknown) { + // A failed initial fold leaves no binding behind, so the next resolution starts afresh. + this.drop(record, true) + throw error + } return binding } diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index b5d57c4efd..701616957f 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -80,7 +80,7 @@ async function bench(renderQuote = false) { const opened = vi.fn<(id: SessionId) => void>() let mainReference: SessionReference | undefined const replaceMain = (id: SessionId, beforeOpen?: (id: SessionId) => void): void => { - const next = runtime.sessions.retain(id, { source: 'mainView' }) + const next = runtime.sessions.retain(id, { source: 'mainView', facets: { conversation: true } }) try { beforeOpen?.(id) } catch (error: unknown) { @@ -476,7 +476,7 @@ describe('Conversation inject API', () => { expect(activate).toHaveBeenLastCalledWith('custom') activate.mockClear() - using mainReference = b.runtime.sessions.retain(ROOT, { source: 'mainView' }) + using mainReference = b.runtime.sessions.retain(ROOT, { source: 'mainView', facets: { conversation: true } }) await b.runtime.flush() expect(mainReference.sessionId).toBe(ROOT) expect(activate).not.toHaveBeenCalled() diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index b2506a1eab..6d436d46db 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -58,7 +58,7 @@ const LAYOUT_CHILDREN = { function provideWorkspaceNavigation(runtime: SlotTestRuntime): (id: SessionId) => void { let mainReference: ReturnType | undefined const openSession = (id: SessionId): void => { - const next = runtime.sessions.retain(id, { source: 'mainView' }) + const next = runtime.sessions.retain(id, { source: 'mainView', facets: { conversation: true } }) mainReference?.release() mainReference = next } 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 9ab5e58380..3a3a0783de 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -1,10 +1,10 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { SessionSeq } from '@deepseek-ai/dsh-session/types' -import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import { brandString } from '@deepseek-ai/dsh-brand' import { createAssistantMessage, type LlmAttemptId } from '@deepseek-ai/dsh-llm' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import { createScope, MutableSessionEventSource, } from '@deepseek-ai/dsh-api-session-controller/client' @@ -69,13 +69,19 @@ function fakeSession(): SessionFace { } } -function fakeSessions(ctx: Context): { sessions: ISessions; binding: SessionBinding } { +function fakeSessions(ctx: Context): { + sessions: ISessions + binding: SessionBinding + retained: SnapshotStore +} { const scope = createScope(ctx, SESSION_ID) + const retained = createSnapshotStore(true) const binding: SessionBinding = { sessionId: SESSION_ID, session: fakeSession(), eventSource: new MutableSessionEventSource(), ctx: scope.ctx, + facet: () => retained, } const list = createSnapshotStore({ ids: [], @@ -107,7 +113,7 @@ function fakeSessions(ctx: Context): { sessions: ISessions; binding: SessionBind sessionOf: candidate => candidate === binding.ctx ? binding.session : undefined, binding: id => id === SESSION_ID ? binding : undefined, } - return { sessions, binding } + return { sessions, binding, retained } } function eventDefinition(kind: string): ConversationNodeDefinition { @@ -136,17 +142,19 @@ async function bootRegistries(): Promise<{ ctx: Context uiConversation: UiConversation binding: SessionBinding + retained: SnapshotStore events: ConversationEventRegistry views: ConversationViewRegistry }> { const ctx = new Context() onTestFinished(async () => { await ctx.fiber.dispose() }) - const { sessions, binding } = fakeSessions(ctx) + const { sessions, binding, retained } = fakeSessions(ctx) const uiConversation = new UiConversation(ctx, sessions) return { ctx, uiConversation, binding, + retained, events: uiConversation.events, views: uiConversation.views, } @@ -441,6 +449,295 @@ describe('Conversation registries', () => { await binding.ctx.fiber.dispose() }) + it('folds nothing while the conversation facet is released and publishes the received window once on resume', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn((event: SessionEventLike) => event.type === 'turn/start' + ? { id: String(event.data.turn), role: 'start' as const } + : event.type === 'turn/end' ? { id: String(event.data.turn), role: 'update' as const } : null) + events.register({ + kind: 'turn-probe', + target: 'chat', + match, + start: () => 'open', + update: () => 'closed', + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: context.id, target: 'chat', data: context.state }), + }) + const built: unknown[] = [] + const chatView: ConversationViewDefinition = { + target: 'chat', + create: () => ({ + empty: [], + replace: ({ nodes }) => { + const data = nodes.map(node => node.data) + built.push(data) + return data + }, + apply: ({ upserts }) => upserts.map(node => node.data), + }), + } + views.register(chatView) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + const listener = vi.fn() + const unsubscribe = conversation.snapshot.subscribe(listener) + retained.set(false) + const cold = conversation.snapshot.getSnapshot() + match.mockClear() + source.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(2), time: 2, data: { turn: 1, reason: { kind: 'completed' } }, + } }) + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(3), time: 3, data: { turn: 2 } } }) + expect(match).not.toHaveBeenCalled() + expect(listener).not.toHaveBeenCalled() + expect(conversation.snapshot.getSnapshot()).toBe(cold) + expect(conversation.openTurn.getSnapshot()).toBe(1) + built.length = 0 + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + expect(built).toEqual([['closed', 'open']]) + expect(conversation.openTurn.getSnapshot()).toBe(2) + source.append({ type: 'event', event: { + type: 'turn/end', seq: SessionSeq(4), time: 4, data: { turn: 2, reason: { kind: 'completed' } }, + } }) + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + unsubscribe() + }) + + it('applies activations and registry changes made while not following once retention resumes', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + retained.set(false) + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + events.register(eventDefinition('message')) + views.register(viewDefinition('chat')) + await Promise.resolve() + expect(conversation.snapshot.getSnapshot().activeTargets.size).toBe(0) + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + retained.set(true) + expect(conversation.openTurn.getSnapshot()).toBe(1) + expect(conversation.snapshot.getSnapshot().views.get('chat')).toBeNull() + }) + + it('publishes a frame-paced update that a facet release interrupted when retention resumes', async () => { + const frames = new Map() + let nextFrame = 0 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.stubGlobal('cancelAnimationFrame', (frame: number) => { frames.delete(frame) }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const chunkProbe: ConversationNodeDefinition = { + kind: 'chunk-probe', + target: 'chat', + match: event => event.type === 'assistant/live-chunk' ? { id: 'chunk', role: 'start' } : null, + start: () => 1, + update: context => context.state + 1, + publication: () => 'animation-frame', + buildViewNode: context => ({ key: context.key, kind: 'chunk-probe', id: context.id, target: 'chat', data: context.state }), + } + events.register(chunkProbe) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + const listener = vi.fn() + const unsubscribe = conversation.snapshot.subscribe(listener) + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'transient', event: { + seq: SessionSeq(1), time: 1, type: 'assistant/live-chunk', + data: { attemptId: brandString('chunk'), turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' } }, + } }) + expect(frames.size).toBe(1) + retained.set(false) + expect(frames.size).toBe(0) + expect(listener).not.toHaveBeenCalled() + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + unsubscribe() + }) + + it('leaves no subscription behind when the initial fold fails and folds afresh on the next resolution', async () => { + const { uiConversation, binding, events, views } = await bootRegistries() + let failing = true + const match = vi.fn((event: SessionEventLike) => { + if (failing) throw new Error('definition failed') + return event.type === 'turn/start' ? { id: String(event.data.turn), role: 'start' as const } : null + }) + events.register({ + kind: 'failing-probe', target: 'chat', match, start: () => null, update: context => context.state, + buildViewNode: context => ({ key: context.key, kind: 'failing-probe', id: context.id, target: 'chat', data: null }), + }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const source = binding.eventSource as MutableSessionEventSource + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + expect(() => uiConversation.binding(binding)).toThrow('definition failed') + match.mockClear() + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(2), time: 2, data: { turn: 2 } } }) + expect(match).not.toHaveBeenCalled() + failing = false + const conversation = uiConversation.binding(binding) + expect(match).toHaveBeenCalledTimes(2) + expect(conversation.openTurn.getSnapshot()).toBe(2) + }) + + it('ignores a window change dispatched after an earlier listener released the facet', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn(() => null) + events.register(eventDefinition('message')) + events.register({ ...eventDefinition('probe'), match }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const source = binding.eventSource as MutableSessionEventSource + const stopReleaser = source.subscribe(() => { retained.set(false) }) + const conversation = uiConversation.binding(binding) + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + match.mockClear() + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } } }) + expect(match).not.toHaveBeenCalled() + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + stopReleaser() + }) + + it('publishes one live chunk received while not following synchronously on resume', async () => { + const frames = new Map() + let nextFrame = 0 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.stubGlobal('cancelAnimationFrame', (frame: number) => { frames.delete(frame) }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const chunkProbe: ConversationNodeDefinition = { + kind: 'chunk-probe', + target: 'chat', + match: event => event.type === 'assistant/live-chunk' ? { id: 'chunk', role: 'start' } : null, + start: () => 1, + update: context => context.state + 1, + publication: () => 'animation-frame', + buildViewNode: context => ({ key: context.key, kind: 'chunk-probe', id: context.id, target: 'chat', data: context.state }), + } + events.register(chunkProbe) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('chat') + retained.set(false) + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'transient', event: { + seq: SessionSeq(1), time: 1, type: 'assistant/live-chunk', + data: { attemptId: brandString('chunk'), turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' } }, + } }) + retained.set(true) + expect(listener).toHaveBeenCalledOnce() + expect(frames.size).toBe(0) + }) + + it('folds the window once when a registry rebuild and a window gap wait for resumption', async () => { + const { uiConversation, binding, retained, events, views } = await bootRegistries() + const match = vi.fn(() => null) + events.register({ ...eventDefinition('probe'), match }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + const source = binding.eventSource as MutableSessionEventSource + retained.set(false) + for (let seq = 1; seq <= 3; seq++) { + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(seq), time: seq, data: { turn: seq } } }) + } + events.register(eventDefinition('late')) + await Promise.resolve() + match.mockClear() + const listener = vi.fn() + conversation.snapshot.subscribe(listener) + retained.set(true) + expect(match).toHaveBeenCalledTimes(3) + expect(conversation.openTurn.getSnapshot()).toBe(3) + }) + + it('keeps following and keeps its activations after the resuming fold fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + let failing = false + events.register({ ...eventDefinition('probe'), match: () => { + if (failing) throw new Error('resume failed') + return null + } }) + views.register(viewDefinition('chat')) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + retained.set(false) + conversation.activate('chat') + failing = true + ;(binding.eventSource as MutableSessionEventSource).replace([{ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 }, + } }], false) + retained.set(true) + expect(errors).toHaveBeenCalled() + failing = false + ;(binding.eventSource as MutableSessionEventSource).append({ type: 'event', event: { + type: 'turn/start', seq: SessionSeq(2), time: 2, data: { turn: 2 }, + } }) + expect(conversation.snapshot.getSnapshot().views.get('chat')).toBeNull() + expect(conversation.openTurn.getSnapshot()).toBe(2) + }) + + it('reaches the same views on resume as when following every event', async () => { + const turnProbe: ConversationNodeDefinition = { + kind: 'turn-probe', + target: 'recovery-probe', + match: event => event.type === 'turn/start' + ? { id: String(event.data.turn), role: 'start' } + : event.type === 'turn/end' ? { id: String(event.data.turn), role: 'update' } : null, + start: () => 'open', + update: () => 'closed', + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: `${context.id}:${context.state}`, target: 'recovery-probe', data: null }), + } + const idsView: ConversationViewDefinition = { + target: 'recovery-probe', + create: () => { + let ids: string[] = [] + return { + empty: [], + replace: ({ nodes }) => (ids = nodes.map(node => node.id)), + apply: ({ upserts }) => { + for (const node of upserts) { + const key = node.id.split(':')[0] + ids = [...ids.filter(id => id.split(':')[0] !== key), node.id] + } + return ids + }, + } + }, + } + const events: SessionEvent[] = [ + { type: 'turn/start', seq: SessionSeq(1), time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: SessionSeq(2), time: 2, data: { turn: 1, reason: { kind: 'completed' } } }, + { type: 'turn/start', seq: SessionSeq(3), time: 3, data: { turn: 2 } }, + ] + const run = async (followAll: boolean): Promise => { + const b = await bootRegistries() + b.events.register(turnProbe) + b.views.register(idsView) + await Promise.resolve() + const conversation = b.uiConversation.binding(b.binding) + conversation.activate('recovery-probe') + if (!followAll) b.retained.set(false) + for (const event of events) (b.binding.eventSource as MutableSessionEventSource).append({ type: 'event', event }) + b.retained.set(true) + return conversation.snapshot.getSnapshot().views.get('recovery-probe') + } + expect(await run(false)).toEqual(await run(true)) + }) + it('rejects duplicate Event Definitions and disposes an ordinary registration once', async () => { const { events } = await bootRegistries() const definition = eventDefinition('message') diff --git a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts index 4475586682..174a05276d 100644 --- a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts +++ b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts @@ -51,7 +51,10 @@ function harness({ manual = false, completedTurn = 1, selected = true, ready = t const list = createSnapshotStore({ ids: [id], phase: 'ready', projectionsBySession: {}, byId: { [id]: row(selected) }, }, { flush: 'sync' }) - const bind = (): SessionBinding => ({ sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext }) + const retainedFacet = createSnapshotStore(true) + const bind = (): SessionBinding => ({ + sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext, facet: () => retainedFacet, + }) let binding = bind() const mark = vi.fn(async (_id: typeof id, _throughTurn: number, _clearManual: boolean) => {}) let frame: FrameRequestCallback | undefined diff --git a/packages/client/ui-session-status/tests/status-controller.client.spec.ts b/packages/client/ui-session-status/tests/status-controller.client.spec.ts index 13ce251f13..72da186bc3 100644 --- a/packages/client/ui-session-status/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session-status/tests/status-controller.client.spec.ts @@ -94,7 +94,7 @@ it('preserves unlisted child status through metadata updates and main view ackno await client.flush() expect(status.getSnapshot().get(childId)).toMatchObject({ running: false, completionUnread: true }) - using reference = sessions.retain(childId, { source: 'mainView' }) + using reference = sessions.retain(childId, { source: 'mainView', facets: { conversation: true } }) await reference.ready expect(sessions.list.getSnapshot().ids).not.toContain(childId) mock.streams.push('sessionStatus/follow', { type: 'changed', state: { 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 ac7fb9bc42..07f0dddaea 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -109,11 +109,13 @@ function createSessionsBench(ctx: Context): SessionsBench { getSnapshot: () => snapshot.getSnapshot(), subscribe: (listener: () => void) => snapshot.subscribe(listener), } as unknown as SessionBinding['session'] + const retainedFacet = createSnapshotStore(true) const binding: SessionBinding = { sessionId: id, session, eventSource: new MutableSessionEventSource(), ctx: scopeCtx as AgentContext, + facet: () => retainedFacet, } bindings.set(id, binding) scopes.set(id, scopeCtx) diff --git a/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx index 2053ab3659..dbf92af821 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/document-seat.client.spec.tsx @@ -56,7 +56,7 @@ async function boot() { 'conversation.session.header.corner': { kind: 'single', scope: 'session' }, }) await rt.sessions.add({ id: SESSION }) - await rt.sessions.retainFor(rt.ctx, SESSION, { source: 'mainView' }).ready + await rt.sessions.retainFor(rt.ctx, SESSION, { source: 'mainView', facets: { conversation: true } }).ready await rt.mount({ inject: [...resourcesInject], apply: resourcesApply }) const read = vi.fn().mockImplementation(async (_sessionId, _path, range) => ({ ok: true, diff --git a/packages/client/ui-sidebar-right/src/client/session-view.ts b/packages/client/ui-sidebar-right/src/client/session-view.ts index f36bb3f977..f2bcb5e7b5 100644 --- a/packages/client/ui-sidebar-right/src/client/session-view.ts +++ b/packages/client/ui-sidebar-right/src/client/session-view.ts @@ -30,7 +30,7 @@ export class SidebarSessionView { private readonly onDispose: (view: SidebarSessionView) => void, private readonly onTabRelease: (view: SidebarSessionView) => void, ) { - this.reference = sessions.retain(sessionId, { source: 'sidebarView' }) + this.reference = sessions.retain(sessionId, { source: 'sidebarView', facets: { conversation: true } }) void this.reference.ready.catch((error: unknown) => { console.error('Sidebar Session opening failed:', error) }) } diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 1380ed4bab..cecf30aa6f 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -90,7 +90,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o 'conversation.session.header.corner': { kind: 'single', scope: 'session' }, }) await runtime.sessions.add({ id: SESSION }) - let reference = runtime.sessions.retainFor(runtime.ctx, SESSION, { source: 'mainView' }) + let reference = runtime.sessions.retainFor(runtime.ctx, SESSION, { source: 'mainView', facets: { conversation: true } }) const feature = await runtime.mount({ inject: [...inject], apply }) // The frame mounts the Conversation column before the right column, so a // Conversation component's mount effect runs before the seat's. The opener @@ -161,7 +161,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o return controller.active()! } const selectSession = (id: SessionId): void => { - const next = runtime.sessions.retainFor(runtime.ctx, id, { source: 'mainView' }) + const next = runtime.sessions.retainFor(runtime.ctx, id, { source: 'mainView', facets: { conversation: true } }) reference.release() reference = next } diff --git a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx index 6d9c3fcbb5..7fa90b5286 100644 --- a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx +++ b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx @@ -106,7 +106,7 @@ function subagentChatResourceProvider(sessions: ISessions): ResourceProvider<'su const address = parseSubagentChatAddress(resourceAddress) if (address === undefined) throw new Error(`ui-subagent: invalid chat resource address "${resourceAddress}"`) if (isAbortRequested(signal)) return - const reference = sessions.retain(address, { source: 'sidebarChat', signal }) + const reference = sessions.retain(address, { source: 'sidebarChat', facets: { conversation: true }, signal }) try { yield { ok: true, value: { address, reference } } await waitForAbort(signal) diff --git a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx index f7417ea910..db15c9cfe7 100644 --- a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx +++ b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx @@ -117,7 +117,7 @@ describe('Sidebar chat registration', () => { const stream = provider!.open(subagentChatAddress(ADDRESS), { signal: controller.signal })[Symbol.asyncIterator]() expect(await stream.next()).toEqual({ done: false, value: { ok: true, value: { address: ADDRESS, reference } } }) expect(refreshProjections).not.toHaveBeenCalled() - expect(retain).toHaveBeenCalledWith(ADDRESS, { source: 'sidebarChat', signal: controller.signal }) + expect(retain).toHaveBeenCalledWith(ADDRESS, { source: 'sidebarChat', facets: { conversation: true }, signal: controller.signal }) const completion = stream.next() await Promise.resolve() controller.abort() diff --git a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx index c2172a1ab4..b2864b96da 100644 --- a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx @@ -115,7 +115,7 @@ async function bench(nodes: ToolResultNode[]) { prompt: vi.fn(async () => ({ ok: true, value: { accepted: true } })), }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx index 5e6968e33d..79bbe5b297 100644 --- a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx +++ b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx @@ -131,7 +131,7 @@ async function bench(snapshot: ChatSnapshot) { summary: { title: 'S', displayTitle: 'S', cwd: '/w' }, snapshot: { running: snapshot.legacy.runningCalls.length > 0 }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready const layout = { openDetails: vi.fn(), closeDetails: vi.fn() } const openWorkspacePath = vi.fn(async () => ({ ok: true, value: { opened: true } })) ctx.provide('layout', layout as never) diff --git a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx index 0c68634e68..67de82d69e 100644 --- a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx +++ b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx @@ -111,7 +111,7 @@ async function bench(nodes: ToolResultNode[]) { prompt: vi.fn(async () => ({ ok: true, value: { accepted: true } })), }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 2f1f855f03..de29c98331 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -33,8 +33,8 @@ en: 27089341ac2cbcc4 zh: 63d818a53a7c20e9 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: - en: 249d9552d8bef805 - zh: 405b1c636cba8e0b + en: c5b33c471cd2aeae + zh: 697387434049749c /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation: en: 8f170900a4096408 zh: 85332e80adf39403 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 07c9c47366..0db6223311 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -89,6 +89,8 @@ Session rows share their existing action contributions between right-click and t `ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?, options?)` opens a Workspace blank only if no later navigation has superseded the request; New Session opens the same blank as Workspace reopening, so it returns to that blank's unsent draft. `forkSession(id, onCreated?, options?)` creates the child without navigating or superseding a pending navigation; `allowMigration` carries the caller's migration permission. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. +The `mainView` reference retains the `conversation` facet. When the main view leaves a non-blank, unarchived Session, navigation first retains it as a `recentViews` reference without facets, so its history stays loaded and returning to it needs no history request, while Conversation assembly stops until it is shown again. A recent view that is running, awaits the user, or has an unread completion is always kept and does not count; up to 10 other recent views are kept, excluding the main-view Session. Beyond that the least recently left unpinned recent view is released first, then the least recently left pinned one. Returning a Session to the main view, removing or archiving it, or disposing the plugin releases its recent view. + Session and Workspace rows derive their affordances from the browser root's access Hooks: `useWorkspaceAccess` gates a Workspace's create, rename, delete, and reorder verbs, and `useSessionAccess` gates a Session row's rename, fork, drag, pin, archive, and unarchive verbs plus the search result's restore control. A refused verb is not rendered, while every Host request remains authoritative. The Ungrouped header offers no New Session, because it has no backing Workspace to start one in. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent, except that restoring a saved blank first reloads that Session's projections, because listed values are cached hints that can lag its log after an unclean Host exit. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index d83d40ca2d..8317114735 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -89,6 +89,8 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** `ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?, options?)` 仅在请求未被后续导航替代时打开工作区空白 Session;新会话与重新打开工作区打开同一个空白会话,因此会回到该空白会话中未发送的草稿。`forkSession(id, onCreated?, options?)` 创建子会话,不导航,也不替代尚未完成的导航;`allowMigration` 携带调用方的迁移许可。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。 +`mainView` 引用保留 `conversation` 子要素。主视图离开一个非空白、未归档的 Session 时,导航先以不带子要素的 `recentViews` 引用保留它,因此其历史仍已加载,切回时无需再请求历史,而 Conversation 组装在重新显示前停止。运行中、等待用户或完成未读的最近访问会话始终保留且不计数;其余最近访问会话最多保留 10 个,不含主视图 Session。超出时先释放最早离开的未置顶会话,再释放最早离开的置顶会话。Session 回到主视图、被移除或归档,或插件卸载时,会释放其最近访问引用。 + Session 行与 Workspace 行的可用操作来自浏览器根的访问 Hook:`useWorkspaceAccess` 门控 Workspace 的新建、重命名、删除与排序动作,`useSessionAccess` 门控 Session 行的重命名、分叉、拖拽、置顶、归档与取消归档动作,以及搜索结果的恢复控件。被拒绝的动作不渲染,但每个发往 Host 的请求仍以其授权为准。Ungrouped 标题行不提供新建会话,因为它没有可在其中新建会话的后备 Workspace。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影;例外是恢复已保存的空白会话时先重新加载该 Session 的投影,因为列表中的值是缓存提示,Host 非正常退出后可能落后于其日志。 diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 920182b43e..19914aef06 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -120,6 +120,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { declare module '@deepseek-ai/dsh-api-session-controller/client' { interface SessionReferenceSourceMap { workspaceOperation: unknown + /** Recently viewed Sessions kept receiving history after leaving the main view. */ + recentViews: unknown } } diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 42265f1af6..2688d56a63 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -14,6 +14,7 @@ import type { // Type-only: pulls the `agentPreset` Session projection value into this program. import type {} from '@deepseek-ai/dsh-agent-preset-registry/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, @@ -23,6 +24,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { DraftInitializationOptions } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { RowToast } from './contract/slots.ts' import { pinOrderAccounts, pinOrderSource } from './pin-order.ts' +import { RecentSessionViews } from './recent-views.ts' import type { WorkspaceViewStoreActions } from './stores.ts' interface MainSelection { @@ -174,6 +176,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { {}, { persist: { name: 'dsh.sessions.current' } }, ) private mainReference: SessionReference | undefined + private readonly recentViews: RecentSessionViews private restorationNavigation: AbortSignal | undefined /** @@ -193,14 +196,17 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly notify: (toast: RowToast) => void, ) { super(ctx, 'uiWorkspace') + this.recentViews = new RecentSessionViews(sessions, workspaces, ctx.uiSession.sessionStatus) ctx.effect(() => { const stop = this.watchNavigation() + const stopRecentViews = this.recentViews.start() return () => { stop() this.lifetime.abort() const reference = this.mainReference this.mainReference = undefined reference?.release() + stopRecentViews() } }, 'ui-workspace: Workspace navigation policy') } @@ -516,6 +522,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { const previous = this.mainReference this.mainReference = undefined this.selection.set({}) + if (previous !== undefined) this.recentViews.leave(previous.sessionId) previous?.release() this.ctx.layout.selectPanel(null) } @@ -527,7 +534,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { beforeOpen?: (sessionId: SessionId) => void, ): void { signal.throwIfAborted() - const reference = this.sessions.retain(target, { source: 'mainView' }) + const reference = this.sessions.retain(target, { source: 'mainView', facets: { conversation: true } }) try { signal.throwIfAborted() beforeOpen?.(reference.sessionId) @@ -548,6 +555,10 @@ class UiWorkspaceService extends Service implements UiWorkspace { } const previous = this.mainReference this.mainReference = reference + // The new main reference already holds the target, so releasing its recent entry first keeps the + // list within its limit when the main view returns to a recent Session. + this.recentViews.enter(reference.sessionId) + if (previous !== undefined && previous.sessionId !== reference.sessionId) this.recentViews.leave(previous.sessionId) previous?.release() if (panel === 'reveal') this.ctx.layout.selectPanel(null) } diff --git a/packages/client/ui-workspace/src/client/recent-views.ts b/packages/client/ui-workspace/src/client/recent-views.ts new file mode 100644 index 0000000000..8cf0976d13 --- /dev/null +++ b/packages/client/ui-workspace/src/client/recent-views.ts @@ -0,0 +1,146 @@ +/** Recently viewed Sessions that keep their history stream after leaving the main view. */ +import type { + ISessions, SessionListState, SessionReference, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { IWorkspaces } from '@deepseek-ai/dsh-api-workspace-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +// TODO: move to plugin Config once the Client supports plugin configuration. +/** Retained recently viewed Sessions that need no attention, excluding the current main-view Session. */ +const RECENT_VIEW_LIMIT = 10 + +interface RecentView { + readonly sessionId: SessionId + readonly reference: SessionReference +} + +/** + * Attention-ordered retention of non-blank Sessions left by the main view. + * Each entry holds one `recentViews` reference without facets, so its history + * stays loaded but nothing is derived from it. A Session that is running, + * awaits the user, or has an unread completion is neither counted nor evicted; + * beyond the limit, the least recently left unpinned Session is evicted first, + * then the least recently left pinned one. + */ +export class RecentSessionViews { + /** Most recently left first. */ + private entries: RecentView[] = [] + private disposed = false + + /** + * @param sessions - Session Controller that owns the references. + * @param workspaces - Workspace Controller whose archived Sessions leave the list and whose pins order eviction. + * @param status - unified Session UI status deciding which Sessions need attention. + */ + constructor( + private readonly sessions: Pick, + private readonly workspaces: Pick, + private readonly status: ObservableSnapshot, + ) {} + + /** + * Retain a Session the main view is leaving; call before releasing its main-view reference. + * @param sessionId - Session leaving the main view. + */ + leave(sessionId: SessionId): void { + const row = this.sessions.list.getSnapshot().byId[sessionId] + if (row === undefined || row.blank || this.archived(sessionId)) return + const target = this.sessions.subagentAddress(sessionId) ?? sessionId + let reference: SessionReference + try { + reference = this.sessions.retain(target, { source: 'recentViews' }) + } catch (error: unknown) { + // Without the reference the Session is released with its main-view reference; navigation continues. + console.warn('recent Session view retention failed:', error) + return + } + // Retaining publishes the list synchronously, which may reconcile or dispose this list before the + // new entry exists, so the entry is inserted into the entries current after retention returns. + if (this.disposed) { + reference.release() + return + } + const previous = this.entries.find(entry => entry.sessionId === sessionId) + this.entries = [{ sessionId, reference }, ...this.entries.filter(entry => entry !== previous)] + previous?.reference.release() + this.reconcile() + } + + /** + * Release the entry of a Session the main view now shows; call after retaining its main-view reference. + * @param sessionId - Session entering the main view. + */ + enter(sessionId: SessionId): void { + this.remove(sessionId) + } + + /** Drop removed and archived Sessions, then evict entries needing no attention beyond the limit. */ + reconcile(): void { + const { byId } = this.sessions.list.getSnapshot() + for (const entry of [...this.entries]) { + if (byId[entry.sessionId] === undefined || this.archived(entry.sessionId)) this.remove(entry.sessionId) + } + this.evict(byId) + } + + /** + * Reconcile whenever the Session list, Workspace list, or Session UI status changes. + * @returns disposer that stops reconciling and releases every entry. + */ + start(): () => void { + const reconcile = (): void => { this.reconcile() } + const stops = [ + this.sessions.list.subscribe(reconcile), + this.workspaces.list.subscribe(reconcile), + this.status.subscribe(reconcile), + ] + return () => { + for (const stop of stops) stop() + this.dispose() + } + } + + /** Release every entry. */ + dispose(): void { + this.disposed = true + const entries = this.entries + this.entries = [] + for (const entry of entries) entry.reference.release() + } + + private evict(byId: SessionListState['byId']): void { + const status = this.status.getSnapshot() + const counted = this.entries.filter(entry => !needsAttention(entry.sessionId, byId, status)) + const excess = counted.length - RECENT_VIEW_LIMIT + if (excess <= 0) return + const pinned = new Set(this.workspaces.list.getSnapshot().pinnedSessionIds) + // Least recently left first, unpinned before pinned. + const candidates = [ + ...counted.filter(entry => !pinned.has(entry.sessionId)).reverse(), + ...counted.filter(entry => pinned.has(entry.sessionId)).reverse(), + ] + const evicted = new Set(candidates.slice(0, excess)) + this.entries = this.entries.filter(entry => !evicted.has(entry)) + for (const entry of evicted) entry.reference.release() + } + + private remove(sessionId: SessionId): void { + const entry = this.entries.find(candidate => candidate.sessionId === sessionId) + if (entry === undefined) return + this.entries = this.entries.filter(candidate => candidate !== entry) + entry.reference.release() + } + + private archived(sessionId: SessionId): boolean { + return this.workspaces.list.getSnapshot().archivedSessionIds.includes(sessionId) + } +} + +/** Whether the user is likely to return to a Session: it runs, awaits the user, or has an unread completion. */ +function needsAttention(sessionId: SessionId, byId: SessionListState['byId'], status: SessionStatusSnapshot): boolean { + const current = status.get(sessionId) + return byId[sessionId]?.running === true || current?.running === true + || current?.pendingInteraction !== undefined || current?.completionUnread === true +} diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index 15abc997d2..b3b1786c4a 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -780,7 +780,7 @@ describe('ui-workspace apply', () => { toast.dismissToast() ;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>) .display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() - expect(b.retain).toHaveBeenCalledExactlyOnceWith('source', { source: 'mainView' }) + expect(b.retain).toHaveBeenCalledExactlyOnceWith('source', { source: 'mainView', facets: { conversation: true } }) expect(b.selectPanel).toHaveBeenCalledExactlyOnceWith(null) expect(b.fork).toHaveBeenCalledOnce() }) @@ -888,7 +888,7 @@ describe('ui-workspace apply', () => { browser.startSession(undefined, { clearPreviousDraft: false }) expect(startSession).toHaveBeenLastCalledWith(undefined, { clearPreviousDraft: false }) browser.open('session' as never) - expect(b.retain).toHaveBeenCalledWith('session', { source: 'mainView' }) + expect(b.retain).toHaveBeenCalledWith('session', { source: 'mainView', facets: { conversation: true } }) const signal = new AbortController().signal await expect(browser.searchSessions('match', signal)).resolves.toEqual({ items: [{ sessionId: 'session', snippet: 'match' }], diff --git a/packages/client/ui-workspace/tests/recent-views.client.spec.ts b/packages/client/ui-workspace/tests/recent-views.client.spec.ts new file mode 100644 index 0000000000..29d4fe56ec --- /dev/null +++ b/packages/client/ui-workspace/tests/recent-views.client.spec.ts @@ -0,0 +1,190 @@ +import { describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { + ISessions, SessionListState, SessionReference, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { IWorkspaces, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' +import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { brandString } from '@deepseek-ai/dsh-brand' +import { RecentSessionViews } from '../src/client/recent-views.ts' + +const sid = (id: string): SessionId => brandString(id) + +function row(id: SessionId, overrides: Partial = {}): SessionSummary { + return { id, displayTitle: id, running: false, blank: false, updatedAt: 0, retainedBy: {}, ...overrides } +} + +function bench(ids: readonly SessionId[]) { + const list = createSnapshotStore({ + ids: [...ids], byId: Object.fromEntries(ids.map(id => [id, row(id)])), phase: 'ready', projectionsBySession: {}, + }) + const workspaces = createSnapshotStore({ + items: [], archivedSessionIds: [], pinnedSessionIds: [], phase: 'ready', state: 'idle', error: null, + }) + const held = new Map() + // The Session Controller publishes the list synchronously inside retain; navigation reconciles from it. + let onRetain = (): void => {} + const retain = vi.fn((target) => { + const sessionId = typeof target === 'string' ? target : target.childSessionId + held.set(sessionId, (held.get(sessionId) ?? 0) + 1) + onRetain() + let released = false + const release = (): void => { + if (released) return + released = true + held.set(sessionId, (held.get(sessionId) ?? 1) - 1) + } + const binding = { sessionId } as SessionReference['binding'] + return { sessionId, binding, ready: Promise.resolve(binding), release, [Symbol.dispose]: release } + }) + const subagentAddress = vi.fn(() => undefined) + const sessions: Pick = { list, retain, subagentAddress } + const workspaceController: Pick = { list: workspaces } + const status = createSnapshotStore(new Map()) + const recent = new RecentSessionViews(sessions, workspaceController, status) + onRetain = () => { recent.reconcile() } + const update = (id: SessionId, patch: Partial): void => { + const state = list.getSnapshot() + list.set({ ...state, byId: { ...state.byId, [id]: row(id, { ...state.byId[id], ...patch }) } }) + } + const retained = (): SessionId[] => [...held].filter(([, count]) => count > 0).map(([id]) => id) + const setOnRetain = (hook: () => void): void => { onRetain = hook } + const setStatus = (id: SessionId, patch: Partial): void => { + const next = new Map(status.getSnapshot()) + next.set(id, { running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, ...patch }) + status.set(next) + } + return { recent, list, workspaces, retain, subagentAddress, update, retained, setOnRetain, setStatus } +} + +describe('recently viewed Sessions', () => { + it('retains a left Session without facets and releases it when the main view returns to it', () => { + const b = bench([sid('a')]) + b.recent.leave(sid('a')) + expect(b.retain).toHaveBeenCalledExactlyOnceWith(sid('a'), { source: 'recentViews' }) + expect(b.retained()).toEqual([sid('a')]) + b.recent.enter(sid('a')) + expect(b.retained()).toEqual([]) + }) + + it('skips blank, archived, and unlisted Sessions and retains a subagent through its address', () => { + const b = bench([sid('blank'), sid('archived'), sid('child')]) + b.update(sid('blank'), { blank: true }) + b.workspaces.set({ ...b.workspaces.getSnapshot(), archivedSessionIds: [sid('archived')] }) + const address = { parentSessionId: sid('parent'), childSessionId: sid('child'), mode: 'continuable' as const } + b.subagentAddress.mockImplementation(id => id === sid('child') ? address : undefined) + b.recent.leave(sid('blank')) + b.recent.leave(sid('archived')) + b.recent.leave(sid('missing')) + expect(b.retain).not.toHaveBeenCalled() + b.recent.leave(sid('child')) + expect(b.retain).toHaveBeenCalledExactlyOnceWith(address, { source: 'recentViews' }) + }) + + it('keeps one entry per Session when it is left again', () => { + const b = bench([sid('a')]) + b.recent.leave(sid('a')) + b.recent.leave(sid('a')) + expect(b.retain).toHaveBeenCalledTimes(2) + expect(b.retained()).toEqual([sid('a')]) + }) + + it('keeps ten idle Sessions beyond any running ones and evicts the least recently left idle Session', () => { + const ids = Array.from({ length: 13 }, (_, index) => sid(`s${index}`)) + const b = bench(ids) + b.update(sid('s0'), { running: true }) + b.setStatus(sid('s1'), { running: true }) + for (const id of ids.slice(0, 12)) b.recent.leave(id) + expect(b.retained()).toHaveLength(12) + b.recent.leave(sid('s12')) + expect(b.retained()).toHaveLength(12) + expect(b.retained()).toEqual(expect.arrayContaining([sid('s0'), sid('s1')])) + expect(b.retained()).not.toContain(sid('s2')) + b.update(sid('s0'), { running: false }) + b.recent.reconcile() + expect(b.retained()).toHaveLength(11) + expect(b.retained()).not.toContain(sid('s0')) + }) + + it('keeps a new entry when retention reconciles a list already beyond the limit', () => { + const ids = Array.from({ length: 12 }, (_, index) => sid(`r${index}`)) + const b = bench(ids) + for (const id of ids) b.update(id, { running: true }) + for (const id of ids.slice(0, 11)) b.recent.leave(id) + b.recent.leave(ids[11]!) + for (const id of ids) b.update(id, { running: false }) + b.recent.reconcile() + expect(b.retained()).toHaveLength(10) + expect(b.retained()).toContain(ids[11]) + b.recent.dispose() + expect(b.retained()).toEqual([]) + }) + + it('releases a reference retained while the list is disposed and reports a failed retention', () => { + const b = bench([sid('a'), sid('b')]) + b.setOnRetain(() => { b.recent.dispose() }) + b.recent.leave(sid('a')) + expect(b.retained()).toEqual([]) + b.recent.leave(sid('b')) + expect(b.retained()).toEqual([]) + const failure = new Error('retain failed') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const other = bench([sid('c')]) + other.retain.mockImplementationOnce(() => { throw failure }) + other.recent.leave(sid('c')) + expect(warn).toHaveBeenCalledWith('recent Session view retention failed:', failure) + expect(other.retained()).toEqual([]) + warn.mockRestore() + }) + + it('retains a Session left again before releasing its earlier entry', () => { + const b = bench([sid('a')]) + b.recent.leave(sid('a')) + const releaseOrder: string[] = [] + b.setOnRetain(() => { releaseOrder.push(`retained:${String(b.retained().length)}`) }) + b.recent.leave(sid('a')) + expect(releaseOrder).toEqual(['retained:1']) + expect(b.retained()).toEqual([sid('a')]) + }) + + it('neither counts nor evicts Sessions awaiting the user or holding an unread completion until they are read', () => { + const ids = Array.from({ length: 13 }, (_, index) => sid(`u${index}`)) + const b = bench(ids) + b.setStatus(sid('u0'), { pendingInteraction: { key: 'question:1', kind: 'question', sessionId: sid('u0') } as SessionPendingInteraction }) + b.setStatus(sid('u1'), { completionUnread: true }) + b.setStatus(sid('u2'), { completionUnread: true, completionFailed: true }) + for (const id of ids) b.recent.leave(id) + expect(b.retained()).toHaveLength(13) + b.setStatus(sid('u1'), { completionUnread: false }) + b.recent.reconcile() + expect(b.retained()).toHaveLength(12) + expect(b.retained()).not.toContain(sid('u1')) + expect(b.retained()).toEqual(expect.arrayContaining([sid('u0'), sid('u2')])) + }) + + it('evicts pinned Sessions only after every unpinned Session needing no attention', () => { + const ids = Array.from({ length: 12 }, (_, index) => sid(`p${index}`)) + const b = bench(ids) + b.workspaces.set({ ...b.workspaces.getSnapshot(), pinnedSessionIds: [sid('p0'), sid('p1')] }) + for (const id of ids) b.recent.leave(id) + expect(b.retained()).toHaveLength(10) + expect(b.retained()).toEqual(expect.arrayContaining([sid('p0'), sid('p1')])) + expect(b.retained()).not.toContain(sid('p2')) + expect(b.retained()).not.toContain(sid('p3')) + }) + + it('drops removed and archived Sessions on reconcile and releases every entry on dispose', () => { + const b = bench([sid('a'), sid('b'), sid('c')]) + for (const id of [sid('a'), sid('b'), sid('c')]) b.recent.leave(id) + const state = b.list.getSnapshot() + const { [sid('a')]: _removed, ...byId } = state.byId + b.list.set({ ...state, ids: state.ids.filter(id => id !== sid('a')), byId }) + b.workspaces.set({ ...b.workspaces.getSnapshot(), archivedSessionIds: [sid('b')] }) + b.recent.reconcile() + expect(b.retained()).toEqual([sid('c')]) + b.recent.dispose() + expect(b.retained()).toEqual([]) + }) +}) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index ed0ada567b..9fad8685b5 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -95,7 +95,7 @@ describe('session rename through the assembled browser', () => { summary: { title: 'Persisted title', displayTitle: 'Session title', cwd: '/w/alpha' }, session: { rename: vi.fn() }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) @@ -169,7 +169,7 @@ describe('session rename through the assembled browser', () => { summary: { title: '旧标题', displayTitle: '旧标题', cwd: '/w/alpha' }, session: { rename }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) @@ -211,7 +211,7 @@ describe('session rename through the assembled browser', () => { summary: { title: '旧标题', displayTitle: '旧标题', cwd: '/w/alpha' }, session: { rename }, }) - await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready + await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 5696257780..c371dcf02e 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -11,13 +11,14 @@ import type { IWorkspaces, WorkspaceId, WorkspaceSnapshot, WorkspaceView, } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { ClientRemote, DirectoryListing } from '@deepseek-ai/dsh-api-remotes/client' -import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { RemoteError, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { LayoutController } from '@deepseek-ai/dsh-client-ui-layout/client' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { DraftInitializationOptions, SessionInputResolver } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { RowToast } from '../src/client/contract/slots.ts' import { DirectoryBrowseError, UiWorkspaceService } from '../src/client/navigation.ts' import { en, zh } from '../src/client/locales.ts' @@ -303,6 +304,8 @@ function bench(options: BenchOptions = {}) { options.configureSessions?.(sessions) const view = createWorkspaceViewStore().create() const notify = vi.fn<(toast: RowToast) => void>() + const status = new MutableSource(new Map()) + ctx.provide('uiSession', { sessionStatus: status } as never) const uiWorkspace = new UiWorkspaceService( ctx, directoryPicker.remote, @@ -311,7 +314,7 @@ function bench(options: BenchOptions = {}) { view.actions, notify, ) - return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify, requestDraftInitialization } + return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify, requestDraftInitialization, status } } function lastOpening(open: MockInstance): Promise { @@ -334,7 +337,7 @@ describe('UiWorkspaceService', () => { expect(b.workspaces.initializeDefault).not.toHaveBeenCalled() b.workspaces.list.set(workspaceState()) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-default'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-default'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.workspaces.initializeDefault).toHaveBeenCalledExactlyOnceWith(expect.any(AbortSignal)) expect(b.sessions.create).toHaveBeenCalledWith({ workspaceId: wid('default') }) @@ -427,10 +430,100 @@ describe('UiWorkspaceService', () => { const b = bench() b.uiWorkspace.openSession(sid('target')) expect(b.selectPanel).toHaveBeenCalledWith(null) - expect(b.sessions.retain).toHaveBeenCalledWith(sid('target'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledWith(sid('target'), { source: 'mainView', facets: { conversation: true } }) expect(b.sessions.refreshProjections).not.toHaveBeenCalled() }) + it('keeps a left Session as a recent view until navigation returns to it or disposes', async () => { + const b = bench({ sessions: sessionState([summary('a'), summary('b'), summary('blank', { blank: true })]) }) + const live = (): SessionId[] => b.sessions.retained + .filter(item => item.release.mock.calls.length === 0) + .map(item => item.reference.sessionId) + b.uiWorkspace.openSession(sid('a')) + b.uiWorkspace.openSession(sid('b')) + expect(b.sessions.retain).toHaveBeenLastCalledWith(sid('a'), { source: 'recentViews' }) + expect(live()).toEqual([sid('b'), sid('a')]) + b.uiWorkspace.openSession(sid('a')) + expect(live()).toEqual([sid('a'), sid('b')]) + b.uiWorkspace.openSession(sid('blank')) + b.uiWorkspace.openSession(sid('b')) + expect(live()).toEqual([sid('a'), sid('b')]) + await b.ctx.fiber.dispose() + expect(live()).toEqual([]) + }) + + it('keeps ten recent views when the main view returns to one and ignores reselecting the current Session', () => { + const ids = Array.from({ length: 12 }, (_, index) => `r${index}`) + const b = bench({ sessions: sessionState(ids.map(id => summary(id))) }) + const recent = (): SessionId[] => b.sessions.retained + .filter(item => item.release.mock.calls.length === 0 && b.sessions.retain.mock.calls[b.sessions.retained.indexOf(item)]?.[1].source === 'recentViews') + .map(item => item.reference.sessionId) + for (const id of ids.slice(0, 11)) b.uiWorkspace.openSession(sid(id)) + expect(recent()).toHaveLength(10) + expect(recent()).not.toContain(sid('r10')) + b.uiWorkspace.openSession(sid('r5')) + expect(recent()).toHaveLength(10) + expect(recent()).toContain(sid('r10')) + expect(recent()).not.toContain(sid('r5')) + const calls = b.sessions.retain.mock.calls.length + b.uiWorkspace.openSession(sid('r5')) + expect(b.sessions.retain.mock.calls.slice(calls)).toEqual([[sid('r5'), { source: 'mainView', facets: { conversation: true } }]]) + expect(recent()).toHaveLength(10) + }) + + it('returns to a recent view through the same generation without reopening its history', async () => { + const storage = new Map() + vi.stubGlobal('localStorage', { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => { storage.set(key, value) }, + removeItem: (key: string) => { storage.delete(key) }, + clear: () => { storage.clear() }, + }) + const runtime = await SlotTestRuntime.create() + const sessions = runtime.sessions + const opened = vi.fn() + await sessions.add({ id: 'a', initialOpen: opened }) + await sessions.add({ id: 'b' }) + const b = bench() + runtime.ctx.provide('layout', b.layout) + const owner = runtime.ctx.isolate('uiWorkspace').isolate('uiSession') + owner.provide('uiSession', { sessionStatus: b.status } as never) + const uiWorkspace = new UiWorkspaceService( + owner, b.directoryPicker.remote, b.workspaces, sessions, b.view.actions, b.notify, + ) + uiWorkspace.openSession(sid('a')) + const binding = sessions.binding('a') + expect(binding?.facet('conversation').getSnapshot()).toBe(true) + uiWorkspace.openSession(sid('b')) + expect(sessions.binding('a')).toBe(binding) + expect(binding?.facet('conversation').getSnapshot()).toBe(false) + uiWorkspace.openSession(sid('a')) + expect(sessions.binding('a')).toBe(binding) + expect(binding?.facet('conversation').getSnapshot()).toBe(true) + expect(opened).toHaveBeenCalledOnce() + await runtime.dispose() + expect(sessions.retainInfo(sid('a')).getSnapshot().referenceCount).toBe(0) + }) + + it('reconciles recent views from Session and Workspace list changes until disposal', async () => { + const b = bench({ sessions: sessionState([summary('a'), summary('b'), summary('c')]) }) + const live = (id: string): boolean => b.sessions.retained.some((item, index) => item.reference.sessionId === sid(id) + && item.release.mock.calls.length === 0 && b.sessions.retain.mock.calls[index]?.[1].source === 'recentViews') + b.uiWorkspace.openSession(sid('a')) + b.uiWorkspace.openSession(sid('b')) + b.uiWorkspace.openSession(sid('c')) + expect(live('a') && live('b')).toBe(true) + b.workspaces.list.update(state => ({ ...state, archivedSessionIds: [sid('a')] })) + expect(live('a')).toBe(false) + b.sessions.list.set(sessionState([summary('c')])) + expect(live('b')).toBe(false) + b.status.set(new Map([[sid('c'), { running: true, pendingInteraction: undefined, completionUnread: false, completionFailed: false }]])) + await b.ctx.fiber.dispose() + expect(b.sessions.list.listenersSnapshot()).toHaveLength(0) + expect(b.workspaces.list.listenersSnapshot()).toHaveLength(0) + expect(b.status.listenersSnapshot()).toHaveLength(0) + }) + it('keeps the current panel when retaining the target fails', () => { const b = bench() b.sessions.retain.mockImplementationOnce(() => { throw new Error('open failed') }) @@ -466,7 +559,7 @@ describe('UiWorkspaceService', () => { await openingB first.resolve(sid('older')) await openingA - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('newer'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('newer'), { source: 'mainView', facets: { conversation: true } }) expect(prepareB).toHaveBeenCalledExactlyOnceWith(sid('newer')) expect(prepareA).not.toHaveBeenCalled() }) @@ -536,7 +629,7 @@ describe('UiWorkspaceService', () => { b.workspaces.list.set(workspaceState([workspace('a')])) b.sessions.list.set(sessionState()) - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('chosen'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('chosen'), { source: 'mainView', facets: { conversation: true } }) expect(b.sessions.create).not.toHaveBeenCalled() }) @@ -583,7 +676,7 @@ describe('UiWorkspaceService', () => { await b.uiWorkspace.forkSession(sid('source')) created.resolve(sid('chosen')) await opening - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('chosen'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('chosen'), { source: 'mainView', facets: { conversation: true } }) }) it('pins on the Host, then leads the Session in its group and flat saved orders; unpin leaves them', async () => { @@ -760,13 +853,15 @@ describe('UiWorkspaceService', () => { }) b.uiWorkspace.startSession(wid('old')) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenLastCalledWith(sid('created-old'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenLastCalledWith(sid('created-old'), { source: 'mainView', facets: { conversation: true } }) }) b.uiWorkspace.openSession(current.id) b.uiWorkspace.startSession() await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenLastCalledWith(sid('created-current-home'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-current-home'), { source: 'mainView', facets: { conversation: true } }) }) + // Leaving a non-blank Session keeps it as a recent view after the new main view is retained. + expect(b.sessions.retain).toHaveBeenLastCalledWith(current.id, { source: 'recentViews' }) const recentOnly = bench({ sessions: sessionState([current, recent]), workspaces: workspaceState([ @@ -776,7 +871,7 @@ describe('UiWorkspaceService', () => { }) recentOnly.uiWorkspace.startSession() await vi.waitFor(() => { - expect(recentOnly.sessions.retain).toHaveBeenLastCalledWith(sid('created-recent-home'), { source: 'mainView' }) + expect(recentOnly.sessions.retain).toHaveBeenLastCalledWith(sid('created-recent-home'), { source: 'mainView', facets: { conversation: true } }) }) b.sessions.create.mockRejectedValueOnce(new Error('create failed')) const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined) @@ -855,7 +950,7 @@ describe('UiWorkspaceService', () => { if (options === undefined) await vi.waitFor(() => { expect(b.sessions.retain).toHaveBeenCalledOnce() }) else await lastOpening(opening) - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView', facets: { conversation: true } }) expect(b.sessions.binding).not.toHaveBeenCalled() expect(b.requestDraftInitialization).not.toHaveBeenCalled() expect(b.notify).not.toHaveBeenCalled() @@ -1026,7 +1121,7 @@ describe('UiWorkspaceService', () => { ])) b.sessions.list.set(sessionState()) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-newest'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledWith(sid('created-newest'), { source: 'mainView', facets: { conversation: true } }) }) }) @@ -1052,7 +1147,7 @@ describe('UiWorkspaceService', () => { workspaces: workspaceState([workspace('a', [sid('saved')])], archived ? [sid('saved')] : []), }) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.sessions.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: wid('a') }) }) @@ -1063,7 +1158,7 @@ describe('UiWorkspaceService', () => { sessions: sessionState([summary('saved', { blank: true })]), workspaces: workspaceState(), }) - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView', facets: { conversation: true } }) expect(b.sessions.create).not.toHaveBeenCalled() }) @@ -1084,7 +1179,7 @@ describe('UiWorkspaceService', () => { expect(b.sessions.retain).not.toHaveBeenCalled() acquired.resolve(sid('saved')) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView', facets: { conversation: true } }) }) }) @@ -1100,7 +1195,7 @@ describe('UiWorkspaceService', () => { }) if (source === 'saved') { await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('created-a'), { source: 'mainView', facets: { conversation: true } }) }) } else { await expect(b.uiWorkspace.connectWorkspace(wid('a'))).resolves.toBe(sid('created-a')) @@ -1157,7 +1252,7 @@ describe('UiWorkspaceService', () => { workspaces: workspaceState([workspace('a', [sid('saved')])]), }) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.sessions.create.mock.calls).toEqual([[{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'ptc' }]]) }) @@ -1177,7 +1272,7 @@ describe('UiWorkspaceService', () => { }, }) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.sessions.refreshProjections).toHaveBeenCalledExactlyOnceWith(sid('saved')) expect(b.sessions.create.mock.calls).toEqual([[{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'ptc' }]]) @@ -1198,7 +1293,7 @@ describe('UiWorkspaceService', () => { }, }) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.sessions.create.mock.calls).toEqual([ [{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'liangshen' }], @@ -1229,7 +1324,7 @@ describe('UiWorkspaceService', () => { }) b.uiWorkspace.startSession(wid('a'), { agentPreset: 'ptc' }) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('blank'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('blank'), { source: 'mainView', facets: { conversation: true } }) }) expect(b.sessions.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: wid('a'), sessionId: sid('blank'), agentPreset: 'ptc' }) }) @@ -1338,7 +1433,7 @@ describe('UiWorkspaceService', () => { expect(b.sessions.retain).not.toHaveBeenCalled() b.sessions.list.set(b.sessions.list.getSnapshot()) await vi.waitFor(() => { - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('blank'), { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('blank'), { source: 'mainView', facets: { conversation: true } }) }) }) @@ -1447,7 +1542,7 @@ describe('UiWorkspaceService', () => { sessions: sessionState(), }) - expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(address, { source: 'mainView' }) + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(address, { source: 'mainView', facets: { conversation: true } }) expect(b.sessions.refreshProjections).not.toHaveBeenCalled() }) 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 c8ee6344b0..eddd9f669c 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -893,7 +893,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionBinding', - declaration: 'export interface SessionBinding {\n readonly sessionId: SessionId;\n readonly session: SessionFace;\n readonly eventSource: SessionEventSource;\n readonly ctx: AgentContext;\n}', + declaration: 'export interface SessionBinding {\n readonly sessionId: SessionId;\n readonly session: SessionFace;\n readonly eventSource: SessionEventSource;\n readonly ctx: AgentContext;\n facet(facet: SessionRetainFacet): ObservableSnapshot;\n}', }, { name: 'SessionEventChange', @@ -955,13 +955,21 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionRequestId', declaration: 'export type SessionRequestId = Branded<\'session-request-id\'>;', }, + { + name: 'SessionRetainFacet', + declaration: 'export type SessionRetainFacet = Extract;', + }, + { + name: 'SessionRetainFacetMap', + declaration: 'export interface SessionRetainFacetMap {\n}', + }, { name: 'SessionRetainInfo', declaration: 'export interface SessionRetainInfo {\n readonly referenceCount: number;\n readonly retainedBy: Readonly>>;\n}', }, { name: 'SessionRetainOptions', - declaration: 'export interface SessionRetainOptions {\n readonly source: SessionReferenceSource;\n readonly signal?: AbortSignal | undefined;\n}', + declaration: 'export interface SessionRetainOptions {\n readonly source: SessionReferenceSource;\n readonly facets?: Readonly>> | undefined;\n readonly signal?: AbortSignal | undefined;\n}', }, { name: 'SessionSearchResultItem', diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index 0d5d70d0e2..cfc0ac78f1 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -7,10 +7,11 @@ import { import type { AgentContext, ISessions, ProjectionsFace, SessionBinding, SessionFace, SessionListState, SessionEventLikeEntry, SessionLiveEventEntry, SessionSearchResultItem, - SessionReference, SessionReferenceSource, SessionRetainInfo, SessionRetainOptions, + SessionReference, SessionReferenceSource, SessionRetainFacet, SessionRetainInfo, SessionRetainOptions, SessionSnapshot, SessionSummary, SessionTarget, SubmissionHandle, } from '@deepseek-ai/dsh-api-session-controller/client' import { scopeIdentityOf } from '@deepseek-ai/dsh-api-session-controller/src/client/scope.ts' +import { heldFacets, RetainedFacets } from '@deepseek-ai/dsh-api-session-controller/src/client/sessions/facets.ts' import type { SessionRequestId } from '@deepseek-ai/dsh-api-session-controller/types' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -205,6 +206,7 @@ interface SessionGeneration { readonly lifetime: AbortController readonly opening: Promise retention: SessionRetainInfo + readonly facets: RetainedFacets live: boolean } @@ -214,6 +216,9 @@ interface OpeningControl { readonly reject: (error: unknown) => void } +/** Fixture references default to a rendering use, so Conversation assembly runs as it does under a main view. */ +const DEFAULT_TEST_RETAIN: SessionRetainOptions = { source: 'testFixture', facets: { conversation: true } } + function freezeRetainedBy( counts: Partial>, ): SessionRetainInfo['retainedBy'] { @@ -343,6 +348,7 @@ export class TestSessions implements ISessions { for (const [id, generation] of this.generations) { generation.live = false generation.retention = EMPTY_RETAIN_INFO + generation.facets.releaseAll() generation.lifetime.abort(new Error('test Session Controller is disposed')) this.publishRetention(id) } @@ -526,14 +532,14 @@ export class TestSessions implements ISessions { /* jscpd:ignore-start -- The fixture intentionally mirrors production SessionReference acquisition and release semantics. */ retain( target: SessionTarget, - options: SessionRetainOptions = { source: 'testFixture' }, + options: SessionRetainOptions = DEFAULT_TEST_RETAIN, ): SessionReference { - const { source, signal } = options + const { source, signal, facets } = options signal?.throwIfAborted() if (this.closed) throw new Error('test Session Controller is disposed') const id = this.resolveTarget(target) const generation = this.generations.get(id) ?? this.materialize(id, this.require(id)) - const reference = this.retainGeneration(id, generation, source) + const reference = this.retainGeneration(id, generation, source, heldFacets(facets)) try { reference.attachOpening(generation.opening, signal) return reference @@ -577,7 +583,7 @@ export class TestSessions implements ISessions { retainFor( ownerCtx: Context, target: SessionTarget, - options: SessionRetainOptions = { source: 'testFixture' }, + options: SessionRetainOptions = DEFAULT_TEST_RETAIN, ): SessionReference { const reference = this.retain(target, options) try { @@ -720,6 +726,7 @@ export class TestSessions implements ISessions { id: SessionId, generation: SessionGeneration, source: SessionReferenceSource, + facets: readonly SessionRetainFacet[], ): TestSessionReference { const previous = generation.retention generation.retention = Object.freeze({ @@ -729,8 +736,10 @@ export class TestSessions implements ISessions { [source]: (previous.retainedBy[source] ?? 0) + 1, }), }) + generation.facets.retain(facets) const reference = new TestSessionReference(id, generation, () => { if (!generation.live) return + generation.facets.release(facets) const count = generation.retention.referenceCount - 1 const { [source]: sourceCount = 0, ...otherSources } = generation.retention.retainedBy const retainedBy = sourceCount > 1 @@ -774,14 +783,16 @@ export class TestSessions implements ISessions { const opening = Promise.withResolvers() void opening.promise.catch(() => {}) const lifetime = new AbortController() + const facets = new RetainedFacets() const generation: SessionGeneration = { - binding: { sessionId: id, session, eventSource: session.eventSource, ctx }, + binding: { sessionId: id, session, eventSource: session.eventSource, ctx, facet: facet => facets.source(facet) }, snapshot, session, fiber, lifetime, opening: opening.promise, retention: EMPTY_RETAIN_INFO, + facets, live: true, } this.generations.set(id, generation) @@ -789,6 +800,7 @@ export class TestSessions implements ISessions { if (generation.live) { generation.live = false generation.retention = EMPTY_RETAIN_INFO + generation.facets.releaseAll() if (this.generations.get(id) === generation) this.generations.delete(id) this.publishRetention(id) } @@ -816,6 +828,7 @@ export class TestSessions implements ISessions { if (!generation.live) return generation.live = false generation.retention = EMPTY_RETAIN_INFO + generation.facets.releaseAll() /* v8 ignore next -- this synchronous path drops only the generation currently stored for id. */ if (this.generations.get(id) === generation) this.generations.delete(id) generation.lifetime.abort(new Error(`test Session generation "${id}" is released`)) diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index 6958a2d239..60fdb12e74 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -267,6 +267,12 @@ describe('sessions', () => { await Promise.all([first.ready, second.ready]) expect(info.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { testOperation: 2 } }) expect(runtime.sessions.list.getSnapshot().byId[id]?.retainedBy).toEqual({ testOperation: 2 }) + const conversation = first.binding.facet('conversation') + expect(conversation.getSnapshot()).toBe(false) + const rendered = runtime.sessions.retain(id) + expect(conversation.getSnapshot()).toBe(true) + rendered.release() + expect(conversation.getSnapshot()).toBe(false) first.release() expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { testOperation: 1 } }) second.release() From 0b75b3da5a6f94f44ad0001d244df12d9df9143d Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:34:28 +0800 Subject: [PATCH 2/9] docs(notes): state that attention-protected recent views are unbounded --- ...026-11-15-session-retain-facets-and-recent-views.i18n.yaml | 4 ++-- .../2026-11-15-session-retain-facets-and-recent-views.md | 1 + .../2026-11-15-session-retain-facets-and-recent-views.zh.md | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml index 54d281d0d2..d52240492c 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -27,8 +27,8 @@ en: f38a402ebd80a0db zh: c1d7daa160a3b38e /agent-note-session-retain-facets-and-recently-viewed-sessions/consequences: - en: e36a70328e1cb0ea - zh: b291b0dc56ea52bd + en: 67c6647ac966ab95 + zh: f70859f9bc4ec1ac /agent-note-session-retain-facets-and-recently-viewed-sessions/testing: en: 2b263d91908a0354 zh: 9c354292c61cf6d9 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md index 53b4d0686b..b10cad3333 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -108,6 +108,7 @@ ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/na - A background Session switches back without a history request, while it performs no Conversation folding until it is shown again. - An unretained Session keeps the memory of its last assembly until it is shown again or its binding retires. +- The attention-protected recent views have no upper bound: an unread completion stays protected until the user reads it, so each Session that finishes unread while the user is elsewhere keeps its generation, loaded event window, and history follow stream until it is read, marked read, removed, or archived. - Returning to a Session that ran in the background pays one catch-up fold, at most equal to the post-open fold of a fresh opening, without a network request. - A rendering owner that omits `conversation: true` sees an unretained stale or empty snapshot without an error. - `SessionRetainOptions` and `SessionBinding` are pre-stable public interfaces; every consumer and the test fixture changed together. diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md index 64ed9b846d..314e467fee 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -108,6 +108,7 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien - 后台 Session 切回时无需历史请求,而在再次显示之前不做任何 Conversation 折叠。 - 未被保留的 Session 保留其最后一次折叠的内存,直到再次显示或其 binding 退役。 +- 受关注保护的最近访问会话没有总量上限:完成未读会一直受保护直到用户读过,因此用户不在时每个以未读状态完成的 Session 都会保留其 generation、已加载的事件窗口和历史跟随流,直到被读过、标为已读、被移除或归档。 - 切回在后台运行过的 Session 要付出一次补折,最多等同于新打开时的一次打开后折叠,但不走网络。 - 漏写 `conversation: true` 的渲染方会看到未被保留的陈旧或空快照,不会报错。 - `SessionRetainOptions` 与 `SessionBinding` 是 pre-stable 公开接口;所有消费方和测试替身已一同修改。 From bad6605c93f699b4df0ba51e220e37b6435c3b07 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:53:26 +0800 Subject: [PATCH 3/9] refactor(ui-workspace): derive recent views from visit order and make the limit configurable Recent views now hold exactly the Sessions one idempotent sync() selects from the visit order and current snapshots, so navigation reports the shown Session once and the main-view Session never counts. A failed Conversation resumption leaves the binding stale so the next window change rebuilds the whole window. --- ...n-retain-facets-and-recent-views.i18n.yaml | 12 +- ...-session-retain-facets-and-recent-views.md | 19 +- ...ssion-retain-facets-and-recent-views.zh.md | 19 +- .../src/client/conversation/assembly.ts | 28 ++- .../conversation-registry.client.spec.ts | 50 +++++ packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- packages/client/ui-workspace/package.json | 1 + .../client/ui-workspace/src/client/index.ts | 17 +- .../ui-workspace/src/client/navigation.ts | 12 +- .../ui-workspace/src/client/recent-views.ts | 186 +++++++++--------- .../tests/recent-views.client.spec.ts | 132 +++++++------ .../tests/workspaces-service.client.spec.ts | 3 +- pnpm-lock.yaml | 3 + 15 files changed, 290 insertions(+), 200 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml index d52240492c..58b3eef4a9 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -15,14 +15,14 @@ en: a492378a57ed4222 zh: d4fec0ebcff7e502 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-conversation-facet: - en: 63d96b2b1c8583e2 - zh: 2b83f63aa8c74714 + en: f8a2eba56afd7586 + zh: fb8eaa9fab8ef755 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/reference-sources-and-facets: en: 9025a3a0380dbcc0 zh: 9eba187f235dc045 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/recently-viewed-sessions-recentviews: - en: 4534183f258404ae - zh: 4168dc2de669b3bd + en: e1a6728468965961 + zh: 4af21b4c306bec27 /agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: en: f38a402ebd80a0db zh: c1d7daa160a3b38e @@ -30,5 +30,5 @@ en: 67c6647ac966ab95 zh: f70859f9bc4ec1ac /agent-note-session-retain-facets-and-recently-viewed-sessions/testing: - en: 2b263d91908a0354 - zh: 9c354292c61cf6d9 + en: eafd3b46ef5bb59d + zh: 351b9d9721d38ba9 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md index b10cad3333..8481a944f3 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -56,7 +56,7 @@ export interface SessionBinding { `ui-conversation` declares `conversation`: Conversation assembly of the event window and materialization of its views. - `BoundConversation` remains one per binding, and its `snapshot`, `openTurn`, and `target(t)` sources keep stable identities. `UiConversation.binding()` registers the binding's disposal on the Session scope before the binding starts following, and a failed initial fold disposes the binding so the next resolution starts afresh. -- When the facet **starts** being retained, the binding first subscribes to the event window, then resumes in one step: the first fold, or a registry change made while not following, rebuilds the current window once; otherwise contiguous changes received meanwhile apply through the incremental assembler and a revision gap rebuilds the whole window. Any pending rAF is then cancelled and the binding publishes once synchronously, also after that fold fails. A view activated while not following is built from the last folded state and catches up on resume. +- When the facet **starts** being retained, the binding first subscribes to the event window, then resumes in one step: the first fold, or a registry change made while not following, rebuilds the current window once; otherwise contiguous changes received meanwhile apply through the incremental assembler and a revision gap rebuilds the whole window. Any pending rAF is then cancelled and the binding publishes once synchronously, also after that fold fails; a failed fold leaves the binding stale, so the next window change rebuilds the whole window instead of extending a partial fold. A view activated while not following is built from the last folded state and catches up on resume. - When the facet **stops** being retained, the binding unsubscribes from the event window and cancels a pending rAF. The last published snapshot remains readable but no longer updates. While old DOM is still mounted during a switch, its components read that snapshot. A feed dispatch already in progress checks whether the binding still follows, so a release during that dispatch stops folding immediately. - Calling `uiConversation.binding()` while the facet is not retained returns the unretained binding, which reads the last or empty snapshot without throwing. - Two computations follow the `conversation` facet: `BoundConversation` and the [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) quota listener, which neither publishes nor replays notices for failures received while the facet is not retained. Other state on `binding.ctx` that events do not drive (input shell, command popups, historical image URLs, agent preset seat) keeps its existing lifetime. @@ -74,19 +74,20 @@ export interface SessionBinding { ### Recently viewed Sessions: `recentViews` -ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) owns a [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts) list whose entries each hold one `recentViews` reference. +ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) owns a [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts), which holds one `recentViews` reference for each recent view. + +Its state records only what the user did: the order in which Sessions left the main view and the Session the main view shows now. One idempotent `sync()` derives the Sessions to hold from that state and the current Session list, Workspace list, and Session UI status, retains the missing ones, then releases the rest. Navigation calls `show(sessionId)` after retaining the new `mainView` reference and before releasing the previous one; Session list, Workspace list, and status changes call `sync()`. Retaining publishes the Session list synchronously, so a re-entrant `sync()` only marks the state dirty and the running pass repeats until the selection is stable. | Rule | Behavior | |---|---| -| Order | After the new `mainView` reference exists, navigation first releases the new main Session's recent entry, then retains the previous main Session as a recent view, then releases the previous `mainView` reference; the previous Session's reference count never reaches zero, and reselecting the current Session leaves the list unchanged | -| Entry | Leaving retains a new `recentViews` reference before releasing any earlier entry for the same Session and inserts it into the list current after retention returns, because retention publishes the Session list synchronously and may reconcile or dispose the list meanwhile | +| Order | Both `mainView` references are held while `show()` syncs, so the previous Session moves to the recent views before its `mainView` reference is released and its reference count never reaches zero; the main-view Session is never a recent view, and reselecting it leaves the selection unchanged | | Blank | A Session still blank when the main view leaves it does not enter | -| Failure | A failed retention is reported to the console and leaves the Session to be released as without recent views; navigation continues | -| Exit | A removed or archived Session leaves when the Session or Workspace list changes | +| Failure | A failed retention is reported to the console once and the Session leaves the order, so it is released with its `mainView` reference; navigation continues | +| Exit | A removed, archived, or evicted Session leaves the order and returns only when the main view leaves it again | | Attention | A Session that is running, awaits the user, or has an unread completion, as the unified Session UI status reports, is neither counted nor evicted; once it is read and idle it counts again | -| Limit | 10 counted Sessions, excluding the current Session; a module constant with a `TODO` until the Client supports configuration | +| Limit | The ui-workspace `recentViewLimit` configuration, 10 by default, counted Sessions besides the main-view Session | | Eviction | Beyond the limit, the least recently left unpinned Session is evicted first, then the least recently left pinned one; the list is checked again whenever the Session list, Workspace list, or Session UI status changes | -| Disposal | Plugin disposal unsubscribes from both lists and the status and releases every reference | +| Disposal | Plugin disposal unsubscribes from both lists and the status, clears the order, and releases every reference | ## Alternatives considered @@ -118,4 +119,4 @@ ui-workspace [navigation](../../../../packages/client/ui-workspace/src/client/na - [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) covers per-facet counting, notifications only at zero transitions, and facets ending with the generation and root disposal. - [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) covers zero folding while unretained, one synchronous publication on resume, equality with continuous following, activation and registry changes while not following, a release during an in-progress dispatch, an interrupted rAF publication, a failed resumption, and a failed initial fold leaving no subscription. - [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) covers quota notices publishing only while the facet is retained. -- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) and [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) cover the attention and pin rules, synchronous re-entrancy during retention, the navigation order at the limit, list-driven reconciliation, and returning to a recent view through the same generation without reopening history. +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) and [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) cover the attention and pin rules, synchronous re-entrancy during retention, the main-view Session staying out of the count, eviction without automatic return, configuration, list-driven reconciliation, and returning to a recent view through the same generation without reopening history. diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md index 314e467fee..bf70578286 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -56,7 +56,7 @@ export interface SessionBinding { `ui-conversation` 声明 `conversation`:对事件窗口做 Conversation 折叠并物化其视图。 - `BoundConversation` 仍然每个 binding 一个,其 `snapshot`、`openTurn` 和 `target(t)` 数据源保持对象标识稳定。`UiConversation.binding()` 先在 Session 作用域上登记该绑定的清理,再让绑定开始跟随;首次折叠失败时清理该绑定,下次解析重新开始。 -- 子要素**开始**被保留时,绑定先订阅事件窗口,再一步完成恢复:首次折叠或未跟随期间发生的注册表变化会按当前窗口整窗重建一次;否则期间收到的连续变化走增量 assembler,revision 出现缺口时整窗重建。随后取消待发的 rAF 并同步发布一次,这次折叠失败时也是如此。未跟随期间激活的视图基于上一次折叠结果建立,并在恢复时补齐。 +- 子要素**开始**被保留时,绑定先订阅事件窗口,再一步完成恢复:首次折叠或未跟随期间发生的注册表变化会按当前窗口整窗重建一次;否则期间收到的连续变化走增量 assembler,revision 出现缺口时整窗重建。随后取消待发的 rAF 并同步发布一次,这次折叠失败时也是如此;折叠失败会让绑定保持过期状态,下一次窗口变化整窗重建,而不是在部分折叠结果上继续增量。未跟随期间激活的视图基于上一次折叠结果建立,并在恢复时补齐。 - 子要素**停止**被保留时,绑定退订事件窗口并取消待发的 rAF。最后一次发布的快照仍可读取,但不再更新。切换过程中旧 DOM 尚未卸载时,其组件读到的就是这份快照。正在进行的事件分发会检查绑定是否仍在跟随,因此分发中途的释放会立即停止折叠。 - 子要素未被保留时调用 `uiConversation.binding()`,得到的是未被保留的绑定,读取上一次或空的快照,不会抛错。 - 跟随 `conversation` 子要素的计算有两项:`BoundConversation` 与 [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) 的 quota 监听;后者对子要素未被保留期间收到的失败既不发布也不补发提示。`binding.ctx` 上其他不由事件驱动的状态(输入 shell、命令弹层、历史图片 URL、agent preset seat)保持原有生命周期。 @@ -74,19 +74,20 @@ export interface SessionBinding { ### 最近访问会话 `recentViews` -ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) 持有一个 [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts) 列表,每一项持有一条 `recentViews` 引用。 +ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/client/navigation.ts) 持有一个 [`RecentSessionViews`](../../../../packages/client/ui-workspace/src/client/recent-views.ts),为每个最近访问会话持有一条 `recentViews` 引用。 + +它的状态只记录用户做过什么:Session 离开主视图的顺序,以及主视图当前显示的 Session。一个幂等的 `sync()` 根据这些状态和当前的 Session 列表、Workspace 列表与 Session UI 状态算出应持有的 Session,先 retain 缺少的,再释放其余的。导航在 retain 新的 `mainView` 引用之后、释放上一个之前调用 `show(sessionId)`;Session 列表、Workspace 列表和状态变化时调用 `sync()`。retain 会同步发布 Session 列表,因此重入的 `sync()` 只标记状态已变化,正在执行的一轮会重复,直到选择稳定。 | 规则 | 行为 | |---|---| -| 顺序 | 新的 `mainView` 引用就绪后,导航先释放新主 Session 的最近访问项,再把上一个主 Session 保留为最近访问会话,最后释放上一个 `mainView` 引用;上一个 Session 的引用计数不会归零,重复选中当前 Session 时列表保持不变 | -| 入队 | 离开时先 retain 新的 `recentViews` 引用,再释放同一 Session 的旧项,并插入 retain 返回时的当前列表,因为 retain 会同步发布 Session 列表,期间可能触发对账或释放本列表 | +| 顺序 | `show()` 同步时两个 `mainView` 引用都还在,因此上一个 Session 先成为最近访问会话、再释放其 `mainView` 引用,引用计数不会归零;主视图 Session 永远不是最近访问会话,重复选中它时选择保持不变 | | 空白 | 离开时仍是空白的 Session 不入队 | -| 失败 | retain 失败时报告到控制台,该 Session 按没有最近访问时的方式释放,导航继续 | -| 出队 | Session 或 Workspace 列表变化时,被移除或归档的 Session 出队 | +| 失败 | retain 失败时报告到控制台一次,该 Session 离开顺序列表,随其 `mainView` 引用一起释放;导航继续 | +| 出队 | 被移除、归档或淘汰的 Session 离开顺序列表,只有主视图再次离开它时才会回来 | | 关注 | 统一 Session UI 状态显示为运行中、等待用户或完成未读的 Session 既不计数也不淘汰;读过且空闲后重新计数 | -| 上限 | 计数的 Session 最多 10 个,不含当前 Session;用模块常量加 `TODO` 写死,等 Client 支持配置后再改 | +| 上限 | 由 ui-workspace 配置 `recentViewLimit` 决定,默认 10,计数的 Session 不含主视图 Session | | 淘汰 | 超出上限时先淘汰最早离开的未置顶 Session,再淘汰最早离开的置顶 Session;Session 列表、Workspace 列表或 Session UI 状态变化时都会重新检查 | -| 卸载 | 插件卸载时退订两个列表与状态,并释放全部引用 | +| 卸载 | 插件卸载时退订两个列表与状态,清空顺序列表,并释放全部引用 | ## 备选方案 @@ -118,4 +119,4 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien - [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) 覆盖按子要素计数、只在零值变化时通知,以及子要素随 generation 退役与根释放结束。 - [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) 覆盖未被保留时零折叠、恢复时同步发布一次、与持续跟随结果一致、未跟随期间的激活与注册表变化、分发中途的释放、被打断的 rAF 发布、恢复失败,以及首次折叠失败不残留订阅。 - [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) 覆盖 quota 提示只在子要素被保留时发布。 -- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) 与 [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) 覆盖关注与置顶规则、retain 期间的同步重入、达到上限时的导航顺序、由列表变化驱动的对账,以及经由同一 generation 切回最近访问会话且不重新打开历史。 +- [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) 与 [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) 覆盖关注与置顶规则、retain 期间的同步重入、主视图 Session 不计数、淘汰后不自动回来、配置、由列表变化驱动的对账,以及经由同一 generation 切回最近访问会话且不重新打开历史。 diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 748a129258..3eed285da4 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -75,7 +75,10 @@ class BoundConversation implements ConversationBinding { private revision = -1 private frame: number | undefined private following = false - /** Resuming rebuilds the whole window: set until the first fold and by registry changes while not following. */ + /** + * The next window change rebuilds the whole window: set until the first fold, by registry changes while not + * following, and by a failed resumption, whose partial fold must not be extended incrementally. + */ private stale = true private disposeFeed: () => void = () => {} private disposeRetained: () => void = () => {} @@ -166,17 +169,14 @@ class BoundConversation implements ConversationBinding { /** * Fold the window changes received while not following and publish once synchronously: a stale * binding rebuilds the whole window, otherwise contiguous changes fold incrementally and a gap rebuilds. + * A failed fold leaves the binding stale, so the next window change rebuilds the whole window. */ private resume(): void { - const window = this.feed.getSnapshot() try { - if (this.stale) { - this.stale = false - this.revision = window.revision - this.assembler.rebuildRegistry(window.entries, window.hasMore) - } else { - this.accept(window) - } + this.accept(this.feed.getSnapshot()) + } catch (error: unknown) { + this.stale = true + throw error } finally { this.cancelFrame() this.publishing(() => this.assembler.flush()) @@ -188,7 +188,17 @@ class BoundConversation implements ConversationBinding { this.publish(this.assembler.replaceWindow(window.entries, window.hasMore)) } + private rebuildWindow(window: SessionEventWindow): void { + this.revision = window.revision + this.publish(this.assembler.rebuildRegistry(window.entries, window.hasMore)) + this.stale = false + } + private accept(window: SessionEventWindow): void { + if (this.stale) { + this.rebuildWindow(window) + return + } if (window.revision === this.revision) return if (window.revision !== this.revision + 1 || window.change.kind === 'replace') { this.replace(window) 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 3a3a0783de..f0a517a5cf 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -690,6 +690,56 @@ describe('Conversation registries', () => { expect(conversation.openTurn.getSnapshot()).toBe(2) }) + it('rebuilds the whole window on the next change after a resuming fold fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { uiConversation, binding, retained, events, views } = await bootRegistries() + let failTurn: number | undefined + events.register({ + kind: 'turn-probe', + target: 'recovery-probe', + match: (event) => { + if (event.type !== 'turn/start') return null + if (event.data.turn === failTurn) { + failTurn = undefined + throw new Error('one-time failure') + } + return { id: String(event.data.turn), role: 'start' } + }, + start: () => null, + update: context => context.state, + buildViewNode: context => ({ key: context.key, kind: 'turn-probe', id: context.id, target: 'recovery-probe', data: null }), + }) + const idsView: ConversationViewDefinition = { + target: 'recovery-probe', + create: () => { + let ids: readonly string[] = [] + return { + empty: [], + replace: ({ nodes }) => (ids = nodes.map(node => node.id)), + apply: ({ upserts }) => (ids = [...ids, ...upserts.map(node => node.id).filter(id => !ids.includes(id))]), + } + }, + } + views.register(idsView) + await Promise.resolve() + const conversation = uiConversation.binding(binding) + conversation.activate('recovery-probe') + const source = binding.eventSource as MutableSessionEventSource + const start = (turn: number): void => { + source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(turn), time: turn, data: { turn } } }) + } + start(1) + retained.set(false) + start(2) + start(3) + failTurn = 2 + retained.set(true) + expect(errors).toHaveBeenCalled() + start(4) + expect(conversation.snapshot.getSnapshot().views.get('recovery-probe')).toEqual(['1', '2', '3', '4']) + }) + it('reaches the same views on resume as when following every event', async () => { const turnProbe: ConversationNodeDefinition = { kind: 'turn-probe', diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index de29c98331..92ffd98bdc 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -33,8 +33,8 @@ en: 27089341ac2cbcc4 zh: 63d818a53a7c20e9 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: - en: c5b33c471cd2aeae - zh: 697387434049749c + en: fd142e4ec98993fb + zh: 015a058302ad1c95 /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation: en: 8f170900a4096408 zh: 85332e80adf39403 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 0db6223311..4f1429ba5e 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -89,7 +89,7 @@ Session rows share their existing action contributions between right-click and t `ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?, options?)` opens a Workspace blank only if no later navigation has superseded the request; New Session opens the same blank as Workspace reopening, so it returns to that blank's unsent draft. `forkSession(id, onCreated?, options?)` creates the child without navigating or superseding a pending navigation; `allowMigration` carries the caller's migration permission. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. -The `mainView` reference retains the `conversation` facet. When the main view leaves a non-blank, unarchived Session, navigation first retains it as a `recentViews` reference without facets, so its history stays loaded and returning to it needs no history request, while Conversation assembly stops until it is shown again. A recent view that is running, awaits the user, or has an unread completion is always kept and does not count; up to 10 other recent views are kept, excluding the main-view Session. Beyond that the least recently left unpinned recent view is released first, then the least recently left pinned one. Returning a Session to the main view, removing or archiving it, or disposing the plugin releases its recent view. +The `mainView` reference retains the `conversation` facet. When the main view leaves a non-blank, unarchived Session, navigation first retains it as a `recentViews` reference without facets, so its history stays loaded and returning to it needs no history request, while Conversation assembly stops until it is shown again. A recent view that is running, awaits the user, or has an unread completion is always kept and does not count; up to `recentViewLimit` other recent views, 10 by default and set in the plugin's `cordis.yml` configuration, are kept besides the main-view Session. Beyond that the least recently left unpinned recent view is released first, then the least recently left pinned one; a released recent view returns only when the main view leaves that Session again. Returning a Session to the main view, removing or archiving it, or disposing the plugin releases its recent view. Session and Workspace rows derive their affordances from the browser root's access Hooks: `useWorkspaceAccess` gates a Workspace's create, rename, delete, and reorder verbs, and `useSessionAccess` gates a Session row's rename, fork, drag, pin, archive, and unarchive verbs plus the search result's restore control. A refused verb is not rendered, while every Host request remains authoritative. The Ungrouped header offers no New Session, because it has no backing Workspace to start one in. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 8317114735..2c789267f8 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -89,7 +89,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** `ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?, options?)` 仅在请求未被后续导航替代时打开工作区空白 Session;新会话与重新打开工作区打开同一个空白会话,因此会回到该空白会话中未发送的草稿。`forkSession(id, onCreated?, options?)` 创建子会话,不导航,也不替代尚未完成的导航;`allowMigration` 携带调用方的迁移许可。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。 -`mainView` 引用保留 `conversation` 子要素。主视图离开一个非空白、未归档的 Session 时,导航先以不带子要素的 `recentViews` 引用保留它,因此其历史仍已加载,切回时无需再请求历史,而 Conversation 组装在重新显示前停止。运行中、等待用户或完成未读的最近访问会话始终保留且不计数;其余最近访问会话最多保留 10 个,不含主视图 Session。超出时先释放最早离开的未置顶会话,再释放最早离开的置顶会话。Session 回到主视图、被移除或归档,或插件卸载时,会释放其最近访问引用。 +`mainView` 引用保留 `conversation` 子要素。主视图离开一个非空白、未归档的 Session 时,导航先以不带子要素的 `recentViews` 引用保留它,因此其历史仍已加载,切回时无需再请求历史,而 Conversation 组装在重新显示前停止。运行中、等待用户或完成未读的最近访问会话始终保留且不计数;其余最近访问会话最多保留 `recentViewLimit` 个(默认 10,在插件的 `cordis.yml` 配置中设置),不含主视图 Session。超出时先释放最早离开的未置顶会话,再释放最早离开的置顶会话;被释放的最近访问会话只有在主视图再次离开该 Session 时才会回来。Session 回到主视图、被移除或归档,或插件卸载时,会释放其最近访问引用。 Session 行与 Workspace 行的可用操作来自浏览器根的访问 Hook:`useWorkspaceAccess` 门控 Workspace 的新建、重命名、删除与排序动作,`useSessionAccess` 门控 Session 行的重命名、分叉、拖拽、置顶、归档与取消归档动作,以及搜索结果的恢复控件。被拒绝的动作不渲染,但每个发往 Host 的请求仍以其授权为准。Ungrouped 标题行不提供新建会话,因为它没有可在其中新建会话的后备 Workspace。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index a2d05e27b6..76b49598bf 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -56,6 +56,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 19914aef06..1b716d2dc0 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -20,6 +20,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { ISessions, SessionForkError } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -143,13 +144,25 @@ export const inject = ['contextMenus', 'uiSession', 'uiSession.sessionStatus', ] +/** Workspace navigation configuration. */ +export interface Config { + /** Recently viewed Sessions that need no attention kept loaded besides the main-view Session. */ + recentViewLimit?: number +} + +/** Validated Workspace navigation configuration. */ +export const Config: z = z.object({ + recentViewLimit: z.natural().default(10), +}) + /** * Register the browser and picker once their slot declarations are on the * ledger. Inject factories return plain callbacks; data reads use the * framework's global hooks. * @param ctx - client root context. + * @param config - validated navigation configuration. */ -export function apply(ctx: Context): void { +export function apply(ctx: Context, config: Config = Config({})): void { const sessions = ctx.get('sessions') as ISessions const workspaces = ctx.get('workspaces') as IWorkspaces // One viewing-store instance, created here as ui-layout does for its layout @@ -163,6 +176,8 @@ export function apply(ctx: Context): void { const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, notify, + // Schemastery's field default is materialized before Cordis calls apply. + config.recentViewLimit as number, ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list }, diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 2688d56a63..138c4456f3 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -186,6 +186,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). * @param notify - show one notice through the Workspace notice channel. + * @param recentViewLimit - recently viewed Sessions needing no attention kept besides the main-view Session. */ constructor( ctx: Context, @@ -194,9 +195,10 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly sessions: ISessions, private readonly view: Pick, private readonly notify: (toast: RowToast) => void, + recentViewLimit: number, ) { super(ctx, 'uiWorkspace') - this.recentViews = new RecentSessionViews(sessions, workspaces, ctx.uiSession.sessionStatus) + this.recentViews = new RecentSessionViews(sessions, workspaces, ctx.uiSession.sessionStatus, recentViewLimit) ctx.effect(() => { const stop = this.watchNavigation() const stopRecentViews = this.recentViews.start() @@ -522,7 +524,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { const previous = this.mainReference this.mainReference = undefined this.selection.set({}) - if (previous !== undefined) this.recentViews.leave(previous.sessionId) + this.recentViews.show(undefined) previous?.release() this.ctx.layout.selectPanel(null) } @@ -555,10 +557,8 @@ class UiWorkspaceService extends Service implements UiWorkspace { } const previous = this.mainReference this.mainReference = reference - // The new main reference already holds the target, so releasing its recent entry first keeps the - // list within its limit when the main view returns to a recent Session. - this.recentViews.enter(reference.sessionId) - if (previous !== undefined && previous.sessionId !== reference.sessionId) this.recentViews.leave(previous.sessionId) + // Both main references are held here, so the previous Session moves to the recent views without a gap. + this.recentViews.show(reference.sessionId) previous?.release() if (panel === 'reveal') this.ctx.layout.selectPanel(null) } diff --git a/packages/client/ui-workspace/src/client/recent-views.ts b/packages/client/ui-workspace/src/client/recent-views.ts index 8cf0976d13..aee06111d8 100644 --- a/packages/client/ui-workspace/src/client/recent-views.ts +++ b/packages/client/ui-workspace/src/client/recent-views.ts @@ -2,140 +2,142 @@ import type { ISessions, SessionListState, SessionReference, } from '@deepseek-ai/dsh-api-session-controller/client' -import type { IWorkspaces } from '@deepseek-ai/dsh-api-workspace-controller/client' +import type { IWorkspaces, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' -// TODO: move to plugin Config once the Client supports plugin configuration. -/** Retained recently viewed Sessions that need no attention, excluding the current main-view Session. */ -const RECENT_VIEW_LIMIT = 10 - -interface RecentView { - readonly sessionId: SessionId - readonly reference: SessionReference -} - /** * Attention-ordered retention of non-blank Sessions left by the main view. - * Each entry holds one `recentViews` reference without facets, so its history - * stays loaded but nothing is derived from it. A Session that is running, - * awaits the user, or has an unread completion is neither counted nor evicted; - * beyond the limit, the least recently left unpinned Session is evicted first, - * then the least recently left pinned one. + * + * The state records only what the user did: the order in which Sessions left the main view and the Session it + * shows now. {@link RecentSessionViews.sync} derives the Sessions to hold from that state and the current Session, + * Workspace, and status snapshots, then retains the missing ones before releasing the rest. Each held Session has + * one `recentViews` reference without facets, so its history stays loaded but nothing is derived from it. + * + * A Session that is running, awaits the user, or has an unread completion is neither counted nor evicted; beyond + * the limit, the least recently left unpinned Session is evicted first, then the least recently left pinned one. + * An evicted, removed, archived, or blank Session also leaves the order, so it returns only when the main view + * leaves it again. */ export class RecentSessionViews { - /** Most recently left first. */ - private entries: RecentView[] = [] - private disposed = false + /** Sessions the main view left that are still candidates, most recently left first. */ + private order: SessionId[] = [] + private current: SessionId | undefined + private readonly held = new Map() + private syncing = false + /** Incremented by every sync request, so a running pass repeats while requests arrive during it. */ + private requests = 0 /** * @param sessions - Session Controller that owns the references. * @param workspaces - Workspace Controller whose archived Sessions leave the list and whose pins order eviction. * @param status - unified Session UI status deciding which Sessions need attention. + * @param limit - Sessions needing no attention kept besides the main-view Session. */ constructor( private readonly sessions: Pick, private readonly workspaces: Pick, private readonly status: ObservableSnapshot, + private readonly limit: number, ) {} /** - * Retain a Session the main view is leaving; call before releasing its main-view reference. - * @param sessionId - Session leaving the main view. + * Record the Session the main view shows now and sync; call after retaining its main-view reference and before + * releasing the previous one, so the previous Session is retained here first. + * @param sessionId - Session the main view shows, or undefined when it shows none. */ - leave(sessionId: SessionId): void { - const row = this.sessions.list.getSnapshot().byId[sessionId] - if (row === undefined || row.blank || this.archived(sessionId)) return - const target = this.sessions.subagentAddress(sessionId) ?? sessionId - let reference: SessionReference - try { - reference = this.sessions.retain(target, { source: 'recentViews' }) - } catch (error: unknown) { - // Without the reference the Session is released with its main-view reference; navigation continues. - console.warn('recent Session view retention failed:', error) - return + show(sessionId: SessionId | undefined): void { + const previous = this.current + if (previous !== undefined && previous !== sessionId) { + this.order = [previous, ...this.order.filter(id => id !== previous)] } - // Retaining publishes the list synchronously, which may reconcile or dispose this list before the - // new entry exists, so the entry is inserted into the entries current after retention returns. - if (this.disposed) { - reference.release() - return - } - const previous = this.entries.find(entry => entry.sessionId === sessionId) - this.entries = [{ sessionId, reference }, ...this.entries.filter(entry => entry !== previous)] - previous?.reference.release() - this.reconcile() + if (sessionId !== undefined) this.order = this.order.filter(id => id !== sessionId) + this.current = sessionId + this.sync() } /** - * Release the entry of a Session the main view now shows; call after retaining its main-view reference. - * @param sessionId - Session entering the main view. - */ - enter(sessionId: SessionId): void { - this.remove(sessionId) - } - - /** Drop removed and archived Sessions, then evict entries needing no attention beyond the limit. */ - reconcile(): void { - const { byId } = this.sessions.list.getSnapshot() - for (const entry of [...this.entries]) { - if (byId[entry.sessionId] === undefined || this.archived(entry.sessionId)) this.remove(entry.sessionId) - } - this.evict(byId) - } - - /** - * Reconcile whenever the Session list, Workspace list, or Session UI status changes. - * @returns disposer that stops reconciling and releases every entry. + * Sync whenever the Session list, Workspace list, or Session UI status changes. + * @returns disposer that stops syncing and releases every held Session. */ start(): () => void { - const reconcile = (): void => { this.reconcile() } + const sync = (): void => { this.sync() } const stops = [ - this.sessions.list.subscribe(reconcile), - this.workspaces.list.subscribe(reconcile), - this.status.subscribe(reconcile), + this.sessions.list.subscribe(sync), + this.workspaces.list.subscribe(sync), + this.status.subscribe(sync), ] return () => { for (const stop of stops) stop() - this.dispose() + this.order = [] + this.current = undefined + this.sync() } } - /** Release every entry. */ - dispose(): void { - this.disposed = true - const entries = this.entries - this.entries = [] - for (const entry of entries) entry.reference.release() + /** + * Hold exactly the Sessions the current state selects, retaining before releasing. Retaining publishes the + * Session list synchronously, so a re-entrant call only records its request and the running sync repeats. + */ + sync(): void { + this.requests++ + if (this.syncing) return + this.syncing = true + try { + let handled: number + do { + handled = this.requests + this.order = this.selected() + const wanted = new Set(this.order) + for (const sessionId of this.order) { + if (!this.held.has(sessionId)) this.acquire(sessionId) + } + for (const [sessionId, reference] of [...this.held]) { + if (wanted.has(sessionId)) continue + this.held.delete(sessionId) + reference.release() + } + } while (this.requests !== handled) + } finally { + this.syncing = false + } } - private evict(byId: SessionListState['byId']): void { + /** The candidates to keep, in order: every eligible Session needing attention plus the first `limit` others. */ + private selected(): SessionId[] { + const { byId } = this.sessions.list.getSnapshot() + const workspaces = this.workspaces.list.getSnapshot() const status = this.status.getSnapshot() - const counted = this.entries.filter(entry => !needsAttention(entry.sessionId, byId, status)) - const excess = counted.length - RECENT_VIEW_LIMIT - if (excess <= 0) return - const pinned = new Set(this.workspaces.list.getSnapshot().pinnedSessionIds) - // Least recently left first, unpinned before pinned. - const candidates = [ - ...counted.filter(entry => !pinned.has(entry.sessionId)).reverse(), - ...counted.filter(entry => pinned.has(entry.sessionId)).reverse(), - ] - const evicted = new Set(candidates.slice(0, excess)) - this.entries = this.entries.filter(entry => !evicted.has(entry)) - for (const entry of evicted) entry.reference.release() + const eligible = this.order.filter(id => id !== this.current && isEligible(id, byId, workspaces)) + const counted = eligible.filter(id => !needsAttention(id, byId, status)) + const countedIds = new Set(counted) + const pinned = new Set(workspaces.pinnedSessionIds) + // Pinned Sessions take the limit first, so eviction reaches them only after every unpinned Session. + const kept = new Set([ + ...counted.filter(id => pinned.has(id)), + ...counted.filter(id => !pinned.has(id)), + ].slice(0, this.limit)) + return eligible.filter(id => kept.has(id) || !countedIds.has(id)) } - private remove(sessionId: SessionId): void { - const entry = this.entries.find(candidate => candidate.sessionId === sessionId) - if (entry === undefined) return - this.entries = this.entries.filter(candidate => candidate !== entry) - entry.reference.release() + private acquire(sessionId: SessionId): void { + const target = this.sessions.subagentAddress(sessionId) ?? sessionId + try { + this.held.set(sessionId, this.sessions.retain(target, { source: 'recentViews' })) + } catch (error: unknown) { + // Without the reference the Session is released with its main-view reference; navigation continues. + console.warn('recent Session view retention failed:', error) + this.order = this.order.filter(id => id !== sessionId) + this.requests++ + } } +} - private archived(sessionId: SessionId): boolean { - return this.workspaces.list.getSnapshot().archivedSessionIds.includes(sessionId) - } +/** Whether a left Session may be kept: it is listed, not blank, and not archived. */ +function isEligible(sessionId: SessionId, byId: SessionListState['byId'], workspaces: WorkspaceSnapshot): boolean { + const row = byId[sessionId] + return row !== undefined && !row.blank && !workspaces.archivedSessionIds.includes(sessionId) } /** Whether the user is likely to return to a Session: it runs, awaits the user, or has an unread completion. */ diff --git a/packages/client/ui-workspace/tests/recent-views.client.spec.ts b/packages/client/ui-workspace/tests/recent-views.client.spec.ts index 29d4fe56ec..f859b4bd49 100644 --- a/packages/client/ui-workspace/tests/recent-views.client.spec.ts +++ b/packages/client/ui-workspace/tests/recent-views.client.spec.ts @@ -8,6 +8,7 @@ import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-clie import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { brandString } from '@deepseek-ai/dsh-brand' +import { Config } from '../src/client/index.ts' import { RecentSessionViews } from '../src/client/recent-views.ts' const sid = (id: string): SessionId => brandString(id) @@ -43,8 +44,8 @@ function bench(ids: readonly SessionId[]) { const sessions: Pick = { list, retain, subagentAddress } const workspaceController: Pick = { list: workspaces } const status = createSnapshotStore(new Map()) - const recent = new RecentSessionViews(sessions, workspaceController, status) - onRetain = () => { recent.reconcile() } + const recent = new RecentSessionViews(sessions, workspaceController, status, 10) + const stop = recent.start() const update = (id: SessionId, patch: Partial): void => { const state = list.getSnapshot() list.set({ ...state, byId: { ...state.byId, [id]: row(id, { ...state.byId[id], ...patch }) } }) @@ -56,17 +57,24 @@ function bench(ids: readonly SessionId[]) { next.set(id, { running: false, pendingInteraction: undefined, completionUnread: false, completionFailed: false, ...patch }) status.set(next) } - return { recent, list, workspaces, retain, subagentAddress, update, retained, setOnRetain, setStatus } + /** Show each Session in the main view in turn, then show `last`. */ + const visit = (ids: readonly SessionId[], last?: SessionId): void => { + for (const id of ids) recent.show(id) + recent.show(last) + } + return { recent, stop, list, workspaces, retain, subagentAddress, update, retained, setOnRetain, setStatus, visit } } describe('recently viewed Sessions', () => { - it('retains a left Session without facets and releases it when the main view returns to it', () => { - const b = bench([sid('a')]) - b.recent.leave(sid('a')) + it('holds a left Session without facets and releases it when the main view returns to it', () => { + const b = bench([sid('a'), sid('b')]) + b.visit([sid('a')], sid('b')) expect(b.retain).toHaveBeenCalledExactlyOnceWith(sid('a'), { source: 'recentViews' }) expect(b.retained()).toEqual([sid('a')]) - b.recent.enter(sid('a')) - expect(b.retained()).toEqual([]) + b.recent.show(sid('a')) + expect(b.retained()).toEqual([sid('b')]) + b.recent.show(sid('a')) + expect(b.retain).toHaveBeenCalledTimes(2) }) it('skips blank, archived, and unlisted Sessions and retains a subagent through its address', () => { @@ -75,90 +83,78 @@ describe('recently viewed Sessions', () => { b.workspaces.set({ ...b.workspaces.getSnapshot(), archivedSessionIds: [sid('archived')] }) const address = { parentSessionId: sid('parent'), childSessionId: sid('child'), mode: 'continuable' as const } b.subagentAddress.mockImplementation(id => id === sid('child') ? address : undefined) - b.recent.leave(sid('blank')) - b.recent.leave(sid('archived')) - b.recent.leave(sid('missing')) + b.visit([sid('blank'), sid('archived'), sid('missing')]) expect(b.retain).not.toHaveBeenCalled() - b.recent.leave(sid('child')) + b.visit([sid('child')]) expect(b.retain).toHaveBeenCalledExactlyOnceWith(address, { source: 'recentViews' }) }) - it('keeps one entry per Session when it is left again', () => { - const b = bench([sid('a')]) - b.recent.leave(sid('a')) - b.recent.leave(sid('a')) - expect(b.retain).toHaveBeenCalledTimes(2) - expect(b.retained()).toEqual([sid('a')]) - }) - it('keeps ten idle Sessions beyond any running ones and evicts the least recently left idle Session', () => { const ids = Array.from({ length: 13 }, (_, index) => sid(`s${index}`)) const b = bench(ids) b.update(sid('s0'), { running: true }) b.setStatus(sid('s1'), { running: true }) - for (const id of ids.slice(0, 12)) b.recent.leave(id) + b.visit(ids.slice(0, 12)) expect(b.retained()).toHaveLength(12) - b.recent.leave(sid('s12')) + b.visit([sid('s12')]) expect(b.retained()).toHaveLength(12) expect(b.retained()).toEqual(expect.arrayContaining([sid('s0'), sid('s1')])) expect(b.retained()).not.toContain(sid('s2')) b.update(sid('s0'), { running: false }) - b.recent.reconcile() expect(b.retained()).toHaveLength(11) expect(b.retained()).not.toContain(sid('s0')) }) - it('keeps a new entry when retention reconciles a list already beyond the limit', () => { - const ids = Array.from({ length: 12 }, (_, index) => sid(`r${index}`)) + it('does not bring an evicted Session back when room frees up', () => { + const ids = Array.from({ length: 12 }, (_, index) => sid(`e${index}`)) const b = bench(ids) - for (const id of ids) b.update(id, { running: true }) - for (const id of ids.slice(0, 11)) b.recent.leave(id) - b.recent.leave(ids[11]!) - for (const id of ids) b.update(id, { running: false }) - b.recent.reconcile() - expect(b.retained()).toHaveLength(10) - expect(b.retained()).toContain(ids[11]) - b.recent.dispose() - expect(b.retained()).toEqual([]) + b.visit(ids.slice(0, 11)) + expect(b.retained()).not.toContain(sid('e0')) + b.workspaces.set({ ...b.workspaces.getSnapshot(), archivedSessionIds: [sid('e5')] }) + expect(b.retained()).toHaveLength(9) + expect(b.retained()).not.toContain(sid('e0')) }) - it('releases a reference retained while the list is disposed and reports a failed retention', () => { - const b = bench([sid('a'), sid('b')]) - b.setOnRetain(() => { b.recent.dispose() }) - b.recent.leave(sid('a')) - expect(b.retained()).toEqual([]) - b.recent.leave(sid('b')) - expect(b.retained()).toEqual([]) + it('keeps the main-view Session out of the count when the list reconciles during retention', () => { + const ids = Array.from({ length: 12 }, (_, index) => sid(`m${index}`)) + const b = bench(ids) + b.visit(ids.slice(0, 10), sid('m10')) + expect(b.retained()).toHaveLength(10) + b.setOnRetain(() => { b.update(sid('m3'), { title: 'touched' }) }) + b.recent.show(sid('m3')) + expect(b.retained()).toHaveLength(10) + expect(b.retained()).toEqual(expect.arrayContaining([sid('m1'), sid('m10')])) + expect(b.retained()).not.toContain(sid('m3')) + }) + + it('retains before releasing and reports a failed retention without retrying it', () => { + const b = bench([sid('a'), sid('b'), sid('c')]) + b.visit([sid('a')], sid('b')) + const order: string[] = [] + b.setOnRetain(() => { order.push(`retained with ${String(b.retained().length)} held`) }) + b.recent.show(sid('a')) + expect(order).toEqual(['retained with 2 held']) + expect(b.retained()).toEqual([sid('b')]) const failure = new Error('retain failed') const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const other = bench([sid('c')]) - other.retain.mockImplementationOnce(() => { throw failure }) - other.recent.leave(sid('c')) + b.retain.mockImplementationOnce(() => { throw failure }) + b.recent.show(sid('c')) + expect(warn).toHaveBeenCalledOnce() expect(warn).toHaveBeenCalledWith('recent Session view retention failed:', failure) - expect(other.retained()).toEqual([]) + b.update(sid('a'), { title: 'touched' }) + expect(b.retained()).toEqual([sid('b')]) warn.mockRestore() }) - it('retains a Session left again before releasing its earlier entry', () => { - const b = bench([sid('a')]) - b.recent.leave(sid('a')) - const releaseOrder: string[] = [] - b.setOnRetain(() => { releaseOrder.push(`retained:${String(b.retained().length)}`) }) - b.recent.leave(sid('a')) - expect(releaseOrder).toEqual(['retained:1']) - expect(b.retained()).toEqual([sid('a')]) - }) - it('neither counts nor evicts Sessions awaiting the user or holding an unread completion until they are read', () => { const ids = Array.from({ length: 13 }, (_, index) => sid(`u${index}`)) const b = bench(ids) b.setStatus(sid('u0'), { pendingInteraction: { key: 'question:1', kind: 'question', sessionId: sid('u0') } as SessionPendingInteraction }) b.setStatus(sid('u1'), { completionUnread: true }) b.setStatus(sid('u2'), { completionUnread: true, completionFailed: true }) - for (const id of ids) b.recent.leave(id) + b.visit(ids) expect(b.retained()).toHaveLength(13) b.setStatus(sid('u1'), { completionUnread: false }) - b.recent.reconcile() expect(b.retained()).toHaveLength(12) expect(b.retained()).not.toContain(sid('u1')) expect(b.retained()).toEqual(expect.arrayContaining([sid('u0'), sid('u2')])) @@ -168,23 +164,33 @@ describe('recently viewed Sessions', () => { const ids = Array.from({ length: 12 }, (_, index) => sid(`p${index}`)) const b = bench(ids) b.workspaces.set({ ...b.workspaces.getSnapshot(), pinnedSessionIds: [sid('p0'), sid('p1')] }) - for (const id of ids) b.recent.leave(id) + b.visit(ids) expect(b.retained()).toHaveLength(10) expect(b.retained()).toEqual(expect.arrayContaining([sid('p0'), sid('p1')])) expect(b.retained()).not.toContain(sid('p2')) expect(b.retained()).not.toContain(sid('p3')) }) - it('drops removed and archived Sessions on reconcile and releases every entry on dispose', () => { - const b = bench([sid('a'), sid('b'), sid('c')]) - for (const id of [sid('a'), sid('b'), sid('c')]) b.recent.leave(id) + it('drops removed and archived Sessions and releases everything when stopped, even during retention', () => { + const b = bench([sid('a'), sid('b'), sid('c'), sid('d')]) + b.visit([sid('a'), sid('b'), sid('c')]) const state = b.list.getSnapshot() const { [sid('a')]: _removed, ...byId } = state.byId b.list.set({ ...state, ids: state.ids.filter(id => id !== sid('a')), byId }) b.workspaces.set({ ...b.workspaces.getSnapshot(), archivedSessionIds: [sid('b')] }) - b.recent.reconcile() expect(b.retained()).toEqual([sid('c')]) - b.recent.dispose() + b.recent.show(sid('d')) + b.setOnRetain(() => { b.stop() }) + b.recent.show(undefined) + expect(b.retain).toHaveBeenLastCalledWith(sid('d'), { source: 'recentViews' }) expect(b.retained()).toEqual([]) }) }) + +describe('recent view configuration', () => { + it('keeps ten recent views by default and rejects a negative limit', () => { + expect(Config({}).recentViewLimit).toBe(10) + expect(Config({ recentViewLimit: 3 }).recentViewLimit).toBe(3) + expect(() => Config({ recentViewLimit: -1 })).toThrow() + }) +}) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index c371dcf02e..aaf519e17f 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -313,6 +313,7 @@ function bench(options: BenchOptions = {}) { sessions, view.actions, notify, + 10, ) return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify, requestDraftInitialization, status } } @@ -489,7 +490,7 @@ describe('UiWorkspaceService', () => { const owner = runtime.ctx.isolate('uiWorkspace').isolate('uiSession') owner.provide('uiSession', { sessionStatus: b.status } as never) const uiWorkspace = new UiWorkspaceService( - owner, b.directoryPicker.remote, b.workspaces, sessions, b.view.actions, b.notify, + owner, b.directoryPicker.remote, b.workspaces, sessions, b.view.actions, b.notify, 10, ) uiWorkspace.openSession(sid('a')) const binding = sessions.binding('a') diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c47d9d1865..0c11bfeea1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7737,6 +7737,9 @@ importers: '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../util/workspace-path + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery clsx: specifier: ^2.0.0 version: 2.1.1 From bf58ff25f4a9820001e9f6bc3540bccfb914c4d9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:12:17 +0800 Subject: [PATCH 4/9] refactor(session-controller): report facet counts through retainInfo instead of SessionBinding SessionBinding stays unchanged; SessionRetainInfo gains optional retainedFacets counts beside retainedBy, and owners derive their facet from retainInfo and the current binding. Adds the upgrade guide for Client plugins that render a Session they retain, and updates two web e2e expectations: a recently viewed Session now keeps its right Sidebar view state when the main view returns to it. --- ...n-retain-facets-and-recent-views.i18n.yaml | 12 +-- ...-session-retain-facets-and-recent-views.md | 12 ++- ...ssion-retain-facets-and-recent-views.zh.md | 12 ++- .../tests/details-session-lifecycle.e2e.ts | 5 +- apps/web/tests/sidebar-right.e2e.ts | 3 +- .../guide.i18n.yaml | 16 ++++ .../guide.md | 26 ++++++ .../guide.zh.md | 26 ++++++ .../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/sessions.ts | 5 + .../src/client/sessions/facets.ts | 93 +++++-------------- .../src/client/sessions/service.ts | 44 ++++----- .../tests/reference-ownership.client.spec.ts | 43 +++------ packages/client/ui-chat/src/client/apply.ts | 22 +++-- .../src/client/conversation/assembly.ts | 15 ++- .../conversation-registry.client.spec.ts | 8 +- .../tests/acknowledge.client.spec.ts | 5 +- .../tests/ui-session.client.spec.ts | 2 - .../tests/workspaces-service.client.spec.ts | 6 +- .../src/client/api-catalog.ts | 4 +- .../client-runtime/src/sessions.ts | 34 ++++--- .../tests/runtime.client.spec.tsx | 7 +- .../sidebar.expected.md | 6 +- 25 files changed, 218 insertions(+), 196 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml index 58b3eef4a9..c78426252b 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -12,8 +12,8 @@ en: c78a249d157157ea zh: bca420c14a3c8da7 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/session-retain-and-facets: - en: a492378a57ed4222 - zh: d4fec0ebcff7e502 + en: aa30c6c943fd1844 + zh: 6fcfd9b2e42bab7e /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-conversation-facet: en: f8a2eba56afd7586 zh: fb8eaa9fab8ef755 @@ -24,11 +24,11 @@ en: e1a6728468965961 zh: 4af21b4c306bec27 /agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: - en: f38a402ebd80a0db - zh: c1d7daa160a3b38e + en: d069b934184f3e56 + zh: fb407797d23e8366 /agent-note-session-retain-facets-and-recently-viewed-sessions/consequences: - en: 67c6647ac966ab95 - zh: f70859f9bc4ec1ac + en: 3340bc5545d66d4c + zh: 7ecd86cd570f6bf4 /agent-note-session-retain-facets-and-recently-viewed-sessions/testing: en: eafd3b46ef5bb59d zh: 351b9d9721d38ba9 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md index 8481a944f3..21194dafa4 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -34,10 +34,10 @@ export interface SessionRetainOptions { readonly signal?: AbortSignal | undefined } -export interface SessionBinding { +export interface SessionRetainInfo { // existing members unchanged - /** Whether any live reference retains `facet`; identity-stable per binding and facet. */ - facet(facet: SessionRetainFacet): ObservableSnapshot + /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ + readonly retainedFacets?: Readonly>> } ``` @@ -46,7 +46,7 @@ export interface SessionBinding { | Declaration | The owning package adds a facet to `SessionRetainFacetMap` through declaration merging; the Controller assigns no meaning to any facet | | Omission | An absent key is not retained; facets have no default | | Immutability | A reference's facet set is fixed at creation; changing the set retains a new reference before releasing the old one | -| Counting | [`RetainedFacets`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet for each generation; a change between zero and nonzero notifies `binding.facet(name)` observers synchronously, before `retainInfo` and list observers hear the same change; retiring the generation ends every facet | +| Counting | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet in the generation's `SessionRetainInfo`, beside the per-source `retainedBy` counts, and `retainInfo(id)` publishes every change; owners derive whether their facet is retained from that snapshot and the current binding, so `SessionBinding` is unchanged; retiring the generation clears every count | | Dependencies | The Controller does not validate dependencies between facets; callers are responsible | | `using()` | Signature unchanged; a borrowed reference serves one operation, and callers omit `facets` | | `retainAgentScope` | Retains no facets | @@ -97,6 +97,8 @@ Its state records only what the user did: the order in which Sessions left the m **Owner-declared facet defaults at runtime.** This requires a Controller runtime registry plus recounting across load order and HMR, while the rule that an omitted facet is not retained suffices. +**Expose a facet observable on `SessionBinding`.** A new required `SessionBinding` member breaks every hand-built binding, including third-party test fakes, while facet counts are local reference counts that `retainInfo` already publishes beside the per-source counts. + **Make `events` a facet.** A Session without its connection can do nothing, and the only connection-free use, the Gateway, already has its own internal entry. **Keep background Session DOM.** React 18 has no ``; K hidden subtrees pay layout, memory, and subscription costs and conflict with the single-Session `session-maybe` binding. @@ -112,7 +114,7 @@ Its state records only what the user did: the order in which Sessions left the m - The attention-protected recent views have no upper bound: an unread completion stays protected until the user reads it, so each Session that finishes unread while the user is elsewhere keeps its generation, loaded event window, and history follow stream until it is read, marked read, removed, or archived. - Returning to a Session that ran in the background pays one catch-up fold, at most equal to the post-open fold of a fresh opening, without a network request. - A rendering owner that omits `conversation: true` sees an unretained stale or empty snapshot without an error. -- `SessionRetainOptions` and `SessionBinding` are pre-stable public interfaces; every consumer and the test fixture changed together. +- `SessionRetainOptions` and `SessionRetainInfo` gain optional fields only; a third-party Client plugin that renders a Session it retains under its own source must add `facets: { conversation: true }`, which the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md) describes. ## Testing diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md index bf70578286..436a8a1fd5 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -34,10 +34,10 @@ export interface SessionRetainOptions { readonly signal?: AbortSignal | undefined } -export interface SessionBinding { +export interface SessionRetainInfo { // existing members unchanged - /** Whether any live reference retains `facet`; identity-stable per binding and facet. */ - facet(facet: SessionRetainFacet): ObservableSnapshot + /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ + readonly retainedFacets?: Readonly>> } ``` @@ -46,7 +46,7 @@ export interface SessionBinding { | 声明方式 | 子要素由其 owner 包通过声明合并加入 `SessionRetainFacetMap`;Controller 不赋予任何子要素含义 | | 缺省 | 未写的键不保留;子要素没有默认值 | | 不可变 | 一条引用的子要素集合在创建时固定;更换集合时先 retain 新引用,再 release 旧引用 | -| 计数 | [`RetainedFacets`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 为每个 generation 的每个子要素各记一个计数;计数在零与非零之间变化时同步通知 `binding.facet(name)` 的观察者,早于 `retainInfo` 与列表观察者收到同一变化;generation 退役时结束全部子要素 | +| 计数 | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 在 generation 的 `SessionRetainInfo` 中为每个子要素记一个计数,与按来源的 `retainedBy` 并列,`retainInfo(id)` 发布每次变化;owner 根据该快照与当前 binding 推导自己的子要素是否被保留,因此 `SessionBinding` 不变;generation 退役时清空全部计数 | | 依赖 | Controller 不校验子要素之间的依赖,由调用方负责 | | `using()` | 签名不变;借出的引用只服务一次操作,调用方不写 `facets` | | `retainAgentScope` | 不保留任何子要素 | @@ -97,6 +97,8 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien **由子要素 owner 在运行时声明默认值。** 这需要 Controller 维护运行时注册表,并在加载顺序与 HMR 下重新计数;而「未写即不保留」的规则已经足够。 +**在 `SessionBinding` 上暴露子要素 observable。** `SessionBinding` 新增必需成员会让所有手写 binding(包括第三方测试替身)失效,而子要素计数本就是本地引用计数,`retainInfo` 已在按来源计数旁发布它们。 + **把 `events` 也作为子要素。** 没有连接的 Session 什么也做不了;唯一不需要连接的 Gateway 已经有独立的内部入口。 **保留后台 Session 的 DOM。** React 18 没有 ``;K 个隐藏子树要付出布局、内存和订阅成本,还与 `session-maybe` 只绑定一个 Session 的设计冲突。 @@ -112,7 +114,7 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien - 受关注保护的最近访问会话没有总量上限:完成未读会一直受保护直到用户读过,因此用户不在时每个以未读状态完成的 Session 都会保留其 generation、已加载的事件窗口和历史跟随流,直到被读过、标为已读、被移除或归档。 - 切回在后台运行过的 Session 要付出一次补折,最多等同于新打开时的一次打开后折叠,但不走网络。 - 漏写 `conversation: true` 的渲染方会看到未被保留的陈旧或空快照,不会报错。 -- `SessionRetainOptions` 与 `SessionBinding` 是 pre-stable 公开接口;所有消费方和测试替身已一同修改。 +- `SessionRetainOptions` 与 `SessionRetainInfo` 只新增可选字段;以自己的来源 retain 并渲染 Session 的第三方 Client 插件需加上 `facets: { conversation: true }`,见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md)。 ## 测试 diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index 05da4a6afa..1a9f6ce871 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -406,9 +406,10 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('push') expect(await paneSnapshot(page)).toEqual(retainedB) await open() - await expect.poll(() => workspaceDirectory.getAttribute('aria-expanded')).toBe('false') + // B stayed a recent view while A was shown, so its Files tree keeps the expanded directory. + await expect.poll(() => workspaceDirectory.getAttribute('aria-expanded')).toBe('true') expect(await paneSnapshot(page)).toEqual(retainedB) - await checkpoint('B restored: normal mode and collapsed Files directory') + await checkpoint('B restored: normal mode and expanded Files directory') await close() await select(original, 'LIGHTHOUSE') await expect.poll(() => columns(page)).toEqual(normalColumns) diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index ea9784b904..2928f03842 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -1020,7 +1020,8 @@ describe('web e2e: shipped right Sidebar', () => { await expect.poll(async () => await settled.getAttribute('aria-selected')).toBe('true') await expect.poll(records, { timeout: 15_000 }).toEqual(before) expect(await column.locator('[data-sidebar-right-open]').count()).toBe(1) - expect(await wrap.getAttribute('aria-pressed')).toBe('true') + // The settled Session stayed a recent view, so its preview keeps the wrap choice made before switching. + expect(await wrap.getAttribute('aria-pressed')).toBe('false') expect(await column.locator('pre').first().innerText()).toContain('produced by the seeded turn') let warningStart = fxTripwire.warnings.length await fx.reload({ waitUntil: 'load' }) diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml new file mode 100644 index 0000000000..69ade9e30b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md +/: + en: b2150db6a81e75e3 + zh: 7bab65cd3b9c17da +/request-the-conversation-facet-when-rendering-a-session: + en: 483a33535effae0e + zh: b9c6452fe95190d9 +/request-the-conversation-facet-when-rendering-a-session/change: + en: d2c046c52e75c057 + zh: ebc263b69bbcf328 +/request-the-conversation-facet-when-rendering-a-session/migration: + en: 4071df91f4ab767d + zh: c009c649bb48f478 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md new file mode 100644 index 0000000000..4c590a3239 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "Client plugins that render a Session's Conversation retain it with the conversation facet." +--- + +# Request the `conversation` facet when rendering a Session + +English | [中文](guide.zh.md) + +## Change + +`sessions.retain()` in `@deepseek-ai/dsh-api-session-controller/client` accepts an optional `facets` record. Every reference still keeps the Session's history stream, but Conversation assembly now runs only while some reference retains the `conversation` facet that `@deepseek-ai/dsh-client-ui-conversation` declares. The existing call signature still compiles. A Client plugin that retains a Session under its own source to render it inside a `SessionProvider`, without that facet, shows the Conversation snapshot from the last time another view rendered the Session, or an empty one, and its quota notices stop. The shipped main view, right Sidebar Session views, and subagent Sidebar chat already request the facet; plugins that retain a Session only to call its operations are unaffected. + +`SessionRetainInfo`, read through `sessions.retainInfo(id)`, gains an optional `retainedFacets` count record that is absent while no reference retains any facet. + +## Migration + +1. Find each `sessions.retain(target, { source: ... })` call whose reference you pass to a `SessionProvider` that renders Conversation content. +2. Add the facet to those calls: + + ```ts ignore-check + sessions.retain(target, { source: 'myPanel', facets: { conversation: true } }) + ``` + +3. Leave `sessions.using()` calls and references that only call Session operations unchanged. +4. Confirm the migration: open your view on a Session that the main view does not show, send a prompt from it, and check that the reply appears while you watch; `sessions.retainInfo(id).getSnapshot().retainedFacets?.conversation` reads a positive count while your view is open. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md new file mode 100644 index 0000000000..551872c121 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "渲染 Session Conversation 的 Client 插件需以 conversation 子要素 retain 该 Session。" +--- + +# 渲染 Session 时请求 `conversation` 子要素 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-api-session-controller/client` 中的 `sessions.retain()` 接受可选的 `facets` 记录。每个引用仍会保活 Session 的历史流,但 Conversation 组装现在只在某个引用保留了 `@deepseek-ai/dsh-client-ui-conversation` 声明的 `conversation` 子要素时才运行。原有调用签名仍可编译。若 Client 插件以自己的来源 retain Session、并在 `SessionProvider` 中渲染它,却未请求该子要素,它显示的是其他视图上次渲染该 Session 时的 Conversation 快照或空快照,quota 提示也不再出现。内置的主视图、右侧边栏 Session 视图和 subagent 侧栏聊天已经请求该子要素;仅为调用 Session 操作而 retain 的插件不受影响。 + +通过 `sessions.retainInfo(id)` 读取的 `SessionRetainInfo` 新增可选的 `retainedFacets` 计数记录,没有任何引用保留子要素时该字段不存在。 + +## 迁移 + +1. 找出每个把引用交给渲染 Conversation 内容的 `SessionProvider` 的 `sessions.retain(target, { source: ... })` 调用。 +2. 为这些调用加上该子要素: + + ```ts ignore-check + sessions.retain(target, { source: 'myPanel', facets: { conversation: true } }) + ``` + +3. `sessions.using()` 调用以及只调用 Session 操作的引用保持不变。 +4. 确认迁移:在你的视图中打开一个主视图未显示的 Session,从中发送一条 prompt,确认回复会在你查看时出现;视图打开期间,`sessions.retainInfo(id).getSnapshot().retainedFacets?.conversation` 读到正数。 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index a8c92e0fbb..18270a40ed 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4f2f2a5276b40d4e zh: 926bb7fc609b971a /session-controller/client-references: - en: e846adfc18abf85c - zh: 973e2204caf4930c + en: 52524cd169a0933f + zh: 3220e5271ff5daa6 /session-controller/session-media-references: en: 954923654eebe2dc zh: 6bd9a7d2ea965aed diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index e82f77558c..7cffbb1ecb 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -87,7 +87,7 @@ The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads onc `sessions.retain(target, { source, facets?, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. -References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. Every reference keeps the history stream; `facets` names owner-declared parts beyond it, such as `conversation`, that the reference also keeps alive. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `binding.facet(name)` reports whether any live reference retains it, reading `false` after the generation ends. The Controller counts facets without interpreting them or their dependencies. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. +References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. Every reference keeps the history stream; `facets` names owner-declared parts beyond it, such as `conversation`, that the reference also keeps alive. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `retainInfo(id)` reports positive per-facet counts in `retainedFacets`, which is absent while no reference retains any facet. The Controller counts facets without interpreting them or their dependencies. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index c4425a49f2..198322d31f 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -87,7 +87,7 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 `sessions.retain(target, { source, facets?, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 -引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活历史流;`facets` 指明在此之外由 owner 声明、该引用同时保活的部分,例如 `conversation`。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`binding.facet(name)` 报告是否有存活引用保留该子要素,generation 结束后读为 `false`。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 +引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活历史流;`facets` 指明在此之外由 owner 声明、该引用同时保活的部分,例如 `conversation`。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`retainInfo(id)` 在 `retainedFacets` 中报告各子要素的正计数,没有任何引用保留子要素时该字段不存在。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 ## 会话媒体引用 diff --git a/packages/api/session-controller/src/client/contract/sessions.ts b/packages/api/session-controller/src/client/contract/sessions.ts index 2e8c43252d..ab7a796ec5 100644 --- a/packages/api/session-controller/src/client/contract/sessions.ts +++ b/packages/api/session-controller/src/client/contract/sessions.ts @@ -48,6 +48,11 @@ export interface SessionRetainInfo { readonly referenceCount: number /** Positive source counts only; a source without references is absent. */ readonly retainedBy: Readonly>> + /** + * Positive counts of references retaining each facet; absent while no reference retains any facet. + * Owners read their facet here, for example `(info.retainedFacets?.conversation ?? 0) > 0`. + */ + readonly retainedFacets?: Readonly>> } /** The sessions-service face injected as `ctx.sessions`. */ diff --git a/packages/api/session-controller/src/client/sessions/facets.ts b/packages/api/session-controller/src/client/sessions/facets.ts index 9556daef62..1d0174ef2f 100644 --- a/packages/api/session-controller/src/client/sessions/facets.ts +++ b/packages/api/session-controller/src/client/sessions/facets.ts @@ -1,13 +1,8 @@ /** Per-generation reference counts of owner-declared retained facets. */ -import { notifySubscribers, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { SessionRetainOptions } from '../contract/sessions.ts' +import type { SessionRetainInfo, SessionRetainOptions } from '../contract/sessions.ts' import type { SessionRetainFacet } from '../index.ts' -interface FacetCount { - count: number - readonly listeners: Set<() => void> - readonly source: ObservableSnapshot -} +type FacetCounts = NonNullable /** * The facet keys a retain request sets to `true`. @@ -19,67 +14,25 @@ export function heldFacets(facets: SessionRetainOptions['facets']): readonly Ses return (Object.keys(facets) as SessionRetainFacet[]).filter(facet => facets[facet] === true) } -/** Facet counts of one live Client generation; observers are notified only when a facet starts or stops being retained. */ -export class RetainedFacets { - private readonly counts = new Map() - - /** - * Observe one facet of this generation. - * @param facet - owner-declared facet name. - * @returns the identity-stable source reading whether any live reference retains `facet`. - */ - source(facet: SessionRetainFacet): ObservableSnapshot { - return this.entry(facet).source - } - - /** - * Count one new reference for each of its facets. - * @param facets - facets one new reference retains. - */ - retain(facets: readonly SessionRetainFacet[]): void { - for (const facet of facets) this.shift(facet, 1) - } - - /** - * Uncount one released reference from each of its facets. - * @param facets - facets of one released reference. - */ - release(facets: readonly SessionRetainFacet[]): void { - for (const facet of facets) this.shift(facet, -1) - } - - /** End every facet when the generation retires. */ - releaseAll(): void { - for (const entry of this.counts.values()) { - if (entry.count === 0) continue - entry.count = 0 - notifySubscribers(entry.listeners, '[session-controller] retained facet') - } - } - - private shift(facet: SessionRetainFacet, delta: 1 | -1): void { - const entry = this.entry(facet) - const wasHeld = entry.count > 0 - entry.count += delta - if (wasHeld !== entry.count > 0) notifySubscribers(entry.listeners, '[session-controller] retained facet') - } - - private entry(facet: SessionRetainFacet): FacetCount { - const existing = this.counts.get(facet) - if (existing !== undefined) return existing - const listeners = new Set<() => void>() - const created: FacetCount = { - count: 0, - listeners, - source: { - getSnapshot: () => created.count > 0, - subscribe: (listener) => { - listeners.add(listener) - return () => { listeners.delete(listener) } - }, - }, - } - this.counts.set(facet, created) - return created - } +/** + * Count one reference's facets in or out of a retain-info snapshot. + * @param counts - the previous positive facet counts, absent when none. + * @param facets - the facets of the retained or released reference. + * @param delta - `1` when the reference is retained, `-1` when it is released. + * @returns the frozen positive counts, or undefined when no facet remains retained. + */ +export function shiftFacetCounts( + counts: FacetCounts | undefined, + facets: readonly SessionRetainFacet[], + delta: 1 | -1, +): FacetCounts | undefined { + if (facets.length === 0) return counts + // The facet key type is empty in programs where no owner has declared a facet, so counts are built over strings. + const next = new Map(Object.entries(counts ?? {})) + for (const facet of facets) next.set(facet, (next.get(facet) ?? 0) + delta) + const positive = [...next].filter(([, count]) => count > 0) + if (positive.length === 0) return undefined + // Facet names are dictionary keys, including names also present on Object.prototype. + const record: FacetCounts = Object.assign(Object.create(null) as object, Object.fromEntries(positive)) + return Object.freeze(record) } diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index 9bc379be2e..5b14bde1ac 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -17,7 +17,7 @@ import type { } from '../contract/sessions.ts' import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts' import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from '../scope.ts' -import { heldFacets, RetainedFacets } from './facets.ts' +import { heldFacets, shiftFacetCounts } from './facets.ts' import { SessionManager } from './manager.ts' import type { SessionRemotes } from './remotes.ts' import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts' @@ -110,14 +110,6 @@ export interface SessionBinding { /** Contiguous event window reserved for Conversation assembly. */ readonly eventSource: SessionEventSource readonly ctx: AgentContext - /** - * Observe whether any live reference retains one facet of this generation. - * @param facet - owner-declared facet name. - * @returns an identity-stable source per binding and facet; it reads false once the generation ends. - * Observers run synchronously inside `retain()` and `release()`, before `retainInfo` and list - * observers hear the same change, and must not release the Session's last reference from that callback. - */ - facet(facet: SessionRetainFacet): ObservableSnapshot } // Scope primitives live in ../scope.ts (the client mirror of host @@ -174,6 +166,14 @@ function freezeRetainedBy(counts: Partial return Object.freeze(counts) } +function retentionOf( + referenceCount: number, + retainedBy: SessionRetainInfo['retainedBy'], + retainedFacets: SessionRetainInfo['retainedFacets'], +): SessionRetainInfo { + return Object.freeze({ referenceCount, retainedBy, ...(retainedFacets === undefined ? {} : { retainedFacets }) }) +} + const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) }) interface ScopeRecord { @@ -182,7 +182,6 @@ interface ScopeRecord { binding: SessionBinding session: Session retention: SessionRetainInfo - readonly facets: RetainedFacets live: boolean } @@ -296,7 +295,6 @@ export class ClientSessions implements ISessions { for (const [, record] of scopes) { record.live = false record.session.unbindScope() - record.facets.releaseAll() } const managerDisposal = this.manager.dispose() for (const [id, record] of scopes) { @@ -577,20 +575,19 @@ export class ClientSessions implements ISessions { ): ClientSessionReference { const record = this.scopes.get(id) ?? this.materializeScope(id) const previous = record.retention - record.retention = Object.freeze({ - referenceCount: previous.referenceCount + 1, - retainedBy: freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), - }) - record.facets.retain(facets) + record.retention = retentionOf( + previous.referenceCount + 1, + freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), + shiftFacetCounts(previous.retainedFacets, facets, 1), + ) const reference = new ClientSessionReference(id, record, () => { if (!record.live) return - record.facets.release(facets) const count = record.retention.referenceCount - 1 const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources record.retention = count === 0 ? EMPTY_RETAIN_INFO - : Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) }) + : retentionOf(count, freezeRetainedBy(retainedBy), shiftFacetCounts(record.retention.retainedFacets, facets, -1)) if (count === 0) this.retireScope(id, record) else this.publishRetention(id) }) @@ -624,7 +621,6 @@ export class ClientSessions implements ISessions { record.live = false if (this.scopes.get(id) === record) this.scopes.delete(id) record.session.unbindScope() - record.facets.releaseAll() const sessionDisposal = this.manager.drop(id, record.session) this.projectList() this.publishRetention(id) @@ -638,21 +634,13 @@ export class ClientSessions implements ISessions { // The Session owns its scoped dispatch point (host Agent.loopCtx mirror); // mint and bind are one step so a live scope record implies a bound actx. session.bindScope(ctx) - const facets = new RetainedFacets() - const binding: SessionBinding = { - sessionId: id, - session, - eventSource: session.eventSource, - ctx, - facet: facet => facets.source(facet), - } + const binding: SessionBinding = { sessionId: id, session, eventSource: session.eventSource, ctx } const record: ScopeRecord = { fiber, ctx, binding, session, retention: EMPTY_RETAIN_INFO, - facets, live: true, } this.scopes.set(id, record) diff --git a/packages/api/session-controller/tests/reference-ownership.client.spec.ts b/packages/api/session-controller/tests/reference-ownership.client.spec.ts index b5327c9251..d1ce84c944 100644 --- a/packages/api/session-controller/tests/reference-ownership.client.spec.ts +++ b/packages/api/session-controller/tests/reference-ownership.client.spec.ts @@ -289,47 +289,34 @@ describe('Client reference sources', () => { }) describe('Client retained facets', () => { - it('counts each facet across references and notifies only when its retention starts or stops', async ({ mock, start }) => { + it('counts each facet across references in the retain info and omits facets nobody retains', async ({ mock, start }) => { const b = await bench(mock, start) + const info = b.svc.retainInfo(ID) using plain = b.svc.retain(ID, { source: workSource }) - const facet = plain.binding.facet('referenceTestFacet') - const other = plain.binding.facet('referenceTestOtherFacet') - expect(plain.binding.facet('referenceTestFacet')).toBe(facet) - const changed = vi.fn() - const stop = facet.subscribe(changed) - expect(facet.getSnapshot()).toBe(false) + expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 } }) + expect('retainedFacets' in info.getSnapshot()).toBe(false) const first = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true, referenceTestOtherFacet: false } }) const second = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) - expect(facet.getSnapshot()).toBe(true) - expect(other.getSnapshot()).toBe(false) - expect(changed).toHaveBeenCalledTimes(1) + expect(info.getSnapshot().retainedFacets).toEqual({ referenceTestFacet: 2 }) + expect(b.svc.list.getSnapshot().byId[ID]?.retainedBy).toEqual({ referenceTestWork: 1, referenceTestView: 2 }) first.release() first.release() - expect(facet.getSnapshot()).toBe(true) - expect(changed).toHaveBeenCalledTimes(1) + expect(info.getSnapshot().retainedFacets).toEqual({ referenceTestFacet: 1 }) second.release() - expect(facet.getSnapshot()).toBe(false) - expect(changed).toHaveBeenCalledTimes(2) - stop() + expect('retainedFacets' in info.getSnapshot()).toBe(false) + expect(plain.sessionId).toBe(ID) }) - it('ends retained facets with the generation, including through root disposal', async ({ mock, start }) => { + it('clears retained facets with the generation and on root disposal', async ({ mock, start }) => { const b = await bench(mock, start) + const info = b.svc.retainInfo(ID) const reference = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) - const facet = reference.binding.facet('referenceTestFacet') - const changed = vi.fn() - facet.subscribe(changed) reference.release() - expect(facet.getSnapshot()).toBe(false) - const replacement = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) - const replacementFacet = replacement.binding.facet('referenceTestFacet') - expect(replacementFacet).not.toBe(facet) - const replacementChanged = vi.fn() - replacementFacet.subscribe(replacementChanged) + expect(info.getSnapshot()).toEqual({ referenceCount: 0, retainedBy: {} }) + b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) + expect(info.getSnapshot().retainedFacets).toEqual({ referenceTestFacet: 1 }) await b.ctx.fiber.dispose() - expect(replacementFacet.getSnapshot()).toBe(false) - expect(replacementChanged).toHaveBeenCalledTimes(1) - expect(changed).toHaveBeenCalledTimes(1) + expect(info.getSnapshot()).toEqual({ referenceCount: 0, retainedBy: {} }) }) }) diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 93139e5335..3c40e7ef5d 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -106,15 +106,19 @@ export function apply(ctx: Context): void { // back into view is not news. const dispose = binding.ctx.effect(() => { // Live quota failures are reported only while a rendering reference retains the Session's Conversation. - const retained = binding.facet('conversation') - let stopEvents = (): void => {} + const retainInfo = ctx.sessions.retainInfo(binding.sessionId) + const retained = (): boolean => ctx.sessions.binding(binding.sessionId) === binding + && (retainInfo.getSnapshot().retainedFacets?.conversation ?? 0) > 0 + let stopEvents: (() => void) | undefined const follow = (): void => { - stopEvents() - stopEvents = () => {} - if (!retained.getSnapshot()) return - stopEvents = binding.eventSource.subscribe(() => { + if (!retained()) { + stopEvents?.() + stopEvents = undefined + return + } + stopEvents ??= binding.eventSource.subscribe(() => { // A dispatch in progress keeps calling copied listeners after unsubscription. - if (!retained.getSnapshot()) return + if (!retained()) return const { change } = binding.eventSource.getSnapshot() if (change.kind !== 'append') return for (const { event } of change.entries) { @@ -125,11 +129,11 @@ export function apply(ctx: Context): void { } }) } - const stopRetained = retained.subscribe(follow) + const stopRetained = retainInfo.subscribe(follow) follow() return () => { stopRetained() - stopEvents() + stopEvents?.() chatSources.delete(binding) quotaSubscriptions.delete(dispose) } diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 3eed285da4..f1094a37fc 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -358,7 +358,7 @@ export class UiConversation extends Service { const binding = new BoundConversation( owner.eventSource, new ConversationNodeAssembler(this.events, this.views, this.groups), - owner.facet('conversation'), + this.retainedConversation(owner), ) const record: BindingRecord = { source: owner, binding, disposeScope: () => {} } this.bindings.set(owner, record) @@ -377,6 +377,19 @@ export class UiConversation extends Service { return binding } + /** + * Whether a reference retains the `conversation` facet of this exact binding; a same-id + * replacement generation's counts do not apply to a binding that is no longer current. + */ + private retainedConversation(owner: SessionBinding): ObservableSnapshot { + const info = this.sessions.retainInfo(owner.sessionId) + return { + getSnapshot: () => this.sessions.binding(owner.sessionId) === owner + && (info.getSnapshot().retainedFacets?.conversation ?? 0) > 0, + subscribe: listener => info.subscribe(listener), + } + } + /** * Resolve one Gateway-authorized durable image URL, cached per Session so * every Conversation target shares one read and one browser URL. 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 f0a517a5cf..e7d6a588c0 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -81,7 +81,6 @@ function fakeSessions(ctx: Context): { session: fakeSession(), eventSource: new MutableSessionEventSource(), ctx: scope.ctx, - facet: () => retained, } const list = createSnapshotStore({ ids: [], @@ -102,7 +101,12 @@ function fakeSessions(ctx: Context): { create: () => Promise.reject(new Error('unused fake Sessions operation')), retain: () => reference, using: async (_target, _options, operation) => await operation(reference), - retainInfo: () => createSnapshotStore({ referenceCount: 1, retainedBy: {} }), + retainInfo: () => ({ + getSnapshot: () => ({ + referenceCount: 1, retainedBy: {}, ...(retained.getSnapshot() ? { retainedFacets: { conversation: 1 } } : {}), + }), + subscribe: listener => retained.subscribe(listener), + }), subagentAddress: () => undefined, refreshProjections: () => Promise.reject(new Error('unused fake Sessions operation')), refresh: () => Promise.reject(new Error('unused fake Sessions operation')), diff --git a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts index 174a05276d..4475586682 100644 --- a/packages/client/ui-session-status/tests/acknowledge.client.spec.ts +++ b/packages/client/ui-session-status/tests/acknowledge.client.spec.ts @@ -51,10 +51,7 @@ function harness({ manual = false, completedTurn = 1, selected = true, ready = t const list = createSnapshotStore({ ids: [id], phase: 'ready', projectionsBySession: {}, byId: { [id]: row(selected) }, }, { flush: 'sync' }) - const retainedFacet = createSnapshotStore(true) - const bind = (): SessionBinding => ({ - sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext, facet: () => retainedFacet, - }) + const bind = (): SessionBinding => ({ sessionId: id, session, eventSource: session.eventSource, ctx: ctx as AgentContext }) let binding = bind() const mark = vi.fn(async (_id: typeof id, _throughTurn: number, _clearManual: boolean) => {}) let frame: FrameRequestCallback | undefined 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 07f0dddaea..ac7fb9bc42 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -109,13 +109,11 @@ function createSessionsBench(ctx: Context): SessionsBench { getSnapshot: () => snapshot.getSnapshot(), subscribe: (listener: () => void) => snapshot.subscribe(listener), } as unknown as SessionBinding['session'] - const retainedFacet = createSnapshotStore(true) const binding: SessionBinding = { sessionId: id, session, eventSource: new MutableSessionEventSource(), ctx: scopeCtx as AgentContext, - facet: () => retainedFacet, } bindings.set(id, binding) scopes.set(id, scopeCtx) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index aaf519e17f..2404d9aa40 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -494,13 +494,13 @@ describe('UiWorkspaceService', () => { ) uiWorkspace.openSession(sid('a')) const binding = sessions.binding('a') - expect(binding?.facet('conversation').getSnapshot()).toBe(true) + expect(sessions.retainInfo(sid('a')).getSnapshot().retainedFacets?.conversation).toBe(1) uiWorkspace.openSession(sid('b')) expect(sessions.binding('a')).toBe(binding) - expect(binding?.facet('conversation').getSnapshot()).toBe(false) + expect(sessions.retainInfo(sid('a')).getSnapshot().retainedFacets?.conversation).toBeUndefined() uiWorkspace.openSession(sid('a')) expect(sessions.binding('a')).toBe(binding) - expect(binding?.facet('conversation').getSnapshot()).toBe(true) + expect(sessions.retainInfo(sid('a')).getSnapshot().retainedFacets?.conversation).toBe(1) expect(opened).toHaveBeenCalledOnce() await runtime.dispose() expect(sessions.retainInfo(sid('a')).getSnapshot().referenceCount).toBe(0) 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 eddd9f669c..ed972f7cbf 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -893,7 +893,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionBinding', - declaration: 'export interface SessionBinding {\n readonly sessionId: SessionId;\n readonly session: SessionFace;\n readonly eventSource: SessionEventSource;\n readonly ctx: AgentContext;\n facet(facet: SessionRetainFacet): ObservableSnapshot;\n}', + declaration: 'export interface SessionBinding {\n readonly sessionId: SessionId;\n readonly session: SessionFace;\n readonly eventSource: SessionEventSource;\n readonly ctx: AgentContext;\n}', }, { name: 'SessionEventChange', @@ -965,7 +965,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionRetainInfo', - declaration: 'export interface SessionRetainInfo {\n readonly referenceCount: number;\n readonly retainedBy: Readonly>>;\n}', + declaration: 'export interface SessionRetainInfo {\n readonly referenceCount: number;\n readonly retainedBy: Readonly>>;\n readonly retainedFacets?: Readonly>>;\n}', }, { name: 'SessionRetainOptions', diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index cfc0ac78f1..ed3527a822 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -11,7 +11,7 @@ import type { SessionSnapshot, SessionSummary, SessionTarget, SubmissionHandle, } from '@deepseek-ai/dsh-api-session-controller/client' import { scopeIdentityOf } from '@deepseek-ai/dsh-api-session-controller/src/client/scope.ts' -import { heldFacets, RetainedFacets } from '@deepseek-ai/dsh-api-session-controller/src/client/sessions/facets.ts' +import { heldFacets, shiftFacetCounts } from '@deepseek-ai/dsh-api-session-controller/src/client/sessions/facets.ts' import type { SessionRequestId } from '@deepseek-ai/dsh-api-session-controller/types' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -206,7 +206,6 @@ interface SessionGeneration { readonly lifetime: AbortController readonly opening: Promise retention: SessionRetainInfo - readonly facets: RetainedFacets live: boolean } @@ -219,6 +218,14 @@ interface OpeningControl { /** Fixture references default to a rendering use, so Conversation assembly runs as it does under a main view. */ const DEFAULT_TEST_RETAIN: SessionRetainOptions = { source: 'testFixture', facets: { conversation: true } } +function retentionOf( + referenceCount: number, + retainedBy: SessionRetainInfo['retainedBy'], + retainedFacets: SessionRetainInfo['retainedFacets'], +): SessionRetainInfo { + return Object.freeze({ referenceCount, retainedBy, ...(retainedFacets === undefined ? {} : { retainedFacets }) }) +} + function freezeRetainedBy( counts: Partial>, ): SessionRetainInfo['retainedBy'] { @@ -348,7 +355,6 @@ export class TestSessions implements ISessions { for (const [id, generation] of this.generations) { generation.live = false generation.retention = EMPTY_RETAIN_INFO - generation.facets.releaseAll() generation.lifetime.abort(new Error('test Session Controller is disposed')) this.publishRetention(id) } @@ -729,17 +735,13 @@ export class TestSessions implements ISessions { facets: readonly SessionRetainFacet[], ): TestSessionReference { const previous = generation.retention - generation.retention = Object.freeze({ - referenceCount: previous.referenceCount + 1, - retainedBy: freezeRetainedBy({ - ...previous.retainedBy, - [source]: (previous.retainedBy[source] ?? 0) + 1, - }), - }) - generation.facets.retain(facets) + generation.retention = retentionOf( + previous.referenceCount + 1, + freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), + shiftFacetCounts(previous.retainedFacets, facets, 1), + ) const reference = new TestSessionReference(id, generation, () => { if (!generation.live) return - generation.facets.release(facets) const count = generation.retention.referenceCount - 1 const { [source]: sourceCount = 0, ...otherSources } = generation.retention.retainedBy const retainedBy = sourceCount > 1 @@ -747,7 +749,7 @@ export class TestSessions implements ISessions { : otherSources generation.retention = count === 0 ? EMPTY_RETAIN_INFO - : Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) }) + : retentionOf(count, freezeRetainedBy(retainedBy), shiftFacetCounts(generation.retention.retainedFacets, facets, -1)) if (count === 0) this.drop(id, generation) else this.publishRetention(id) }) @@ -783,16 +785,14 @@ export class TestSessions implements ISessions { const opening = Promise.withResolvers() void opening.promise.catch(() => {}) const lifetime = new AbortController() - const facets = new RetainedFacets() const generation: SessionGeneration = { - binding: { sessionId: id, session, eventSource: session.eventSource, ctx, facet: facet => facets.source(facet) }, + binding: { sessionId: id, session, eventSource: session.eventSource, ctx }, snapshot, session, fiber, lifetime, opening: opening.promise, retention: EMPTY_RETAIN_INFO, - facets, live: true, } this.generations.set(id, generation) @@ -800,7 +800,6 @@ export class TestSessions implements ISessions { if (generation.live) { generation.live = false generation.retention = EMPTY_RETAIN_INFO - generation.facets.releaseAll() if (this.generations.get(id) === generation) this.generations.delete(id) this.publishRetention(id) } @@ -828,7 +827,6 @@ export class TestSessions implements ISessions { if (!generation.live) return generation.live = false generation.retention = EMPTY_RETAIN_INFO - generation.facets.releaseAll() /* v8 ignore next -- this synchronous path drops only the generation currently stored for id. */ if (this.generations.get(id) === generation) this.generations.delete(id) generation.lifetime.abort(new Error(`test Session generation "${id}" is released`)) diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index 60fdb12e74..1672fe589a 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -267,12 +267,11 @@ describe('sessions', () => { await Promise.all([first.ready, second.ready]) expect(info.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { testOperation: 2 } }) expect(runtime.sessions.list.getSnapshot().byId[id]?.retainedBy).toEqual({ testOperation: 2 }) - const conversation = first.binding.facet('conversation') - expect(conversation.getSnapshot()).toBe(false) + expect('retainedFacets' in info.getSnapshot()).toBe(false) const rendered = runtime.sessions.retain(id) - expect(conversation.getSnapshot()).toBe(true) + expect(info.getSnapshot().retainedFacets).toEqual({ conversation: 1 }) rendered.release() - expect(conversation.getSnapshot()).toBe(false) + expect('retainedFacets' in info.getSnapshot()).toBe(false) first.release() expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { testOperation: 1 } }) second.release() diff --git a/snapshots/web/details-session-lifecycle/sidebar.expected.md b/snapshots/web/details-session-lifecycle/sidebar.expected.md index 4607cf35ed..db5f8c87f3 100644 --- a/snapshots/web/details-session-lifecycle/sidebar.expected.md +++ b/snapshots/web/details-session-lifecycle/sidebar.expected.md @@ -229,7 +229,7 @@ } ``` -## B restored: normal mode and collapsed Files directory +## B restored: normal mode and expanded Files directory ```json { @@ -249,7 +249,9 @@ "panelOuterWidth": 756, "coversViewport": false, "resizeHandleWidth": 8, - "expandedDirectories": [], + "expandedDirectories": [ + "workspace" + ], "panes": [ { "active": true, From 4b01a4afda5767e8e2b12b88d3f761093884526f Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:01:40 +0800 Subject: [PATCH 5/9] feat(client): keep drafts with a connectionless Session hold and fold only the last page on return Session references gain connection (true by default). When no reference keeps it, the Session disconnects and empties its window while keeping its scope. When the last facet is released, the Session keeps only its last Turn-aligned page visible and its event stream buffers the older records, answering page reads from that buffer before the Host. BoundConversation folds only while the conversation facet is retained and drops its fold on release. The input hub holds a Session with { source: 'draft', connection: false } while its draft has attachments, replacing the root-level draft-attachment ownership; reload marks remain. --- ...n-retain-facets-and-recent-views.i18n.yaml | 33 +++-- ...-session-retain-facets-and-recent-views.md | 73 +++++----- ...ssion-retain-facets-and-recent-views.zh.md | 73 +++++----- ...achments-across-session-switches.i18n.yaml | 8 +- ...aft-attachments-across-session-switches.md | 6 +- ...-attachments-across-session-switches.zh.md | 6 +- .../guide.i18n.yaml | 8 +- .../guide.md | 4 +- .../guide.zh.md | 4 +- .../api/gateway/src/client/journal-stream.ts | 8 + .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 4 +- packages/api/session-controller/README.zh.md | 4 +- .../src/client/contract/sessions.ts | 14 +- .../src/client/sessions/buffered-pages.ts | 41 ++++++ .../src/client/sessions/history-records.ts | 18 ++- .../src/client/sessions/service.ts | 50 +++++-- .../src/client/sessions/session.ts | 41 ++++++ .../src/client/transport.ts | 43 +++++- .../tests/reference-ownership.client.spec.ts | 64 +++++++- .../tests/session.client.spec.ts | 114 +++++++++++++++ .../client/ui-conversation/README.i18n.yaml | 8 +- packages/client/ui-conversation/README.md | 4 +- packages/client/ui-conversation/README.zh.md | 4 +- .../src/client/conversation/assembly.ts | 70 ++++----- .../ui-conversation/src/client/input/hub.ts | 137 +++++++++--------- .../ui-conversation/src/client/service.ts | 65 --------- .../conversation-registry.client.spec.ts | 16 +- .../draft-attachment-retention.client.spec.ts | 71 ++++----- .../src/client/api-catalog.ts | 4 +- .../client-runtime/src/sessions.ts | 23 ++- .../tests/runtime.client.spec.tsx | 12 +- scripts/no-unknown-casts.baseline.json | 3 - 33 files changed, 676 insertions(+), 361 deletions(-) create mode 100644 packages/api/session-controller/src/client/sessions/buffered-pages.ts diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml index c78426252b..1bc6712e57 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -9,26 +9,29 @@ en: 455344d0dc6aec78 zh: cd0b86cc1cd2cbe7 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision: - en: c78a249d157157ea - zh: bca420c14a3c8da7 -/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/session-retain-and-facets: - en: aa30c6c943fd1844 - zh: 6fcfd9b2e42bab7e + en: d1fa71821f857f8b + zh: 15308ccd85c6c25c +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/connection-and-facets: + en: 6c72ad036c9f9834 + zh: 0922647e1f58a811 /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-conversation-facet: - en: f8a2eba56afd7586 - zh: fb8eaa9fab8ef755 + en: a6031fa553aae23b + zh: 77e534b656ae660e +/agent-note-session-retain-facets-and-recently-viewed-sessions/decision/the-draft-reference: + en: db1266225cc204e9 + zh: d786fe7fca2c783e /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/reference-sources-and-facets: - en: 9025a3a0380dbcc0 - zh: 9eba187f235dc045 + en: cb761521ca56fe93 + zh: 76f8797f4808407d /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/recently-viewed-sessions-recentviews: en: e1a6728468965961 zh: 4af21b4c306bec27 /agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: - en: d069b934184f3e56 - zh: fb407797d23e8366 + en: 7a484119b745aee9 + zh: 3092d3dbda8397cd /agent-note-session-retain-facets-and-recently-viewed-sessions/consequences: - en: 3340bc5545d66d4c - zh: 7ecd86cd570f6bf4 + en: 9ec4b80ad5f74041 + zh: f20bc50bf5e4dd2c /agent-note-session-retain-facets-and-recently-viewed-sessions/testing: - en: eafd3b46ef5bb59d - zh: 351b9d9721d38ba9 + en: 83e4d88dce18a4de + zh: 36bdf8f95c1fa373 diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md index 21194dafa4..a4e7010834 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -14,23 +14,19 @@ The retain interface could only express retaining or releasing the whole Session ## Decision -This decision extends [Client Session references](2026-09-15-client-session-references.md) without superseding it: references, source counts, and `ready` semantics are unchanged, and `SessionRetainOptions` carries facets. +This decision extends [Client Session references](2026-09-15-client-session-references.md) without superseding it: references and source counts are unchanged; `SessionRetainOptions` carries `connection` and facets, and a reference without the connection is ready once its binding exists. It replaces the draft-attachment ownership of [draft attachments across Session switches](../bug-fix/2026-11-13-draft-attachments-across-session-switches.md) with the `draft` reference. -### Session retain and facets +### Connection and facets -A Session retain always keeps the binding, scope, history connection, and event window alive. The connection is mandatory and is not a facet. - -A facet is a part retained beyond that baseline, and each facet is counted independently. A reference declares the facets it retains through its options when it is created: +A Session reference always keeps the Session object and its scope, which hold local state such as the composer draft and pending submission echoes. Two options decide what it keeps beyond that: ```ts ignore-check -// session-controller/client: declares no facets -export interface SessionRetainFacetMap {} -export type SessionRetainFacet = Extract - export interface SessionRetainOptions { readonly source: SessionReferenceSource - /** Parts kept alive beyond the Session's history stream; an absent key is not retained. */ - readonly facets?: Readonly>> + /** Keeps the Session's own event connection and the event window it keeps current; defaults to `true`. */ + readonly connection?: boolean + /** Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed. */ + readonly facets?: Readonly>> readonly signal?: AbortSignal | undefined } @@ -38,38 +34,45 @@ export interface SessionRetainInfo { // existing members unchanged /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ readonly retainedFacets?: Readonly>> + /** Positive count of references keeping the event connection; absent while none does. */ + readonly connectionCount?: number } ``` | Rule | Behavior | |---|---| -| Declaration | The owning package adds a facet to `SessionRetainFacetMap` through declaration merging; the Controller assigns no meaning to any facet | -| Omission | An absent key is not retained; facets have no default | -| Immutability | A reference's facet set is fixed at creation; changing the set retains a new reference before releasing the old one | -| Counting | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet in the generation's `SessionRetainInfo`, beside the per-source `retainedBy` counts, and `retainInfo(id)` publishes every change; owners derive whether their facet is retained from that snapshot and the current binding, so `SessionBinding` is unchanged; retiring the generation clears every count | -| Dependencies | The Controller does not validate dependencies between facets; callers are responsible | -| `using()` | Signature unchanged; a borrowed reference serves one operation, and callers omit `facets` | -| `retainAgentScope` | Retains no facets | +| Connection | The connection is the Session's own follow stream plus the event window it keeps current, not the page transport. It opens when the first reference that keeps it is retained; when the last such reference is released while the scope remains, `Session.disconnect()` closes it, empties the window, and returns the Session to its cold state while keeping pending submission echoes; the next reference that keeps it connects as a first open | +| Facets | The owning package adds a facet to `SessionRetainFacetMap` through declaration merging; the Controller assigns no meaning to any facet. An absent key is not computed; a facet computes over the data the connection keeps, so without it there is nothing to compute | +| Buffered older pages | When the last facet is released while the connection remains, `Session.bufferOlder()` keeps only the last Turn-aligned page visible and hands the older entries to its `SessionEventStream`. The Session pages back exactly as before; the stream answers page reads from those buffered records, cut by the request's Turn window, without a request, and reads Host pages after they run out. A replaced window drops the buffer, and it leaves with the stream on resync, disconnect, or disposal. [`buffered-pages.ts`](../../../../packages/api/session-controller/src/client/sessions/buffered-pages.ts) owns the page cut | +| Counting | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) keeps one count per facet beside `connectionCount` and the per-source `retainedBy` counts in the generation's `SessionRetainInfo`; `retainInfo(id)` publishes every change, and owners derive their facet from that snapshot and the current binding, so `SessionBinding` is unchanged | +| Immutability | A reference's options are fixed at creation; changing them retains a new reference before releasing the old one | +| `using()` | Signature unchanged; borrowed references keep the connection by default and request no facet | +| `retainAgentScope` | Keeps neither the connection nor a facet | ### The `conversation` facet `ui-conversation` declares `conversation`: Conversation assembly of the event window and materialization of its views. - `BoundConversation` remains one per binding, and its `snapshot`, `openTurn`, and `target(t)` sources keep stable identities. `UiConversation.binding()` registers the binding's disposal on the Session scope before the binding starts following, and a failed initial fold disposes the binding so the next resolution starts afresh. -- When the facet **starts** being retained, the binding first subscribes to the event window, then resumes in one step: the first fold, or a registry change made while not following, rebuilds the current window once; otherwise contiguous changes received meanwhile apply through the incremental assembler and a revision gap rebuilds the whole window. Any pending rAF is then cancelled and the binding publishes once synchronously, also after that fold fails; a failed fold leaves the binding stale, so the next window change rebuilds the whole window instead of extending a partial fold. A view activated while not following is built from the last folded state and catches up on resume. -- When the facet **stops** being retained, the binding unsubscribes from the event window and cancels a pending rAF. The last published snapshot remains readable but no longer updates. While old DOM is still mounted during a switch, its components read that snapshot. A feed dispatch already in progress checks whether the binding still follows, so a release during that dispatch stops folding immediately. -- Calling `uiConversation.binding()` while the facet is not retained returns the unretained binding, which reads the last or empty snapshot without throwing. -- Two computations follow the `conversation` facet: `BoundConversation` and the [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) quota listener, which neither publishes nor replays notices for failures received while the facet is not retained. Other state on `binding.ctx` that events do not drive (input shell, command popups, historical image URLs, agent preset seat) keeps its existing lifetime. +- While the facet is retained, the binding folds the whole current window once, publishes it synchronously, and follows window changes; a fold that fails leaves the binding unfolded, so the next window change folds the whole window again. +- When the facet is released, the binding unsubscribes, cancels a pending rAF, drops its fold, and publishes the empty result once; registry changes while released are not applied until it is retained again. A feed dispatch already in progress checks whether the binding still follows, so a release during that dispatch stops folding immediately. +- Two computations follow the `conversation` facet: `BoundConversation` and the [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) quota listener, which neither publishes nor replays notices for failures received while the facet is not retained. + +### The `draft` reference + +The [input hub](../../../../packages/client/ui-conversation/src/client/input/hub.ts) holds a Session with `{ source: 'draft', connection: false }` while its composer draft has attachments and the Session is not removed. The scope, and with it the same composer shell and its browser-owned attachments, therefore survives every view releasing the Session; returning reconnects and refolds while the composer keeps its attachments, uploads, and failed-upload retries. Removing the last attachment, sending it, or removing the Session releases the hold, and scope teardown then releases every draft attachment. A page unload still marks the Sessions whose draft holds attachments, and the next page reports them as discarded. ### Reference sources and facets -| Source | Owning package | `facets` | +| Source | Owning package | Options | |---|---|---| | `mainView` | declared by ui-session, retained by ui-workspace | `{ conversation: true }` | | `sidebarView` | ui-sidebar-right | `{ conversation: true }` | | `sidebarChat` | ui-subagent | `{ conversation: true }` | -| `recentViews` | ui-workspace | omitted | -| `using()` callers and `gateway` | their own packages | omitted | +| `recentViews` | ui-workspace | omitted: connection only | +| `draft` | ui-conversation | `{ connection: false }` | +| `using()` callers | their own packages | omitted | +| `gateway` | session-controller | internal entry without connection | | Test fixture default | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | ### Recently viewed Sessions: `recentViews` @@ -99,26 +102,30 @@ Its state records only what the user did: the order in which Sessions left the m **Expose a facet observable on `SessionBinding`.** A new required `SessionBinding` member breaks every hand-built binding, including third-party test fakes, while facet counts are local reference counts that `retainInfo` already publishes beside the per-source counts. -**Make `events` a facet.** A Session without its connection can do nothing, and the only connection-free use, the Gateway, already has its own internal entry. +**Retention levels instead of facets.** A fixed `state`, `cache`, `live` enumeration cannot grow with later owner needs, while a default-on `connection` plus owner facets expresses the same three states. + +**Keep the last fold after the facet is released.** A stale result with no owner adds a hidden state; the window stays, and folding only its last page on return is cheap. + +**Root-level draft-attachment ownership.** Recording owners in the Conversation service and re-adopting them in a new composer duplicates Session lifetime tracking with a catalog watch; holding the scope keeps the composer itself. **Keep background Session DOM.** React 18 has no ``; K hidden subtrees pay layout, memory, and subscription costs and conflict with the single-Session `session-maybe` binding. **Keep folding while unretained and only defer publication.** The `match`/`update` cost of stream chunks remains. -**Compute a bespoke difference between the folded inputs and the window.** One attempt can start, stream, and settle entirely while unretained, which makes such difference logic error-prone; resumption instead reuses the assembler's existing contiguous-change and gap-rebuild paths. +**Compute a bespoke difference between the folded inputs and the window.** One attempt can start, stream, and settle entirely while unretained, which makes such difference logic error-prone; returning folds the last page from scratch instead. ## Consequences -- A background Session switches back without a history request, while it performs no Conversation folding until it is shown again. -- An unretained Session keeps the memory of its last assembly until it is shown again or its binding retires. +- A recent view switches back without a history request and folds only its last page; paging back through pages already loaded makes no request. +- A recent view keeps its whole loaded window in memory; it keeps no Conversation fold. +- A Session evicted from the recent views with draft attachments keeps its composer but not its window, so returning to it requests history again. - The attention-protected recent views have no upper bound: an unread completion stays protected until the user reads it, so each Session that finishes unread while the user is elsewhere keeps its generation, loaded event window, and history follow stream until it is read, marked read, removed, or archived. -- Returning to a Session that ran in the background pays one catch-up fold, at most equal to the post-open fold of a fresh opening, without a network request. - A rendering owner that omits `conversation: true` sees an unretained stale or empty snapshot without an error. -- `SessionRetainOptions` and `SessionRetainInfo` gain optional fields only; a third-party Client plugin that renders a Session it retains under its own source must add `facets: { conversation: true }`, which the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md) describes. +- `SessionRetainOptions` and `SessionRetainInfo` gain optional fields only; a third-party Client plugin that renders a Session it retains under its own source must add `facets: { conversation: true }`, and a plugin that only needs local state may pass `connection: false`, which the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md) describes. ## Testing -- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) covers per-facet counting, notifications only at zero transitions, and facets ending with the generation and root disposal. -- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) covers zero folding while unretained, one synchronous publication on resume, equality with continuous following, activation and registry changes while not following, a release during an in-progress dispatch, an interrupted rAF publication, a failed resumption, and a failed initial fold leaving no subscription. +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) covers per-facet and connection counting, holding a Session without connecting it, disconnecting after the last connected reference, buffering older pages after the last facet, and counts ending with the generation and root disposal; [session.client.spec.ts](../../../../packages/api/session-controller/tests/session.client.spec.ts) covers buffered-page paging, Turn jumps, Host paging after buffered pages, buffering again after live growth, and disconnect then reconnect. +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) covers dropping the fold on release, one synchronous fold on retention, equality with continuous following, activation and registry changes while not following, a release during an in-progress dispatch, a cancelled rAF publication, a failed fold, and a failed initial fold leaving no subscription; [draft-attachment-retention.client.spec.ts](../../../../packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts) covers the `draft` reference, its release, removed Sessions, and unload marks. - [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) covers quota notices publishing only while the facet is retained. - [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) and [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) cover the attention and pin rules, synchronous re-entrancy during retention, the main-view Session staying out of the count, eviction without automatic return, configuration, list-driven reconciliation, and returning to a recent view through the same generation without reopening history. diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md index 436a8a1fd5..a726502294 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -14,23 +14,19 @@ retain 接口只能表达保住或释放整个 Session,无法表达「只收 ## 决策 -本决策扩展 [Client Session 引用](2026-09-15-client-session-references.zh.md),但不取代它:引用、来源计数和 `ready` 语义不变,`SessionRetainOptions` 携带子要素。 +本决策扩展 [Client Session 引用](2026-09-15-client-session-references.zh.md),但不取代它:引用与来源计数不变;`SessionRetainOptions` 携带 `connection` 与子要素,不保留连接的引用在 binding 建好时即就绪。它以 `draft` 引用取代 [跨会话切换保留草稿附件](../bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md) 中的草稿附件归属机制。 -### Session retain 与子要素 +### 连接与子要素 -Session retain 始终保活 binding、作用域、历史连接和事件窗口。连接是强制的,不作为子要素。 - -子要素(facet)是在此基础上另外保留的部分,每个子要素单独计数。引用在创建时通过 options 声明要保留哪些子要素: +Session 引用始终保活 Session 对象及其作用域,作用域上保存草稿、发送回显等本地状态。两个选项决定在此之外还保留什么: ```ts ignore-check -// session-controller/client: declares no facets -export interface SessionRetainFacetMap {} -export type SessionRetainFacet = Extract - export interface SessionRetainOptions { readonly source: SessionReferenceSource - /** Parts kept alive beyond the Session's history stream; an absent key is not retained. */ - readonly facets?: Readonly>> + /** Keeps the Session's own event connection and the event window it keeps current; defaults to `true`. */ + readonly connection?: boolean + /** Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed. */ + readonly facets?: Readonly>> readonly signal?: AbortSignal | undefined } @@ -38,38 +34,45 @@ export interface SessionRetainInfo { // existing members unchanged /** Positive counts of references retaining each facet; absent while no reference retains any facet. */ readonly retainedFacets?: Readonly>> + /** Positive count of references keeping the event connection; absent while none does. */ + readonly connectionCount?: number } ``` | 规则 | 行为 | |---|---| -| 声明方式 | 子要素由其 owner 包通过声明合并加入 `SessionRetainFacetMap`;Controller 不赋予任何子要素含义 | -| 缺省 | 未写的键不保留;子要素没有默认值 | -| 不可变 | 一条引用的子要素集合在创建时固定;更换集合时先 retain 新引用,再 release 旧引用 | -| 计数 | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 在 generation 的 `SessionRetainInfo` 中为每个子要素记一个计数,与按来源的 `retainedBy` 并列,`retainInfo(id)` 发布每次变化;owner 根据该快照与当前 binding 推导自己的子要素是否被保留,因此 `SessionBinding` 不变;generation 退役时清空全部计数 | -| 依赖 | Controller 不校验子要素之间的依赖,由调用方负责 | -| `using()` | 签名不变;借出的引用只服务一次操作,调用方不写 `facets` | -| `retainAgentScope` | 不保留任何子要素 | +| 连接 | 连接指 Session 自己的 follow 流及其维持最新的事件窗口,不是页面传输连接。第一个保留连接的引用出现时建立;作用域仍在而最后一个保留连接的引用被释放时,`Session.disconnect()` 关闭连接、清空窗口,并让 Session 回到 cold 状态,发送回显保留;下一个保留连接的引用按首次打开的流程重新连接 | +| 子要素 | owner 包通过声明合并把子要素加入 `SessionRetainFacetMap`;Controller 不赋予任何子要素含义。未写的键不计算;子要素基于连接保有的数据计算,没有数据就无从计算 | +| 缓冲的更早页 | 连接仍在而最后一个子要素被释放时,`Session.bufferOlder()` 只让按 Turn 对齐的最后一页可见,并把更早的条目交给它的 `SessionEventStream`。Session 的翻页逻辑不变;stream 读页时先按请求的 Turn 窗口从这些缓冲记录中切一页返回,不发请求,用完后再读 Host 分页。窗口被整体替换时丢弃缓冲,resync、断开或销毁时随 stream 一起丢弃。[`buffered-pages.ts`](../../../../packages/api/session-controller/src/client/sessions/buffered-pages.ts) 负责分页切点 | +| 计数 | [`shiftFacetCounts`](../../../../packages/api/session-controller/src/client/sessions/facets.ts) 在 generation 的 `SessionRetainInfo` 中为每个子要素记一个计数,与 `connectionCount` 和按来源的 `retainedBy` 并列;`retainInfo(id)` 发布每次变化,owner 根据该快照与当前 binding 推导自己的子要素,因此 `SessionBinding` 不变 | +| 不可变 | 一条引用的选项在创建时固定;更改时先 retain 新引用,再 release 旧引用 | +| `using()` | 签名不变;借出的引用默认保留连接,不请求子要素 | +| `retainAgentScope` | 既不保留连接,也不保留子要素 | ### `conversation` 子要素 `ui-conversation` 声明 `conversation`:对事件窗口做 Conversation 折叠并物化其视图。 - `BoundConversation` 仍然每个 binding 一个,其 `snapshot`、`openTurn` 和 `target(t)` 数据源保持对象标识稳定。`UiConversation.binding()` 先在 Session 作用域上登记该绑定的清理,再让绑定开始跟随;首次折叠失败时清理该绑定,下次解析重新开始。 -- 子要素**开始**被保留时,绑定先订阅事件窗口,再一步完成恢复:首次折叠或未跟随期间发生的注册表变化会按当前窗口整窗重建一次;否则期间收到的连续变化走增量 assembler,revision 出现缺口时整窗重建。随后取消待发的 rAF 并同步发布一次,这次折叠失败时也是如此;折叠失败会让绑定保持过期状态,下一次窗口变化整窗重建,而不是在部分折叠结果上继续增量。未跟随期间激活的视图基于上一次折叠结果建立,并在恢复时补齐。 -- 子要素**停止**被保留时,绑定退订事件窗口并取消待发的 rAF。最后一次发布的快照仍可读取,但不再更新。切换过程中旧 DOM 尚未卸载时,其组件读到的就是这份快照。正在进行的事件分发会检查绑定是否仍在跟随,因此分发中途的释放会立即停止折叠。 -- 子要素未被保留时调用 `uiConversation.binding()`,得到的是未被保留的绑定,读取上一次或空的快照,不会抛错。 -- 跟随 `conversation` 子要素的计算有两项:`BoundConversation` 与 [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) 的 quota 监听;后者对子要素未被保留期间收到的失败既不发布也不补发提示。`binding.ctx` 上其他不由事件驱动的状态(输入 shell、命令弹层、历史图片 URL、agent preset seat)保持原有生命周期。 +- 子要素被保留期间,绑定对当前整个窗口折叠一次、同步发布,并跟随窗口变化;折叠失败时绑定保持未折叠,下一次窗口变化重新整窗折叠。 +- 子要素被释放时,绑定退订、取消待发的 rAF、丢弃折叠结果,并发布一次空结果;释放期间的注册表变化要等再次保留时才生效。正在进行的事件分发会检查绑定是否仍在跟随,因此分发中途的释放会立即停止折叠。 +- 跟随 `conversation` 子要素的计算有两项:`BoundConversation` 与 [ui-chat](../../../../packages/client/ui-chat/src/client/apply.ts) 的 quota 监听;后者对子要素未被保留期间收到的失败既不发布也不补发提示。 + +### `draft` 引用 + +[输入 hub](../../../../packages/client/ui-conversation/src/client/input/hub.ts) 在某个 Session 的输入框草稿有附件且该 Session 未被移除时,以 `{ source: 'draft', connection: false }` 持有它。因此所有视图都释放该 Session 后,作用域以及同一个输入框 shell 和其中的浏览器侧附件仍然保留;切回时重新连接并重新折叠,输入框保留附件、上传进度和失败上传的重试。移除最后一个附件、发送它或移除 Session 会释放这条引用,随后作用域销毁时释放全部草稿附件。页面卸载时仍为草稿有附件的 Session 写标记,下一个页面提示这些附件已失效。 ### 引用来源与子要素 -| 来源 | 所属包 | `facets` | +| 来源 | 所属包 | 选项 | |---|---|---| | `mainView` | ui-session 声明,ui-workspace 调用 | `{ conversation: true }` | | `sidebarView` | ui-sidebar-right | `{ conversation: true }` | | `sidebarChat` | ui-subagent | `{ conversation: true }` | -| `recentViews` | ui-workspace | 不写 | -| `using()` 调用方与 `gateway` | 各自的包 | 不写 | +| `recentViews` | ui-workspace | 不写:只保连接 | +| `draft` | ui-conversation | `{ connection: false }` | +| `using()` 调用方 | 各自的包 | 不写 | +| `gateway` | session-controller | 不保留连接的内部入口 | | 测试替身默认值 | test-support/client-runtime | `{ source: 'testFixture', facets: { conversation: true } }` | ### 最近访问会话 `recentViews` @@ -99,26 +102,30 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien **在 `SessionBinding` 上暴露子要素 observable。** `SessionBinding` 新增必需成员会让所有手写 binding(包括第三方测试替身)失效,而子要素计数本就是本地引用计数,`retainInfo` 已在按来源计数旁发布它们。 -**把 `events` 也作为子要素。** 没有连接的 Session 什么也做不了;唯一不需要连接的 Gateway 已经有独立的内部入口。 +**用固定级别代替子要素。** 固定的 `state`、`cache`、`live` 枚举无法随后续 owner 诉求扩展,而默认开启的 `connection` 加上 owner 子要素就能表达这三种状态。 + +**释放子要素后保留最后一次折叠结果。** 无主的陈旧结果会多出一个隐含状态;窗口仍在,切回时只折叠最后一页的代价很小。 + +**在根级维护草稿附件归属。** 在 Conversation 服务中记录归属并在新输入框中重新接回,等于用会话目录监听重复跟踪 Session 生命周期;保住作用域就能保住输入框本身。 **保留后台 Session 的 DOM。** React 18 没有 ``;K 个隐藏子树要付出布局、内存和订阅成本,还与 `session-maybe` 只绑定一个 Session 的设计冲突。 **未被保留时继续折叠,只推迟发布。** 流式块的 `match`/`update` 成本仍然存在。 -**自行计算已折叠输入与窗口之间的差集。** 未被保留期间,一次 attempt 可能从开始、流式到 settle 全部完成,这类差集逻辑容易出错;恢复改为复用 assembler 现有的连续变化路径与缺口重建路径。 +**自行计算已折叠输入与窗口之间的差集。** 未被保留期间,一次 attempt 可能从开始、流式到 settle 全部完成,这类差集逻辑容易出错;切回时改为从头折叠最后一页。 ## 后果 -- 后台 Session 切回时无需历史请求,而在再次显示之前不做任何 Conversation 折叠。 -- 未被保留的 Session 保留其最后一次折叠的内存,直到再次显示或其 binding 退役。 +- 最近访问会话切回时无需历史请求,只折叠最后一页;往上翻阅已加载的页不发请求。 +- 最近访问会话在内存中保留其完整的已加载窗口,但不保留 Conversation 折叠结果。 +- 带草稿附件被淘汰出最近访问会话的 Session 保留输入框,但不保留窗口,切回时要重新请求历史。 - 受关注保护的最近访问会话没有总量上限:完成未读会一直受保护直到用户读过,因此用户不在时每个以未读状态完成的 Session 都会保留其 generation、已加载的事件窗口和历史跟随流,直到被读过、标为已读、被移除或归档。 -- 切回在后台运行过的 Session 要付出一次补折,最多等同于新打开时的一次打开后折叠,但不走网络。 - 漏写 `conversation: true` 的渲染方会看到未被保留的陈旧或空快照,不会报错。 -- `SessionRetainOptions` 与 `SessionRetainInfo` 只新增可选字段;以自己的来源 retain 并渲染 Session 的第三方 Client 插件需加上 `facets: { conversation: true }`,见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md)。 +- `SessionRetainOptions` 与 `SessionRetainInfo` 只新增可选字段;以自己的来源 retain 并渲染 Session 的第三方 Client 插件需加上 `facets: { conversation: true }`,只需本地状态的插件可写 `connection: false`,见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md)。 ## 测试 -- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) 覆盖按子要素计数、只在零值变化时通知,以及子要素随 generation 退役与根释放结束。 -- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) 覆盖未被保留时零折叠、恢复时同步发布一次、与持续跟随结果一致、未跟随期间的激活与注册表变化、分发中途的释放、被打断的 rAF 发布、恢复失败,以及首次折叠失败不残留订阅。 +- [reference-ownership.client.spec.ts](../../../../packages/api/session-controller/tests/reference-ownership.client.spec.ts) 覆盖按子要素与连接计数、不建立连接地持有 Session、最后一个保留连接的引用释放后断开、最后一个子要素释放后缓冲更早页,以及计数随 generation 退役与根释放结束;[session.client.spec.ts](../../../../packages/api/session-controller/tests/session.client.spec.ts) 覆盖缓冲页翻页、Turn 跳转、缓冲页用完后的 Host 分页、实时增长后再次缓冲,以及断开后重新连接。 +- [conversation-registry.client.spec.ts](../../../../packages/client/ui-conversation/tests/conversation-registry.client.spec.ts) 覆盖释放时丢弃折叠、保留时同步折叠一次、与持续跟随结果一致、未跟随期间的激活与注册表变化、分发中途的释放、被取消的 rAF 发布、折叠失败,以及首次折叠失败不残留订阅;[draft-attachment-retention.client.spec.ts](../../../../packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts) 覆盖 `draft` 引用、其释放、被移除的 Session 与卸载标记。 - [quota-notice.client.spec.tsx](../../../../packages/client/ui-chat/tests/quota-notice.client.spec.tsx) 覆盖 quota 提示只在子要素被保留时发布。 - [recent-views.client.spec.ts](../../../../packages/client/ui-workspace/tests/recent-views.client.spec.ts) 与 [workspaces-service.client.spec.ts](../../../../packages/client/ui-workspace/tests/workspaces-service.client.spec.ts) 覆盖关注与置顶规则、retain 期间的同步重入、主视图 Session 不计数、淘汰后不自动回来、配置、由列表变化驱动的对账,以及经由同一 generation 切回最近访问会话且不重新打开历史。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml index db0702f47e..bf3ab5ad3d 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -9,11 +9,11 @@ en: 3f4030763e1f0105 zh: c8a0bc5641d7bed4 /agent-note-draft-attachments-across-session-switches/decision: - en: 40697e88c2ed6ca8 - zh: eeb363374b25c3a2 + en: 3b2603721398054c + zh: 7d2e5f3be236f1d3 /agent-note-draft-attachments-across-session-switches/alternatives-considered: - en: 2c43ad479f4a3577 - zh: 07743f45870eb0fe + en: 01a406120acfc8b9 + zh: 17a3fd9be7a303fb /agent-note-draft-attachments-across-session-switches/consequences: en: 6ac6defa552ea040 zh: aa64a3c3e54dbebc diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md index 8c33335f55..3c45613f1d 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -10,14 +10,16 @@ Switching to another Session and back emptied the composer's attachment rail whi ## Decision -**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A message the Host accepts leaves that ownership at once, while the registry keeps its attachments until the echo settles them. A retiring composer releases its attachments only when its Session was removed or a message or command was already submitted, because the Client cannot tell whether a submitted command consumed them; an aborted slash-line adjudication keeps them. Otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. +**A draft with attachments holds its Session's scope.** While a composer draft has attachments and its Session is not removed, the input hub holds the Session with a `draft` reference that keeps no event connection, as [Session retain facets and recently viewed Sessions](../architecture/2026-11-15-session-retain-facets-and-recent-views.md) defines. Switching away and evicting the Session from the recent views therefore keep the same composer shell and its attachments: an active upload keeps running, a failed upload keeps its in-place retry, and a pasted image keeps its bytes in memory. Removing the last attachment, sending it, or removing the Session releases the hold; scope teardown then releases every attachment the draft still holds. -**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session whose draft holds attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark shows the "add them again" notice. ## Alternatives considered **Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart. +**Recording draft-attachment owners in the Conversation service and re-adopting them in the next composer.** It keeps attachments without holding the scope, but it tracks Session lifetime a second time through a catalog watch and splits submission release across composer phases; holding the scope keeps the composer itself. + **Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again. ## Consequences diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md index 645a79c881..e6a29cd8fe 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -10,14 +10,16 @@ Status: implemented ## 决策 -**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。Host 接受消息时,这些附件立即退出会话归属,注册表则保留它们直到回显结算。退役的输入框只在其会话已被删除、或消息与命令已经提交时释放附件,因为客户端无法判断已提交的命令是否用掉了附件;被中止的斜杠行裁决会保留附件。其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 +**带附件的草稿持有其会话的作用域。** 输入框草稿有附件且其会话未被删除时,输入 hub 以不保留事件连接的 `draft` 引用持有该会话,见 [Session retain 子要素与最近访问会话](../architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md)。因此切走以及从最近访问会话中被淘汰时,同一个输入框 shell 和其中的附件都会保留:进行中的上传继续进行,失败的上传保留原位重试,粘贴的图片把字节保留在内存中。移除最后一个附件、发送它或删除会话会释放这条引用;随后作用域销毁时释放草稿仍持有的全部附件。 -**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个草稿持有附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记的输入框会显示「请重新添加」提示。 ## 考虑过的替代方案 **刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 +**在 Conversation 服务中记录草稿附件归属,并在下一个输入框中接回。** 它不持有作用域也能保留附件,但要通过会话目录监听再跟踪一遍 Session 生命周期,并按输入框阶段拆分已提交附件的释放;持有作用域就能保住输入框本身。 + **切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 ## 影响 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml index 69ade9e30b..bbeebe8c73 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 483a33535effae0e zh: b9c6452fe95190d9 /request-the-conversation-facet-when-rendering-a-session/change: - en: d2c046c52e75c057 - zh: ebc263b69bbcf328 + en: e7fc1fb6f9b86713 + zh: 8ed8407625f1efeb /request-the-conversation-facet-when-rendering-a-session/migration: - en: 4071df91f4ab767d - zh: c009c649bb48f478 + en: 3a61ac3c7bad44dc + zh: 62156a5c604f35a1 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md index 4c590a3239..900324ebb2 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.md @@ -11,7 +11,7 @@ English | [中文](guide.zh.md) `sessions.retain()` in `@deepseek-ai/dsh-api-session-controller/client` accepts an optional `facets` record. Every reference still keeps the Session's history stream, but Conversation assembly now runs only while some reference retains the `conversation` facet that `@deepseek-ai/dsh-client-ui-conversation` declares. The existing call signature still compiles. A Client plugin that retains a Session under its own source to render it inside a `SessionProvider`, without that facet, shows the Conversation snapshot from the last time another view rendered the Session, or an empty one, and its quota notices stop. The shipped main view, right Sidebar Session views, and subagent Sidebar chat already request the facet; plugins that retain a Session only to call its operations are unaffected. -`SessionRetainInfo`, read through `sessions.retainInfo(id)`, gains an optional `retainedFacets` count record that is absent while no reference retains any facet. +`retain()` also accepts `connection`, `true` by default; `false` keeps the Session object and its local state, such as the composer draft, without its event connection or event window. `SessionRetainInfo`, read through `sessions.retainInfo(id)`, gains optional `retainedFacets` and `connectionCount` counts that are absent while zero. ## Migration @@ -22,5 +22,5 @@ English | [中文](guide.zh.md) sessions.retain(target, { source: 'myPanel', facets: { conversation: true } }) ``` -3. Leave `sessions.using()` calls and references that only call Session operations unchanged. +3. Leave `sessions.using()` calls and references that only call Session operations unchanged; pass `connection: false` only when the reference needs neither events nor history. 4. Confirm the migration: open your view on a Session that the main view does not show, send a prompt from it, and check that the reply appears while you watch; `sessions.retainInfo(id).getSnapshot().retainedFacets?.conversation` reads a positive count while your view is open. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md index 551872c121..50e92c63a1 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/session-retain-conversation-facet/guide.zh.md @@ -11,7 +11,7 @@ description: "渲染 Session Conversation 的 Client 插件需以 conversation `@deepseek-ai/dsh-api-session-controller/client` 中的 `sessions.retain()` 接受可选的 `facets` 记录。每个引用仍会保活 Session 的历史流,但 Conversation 组装现在只在某个引用保留了 `@deepseek-ai/dsh-client-ui-conversation` 声明的 `conversation` 子要素时才运行。原有调用签名仍可编译。若 Client 插件以自己的来源 retain Session、并在 `SessionProvider` 中渲染它,却未请求该子要素,它显示的是其他视图上次渲染该 Session 时的 Conversation 快照或空快照,quota 提示也不再出现。内置的主视图、右侧边栏 Session 视图和 subagent 侧栏聊天已经请求该子要素;仅为调用 Session 操作而 retain 的插件不受影响。 -通过 `sessions.retainInfo(id)` 读取的 `SessionRetainInfo` 新增可选的 `retainedFacets` 计数记录,没有任何引用保留子要素时该字段不存在。 +`retain()` 还接受 `connection`,默认 `true`;`false` 只保活 Session 对象及其本地状态(如输入框草稿),不保留事件连接和事件窗口。通过 `sessions.retainInfo(id)` 读取的 `SessionRetainInfo` 新增可选的 `retainedFacets` 与 `connectionCount` 计数,为零时字段不存在。 ## 迁移 @@ -22,5 +22,5 @@ description: "渲染 Session Conversation 的 Client 插件需以 conversation sessions.retain(target, { source: 'myPanel', facets: { conversation: true } }) ``` -3. `sessions.using()` 调用以及只调用 Session 操作的引用保持不变。 +3. `sessions.using()` 调用以及只调用 Session 操作的引用保持不变;只有在既不需要事件也不需要历史时才传 `connection: false`。 4. 确认迁移:在你的视图中打开一个主视图未显示的 Session,从中发送一条 prompt,确认回复会在你查看时出现;视图打开期间,`sessions.retainInfo(id).getSnapshot().retainedFacets?.conversation` 读到正数。 diff --git a/packages/api/gateway/src/client/journal-stream.ts b/packages/api/gateway/src/client/journal-stream.ts index 2804feb0aa..8cc9b43926 100644 --- a/packages/api/gateway/src/client/journal-stream.ts +++ b/packages/api/gateway/src/client/journal-stream.ts @@ -211,6 +211,14 @@ export abstract class RemoteJournalStream< }) } + /** + * Record that the domain no longer publishes entries before `cursor`, so a later page may return them again. + * @param cursor - first cursor of an entry the open, published window still holds. + */ + protected releaseBefore(cursor: Cursor): void { + this.firstCursor = cursor + } + /** Replace the active physical generation while retaining the published window. */ restart(): void { this.stream.restart() diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 18270a40ed..fe21160b37 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4f2f2a5276b40d4e zh: 926bb7fc609b971a /session-controller/client-references: - en: 52524cd169a0933f - zh: 3220e5271ff5daa6 + en: d816da086dcda253 + zh: 0f6efc1efff58efb /session-controller/session-media-references: en: 954923654eebe2dc zh: 6bd9a7d2ea965aed diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 7cffbb1ecb..189ba185a7 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -85,9 +85,9 @@ The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads onc ## Client references -`sessions.retain(target, { source, facets?, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. +`sessions.retain(target, { source, connection?, facets?, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. -References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. Every reference keeps the history stream; `facets` names owner-declared parts beyond it, such as `conversation`, that the reference also keeps alive. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `retainInfo(id)` reports positive per-facet counts in `retainedFacets`, which is absent while no reference retains any facet. The Controller counts facets without interpreting them or their dependencies. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. +References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. Every reference keeps the Session object and its scope. `connection`, `true` by default, also keeps the Session's own event connection and the event window it keeps current; when no reference keeps it, the Session disconnects, empties its window, and keeps local state such as pending submission echoes, and the next connected reference connects as a first open. A `connection: false` reference is ready once its binding exists. `facets` names owner-declared computations over that data, such as `conversation`. When the last facet is released while the connection remains, the Session keeps only its last Turn-aligned page visible and its event stream holds the older entries in memory, so page reads return them without a request before Host paging resumes. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `retainInfo(id)` reports positive per-facet counts in `retainedFacets` and the connected reference count in `connectionCount`, each absent while zero. The Controller counts facets without interpreting them or their dependencies. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 198322d31f..35683bb228 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -85,9 +85,9 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 ## Client 引用 -`sessions.retain(target, { source, facets?, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 +`sessions.retain(target, { source, connection?, facets?, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 -引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活历史流;`facets` 指明在此之外由 owner 声明、该引用同时保活的部分,例如 `conversation`。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`retainInfo(id)` 在 `retainedFacets` 中报告各子要素的正计数,没有任何引用保留子要素时该字段不存在。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 +引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活 Session 对象及其作用域。`connection` 默认为 `true`,同时保活 Session 自己的事件连接及其维持最新的事件窗口;没有引用保留连接时,Session 断开连接、清空窗口并保留发送回显等本地状态,下一个保留连接的引用按首次打开的流程重新连接。`connection: false` 的引用在 binding 建好时即就绪。`facets` 指明由 owner 声明、基于这些数据的计算,例如 `conversation`。连接仍在而最后一个子要素被释放时,Session 只让按 Turn 对齐的最后一页可见,更早的条目由其事件流留在内存里,读页时先从本地返回、不发请求,用完后再走 Host 分页。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`retainInfo(id)` 在 `retainedFacets` 中报告各子要素的正计数,在 `connectionCount` 中报告保留连接的引用数,为零时字段不存在。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 ## 会话媒体引用 diff --git a/packages/api/session-controller/src/client/contract/sessions.ts b/packages/api/session-controller/src/client/contract/sessions.ts index ab7a796ec5..c18117cd38 100644 --- a/packages/api/session-controller/src/client/contract/sessions.ts +++ b/packages/api/session-controller/src/client/contract/sessions.ts @@ -36,10 +36,16 @@ export interface SessionReference extends Disposable { export interface SessionRetainOptions { readonly source: SessionReferenceSource /** - * Facets this reference keeps alive beyond the history stream every reference retains. - * A facet is retained only when its key is `true`; the set is fixed for the reference's lifetime. + * Whether this reference keeps the Session's own event connection and the event window it keeps current, so a + * return shows the data at once. Defaults to `true`; `false` keeps only the Session object and its local state, + * such as the composer draft. This is not the page's transport connection. */ - readonly facets?: Readonly>> | undefined + readonly connection?: boolean | undefined + /** + * Owner-declared facets this reference keeps computing over the Session's data; an absent key is not computed. + * The set is fixed for the reference's lifetime. + */ + readonly facets?: Readonly>> | undefined readonly signal?: AbortSignal | undefined } @@ -53,6 +59,8 @@ export interface SessionRetainInfo { * Owners read their facet here, for example `(info.retainedFacets?.conversation ?? 0) > 0`. */ readonly retainedFacets?: Readonly>> + /** Positive count of references keeping the event connection; absent while none does. */ + readonly connectionCount?: number } /** The sessions-service face injected as `ctx.sessions`. */ diff --git a/packages/api/session-controller/src/client/sessions/buffered-pages.ts b/packages/api/session-controller/src/client/sessions/buffered-pages.ts new file mode 100644 index 0000000000..299cc0843a --- /dev/null +++ b/packages/api/session-controller/src/client/sessions/buffered-pages.ts @@ -0,0 +1,41 @@ +/** Turn-aligned page cuts over buffered Session entries. */ +import type { SessionEventLikeEntry, SessionLiveEventEntry } from '../contract/events.ts' + +/** Minimum messages and Turn starts one page covers, as the Host pages history. */ +export interface PageRule { + readonly minMessages: number + readonly minTurns: number +} + +/** + * Find where the last page of `entries` starts: the latest `turn/start` at or before which the page holds at least + * `minMessages` user or assistant messages and crosses at least `minTurns` Turn starts. + * @param entries - contiguous entries or wire records in seq order. + * @param rule - page minima; absent minima make the whole range one page. + * @returns index of the page's first entry; 0 when the whole range is one page. + */ +export function tailPageStart( + entries: readonly { readonly event: { readonly type: string } }[], + rule: PageRule | undefined, +): number { + if (rule === undefined) return 0 + let messages = 0 + let turns = 0 + for (let index = entries.length - 1; index > 0; index--) { + const type = entries[index]?.event.type + if (type === 'user/message' || type === 'assistant/message') messages++ + if (type !== 'turn/start') continue + turns++ + if (messages >= rule.minMessages && turns >= rule.minTurns) return index + } + return 0 +} + +/** + * Whether a window entry is a durable event rather than a transient Assistant chunk. + * @param entry - window entry. + * @returns true for a durable event. + */ +export function isDurableEntry(entry: SessionEventLikeEntry): entry is SessionLiveEventEntry { + return entry.type === 'event' +} diff --git a/packages/api/session-controller/src/client/sessions/history-records.ts b/packages/api/session-controller/src/client/sessions/history-records.ts index 9a7f14cfa6..01144849d6 100644 --- a/packages/api/session-controller/src/client/sessions/history-records.ts +++ b/packages/api/session-controller/src/client/sessions/history-records.ts @@ -3,7 +3,7 @@ import type { SessionHistoryRecord, } from '../../types.ts' -import type { SessionEventLikeEntry } from '../contract/events.ts' +import type { SessionEventLikeEntry, SessionLiveEventEntry } from '../contract/events.ts' /** * Narrow aligned wire records to their Client event types without allocation. @@ -13,7 +13,21 @@ import type { SessionEventLikeEntry } from '../contract/events.ts' export function historyEntries( records: readonly SessionHistoryRecord[], ): readonly SessionEventLikeEntry[] { - return records as unknown as readonly SessionEventLikeEntry[] + // Both views share the same validated objects. + const aligned: readonly unknown[] = records + return aligned as readonly SessionEventLikeEntry[] +} + +/** + * View durable window entries, which the Client received as validated wire records, as those records again. + * @param entries - durable entries taken from the event window. + * @returns the same array typed as history transport records. + */ +export function historyRecords( + entries: readonly SessionLiveEventEntry[], +): readonly SessionHistoryRecord[] { + const aligned: readonly unknown[] = entries + return aligned as readonly SessionHistoryRecord[] } /** diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index 5b14bde1ac..326493f9b4 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -170,8 +170,26 @@ function retentionOf( referenceCount: number, retainedBy: SessionRetainInfo['retainedBy'], retainedFacets: SessionRetainInfo['retainedFacets'], + connectionCount: number, ): SessionRetainInfo { - return Object.freeze({ referenceCount, retainedBy, ...(retainedFacets === undefined ? {} : { retainedFacets }) }) + return Object.freeze({ + referenceCount, + retainedBy, + ...(retainedFacets === undefined ? {} : { retainedFacets }), + ...(connectionCount === 0 ? {} : { connectionCount }), + }) +} + +/** + * Drop what no remaining reference keeps: the connection when none keeps it, otherwise the older window pages + * when no facet computes over them any longer. + */ +function releaseConnectionWork(session: Session, before: SessionRetainInfo, after: SessionRetainInfo): void { + if ((before.connectionCount ?? 0) > 0 && after.connectionCount === undefined) { + void session.disconnect() + return + } + if (before.retainedFacets !== undefined && after.retainedFacets === undefined) session.bufferOlder() } const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) }) @@ -309,12 +327,13 @@ export class ClientSessions implements ISessions { retain(target: SessionTarget, options: SessionRetainOptions): SessionReference { const { source, signal, facets } = options + const connected = options.connection !== false signal?.throwIfAborted() if (this.closed) throw new Error('Session Controller is disposed') const id = this.manager.resolveTarget(target) - const reference = this.retainScope(id, source, heldFacets(facets)) + const reference = this.retainScope(id, source, heldFacets(facets), connected) try { - reference.attachOpening(this.manager.get(id).open(), signal) + reference.attachOpening(connected ? this.manager.get(id).open() : Promise.resolve(), signal) return reference } catch (error) { reference.release() @@ -526,7 +545,7 @@ export class ClientSessions implements ISessions { */ retainAgentScope(id: SessionId): SessionReference { if (this.closed) throw new Error('Session Controller is disposed') - return this.retainScope(id, 'gateway', []) + return this.retainScope(id, 'gateway', [], false) } /** @@ -572,24 +591,37 @@ export class ClientSessions implements ISessions { id: SessionId, source: SessionReferenceSource, facets: readonly SessionRetainFacet[], + connected: boolean, ): ClientSessionReference { const record = this.scopes.get(id) ?? this.materializeScope(id) const previous = record.retention + const connection = connected ? 1 : 0 record.retention = retentionOf( previous.referenceCount + 1, freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), shiftFacetCounts(previous.retainedFacets, facets, 1), + (previous.connectionCount ?? 0) + connection, ) const reference = new ClientSessionReference(id, record, () => { if (!record.live) return - const count = record.retention.referenceCount - 1 - const { [source]: sourceCount = 0, ...otherSources } = record.retention.retainedBy + const before = record.retention + const count = before.referenceCount - 1 + const { [source]: sourceCount = 0, ...otherSources } = before.retainedBy const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources record.retention = count === 0 ? EMPTY_RETAIN_INFO - : retentionOf(count, freezeRetainedBy(retainedBy), shiftFacetCounts(record.retention.retainedFacets, facets, -1)) - if (count === 0) this.retireScope(id, record) - else this.publishRetention(id) + : retentionOf( + count, + freezeRetainedBy(retainedBy), + shiftFacetCounts(before.retainedFacets, facets, -1), + (before.connectionCount ?? 0) - connection, + ) + if (count === 0) { + this.retireScope(id, record) + return + } + this.publishRetention(id) + releaseConnectionWork(record.session, before, record.retention) }) if (this.list.getSnapshot().byId[id] === undefined && this.manager.subagentAddress(id) !== undefined) { this.projectList() diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 9b795949ab..1f6c34eb73 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -8,6 +8,7 @@ import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { MessageId } from '@deepseek-ai/dsh-llm/types' import type { UserMessage } from '@deepseek-ai/dsh-llm/types' import { SessionLogOffset, SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types' +import { isDurableEntry, tailPageStart } from './buffered-pages.ts' import { SessionEventStream } from '../transport.ts' import type { SessionJournalChange } from '../transport.ts' import type { @@ -680,6 +681,46 @@ export class Session implements SessionFace { this.notifier.markDirty() } + /** + * Keep only the last page visible and buffer the older entries in the event stream, so paging back returns them + * without a request. Applies only to an open window longer than one page with no paging in progress. + */ + bufferOlder(): void { + const events = this.events + if (this.openState !== 'open' || events === undefined || this.olderRequest !== null || this.pendingHistory !== null) return + const { entries } = this.eventSource.getSnapshot() + const start = tailPageStart(entries, HISTORY_PAGE_OPTIONS.turnWindow) + const first = entries[start] + const older = entries.slice(0, start) + if (first === undefined || older.length === 0 || !older.every(isDurableEntry)) return + events.bufferOlder(older, first.event.seq, this.hasMore) + this.baseSeq = SessionLogOffset(first.event.seq) + this.hasMore = true + this.eventSource.replace(entries.slice(start), true) + this.notifier.markDirty() + } + + /** + * Close the event connection and drop the window while keeping the Session object, including pending + * submission echoes; the next `open()` connects as the first open did. + * @returns when the Remote iterator has completed teardown. + */ + async disconnect(): Promise { + if (this.openState === 'cold') return + this.openGeneration++ + this.clearOlderHistory() + const events = this.events + this.events = undefined + this.openPromise = null + this.openState = 'cold' + this.openError = null + this.baseSeq = SessionLogOffset(0) + this.hasMore = false + this.eventSource.replace([], false) + this.notifier.markDirty() + await events?.dispose() + } + /** * Stop the Session's live Remote source. * @returns when the Remote iterator has completed teardown. diff --git a/packages/api/session-controller/src/client/transport.ts b/packages/api/session-controller/src/client/transport.ts index cc115f30cc..996151c306 100644 --- a/packages/api/session-controller/src/client/transport.ts +++ b/packages/api/session-controller/src/client/transport.ts @@ -21,10 +21,12 @@ import type { SessionPageRequest, SessionProjectionBaseline, } from '../types.ts' +import { tailPageStart } from './sessions/buffered-pages.ts' import { historyEntries, historyRecordFirstSeq, historyRecordLastSeq, + historyRecords, } from './sessions/history-records.ts' import type { SessionEventLikeEntry, SessionLiveEventEntry } from './contract/events.ts' import type { SessionRemotes } from './sessions/remotes.ts' @@ -134,7 +136,18 @@ export function createSessionControlStream( }) } -/** Gateway-owned event journal bound to one ordinary or direct-subagent Session address. */ +/** Older records the published window released into memory, served to page reads before the Host. */ +interface BufferedRecords { + /** Contiguous records before the published window, oldest first. */ + records: readonly SessionHistoryRecord[] + /** Whether the Host has history before `records`. */ + hostHasMore: boolean +} + +/** + * Gateway-owned event journal bound to one ordinary or direct-subagent Session address. Pages before the published + * window come from buffered records first and from the Host after they run out; a replaced window drops the buffer. + */ export class SessionEventStream extends RemoteJournalStream< SessionJournalPage, SessionHistoryRecord, @@ -152,6 +165,7 @@ export class SessionEventStream extends RemoteJournalStream< private readonly address: SessionAddress, options: SessionEventStreamOptions, ) { + const buffered: BufferedRecords = { records: [], hostHasMore: false } super(remote, { name: 'session event stream', emptyCursor: -1, @@ -161,12 +175,31 @@ export class SessionEventStream extends RemoteJournalStream< last: historyRecordLastSeq, compare: (left, right) => left - right, follows: (left, right) => right === left + 1, - publish: (change) => { options.publish(toSessionJournalChange(change)) }, + publish: (change) => { + if (change.type === 'replace') buffered.records = [] + options.publish(toSessionJournalChange(change)) + }, ...(options.carrierFailed === undefined ? {} : { carrierFailed: options.carrierFailed }), failed: options.failed, }) + this.buffered = buffered + } + + private readonly buffered: BufferedRecords + + /** + * Release the start of the published window into memory; later pages before the window return it without a + * request. + * @param entries - durable entries at the window's start, oldest first, that the window no longer shows. + * @param firstSeq - seq of the first entry the window still shows. + * @param hostHasMore - whether the Host has history before `entries`; ignored while older entries are buffered. + */ + bufferOlder(entries: readonly SessionLiveEventEntry[], firstSeq: number, hostHasMore: boolean): void { + if (this.buffered.records.length === 0) this.buffered.hostHasMore = hostHasMore + this.buffered.records = [...this.buffered.records, ...historyRecords(entries)] + this.releaseBefore(firstSeq) } /** @inheritdoc */ @@ -227,6 +260,12 @@ export class SessionEventStream extends RemoteJournalStream< throughSeq: number, signal: AbortSignal, ): Promise { + const buffered = this.buffered.records + if (buffered.length > 0) { + const start = tailPageStart(buffered, request.turnWindow) + this.buffered.records = buffered.slice(0, start) + return { records: buffered.slice(start), hasMore: start > 0 || this.buffered.hostHasMore } + } const result = await this.remote.session.page( { address: this.address, throughSeq, ...request }, signal, diff --git a/packages/api/session-controller/tests/reference-ownership.client.spec.ts b/packages/api/session-controller/tests/reference-ownership.client.spec.ts index d1ce84c944..80f0c14d04 100644 --- a/packages/api/session-controller/tests/reference-ownership.client.spec.ts +++ b/packages/api/session-controller/tests/reference-ownership.client.spec.ts @@ -9,6 +9,7 @@ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { ok, type RemoteMock } from '@deepseek-ai/dsh-remote-mock' import { createClientTest, webApp, type TestClient } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import { ClientSessions } from '../src/client/sessions/service.ts' +import { Session } from '../src/client/sessions/session.ts' import { FOLLOW, followScript, type HistoryAnswer } from './remote/session.client.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -79,7 +80,9 @@ describe('Client reference sources', () => { const second = b.svc.retain(ID, { source: workSource }) const acquisitions = Promise.allSettled([first.ready, second.ready]) expect(binding).toBeDefined() - expect(source.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { referenceTestView: 1, referenceTestWork: 1 } }) + expect(source.getSnapshot()).toEqual({ + referenceCount: 2, retainedBy: { referenceTestView: 1, referenceTestWork: 1 }, connectionCount: 2, + }) expect(b.svc.list.getSnapshot().byId[ID]?.retainedBy).toBe(source.getSnapshot().retainedBy) await entered.promise expect(mock.log.requests(FOLLOW)).toHaveLength(1) @@ -92,7 +95,7 @@ describe('Client reference sources', () => { expect(a.binding.session.getSnapshot().openState).toBe('open') a.release() a[Symbol.dispose]() - expect(source.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 } }) + expect(source.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 }, connectionCount: 1 }) expect(() => a.binding).toThrow('is released') c.release() expect(source.getSnapshot()).toEqual({ referenceCount: 0, retainedBy: {} }) @@ -105,7 +108,7 @@ describe('Client reference sources', () => { using second = b.svc.retain(ID, { source: workSource }) await Promise.all([first.ready, second.ready]) const source = b.svc.retainInfo(ID) - expect(source.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { referenceTestWork: 2 } }) + expect(source.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { referenceTestWork: 2 }, connectionCount: 2 }) first.release() expect(source.getSnapshot().retainedBy.referenceTestWork).toBe(1) second.release() @@ -160,7 +163,9 @@ describe('Client reference sources', () => { mock.stream(FOLLOW, followScript(() => Promise.reject(failure))) const failed = b.svc.retain(ID, { source: viewSource }) await expect(failed.ready).resolves.toBe(binding) - expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { gateway: 1, referenceTestView: 1 } }) + expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ + referenceCount: 2, retainedBy: { gateway: 1, referenceTestView: 1 }, connectionCount: 1, + }) expect(binding.session.getSnapshot().openState).toBe('error') failed.release() mock.stream(FOLLOW, followScript(EMPTY_HISTORY)) @@ -182,9 +187,11 @@ describe('Client reference sources', () => { const rejected = expect(cancelled.ready).rejects.toBe(reason) controller.abort(reason) await rejected - expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { referenceTestView: 1, referenceTestWork: 1 } }) + expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ + referenceCount: 2, retainedBy: { referenceTestView: 1, referenceTestWork: 1 }, connectionCount: 2, + }) cancelled.release() - expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 } }) + expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 }, connectionCount: 1 }) opening.resolve(EMPTY_HISTORY) using reference = survivor await reference.ready @@ -293,9 +300,9 @@ describe('Client retained facets', () => { const b = await bench(mock, start) const info = b.svc.retainInfo(ID) using plain = b.svc.retain(ID, { source: workSource }) - expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 } }) + expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 }, connectionCount: 1 }) expect('retainedFacets' in info.getSnapshot()).toBe(false) - const first = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true, referenceTestOtherFacet: false } }) + const first = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) const second = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) expect(info.getSnapshot().retainedFacets).toEqual({ referenceTestFacet: 2 }) expect(b.svc.list.getSnapshot().byId[ID]?.retainedBy).toEqual({ referenceTestWork: 1, referenceTestView: 2 }) @@ -320,6 +327,47 @@ describe('Client retained facets', () => { }) }) +describe('Client connection retention', () => { + it('holds a Session without connecting it and connects once a reference keeps the connection', async ({ mock, start }) => { + const b = await bench(mock, start) + const held = b.svc.retain(ID, { source: workSource, connection: false }) + await held.ready + expect(held.binding.session.getSnapshot().openState).toBe('cold') + expect(mock.log.requests(FOLLOW)).toHaveLength(0) + expect(b.svc.retainInfo(ID).getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { referenceTestWork: 1 } }) + const viewed = b.svc.retain(ID, { source: viewSource }) + await viewed.ready + expect(viewed.binding).toBe(held.binding) + expect(viewed.binding.session.getSnapshot().openState).toBe('open') + expect(b.svc.retainInfo(ID).getSnapshot().connectionCount).toBe(1) + viewed.release() + await vi.waitFor(() => { expect(held.binding.session.getSnapshot().openState).toBe('cold') }) + expect(b.svc.binding(ID)).toBe(held.binding) + held.release() + expect(b.svc.binding(ID)).toBeUndefined() + }) + + it('keeps the connection while another reference keeps it', async ({ mock, start }) => { + const b = await bench(mock, start) + using first = b.svc.retain(ID, { source: viewSource }) + const second = b.svc.retain(ID, { source: workSource }) + await Promise.all([first.ready, second.ready]) + second.release() + expect(first.binding.session.getSnapshot().openState).toBe('open') + expect(b.svc.retainInfo(ID).getSnapshot().connectionCount).toBe(1) + }) + + it('buffers the older window pages when the last facet is released', async ({ mock, start }) => { + const b = await bench(mock, start) + const buffered = vi.spyOn(Session.prototype, 'bufferOlder') + using view = b.svc.retain(ID, { source: workSource }) + const rendered = b.svc.retain(ID, { source: viewSource, facets: { referenceTestFacet: true } }) + await Promise.all([view.ready, rendered.ready]) + rendered.release() + expect(buffered).toHaveBeenCalledOnce() + }) +}) + describe('ClientSessions.using', () => { it('awaits callback settlement before releasing and returns its result', async ({ mock, start }) => { const b = await bench(mock, start) diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index 1d4fc6f65a..5bf0b24f0f 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -182,6 +182,120 @@ describe('live event path', () => { }) }) +/** `count` consecutive plain Turns of six events each, starting at seq 0. */ +function turns(count: number): SessionEvent[] { + return Array.from({ length: count }, (_, turn) => plainTurn(SessionSeq(turn * 6), turn, `ask ${turn}`, `answer ${turn}`)).flat() +} + +describe('buffered older pages', () => { + // 60 Turns hold 120 messages: the 50-message, two-Turn page rule cuts them into three pages. + const all = turns(60) + + it('keeps only the last page visible and pages the buffered entries back without a request', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(all))) + await session.open() + session.bufferOlder() + const tail = eventSeqs(session) + expect(tail.length).toBeLessThan(all.length) + expect(tail.at(-1)).toBe(all.at(-1)!.seq) + expect(session.getSnapshot().hasMore).toBe(true) + while (session.getSnapshot().hasMore) { + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot().historyLoadStatus).toBe('pendingConsumption') + expect(session.consumeOlder()).toBe(true) + } + expect(eventSeqs(session)).toEqual(all.map(event => event.seq)) + expect(mock.log.requests(PAGE)).toHaveLength(0) + }) + + it('continues paging from the Host after the buffered entries run out', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const window = turns(61).slice(6) + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(window, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + session.bufferOlder() + await session.loadThrough(SessionSeq(6)) + expect(eventSeqs(session)[0]).toBe(6) + expect(mock.log.requests(PAGE)).toHaveLength(0) + await session.loadOlder() + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)[0]).toBe(0) + expect(session.getSnapshot().hasMore).toBe(false) + }) + + it('serves a turn jump from buffered entries in jump-sized pages without a request', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(all))) + await session.open() + session.bufferOlder() + const tailStart = eventSeqs(session)[0]! + await session.loadThrough(SessionSeq(tailStart - 1)) + // A jump page asks for 200 messages, more than the buffered entries carry, so one page returns all of them. + expect(eventSeqs(session)).toEqual(all.map(event => event.seq)) + expect(session.getSnapshot().hasMore).toBe(false) + expect(mock.log.requests(PAGE)).toHaveLength(0) + }) + + it('drops buffered entries with the stream on resync', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(all))) + mock.remote.session.page.mockImplementation(pageRule(history(older, true))) + await session.open() + session.bufferOlder() + await session.resync() + await session.loadOlder() + expect(mock.log.requests(PAGE)).toHaveLength(0) + expect(eventSeqs(session)).toEqual(all.map(event => event.seq)) + }) + + it('buffers again after live events grow the window and keeps the Host boundary of the first buffer', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const window = turns(61).slice(6) + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(window, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + session.bufferOlder() + const firstTail = eventSeqs(session)[0]! + for (const event of plainTurn(SessionSeq(366), 61, 'more', 'answer')) await pushEvent(mock, event) + for (const event of turns(80).slice(372)) await pushEvent(mock, event) + session.bufferOlder() + expect(eventSeqs(session)[0]).toBeGreaterThan(firstTail) + while (session.getSnapshot().hasMore) await session.loadOlder() + expect(eventSeqs(session)[0]).toBe(0) + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + + it('buffers nothing for a short, closed, or paging window', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + session.bufferOlder() + mock.stream(FOLLOW, followScript(history(turns(2)))) + await session.open() + session.bufferOlder() + expect(eventSeqs(session)).toEqual(turns(2).map(event => event.seq)) + expect(session.getSnapshot().hasMore).toBe(false) + }) + + it('disconnects to a cold Session that keeps nothing of its window and reconnects as a first open', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(all))) + await session.open() + session.bufferOlder() + await session.disconnect() + expect(session.getSnapshot()).toMatchObject({ openState: 'cold', hasMore: false }) + expect(eventSeqs(session)).toEqual([]) + await session.disconnect() + mock.stream(FOLLOW, followScript(history(all))) + await session.open() + expect(eventSeqs(session)).toEqual(all.map(event => event.seq)) + expect(mock.log.requests(FOLLOW)).toHaveLength(2) + }) +}) + describe('paging', () => { it('prepends an older page and keeps seq continuity', async ({ mock, start }) => { const older = plainTurn(SessionSeq(0), 0, '旧问', '旧答') diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 07d4843e4e..93fb959b52 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -15,14 +15,14 @@ en: eef4f18c3972ccc4 zh: 6be65c6ac84ce497 /deepseek-ai-dsh-client-ui-conversation/conversation-assembly: - en: 541e9f117a5ef93b - zh: f6ad83efa7d9783f + en: 4dcb2d887e3df57f + zh: d4a6e5f4f9a4d67d /deepseek-ai-dsh-client-ui-conversation/sent-user-text: en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: ff204aa7b6c6666a - zh: 5b437f63b8e18f95 + en: 8ad7f24bef08474a + zh: 23accc0d5e837714 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index bc818a566c..358a1c0d46 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -32,7 +32,7 @@ Desktop product events use the optional [product analytics service](../product-a `ConversationBinding.openTurn` is an identity-stable, read-only source of the latest turn number when its start is loaded and it remains open, or `undefined` otherwise. While the `conversation` retain facet is held, observed turn changes publish synchronously even when no View is active. Fixed stop input reads this source alongside Session running and pending-interaction state. Unloading the Session binding detaches its event-source subscription. -The package declares the `conversation` retain facet. A binding follows its event source only while some Session reference retains that facet, which rendering owners such as the main view and Sidebar views request. While it is not retained, the Session still receives events but the binding neither folds nor publishes: readers see the last published snapshot, and target activations and registry rebuilds wait. When retention resumes, the binding folds the events received meanwhile, rebuilding from the complete window after a gap, and publishes once. +The package declares the `conversation` retain facet. A binding follows its event source only while some Session reference retains that facet, which rendering owners such as the main view and Sidebar views request. When the last such reference is released, the binding drops its fold and publishes the empty result; the Session still receives events, and the Session Controller keeps only the last page of its window visible. When retention resumes, the binding folds that window once and publishes it, and paging back folds each older page as it arrives. The adapter passes each `SessionEventLikeEntry` directly to the assembler. Its outer `type` distinguishes durable events from Client-only transient events, while its inner `event` always exposes `type`, `seq`, `time`, and `data`; Definitions receive that inner `SessionEventLike`. Replacement windows may include both entry variants, while historical prepends carry durable entries and live appends may carry either. Definitions use the same match/start/update interface for durable and transient events. The earliest loaded start initializes State; every later Match, including another start for that identity, updates it. Definitions that do not consume Assistant deltas return `null` for `assistant/live-chunk`. Replacement windows and revision gaps rebuild from the complete loaded window; contiguous append, prepend, and Assistant-settlement revisions use incremental assembly. Settlement removes only the named attempt's transient matches, applies its optional durable entry, and recomputes the affected Contexts from their remaining earliest start, refreshing predecessor indexes and dependents without replacing unrelated target nodes. A Context with no remaining start has no State. Its key and previously published nodes remain available to later evidence until a full window rebuild; the owning Definition may hide those nodes. The assembler owns Context matching, Turn/Step locations, target node materialization, target activity, and stable target sources. `ConversationSnapshot` contains only target-neutral views and active-target facts; Session lifecycle state remains in `SessionSnapshot`. @@ -102,7 +102,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.canInsertReferences()` reads the current precondition without notifying changes: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set, and `addReferences` rechecks it. Quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.canInsertReferences()` reads the current precondition without notifying changes: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set, and `addReferences` rechecks it. Quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; while a draft has attachments, the input hub holds its Session with a `draft` reference that keeps no event connection, so the same composer keeps them after every view releases the Session. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 70151a12f6..a493dcb319 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -32,7 +32,7 @@ kind: "package-reference" `ConversationBinding.openTurn` 是对象标识稳定的只读来源:最新轮次的开始事件已加载且尚未结束时提供其编号,否则为 `undefined`。在 `conversation` retain 子要素被保留期间,观察到的轮次变化同步发布,即使没有活动视图也是如此。固定停止输入同时读取这个来源、会话运行状态和待处理交互状态。卸载会话绑定会解除其事件源订阅。 -本包声明 `conversation` retain 子要素。只有当某个 Session 引用保留该子要素时,绑定才跟随其事件源;主视图和侧栏视图等渲染方会请求它。未被保留时,Session 仍接收事件,但绑定既不折叠也不发布:读取方看到最后一次发布的快照,目标激活与注册表重建也会等待。恢复保留后,绑定折叠期间收到的事件(出现缺口时从完整窗口重建),并发布一次。 +本包声明 `conversation` retain 子要素。只有当某个 Session 引用保留该子要素时,绑定才跟随其事件源;主视图和侧栏视图等渲染方会请求它。最后一个这样的引用被释放时,绑定丢弃折叠结果并发布一次空结果;Session 仍接收事件,Session Controller 只让其窗口的最后一页可见。恢复保留后,绑定对该窗口折叠一次并发布,往上翻页时逐页折叠新进入的页。 适配器把每个 `SessionEventLikeEntry` 直接交给 assembler。外层 `type` 区分持久事件与 Client-only transient event,内部 `event` 则统一公开 `type`、`seq`、`time` 与 `data`;Definition 接收这个内部 `SessionEventLike`。replacement window 可以包含两种 entry,历史 prepend 携带持久 entry,实时 append 则可以携带任一种。持久与瞬态事件使用同一组 match/start/update 接口。当前最早的 start 初始化 State;后续所有 Match,包括同一身份的其他 start,都用于更新。不消费 Assistant delta 的 Definition 对 `assistant/live-chunk` 返回 `null`。replace window 或 revision 断档从完整已加载窗口重建;连续 revision 的 append、prepend 与 Assistant settlement 使用增量组装。settlement 只删除具名 attempt 的 transient match,应用可选持久 entry,并从剩余最早的 start 重算受影响的 Context,刷新前序索引及 dependent,不替换无关 target node。没有剩余 start 的 Context 不保留 State,但其 key 和已发布节点仍保留,供后续证据复用,直到完整窗口重建;所属 Definition 可以隐藏这些节点。assembler 拥有 Context 匹配、Turn/Step location、target node 物化、target activity 和稳定 target source。`ConversationSnapshot` 只包含与 target 无关的 View 与 active-target 事实;Session lifecycle 状态仍属于 `SessionSnapshot`。 @@ -102,7 +102,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.canInsertReferences()` 读取当前的前置条件,不通知变化:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false,`addReferences` 执行时会再次检查。引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.canInsertReferences()` 读取当前的前置条件,不通知变化:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false,`addReferences` 执行时会再次检查。引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;草稿有附件期间,输入 hub 以不保留事件连接的 `draft` 引用持有其 Session,因此所有视图都释放该 Session 后,同一个输入框仍保留这些附件。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index f1094a37fc..75c8ca3364 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -30,9 +30,9 @@ import { UserTextRegistry } from './user-text-registry.ts' declare module '@deepseek-ai/dsh-api-session-controller/client' { interface SessionRetainFacetMap { /** - * Conversation assembly of the Session's event window. While no reference retains it, the - * Session still receives events but its Conversation binding neither folds nor publishes; - * readers see the last published snapshot until retention resumes and folds the window once. + * Conversation assembly of the Session's event window. While a reference retains it, the binding folds the + * window and follows its changes; when the last such reference is released, the binding drops the fold and + * publishes the empty result, and retaining it again folds the current window once. */ conversation: unknown } @@ -51,7 +51,7 @@ export interface ConversationBinding { readonly openTurn: ObservableSnapshot /** * Add one selected target to the Session's monotonic active set; while the facet is not retained, - * the target's view is built from the last folded state and catches up when retention resumes. + * the target's view stays empty until retention folds the window. * @param target - registered or subsequently registered Conversation target. */ activate(target: string): void @@ -75,11 +75,8 @@ class BoundConversation implements ConversationBinding { private revision = -1 private frame: number | undefined private following = false - /** - * The next window change rebuilds the whole window: set until the first fold, by registry changes while not - * following, and by a failed resumption, whose partial fold must not be extended incrementally. - */ - private stale = true + /** Whether the assembler holds the window at `revision`; a failed fold leaves nothing to extend incrementally. */ + private folded = false private disposeFeed: () => void = () => {} private disposeRetained: () => void = () => {} @@ -131,10 +128,8 @@ class BoundConversation implements ConversationBinding { } rebuild(): void { - if (!this.following) { - this.stale = true - return - } + // A binding that does not follow holds no fold; following again rebuilds against the current registry. + if (!this.following) return this.publish(this.assembler.rebuildRegistry()) } @@ -146,16 +141,21 @@ class BoundConversation implements ConversationBinding { } /** - * Start or stop following the feed. Stopping keeps the last published snapshot readable. - * Resuming subscribes first, so a failed catch-up is repaired by the next window change. + * Start or stop following the feed. Starting folds the whole current window and publishes it at once; + * stopping drops the fold and publishes the empty result. */ private follow(retained: boolean): void { if (retained === this.following) return this.following = retained + this.cancelFrame() if (!retained) { this.disposeFeed() this.disposeFeed = () => {} - this.cancelFrame() + this.folded = false + this.publishing(() => { + this.assembler.rebuildRegistry([], false) + return this.assembler.flush() + }) return } // A dispatch already in progress keeps a copy of its listeners, so the callback checks @@ -163,24 +163,20 @@ class BoundConversation implements ConversationBinding { this.disposeFeed = this.feed.subscribe(() => { if (this.following) this.accept(this.feed.getSnapshot()) }) - this.resume() + this.foldWindow() } - /** - * Fold the window changes received while not following and publish once synchronously: a stale - * binding rebuilds the whole window, otherwise contiguous changes fold incrementally and a gap rebuilds. - * A failed fold leaves the binding stale, so the next window change rebuilds the whole window. - */ - private resume(): void { - try { - this.accept(this.feed.getSnapshot()) - } catch (error: unknown) { - this.stale = true - throw error - } finally { - this.cancelFrame() - this.publishing(() => this.assembler.flush()) - } + /** Fold the whole current window against the current registry and publish it synchronously. */ + private foldWindow(): void { + const window = this.feed.getSnapshot() + this.folded = false + this.cancelFrame() + this.publishing(() => { + this.assembler.rebuildRegistry(window.entries, window.hasMore) + this.revision = window.revision + this.folded = true + return this.assembler.flush() + }) } private replace(window: SessionEventWindow): void { @@ -188,15 +184,9 @@ class BoundConversation implements ConversationBinding { this.publish(this.assembler.replaceWindow(window.entries, window.hasMore)) } - private rebuildWindow(window: SessionEventWindow): void { - this.revision = window.revision - this.publish(this.assembler.rebuildRegistry(window.entries, window.hasMore)) - this.stale = false - } - private accept(window: SessionEventWindow): void { - if (this.stale) { - this.rebuildWindow(window) + if (!this.folded) { + this.foldWindow() return } if (window.revision === this.revision) return diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 7844495e2e..ad18048d26 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -9,7 +9,7 @@ import type { PlanProjection } from '@deepseek-ai/dsh-plan-mode/types' import type { GoalProjection } from '@deepseek-ai/dsh-goal/types' import type { Context } from '@deepseek-ai/cordis' import type { - ISessions, SessionBinding, SessionFace, + ISessions, SessionBinding, SessionFace, SessionReference, SessionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' @@ -17,8 +17,8 @@ import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { ModelSelectionProjection } from '@deepseek-ai/dsh-agent/types' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { - DraftAttachmentId, DraftAttachmentSerializationResult, DraftInitializationOptions, DraftInitializationResult, InputTriggerController, - SessionInputResolver, SessionInput, SubmitOutcome, + DraftAttachmentId, DraftAttachmentSerializationResult, DraftInitializationOptions, DraftInitializationResult, InputState, + InputTriggerController, SessionInputResolver, SessionInput, SubmitOutcome, } from '../contract/input.ts' import type { ComposerKeyboard } from '../contract/draft-editor.ts' import type { ComposerBlocks } from '../contract/composer-blocks.ts' @@ -52,9 +52,18 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void - draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] - draftAttachmentSessions(): readonly SessionId[] - releaseDraftSession(sessionId: SessionId): void +} + +declare module '@deepseek-ai/dsh-api-session-controller/client' { + interface SessionReferenceSourceMap { + /** A Session whose composer draft holds attachments, kept without its event connection. */ + draft: unknown + } +} + +/** Whether a draft must keep its Session: it holds browser-owned attachments that nothing can restore. */ +function draftNeedsHold(input: InputState, session: SessionSnapshot): boolean { + return input.attachmentIds.length > 0 && !session.removed } /** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ @@ -85,8 +94,6 @@ function takeUnloadMark(sessionId: SessionId): boolean { /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() - private knownSessionIds: Set | undefined - private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -95,7 +102,23 @@ export class InputHub implements SessionInputResolver { constructor( private readonly rootCtx: Context, private readonly t: TranslateNS<'conversation'>, - ) {} + ) { + // An unloading page discards the attachments of every draft that holds its Session. + rootCtx.effect(() => { + const onHide = (): void => { writeUnloadMarks(this.draftHeldSessions()) } + // A back-forward cache restore keeps the drafts, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of this.draftHeldSessions()) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + } + }, 'conversation.input: draft attachment unload marks') + } /** * Resolve the facade for one session-scope ctx (SessionInputResolver face). @@ -194,26 +217,14 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() - // Snapshot the phase before dispose resets the machine. - const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) + // The draft hold keeps this scope while the draft has attachments, so teardown releases them for good. const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - if (conversation === undefined) return - if (binding.session.getSnapshot().removed) { - conversation.releaseDraftSession(binding.sessionId) - return - } - // Teardown aborts adjudication before any message leaves, so those attachments stay with the draft. - // A message or command already submitted cannot settle through its retirement path after teardown, - // and the Client cannot tell whether a submitted command consumed its attachments, so both release - // here rather than risk a duplicate submission; every other draft attachment stays registered for - // the Session's next composer. - if (phaseAtTeardown === 'sending' || phaseAtTeardown === 'submitting') { - for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) - } + for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) } }, 'conversation.input: session shell') + actx.effect(() => this.holdDraft(binding, shell), 'conversation.input: draft hold') actx.inject(['inputTriggers'], (scope) => { scope.effect(() => { shell.refreshLexiconSubscription() @@ -221,62 +232,48 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) - this.ensureLifecycleWatch() - const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] - // A Session switch keeps the draft's attachments registered; this composer re-adopts them. - if (retained.length > 0) shell.addAttachments(retained) // A reload discarded the browser-owned attachments; say so instead of dropping them silently. - if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) + if (takeUnloadMark(binding.sessionId)) shell.notify('error', this.t('attachments.unavailable')) return shell } /** - * Install the root-lifetime watchers once: a Session removed while no composer - * is mounted releases its draft attachments, and an unloading page marks the - * Sessions whose attachments it discards. + * Hold the Session without its event connection while its draft has attachments, so leaving the recent views + * keeps the scope, and with it the shell and its attachments. + * @returns disposer releasing the hold. */ - private ensureLifecycleWatch(): void { - if (this.lifecycleWatchInstalled) return - this.lifecycleWatchInstalled = true + private holdDraft(binding: SessionBinding, shell: SessionInputShell): () => void { const sessions = this.sessions() - this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) - this.rootCtx.effect(() => { - const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) - const conversation = (): ConversationAttachmentFace | undefined => - this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } - // A back-forward cache restore keeps the registry, so the marks just written are stale. - const onShow = (event: PageTransitionEvent): void => { - if (!event.persisted) return - for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + let reference: SessionReference | undefined + const release = (): void => { + const held = reference + reference = undefined + held?.release() + } + const sync = (): void => { + const needed = draftNeedsHold(shell.snapshot, binding.session.getSnapshot()) + if (needed === (reference !== undefined)) return + if (!needed) { + release() + return } - window.addEventListener('pagehide', onHide) - window.addEventListener('pageshow', onShow) - return () => { - stop() - window.removeEventListener('pagehide', onHide) - window.removeEventListener('pageshow', onShow) - this.knownSessionIds = undefined - this.lifecycleWatchInstalled = false - } - }, 'conversation.input: draft attachment lifecycle') + const target = sessions.subagentAddress(binding.sessionId) ?? binding.sessionId + reference = sessions.retain(target, { source: 'draft', connection: false }) + } + const stops = [shell.state.subscribe(sync), binding.session.subscribe(sync)] + sync() + return () => { + for (const stop of stops) stop() + release() + } } - /** Release draft attachments and unload marks for every Session removed from the catalog. */ - private cleanupRemovedSessions(): void { - const known = this.knownSessionIds - /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ - if (known === undefined) return - const liveIds = new Set(this.sessions().list.getSnapshot().ids) - const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const id of [...known]) { - if (liveIds.has(id)) continue - known.delete(id) - conversation?.releaseDraftSession(id) - takeUnloadMark(id) - } - for (const id of liveIds) known.add(id) + /** Sessions a draft reference currently holds. */ + private draftHeldSessions(): SessionId[] { + const sessions = this.sessions() + // byId also lists retained subagent Sessions outside the Host list. + return (Object.keys(sessions.list.getSnapshot().byId) as SessionId[]) + .filter(id => (sessions.retainInfo(id).getSnapshot().retainedBy.draft ?? 0) > 0) } /** diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index e4eb324030..72614f500b 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -161,10 +161,6 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() - /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ - private readonly sessionDraftIds = new Map>() - /** Reverse ownership lookup for release and Workspace rebinding. */ - private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -205,8 +201,6 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() - this.sessionDraftIds.clear() - this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -290,11 +284,6 @@ export class ConversationController extends Service implements IConversation { ) // The composer owns the attachments until the Host accepts the prompt. const ownership = { accepted: false, retiredUnobserved: false } - // An accepted message's attachments leave the draft: a later composer must not re-adopt them, while - // the registry keeps them until the echo settles their previews or an unobserved retirement releases them. - const disownAccepted = (): void => { - for (const attachment of attachments) this.forgetDraftAttachment(attachment.id) - } const acceptance = Promise.withResolvers() const submission = session.beginSubmission({ mode, @@ -302,7 +291,6 @@ export class ConversationController extends Service implements IConversation { attachments: pendingAttachments, onAccept: () => { ownership.accepted = true - disownAccepted() accept?.() acceptance.resolve(undefined) }, @@ -326,7 +314,6 @@ export class ConversationController extends Service implements IConversation { const result = await Promise.race([session.prompt(content, mode, signal, submission.requestId), acceptance.promise]) if (result !== undefined && !result.ok) return { kind: 'error' } ownership.accepted = true - disownAccepted() // An accepted prompt whose echo already retired unobserved, as when its queue entry was removed. if (ownership.retiredUnobserved) this.releaseDraftAttachments(attachments) return { kind: 'success' } @@ -350,7 +337,6 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) - this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -361,7 +347,6 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) - this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -389,7 +374,6 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue - this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -525,59 +509,11 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) - this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } - /** - * Draft attachment ids a Session still owns after its composer retired. - * @param sessionId - owning Session identity. - * @returns registered ids in registration order. - */ - draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { - return [...this.sessionDraftIds.get(sessionId) ?? []] - } - - /** - * Sessions that still own registered draft attachments. - * @returns Session identities with at least one registered attachment. - */ - draftAttachmentSessions(): readonly SessionId[] { - return [...this.sessionDraftIds.keys()] - } - - /** - * Release every draft attachment one removed Session owns. - * @param sessionId - removed Session identity. - */ - releaseDraftSession(sessionId: SessionId): void { - for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) - } - - /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ - private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { - this.forgetDraftAttachment(id) - this.draftAttachmentSession.set(id, sessionId) - let ids = this.sessionDraftIds.get(sessionId) - if (ids === undefined) { - ids = new Set() - this.sessionDraftIds.set(sessionId, ids) - } - ids.add(id) - } - - /** Forget one draft attachment's owning Session. */ - private forgetDraftAttachment(id: DraftAttachmentId): void { - const sessionId = this.draftAttachmentSession.get(id) - if (sessionId === undefined) return - this.draftAttachmentSession.delete(id) - const ids = this.sessionDraftIds.get(sessionId) - ids?.delete(id) - if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) - } - /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -674,7 +610,6 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) - this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue 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 e7d6a588c0..47e653fbae 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -453,7 +453,7 @@ describe('Conversation registries', () => { await binding.ctx.fiber.dispose() }) - it('folds nothing while the conversation facet is released and publishes the received window once on resume', async () => { + it('drops the fold when the conversation facet is released and folds the received window once on resume', async () => { const { uiConversation, binding, retained, events, views } = await bootRegistries() const match = vi.fn((event: SessionEventLike) => event.type === 'turn/start' ? { id: String(event.data.turn), role: 'start' as const } @@ -488,7 +488,11 @@ describe('Conversation registries', () => { const listener = vi.fn() const unsubscribe = conversation.snapshot.subscribe(listener) retained.set(false) - const cold = conversation.snapshot.getSnapshot() + // Releasing the facet drops the fold and publishes the empty result once. + expect(listener).toHaveBeenCalledOnce() + expect(conversation.openTurn.getSnapshot()).toBeUndefined() + const released = conversation.snapshot.getSnapshot() + listener.mockClear() match.mockClear() source.append({ type: 'event', event: { type: 'turn/end', seq: SessionSeq(2), time: 2, data: { turn: 1, reason: { kind: 'completed' } }, @@ -496,8 +500,7 @@ describe('Conversation registries', () => { source.append({ type: 'event', event: { type: 'turn/start', seq: SessionSeq(3), time: 3, data: { turn: 2 } } }) expect(match).not.toHaveBeenCalled() expect(listener).not.toHaveBeenCalled() - expect(conversation.snapshot.getSnapshot()).toBe(cold) - expect(conversation.openTurn.getSnapshot()).toBe(1) + expect(conversation.snapshot.getSnapshot()).toBe(released) built.length = 0 retained.set(true) expect(listener).toHaveBeenCalledOnce() @@ -527,7 +530,7 @@ describe('Conversation registries', () => { expect(conversation.snapshot.getSnapshot().views.get('chat')).toBeNull() }) - it('publishes a frame-paced update that a facet release interrupted when retention resumes', async () => { + it('cancels a frame-paced update on release and publishes synchronously when retention resumes', async () => { const frames = new Map() let nextFrame = 0 vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { @@ -559,9 +562,10 @@ describe('Conversation registries', () => { expect(frames.size).toBe(1) retained.set(false) expect(frames.size).toBe(0) - expect(listener).not.toHaveBeenCalled() + listener.mockClear() retained.set(true) expect(listener).toHaveBeenCalledOnce() + expect(frames.size).toBe(0) unsubscribe() }) diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts index df098003bb..a4b5b42620 100644 --- a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -1,6 +1,6 @@ // @vitest-environment jsdom -// Draft attachments outlive their Session's composer: a switch keeps them registered, -// a removed Session releases them, and a page unload reports what it discarded. +// A draft with attachments holds its Session without the event connection, so leaving every view keeps the same +// composer and its attachments; a removed Session releases them, and a page unload reports what it discarded. import { AttachmentId } from '@deepseek-ai/dsh-attachment' import { brandString } from '@deepseek-ai/dsh-brand' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -66,13 +66,12 @@ async function bench(prepare?: () => void) { const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) const shell = shellNow() const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior - /** Retire the Session's composer, as a switch to another Session does. */ + /** Release the viewing reference, as leaving every view of the Session does. */ const switchAway = async (): Promise => { reference.release() await runtime.flush() - expect(runtime.sessions.binding(SESSION)).toBeUndefined() } - /** Mount a fresh composer for the Session again. */ + /** Retain the Session for a view again. */ const switchBack = async () => { reference = runtime.sessions.retain(sessionId()) await reference.ready @@ -89,7 +88,7 @@ beforeEach(() => { localStorage.clear() }) afterEach(() => { vi.restoreAllMocks() }) describe('draft attachments across a Session switch', () => { - it('re-adopts settled files and images without uploading them again', async () => { + it('holds the Session without its connection and keeps the same composer and attachments', async () => { const b = await bench() const revoked = vi.spyOn(URL, 'revokeObjectURL') try { @@ -100,8 +99,9 @@ describe('draft attachments across a Session switch', () => { for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) await b.switchAway() - expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + expect(b.runtime.sessions.retainInfo(sessionId()).getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { draft: 1 } }) const back = await b.switchBack() + expect(back).toBe(b.shell) expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) expect(b.upload).toHaveBeenCalledOnce() @@ -112,6 +112,22 @@ describe('draft attachments across a Session switch', () => { } }) + it('releases the hold once the draft has no attachments', async () => { + const b = await bench() + try { + const [draft] = b.root.createDrafts(sessionId(), [new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + expect(b.runtime.sessions.binding(SESSION)).toBeDefined() + b.shell.removeAttachment(draft.id) + await b.runtime.flush() + expect(b.runtime.sessions.binding(SESSION)).toBeUndefined() + } finally { + await b.runtime.dispose() + } + }) + it('keeps an upload running while the Session is switched away', async () => { const b = await bench() try { @@ -156,7 +172,7 @@ describe('draft attachments across a Session switch', () => { }) describe('removed Sessions', () => { - it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + it('releases the draft attachments of a Session removed while no view holds it', async () => { const b = await bench() try { b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) @@ -164,17 +180,16 @@ describe('removed Sessions', () => { if (draft === undefined) throw new Error('draft missing') b.shell.addAttachments([draft.id]) await b.switchAway() - localStorage.setItem(UNLOAD_MARK, '1') await b.runtime.sessions.remove(SESSION) - await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + await b.runtime.flush() + expect(b.runtime.sessions.binding(SESSION)).toBeUndefined() expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) - expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() } finally { await b.runtime.dispose() } }) - it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + it('releases the draft attachments when the last view of a removed Session closes', async () => { const b = await bench() try { b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) @@ -183,7 +198,7 @@ describe('removed Sessions', () => { b.shell.addAttachments([draft.id]) await b.runtime.sessions.remove(SESSION) await b.switchAway() - expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) } finally { await b.runtime.dispose() } @@ -213,7 +228,7 @@ describe('page unload report', () => { } }) - it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + it('drops marks a back-forward restore made stale', async () => { const b = await bench() try { b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) @@ -229,30 +244,24 @@ describe('page unload report', () => { Object.defineProperty(cached, 'persisted', { value: true }) window.dispatchEvent(cached) expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() - localStorage.setItem(UNLOAD_MARK, '1') - await b.switchAway() - const back = await b.switchBack() - expect(back.notices.getSnapshot()).toBeNull() - expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() } finally { await b.runtime.dispose() } }) it('keeps working when browser storage refuses the marks', async () => { - const b = await bench() const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const b = await bench(() => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + }) try { b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) if (draft === undefined) throw new Error('draft missing') b.shell.addAttachments([draft.id]) - vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) - vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) window.dispatchEvent(new Event('pagehide')) - await b.switchAway() - const back = await b.switchBack() - expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.shell.snapshot.attachmentIds).toEqual([draft.id]) expect(errors).toHaveBeenCalledTimes(2) } finally { await b.runtime.dispose() @@ -261,7 +270,7 @@ describe('page unload report', () => { }) describe('submitted attachments', () => { - it('does not re-adopt or report attachments of an accepted message whose echo has not retired', async () => { + it('does not hold or report attachments of an accepted message', async () => { const b = await bench() try { b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) @@ -275,19 +284,15 @@ describe('submitted attachments', () => { await b.runtime.flush() // The registry still holds the attachment for the echo; the draft no longer owns it. expect(b.root.resolveDraftAttachments([draft.id])).toHaveLength(1) - expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) - expect(b.root.draftAttachmentSessions()).toEqual([]) + expect(b.runtime.sessions.retainInfo(sessionId()).getSnapshot().retainedBy.draft).toBeUndefined() window.dispatchEvent(new Event('pagehide')) expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() - await b.switchAway() - const back = await b.switchBack() - expect(back.snapshot.attachmentIds).toEqual([]) } finally { await b.runtime.dispose() } }) - it('keeps the attachments of a slash line whose adjudication a switch aborted', async () => { + it('keeps a slash line adjudicating with its attachments while the Session is switched away', async () => { const adjudicate = vi.fn(() => new Promise(() => undefined)) const b = await bench() try { @@ -303,8 +308,8 @@ describe('submitted attachments', () => { expect(b.shell.snapshot.phase).toBe('adjudicating') expect(adjudicate).toHaveBeenCalledOnce() await b.switchAway() - expect(b.root.draftAttachmentIds(sessionId())).toEqual([draft.id]) const back = await b.switchBack() + expect(back.snapshot.phase).toBe('adjudicating') expect(back.snapshot.attachmentIds).toEqual([draft.id]) } finally { await b.runtime.dispose() 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 ed972f7cbf..fbfffa7504 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -965,11 +965,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionRetainInfo', - declaration: 'export interface SessionRetainInfo {\n readonly referenceCount: number;\n readonly retainedBy: Readonly>>;\n readonly retainedFacets?: Readonly>>;\n}', + declaration: 'export interface SessionRetainInfo {\n readonly referenceCount: number;\n readonly retainedBy: Readonly>>;\n readonly retainedFacets?: Readonly>>;\n readonly connectionCount?: number;\n}', }, { name: 'SessionRetainOptions', - declaration: 'export interface SessionRetainOptions {\n readonly source: SessionReferenceSource;\n readonly facets?: Readonly>> | undefined;\n readonly signal?: AbortSignal | undefined;\n}', + declaration: 'export interface SessionRetainOptions {\n readonly source: SessionReferenceSource;\n readonly connection?: boolean | undefined;\n readonly facets?: Readonly>> | undefined;\n readonly signal?: AbortSignal | undefined;\n}', }, { name: 'SessionSearchResultItem', diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index ed3527a822..56fcc375d1 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -222,8 +222,14 @@ function retentionOf( referenceCount: number, retainedBy: SessionRetainInfo['retainedBy'], retainedFacets: SessionRetainInfo['retainedFacets'], + connectionCount: number, ): SessionRetainInfo { - return Object.freeze({ referenceCount, retainedBy, ...(retainedFacets === undefined ? {} : { retainedFacets }) }) + return Object.freeze({ + referenceCount, + retainedBy, + ...(retainedFacets === undefined ? {} : { retainedFacets }), + ...(connectionCount === 0 ? {} : { connectionCount }), + }) } function freezeRetainedBy( @@ -545,9 +551,10 @@ export class TestSessions implements ISessions { if (this.closed) throw new Error('test Session Controller is disposed') const id = this.resolveTarget(target) const generation = this.generations.get(id) ?? this.materialize(id, this.require(id)) - const reference = this.retainGeneration(id, generation, source, heldFacets(facets)) + const connected = options.connection !== false + const reference = this.retainGeneration(id, generation, source, heldFacets(facets), connected) try { - reference.attachOpening(generation.opening, signal) + reference.attachOpening(connected ? generation.opening : Promise.resolve(), signal) return reference } catch (error: unknown) { reference.release() @@ -733,12 +740,15 @@ export class TestSessions implements ISessions { generation: SessionGeneration, source: SessionReferenceSource, facets: readonly SessionRetainFacet[], + connected: boolean, ): TestSessionReference { const previous = generation.retention + const connection = connected ? 1 : 0 generation.retention = retentionOf( previous.referenceCount + 1, freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), shiftFacetCounts(previous.retainedFacets, facets, 1), + (previous.connectionCount ?? 0) + connection, ) const reference = new TestSessionReference(id, generation, () => { if (!generation.live) return @@ -749,7 +759,12 @@ export class TestSessions implements ISessions { : otherSources generation.retention = count === 0 ? EMPTY_RETAIN_INFO - : retentionOf(count, freezeRetainedBy(retainedBy), shiftFacetCounts(generation.retention.retainedFacets, facets, -1)) + : retentionOf( + count, + freezeRetainedBy(retainedBy), + shiftFacetCounts(generation.retention.retainedFacets, facets, -1), + (generation.retention.connectionCount ?? 0) - connection, + ) if (count === 0) this.drop(id, generation) else this.publishRetention(id) }) diff --git a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx index 1672fe589a..3daf942716 100644 --- a/packages/test-support/client-runtime/tests/runtime.client.spec.tsx +++ b/packages/test-support/client-runtime/tests/runtime.client.spec.tsx @@ -265,16 +265,22 @@ describe('sessions', () => { const second = runtime.sessions.retain(id, { source: 'testOperation' }) const scope = first.binding.ctx await Promise.all([first.ready, second.ready]) - expect(info.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { testOperation: 2 } }) + expect(info.getSnapshot()).toEqual({ referenceCount: 2, retainedBy: { testOperation: 2 }, connectionCount: 2 }) expect(runtime.sessions.list.getSnapshot().byId[id]?.retainedBy).toEqual({ testOperation: 2 }) expect('retainedFacets' in info.getSnapshot()).toBe(false) const rendered = runtime.sessions.retain(id) expect(info.getSnapshot().retainedFacets).toEqual({ conversation: 1 }) rendered.release() - expect('retainedFacets' in info.getSnapshot()).toBe(false) + const draftHeld = runtime.sessions.retain(id, { source: 'testOperation', connection: false }) + await draftHeld.ready + expect(info.getSnapshot()).toMatchObject({ referenceCount: 3, connectionCount: 2 }) first.release() - expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { testOperation: 1 } }) second.release() + expect(info.getSnapshot()).toEqual({ referenceCount: 1, retainedBy: { testOperation: 1 } }) + const another = runtime.sessions.retain(id, { source: 'testOperation', connection: false }) + another.release() + draftHeld.release() + expect('retainedFacets' in info.getSnapshot()).toBe(false) await scope.fiber.dispose() expect(info.getSnapshot()).toEqual({ referenceCount: 0, retainedBy: {} }) diff --git a/scripts/no-unknown-casts.baseline.json b/scripts/no-unknown-casts.baseline.json index f1ce3ad4af..3d3c93814e 100644 --- a/scripts/no-unknown-casts.baseline.json +++ b/scripts/no-unknown-casts.baseline.json @@ -186,9 +186,6 @@ "packages/api/session-controller/src/client/sessions/assistant-stream.ts": { "8a6d86a1925458d196d5a03716c20003a0347d08125c1e8461ed83001b6a1ac2": 1 }, - "packages/api/session-controller/src/client/sessions/history-records.ts": { - "8cd779a2bf2a4c61fb2963fbfbfe761c89a211e607ab1e064c3f9380331310d2": 1 - }, "packages/api/session-controller/src/client/transport.ts": { "6a6302072b3044d1366f925d2ccea779370ea82e46555e897fe556b5c0d23ff1": 1 }, From 33bf943702a3f0d0b698397237394f259fb7bda8 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:20:25 +0800 Subject: [PATCH 6/9] refactor(session-controller): share retain-info counting with the test fixture --- .../src/client/sessions/facets.ts | 45 +++++++++++++- .../src/client/sessions/service.ts | 48 ++------------- .../client-runtime/src/sessions.ts | 58 +++---------------- 3 files changed, 56 insertions(+), 95 deletions(-) diff --git a/packages/api/session-controller/src/client/sessions/facets.ts b/packages/api/session-controller/src/client/sessions/facets.ts index 1d0174ef2f..cbdb55acaa 100644 --- a/packages/api/session-controller/src/client/sessions/facets.ts +++ b/packages/api/session-controller/src/client/sessions/facets.ts @@ -1,6 +1,6 @@ -/** Per-generation reference counts of owner-declared retained facets. */ +/** Per-generation reference counts: sources, owner-declared facets, and the event connection. */ import type { SessionRetainInfo, SessionRetainOptions } from '../contract/sessions.ts' -import type { SessionRetainFacet } from '../index.ts' +import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts' type FacetCounts = NonNullable @@ -14,6 +14,45 @@ export function heldFacets(facets: SessionRetainOptions['facets']): readonly Ses return (Object.keys(facets) as SessionRetainFacet[]).filter(facet => facets[facet] === true) } +/** What one reference counts while it lives. */ +export interface RetainedUse { + readonly source: SessionReferenceSource + readonly facets: readonly SessionRetainFacet[] + readonly connected: boolean +} + +/** Source labels are dictionary keys, including names also present on Object.prototype. */ +function freezeRetainedBy(counts: Partial>): SessionRetainInfo['retainedBy'] { + Object.setPrototypeOf(counts, null) + return Object.freeze(counts) +} + +/** Retain info of a generation that no reference holds. */ +export const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) }) + +/** + * Count one reference in or out of a generation's retain info. + * @param info - the generation's current retain info. + * @param use - what the retained or released reference counts. + * @param delta - `1` when the reference is retained, `-1` when it is released. + * @returns the frozen next retain info; {@link EMPTY_RETAIN_INFO} once no reference remains. + */ +export function shiftRetention(info: SessionRetainInfo, use: RetainedUse, delta: 1 | -1): SessionRetainInfo { + const referenceCount = info.referenceCount + delta + if (referenceCount === 0) return EMPTY_RETAIN_INFO + const { [use.source]: sourceCount = 0, ...otherSources } = info.retainedBy + const nextSource = sourceCount + delta + const retainedBy = freezeRetainedBy(nextSource > 0 ? { ...otherSources, [use.source]: nextSource } : otherSources) + const retainedFacets = shiftFacetCounts(info.retainedFacets, use.facets, delta) + const connectionCount = (info.connectionCount ?? 0) + (use.connected ? delta : 0) + return Object.freeze({ + referenceCount, + retainedBy, + ...(retainedFacets === undefined ? {} : { retainedFacets }), + ...(connectionCount === 0 ? {} : { connectionCount }), + }) +} + /** * Count one reference's facets in or out of a retain-info snapshot. * @param counts - the previous positive facet counts, absent when none. @@ -21,7 +60,7 @@ export function heldFacets(facets: SessionRetainOptions['facets']): readonly Ses * @param delta - `1` when the reference is retained, `-1` when it is released. * @returns the frozen positive counts, or undefined when no facet remains retained. */ -export function shiftFacetCounts( +function shiftFacetCounts( counts: FacetCounts | undefined, facets: readonly SessionRetainFacet[], delta: 1 | -1, diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index 326493f9b4..0a6604f436 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -17,7 +17,7 @@ import type { } from '../contract/sessions.ts' import type { SessionReferenceSource, SessionRetainFacet } from '../index.ts' import { createScope, scopeIdentityOf, scopeOf as scopeTagOf } from '../scope.ts' -import { heldFacets, shiftFacetCounts } from './facets.ts' +import { EMPTY_RETAIN_INFO, heldFacets, shiftRetention } from './facets.ts' import { SessionManager } from './manager.ts' import type { SessionRemotes } from './remotes.ts' import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts' @@ -160,26 +160,6 @@ function incrementedTitle(title: string): string { return `${title} (1)` } -/** Source labels are dictionary keys, including names also present on Object.prototype. */ -function freezeRetainedBy(counts: Partial>): SessionRetainInfo['retainedBy'] { - Object.setPrototypeOf(counts, null) - return Object.freeze(counts) -} - -function retentionOf( - referenceCount: number, - retainedBy: SessionRetainInfo['retainedBy'], - retainedFacets: SessionRetainInfo['retainedFacets'], - connectionCount: number, -): SessionRetainInfo { - return Object.freeze({ - referenceCount, - retainedBy, - ...(retainedFacets === undefined ? {} : { retainedFacets }), - ...(connectionCount === 0 ? {} : { connectionCount }), - }) -} - /** * Drop what no remaining reference keeps: the connection when none keeps it, otherwise the older window pages * when no facet computes over them any longer. @@ -192,8 +172,6 @@ function releaseConnectionWork(session: Session, before: SessionRetainInfo, afte if (before.retainedFacets !== undefined && after.retainedFacets === undefined) session.bufferOlder() } -const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ referenceCount: 0, retainedBy: freezeRetainedBy({}) }) - interface ScopeRecord { fiber: Fiber ctx: AgentContext @@ -594,29 +572,13 @@ export class ClientSessions implements ISessions { connected: boolean, ): ClientSessionReference { const record = this.scopes.get(id) ?? this.materializeScope(id) - const previous = record.retention - const connection = connected ? 1 : 0 - record.retention = retentionOf( - previous.referenceCount + 1, - freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), - shiftFacetCounts(previous.retainedFacets, facets, 1), - (previous.connectionCount ?? 0) + connection, - ) + const use = { source, facets, connected } + record.retention = shiftRetention(record.retention, use, 1) const reference = new ClientSessionReference(id, record, () => { if (!record.live) return const before = record.retention - const count = before.referenceCount - 1 - const { [source]: sourceCount = 0, ...otherSources } = before.retainedBy - const retainedBy = sourceCount > 1 ? { ...otherSources, [source]: sourceCount - 1 } : otherSources - record.retention = count === 0 - ? EMPTY_RETAIN_INFO - : retentionOf( - count, - freezeRetainedBy(retainedBy), - shiftFacetCounts(before.retainedFacets, facets, -1), - (before.connectionCount ?? 0) - connection, - ) - if (count === 0) { + record.retention = shiftRetention(before, use, -1) + if (record.retention.referenceCount === 0) { this.retireScope(id, record) return } diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index 56fcc375d1..9a45640fa1 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -11,7 +11,11 @@ import type { SessionSnapshot, SessionSummary, SessionTarget, SubmissionHandle, } from '@deepseek-ai/dsh-api-session-controller/client' import { scopeIdentityOf } from '@deepseek-ai/dsh-api-session-controller/src/client/scope.ts' -import { heldFacets, shiftFacetCounts } from '@deepseek-ai/dsh-api-session-controller/src/client/sessions/facets.ts' +import { + EMPTY_RETAIN_INFO, + heldFacets, + shiftRetention, +} from '@deepseek-ai/dsh-api-session-controller/src/client/sessions/facets.ts' import type { SessionRequestId } from '@deepseek-ai/dsh-api-session-controller/types' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -218,32 +222,6 @@ interface OpeningControl { /** Fixture references default to a rendering use, so Conversation assembly runs as it does under a main view. */ const DEFAULT_TEST_RETAIN: SessionRetainOptions = { source: 'testFixture', facets: { conversation: true } } -function retentionOf( - referenceCount: number, - retainedBy: SessionRetainInfo['retainedBy'], - retainedFacets: SessionRetainInfo['retainedFacets'], - connectionCount: number, -): SessionRetainInfo { - return Object.freeze({ - referenceCount, - retainedBy, - ...(retainedFacets === undefined ? {} : { retainedFacets }), - ...(connectionCount === 0 ? {} : { connectionCount }), - }) -} - -function freezeRetainedBy( - counts: Partial>, -): SessionRetainInfo['retainedBy'] { - Object.setPrototypeOf(counts, null) - return Object.freeze(counts) -} - -const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({ - referenceCount: 0, - retainedBy: freezeRetainedBy({}), -}) - // TestSessions implements SessionReference against its fixture-owned // SessionGeneration without importing the production service's private record. /* jscpd:ignore-start -- The fixture intentionally mirrors production SessionReference settlement and release semantics. */ @@ -742,30 +720,12 @@ export class TestSessions implements ISessions { facets: readonly SessionRetainFacet[], connected: boolean, ): TestSessionReference { - const previous = generation.retention - const connection = connected ? 1 : 0 - generation.retention = retentionOf( - previous.referenceCount + 1, - freezeRetainedBy({ ...previous.retainedBy, [source]: (previous.retainedBy[source] ?? 0) + 1 }), - shiftFacetCounts(previous.retainedFacets, facets, 1), - (previous.connectionCount ?? 0) + connection, - ) + const use = { source, facets, connected } + generation.retention = shiftRetention(generation.retention, use, 1) const reference = new TestSessionReference(id, generation, () => { if (!generation.live) return - const count = generation.retention.referenceCount - 1 - const { [source]: sourceCount = 0, ...otherSources } = generation.retention.retainedBy - const retainedBy = sourceCount > 1 - ? { ...otherSources, [source]: sourceCount - 1 } - : otherSources - generation.retention = count === 0 - ? EMPTY_RETAIN_INFO - : retentionOf( - count, - freezeRetainedBy(retainedBy), - shiftFacetCounts(generation.retention.retainedFacets, facets, -1), - (generation.retention.connectionCount ?? 0) - connection, - ) - if (count === 0) this.drop(id, generation) + generation.retention = shiftRetention(generation.retention, use, -1) + if (generation.retention.referenceCount === 0) this.drop(id, generation) else this.publishRetention(id) }) this.publishRetention(id) From 24df14af2845a5334289906a6271e4c09386d338 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:11:26 +0800 Subject: [PATCH 7/9] fix(client): keep gap repair, disconnect, and recent-view counting correct while Sessions are buffered - Only page reads before the window take buffered records; a live gap repair reads the Host. - A resync whose teardown a disconnect interrupted stays cold. - A Session the main view already retains takes no recent-view slot before show(), so losing its unread protection during retention evicts nothing. - Buffering marks the window partial, so the start-of-history marker survives after the buffer runs out. --- .../src/client/sessions/session.ts | 5 ++- .../src/client/transport.ts | 3 +- .../tests/session.client.spec.ts | 36 +++++++++++++++++++ .../ui-workspace/src/client/recent-views.ts | 3 +- .../tests/recent-views.client.spec.ts | 17 +++++++++ 5 files changed, 61 insertions(+), 3 deletions(-) diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 1f6c34eb73..95b3e3d0b5 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -585,11 +585,13 @@ export class Session implements SessionFace { * reconnecting control stream and remains untouched. */ 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++ + const generation = ++this.openGeneration this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() + // A disconnect during teardown ends this rebuild; the Session stays cold. + if (generation !== this.openGeneration) return this.openPromise = null this.openState = 'cold' this.openError = null @@ -696,6 +698,7 @@ export class Session implements SessionFace { events.bufferOlder(older, first.event.seq, this.hasMore) this.baseSeq = SessionLogOffset(first.event.seq) this.hasMore = true + this.historyWasPartial = true this.eventSource.replace(entries.slice(start), true) this.notifier.markDirty() } diff --git a/packages/api/session-controller/src/client/transport.ts b/packages/api/session-controller/src/client/transport.ts index 996151c306..fc332b7670 100644 --- a/packages/api/session-controller/src/client/transport.ts +++ b/packages/api/session-controller/src/client/transport.ts @@ -261,7 +261,8 @@ export class SessionEventStream extends RemoteJournalStream< signal: AbortSignal, ): Promise { const buffered = this.buffered.records - if (buffered.length > 0) { + // Only a page before the window reads the buffer; a gap repair without beforeSeq reads the Host. + if (request.beforeSeq !== undefined && buffered.length > 0) { const start = tailPageStart(buffered, request.turnWindow) this.buffered.records = buffered.slice(0, start) return { records: buffered.slice(start), hasMore: start > 0 || this.buffered.hostHasMore } diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index 5bf0b24f0f..a069a1d81c 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -270,6 +270,42 @@ describe('buffered older pages', () => { expect(mock.log.requests(PAGE)).toHaveLength(1) }) + it('repairs a live seq gap from the Host while older entries are buffered', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(all))) + mock.remote.session.page.mockImplementation(pageRule(history(turns(61)))) + await session.open() + session.bufferOlder() + await pushEvent(mock, ev.assistant(SessionSeq(363), 60, 'late')) + await vi.waitFor(() => { expect(eventSeqs(session).at(-1)).toBe(363) }) + expect(session.getSnapshot().openError).toBeNull() + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + + it('stays cold when a disconnect lands while a resync tears down its stream', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(turns(2)))) + await session.open() + const resynced = session.resync() + await session.disconnect() + await resynced + expect(session.getSnapshot().openState).toBe('cold') + expect(mock.log.requests(FOLLOW)).toHaveLength(1) + }) + + it('keeps the start-of-history marker after a short window grows live and its buffer runs out', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(turns(2)))) + await session.open() + // 30 Turns exceed one page by a few Turns, so the buffer holds a single page. + for (const event of turns(30).slice(12)) await pushEvent(mock, event) + session.bufferOlder() + expect(session.getSnapshot().hasMore).toBe(true) + await session.loadOlder() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + expect(mock.log.requests(PAGE)).toHaveLength(0) + }) + it('buffers nothing for a short, closed, or paging window', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) session.bufferOlder() diff --git a/packages/client/ui-workspace/src/client/recent-views.ts b/packages/client/ui-workspace/src/client/recent-views.ts index aee06111d8..99f914ed7a 100644 --- a/packages/client/ui-workspace/src/client/recent-views.ts +++ b/packages/client/ui-workspace/src/client/recent-views.ts @@ -110,7 +110,8 @@ export class RecentSessionViews { const workspaces = this.workspaces.list.getSnapshot() const status = this.status.getSnapshot() const eligible = this.order.filter(id => id !== this.current && isEligible(id, byId, workspaces)) - const counted = eligible.filter(id => !needsAttention(id, byId, status)) + // A Session the main view already retains, but has not shown yet, takes no recent-view slot. + const counted = eligible.filter(id => !needsAttention(id, byId, status) && (byId[id]?.retainedBy.mainView ?? 0) === 0) const countedIds = new Set(counted) const pinned = new Set(workspaces.pinnedSessionIds) // Pinned Sessions take the limit first, so eviction reaches them only after every unpinned Session. diff --git a/packages/client/ui-workspace/tests/recent-views.client.spec.ts b/packages/client/ui-workspace/tests/recent-views.client.spec.ts index f859b4bd49..c6e6db2ad0 100644 --- a/packages/client/ui-workspace/tests/recent-views.client.spec.ts +++ b/packages/client/ui-workspace/tests/recent-views.client.spec.ts @@ -127,6 +127,23 @@ describe('recently viewed Sessions', () => { expect(b.retained()).not.toContain(sid('m3')) }) + it('keeps a Session the main view retains out of the count before it is shown', () => { + const ids = Array.from({ length: 13 }, (_, index) => sid(`n${index}`)) + const b = bench(ids) + b.setStatus(sid('n0'), { completionUnread: true }) + b.visit(ids.slice(0, 11), sid('n11')) + expect(b.retained()).toHaveLength(11) + // Retaining n0 for the main view publishes the list; the status then stops protecting it before show(). + b.update(sid('n0'), { retainedBy: { mainView: 1 } }) + b.setStatus(sid('n0'), { completionUnread: false }) + expect(b.retained()).toHaveLength(11) + expect(b.retained()).toContain(sid('n1')) + // Showing n0 moves n11 into the recent views; only that one extra Session evicts the oldest. + b.recent.show(sid('n0')) + expect(b.retained()).toEqual(expect.arrayContaining(ids.slice(2, 12))) + expect(b.retained()).toHaveLength(10) + }) + it('retains before releasing and reports a failed retention without retrying it', () => { const b = bench([sid('a'), sid('b'), sid('c')]) b.visit([sid('a')], sid('b')) From fff31dd57bde1ad1024c4189e78f395b395c53d9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:53:12 +0800 Subject: [PATCH 8/9] fix(session-controller): consume an arrived older page before buffering the window --- .../src/client/sessions/session.ts | 2 ++ .../tests/session.client.spec.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 95b3e3d0b5..7ba34a5ad8 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -688,6 +688,8 @@ export class Session implements SessionFace { * without a request. Applies only to an open window longer than one page with no paging in progress. */ bufferOlder(): void { + // A page that arrived but was not consumed joins the window first, so no remounted view finds it waiting. + this.consumeOlder() const events = this.events if (this.openState !== 'open' || events === undefined || this.olderRequest !== null || this.pendingHistory !== null) return const { entries } = this.eventSource.getSnapshot() diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index a069a1d81c..0eb00378e7 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -306,6 +306,22 @@ describe('buffered older pages', () => { expect(mock.log.requests(PAGE)).toHaveLength(0) }) + it('consumes an arrived older page before buffering', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const window = turns(61).slice(6) + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(window, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot().historyLoadStatus).toBe('pendingConsumption') + session.bufferOlder() + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', hasMore: true }) + while (session.getSnapshot().hasMore) await session.loadOlder() + expect(eventSeqs(session)).toEqual(turns(61).map(event => event.seq)) + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + it('buffers nothing for a short, closed, or paging window', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) session.bufferOlder() From 116b7d4868c5c204a7edce9b5ca7b1ef0acb86e9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:37:22 +0800 Subject: [PATCH 9/9] feat(ui-workspace): sync the recent-view limit from the Host Config recentViewLimit becomes a volatile field of the ui-workspace Host Config (z.natural().default(10)). The browser receives it through synced plugin configuration, and RecentSessionViews reconciles whenever it changes, so a cordis.yml edit takes effect without a page reload. Until a value arrives, every counted recent view is kept. The package gains a Host compiler face: src/types.ts holds the shared Config type, tsconfig.host.json and tsconfig.client.json replace the single Client config, and every reference names the face it compiles against. --- ...n-retain-facets-and-recent-views.i18n.yaml | 4 +- ...-session-retain-facets-and-recent-views.md | 2 +- ...ssion-retain-facets-and-recent-views.zh.md | 2 +- apps/web/tests/draft-initialization.e2e.ts | 7 +- packages/client/ui-agent-preset/tsconfig.json | 2 +- packages/client/ui-chat/tsconfig.client.json | 2 +- .../ui-directory-picker-browse/tsconfig.json | 2 +- .../ui-directory-picker-native/tsconfig.json | 2 +- .../ui-entry-customization/tsconfig.json | 2 +- packages/client/ui-open-in-app/tsconfig.json | 2 +- packages/client/ui-schedule/tsconfig.json | 2 +- packages/client/ui-subagent/tsconfig.json | 2 +- packages/client/ui-workflow-run/tsconfig.json | 2 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- packages/client/ui-workspace/package.json | 21 ++-- .../client/ui-workspace/src/client/index.ts | 22 +--- .../ui-workspace/src/client/navigation.ts | 7 +- .../ui-workspace/src/client/recent-views.ts | 16 ++- packages/client/ui-workspace/src/index.ts | 20 +++- packages/client/ui-workspace/src/types.ts | 8 ++ .../tests/access-assembly.client.spec.tsx | 2 +- .../ui-workspace/tests/apply.client.spec.ts | 67 ++++++------ .../ui-workspace/tests/config.host.spec.ts | 25 +++++ .../tests/host-home-staleness.client.spec.tsx | 2 +- .../tests/recent-views.client.spec.ts | 37 +++++-- .../tests/rename-assembly.client.spec.tsx | 6 +- .../workspace-picker-factory.client.spec.tsx | 2 +- .../tests/workspaces-service.client.spec.ts | 5 +- .../client/ui-workspace/tsconfig.client.json | 103 ++++++++++++++++++ .../client/ui-workspace/tsconfig.host.json | 20 ++++ packages/client/ui-workspace/tsconfig.json | 91 +--------------- .../client-ui-forge/tsconfig.client.json | 2 +- .../deepseek-chat-import/tsconfig.client.json | 2 +- .../liveshare/tsconfig.client.json | 2 +- .../test-support/client-runtime/tsconfig.json | 2 +- pnpm-lock.yaml | 10 +- tsconfig.client.json | 2 +- tsconfig.host.json | 1 + 40 files changed, 309 insertions(+), 207 deletions(-) create mode 100644 packages/client/ui-workspace/src/types.ts create mode 100644 packages/client/ui-workspace/tests/config.host.spec.ts create mode 100644 packages/client/ui-workspace/tsconfig.client.json create mode 100644 packages/client/ui-workspace/tsconfig.host.json diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml index 1bc6712e57..1eacb1f915 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.i18n.yaml @@ -24,8 +24,8 @@ en: cb761521ca56fe93 zh: 76f8797f4808407d /agent-note-session-retain-facets-and-recently-viewed-sessions/decision/recently-viewed-sessions-recentviews: - en: e1a6728468965961 - zh: 4af21b4c306bec27 + en: 1af8b25948c049f2 + zh: 6444d8d9eacf6fc2 /agent-note-session-retain-facets-and-recently-viewed-sessions/alternatives-considered: en: 7a484119b745aee9 zh: 3092d3dbda8397cd diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md index a4e7010834..ab543402e6 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.md @@ -88,7 +88,7 @@ Its state records only what the user did: the order in which Sessions left the m | Failure | A failed retention is reported to the console once and the Session leaves the order, so it is released with its `mainView` reference; navigation continues | | Exit | A removed, archived, or evicted Session leaves the order and returns only when the main view leaves it again | | Attention | A Session that is running, awaits the user, or has an unread completion, as the unified Session UI status reports, is neither counted nor evicted; once it is read and idle it counts again | -| Limit | The ui-workspace `recentViewLimit` configuration, 10 by default, counted Sessions besides the main-view Session | +| Limit | The ui-workspace `recentViewLimit` configuration, 10 by default, counted Sessions besides the main-view Session; a volatile Host `Config` field the browser receives through [synced plugin configuration](2026-11-15-client-config-sync.md), so a change applies without a reload and Sessions already evicted do not return | | Eviction | Beyond the limit, the least recently left unpinned Session is evicted first, then the least recently left pinned one; the list is checked again whenever the Session list, Workspace list, or Session UI status changes | | Disposal | Plugin disposal unsubscribes from both lists and the status, clears the order, and releases every reference | diff --git a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md index a726502294..a79310566f 100644 --- a/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-15-session-retain-facets-and-recent-views.zh.md @@ -88,7 +88,7 @@ ui-workspace 的 [navigation](../../../../packages/client/ui-workspace/src/clien | 失败 | retain 失败时报告到控制台一次,该 Session 离开顺序列表,随其 `mainView` 引用一起释放;导航继续 | | 出队 | 被移除、归档或淘汰的 Session 离开顺序列表,只有主视图再次离开它时才会回来 | | 关注 | 统一 Session UI 状态显示为运行中、等待用户或完成未读的 Session 既不计数也不淘汰;读过且空闲后重新计数 | -| 上限 | 由 ui-workspace 配置 `recentViewLimit` 决定,默认 10,计数的 Session 不含主视图 Session | +| 上限 | 由 ui-workspace 配置 `recentViewLimit` 决定,默认 10,计数的 Session 不含主视图 Session;它是 Host `Config` 的 volatile 字段,浏览器经[前端插件配置同步](2026-11-15-client-config-sync.zh.md)接收,修改后无需刷新即生效,已淘汰的 Session 不会回来 | | 淘汰 | 超出上限时先淘汰最早离开的未置顶 Session,再淘汰最早离开的置顶 Session;Session 列表、Workspace 列表或 Session UI 状态变化时都会重新检查 | | 卸载 | 插件卸载时退订两个列表与状态,清空顺序列表,并释放全部引用 | diff --git a/apps/web/tests/draft-initialization.e2e.ts b/apps/web/tests/draft-initialization.e2e.ts index af536fa844..efad3f69da 100644 --- a/apps/web/tests/draft-initialization.e2e.ts +++ b/apps/web/tests/draft-initialization.e2e.ts @@ -73,11 +73,12 @@ async function observeDraftApi(page: Page): Promise { if (typeof exports.apply !== 'function') { throw new Error(`ui-workspace factory returned keys ${Object.keys(exports).join(',')}; apply is ${typeof exports.apply}`) } - const originalApply = exports.apply as (ctx: WorkspaceApplyContext) => unknown + const originalApply = exports.apply as (ctx: WorkspaceApplyContext, ...rest: readonly unknown[]) => unknown return { ...exports, - apply(ctx: WorkspaceApplyContext) { - const result = originalApply.call(exports, ctx) + // Forward the synced Config and any later argument the Loader passes. + apply(ctx: WorkspaceApplyContext, ...rest: readonly unknown[]) { + const result = originalApply.call(exports, ctx, ...rest) observation.startSession = (workspaceId, options) => { const workspace = ctx.get('uiWorkspace') if (workspace === undefined) throw new Error('The shipped uiWorkspace service is unavailable') diff --git a/packages/client/ui-agent-preset/tsconfig.json b/packages/client/ui-agent-preset/tsconfig.json index 6857e811d7..c411802016 100644 --- a/packages/client/ui-agent-preset/tsconfig.json +++ b/packages/client/ui-agent-preset/tsconfig.json @@ -39,7 +39,7 @@ "path": "../ui-session" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-settings/tsconfig.client.json" diff --git a/packages/client/ui-chat/tsconfig.client.json b/packages/client/ui-chat/tsconfig.client.json index 4040aacd08..d45708b9fa 100644 --- a/packages/client/ui-chat/tsconfig.client.json +++ b/packages/client/ui-chat/tsconfig.client.json @@ -106,7 +106,7 @@ "path": "../ui-slots" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-sidebar-documentpreview/tsconfig.client.json" diff --git a/packages/client/ui-directory-picker-browse/tsconfig.json b/packages/client/ui-directory-picker-browse/tsconfig.json index 291b7c6137..5672d1c28a 100644 --- a/packages/client/ui-directory-picker-browse/tsconfig.json +++ b/packages/client/ui-directory-picker-browse/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } diff --git a/packages/client/ui-directory-picker-native/tsconfig.json b/packages/client/ui-directory-picker-native/tsconfig.json index c57a21a081..5c183fdfb0 100644 --- a/packages/client/ui-directory-picker-native/tsconfig.json +++ b/packages/client/ui-directory-picker-native/tsconfig.json @@ -18,7 +18,7 @@ "path": "../ui-renderer" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } diff --git a/packages/client/ui-entry-customization/tsconfig.json b/packages/client/ui-entry-customization/tsconfig.json index e65933f5ea..13e629c826 100644 --- a/packages/client/ui-entry-customization/tsconfig.json +++ b/packages/client/ui-entry-customization/tsconfig.json @@ -10,7 +10,7 @@ { "path": "../../client/ui-conversation/tsconfig.client.json" }, { "path": "../../client/ui-sidebar-right" }, { "path": "../../client/ui-plugin-manager/tsconfig.client.json" }, - { "path": "../../client/ui-workspace" }, + { "path": "../../client/ui-workspace/tsconfig.client.json" }, { "path": "../../client/ui-primitives" }, { "path": "../../client/ui-renderer" }, { "path": "../../client/ui-slots" }, diff --git a/packages/client/ui-open-in-app/tsconfig.json b/packages/client/ui-open-in-app/tsconfig.json index 9e6a381554..cd08a5b44c 100644 --- a/packages/client/ui-open-in-app/tsconfig.json +++ b/packages/client/ui-open-in-app/tsconfig.json @@ -78,7 +78,7 @@ "path": "../ui-sidebar-browser/tsconfig.client.json" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } diff --git a/packages/client/ui-schedule/tsconfig.json b/packages/client/ui-schedule/tsconfig.json index 4d6865e1ae..304cfc91b7 100644 --- a/packages/client/ui-schedule/tsconfig.json +++ b/packages/client/ui-schedule/tsconfig.json @@ -42,7 +42,7 @@ "path": "../ui-tool" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-renderer" diff --git a/packages/client/ui-subagent/tsconfig.json b/packages/client/ui-subagent/tsconfig.json index 0efb4d9c5e..5df2631150 100644 --- a/packages/client/ui-subagent/tsconfig.json +++ b/packages/client/ui-subagent/tsconfig.json @@ -66,7 +66,7 @@ "path": "../ui-slots" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" } ] } diff --git a/packages/client/ui-workflow-run/tsconfig.json b/packages/client/ui-workflow-run/tsconfig.json index 786a9f9b06..5dae70f711 100644 --- a/packages/client/ui-workflow-run/tsconfig.json +++ b/packages/client/ui-workflow-run/tsconfig.json @@ -36,7 +36,7 @@ "path": "../ui-session" }, { - "path": "../ui-workspace" + "path": "../ui-workspace/tsconfig.client.json" }, { "path": "../ui-primitives" diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 92ffd98bdc..d2930fd166 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -33,8 +33,8 @@ en: 27089341ac2cbcc4 zh: 63d818a53a7c20e9 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: - en: fd142e4ec98993fb - zh: 015a058302ad1c95 + en: cecb53516a3fe30c + zh: 5d96148c1a3e6a1a /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation: en: 8f170900a4096408 zh: 85332e80adf39403 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 4f1429ba5e..86563de8b8 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -89,7 +89,7 @@ Session rows share their existing action contributions between right-click and t `ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?, options?)` opens a Workspace blank only if no later navigation has superseded the request; New Session opens the same blank as Workspace reopening, so it returns to that blank's unsent draft. `forkSession(id, onCreated?, options?)` creates the child without navigating or superseding a pending navigation; `allowMigration` carries the caller's migration permission. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. -The `mainView` reference retains the `conversation` facet. When the main view leaves a non-blank, unarchived Session, navigation first retains it as a `recentViews` reference without facets, so its history stays loaded and returning to it needs no history request, while Conversation assembly stops until it is shown again. A recent view that is running, awaits the user, or has an unread completion is always kept and does not count; up to `recentViewLimit` other recent views, 10 by default and set in the plugin's `cordis.yml` configuration, are kept besides the main-view Session. Beyond that the least recently left unpinned recent view is released first, then the least recently left pinned one; a released recent view returns only when the main view leaves that Session again. Returning a Session to the main view, removing or archiving it, or disposing the plugin releases its recent view. +The `mainView` reference retains the `conversation` facet. When the main view leaves a non-blank, unarchived Session, navigation first retains it as a `recentViews` reference without facets, so its history stays loaded and returning to it needs no history request, while Conversation assembly stops until it is shown again. A recent view that is running, awaits the user, or has an unread completion is always kept and does not count; up to `recentViewLimit` other recent views, 10 by default, are kept besides the main-view Session. `recentViewLimit` is a volatile field of the plugin's Host `Config`, set in its `cordis.yml` row and synced to the browser through [Client Modules](../modules/README.md#synced-plugin-configuration); a change takes effect without a page reload, releasing or keeping recent views by the new limit, and Sessions already released do not return. Until the browser receives a value, every counted recent view is kept. Beyond that the least recently left unpinned recent view is released first, then the least recently left pinned one; a released recent view returns only when the main view leaves that Session again. Returning a Session to the main view, removing or archiving it, or disposing the plugin releases its recent view. Session and Workspace rows derive their affordances from the browser root's access Hooks: `useWorkspaceAccess` gates a Workspace's create, rename, delete, and reorder verbs, and `useSessionAccess` gates a Session row's rename, fork, drag, pin, archive, and unarchive verbs plus the search result's restore control. A refused verb is not rendered, while every Host request remains authoritative. The Ungrouped header offers no New Session, because it has no backing Workspace to start one in. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 2c789267f8..ee657f4fc2 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -89,7 +89,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** `ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?, options?)` 仅在请求未被后续导航替代时打开工作区空白 Session;新会话与重新打开工作区打开同一个空白会话,因此会回到该空白会话中未发送的草稿。`forkSession(id, onCreated?, options?)` 创建子会话,不导航,也不替代尚未完成的导航;`allowMigration` 携带调用方的迁移许可。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。 -`mainView` 引用保留 `conversation` 子要素。主视图离开一个非空白、未归档的 Session 时,导航先以不带子要素的 `recentViews` 引用保留它,因此其历史仍已加载,切回时无需再请求历史,而 Conversation 组装在重新显示前停止。运行中、等待用户或完成未读的最近访问会话始终保留且不计数;其余最近访问会话最多保留 `recentViewLimit` 个(默认 10,在插件的 `cordis.yml` 配置中设置),不含主视图 Session。超出时先释放最早离开的未置顶会话,再释放最早离开的置顶会话;被释放的最近访问会话只有在主视图再次离开该 Session 时才会回来。Session 回到主视图、被移除或归档,或插件卸载时,会释放其最近访问引用。 +`mainView` 引用保留 `conversation` 子要素。主视图离开一个非空白、未归档的 Session 时,导航先以不带子要素的 `recentViews` 引用保留它,因此其历史仍已加载,切回时无需再请求历史,而 Conversation 组装在重新显示前停止。运行中、等待用户或完成未读的最近访问会话始终保留且不计数;其余最近访问会话最多保留 `recentViewLimit` 个(默认 10),不含主视图 Session。`recentViewLimit` 是插件 Host `Config` 的 volatile 字段,在其 `cordis.yml` 行中设置,并经 [Client Modules](../modules/README.zh.md#synced-plugin-configuration) 同步到浏览器;修改后无需刷新页面即生效,按新上限释放或保留最近访问会话,已释放的 Session 不会回来。浏览器收到值之前,所有计数的最近访问会话都会保留。超出时先释放最早离开的未置顶会话,再释放最早离开的置顶会话;被释放的最近访问会话只有在主视图再次离开该 Session 时才会回来。Session 回到主视图、被移除或归档,或插件卸载时,会释放其最近访问引用。 Session 行与 Workspace 行的可用操作来自浏览器根的访问 Hook:`useWorkspaceAccess` 门控 Workspace 的新建、重命名、删除与排序动作,`useSessionAccess` 门控 Session 行的重命名、分叉、拖拽、置顶、归档与取消归档动作,以及搜索结果的恢复控件。被拒绝的动作不渲染,但每个发往 Host 的请求仍以其授权为准。Ungrouped 标题行不提供新建会话,因为它没有可在其中新建会话的后备 Workspace。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index 76b49598bf..cbc11ffb90 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -55,20 +55,26 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, "devDependencies": { - "@deepseek-ai/schemastery": "workspace:~", - "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", @@ -82,14 +88,11 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "clsx": "^2.0.0", - "react": "^18.2.0", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", - "@deepseek-ai/dsh-util-text-search": "workspace:*" + "react": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 1b716d2dc0..84554ac66b 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -20,7 +20,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { WorkspaceNavigationConfig } from '../types.ts' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { ISessions, SessionForkError } from '@deepseek-ai/dsh-api-session-controller/client' import type { @@ -144,25 +145,14 @@ export const inject = ['contextMenus', 'uiSession', 'uiSession.sessionStatus', ] -/** Workspace navigation configuration. */ -export interface Config { - /** Recently viewed Sessions that need no attention kept loaded besides the main-view Session. */ - recentViewLimit?: number -} - -/** Validated Workspace navigation configuration. */ -export const Config: z = z.object({ - recentViewLimit: z.natural().default(10), -}) - /** * Register the browser and picker once their slot declarations are on the * ledger. Inject factories return plain callbacks; data reads use the * framework's global hooks. * @param ctx - client root context. - * @param config - validated navigation configuration. + * @param config - Host-synced navigation configuration. */ -export function apply(ctx: Context, config: Config = Config({})): void { +export function apply(ctx: Context, config: SyncedConfig): void { const sessions = ctx.get('sessions') as ISessions const workspaces = ctx.get('workspaces') as IWorkspaces // One viewing-store instance, created here as ui-layout does for its layout @@ -175,9 +165,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { let toastSeq = 0 const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, notify, - // Schemastery's field default is materialized before Cordis calls apply. - config.recentViewLimit as number, + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions, notify, config.recentViewLimit, ) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list }, diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 138c4456f3..9a5aec0e2f 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -13,7 +13,7 @@ import type { } from '@deepseek-ai/dsh-api-session-controller/client' // Type-only: pulls the `agentPreset` Session projection value into this program. import type {} from '@deepseek-ai/dsh-agent-preset-registry/types' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { @@ -186,7 +186,8 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param sessions - pure Session Controller. * @param view - the browser's viewing-store write set (one instance shared with its registration). * @param notify - show one notice through the Workspace notice channel. - * @param recentViewLimit - recently viewed Sessions needing no attention kept besides the main-view Session. + * @param recentViewLimit - Host-synced count of recently viewed Sessions needing no attention kept + * besides the main-view Session; absent until a value arrives, and followed while it changes. */ constructor( ctx: Context, @@ -195,7 +196,7 @@ class UiWorkspaceService extends Service implements UiWorkspace { private readonly sessions: ISessions, private readonly view: Pick, private readonly notify: (toast: RowToast) => void, - recentViewLimit: number, + recentViewLimit: ObservableSnapshot, ) { super(ctx, 'uiWorkspace') this.recentViews = new RecentSessionViews(sessions, workspaces, ctx.uiSession.sessionStatus, recentViewLimit) diff --git a/packages/client/ui-workspace/src/client/recent-views.ts b/packages/client/ui-workspace/src/client/recent-views.ts index 99f914ed7a..535535efa8 100644 --- a/packages/client/ui-workspace/src/client/recent-views.ts +++ b/packages/client/ui-workspace/src/client/recent-views.ts @@ -33,13 +33,14 @@ export class RecentSessionViews { * @param sessions - Session Controller that owns the references. * @param workspaces - Workspace Controller whose archived Sessions leave the list and whose pins order eviction. * @param status - unified Session UI status deciding which Sessions need attention. - * @param limit - Sessions needing no attention kept besides the main-view Session. + * @param limit - Host-synced count of Sessions needing no attention kept besides the main-view Session; + * absent until a value arrives. */ constructor( private readonly sessions: Pick, private readonly workspaces: Pick, private readonly status: ObservableSnapshot, - private readonly limit: number, + private readonly limit: ObservableSnapshot, ) {} /** @@ -58,7 +59,7 @@ export class RecentSessionViews { } /** - * Sync whenever the Session list, Workspace list, or Session UI status changes. + * Sync whenever the Session list, Workspace list, Session UI status, or recent-view limit changes. * @returns disposer that stops syncing and releases every held Session. */ start(): () => void { @@ -67,6 +68,7 @@ export class RecentSessionViews { this.sessions.list.subscribe(sync), this.workspaces.list.subscribe(sync), this.status.subscribe(sync), + this.limit.subscribe(sync), ] return () => { for (const stop of stops) stop() @@ -104,7 +106,11 @@ export class RecentSessionViews { } } - /** The candidates to keep, in order: every eligible Session needing attention plus the first `limit` others. */ + /** + * The candidates to keep, in order: every eligible Session needing attention plus the first `limit` others. + * No limit keeps every counted Session, which reaches the same result as the main view alone being loaded before + * the Host sends one. + */ private selected(): SessionId[] { const { byId } = this.sessions.list.getSnapshot() const workspaces = this.workspaces.list.getSnapshot() @@ -118,7 +124,7 @@ export class RecentSessionViews { const kept = new Set([ ...counted.filter(id => pinned.has(id)), ...counted.filter(id => !pinned.has(id)), - ].slice(0, this.limit)) + ].slice(0, this.limit.getSnapshot() ?? Number.POSITIVE_INFINITY)) return eligible.filter(id => kept.has(id) || !countedIds.has(id)) } diff --git a/packages/client/ui-workspace/src/index.ts b/packages/client/ui-workspace/src/index.ts index bb551f7b1a..04ea3caded 100644 --- a/packages/client/ui-workspace/src/index.ts +++ b/packages/client/ui-workspace/src/index.ts @@ -1,9 +1,19 @@ /** - * Workspace picker plugin, node half. Pure UI plugin: the empty apply exists - * so the plugin appears in the host cordis.yml / Loader (load and lifecycle - * follow the host; the browser half ships via exports["./client"], discovered - * through the package.json dsh.client declaration). + * Workspace picker plugin, node half. The browser half ships via + * exports["./client"], discovered through the package.json dsh.client + * declaration. The Host behavior is this plugin's configuration: its volatile + * fields are the live values the browser receives through its synced Config. */ +import z from '@deepseek-ai/schemastery' +import type { WorkspaceNavigationConfig } from './types.ts' -/** Host plugin body — no host-side behavior for the workspace picker plugin. */ +/** Live Workspace navigation preferences; the browser receives them through its synced Config. */ +export type Config = WorkspaceNavigationConfig + +/** Live Workspace navigation preferences projected to the browser. */ +export const Config = z.object({ + recentViewLimit: z.natural().default(10).volatile(), +}) + +/** Register the browser plugin without Host behavior. */ export function apply(): void {} diff --git a/packages/client/ui-workspace/src/types.ts b/packages/client/ui-workspace/src/types.ts new file mode 100644 index 0000000000..15e157cfa1 --- /dev/null +++ b/packages/client/ui-workspace/src/types.ts @@ -0,0 +1,8 @@ +/** Workspace navigation configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Live Workspace navigation preferences; the browser receives every field through its synced Config. */ +export interface WorkspaceNavigationConfig { + /** Recently viewed Sessions needing no attention kept loaded besides the main-view Session. */ + recentViewLimit: Volatile +} diff --git a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx index 216348dd92..4ecc197fb1 100644 --- a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx @@ -81,7 +81,7 @@ async function bench(access: ClientAccessState, options: { ungroupedSession?: Se SidebarFrame as never, ) await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) return runtime } diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index b3b1786c4a..187d95ef95 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -11,7 +11,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { HostObservable, PropsRenderSlots, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' import type { ShortcutCommand } from '@deepseek-ai/dsh-client-shortcuts/client' -import { RemoteError, StaticRemoteAccess, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { RemoteError, StaticRemoteAccess, syncedConfig, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' @@ -29,7 +29,6 @@ import type { ArchiveToastInjected, ToastDisplayInjected } from '../src/client/c import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' -import { apply as hostApply } from '../src/index.ts' import { SECTION_HOOK_CONTEXT, SECTION_INJECT } from './section-scroller.client.ts' import { provideSessionStatus } from './session-status.client.ts' @@ -239,10 +238,6 @@ function viewInstance(slots: SlotRegistry) { const settled = (): Promise => new Promise((resolve) => { setTimeout(resolve, 0) }) describe('ui-workspace apply', () => { - it('keeps the host Loader entry inert', () => { - expect(hostApply).not.toThrow() - }) - it('declares the services it drives', () => { expect(inject).toEqual(['contextMenus', 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout', 'shortcuts', 'remoteAccess', @@ -254,7 +249,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) const provideRoot = vi.spyOn(b.slots, 'provideRoot') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const keyed = provideRoot.mock.calls.map(([contribution]) => contribution.keyedHooks?.['workspaceAccess']).find(Boolean) // `useWorkspaceAccess(workspaceId, action)` reads the Workspace resource's answer; a call without an action names no source. expect(keyed?.('w1', 'workspace/follow')).toBe(ALLOWED) @@ -269,7 +264,7 @@ describe('ui-workspace apply', () => { it('hangs Workspace-guarded effects on the calling plugin, so they leave when it unloads', async () => { const b = await bench('static') onTestFinished(() => b.ctx.fiber.dispose()) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const dispose = vi.fn() const caller = b.ctx.plugin({ inject: ['uiWorkspace'], @@ -286,7 +281,7 @@ describe('ui-workspace apply', () => { onTestFinished(() => b.ctx.fiber.dispose()) b.initializeDefault.mockRejectedValueOnce(new Error('denied')) declare(b.slots, 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const face = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected await vi.waitFor(() => { expect(face.hooks.toast.getSnapshot()).toMatchObject({ kind: 'defaultWorkspaceFailed' }) @@ -298,7 +293,7 @@ describe('ui-workspace apply', () => { it('registers browser and pickers for declarations arriving before or after apply', async () => { const before = await bench() declare(before.slots, 'sidebar.workspaces') - await before.ctx.plugin({ inject: [...inject], apply }).await() + await before.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() expect(before.slots.entries('sidebar.workspaces')[0]!.component).toBe(WorkspaceBrowser) // Copy rides the standard locale seat: the entry declares the namespace // and apply registered both dictionaries. @@ -306,7 +301,7 @@ describe('ui-workspace apply', () => { expect(before.locale.bind('workspace')('session.new')).toBe('新会话') const after = await bench() - await after.ctx.plugin({ inject: [...inject], apply }).await() + await after.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() declare(after.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') await Promise.resolve() expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker) @@ -319,7 +314,7 @@ describe('ui-workspace apply', () => { it('declares the two Session row lists and registers the shipped actions and overlay surfaces into them', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() // The menu list binds the row's open state into every entry's hook; the // hover-button list carries no common face. expect(b.slots.spec(MENU_ITEM)).toEqual({ @@ -370,7 +365,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const action = sessionMenuActions(b.ctx) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const menu = b.ctx.contextMenus.resolve({ kind: 'session', value: { sessionId: sid('cold'), displayTitle: 'Cold' } }) @@ -400,7 +395,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const action = sessionMenuActions(b.ctx) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const writeText = vi.fn(async () => { @@ -426,7 +421,7 @@ describe('ui-workspace apply', () => { name: 'shell.overlay', id: 'test-sidebar-owner', children: { 'sidebar.workspaces': { kind: 'single', scope: 'root', inject: SECTION_INJECT } }, }, SidebarDeclarationOwner) - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() b.setSessions(sessionState([{ ...summary('source', 1), retainedBy: { mainView: 1 } }])) const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected @@ -473,7 +468,7 @@ describe('ui-workspace apply', () => { const b = await bench() b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')])) declare(b.slots, 'sidebar.workspaces') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const pin = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected const pinButton = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected @@ -502,7 +497,7 @@ describe('ui-workspace apply', () => { b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two', 'three'])])) b.setSessions(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const view = viewInstance(b.slots) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected expect(view.getSnapshot().sessionOrderByAccount).toEqual({}) @@ -543,7 +538,7 @@ describe('ui-workspace apply', () => { b.setWorkspaces(workspaceState([workspace('alpha', ['one'])])) b.setSessions(sessionState([summary('one', 1)])) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const view = viewInstance(b.slots) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const pin = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected @@ -560,7 +555,7 @@ describe('ui-workspace apply', () => { it('archives through the navigation service and raises the archived notice; Host rejections are console diagnostics', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const archiveSession = vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined) const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected @@ -599,7 +594,7 @@ describe('ui-workspace apply', () => { const b = await bench() b.setSessions(sessionState([{ ...summary('busy', 3), displayTitle: 'Busy session' }])) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const activity = [{ kind: 'turn' as const }, { kind: 'job' as const, items: [{ id: 'bash-1', label: 'pnpm run build' }] }] const refusal = Object.assign(new Error('workspace session archive failed: workspace/session-active: active'), { name: 'WorkspaceArchiveError', @@ -636,7 +631,7 @@ describe('ui-workspace apply', () => { it('the notice share takes the notice down, undoes an archive, and shows the archived rows', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected @@ -676,7 +671,7 @@ describe('ui-workspace apply', () => { it('routes fork and rename through their shares, the rename dialog, and the browser face', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) // Fork goes through the navigation service, which leaves the child unselected. @@ -732,7 +727,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() if (state !== 'absent') { const source = b.ctx.sessions.retain(sid('source'), { source: 'controllerOperation' }) onTestFinished(() => { source.release() }) @@ -761,7 +756,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() b.fork.mockRejectedValueOnce(new SessionForkError( new RemoteError('session/migration-required', 'migration required', { sessionId: sid('source') }), sid('source'), @@ -792,7 +787,7 @@ describe('ui-workspace apply', () => { b.setSessions(sessionState([summary('source', 1)])) if (timing === 'before the notice') b.setWorkspaces(workspaceState([], [sid('source')])) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() b.fork.mockRejectedValueOnce(new SessionForkError( new RemoteError('session/migration-required', 'migration required', { sessionId: sid('source') }), sid('source'), @@ -820,7 +815,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() using source = b.ctx.sessions.retain(sid('source'), { source: 'controllerOperation' }) await source.ready b.history.set({ openState: 'open', subagent: { @@ -846,7 +841,7 @@ describe('ui-workspace apply', () => { const b = await bench() onTestFinished(() => b.ctx.fiber.dispose()) declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() using source = b.ctx.sessions.retain(sid('source'), { source: 'controllerOperation' }) await source.ready b.retain.mockClear() @@ -876,7 +871,7 @@ describe('ui-workspace apply', () => { it('routes browser actions and picker creation to the services', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const startSession = vi.spyOn(b.ctx.uiWorkspace, 'startSession').mockImplementation(() => undefined) const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected @@ -909,7 +904,7 @@ describe('ui-workspace apply', () => { it('declares the browser child slots and reports directory-flow occupancy per surface', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() // Registration declared the child holes (declaration = render authorization). expect(b.slots.spec('sidebar.workspaces.directoryFlow')).toMatchObject({ kind: 'single' }) expect(b.slots.spec('conversation.hero.workspace.directoryFlow')).toMatchObject({ kind: 'single' }) @@ -934,7 +929,7 @@ describe('ui-workspace apply', () => { it('registers the reusable picker Factory and its own directory-flow hole without an outside declaration', async () => { const b = await bench() - const fiber = b.ctx.plugin({ inject: [...inject], apply }) + const fiber = b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) await fiber.await() expect(b.slots.snapshot('factory:workspace.picker')).toMatchObject([{ type: 'factory', @@ -959,7 +954,7 @@ describe('ui-workspace apply', () => { error: new RemoteError('gateway/internal', 'index unavailable', {}), }) as never) declare(b.slots, 'sidebar.workspaces') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected await expect(browser.searchSessions('needle', new AbortController().signal)) .rejects.toThrow('index unavailable') @@ -968,7 +963,7 @@ describe('ui-workspace apply', () => { it('unregisters every entry on teardown', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') - const fiber = b.ctx.plugin({ inject: [...inject], apply }) + const fiber = b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) await fiber.await() expect(b.slots.entries(MENU_ITEM)).toHaveLength(0) expect(b.slots.entries(ROW_ACTION)).toHaveLength(2) @@ -991,7 +986,7 @@ describe('ui-workspace apply', () => { it('keeps one archive notice for queued cleanup and replaces it on failure', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected @@ -1012,7 +1007,7 @@ it('keeps one archive notice for queued cleanup and replaces it on failure', asy it('returns to the ordinary archive notice when a queued cleanup settles without acting', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined) const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected @@ -1035,7 +1030,7 @@ it('returns to the ordinary archive notice when a queued cleanup settles without it('falls back to the ordinary notice when a follow-up notice provider fails', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'shell.overlay') - await b.ctx.plugin({ inject: [...inject], apply }).await() + await b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })).await() vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined) const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) const failure = new Error('notice unavailable') @@ -1052,7 +1047,7 @@ it('captures Workspace menu requests, rechecks mutable access, and withdraws reg const b = await bench() b.setWorkspaces(workspaceState([workspace('alpha', [])])) declare(b.slots, 'sidebar.workspaces') - const fiber = b.ctx.plugin({ inject: [...inject], apply }) + const fiber = b.ctx.plugin({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) await fiber.await() const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected const target = { kind: 'workspace' as const, value: { workspaceId: 'alpha' as WorkspaceId, path: '/projects/alpha', displayTitle: 'Alpha' } } diff --git a/packages/client/ui-workspace/tests/config.host.spec.ts b/packages/client/ui-workspace/tests/config.host.spec.ts new file mode 100644 index 0000000000..d53641d91f --- /dev/null +++ b/packages/client/ui-workspace/tests/config.host.spec.ts @@ -0,0 +1,25 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished } from 'vitest' +import { apply, Config } from '../src/index.ts' + +describe('ui-workspace host', () => { + it('keeps ten recent views by default and rejects a negative or fractional limit', () => { + expect(Config({}).recentViewLimit?.get()).toBe(10) + expect(Config({ recentViewLimit: 3 }).recentViewLimit?.get()).toBe(3) + expect(Config({ recentViewLimit: 0 }).recentViewLimit?.get()).toBe(0) + expect(() => Config({ recentViewLimit: -1 })).toThrow() + expect(() => Config({ recentViewLimit: 1.5 })).toThrow() + }) + + it('loads as an inert Loader entry that only declares its synced Config', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + let received: Config | undefined + const fiber = ctx.plugin({ + Config, + apply: (_ctx: Context, config: Config) => { received = config; apply() }, + }, { recentViewLimit: 4 }) + await expect(fiber.await()).resolves.toBeDefined() + expect(received?.recentViewLimit.get()).toBe(4) + }) +}) diff --git a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx index 2d245f47f8..6e1ee5140a 100644 --- a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx +++ b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx @@ -53,7 +53,7 @@ async function bench() { { 'sidebar.workspaces': { kind: 'single', scope: 'root', inject: SECTION_INJECT } } as never, SidebarFrame as never, ) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) return { runtime, remote } } diff --git a/packages/client/ui-workspace/tests/recent-views.client.spec.ts b/packages/client/ui-workspace/tests/recent-views.client.spec.ts index c6e6db2ad0..88223058ca 100644 --- a/packages/client/ui-workspace/tests/recent-views.client.spec.ts +++ b/packages/client/ui-workspace/tests/recent-views.client.spec.ts @@ -8,7 +8,6 @@ import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-clie import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { brandString } from '@deepseek-ai/dsh-brand' -import { Config } from '../src/client/index.ts' import { RecentSessionViews } from '../src/client/recent-views.ts' const sid = (id: string): SessionId => brandString(id) @@ -17,7 +16,7 @@ function row(id: SessionId, overrides: Partial = {}): SessionSum return { id, displayTitle: id, running: false, blank: false, updatedAt: 0, retainedBy: {}, ...overrides } } -function bench(ids: readonly SessionId[]) { +function bench(ids: readonly SessionId[], limit = 10) { const list = createSnapshotStore({ ids: [...ids], byId: Object.fromEntries(ids.map(id => [id, row(id)])), phase: 'ready', projectionsBySession: {}, }) @@ -44,7 +43,8 @@ function bench(ids: readonly SessionId[]) { const sessions: Pick = { list, retain, subagentAddress } const workspaceController: Pick = { list: workspaces } const status = createSnapshotStore(new Map()) - const recent = new RecentSessionViews(sessions, workspaceController, status, 10) + const recentViewLimit = createSnapshotStore(limit) + const recent = new RecentSessionViews(sessions, workspaceController, status, recentViewLimit) const stop = recent.start() const update = (id: SessionId, patch: Partial): void => { const state = list.getSnapshot() @@ -62,7 +62,10 @@ function bench(ids: readonly SessionId[]) { for (const id of ids) recent.show(id) recent.show(last) } - return { recent, stop, list, workspaces, retain, subagentAddress, update, retained, setOnRetain, setStatus, visit } + return { + recent, stop, list, workspaces, retain, subagentAddress, update, retained, setOnRetain, setStatus, visit, + recentViewLimit, + } } describe('recently viewed Sessions', () => { @@ -205,9 +208,27 @@ describe('recently viewed Sessions', () => { }) describe('recent view configuration', () => { - it('keeps ten recent views by default and rejects a negative limit', () => { - expect(Config({}).recentViewLimit).toBe(10) - expect(Config({ recentViewLimit: 3 }).recentViewLimit).toBe(3) - expect(() => Config({ recentViewLimit: -1 })).toThrow() + it('follows a changed limit, evicting and retaining as it moves', () => { + const ids = Array.from({ length: 5 }, (_, index) => sid(`l${index}`)) + const b = bench(ids, 2) + b.visit(ids.slice(0, 4), sid('l4')) + expect(b.retained()).toEqual([sid('l2'), sid('l3')]) + // Raising the limit does not bring back evicted Sessions; the next Sessions left fill the room. + b.recentViewLimit.set(4) + expect(b.retained()).toEqual([sid('l2'), sid('l3')]) + b.visit([sid('l2')], sid('l1')) + expect(b.retained().toSorted()).toEqual([sid('l2'), sid('l3'), sid('l4')]) + b.recentViewLimit.set(1) + expect(b.retained()).toEqual([sid('l2')]) + }) + + it('keeps every counted Session while the Host sends no limit', () => { + const ids = Array.from({ length: 12 }, (_, index) => sid(`n${index}`)) + const b = bench(ids) + b.recentViewLimit.set(undefined) + b.visit(ids.slice(0, 11), sid('n11')) + expect(b.retained()).toHaveLength(11) + b.recentViewLimit.set(3) + expect(b.retained()).toHaveLength(3) }) }) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 9fad8685b5..4b29c52a91 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -98,7 +98,7 @@ describe('session rename through the assembled browser', () => { await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) const registerAction = (id: string, order: number, priority: number, label: string) => { runtime.slots.register( { name: 'sidebar.workspaces.session.menu.item', id, order, priority }, @@ -172,7 +172,7 @@ describe('session rename through the assembled browser', () => { await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) const view = runtime.renderRoot() // The current session's group auto-expands; open the row's action menu. @@ -214,7 +214,7 @@ describe('session rename through the assembled browser', () => { await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView', facets: { conversation: true } }).ready await seedWorkspace(runtime) await declareFrame(runtime) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) const view = runtime.renderRoot() await runtime.flush() diff --git a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx index ae59b2fbe6..a71fa3bdf7 100644 --- a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx @@ -97,7 +97,7 @@ async function bench(): Promise { }] as never }) await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ recentViewLimit: 10 })) await runtime.root.declare({} as never, ImportDialog as never) runtime.renderRoot() return runtime diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 2404d9aa40..c6ea80ed44 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -313,7 +313,7 @@ function bench(options: BenchOptions = {}) { sessions, view.actions, notify, - 10, + createSnapshotStore(10), ) return { ctx, directoryPicker, sessions, uiWorkspace, workspaces, layout, selectPanel, view, notify, requestDraftInitialization, status } } @@ -490,7 +490,8 @@ describe('UiWorkspaceService', () => { const owner = runtime.ctx.isolate('uiWorkspace').isolate('uiSession') owner.provide('uiSession', { sessionStatus: b.status } as never) const uiWorkspace = new UiWorkspaceService( - owner, b.directoryPicker.remote, b.workspaces, sessions, b.view.actions, b.notify, 10, + owner, b.directoryPicker.remote, b.workspaces, sessions, b.view.actions, b.notify, + createSnapshotStore(10), ) uiWorkspace.openSession(sid('a')) const binding = sessions.binding('a') diff --git a/packages/client/ui-workspace/tsconfig.client.json b/packages/client/ui-workspace/tsconfig.client.json new file mode 100644 index 0000000000..5ece7218e8 --- /dev/null +++ b/packages/client/ui-workspace/tsconfig.client.json @@ -0,0 +1,103 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../config" + }, + { + "path": "../../util/text-search" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../ui-session-status/tsconfig.client.json" + }, + { + "path": "../../preset/agent-preset-registry" + }, + { + "path": "../../api/workspace-controller/tsconfig.client.json" + }, + { + "path": "../../api/remote-access/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../connection/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../core/session" + }, + { + "path": "../../subagent/subagent" + }, + { + "path": "../../jobs/jobs" + }, + { + "path": "../../schedule/schedule" + }, + { + "path": "../ui-sidebar" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../../util/values" + }, + { + "path": "../../util/workspace-path" + }, + { + "path": "../shortcuts/tsconfig.client.json" + }, + { + "path": "../product-analytics/tsconfig.client.json" + }, + { + "path": "../ui-context-menu" + } + ], + "exclude": [ + "src/index.ts" + ] +} diff --git a/packages/client/ui-workspace/tsconfig.host.json b/packages/client/ui-workspace/tsconfig.host.json new file mode 100644 index 0000000000..f41a2db85d --- /dev/null +++ b/packages/client/ui-workspace/tsconfig.host.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/types.ts", + "src/index.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + } + ] +} diff --git a/packages/client/ui-workspace/tsconfig.json b/packages/client/ui-workspace/tsconfig.json index 310c8cfb92..2eca820546 100644 --- a/packages/client/ui-workspace/tsconfig.json +++ b/packages/client/ui-workspace/tsconfig.json @@ -1,96 +1,11 @@ { - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ { - "path": "../../util/text-search" + "path": "./tsconfig.host.json" }, { - "path": "../../api/session-controller/tsconfig.client.json" - }, - { - "path": "../ui-session-status/tsconfig.client.json" - }, - { - "path": "../../preset/agent-preset-registry" - }, - { - "path": "../../api/workspace-controller/tsconfig.client.json" - }, - { - "path": "../../api/remote-access/tsconfig.client.json" - }, - { - "path": "../locale/tsconfig.client.json" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../ui-slots" - }, - { - "path": "../ui-primitives" - }, - { - "path": "../connection/tsconfig.client.json" - }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, - { - "path": "../store" - }, - { - "path": "../../core/agent" - }, - { - "path": "../../core/session" - }, - { - "path": "../../subagent/subagent" - }, - { - "path": "../../jobs/jobs" - }, - { - "path": "../../schedule/schedule" - }, - { - "path": "../ui-sidebar" - }, - { - "path": "../ui-conversation/tsconfig.client.json" - }, - { - "path": "../ui-layout" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-session" - }, - { - "path": "../../util/values" - }, - { - "path": "../../util/workspace-path" - }, - { - "path": "../shortcuts/tsconfig.client.json" - }, - { - "path": "../product-analytics/tsconfig.client.json" - }, - { - "path": "../ui-context-menu" + "path": "./tsconfig.client.json" } ] } diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index b0c696724c..a2c391e3d9 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -63,7 +63,7 @@ "path": "../../client/ui-slots" }, { - "path": "../../client/ui-workspace" + "path": "../../client/ui-workspace/tsconfig.client.json" }, { "path": "../../core/session" diff --git a/packages/experimental/deepseek-chat-import/tsconfig.client.json b/packages/experimental/deepseek-chat-import/tsconfig.client.json index fdc30fce08..ecf732f99e 100644 --- a/packages/experimental/deepseek-chat-import/tsconfig.client.json +++ b/packages/experimental/deepseek-chat-import/tsconfig.client.json @@ -19,7 +19,7 @@ { "path": "../../client/ui-primitives" }, { "path": "../../client/ui-renderer" }, { "path": "../../client/ui-sidebar" }, - { "path": "../../client/ui-workspace" }, + { "path": "../../client/ui-workspace/tsconfig.client.json" }, { "path": "../../client/ui-slots" }, { "path": "../../typert/protocol" } ] diff --git a/packages/experimental/liveshare/tsconfig.client.json b/packages/experimental/liveshare/tsconfig.client.json index 6e9af26aa1..c0be49ee8d 100644 --- a/packages/experimental/liveshare/tsconfig.client.json +++ b/packages/experimental/liveshare/tsconfig.client.json @@ -99,7 +99,7 @@ "path": "../../client/ui-slots/tsconfig.json" }, { - "path": "../../client/ui-workspace/tsconfig.json" + "path": "../../client/ui-workspace/tsconfig.client.json" }, { "path": "../../core/session" diff --git a/packages/test-support/client-runtime/tsconfig.json b/packages/test-support/client-runtime/tsconfig.json index 9777e82c3b..9bd16c5561 100644 --- a/packages/test-support/client-runtime/tsconfig.json +++ b/packages/test-support/client-runtime/tsconfig.json @@ -70,7 +70,7 @@ "path": "../../client/ui-renderer" }, { - "path": "../../client/ui-workspace" + "path": "../../client/ui-workspace/tsconfig.client.json" }, { "path": "../../client/ui-session" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c11bfeea1..7609430a44 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7643,6 +7643,10 @@ importers: version: 18.3.1 packages/client/ui-workspace: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -7668,6 +7672,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-connection': specifier: workspace:* version: link:../connection @@ -7737,9 +7744,6 @@ importers: '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../util/workspace-path - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery clsx: specifier: ^2.0.0 version: 2.1.1 diff --git a/tsconfig.client.json b/tsconfig.client.json index 23e80ae3c6..458ed45a87 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -124,7 +124,7 @@ { "path": "./packages/client/ui-tool" }, { "path": "./packages/client/ui-deliverables/tsconfig.client.json" }, { "path": "./packages/client/ui-workflow-run" }, - { "path": "./packages/client/ui-workspace" }, + { "path": "./packages/client/ui-workspace/tsconfig.client.json" }, { "path": "./packages/client/ui-input-trigger" }, { "path": "./packages/client/ui-commands" }, { "path": "./packages/client/ui-skill" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index 42aa34e68e..f90d8a900e 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -322,6 +322,7 @@ { "path": "./packages/client/ui-theme/tsconfig.host.json" }, { "path": "./packages/client/ui-chat/tsconfig.host.json" }, { "path": "./packages/client/ui-conversation/tsconfig.host.json" }, + { "path": "./packages/client/ui-workspace/tsconfig.host.json" }, { "path": "./packages/client/ui-connector-account/tsconfig.host.json" }, { "path": "./packages/client/ui-settings/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" },