Merge remote-tracking branch 'origin/master' into xtr/react-loop-simplification
# Conflicts: # .agents/notes/implemented/architecture/2026-07-22-unified-send-and-coalesced-user-messages.i18n.yaml # .agents/notes/implemented/architecture/2026-07-22-unified-send-and-coalesced-user-messages.md # .agents/notes/implemented/architecture/2026-07-22-unified-send-and-coalesced-user-messages.zh.md # .agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.i18n.yaml # .agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.md # .agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.zh.md # .agents/notes/implemented/simplification/2026-07-17-one-send-one-turn.i18n.yaml # .agents/notes/implemented/simplification/2026-07-17-one-send-one-turn.md # .agents/notes/implemented/simplification/2026-07-17-one-send-one-turn.zh.md # docs/architecture.i18n.yaml # docs/cordis-catalog/events.md # docs/cordis-catalog/services.md # docs/core-data-structures/core.i18n.yaml # docs/core-data-structures/core.md # docs/core-data-structures/core.zh.md # docs/defensive-patterns.i18n.yaml # packages/client/runtime/src/client/sessions/session.ts # packages/client/runtime/tests/queue-store.spec.ts # packages/context/time-context/tests/time-context.spec.ts # packages/context/workspace-context/tests/workspace-context.spec.ts # packages/cordis/tool-cordis/src/api-catalog.ts # packages/core/agent-loop/README.i18n.yaml # packages/core/agent-loop/README.md # packages/core/agent-loop/README.zh.md # packages/core/agent-loop/src/agent.ts # packages/core/agent/README.i18n.yaml # packages/core/agent/README.md # packages/core/agent/README.zh.md # packages/core/agent/src/types.ts # packages/core/agent/tests/agent.spec.ts # packages/core/scope/src/scoped-events.generated.ts # packages/goal/command-goal/tests/command-goal.spec.ts # packages/goal/goal-session/src/index.ts # packages/goal/goal-session/tests/goal-session.spec.ts # packages/goal/goal/tests/goal.spec.ts # packages/goal/goal/tests/projection.spec.ts # packages/goal/tool-goal/tests/tool-goal.spec.ts # packages/host/apiproxy/src/api-proxy.ts # packages/host/apiproxy/src/api/events.schema.ts # packages/host/apiproxy/src/api/events.ts # packages/host/apiproxy/tests/api-proxy-workspace.spec.ts # packages/llm/llm/README.i18n.yaml # packages/llm/llm/README.zh.md # packages/llm/llm/src/index.ts # packages/pty/pty-local/tests/index.spec.ts # packages/pty/pty-local/tests/local.spec.ts # packages/pty/pty/tests/service.spec.ts # packages/pty/tool-pty/tests/loader-composition.spec.ts # packages/pty/tool-pty/tests/tools.spec.ts # packages/skill/tool-skill/tests/tool-skill.spec.ts # packages/tasks/tasks-local/tests/tasks.spec.ts # packages/ui/tui/src/index.ts # packages/ui/tui/tests/harness.ts # packages/ui/tui/tests/tui.spec.ts # scripts/gen-cordis-catalog.ts # scripts/type-equiv.manifest.json
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write
|
||||
# pnpm run verify-translation-pairing --write packages/session-title/README.md
|
||||
README.md: 64bca8153e566e1590776af511662a873198106e
|
||||
README.zh.md: b6779f3e798d695a3c22634bb298f2a7681edbfb
|
||||
README.zh.md: 5ff52211ac975e31845285f99618503cd775eded
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
持久会话标题状态、一个可选异步提供方 seam,以及两个可选启用的模型后端实现。内置首消息回退属于服务本身,因此任何组合都能在不调用辅助模型的情况下为会话生成标题。
|
||||
持久化的会话标题状态、一个可选异步提供方 seam,以及两个由模型支持、可选启用的实现。内置首消息回退属于服务本身,因此任何组合都能在不调用辅助模型的情况下为会话生成标题。
|
||||
|
||||
| 包 | 职责 | ctx 键 |
|
||||
|---|---|---|
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write
|
||||
# pnpm run verify-translation-pairing --write packages/session-title/session-title-all-messages-llm/README.md
|
||||
README.md: 25ec92432b5c2d18624f2f4d851552ee2b3bf5d0
|
||||
README.zh.md: 685046a2a4d0859e6eca86cfba67690b8271afaf
|
||||
README.zh.md: 947aa614741b2b0bd50e70f1d273a625a5624cc6
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
可选的 `ctx.sessionTitle` 提供方,通过 `ctx.llm` 总结所有符合条件的用户消息。它注册 `all-user-messages` 节奏,并在每条新用户提示词后启动新 revision,同时使用 seed 历史与子会话提示词。较新的 revision 会中止并取代旧工作;即使提供方忽略取消,也无法提交陈旧输出。
|
||||
可选的 `ctx.sessionTitle` 提供方,通过 `ctx.llm` 总结所有符合条件的用户消息。它注册 `all-user-messages` 节奏,并在每条新用户提示词后启动新 revision,同时使用预置历史与子会话提示词。较新的 revision 会中止并取代旧工作;即使提供方忽略取消,也无法提交陈旧输出。
|
||||
|
||||
该插件使用完整且必填的[共享 LLM 配置](../session-title-llm/README.md#configuration)。同时省略 `provider` 与 `model` 时,会继承每个当前已记录主请求的确切路由;也可以同时设置二者,使标题生成使用独立路由。如果最终封装的聚合提示词超过 `maxInputBytes`,请求会失败而不是截断历史;自动使用时会发出警告并保留先前标题。
|
||||
该插件使用完整且必填的[共享大语言模型(LLM)配置](../session-title-llm/README.md#configuration)。同时省略 `provider` 与 `model` 时,会继承每个当前已记录主请求的确切路由;也可以同时设置二者,使标题生成使用独立路由。如果最终封装的聚合提示词超过 `maxInputBytes`,请求会失败而不是截断历史;自动使用时会发出警告并保留先前标题。
|
||||
|
||||
## 模型体验
|
||||
|
||||
@@ -12,17 +12,17 @@
|
||||
|
||||
#### 模型看到的内容
|
||||
|
||||
标题模型会收到共享标题指令,以及一个 JSON 数组,其中按日志顺序包含截至当前 revision 的所有符合条件用户消息和确切 seq。Seed 历史也包含在内。
|
||||
标题模型会收到共享标题指令,以及一个 JSON 数组,其中按日志顺序包含截至当前 revision 的所有符合条件用户消息和确切 seq。预置历史也包含在内。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
每条符合条件的新提示词之后都可能发送一项辅助请求,每次请求受 `maxInputBytes` 和 `maxOutputTokens` 约束;显式刷新可能增加调用。主 agent 请求不会增加 token。
|
||||
每条符合条件的新提示词之后都可能发送一次辅助请求,每次请求受 `maxInputBytes` 和 `maxOutputTokens` 约束;显式刷新可能增加调用。主 agent(智能体)请求不会增加 token。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
不会使主请求失效。每条提示词后,辅助输入都会增长或变化,因此提供方专用缓存复用会在第一个变化的 JSON token 处结束。
|
||||
不会使主请求的 KV Cache 失效。每条提示词后,辅助输入都会增长或变化,因此提供方专用缓存复用会在第一个变化的 JSON token 处结束。
|
||||
|
||||
## 已知限制与暂缓工作
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- 输入溢出时保留先前标题;对于很长的会话,此提供方没有摘要再摘要机制或保留策略。
|
||||
- 输入溢出时保留先前标题;对于很长的会话,此提供方没有基于摘要继续生成摘要的机制或保留策略。
|
||||
- 它平等对待所有符合条件的用户消息,不提供权重、过滤或手动标题优先级。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write
|
||||
# pnpm run verify-translation-pairing --write packages/session-title/session-title-first-message-llm/README.md
|
||||
README.md: c24d4de1fa945d11b5a868cad88a94ed14ad3891
|
||||
README.zh.md: a3adc5366c841ed6aa08220209ed372db1fc8666
|
||||
README.zh.md: 1f864b16c473654d0a52716cddbe26fe087860dc
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
可选的 `ctx.sessionTitle` 提供方,通过 `ctx.llm` 总结第一条符合条件的用户消息。它注册 `first-message` 节奏,只在全新非 fork 会话首次创建回退时自动运行,并将结果归因于该消息的确切 seq。自动失败会保留回退,之后只能通过 `ctx.sessionTitle.refresh()` 重试。
|
||||
|
||||
该插件使用完整且必填的[共享 LLM 配置](../session-title-llm/README.md#configuration)。同时省略 `provider` 与 `model` 时,会继承当前已记录主请求的确切路由;也可以同时设置二者,使标题生成使用独立路由。
|
||||
该插件使用完整且必填的[共享大语言模型(LLM)配置](../session-title-llm/README.md#configuration)。同时省略 `provider` 与 `model` 时,会继承当前已记录主请求的确切路由;也可以同时设置二者,使标题生成使用独立路由。
|
||||
|
||||
## 模型体验
|
||||
|
||||
@@ -12,17 +12,17 @@
|
||||
|
||||
#### 模型看到的内容
|
||||
|
||||
标题模型会收到共享标题指令,以及一个只包含第一条符合条件用户消息的 JSON 数组。后续提示词与继承的 fork 历史不会触发另一项自动调用。
|
||||
标题模型会收到共享标题指令,以及一个只包含第一条符合条件用户消息的 JSON 数组。后续提示词与继承的 fork 历史不会触发再次自动调用。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
全新会话最多自动发出一项辅助请求,并受 `maxInputBytes` 和 `maxOutputTokens` 约束;显式刷新可能发出额外调用。主 agent 请求不会增加 token。
|
||||
全新会话最多自动发出一次辅助请求,并受 `maxInputBytes` 和 `maxOutputTokens` 约束;显式刷新可能发出额外调用。主 agent(智能体)请求不会增加 token。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
不会使主请求失效。辅助请求使用已配置或已记录路由,其缓存行为由提供方决定。
|
||||
不会使主请求的 KV Cache 失效。辅助请求使用已配置或已记录路由,其缓存行为由提供方决定。
|
||||
|
||||
## 已知限制与暂缓工作
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- 对于长期会话,第一条消息可能不再具有代表性;如果后续提示词应触发重新生成标题,请使用全消息提供方。
|
||||
- Fork 会保留继承的标题,绝不会自动运行此提供方,即使 seed 中的首消息来自父会话。
|
||||
- fork 会保留继承的标题,绝不会自动运行此提供方,即使其预置的首消息来自父会话。
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/session-title/session-title-llm/README.md
|
||||
README.md: 342687b5aa0cd35a70abf8cc66b3fe80342bce0b
|
||||
README.zh.md: 2bb48b52ae6298c5c895ef99ff54cf5f1d7a6d8c
|
||||
README.zh.md: d86366b589ba016793ca63daa7279504761744b3
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
模型后端会话标题提供方的共享实现策略。它解析辅助路由,将精确选中的用户消息封装为 JSON,记录可分发的确切请求,应用语言感知的标题指令,强制执行输入和输出预算,组合超时与调用方取消,组装流,并返回带有确切来源 seq 和模型 provenance 的规范化文本。
|
||||
由模型支持的会话标题提供方的共享实现策略。它解析辅助路由,将精确选中的用户消息封装为 JSON,记录可分发的确切请求,应用语言感知的标题指令,强制执行输入和输出预算,组合超时与调用方取消,组装流,并返回带有确切来源 seq 和模型来源信息的规范化文本。
|
||||
|
||||
此包是普通库,不是 Cordis 插件。提供方插件调用 `registerSessionTitleLlmProvider()`,传入各自节奏与消息选择器;该函数验证共享配置,并将每个 revision 委派给 `generateSessionTitleWithLlm()`,使两者的注册、路由、提示词、取消与验证行为不会漂移。
|
||||
此包(package)是普通库,不是 Cordis 插件。提供方插件调用 `registerSessionTitleLlmProvider()`,传入各自节奏与消息选择器;该函数验证共享配置,并将每次修订委派给 `generateSessionTitleWithLlm()`,使各插件的注册、路由、提示词、取消与验证行为不会漂移。
|
||||
|
||||
## 路由与失败契约
|
||||
|
||||
`provider` 和 `model` 覆盖项都是可选的,但必须同时作为非空字符串提供。如果没有这一对取值,辅助模块会使用当前会话已记录 `request/header` 中捕获的确切提供方/模型路由;因此,在任何路由出现前显式刷新时必须提供覆盖项。辅助模块在记录或分发前,以 `maxInputBytes` 测量最终 JSON 封装的用户提示词,包括 seq 字段、包装层与 JSON 转义,而不是将其截断。消费流期间和流完成后都会重新检查超时与调用方取消,因此即使 interceptor 或适配器忽略 abort,也不能接受迟到的成功结果。格式错误或空输出、工具调用和非 stop 结束原因同样会 reject;会话标题服务决定该 reject 属于自动警告还是显式调用方失败。
|
||||
`provider` 和 `model` 覆盖项都是可选的,但必须同时作为非空字符串提供。如果没有这一对取值,辅助模块会使用当前会话已记录 `request/header` 中捕获的确切提供方/模型路由;因此,在任何路由出现前显式刷新时必须提供覆盖项。辅助模块在记录或分发前,依据 `maxInputBytes` 检查最终 JSON 封装用户提示词的大小,包括 seq 字段、包装层与 JSON 转义,而不是将其截断。消费流期间和流完成后都会重新检查超时与调用方取消,因此即使 interceptor 或适配器忽略 abort,也不能接受迟到的成功结果。格式错误或空输出、工具调用和非 stop 结束原因同样会导致调用被拒绝;会话标题服务决定该拒绝属于自动警告还是显式调用方失败。
|
||||
|
||||
路由与输入验证完成后,辅助模块会在模型分发前直接通过 `Session` 追加仅写入日志的 `session/title-llm-request` 事件。它包含标题提供方 id、确切来源 seq、路由、系统提示词、消息列表,以及该调用使用的输出 token 上限。持久化会尽快观察该记录;追加不需要标题专属标记、类型断言、结算队列或 flush。分发的 envelope 会深度冻结,携带 `purpose: 'session-title'`,且有意不包含 dsh-agent-loop 的进程本地请求身份。Interceptor 会与记录保持一致,而循环专用重建观察者不会把它与对话 header 比较。DeepSeek 适配器会将该 purpose 映射为关闭 thinking,使少量输出预算全部用于可见标题文本;其他适配器负责自身 purpose 专用行为。后续模型失败会保留请求记录;从未成为可分发请求的验证失败不会创建记录。该事件始终位于派生模型历史之外。
|
||||
路由与输入验证完成后,辅助模块会在模型分发前直接通过 `Session` 追加仅写入日志的 `session/title-llm-request` 事件。它包含标题提供方 id、确切来源 seq、路由、系统提示词、消息列表,以及该调用使用的输出 token 上限。持久化会立即观察到该记录;追加不需要标题专属标记、类型断言、结算队列或刷写。分发的请求封套会深度冻结,携带 `purpose: 'session-title'`,且有意不包含 dsh-agent-loop 的进程本地请求身份。拦截器会与记录保持一致,而循环专用重建观察者不会把它与对话请求头比较。DeepSeek 适配器会根据该用途禁用思考,使少量输出预算全部用于可见标题文本;其他适配器负责自身用途专用行为。后续模型失败会保留请求记录;从未成为可分发请求的验证失败不会创建记录。该事件始终位于派生模型历史之外。
|
||||
|
||||
## 配置
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
| `targetCjkCharacters` | 中文、日文或韩文标题的正整数目标字符数。 |
|
||||
| `maxInputBytes` | 最终 JSON 封装用户提示词的正整数 UTF-8 字节上限。 |
|
||||
| `maxOutputTokens` | 辅助生成的正整数 token 上限。 |
|
||||
| `timeoutMs` | 运行时定时器限制内的端到端正数 deadline。 |
|
||||
| `timeoutMs` | 运行时定时器限制内的正数端到端时限。 |
|
||||
| `provider`, `model` | 可选显式路由;二者同时提供或同时省略。 |
|
||||
|
||||
## 模型体验
|
||||
@@ -31,17 +31,17 @@
|
||||
|
||||
#### 模型看到的内容
|
||||
|
||||
标题模型会收到固定系统指令,要求以输入语言返回一个简洁且无装饰的标题,其中包含所配置的词数与 CJK 字符数目标。它唯一的用户消息包含一个 JSON 数组,其中是精确选中的用户消息及其 seq。
|
||||
标题模型会收到固定系统指令,要求以输入语言返回一个简洁且无装饰的标题;该指令包含所配置的词数与 CJK 字符数目标。它唯一的用户消息包含一个 JSON 数组,其中是精确选中的用户消息及其 seq。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
辅助请求根据所选输入大小和 `maxOutputTokens` 消耗 token。它与主 agent 请求相互独立,不会向 agent 历史增加标题文本或封装内容。DeepSeek 标题调用会关闭 thinking;主对话保留自身配置的 thinking 模式。
|
||||
辅助请求根据所选输入大小和 `maxOutputTokens` 消耗 token。它与主 agent(智能体)请求相互独立,不会向 agent 历史增加标题文本或封装内容。DeepSeek 标题调用会关闭思考;主对话保留自身配置的思考模式。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
不会使主请求失效。辅助缓存复用由提供方决定;固定指令可复用,而 JSON 消息数组会随每个 revision 变化。
|
||||
不会使主请求的 KV Cache 失效。辅助缓存复用由提供方决定;固定指令可复用,而 JSON 消息数组会随每次修订变化。
|
||||
|
||||
## 已知限制与暂缓工作
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- 辅助模块只接受文本输出,并拒绝工具调用;不公开结构化输出适配器或提供方专用提示词变体。
|
||||
- 它对整个封装用户提示词强制执行字节上限,不会剪裁单条消息或应用保留策略。
|
||||
|
||||
@@ -36,7 +36,7 @@ class CooperativeAdapter extends LlmAdapter {
|
||||
if (signal === undefined) throw new Error('expected title request signal')
|
||||
await new Promise<never>((_resolve, reject) => {
|
||||
const rejectAbort = (): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- exercise exact AbortSignal.reason propagation
|
||||
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise exact AbortSignal.reason propagation
|
||||
reject(signal.reason)
|
||||
}
|
||||
if (signal.aborted) {
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/session-title/session-title/README.md
|
||||
README.md: 1939d00f7e78834ec19e2d6b4590cf12af297a30
|
||||
README.zh.md: d373c212a193a82567686a634bad79726185e832
|
||||
README.md: 9a5ec27c36f3411add37ebe231262eb5d205bc9e
|
||||
README.zh.md: 38fc9f82e3fcd94233cad31e291b8258c97d0975
|
||||
|
||||
@@ -10,6 +10,7 @@ Only text blocks from human `user/message` events are eligible. The first eligib
|
||||
|
||||
- `get(session)` folds the latest accepted title from a live or replayed log.
|
||||
- `refresh(session, signal?)` materializes the fallback when needed, then explicitly runs the registered provider over the current eligible messages. Provider errors and caller cancellation reject; cancellation does not roll back an already accepted fallback event.
|
||||
- `rename(session, title)` accepts an explicit user title synchronously: it normalizes the text, supersedes in-flight automatic work, and appends a `session/title` event with the `user` source. A user-sourced latest title pins the session — later user messages schedule no automatic revision; an explicit `refresh` remains the deliberate unpin.
|
||||
- `register(provider)` installs the sole optional provider and returns its awaitable Cordis effect disposer. A second registration throws immediately; disposal aborts pending and active calls, waits for their settlement, and only then permits another provider to register.
|
||||
|
||||
Automatic work never delays the main agent response. A provider starts only after a marked loop-built request's exact route matches the current logged `request/header`, including when the unchanged header needs no new snapshot. Its late completion appends a standalone log-only event directly through `Session` without opening a turn. Persistence observes that event eagerly and drains on ordinary lifecycle checkpoints; title publication itself does not force a flush. Automatic failures warn and retain the latest title. New all-message revisions, provider disposal, session disposal, and explicit refresh abort older work, and a stale completion cannot append. Concurrent explicit refreshes reserve their revision before provider work, while overlapping automatic and explicit fallback requests share one session-local in-flight append. The service and bundled model provider each append their own literal event type, so no generic title-write marker, cast, or settlement queue is needed. Service teardown cancels queued work and drains calls that ignore cancellation before unloading completes.
|
||||
@@ -50,5 +51,5 @@ None for the main request; title events do not change its reconstructed content
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- Manual rename, title deletion, generated-versus-user precedence, search, and list indexing are outside this service.
|
||||
- Title deletion (unpinning back to automatic titles without an explicit `refresh`), search, and list indexing are outside this service.
|
||||
- The provider registry deliberately accepts at most one implementation, so a deployment cannot compose competing title strategies without writing one provider that owns their precedence.
|
||||
|
||||
@@ -2,19 +2,20 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
由日志支持的会话标题,提供即时确定性回退与一个可选异步提供方。每个已接受 revision 都是仅写入日志的 `session/title` 事件;`foldSessionTitle()` 与 `ctx.sessionTitle.get()` 会选择最新事件,并返回其事件 seq 和时间戳。
|
||||
由日志支持的会话标题,提供即时确定性回退与一个可选异步提供方。每次已接受的修订都是仅写入日志的 `session/title` 事件;`foldSessionTitle()` 与 `ctx.sessionTitle.get()` 会选择最新事件,并返回其事件 seq 和时间戳。
|
||||
|
||||
只有用户 `user/message` 事件中的文本块符合条件。第一条符合条件的提示词会安排回退,从其开头若干词生成标题,并受所配置 UTF-8 字节上限约束。系统会规范化空白、移除终端控制序列,且截断绝不会切断 code point。空提示词和非文本提示词会等待后续符合条件的输入。
|
||||
只有用户 `user/message` 事件中的文本块符合条件。第一条符合条件的提示词会安排回退,从其开头若干词生成标题,并受所配置 UTF-8 字节上限约束。系统会规范化空白、移除终端控制序列,且截断绝不会切断码点。空提示词和非文本提示词会等待后续符合条件的输入。
|
||||
|
||||
## 服务:`SessionTitleService`(ctx 键:`sessionTitle`)
|
||||
|
||||
- `get(session)` 从活跃或回放日志折叠最新已接受标题。
|
||||
- `refresh(session, signal?)` 在需要时物化回退,然后显式运行已注册提供方,处理当前符合条件的消息。提供方错误与调用方取消会 reject;取消不会回滚已接受的回退事件。
|
||||
- `register(provider)` 安装唯一可选提供方,并返回可等待的 Cordis effect disposer。第二次注册会立即抛出;资源释放会中止待处理和活跃调用,等待其结算,之后才允许注册另一个提供方。
|
||||
- `refresh(session, signal?)` 在需要时物化回退,然后显式运行已注册提供方,处理当前符合条件的消息。提供方错误或调用方取消都会导致返回的 Promise 被拒绝;取消不会回滚已接受的回退事件。
|
||||
- `rename(session, title)` 同步接受用户显式标题:规范化文本、取代在途自动工作,并追加一条 `user` 来源的 `session/title` 事件。最新标题来源为 user 即钉住该会话——后续用户消息不再安排自动 revision;显式 `refresh` 仍是有意的解钉手段。
|
||||
- `register(provider)` 安装唯一可选提供方,并返回可等待的 Cordis effect disposer。第二次注册会立即抛出;对提供方执行 dispose(资源释放)会中止待处理和活跃调用,等待其结算,之后才允许注册另一个提供方。
|
||||
|
||||
自动工作绝不会延迟主 agent(智能体)响应。只有当带标记、由循环构建的请求,其确切路由与当前已记录的 `request/header` 匹配时,提供方才会启动;即使 header 未变而无需新快照,也适用此规则。延迟完成会直接通过 `Session` 追加一个独立的纯日志事件,而不打开轮次。持久化会尽快观察该事件,并在常规生命周期检查点排空;标题发布本身不会强制 flush。自动失败会发出警告并保留最新标题。新的全消息 revision、提供方资源释放、会话资源释放和显式刷新都会中止旧工作,陈旧完成值无法追加。并发显式刷新会在提供方工作之前预留修订号;重叠的自动/显式回退请求共享一个会话本地进行中追加。服务与随附模型提供方各自追加自己的字面量事件类型,因此不需要通用标题写入标记、类型断言或结算队列。服务 teardown 会取消排队工作,并在卸载完成前排空忽略取消的调用。
|
||||
自动工作绝不会延迟主 agent(智能体)响应。只有当带标记、由循环构建的请求,其确切路由与当前已记录的 `request/header` 匹配时,提供方才会启动;即使请求头未变而无需新快照,也适用此规则。延迟完成会直接通过 `Session` 追加一个独立的纯日志事件,而不打开轮次。持久化会立即观察到该事件,并在常规生命周期检查点完成刷写;标题发布本身不会强制刷写。自动失败会发出警告并保留最新标题。新的全消息修订、提供方 dispose、会话 dispose 和显式刷新都会中止旧工作,陈旧的完成结果无法追加。并发显式刷新会在提供方工作之前预留修订号;重叠的自动/显式回退请求共享一个会话本地正在进行的追加操作。服务与内置模型提供方各自追加自己的字面事件类型,因此不需要通用标题写入标记、类型断言或结算队列。服务拆卸会取消排队工作,并在卸载完成前等待不响应取消的调用结算完成。
|
||||
|
||||
Fork 会原样继承 seed 中的标题事件。首消息节奏不会自动为子会话重新生成标题;全消息节奏可以在子会话收到后续用户提示词后追加新 revision。
|
||||
Fork 出的会话会原样继承种子中的标题事件。首消息节奏不会自动为子会话重新生成标题;全消息节奏可以在子会话收到后续用户提示词后追加新修订。
|
||||
|
||||
## 配置
|
||||
|
||||
@@ -28,7 +29,7 @@ Fork 会原样继承 seed 中的标题事件。首消息节奏不会自动为子
|
||||
|
||||
## 提供方契约
|
||||
|
||||
提供方会提供品牌化稳定 id、自动模式(`first-message` 或 `all-user-messages`)和 `generate(request)`。请求携带活跃会话、截至一个固定 revision 的所有符合条件消息、可用时当前已记录的主请求路由,以及取消信号。结果包含非空标题、该请求中唯一且有序的来源消息 seq,以及可选模型 provenance。服务会在结果持久化前进行规范化和验证。
|
||||
提供方会提供带品牌类型的稳定 id、自动模式(`first-message` 或 `all-user-messages`)和 `generate(request)`。请求携带活跃会话、截至一次固定修订的所有符合条件消息、可用时当前已记录的主请求路由,以及取消信号。结果包含非空标题、该请求中唯一且有序的来源消息 seq,以及可选的模型来源信息。服务会在结果持久保存前进行规范化和验证。
|
||||
|
||||
参见[会话标题数据结构](../../../docs/core-data-structures/session-title.md)与[已实现决策](../../../.agents/notes/implemented/feature/2026-07-21-log-backed-session-titles.md)。
|
||||
|
||||
@@ -42,13 +43,13 @@ Fork 会原样继承 seed 中的标题事件。首消息节奏不会自动为子
|
||||
|
||||
#### Token 影响
|
||||
|
||||
回退与已接受的提供方 revision 不会向主 agent 请求增加 token。可选提供方的独立辅助请求由对应提供方包记录。
|
||||
回退与已接受的提供方修订不会向主 agent 请求增加 token。可选提供方的独立辅助请求由对应提供方包(package)的文档说明。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
不影响主请求;标题事件不会改变重建内容或缓存键。
|
||||
|
||||
## 已知限制与暂缓工作
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- 手动重命名、删除标题、生成标题与用户标题的优先级、搜索和列表索引都不属于此服务。
|
||||
- 删除标题(不经显式 `refresh` 就解钉回自动标题)、搜索和列表索引不属于此服务。
|
||||
- 提供方注册表有意最多接受一个实现,因此部署若要组合相互竞争的标题策略,必须编写一个自行负责优先级的提供方。
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Context, FiberState, Service, type Fiber } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import { z as zod } from 'zod'
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
import { deepFreeze, isAgentLoopRequest } from '@deepseek-ai/dsh-llm'
|
||||
import { assertNever, deepFreeze, isAgentLoopRequest } from '@deepseek-ai/dsh-llm'
|
||||
import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
|
||||
import type {
|
||||
Session,
|
||||
@@ -52,14 +52,18 @@ export type SessionTitleSource =
|
||||
readonly provider: SessionTitleProviderId
|
||||
readonly model?: SessionTitleModelProvenance
|
||||
}
|
||||
| {
|
||||
/** Explicit user rename: pins the title — automatic generation stops scheduling. */
|
||||
readonly kind: 'user'
|
||||
}
|
||||
|
||||
/** Payload of the log-only `session/title` event. */
|
||||
export interface SessionTitleEventData {
|
||||
/** Normalized non-empty title text. */
|
||||
readonly title: string
|
||||
/** Exact human `user/message` seqs used to derive this title. */
|
||||
/** Exact human `user/message` seqs used to derive this title; empty for an explicit user rename. */
|
||||
readonly messageSeqs: number[]
|
||||
/** Built-in fallback or registered-provider provenance. */
|
||||
/** Built-in fallback, registered-provider, or explicit-user provenance. */
|
||||
readonly source: SessionTitleSource
|
||||
}
|
||||
|
||||
@@ -97,6 +101,16 @@ declare module '@deepseek-ai/dsh-session' {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejection of an explicit user title whose text normalizes to empty — the
|
||||
* one {@link SessionTitleService.rename} failure that blames the input.
|
||||
* Callers translating rename failures onto a wire (`title-invalid`) narrow on
|
||||
* this class; liveness and disposal failures stay plain `Error`s.
|
||||
*/
|
||||
export class SessionTitleInvalidError extends Error {
|
||||
override readonly name = 'SessionTitleInvalidError'
|
||||
}
|
||||
|
||||
/** One eligible human text message exposed to title providers. */
|
||||
export interface SessionTitleUserMessage {
|
||||
/** Source `user/message` event seq. */
|
||||
@@ -180,20 +194,27 @@ export function foldSessionTitle(events: readonly SessionEvent[]): SessionTitleS
|
||||
return deepFreeze({
|
||||
title: event.data.title,
|
||||
messageSeqs: [...event.data.messageSeqs],
|
||||
source: event.data.source.kind === 'fallback'
|
||||
? { kind: 'fallback' }
|
||||
: {
|
||||
kind: 'provider',
|
||||
provider: event.data.source.provider,
|
||||
...(event.data.source.model === undefined
|
||||
? {}
|
||||
: { model: { ...event.data.source.model } }),
|
||||
},
|
||||
source: copySessionTitleSource(event.data.source),
|
||||
eventSeq: event.seq,
|
||||
updatedAt: event.time,
|
||||
})
|
||||
}
|
||||
|
||||
/** Defensive copy of a logged title source (the snapshot must not alias log-owned objects). */
|
||||
function copySessionTitleSource(source: SessionTitleSource): SessionTitleSource {
|
||||
switch (source.kind) {
|
||||
case 'fallback': return { kind: 'fallback' }
|
||||
case 'provider': return {
|
||||
kind: 'provider',
|
||||
provider: source.provider,
|
||||
...(source.model === undefined ? {} : { model: { ...source.model } }),
|
||||
}
|
||||
case 'user': return { kind: 'user' }
|
||||
/* v8 ignore next -- closed-union exhaustiveness guard */
|
||||
default: return assertNever(source, 'SessionTitleSource')
|
||||
}
|
||||
}
|
||||
|
||||
/** Service-owned resolved limits. */
|
||||
interface ResolvedConfig {
|
||||
readonly fallbackMaxWords: number
|
||||
@@ -328,6 +349,39 @@ export class SessionTitleService extends Service {
|
||||
return foldSessionTitle(session.events)
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept an explicit user title. Appends a `session/title` event with the
|
||||
* `user` source, which pins the title: in-flight automatic generation is
|
||||
* superseded and later user messages schedule none (an explicit
|
||||
* {@link SessionTitleService.refresh} remains the deliberate unpin).
|
||||
* @param session - exact live session to rename.
|
||||
* @param title - raw user input; normalized before acceptance.
|
||||
* @returns the accepted title snapshot.
|
||||
* @throws {SessionTitleInvalidError} when the title normalizes to empty.
|
||||
* @throws {Error} when the session is not live or the service is disposed.
|
||||
*/
|
||||
rename(session: Session, title: string): SessionTitleSnapshot {
|
||||
this.assertServiceActive()
|
||||
if (this.ctx.sessions.get(session.id) !== session) {
|
||||
throw new Error(`session "${session.id}" is not live in this store`)
|
||||
}
|
||||
const normalized = normalizeSessionTitle(title, this.config.maxTitleBytes)
|
||||
if (normalized.length === 0) {
|
||||
throw new SessionTitleInvalidError('session title must contain visible characters')
|
||||
}
|
||||
const state = this.stateFor(session)
|
||||
this.supersede(state, 'user rename superseded automatic title generation')
|
||||
session.append('session/title', {
|
||||
title: normalized,
|
||||
messageSeqs: [],
|
||||
source: { kind: 'user' },
|
||||
})
|
||||
const snapshot = this.get(session)
|
||||
/* v8 ignore next -- unreachable: the append above just committed a session/title event. */
|
||||
if (snapshot === undefined) throw new Error('renamed title failed to fold')
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicitly retry the registered provider, or materialize the built-in
|
||||
* fallback when no provider is registered.
|
||||
@@ -345,6 +399,16 @@ export class SessionTitleService extends Service {
|
||||
const messages = collectSessionTitleMessages(session.events)
|
||||
const latest = messages.at(-1)
|
||||
if (registration === undefined || registration.closing || latest === undefined) {
|
||||
// Explicit refresh is the unpin even without a provider: a standing
|
||||
// user title must not short-circuit ensureFallback into a no-op, so
|
||||
// re-derive and append the fallback over it when one is derivable.
|
||||
const current = this.get(session)
|
||||
const [first] = messages
|
||||
if (current?.source.kind === 'user' && first !== undefined) {
|
||||
this.appendFallback(session, first)
|
||||
signal?.throwIfAborted()
|
||||
return this.get(session)
|
||||
}
|
||||
const fallback = await this.ensureFallback(session)
|
||||
signal?.throwIfAborted()
|
||||
return fallback
|
||||
@@ -398,6 +462,8 @@ export class SessionTitleService extends Service {
|
||||
private onUserMessage(session: Session, event: Extract<SessionEvent, { type: 'user/message' }>): void {
|
||||
if (!this.serviceActive()) return
|
||||
if (event.data.source.kind !== 'user' || collectSessionTitleMessages([event]).length === 0) return
|
||||
// A user rename pins the title: no automatic revision may override it.
|
||||
if (this.get(session)?.source.kind === 'user') return
|
||||
const registration = this.registration
|
||||
if (registration !== undefined && !registration.closing) {
|
||||
const messages = collectSessionTitleMessages(session.events, event.seq)
|
||||
@@ -668,6 +734,23 @@ export class SessionTitleService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive and append the deterministic fallback title over whatever stands
|
||||
* (the refresh unpin path: overwriting a pinned user title is the point).
|
||||
* Synchronous on purpose — no await may separate derivation from append, so
|
||||
* it needs neither ensureFallback's in-flight dedup nor its liveness
|
||||
* re-check. An underivable fallback (empty after the caps) appends nothing.
|
||||
*/
|
||||
private appendFallback(session: Session, first: SessionTitleUserMessage): void {
|
||||
const title = fallbackSessionTitle(first.text, this.config.fallbackMaxWords, this.config.fallbackMaxBytes)
|
||||
if (title.length === 0) return
|
||||
session.append('session/title', {
|
||||
title,
|
||||
messageSeqs: [first.seq],
|
||||
source: { kind: 'fallback' },
|
||||
})
|
||||
}
|
||||
|
||||
/** Create the first deterministic fallback if the session still lacks a title. */
|
||||
private async ensureFallback(session: Session): Promise<SessionTitleSnapshot | undefined> {
|
||||
this.assertServiceActive()
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-session-title'
|
||||
|
||||
@@ -15,11 +16,26 @@ export const name = 'session-title-invariant'
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: the service validates provider revisions before their
|
||||
* title append, and its remaining lifecycle state is process-local and covered
|
||||
* by package tests.
|
||||
* Durable title-provenance invariant: an automatic title always cites at
|
||||
* least one human `user/message` seq, and an explicit user rename cites none
|
||||
* — `messageSeqs` is empty iff `source.kind` is `user`. Provider revisions
|
||||
* are validated by the service before their append; this checks the durable
|
||||
* relationship every appended `session/title` event must keep, whichever
|
||||
* writer produced it.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
|
||||
// internal/dispatch interception rejects the append before publication
|
||||
// (the session/event listener would only observe the already-committed log).
|
||||
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
||||
if (eventName !== 'session/event') return
|
||||
const [, event] = args as [unknown, SessionEvent]
|
||||
if (event.type !== 'session/title') return
|
||||
const { source, messageSeqs } = event.data
|
||||
if ((messageSeqs.length === 0) !== (source.kind === 'user')) {
|
||||
fail(`session/title event ${String(event.seq)} breaks provenance: source "${source.kind}" with ${String(messageSeqs.length)} cited message seq(s)`)
|
||||
}
|
||||
}, { global: true })
|
||||
}, { inject: ['sessions'] })
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
|
||||
44
packages/session-title/session-title/tests/invariant.spec.ts
Normal file
44
packages/session-title/session-title/tests/invariant.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Title-provenance invariant: messageSeqs is empty iff source.kind is 'user'
|
||||
// — the durable relationship every appended session/title event must keep.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import * as SessionTitleInvariantCompanion from '@deepseek-ai/dsh-session-title/invariant'
|
||||
import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
|
||||
async function setup(): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(SessionTitleInvariantCompanion)
|
||||
return ctx
|
||||
}
|
||||
|
||||
describe('session-title provenance invariant', () => {
|
||||
it('accepts cited automatic titles and citation-free user renames', async () => {
|
||||
const ctx = await setup()
|
||||
const session = ctx.sessions.create(SessionId('title-invariant-valid'))
|
||||
expect(() => {
|
||||
session.append('session/title', { title: 'auto', messageSeqs: [1], source: { kind: 'fallback' } })
|
||||
session.append('session/title', { title: 'named', messageSeqs: [], source: { kind: 'user' } })
|
||||
}).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects a citation-free automatic title and a user rename that cites messages', async () => {
|
||||
const ctx = await setup()
|
||||
const session = ctx.sessions.create(SessionId('title-invariant-invalid'))
|
||||
expect(() => {
|
||||
session.append('session/title', { title: 'auto', messageSeqs: [], source: { kind: 'fallback' } })
|
||||
}).toThrow(expect.objectContaining<Partial<InvariantError>>({
|
||||
code: 'INVARIANT',
|
||||
packageName: '@deepseek-ai/dsh-session-title',
|
||||
}))
|
||||
expect(() => {
|
||||
session.append('session/title', { title: 'named', messageSeqs: [1], source: { kind: 'user' } })
|
||||
}).toThrow(expect.objectContaining<Partial<InvariantError>>({
|
||||
code: 'INVARIANT',
|
||||
packageName: '@deepseek-ai/dsh-session-title',
|
||||
}))
|
||||
expect(session.seq).toBe(0)
|
||||
})
|
||||
})
|
||||
181
packages/session-title/session-title/tests/rename.spec.ts
Normal file
181
packages/session-title/session-title/tests/rename.spec.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
// SessionTitleService.rename: user-source acceptance, normalization/rejection
|
||||
// boundaries, and the pin (a user-sourced latest title schedules no automatic
|
||||
// revision; explicit refresh stays the unpin).
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import SessionTitleService, {
|
||||
SessionTitleProviderId,
|
||||
foldSessionTitle,
|
||||
type SessionTitleProviderRequest,
|
||||
} from '@deepseek-ai/dsh-session-title'
|
||||
|
||||
const CONFIG = {
|
||||
fallbackMaxWords: 5,
|
||||
fallbackMaxBytes: 40,
|
||||
maxTitleBytes: 40,
|
||||
} as const
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
}
|
||||
|
||||
function appendHumanPrompt(session: ReturnType<Context['sessions']['create']>, text: string) {
|
||||
return session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text }],
|
||||
source: { kind: 'user' },
|
||||
}), { surfaceOp: 'append' })
|
||||
}
|
||||
|
||||
describe('SessionTitleService.rename', () => {
|
||||
it('appends a normalized user-source title', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionTitleService, CONFIG)
|
||||
const session = ctx.sessions.create(SessionId('rename-accept'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendHumanPrompt(session, 'Original prompt text')
|
||||
await settle()
|
||||
|
||||
const accepted = ctx.sessionTitle.rename(session, ' Hand\tpicked name ')
|
||||
expect(accepted).toMatchObject({
|
||||
title: 'Hand picked name',
|
||||
messageSeqs: [],
|
||||
source: { kind: 'user' },
|
||||
})
|
||||
const event = session.events.findLast(item => item.type === 'session/title')
|
||||
expect(event?.data).toEqual({
|
||||
title: 'Hand picked name',
|
||||
messageSeqs: [],
|
||||
source: { kind: 'user' },
|
||||
})
|
||||
// foldSessionTitle round-trips the third source kind.
|
||||
expect(foldSessionTitle(session.events)?.source).toEqual({ kind: 'user' })
|
||||
})
|
||||
|
||||
it('rejects titles that normalize to empty and dead sessions', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionTitleService, CONFIG)
|
||||
const session = ctx.sessions.create(SessionId('rename-reject'))
|
||||
expect(() => ctx.sessionTitle.rename(session, ' [31m ')).toThrow(/visible characters/)
|
||||
|
||||
expect(() => ctx.sessionTitle.rename(new Session(SessionId('detached')), 'name'))
|
||||
.toThrow(/not live in this store/)
|
||||
})
|
||||
|
||||
it('pins the title: later user messages schedule no automatic revision; refresh unpins', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionTitleService, CONFIG)
|
||||
const generate = vi.fn(async (request: SessionTitleProviderRequest) => ({
|
||||
title: 'Provider title',
|
||||
messageSeqs: request.messages.map(message => message.seq),
|
||||
}))
|
||||
ctx.sessionTitle.register({
|
||||
id: SessionTitleProviderId('pin-provider'),
|
||||
automatic: 'all-user-messages',
|
||||
generate,
|
||||
})
|
||||
const session = ctx.sessions.create(SessionId('rename-pin'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendHumanPrompt(session, 'First prompt')
|
||||
await settle()
|
||||
ctx.sessionTitle.rename(session, 'Pinned by hand')
|
||||
|
||||
// A later eligible prompt must schedule nothing while the pin stands.
|
||||
appendHumanPrompt(session, 'Second prompt after the pin')
|
||||
await settle()
|
||||
session.append('request/header', {
|
||||
header: { config: { provider: 'main-route', model: 'chat-model' } },
|
||||
reason: 'change',
|
||||
})
|
||||
await settle()
|
||||
expect(generate).not.toHaveBeenCalled()
|
||||
expect(ctx.sessionTitle.get(session)?.title).toBe('Pinned by hand')
|
||||
|
||||
// Explicit refresh remains the deliberate unpin.
|
||||
const refreshed = await ctx.sessionTitle.refresh(session)
|
||||
expect(generate).toHaveBeenCalledOnce()
|
||||
expect(refreshed?.title).toBe('Provider title')
|
||||
expect(ctx.sessionTitle.get(session)?.source.kind).toBe('provider')
|
||||
})
|
||||
|
||||
it('fallback-only refresh also unpins: the user title yields to a re-derived fallback', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionTitleService, CONFIG)
|
||||
const session = ctx.sessions.create(SessionId('rename-unpin-fallback'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendHumanPrompt(session, 'Derivable prompt words')
|
||||
await settle()
|
||||
ctx.sessionTitle.rename(session, 'Pinned without provider')
|
||||
expect(ctx.sessionTitle.get(session)?.source.kind).toBe('user')
|
||||
|
||||
const refreshed = await ctx.sessionTitle.refresh(session)
|
||||
expect(refreshed).toMatchObject({
|
||||
title: 'Derivable prompt words',
|
||||
source: { kind: 'fallback' },
|
||||
})
|
||||
// The pin is gone: the latest title is fallback-sourced, so the
|
||||
// onUserMessage pin check no longer skips scheduling.
|
||||
expect(ctx.sessionTitle.get(session)?.source.kind).toBe('fallback')
|
||||
})
|
||||
|
||||
it('supersedes in-flight automatic generation: a late provider result cannot override the user title', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionTitleService, CONFIG)
|
||||
// The provider parks on a test-held deferred so rename lands while its
|
||||
// generation is ACTIVE (not merely scheduled).
|
||||
let releaseProvider: (() => void) | undefined
|
||||
const gate = new Promise<void>((resolve) => { releaseProvider = resolve })
|
||||
let aborted = false
|
||||
const generate = vi.fn(async (request: SessionTitleProviderRequest) => {
|
||||
request.signal.addEventListener('abort', () => { aborted = true })
|
||||
await gate
|
||||
return { title: 'Late provider title', messageSeqs: request.messages.map(message => message.seq) }
|
||||
})
|
||||
ctx.sessionTitle.register({
|
||||
id: SessionTitleProviderId('deferred-provider'),
|
||||
automatic: 'all-user-messages',
|
||||
generate,
|
||||
})
|
||||
const session = ctx.sessions.create(SessionId('rename-supersede'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendHumanPrompt(session, 'Prompt that triggers generation')
|
||||
session.append('request/header', {
|
||||
header: { config: { provider: 'main-route', model: 'chat-model' } },
|
||||
reason: 'change',
|
||||
})
|
||||
await settle()
|
||||
expect(generate).toHaveBeenCalledOnce()
|
||||
|
||||
ctx.sessionTitle.rename(session, 'User wins')
|
||||
expect(aborted).toBe(true)
|
||||
releaseProvider?.()
|
||||
await settle()
|
||||
// The released provider result must not append over the user title, and
|
||||
// the swallowed abort must not surface as an unhandled rejection.
|
||||
const latest = session.events.findLast(item => item.type === 'session/title')
|
||||
expect(latest?.data).toMatchObject({ title: 'User wins', source: { kind: 'user' } })
|
||||
})
|
||||
|
||||
it('fallback-only refresh keeps the user title when no fallback is derivable', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
// A 3-byte fallback cap cannot hold the 4-byte emoji prompt: the
|
||||
// re-derived fallback is empty, so the pinned title survives the refresh.
|
||||
await ctx.plugin(SessionTitleService, { ...CONFIG, fallbackMaxBytes: 3 })
|
||||
const session = ctx.sessions.create(SessionId('rename-unpin-empty'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendHumanPrompt(session, '😀😀')
|
||||
await settle()
|
||||
ctx.sessionTitle.rename(session, 'Sticky emoji pin')
|
||||
|
||||
const refreshed = await ctx.sessionTitle.refresh(session)
|
||||
expect(refreshed?.title).toBe('Sticky emoji pin')
|
||||
expect(ctx.sessionTitle.get(session)?.source.kind).toBe('user')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user