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,