فهرست منبع

只保留 Bot 模式:删除普通聊天、历史与文件库

所有账号统一使用 Bot 单聊和群聊;旧链接跳转到 /conversations。
删除普通聊天的前端页面、实时协议、聊天缓存与转录存储、设备配对、
Hermes 原生 Bot 中继及对应测试和文档。未读只统计 Bot 会话。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HvtCVd6vwAvwixrtCT1h76
Claude 4 ساعت پیش
والد
کامیت
0c1df416ba
100فایلهای تغییر یافته به همراه173 افزوده شده و 15190 حذف شده
  1. 1 1
      README.md
  2. 0 1
      docker.env.example
  3. 0 1
      docs/docker-install.md
  4. 27 0
      docs/embedded-hermes-migration.md
  5. 0 21
      docs/hermes-bot-relay.md
  6. 0 47
      docs/http-sse-realtime.md
  7. 0 32
      docs/ordinary-chat-incremental-sync.md
  8. 0 40
      docs/read-cache.md
  9. 0 1
      package.json
  10. 0 131
      scripts/verify-mobile-pair.test.ts
  11. 4 11
      src/client/App.vue
  12. 0 284
      src/client/api/chatTranscript.ts
  13. 1 1
      src/client/api/client.ts
  14. 0 40
      src/client/api/files.ts
  15. 0 105
      src/client/api/httpRealtime.ts
  16. 0 64
      src/client/api/pairing.ts
  17. 10 118
      src/client/api/profiles.ts
  18. 0 182
      src/client/api/realtime.ts
  19. 0 169
      src/client/api/sessions.ts
  20. 29 295
      src/client/components/app/NodePairingPanel.vue
  21. 8 16
      src/client/components/app/SettingsCenterDialog.vue
  22. 2 6
      src/client/components/app/SystemOverviewPanel.vue
  23. 24 288
      src/client/components/app/WorkspaceShell.vue
  24. 0 6
      src/client/components/common/types.ts
  25. 0 150
      src/client/components/composer/ModelChoiceDialog.vue
  26. 0 97
      src/client/components/library/LibraryGrid.vue
  27. 0 415
      src/client/components/messages/MessageTimeline.vue
  28. 0 67
      src/client/components/messages/SessionOutline.vue
  29. 0 93
      src/client/components/workspace/WorkspaceView.vue
  30. 0 40
      src/client/components/workspace/pendingComposer.ts
  31. 7 8
      src/client/router/index.ts
  32. 0 1105
      src/client/stores/chat.ts
  33. 0 81
      src/client/stores/files.ts
  34. 0 53
      src/client/utils/cache.ts
  35. 0 40
      src/client/utils/chatHistory.ts
  36. 0 33
      src/client/utils/contextUsage.ts
  37. 0 14
      src/client/utils/interfaceMode.ts
  38. 0 397
      src/client/utils/messageReducer.ts
  39. 0 42
      src/client/utils/sessionModel.ts
  40. 0 19
      src/client/utils/sessionOrder.ts
  41. 0 72
      src/client/utils/sessionOutline.ts
  42. 0 10
      src/client/utils/sessionOwnership.ts
  43. 0 31
      src/client/utils/sessionPreferences.ts
  44. 0 596
      src/client/views/ChatView.vue
  45. 0 25
      src/client/views/ConversationsView.vue
  46. 0 156
      src/client/views/FilesView.vue
  47. 0 466
      src/client/views/HistoryView.vue
  48. 14 118
      src/server/app.ts
  49. 0 1577
      src/server/chatCache.ts
  50. 0 86
      src/server/chatTranscriptApi.ts
  51. 0 1209
      src/server/chatTranscriptStore.ts
  52. 0 26
      src/server/chatUnread.ts
  53. 0 11
      src/server/config.ts
  54. 0 62
      src/server/hermes/socket.ts
  55. 0 90
      src/server/hermesBotRelay.ts
  56. 1 2
      src/server/index.ts
  57. 0 36
      src/server/pushEventAdapter.ts
  58. 0 1416
      src/server/pushEvents.ts
  59. 0 261
      src/server/realtimeApi.ts
  60. 0 666
      src/server/realtimeBroker.ts
  61. 0 354
      src/server/realtimeProtocol.ts
  62. 0 92
      src/server/realtimeReceipts.ts
  63. 6 830
      src/server/routes.ts
  64. 7 31
      src/server/unreadCenter.ts
  65. 0 139
      src/server/workspaceRemoteAgents.ts
  66. 1 11
      src/server/workspaceStore.ts
  67. 0 125
      src/shared/chatTranscript.ts
  68. 0 15
      tests/client/agentAvatar.test.ts
  69. 2 3
      tests/client/chatAppearance.test.ts
  70. 0 478
      tests/client/chatCrossClientSync.test.ts
  71. 0 109
      tests/client/chatLifecycle.test.ts
  72. 0 266
      tests/client/chatModelSync.test.ts
  73. 0 66
      tests/client/chatProtocol.test.ts
  74. 0 213
      tests/client/chatStore.test.ts
  75. 0 38
      tests/client/contextUsage.test.ts
  76. 2 2
      tests/client/csrfRecovery.test.ts
  77. 0 25
      tests/client/filesProtocol.test.ts
  78. 0 39
      tests/client/httpRealtimeRecovery.test.ts
  79. 0 25
      tests/client/interfaceMode.test.ts
  80. 1 2
      tests/client/messageFailure.test.ts
  81. 0 41
      tests/client/modelChoiceDialog.test.ts
  82. 1 106
      tests/client/nodePairingPanel.test.ts
  83. 0 184
      tests/client/ordinaryTranscriptV2.test.ts
  84. 0 40
      tests/client/scopedCache.test.ts
  85. 2 3
      tests/client/serviceWarnings.test.ts
  86. 0 55
      tests/client/sessionModel.test.ts
  87. 0 19
      tests/client/sessionOrder.test.ts
  88. 0 51
      tests/client/sessionOutline.test.ts
  89. 0 40
      tests/client/sessionPreferences.test.ts
  90. 0 24
      tests/client/sessionProtocol.test.ts
  91. 0 13
      tests/client/sessionUnread.test.ts
  92. 11 38
      tests/client/settingsCenterDialog.test.ts
  93. 1 2
      tests/client/systemMessageNotice.test.ts
  94. 0 2
      tests/client/typingIndicator.test.ts
  95. 8 82
      tests/client/workspaceShell.test.ts
  96. 1 1
      tests/e2e/bot-panels.spec.ts
  97. 1 1
      tests/e2e/credential-vault.spec.ts
  98. 0 131
      tests/e2e/hermesMedia.spec.ts
  99. 0 63
      tests/e2e/model-confirmation.spec.ts
  100. 1 1
      tests/e2e/npmUpdate.spec.ts

+ 1 - 1
README.md

@@ -42,7 +42,7 @@ npm start
 
 Web 数据默认保存在 `~/.yaoyao`,可用 `YAOYAO_HOME` 指定(兼容 `HERMES_YAOYAO_HOME`)。旧默认目录 `~/.hermes-yaoyao` 会在服务空闲并停止后整体迁移至 `~/.yaoyao`,保留账号、会话、文件和密钥;两目录同时有数据时停止迁移,避免覆盖。备份应包含整个数据目录及加密密钥。
 
-由 Web 或 iOS 创建的普通聊天会按登录用户、Profile 和 Session ID 在 `chat-cache.sqlite3` 中登记所有权并持久化;后续续聊与列表展示以这份服务端登记为准,不再单独依赖 Hermes 的 `source` 标记。Web 的只读历史记录不进入该数据库,按需读取内置 Hermes 的会话库。可通过 `HERMES_YAOYAO_CHAT_CACHE_MODE=upstream-only|shadow|prefer-local` 切换策略,默认 `prefer-local`。
+夭夭只保留 Bot 模式:所有账号(包括管理员)都在「聊天」中通过 Bot 单聊和群聊使用 Hermes。原来的普通聊天、只读历史、文件库页面和 `chat-cache.sqlite3` 已删除,旧链接 `/chat`、`/history`、`/files` 会跳转到 `/conversations`;需要旧会话内容时,请在 Bot 中引用或重新发起。
 
 ## macOS 桌面版
 

+ 0 - 1
docker.env.example

@@ -18,7 +18,6 @@ HERMES_YAOYAO_PUBLISHED_PORT=15300
 # 可选:首次启动只读导入原有 Hermes 数据目录(包含 config.yaml),启动时额外加 -f compose.hermes-import.yaml。
 # Linux 示例:/srv/hermes-data;macOS 示例:/Users/你的用户名/.hermes。
 # HERMES_YAOYAO_HERMES_DIR=/srv/hermes-data
-HERMES_YAOYAO_CHAT_CACHE_MODE=prefer-local
 # 官方稳定发布源;自定义 Git 仓库可覆盖。容器仍由部署者重建升级。
 HERMES_YAOYAO_RELEASE_SOURCE=https://github.com/Lsamien/yaoyao.git
 # 首次登录后在 Web 系统设置 → 模型服务中配置模型。

+ 0 - 1
docs/docker-install.md

@@ -39,7 +39,6 @@ cp docker.env.example docker.env
 | `HERMES_YAOYAO_BIND_ADDRESS` | Web 的宿主机发布地址,默认 `127.0.0.1`;局域网访问可设为 `0.0.0.0` |
 | `HERMES_YAOYAO_PUBLISHED_PORT` | 宿主机 Web 端口,默认 `15300` |
 | `HERMES_YAOYAO_ALLOWED_HOSTS` | 使用域名访问时填写对应域名,多个值用英文逗号分隔 |
-| `HERMES_YAOYAO_CHAT_CACHE_MODE` | 普通聊天缓存策略,默认 `prefer-local` |
 
 内置 Hermes 的会话、Profile、模型配置和凭据都保存在 `yaoyao-data` 数据卷的 `hermes/` 目录;首次登录后在“系统设置 → 模型服务”中配置模型。
 

+ 27 - 0
docs/embedded-hermes-migration.md

@@ -230,3 +230,30 @@ yaovi-agent 在内置 Hermes 的同时还做了很多产品层改动,本方案
 - `npm run typecheck`、`npm run build` 通过;`npm run kernel:test` 25 个用例通过;内置网关与 Bot 端到端测试通过。
 - `npm test`:仍只有原有的 28 个环境相关失败(另有 1 个托管浏览器用例在全量并发时偶发失败,单独运行通过)。
 - 桌面测试结果与原提交一致。
+
+
+## 13. 只保留 Bot 模式(2026-11-16,`only-0.1` 分支)
+
+用户确认:原来的普通模式(直接与 Hermes Profile 对话)不再保留,所有账号只使用 Bot 模式。
+
+### 行为变化
+
+- 管理员与子账号使用同一套界面:「聊天」里的 Bot 单聊和群聊,以及工具菜单(电脑接管、自动化等)。设置中心默认打开「我的资料」,不再有模式切换。
+- 旧链接 `/`、`/chat/*`、`/history/*`、`/files`、`/artifacts` 及未知路径都跳转到 `/conversations`。
+- 未读只统计 Bot 会话;为兼容旧客户端,接口仍返回 `chat` 字段,固定为 0。
+- 账号扫码登录保留;设备配对(`/api/app/pairings*`、`/api/app/paired-devices*`、`/api/pair/v1/*`)删除。远程 Bot 已在此前停用,因此已有节点记录只能查看和删除,新的子节点配对会因对端没有配对接口而失败。
+- 不再写入 `chat-cache.sqlite3` 和 `realtime-receipts.sqlite3`;已有文件保留在数据目录中,可手动删除。`HERMES_YAOYAO_CHAT_CACHE_MODE` 已停用。
+
+### 删除的代码
+
+- 前端:普通聊天、历史、文件库页面及其 store、实时协议客户端、会话工具函数,`MessageTimeline.vue` 等仅普通模式使用的组件;Profile 显示名编辑接口改为只读的 `/api/profile-identities`。
+- 服务端:`/api/app/sessions*`、`/api/sessions/*`、`/api/realtime/*`、`/node/:deviceID/api/*` 和兜底转发 `/api/*`;聊天缓存、转录存储、实时代理/回执、普通聊天推送、Hermes 原生 Bot 中继、远程 Bot 导出。所有客户端 WebSocket 升级请求一律拒绝。
+- 测试:只覆盖普通模式的单元测试、Playwright 用例(`workspace.spec`、`ordinary-local`、`session-deletion`、`model-confirmation`、`hermesMedia`)和依赖 yaoyao-mobile 普通聊天的 `test:pair:mobile`;混合用例改为只验证 Bot 时间线。文档 `http-sse-realtime.md`、`ordinary-chat-incremental-sync.md`、`read-cache.md`、`hermes-bot-relay.md` 删除。
+
+### 验证
+
+- `npm run typecheck`、`npm run build` 通过。
+- `npm test`:仍是原有的 28 个环境相关失败(messageTime、credentialVault*、workspaceStopUi、serviceCli),无新增失败。
+- 内置内核多账号测试改为断言普通聊天接口对所有账号返回 403/404。
+- 用构建产物启动服务并在浏览器中创建管理员:旧链接全部跳转到 `/conversations`,页面无控制台错误,也没有 4xx 请求。
+- 剩余 Playwright 套件仍依赖旧的假 9119 夹具,本次只做了能被 `--list` 解析的修改,未实际运行。

+ 0 - 21
docs/hermes-bot-relay.md

@@ -1,21 +0,0 @@
-# Hermes Bot 原生转接
-
-Hermes Bot 使用 Hermes Desktop 的 Profile、机器人和群聊数据;与 Web 自建的 Bot 模式分开。手机不创建 Profile 或群聊,也不复制群聊到子节点。
-
-- 本地路径:手机 → 主服务器 15300 → 本机 Hermes Gateway。
-- 远程路径:手机 → 主服务器 15300 → 已配对的子节点 15300 → 子节点 Hermes Gateway。
-- `GET /api/app/hermes-bot/roster` 返回当前账号已配对子节点的原生名单及各节点错误。
-- `/api/app/hermes-bot/nodes/:id/api/...` 转接名单、历史、附件和 HTTP/SSE 聊天。主账号拥有节点记录;子节点凭据只保存在服务端。保留命令幂等键、事件游标;禁止跟随重定向。
-- 搜索类型为“机器人和群聊 / 仅机器人 / 仅群聊”,另有显示隐藏机器人的开关;置顶和隐藏保留原生语义。
-- 群聊支持新帖子、讨论串切换、回复、分享。未发送的新帖子没有记录;选择按账号和群聊保存。成员配置只读,仅解析已确认的连接身份。
-- 同步只更新主节点已有群聊的消息及讨论串,保留名称、成员、头像等原生配置。不存在或已删除的群聊拒绝写入;不会通过裁剪清除其他群聊配置。
-
-旧版仅保存在手机上的子节点需在主服务器重新扫码授权。保留旧记录,不上传手机中的长期凭据。已经添加到主服务器的扫码节点可直接使用;子节点需支持现有配对及 HTTP/SSE 协议。
-
-验证:`hermesBotRelay.test.ts`、`workspacePairedNodes.test.ts`、`workspaceRemoteAgents.test.ts`、`workspaceRoutes.test.ts`;iOS 的 Bots、BotGroupRuntime、BotGatewayConnectionPool、WorkspaceChat 测试及原生名单、新帖子、只读成员界面测试。远程协议使用受控子节点夹具验证,未以用户真实远程机器人发送消息。
-
-## 已有原生会话的恢复授权
-
-本地机器人使用 `/api/app/hermes-bot/local/api/...`;远程单聊使用 `/api/app/hermes-bot/nodes/:id/native/api/...`,主服务转到子节点 `/node/:device/api/hermes-bot/api/...`。普通节点请求继续走原路径,保持群聊工作会话的授权语义。
-
-原生通道拥有独立身份。恢复前由服务端通过原生 `profiles.list` 读取 Profile 的 `ui_meta.hermes-bots.chat`,只允许恢复该绑定会话。REST `/api/profiles` 不包含这份元数据,不能用于这一授权判断。普通聊天的原生历史仍然只读;原生通道不会把旧聊天导入普通 Web 聊天的所有权记录。

+ 0 - 47
docs/http-sse-realtime.md

@@ -1,47 +0,0 @@
-# HTTP + SSE realtime bridge
-
-15300 remains the only client entrypoint. It owns authenticated upstream WebSocket connections to 9119; it does not run a second Agent engine or move Python group data.
-
-## Contract (version 1)
-
-All endpoints are relative to `/api/realtime` (also supported beneath an authorized `/node/:deviceID` base URL).
-
-| Method | Path | Behavior |
-| --- | --- | --- |
-| GET | `/capabilities` | `protocolVersion`, `channels`, `brokerEpoch`; Cookie callers also receive a CSRF token. |
-| POST | `/channels` | `{channel:"chat"}` or `{channel:"groups",epoch,cursor}`; returns `{id,brokerEpoch}`. |
-| GET | `/channels/:id/events` | SSE `ready`, `frame`, `reset`; `frame.data` is the existing RPC/group envelope. |
-| POST | `/channels/:id/commands` | Whitelisted RPC `{method,params}` plus a stable `Idempotency-Key`. |
-| GET | `/commands/:requestId` | Auth-scoped command receipt. |
-| DELETE | `/channels/:id` | Detach the subscriber; does not stop a running Agent. |
-
-Cookie mutations require Origin and X-CSRF-Token. Paired Bearer callers retain their device scopes. SSE credentials are headers/Cookies, never long-lived query credentials. Each channel belongs to its authenticated principal; opening a session explicitly registers that route. Existing shared-history access is unchanged, but events are not broadcast to unrelated subscribers.
-
-Chat frames retain their upstream seq separately from the opaque SSE `id`. Send `Last-Event-ID` only to the same channel. `409 reset_required`, SSE `reset`, or a missing channel requires session resume and authoritative REST history reconciliation. A mere downstream network interruption reconnects the same channel without rebuilding runtimes. Group envelopes retain their original epoch/cursor validation.
-
-## Receipts and failure semantics
-
-`state` is `confirmed`, `rejected`, `pending`, or `unknown`. Only an actual upstream RPC acknowledgement is confirmed; receiving HTTP 200 alone is not a submission acknowledgement. Identical keys reuse the original operation; different payloads under one key conflict. Network retry must retain the key and original encoded command, not rerun attachment preparation. The iOS Outbox ID is the prompt key.
-
-`realtime-receipts.sqlite3` records write-ahead fingerprints and bounded recovery metadata, not prompts, attachment bytes, transcript content or full event streams. Allowed attachment commands retain their file references; allowed configuration commands retain their applied value and model confirmation metadata. Terminal results retain 24 hours, then compact into permanent owner/request/fingerprint tombstones that return `unknown`. Compaction never makes an admitted request executable again, including after a restart; changed payloads still conflict. Tombstones contain no command bodies or RPC results and grow with unique retired admissions. Pending operations become unknown on process restart. Unknown receipts are never automatically re-executed or evicted to permit retries; capacity exhaustion rejects new admissions. Full RPC results have a separate bounded in-memory cache, so clients must refresh resource data rather than assume a history snapshot was persisted.
-
-Clients must persist each stable command ID as attempted **before** its POST. An absent receipt is permission to submit only when a durable local record proves that command was never attempted. For an attempted or legacy uncertain prompt, reconcile the exact `client_message_id` against the canonical transcript; absence from a recent page is not proof of non-execution. Keep unresolved sends uncertain, and never submit an attachment label without a recovered file reference.
-
-## Resource limits and HTTP-only clients
-
-- Recent events: 10 minutes, 8 MiB or 10,000 events per principal, 128 MiB globally.
-- At most 8 live subscribers per principal. Up to 32 detached/reconnectable handles; oldest detached handles may be evicted under pressure and then require REST recovery.
-- Slow output: 1 MiB backlog / 15 seconds; detach only the slow downstream.
-- Idle upstreams close after five minutes with no channels, work or pending commands. Running/waiting Agent sessions are retained.
-- Dedicated RPC parser retains 36 MiB frame / 25 MiB attachment bounds. The global JSON parser remains 2 MiB.
-- Old client WS endpoints, WS tickets and realtime leases are removed. Requests receive `410 http_sse_required`; only server-to-9119 WebSockets remain. HTTP RPC mutations use CSRF or paired Bearer authorization.
-- Ordinary chat push recovery uses broker transports. Group push retains its independent durable journal cursor.
-- Different credential scopes are not silently pooled. If they target the same already-owned runtime, the bridge fails closed with `session_scope_conflict` instead of stealing its upstream event receiver.
-
-This does not guarantee Agent survival after 15300/9119 restarts or prolonged upstream loss. Upstream recovery uses `session.events.since` when available; missing/truncated replay falls back to REST history, not to an old client transport. Web and shipping iOS clients require HTTP+SSE capability version 1. Missing capabilities, authentication errors and network errors never downgrade to WebSocket.
-
-## Verification
-
-Run `npm run typecheck`, `npm test`, `npm run build`, and `npx playwright test`. Realtime tests cover shared ownership, route isolation, CSRF, durable unknown receipts, reply loss, replay, cache pressure and a real 21-second downstream outage. Fixture latency samples are not model inference benchmarks.
-
-The iOS `HTTPRealtimeAcceptanceUITests` is opt-in (`HERMES_SSE_ACCEPTANCE=1` in the test runner environment). Start the isolated 19119 fake Hermes and 18801 e2e server and initialize the fixture admin password as in Playwright before running it. It uses an ephemeral cookie jar, not saved user accounts.

+ 0 - 32
docs/ordinary-chat-incremental-sync.md

@@ -1,32 +0,0 @@
-# 普通聊天按需读取与增量同步
-
-范围为应用登记的普通聊天。独立的只读历史入口继续走原来的上游读取链路。
-
-- 已持久化的列表和详情从 SQLite 生成。旧版本或新建会话缺少摘要时,才补齐摘要;换分页参数不再使已知列表回源。
-- 消息页按实际位置覆盖范围读取,本地只存了尾部也可以命中该页,不必先下载完整会话。新回合不清除已经保存的历史覆盖信息。
-- 回复完成或实时事件出现缺口时,校对当前会话的详情及最新消息,每页 100 条,遇到已保存的稳定位置即停止。按消息 ID 和内容摘要更新,未变化的消息不重写。
-- 同一会话合并并发同步。读取期间收到新事件时,旧结果不能覆盖新修订;同步提交后发送账号隔离的失效通知,客户端再按需读取。
-- 已缓存的旧页不等待后台同步。最新页可以等待正在提交的尾部;同步失败仍返回已有本地内容。
-- 普通页面刷新不绕过本地缓存。会话操作中的“强制刷新历史”才使用 `X-Yaoyao-Cache: bypass`,完整校对并替换历史。下载失败或分页期间消息总数变化时,不替换已有记录。
-- 旧消息删除、重排等改变历史位置的情况保留本地内容,等待明确强制刷新,不把它当作普通尾部追加。
-- 模型变化继续由实时事件和进入页面时的必要校验处理,取消每 3 秒无条件读取会话详情。
-
-## 用户消息身份
-
-- `chat_message_identities` 按账号、Profile 和会话保存正式消息 ID 与 `client_message_id` 的一对一关联;强制刷新、重启后继续保留,会话压缩迁移和删除时同步处理。
-- 上游携带客户端 ID 时直接保留。旧版上游缺少 ID 时,仅在历史覆盖完整后,结合已确认的提交回执、运行开始时间、下一次提交边界和完整文本寻找唯一对应记录;未确认、被拒绝、排队或对应关系不唯一时不猜测。该兼容路径要求上游时间落在本地记录的提交窗口内。
-- 已有缓存缺失 ID 时,在本地消息读取中恢复关联,无需额外请求上游。前端通过正式 ID 与客户端 ID 合并已有气泡;迟到的发送回执不能覆盖正式消息状态。相同文字的多次独立提交始终保留。
-
-## 验证
-
-工具生命周期同时覆盖实时事件、持久化投影、历史恢复与各端展示:无调用 ID 的 `tool.generating` 只是进度通知;真实调用按工具 ID 合并。回合结束后,缺少完成回执的工具显示结果未确认,失败结果(包括非零退出码)保留失败。历史快照通过用户消息身份替换已完成回合的临时投影,并保护仍在执行、其后已有排队输入的回合。
-
-真实受影响会话的副本回放中,13 条重复累计的工具显示恢复为 5 次实际调用,残留运行状态为 0。文件目录规则见 [服务端文件访问权限](file-access.md)。
-
-- 1,000 条已缓存消息,20 次历史分页读取不请求上游。
-- 新增回复只读取一页尾部;漏掉 130 条消息只补两页;原有消息不重新写入。
-- 明确强制刷新才覆盖旧编辑和删除;失败时保留旧记录;并发完成事件提交后再通知客户端。
-- 浏览器验证普通重载命中本地、强制刷新回源,以及只读历史和普通聊天的边界。
-- 用户消息回归覆盖历史与回执乱序、已有重复缓存、连续相同文本、跨页歧义、重启及强制刷新后的身份保留。
-
-这些请求数来自隔离测试,并非对真实网络耗时的估计。

+ 0 - 40
docs/read-cache.md

@@ -1,40 +0,0 @@
-# 15300 热点读取缓存
-
-15300 包含两层读取能力:进程内热点缓存,以及仅面向 `source=web` 普通聊天的持久化投影。它们不改变模型生成速度,也不替代 iOS 本地缓存。
-
-## 持久化普通聊天
-
-`chat-cache.sqlite3` 保存 Web/iOS 创建的普通聊天会话、消息、事件游标和附件索引;`chat-cache-assets` 保存已读取的媒体文件。完整同步的会话优先从本地返回,缓存缺失、事件变更或同步断档时才访问 9119。Web 只读历史记录不写入这两个位置,保持现有按需读取和短时内存缓存。
-
-`HERMES_YAOYAO_CHAT_CACHE_MODE` 支持 `upstream-only`、`shadow` 和 `prefer-local`,默认 `prefer-local`。本地数据库不可用时服务退回上游读取;发送、停止、审批、澄清和分支始终需要 9119 确认。
-
-## 上游认证租期
-
-`UpstreamServiceSession` 将成功的状态/身份检查复用 30 秒,并合并同一时间的并发检查。每个客户端请求仍执行 15300 的用户、角色或配对设备授权。
-
-上游返回 401 时仅对该请求重新认证并重试一次;并发 401 共用登录任务。不会因为网络超时或 5xx 自动重放写请求。服务账号配置变化会立即使租期及读取缓存失效;旧验证或登录响应不能覆盖新凭据。鉴权端点本身不进入读取缓存。
-
-## 读取策略
-
-| 数据 | 新鲜期 | 后台刷新宽限 |
-| --- | --- | --- |
-| Profile/身份列表 | 5 秒 | 15 秒 |
-| 模型选项 | 30 秒 | 60 秒 |
-| 非持久化会话列表、团队/话题列表 | 2 秒 | 无 |
-| 非持久化会话详情、最近消息、团队详情 | 1 秒 | 无 |
-| 已加载的较早消息页 | 10 秒 | 无 |
-
-仅缓存白名单 GET 的成功 JSON。容量上限为 64 MiB / 512 项,每项不超过 2 MiB,使用 LRU 淘汰;相同读取会合并。缓存键包含已验证的 15300 用户/授权版本或配对设备、上游 Cookie 的摘要、Profile、分页参数和请求头。缓存键不记录原始凭据。
-
-后台推送确认、命令回执、鉴权、搜索、未读确认、团队游标能力端点、增量 `afterSeq`、Range/条件读取以及错误响应不缓存。上游显式 `no-store` 或 `Set-Cookie` 响应不缓存。
-
-这是服务端应用数据缓存,而不是浏览器 HTTP 缓存。浏览器仍可保持 `cache: no-store`。客户端需要强制最新数据时可发送 `X-Yaoyao-Cache: bypass`;内部调用可指定 `cache: 'reload'`。
-
-## 一致性边界
-
-- HTTP 写入前后失效相应资源;聊天命令和实时事件在投递给客户端之前失效对应会话缓存。
-- 团队事件失效房间与列表缓存;获取新的团队 journal cursor 后清除较早的团队快照,保留 snapshot-after-anchor 顺序。
-- 断线重置会清除相关缓存。刷新期间发生失效时,较早响应不会重新填回缓存,后续请求不会加入过时的在途读取。
-- 缓存只负责读取;发送、停止、审批必须等待真实上游确认。没有事件通知的外部修改仍受上述短 TTL 约束,不能声称跨所有外部写入的强一致。
-
-`UpstreamClient.readCache.stats()` 提供进程内命中、未命中、合并、淘汰、内存及在途数量,用于测试和诊断,不公开缓存内容。

+ 0 - 1
package.json

@@ -24,7 +24,6 @@
     "brand:verify": "node scripts/verify-brand.mjs",
     "release:verify": "node scripts/verify-release.mjs",
     "verify:lifecycle": "node scripts/verify-lifecycle.mjs",
-    "test:pair:mobile": "node --import tsx --test scripts/verify-mobile-pair.test.ts",
     "test:e2e:workspace": "npm run build && playwright test -c playwright.workspace.config.ts",
     "test:e2e:desktop-hosts": "npm run build && playwright test -c playwright.desktop-hosts.config.ts",
     "test:e2e:team-tools": "npm run build && playwright test -c playwright.team-tools.config.ts",

+ 0 - 131
scripts/verify-mobile-pair.test.ts

@@ -1,131 +0,0 @@
-/** Optional two-checkout acceptance: real mobile core + real BFF over local HTTP.
- * Hermes is a deterministic loopback fixture. No production service is used. */
-import test from 'node:test'
-import assert from 'node:assert/strict'
-import { createServer, type Server } from 'node:http'
-import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
-import { pathToFileURL } from 'node:url'
-import { randomUUID } from 'node:crypto'
-import { DatabaseSync } from 'node:sqlite'
-import { WebSocketServer } from 'ws'
-import { createApplication, type ApplicationRuntime } from '../src/server/app.js'
-import type { ServerConfig } from '../src/server/config.js'
-
-const root = resolve(import.meta.dirname, '..')
-const mobile = resolve(process.env.YAOYAO_MOBILE_CHECKOUT ?? join(root, '../yaoyao-mobile'))
-const { YaoyaoAPI } = await import(pathToFileURL(join(mobile, 'apps/mobile/src/core/api.ts')).href)
-const { OrdinaryStore } = await import(pathToFileURL(join(mobile, 'apps/mobile/src/core/ordinary.ts')).href)
-const { createOrdinaryCache } = await import(pathToFileURL(join(mobile, 'apps/mobile/src/core/ordinary-cache.ts')).href)
-const listen = (server: Server, port = 0) => new Promise<string>(done => server.listen(port, '127.0.0.1', () => done(`http://127.0.0.1:${(server.address() as { port: number }).port}`)))
-const close = (server: Server) => new Promise<void>(done => { server.close(() => done()); server.closeAllConnections() })
-function sqlite(db: DatabaseSync) {
-  return { async execAsync(sql: string) { db.exec(sql) }, async runAsync(sql: string, ...args: any[]) { return db.prepare(sql).run(...args) },
-    async getFirstAsync(sql: string, ...args: any[]) { return db.prepare(sql).get(...args) ?? null }, async getAllAsync(sql: string, ...args: any[]) { return db.prepare(sql).all(...args) } }
-}
-
-test('mobile 1.5 core recovers durable attachments across BFF restart, never repeats admission, and loses its transcript stream on logout', { timeout: 45000 }, async () => {
-  const home = mkdtempSync(join(tmpdir(), 'yaoyao-mobile-pair-')), cookies = new Map<string, string>()
-  const commands: Array<{ method: string; params: any }> = []
-  let runtime: ApplicationRuntime | undefined, web: Server | undefined, store: any, api: any, db: DatabaseSync | undefined
-  let attached = false, simulateDisconnect = true
-  const hermes = createServer((req, res) => {
-    res.setHeader('Content-Type', 'application/json')
-    const path = req.url?.split('?')[0]
-    res.end(JSON.stringify(path === '/api/status' ? { auth_required: true, dashboard_running: true }
-      : path === '/api/auth/ws-ticket' ? { ticket: 'fixture' }
-      : path === '/api/profiles' ? { profiles: [{ name: 'default', is_default: true }] }
-      : path?.endsWith('/messages') ? { messages: [], pagination: { total: 0, returned: 0 } }
-      : path === '/api/sessions' || path === '/api/profiles/sessions' ? { sessions: [] }
-      : path === '/api/config' ? { config: { terminal: { cwd: '' } } } : { ok: true }))
-  })
-  const upstream = await listen(hermes), ws = new WebSocketServer({ server: hermes })
-  ws.on('connection', socket => {
-    socket.send(JSON.stringify({ method: 'event', params: { type: 'gateway.ready', payload: { replay_epoch: 'fixture' } } }))
-    socket.on('message', raw => {
-      const f = JSON.parse(String(raw)); commands.push(f)
-      const result = ['session.create', 'session.resume'].includes(f.method) ? { session_id: 'runtime-fixture', stored_session_id: 'stored-fixture', running: false, info: { profile_name: 'default' } }
-        : f.method === 'file.attach' ? { ref_text: '@file:/fixture/upload.txt', path: '/fixture/upload.txt' }
-        : f.method === 'session.events.since' ? { epoch: 'fixture', events: [] }
-        : f.method === 'session.active_list' ? { sessions: [{ id: 'runtime-fixture', status: 'idle' }] } : { status: 'accepted', ok: true }
-      socket.send(JSON.stringify({ id: f.id, result }))
-    })
-  })
-  for (const folder of ['media', 'attachments', 'images']) mkdirSync(join(home, folder))
-  const config: ServerConfig = { home, host: '127.0.0.1', port: 0, upstream: new URL(upstream), allowedHosts: new Set(),
-    mediaRoot: join(home, 'media'), attachmentsRoot: join(home, 'attachments'), imagesRoot: join(home, 'images'), mediaOwner: 'fixture',
-    production: true, allowInsecureLan: false, insecureLan: false, superviseDashboard: false, localVmHost: 'runner' }
-  const fetcher = async (url: string, options?: RequestInit) => {
-    const headers = new Headers(options?.headers)
-    // This Node fixture has no native Cookie/URLSession jar. Avoid reusing its
-    // global fetch pool across a deliberately destroyed/rebound test listener.
-    headers.set('Connection', 'close')
-    headers.set('Cookie', [...cookies].map(([k, v]) => `${k}=${v}`).join('; '))
-    if (attached && simulateDisconnect && decodeURIComponent(new URL(url).pathname).startsWith('/api/realtime/commands/ios:prompt:')) {
-      simulateDisconnect = false; throw new Error('Fixture disconnect before prompt admission')
-    }
-    const response = await fetch(url, { ...options, headers })
-    for (const cookie of response.headers.getSetCookie()) {
-      const pair = cookie.split(';')[0]!, at = pair.indexOf('='); cookies.set(pair.slice(0, at), pair.slice(at + 1))
-    }
-    if (options?.method === 'POST' && new URL(url).pathname.endsWith('/commands') && JSON.parse(String(options.body)).method === 'file.attach' && response.ok) attached = true
-    return response
-  }
-  const openCache = async () => {
-    db = new DatabaseSync(join(home, 'mobile.sqlite3'))
-    db.exec('CREATE TABLE IF NOT EXISTS account_documents(scope TEXT PRIMARY KEY,payload TEXT NOT NULL)')
-    return createOrdinaryCache(sqlite(db))
-  }
-  try {
-    runtime = createApplication({ config, deferBackground: true }); web = createServer(runtime.app.callback())
-    const origin = await listen(web); config.port = Number(new URL(origin).port)
-    api = new YaoyaoAPI(origin, fetcher); await api.bootstrap()
-    const setup = await api.request('/api/app/setup', 'POST', { username: 'pair-fixture', password: 'pair-fixture-password' })
-    api.csrf = setup.csrfToken
-    const owner = setup.user.id
-    assert.ok((await api.request('/api/realtime/capabilities')).features.includes('ordinary-chat-transcript-v2'))
-    store = new OrdinaryStore(api, await openCache(), 'pair-account', randomUUID, async () => 'Zml4dHVyZQ==')
-    await store.start(); await store.newSession('default')
-    await store.setAttachments([{ id: 'file', name: 'fixture.txt', mimeType: 'text/plain', uri: 'file:///fixture.txt' }])
-    await store.send('paired attachment')
-    const pending = store.getSnapshot().data.pending[0]
-    assert.ok(pending, 'the interrupted send must remain in the durable mobile cache')
-    assert.ok(pending.attemptedCommands.includes(`ios:attachment:${pending.id}:file`), JSON.stringify({ state: pending.state, error: pending.error, attempted: pending.attemptedCommands, methods: commands.map(f => f.method) }))
-    assert.ok(!pending.attemptedCommands.includes(`ios:prompt:${pending.id}`))
-    assert.equal(commands.filter(f => f.method === 'file.attach').length, 1)
-    assert.equal(commands.filter(f => f.method === 'prompt.submit').length, 0)
-    await store.close(); await api.close(); db!.close(); db = undefined
-    runtime.close(); runtime = undefined; await close(web); web = undefined
-    runtime = createApplication({ config, deferBackground: true }); web = createServer(runtime.app.callback()); await listen(web, config.port)
-    api = new YaoyaoAPI(origin, fetcher); await api.bootstrap()
-    store = new OrdinaryStore(api, await openCache(), 'pair-account', randomUUID, async () => 'Zml4dHVyZQ==')
-    await store.start(); await store.retry(pending.id); await store.retry(pending.id)
-    assert.equal(commands.filter(f => f.method === 'file.attach').length, 1, 'restart must reuse the persisted attachment reference')
-    const prompts = commands.filter(f => f.method === 'prompt.submit')
-    assert.equal(prompts.length, 1, JSON.stringify({ expectation: 'retry must execute the never-admitted prompt once', pending: store.getSnapshot().data.pending.map((p: any) => ({ state: p.state, error: p.error, attempted: p.attemptedCommands })), methods: commands.map(f => f.method) }))
-    assert.match(prompts[0]!.params.text, /@file:\/fixture\/upload\.txt/)
-    const snapshot = await api.request('/api/app/chat/sessions/stored-fixture/snapshot?profile=default')
-    assert.equal(snapshot.protocol, 'ordinary-chat-transcript-v2')
-    assert.ok(snapshot.messages.some((m: any) => m.client_message_id === pending.id))
-    let ready!: () => void
-    const opened = new Promise<void>(done => { ready = done }), frames: any[] = []
-    const stream = api.events('/api/app/chat/sessions/stored-fixture/events?profile=default', `${snapshot.epoch}:${snapshot.cursor}`, async (frame: any) => {
-      frames.push(frame); if (frame.event === 'ready') ready()
-    }).catch((error: Error) => error)
-    await opened
-    await api.request('/api/app/logout', 'POST', {})
-    runtime.chatCache!.store.recordCommand(owner, 'default', 'stored-fixture', 'prompt.submit', { text: 'must-not-leak-after-logout', _delivery_id: 'late-fixture' })
-    let timeout: ReturnType<typeof setTimeout> | undefined
-    try { await Promise.race([stream, new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Logged-out transcript stream did not close')), 1500) })]) }
-    finally { clearTimeout(timeout) }
-    assert.ok(!JSON.stringify(frames).includes('must-not-leak-after-logout'))
-    console.log('PAIR_OK: transcript-v2 handshake; real HTTP/SSE; SQLite reopen; BFF restart; attachment once; prompt once; canonical echo; logout closes stream')
-  } finally {
-    await store?.close().catch(() => {}); await api?.close().catch(() => {}); db?.close(); runtime?.close()
-    if (web) await close(web)
-    for (const socket of ws.clients) socket.terminate()
-    await new Promise<void>(done => ws.close(() => done())); await close(hermes)
-    rmSync(home, { recursive: true, force: true })
-  }
-})

+ 4 - 11
src/client/App.vue

@@ -6,7 +6,6 @@ import LoginView from '@/views/LoginView.vue'
 import PasswordChangeView from '@/views/PasswordChangeView.vue'
 import { useUnreadStore } from '@/stores/unread'
 import { useAuthStore } from '@/stores/auth'
-import { useChatStore } from '@/stores/chat'
 import { useThemeStore } from '@/stores/theme'
 import AgentIdentityFixture from '@/components/app/AgentIdentityFixture.vue'
 
@@ -16,25 +15,19 @@ watch(()=>auth.isAuthenticated ? `${auth.serverIdentity?.serverId ?? location.or
  if(auth.isAuthenticated&&auth.user)unread.start(auth.user.id)
  else { unread.reset();void window.yaoyaoDesktop?.unreadState?.(null).catch(()=>{}) }
 },{immediate:true})
-const chat = useChatStore()
 const theme = useThemeStore()
 const route = useRoute()
 const router = useRouter()
-const allowedRoute = computed(() => !auth.isBotOnly || /^\/conversations(?:\/|$)/.test(route.path))
-watch([() => auth.isBotOnly, () => route.path], () => {
+// Bot mode is the only interface for every account.
+const allowedRoute = computed(() => /^\/conversations(?:\/|$)/.test(route.path))
+watch(() => route.path, () => {
   if (!allowedRoute.value) void router.replace('/conversations')
 }, { immediate: true, flush: 'sync' })
 const agentIdentityFixture = import.meta.env.DEV
   && new URLSearchParams(window.location.search).get('fixture') === 'agent-identity'
 
 const pageTitle = computed(() => {
-  const name = route.name === 'computer' ? '电脑接管' : route.name === 'bot-automations' ? '自动化' : route.path.startsWith('/history')
-    ? '历史记录'
-    : route.path.startsWith('/conversations')
-    ? '聊天'
-    : route.path.startsWith('/files')
-      ? '文件库'
-      : chat.activeSession?.title || '对话'
+  const name = route.name === 'computer' ? '电脑接管' : route.name === 'bot-automations' ? '自动化' : '聊天'
   return `${name} · 夭夭 AI`
 })
 

+ 0 - 284
src/client/api/chatTranscript.ts

@@ -1,284 +0,0 @@
-import { apiRequest } from './client'
-import { SSEParser } from '@shared/sse'
-import {
-  applyTranscriptEvent,
-  CHAT_TRANSCRIPT_FEATURE,
-  TranscriptGap,
-  type TranscriptEvent,
-  type TranscriptControlEvent,
-  type TranscriptMessage,
-  type TranscriptSnapshot,
-} from '@shared/chatTranscript'
-
-/** Serial, durable replica: no state/cursor becomes visible before changed commits it. */
-export class ChatTranscriptClient {
-  private abort = new AbortController()
-  private snapshot?: TranscriptSnapshot
-  private fetchingOlder = false
-  private operations: Promise<unknown> = Promise.resolve()
-  private request?: AbortController
-  private readonly foreground = () => {
-    if (document.visibilityState === 'visible') this.request?.abort()
-  }
-  constructor(
-    readonly profile: string,
-    readonly sessionId: string,
-    readonly changed: (snapshot: TranscriptSnapshot) => Promise<void>,
-    readonly failed: (error: Error) => void,
-    readonly initialCount = 150,
-  ) {
-    if (typeof document !== 'undefined') document.addEventListener('visibilitychange', this.foreground)
-  }
-  static async supported(): Promise<boolean> {
-    return (await apiRequest<{ features: string[] }>('/api/app/chat/capabilities')).features.includes(
-      CHAT_TRANSCRIPT_FEATURE,
-    )
-  }
-  close() {
-    this.abort.abort()
-    this.request?.abort()
-    if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', this.foreground)
-  }
-  restore(value: TranscriptSnapshot) {
-    if (
-      value.protocol === CHAT_TRANSCRIPT_FEATURE &&
-      value.profile === this.profile &&
-      value.sessionId === this.sessionId
-    )
-      this.snapshot = value
-  }
-  private serial<T>(operation: () => Promise<T>): Promise<T> {
-    const task = this.operations.then(operation, operation)
-    this.operations = task.catch(() => {})
-    return task
-  }
-  private path(suffix: string, query: Record<string, string> = {}) {
-    return `/api/app/chat/sessions/${encodeURIComponent(this.sessionId)}/${suffix}?${new URLSearchParams({ profile: this.profile, ...query })}`
-  }
-  private async page(before?: number): Promise<TranscriptSnapshot> {
-    const value = await apiRequest<TranscriptSnapshot>(
-      this.path('snapshot', { limit: '150', ...(before === undefined ? {} : { before: String(before) }) }),
-      { signal: this.abort.signal },
-    )
-    if (
-      value.protocol !== CHAT_TRANSCRIPT_FEATURE ||
-      value.profile !== this.profile ||
-      value.sessionId !== this.sessionId
-    )
-      throw new TranscriptGap()
-    return value
-  }
-  private async commit(value: TranscriptSnapshot) {
-    if (this.abort.signal.aborted) return
-    await this.changed(value)
-    if (!this.abort.signal.aborted) this.snapshot = value
-  }
-  private merge(current: TranscriptSnapshot, page: TranscriptSnapshot): TranscriptMessage[] {
-    const deleted = new Set([...(current.deletedIds ?? []), ...(page.deletedIds ?? [])])
-    const messages = new Map(current.messages.filter((m) => !deleted.has(m.id)).map((m) => [m.id, m]))
-    for (const message of page.messages)
-      if (!deleted.has(message.id) && (messages.get(message.id)?.revision ?? 0) < message.revision)
-        messages.set(message.id, message)
-    return [...messages.values()].sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))
-  }
-  private async hydrate() {
-    let value = await this.page()
-    if (this.abort.signal.aborted) return
-    while (value.messages.length < this.initialCount && value.hasOlder && value.messages.length) {
-      const older = await this.page(value.messages[0]!.seq)
-      if (older.epoch !== value.epoch) throw new TranscriptGap()
-      const messages = this.merge(value, older),
-        added = messages.length - value.messages.length
-      value = {
-        ...value,
-        messages,
-        hasOlder: older.hasOlder,
-        deletedIds: [...new Set([...(value.deletedIds ?? []), ...(older.deletedIds ?? [])])],
-      }
-      if (!added) break
-    }
-    await this.serial(async () => {
-      const old = this.snapshot
-      if (old?.epoch === value.epoch && old.cursor > value.cursor) return
-      // An authoritative generation replaces the covered window. Older loaded
-      // pages can be retained only inside the same epoch and outside that window.
-      if (old?.epoch === value.epoch && value.messages.length) {
-        const first = value.messages[0]!.seq
-        value = {
-          ...value,
-          messages: this.merge({ ...old, messages: old.messages.filter((m) => m.seq < first) }, value),
-        }
-      }
-      await this.commit(value)
-    })
-  }
-  async loadOlder() {
-    const starting = this.snapshot
-    if (this.fetchingOlder || !starting?.hasOlder || !starting.messages.length) return
-    this.fetchingOlder = true
-    try {
-      const page = await this.page(starting.messages[0]!.seq)
-      await this.serial(async () => {
-        const current = this.snapshot
-        if (!current || page.epoch !== current.epoch) return
-        await this.commit({
-          ...current,
-          messages: this.merge(current, page),
-          hasOlder: page.hasOlder,
-          deletedIds: [...new Set([...(current.deletedIds ?? []), ...(page.deletedIds ?? [])])],
-        })
-      })
-    } finally {
-      this.fetchingOlder = false
-    }
-  }
-  private async receive(event: TranscriptEvent) {
-    await this.serial(async () => {
-      const current = this.snapshot
-      if (!current) throw new TranscriptGap()
-      if (
-        event.profile !== this.profile ||
-        event.sessionId !== this.sessionId ||
-        event.epoch !== current.epoch ||
-        !Number.isSafeInteger(event.cursor)
-      )
-        throw new TranscriptGap()
-      if (event.cursor <= current.cursor) return
-      if (
-        event.previousCursor !== current.cursor ||
-        event.type === 'session.deleted' ||
-        event.type === 'session.migrated'
-      )
-        throw new TranscriptGap()
-      const data = event.data as Record<string, any>,
-        deleted = new Set(current.deletedIds ?? [])
-      if (event.type === 'message.deleted') deleted.add(String(data.id))
-      const before = current.messages[0]?.seq
-      const unloaded =
-        ['message.patch', 'message.upsert'].includes(event.type) &&
-        typeof data.seq === 'number' &&
-        before !== undefined &&
-        data.seq < before
-      const messages =
-        unloaded || (event.type !== 'message.deleted' && deleted.has(String(data.id)))
-          ? current.messages
-          : applyTranscriptEvent(current.messages, event)
-      const next: TranscriptSnapshot = {
-        ...current,
-        messages,
-        cursor: event.cursor,
-        deletedIds: [...deleted],
-        total: event.total ?? current.total,
-      }
-      if (event.type === 'session.changed') {
-        for (const key of [
-          'running',
-          'queued',
-          'pendingApproval',
-          'pendingClarification',
-          'liveStatus',
-          'error',
-        ] as const)
-          if (data[key] !== undefined) (next as any)[key] = data[key]
-        if (data.eventType === 'session.info' && data.payload)
-          next.session = { ...next.session, ...data.payload }
-      }
-      await this.commit(next)
-    })
-  }
-  private async control(input: unknown) {
-    const value = input as Partial<TranscriptControlEvent>
-    const cursor = value.cursor
-    await this.serial(async () => {
-      const current = this.snapshot
-      if (
-        !current ||
-        value.epoch !== current.epoch ||
-        typeof cursor !== 'number' ||
-        !Number.isSafeInteger(cursor) ||
-        typeof value.running !== 'boolean' ||
-        typeof value.queued !== 'boolean'
-      ) throw new TranscriptGap()
-      if (cursor < current.cursor) return
-      if (cursor > current.cursor) throw new TranscriptGap()
-      await this.commit({
-        ...current,
-        running: value.running,
-        queued: value.queued,
-        pendingApproval: value.pendingApproval ?? null,
-        pendingClarification: value.pendingClarification ?? null,
-        liveStatus: value.liveStatus ?? null,
-        error: value.error ?? null,
-      })
-    })
-  }
-  async run() {
-    let needsSnapshot = !this.snapshot
-    let restorePending = Boolean(this.snapshot)
-    while (!this.abort.signal.aborted) {
-      let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
-      let watchdog: ReturnType<typeof setTimeout> | undefined
-      try {
-        if (restorePending) {
-          const saved = this.snapshot!
-          await this.serial(() => this.commit(saved))
-          restorePending = false
-        }
-        if (needsSnapshot) {
-          await this.hydrate()
-          needsSnapshot = false
-        }
-        if (this.abort.signal.aborted) return
-        const current = this.snapshot
-        if (!current) return
-        const attempt = new AbortController()
-        this.request = attempt
-        watchdog = setTimeout(() => attempt.abort(), 45_000)
-        const response = await fetch(this.path('events'), {
-          headers: { Accept: 'text/event-stream', 'Last-Event-ID': `${current.epoch}:${current.cursor}` },
-          credentials: 'include',
-          cache: 'no-store',
-          signal: attempt.signal,
-        })
-        if (response.status === 409) throw new TranscriptGap()
-        if (!response.ok || !response.body) throw new Error(`聊天消息流 HTTP ${response.status}`)
-        const parser = new SSEParser(),
-          decoder = new TextDecoder()
-        reader = response.body.getReader()
-        while (!this.abort.signal.aborted) {
-          clearTimeout(watchdog)
-          watchdog = setTimeout(() => attempt.abort(), 45_000)
-          const { value, done } = await reader.read()
-          if (done) break
-          for (const frame of parser.feed(decoder.decode(value, { stream: true }))) {
-            if (frame.event === 'reset') throw new TranscriptGap()
-            if (frame.event === 'ready' || frame.event === 'state') {
-              await this.control(JSON.parse(frame.data))
-              continue
-            }
-            if (frame.event === 'transcript') await this.receive(JSON.parse(frame.data))
-          }
-        }
-      } catch (error) {
-        if (this.abort.signal.aborted) return
-        if (error instanceof TranscriptGap) needsSnapshot = true
-        this.failed(error instanceof Error ? error : new Error('聊天消息需要同步'))
-      } finally {
-        clearTimeout(watchdog)
-        this.request = undefined
-        await reader?.cancel().catch(() => {})
-        reader?.releaseLock()
-      }
-      await new Promise<void>((resolve) => {
-        const finish = () => {
-          clearTimeout(timer)
-          this.abort.signal.removeEventListener('abort', finish)
-          resolve()
-        }
-        const timer = setTimeout(finish, 1000)
-        this.abort.signal.addEventListener('abort', finish, { once: true })
-        if (this.abort.signal.aborted) finish()
-      })
-    }
-  }
-}

+ 1 - 1
src/client/api/client.ts

@@ -137,7 +137,7 @@ function errorMessage(payload: unknown, fallback: string): string {
 }
 
 export async function apiRequest<T>(path: string, options: ApiRequestOptions = {}): Promise<T> {
-  if (!path.startsWith('/api/app/') && !path.startsWith('/api/realtime/')) throw new ApiError('客户端仅允许访问应用接口', 0, 'INVALID_PATH')
+  if (!path.startsWith('/api/app/')) throw new ApiError('客户端仅允许访问应用接口', 0, 'INVALID_PATH')
 
   const method = (options.method ?? 'GET').toUpperCase()
   const requiresCsrf = options.csrf !== false && !['GET', 'HEAD', 'OPTIONS'].includes(method)

+ 0 - 40
src/client/api/files.ts

@@ -1,40 +0,0 @@
-import type { FileKind, FileLibraryPage } from '@shared/types'
-import { apiRequest, apiUrl, unwrapData } from './client'
-import { normalizeFile, number, record, values } from '@/utils/normalize'
-
-export interface FileQuery {
-  search?: string
-  kind?: FileKind | 'all'
-  profile?: string
-  conversationOnly?: boolean
-  cursor?: string
-  limit?: number
-}
-
-export async function getFiles(query: FileQuery = {}): Promise<FileLibraryPage> {
-  const serverKind = query.kind === 'image' || query.kind === 'video' ? query.kind : undefined
-  const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/files', {
-    search: query.search,
-    kind: serverKind,
-    profile: query.profile,
-    conversationOnly: query.conversationOnly || undefined,
-    cursor: query.cursor,
-    limit: Math.max(1, Math.min(100, query.limit ?? 50)),
-  })))
-  const source = record(payload)
-  const responseProfile = typeof source.profile === 'string' ? source.profile : query.profile
-  return {
-    items: values(source.items ?? source.files ?? payload)
-      .map(item => normalizeFile(item, responseProfile)).filter(file => file.id),
-    nextCursor: typeof source.nextCursor === 'string' ? source.nextCursor : typeof source.next_cursor === 'string' ? source.next_cursor : null,
-    total: number(source.total) || undefined,
-  }
-}
-
-export function fileDownloadUrl(id: string, profile?: string): string {
-  return apiUrl(`/api/app/files/${encodeURIComponent(id)}/download`, { profile })
-}
-
-export function filePreviewUrl(id: string, profile?: string): string {
-  return apiUrl(`/api/app/files/${encodeURIComponent(id)}/preview`, { profile })
-}

+ 0 - 105
src/client/api/httpRealtime.ts

@@ -1,105 +0,0 @@
-import type { JsonValue } from '@shared/types'
-import { SSEParser } from '@shared/sse'
-import { apiRequest, ApiError, setApiCsrfToken } from './client'
-import { createId } from '@/utils/id'
-import { CHAT_TRANSCRIPT_FEATURE } from '@shared/chatTranscript'
-
-export class HTTPRPCError extends Error {
-  constructor(message: string, readonly code?: string | number, readonly data?: JsonValue) { super(message) }
-}
-
-export class HTTPRealtimeChannel {
-  private id = ''
-  private cursor = ''
-  private stopped = false
-  private abort?: AbortController
-  private ready = false
-  constructor(readonly onFrame: (frame: string) => Promise<unknown>, readonly onFailure: (error: Error) => void) {}
-  static async requireSupport(): Promise<string[]> {
-    let value: { protocolVersion: number; csrfToken?: string; features?: string[] }
-    try { value = await apiRequest('/api/realtime/capabilities') }
-    catch (e) {
-      if (e instanceof ApiError && [404, 405, 410].includes(e.status)) throw new ApiError('此服务端不支持 HTTP+SSE,请升级 15300 服务', 409, 'HTTP_SSE_REQUIRED')
-      throw e
-    }
-    if (value.protocolVersion !== 1) throw new ApiError('不支持的实时协议版本', 409, 'UNSUPPORTED_REALTIME_PROTOCOL')
-    if (value.csrfToken) setApiCsrfToken(value.csrfToken)
-    return value.features ?? []
-  }
-  async open(channel: 'chat' | 'groups', anchor?: { epoch: string; cursor: number }): Promise<void> {
-    const created = await apiRequest<{ id: string }>('/api/realtime/channels', { method: 'POST', body: { channel, ...(channel==='chat'?{chatProtocol:CHAT_TRANSCRIPT_FEATURE}:{}), ...anchor } })
-    this.id = created.id
-    if (this.stopped) { this.close(); return }
-    await new Promise<void>((resolve, reject) => {
-      const timer = window.setTimeout(() => { this.abort?.abort(); reject(new ApiError('实时事件握手超时', 0, 'REALTIME_READY_TIMEOUT')) }, 20_000)
-      void this.readLoop(() => { window.clearTimeout(timer); this.ready = true; resolve() }).catch(error => {
-        window.clearTimeout(timer)
-        if (!this.ready) reject(error)
-        if (!this.stopped) this.onFailure(error instanceof Error ? error : new Error(String(error)))
-      })
-    })
-  }
-  private async readLoop(onReady: () => void): Promise<void> {
-    let attempt = 0
-    while (!this.stopped) {
-      const attemptAbort = new AbortController()
-      this.abort = attemptAbort
-      let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
-      let watchdog: number | undefined
-      try {
-        watchdog = window.setTimeout(() => attemptAbort.abort(), 45_000)
-        const headers: Record<string, string> = { Accept: 'text/event-stream' }
-        if (this.cursor) headers['Last-Event-ID'] = this.cursor
-        const response = await fetch(`/api/realtime/channels/${this.id}/events`, { credentials: 'same-origin', headers, signal: attemptAbort.signal, cache: 'no-store' })
-        if ([401, 403, 404, 409, 428].includes(response.status)) throw new ApiError('实时连接需要重新同步', response.status, 'REALTIME_RESET_REQUIRED')
-        if (!response.ok) throw new Error(`SSE HTTP ${response.status}`)
-        if (!response.headers.get('content-type')?.startsWith('text/event-stream') || !response.body) throw new ApiError('无效的事件流响应', 502, 'INVALID_EVENT_STREAM')
-        reader = response.body.getReader()
-        const parser = new SSEParser(), decoder = new TextDecoder()
-        while (!this.stopped) {
-          window.clearTimeout(watchdog)
-          watchdog = window.setTimeout(() => attemptAbort.abort(), 45_000)
-          const { value, done } = await reader.read()
-          if (done) throw new Error('SSE disconnected')
-          attempt = 0
-          for (const entry of parser.feed(decoder.decode(value, { stream: true }))) {
-            if (entry.event === 'reset') throw new ApiError('事件需要重新同步', 409, 'REALTIME_RESET_REQUIRED')
-            if (entry.event === 'ready') continue
-            if (entry.event !== 'frame') continue
-            if (entry.id && entry.id === this.cursor) continue
-            await this.onFrame(entry.data)
-            if (entry.id) this.cursor = entry.id
-            const frame = JSON.parse(entry.data)
-            if (frame.type === 'group.ready' || frame.params?.type === 'gateway.ready') onReady()
-          }
-        }
-      } catch (error) {
-        if (this.stopped) return
-        if (error instanceof ApiError) throw error
-      } finally { window.clearTimeout(watchdog); await reader?.cancel().catch(() => {}); reader?.releaseLock() }
-      await new Promise(r => window.setTimeout(r, Math.min(15_000, 500 * 2 ** Math.min(attempt++, 5))))
-    }
-  }
-  async request(method: string, params: Record<string, JsonValue>, timeoutMs: number, requestId = createId('http-rpc')): Promise<JsonValue> {
-    if (!this.ready || this.stopped) throw new ApiError('事件通道尚未就绪', 0, 'REALTIME_NOT_READY')
-    type Receipt = { state: string; response?: { result?: JsonValue; error?: { message?: string; code?: string | number; data?: JsonValue } } }
-    let receipt: Receipt
-    try {
-      receipt = await apiRequest(`/api/realtime/channels/${this.id}/commands`, {
-        method: 'POST', headers: { 'Idempotency-Key': requestId }, body: { jsonrpc: '2.0', method, params }, timeoutMs,
-      })
-    } catch (error) {
-      if (error instanceof ApiError && error.status >= 400 && error.status < 500) throw error
-      try { receipt = await apiRequest(`/api/realtime/commands/${encodeURIComponent(requestId)}`) }
-      catch { throw new ApiError('提交结果未知,请同步历史确认', 0, 'SUBMISSION_UNCERTAIN') }
-    }
-    if (receipt.state === 'unknown' || receipt.state === 'pending') throw new ApiError('提交结果未知,请同步历史确认', 0, 'SUBMISSION_UNCERTAIN')
-    if (receipt.response?.error) throw new HTTPRPCError(receipt.response.error.message ?? '上游拒绝请求', receipt.response.error.code, receipt.response.error.data)
-    if (receipt.state !== 'confirmed') throw new ApiError('无效的命令回执', 502, 'INVALID_RECEIPT')
-    return receipt.response?.result ?? null
-  }
-  close(): void {
-    this.stopped = true; this.abort?.abort()
-    if (this.id) { const id = this.id; this.id = ''; void apiRequest(`/api/realtime/channels/${id}`, { method: 'DELETE' }).catch(() => {}) }
-  }
-}

+ 0 - 64
src/client/api/pairing.ts

@@ -1,64 +0,0 @@
-import type { JsonValue } from '@shared/types'
-import { apiRequest } from './client'
-
-export type NodeScope =
-  | 'agents.read'
-  | 'history.read'
-  | 'sessions.execute'
-  | 'groups.read'
-  | 'groups.execute'
-
-export interface PairingSession {
-  protocolVersion: number
-  pairingId: string
-  nodeId: string
-  fingerprint: string
-  scopes: NodeScope[]
-  expiresAt: number
-  qrPayload: string
-}
-
-export interface PairedDevice {
-  id: string
-  name: string
-  scopes: NodeScope[]
-  createdAt: number
-  lastUsedAt: number
-}
-
-export interface PairedDevicesResponse {
-  nodeId: string
-  fingerprint: string
-  devices: PairedDevice[]
-}
-
-export async function createPairing(
-  scopes: NodeScope[],
-): Promise<PairingSession> {
-  return apiRequest<PairingSession>('/api/app/pairings', {
-    method: 'POST',
-    body: { scopes } as unknown as JsonValue,
-  })
-}
-
-export async function pairChildNode(qrPayload: string, name?: string): Promise<void> {
-  await apiRequest('/api/app/nodes', {
-    method: 'POST', body: { qrPayload, name: name || '' } as unknown as JsonValue,
-  })
-}
-
-export async function pairingStatus(
-  pairingId: string,
-): Promise<{ state: 'pending' | 'claimed' | 'expired'; deviceID?: string }> {
-  return apiRequest(`/api/app/pairings/${encodeURIComponent(pairingId)}`)
-}
-
-export async function pairedDevices(): Promise<PairedDevicesResponse> {
-  return apiRequest('/api/app/paired-devices')
-}
-
-export async function revokePairedDevice(deviceId: string): Promise<void> {
-  await apiRequest(`/api/app/paired-devices/${encodeURIComponent(deviceId)}`, {
-    method: 'DELETE', body: {} as JsonValue,
-  })
-}

+ 10 - 118
src/client/api/profiles.ts

@@ -1,23 +1,7 @@
-import type { JsonValue, ModelOption, Profile } from '@shared/types'
+import type { ModelOption, Profile } from '@shared/types'
 import { apiRequest, unwrapData } from './client'
 import { normalizeModel, normalizeProfile, record, values } from '@/utils/normalize'
-import { ChatRpcSocket } from './realtime'
-import {
-  AGENT_MASCOT_EXPRESSIONS,
-  AGENT_MASCOT_SHAPES,
-  AGENT_MASCOT_BODIES, AGENT_IMAGE_CROPS,
-  YAOYAO_AGENT_IDENTITY_NAMESPACE,
-  agentIdentityFromProfile,
-  agentIdentityMetadata,
-  encodeAgentAvatar,
-  type AgentAvatarMode,
-  type AgentMascotExpression,
-  type AgentMascotShape,
-} from '@shared/agentIdentity'
-
-const MAX_AGENT_NAME_LENGTH = 100
-const MAX_AGENT_AVATAR_LENGTH = 2_800_000
-const avatarDataURLPattern = /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/i
+import type { AgentAvatarMode, AgentMascotExpression, AgentMascotShape } from '@shared/agentIdentity'
 
 export type ProfileIdentityInput = {
   title: string
@@ -30,109 +14,17 @@ export type ProfileIdentityInput = {
   avatarDataURL?: string | null
 }
 
-function jsonObject(value: unknown): Record<string, JsonValue> {
-  return record(value) as Record<string, JsonValue>
-}
-
-function readProfileEntries(value: JsonValue): Record<string, JsonValue>[] {
-  const source = jsonObject(value)
-  return values(source.profiles).flatMap(item => {
-    const outer = jsonObject(item)
-    const profile = jsonObject(outer.profile)
-    return Object.keys(profile).length ? [profile] : [outer]
-  })
-}
-
-function validateIdentity(input: ProfileIdentityInput): ProfileIdentityInput {
-  const title = input.title.trim().replace(/\s+/g, ' ')
-  if (!title || title.length > MAX_AGENT_NAME_LENGTH || /[\u0000-\u001f\u007f]/.test(title)) {
-    throw new Error(`机器人名称应为 1 至 ${MAX_AGENT_NAME_LENGTH} 个字符`)
-  }
-  const avatarDataURL = input.avatarDataURL === undefined ? undefined : input.avatarDataURL?.trim() || null
-  if (avatarDataURL && (avatarDataURL.length > MAX_AGENT_AVATAR_LENGTH || !avatarDataURLPattern.test(avatarDataURL))) {
-    throw new Error('头像必须是小于 2 MB 的 PNG、JPEG 或 WebP 图片')
-  }
-  if (!AGENT_MASCOT_SHAPES.includes(input.shape)) throw new Error('请选择有效的头像形状')
-  if (!AGENT_MASCOT_EXPRESSIONS.includes(input.expression)) throw new Error('请选择有效的基础表情')
-  if (input.bodyId != null && !AGENT_MASCOT_BODIES.includes(input.bodyId)) throw new Error('请选择有效的造型')
-  if (input.imageCrop != null && !AGENT_IMAGE_CROPS.includes(input.imageCrop)) throw new Error('请选择有效的裁剪')
-  if (!/^#[0-9a-f]{6}$/i.test(input.color)) throw new Error('请选择有效的头像颜色')
-  return {
-    title,
-    avatarMode: input.avatarMode === 'image' && avatarDataURL ? 'image' : 'mascot',
-    shape: input.shape,
-    color: input.color.toLowerCase(),
-    expression: input.expression,
-    bodyId: input.bodyId ?? null, imageCrop: input.imageCrop ?? 'rounded',
-    avatarDataURL,
-  }
-}
-
-/**
- * Yaoyao owns this identity in a dedicated Hermes metadata namespace. The
- * native Desktop Bots title/avatar are deliberately left untouched.
- */
-export async function updateProfileIdentity(profile: Profile, input: ProfileIdentityInput): Promise<void> {
-  const identity = validateIdentity(input)
-  const control = new ChatRpcSocket()
-  await control.connect()
-  try {
-    const listed = await control.request('profiles.list', { include_sessions: false })
-    const current = readProfileEntries(listed).find(item => String(item.name ?? '') === profile.name)
-    if (!current) throw new Error('该机器人已不存在,请刷新后重试')
-    const revisions = jsonObject(current.ui_meta_revisions)
-    const revision = typeof revisions[YAOYAO_AGENT_IDENTITY_NAMESPACE] === 'number'
-      ? revisions[YAOYAO_AGENT_IDENTITY_NAMESPACE] as number
-      : 0
-    const currentIdentity = agentIdentityFromProfile(current)
-    const nextIdentity = {
-      ...currentIdentity,
-      displayName: identity.title,
-      avatarMode: identity.avatarMode,
-      shape: identity.shape,
-      color: identity.color,
-      expression: identity.expression,
-      bodyId: identity.bodyId ?? null,
-      imageCrop: identity.imageCrop ?? 'rounded',
-      ...(identity.avatarDataURL ? { imageDataURL: identity.avatarDataURL } : {}),
-    }
-    if (!identity.avatarDataURL) delete nextIdentity.imageDataURL
-    await control.request('profiles.configure', {
-      name: profile.name,
-      ui_meta: {
-        [YAOYAO_AGENT_IDENTITY_NAMESPACE]: agentIdentityMetadata(nextIdentity) as Record<string, JsonValue>,
-      },
-      ui_meta_expected_revisions: {
-        [YAOYAO_AGENT_IDENTITY_NAMESPACE]: revision,
-      },
-    })
-  } finally {
-    control.close()
-  }
-}
-
-/** Fetch Yaoyao-owned identity for every profile. */
+/** Yaoyao-owned display identity of every base Profile (read through the in-process Hermes). */
 export async function getProfileIdentities(profiles: Profile[]): Promise<Record<string, { displayName: string; avatar: string }>> {
   if (!profiles.length) return {}
   const allowed = new Set(profiles.map(profile => profile.name))
-  const control = new ChatRpcSocket()
-  await control.connect()
-  try {
-    const listed = await control.request('profiles.list', { include_sessions: false })
-    return Object.fromEntries(
-      readProfileEntries(listed)
-        .filter(item => allowed.has(String(item.name ?? '')))
-        .map(item => {
-          const identity = agentIdentityFromProfile(item)
-          return [String(item.name), {
-            displayName: identity.displayName,
-            avatar: encodeAgentAvatar(identity),
-          }]
-        }),
-    )
-  } finally {
-    control.close()
-  }
+  const payload = record(await apiRequest<unknown>('/api/profile-identities'))
+  return Object.fromEntries(values(payload.profiles).flatMap(raw => {
+    const item = record(raw)
+    const name = typeof item.name === 'string' ? item.name : ''
+    if (!allowed.has(name)) return []
+    return [[name, { displayName: String(item.displayName ?? name), avatar: String(item.avatar ?? '') }]]
+  }))
 }
 
 export async function getProfiles(): Promise<Profile[]> {

+ 0 - 182
src/client/api/realtime.ts

@@ -1,182 +0,0 @@
-import { publishServerIdentity } from './serverIdentity'
-import type { GroupSocketEnvelope, JsonValue, RealtimeConnectionState, RpcEventFrame } from '@shared/types'
-import { ApiError } from './client'
-import { number, record, string } from '@/utils/normalize'
-import { HTTPRealtimeChannel, HTTPRPCError } from './httpRealtime'
-import { CHAT_TRANSCRIPT_FEATURE } from '@shared/chatTranscript'
-
-export class RpcError extends Error {
-  constructor(message: string, readonly code?: number | string, readonly data?: JsonValue) {
-    super(message); this.name = 'RpcError'
-  }
-}
-
-type StateListener = (state: RealtimeConnectionState, reason?: string) => void
-type RpcEventListener = (event: RpcEventFrame['params']) => void
-
-/** Historical facade name retained for store injection; transport is HTTP+SSE only. */
-export class ChatRpcSocket {
-  private http?: HTTPRealtimeChannel
-  private generation = 0
-  private openingRequests = 0
-  private earlyFrames: string[] = []
-  private eventListeners = new Set<RpcEventListener>()
-  private stateListeners = new Set<StateListener>()
-  state: RealtimeConnectionState = 'idle'
-  transcriptSupported = false
-
-  onEvent(listener: RpcEventListener): () => void { this.eventListeners.add(listener); return () => this.eventListeners.delete(listener) }
-  onState(listener: StateListener): () => void { this.stateListeners.add(listener); return () => this.stateListeners.delete(listener) }
-  async connect(): Promise<void> {
-    this.close()
-    const generation = ++this.generation
-    this.publishState('connecting')
-    this.transcriptSupported = (await HTTPRealtimeChannel.requireSupport()).includes(CHAT_TRANSCRIPT_FEATURE)
-    if(!this.transcriptSupported)throw new ApiError('普通聊天需要新版服务端,请先升级服务端',426,'ordinary_chat_upgrade_required')
-    if (generation !== this.generation) return
-    this.http = new HTTPRealtimeChannel(frame => this.handleMessage(frame, generation), error => {
-      if (generation === this.generation) this.publishState('failed', error.message)
-    })
-    await this.http.open('chat')
-  }
-  close(): void {
-    this.generation++; this.http?.close(); this.http = undefined
-    this.earlyFrames = []; this.openingRequests = 0
-    this.publishState('disconnected')
-  }
-  async request(method: string, params: Record<string, JsonValue> = {}, timeoutMs = 120_000, requestId?: string): Promise<JsonValue> {
-    if (!this.http) throw new ApiError('HTTP 事件通道尚未就绪', 0, 'REALTIME_NOT_READY')
-    const generation = this.generation
-    const opening = ['session.create', 'session.resume', 'session.branch'].includes(method)
-    if (opening) this.openingRequests++
-    try { return await this.http.request(method, params, timeoutMs, requestId) }
-    catch (error) { if (error instanceof HTTPRPCError) throw new RpcError(error.message, error.code, error.data); throw error }
-    finally {
-      if (opening && generation === this.generation) {
-        this.openingRequests--
-        window.setTimeout(() => {
-          if (generation !== this.generation || this.openingRequests) return
-          const frames = this.earlyFrames; this.earlyFrames = []
-          for (const frame of frames) void this.handleMessage(frame, generation)
-        }, 0)
-      }
-    }
-  }
-  private async handleMessage(text: string, generation: number): Promise<void> {
-    if (generation !== this.generation) return
-    const frame = record(JSON.parse(text))
-    if (frame.method !== 'event') return
-    const params = record(frame.params), type = string(params.type)
-    if (!type) return
-    if (this.openingRequests && type !== 'gateway.ready') {
-      if (this.earlyFrames.length >= 512) { this.earlyFrames = []; this.publishState('failed', '事件缓存已满,需要重新同步') }
-      else this.earlyFrames.push(text)
-      return
-    }
-    if (type === 'server.identity.changed') publishServerIdentity(params.payload)
-    if (type === 'gateway.ready') this.publishState('ready')
-    const event: RpcEventFrame['params'] = {
-      type, session_id: string(params.session_id) || undefined,
-      profile: string(params.profile) || undefined, payload: (params.payload ?? null) as JsonValue,
-    }
-    for (const listener of this.eventListeners) listener(event)
-  }
-  private publishState(state: RealtimeConnectionState, reason?: string): void {
-    this.state = state
-    for (const listener of this.stateListeners) listener(state, reason)
-  }
-}
-
-export interface GroupEventSocketOptions {
-  epoch: string
-  cursor: number
-  onEnvelope(envelope: GroupSocketEnvelope): void
-  onState?(state: RealtimeConnectionState, reason?: string): void
-  onReset(reason: string): void
-}
-
-export class GroupEventSocket {
-  private http?: HTTPRealtimeChannel
-  private generation = 0
-  private epoch = ''
-  private cursor = 0
-  state: RealtimeConnectionState = 'idle'
-  async connect(options: GroupEventSocketOptions): Promise<void> {
-    this.close()
-    this.epoch = options.epoch; this.cursor = options.cursor
-    const generation = ++this.generation
-    this.publish(options, 'connecting')
-    await HTTPRealtimeChannel.requireSupport()
-    if (generation !== this.generation) return
-    this.http = new HTTPRealtimeChannel(frame => this.handleMessage(frame, generation, options), error => {
-      if (generation === this.generation) this.needsReset(options, error.message)
-    })
-    await this.http.open('groups', { epoch: this.epoch, cursor: this.cursor })
-  }
-  close(): void {
-    this.generation++; this.http?.close(); this.http = undefined
-    this.state = 'disconnected'
-  }
-  private async handleMessage(data: unknown, generation: number, options: GroupEventSocketOptions): Promise<void> {
-    if (generation !== this.generation) return
-    let text: string
-    if (typeof data === 'string') text = data
-    else if (data instanceof Blob) text = await data.text()
-    else if (data instanceof ArrayBuffer) text = new TextDecoder().decode(data)
-    else return
-    let decoded: unknown
-    try { decoded = JSON.parse(text) } catch {
-      this.needsReset(options, 'malformed_frame')
-      return
-    }
-    const source = record(decoded)
-    const envelope: GroupSocketEnvelope = {
-      type: string(source.type) as GroupSocketEnvelope['type'],
-      epoch: string(source.epoch) || undefined,
-      cursor: source.cursor == null ? undefined : number(source.cursor, -1),
-      heartbeatSeconds: source.heartbeatSeconds == null && source.heartbeat_seconds == null ? undefined : number(source.heartbeatSeconds ?? source.heartbeat_seconds),
-      roomId: string(source.roomId ?? source.room_id) || undefined,
-      event: string(source.event) || undefined,
-      payload: (source.payload ?? null) as JsonValue,
-      reason: string(source.reason) || undefined,
-    }
-    if (!['group.ready', 'group.event', 'group.heartbeat', 'group.reset_required'].includes(envelope.type)) {
-      this.needsReset(options, 'unknown_envelope')
-      return
-    }
-    if (envelope.epoch && envelope.epoch !== this.epoch) {
-      this.needsReset(options, 'epoch_mismatch')
-      return
-    }
-    if (envelope.type === 'group.ready') {
-      if (envelope.cursor !== this.cursor) return this.needsReset(options, 'ready_cursor_mismatch')
-      this.publish(options, 'ready')
-      options.onEnvelope(envelope)
-      return
-    }
-    if (envelope.type === 'group.event') {
-      if (envelope.cursor == null || envelope.cursor < 0) return this.needsReset(options, 'invalid_cursor')
-      if (envelope.cursor <= this.cursor) return
-      if (envelope.cursor !== this.cursor + 1) return this.needsReset(options, 'cursor_gap')
-      this.cursor = envelope.cursor
-      options.onEnvelope(envelope)
-      return
-    }
-    if (envelope.type === 'group.reset_required') {
-      this.needsReset(options, envelope.reason || 'server_reset')
-      return
-    }
-    if (envelope.cursor != null && envelope.cursor !== this.cursor) this.needsReset(options, 'heartbeat_cursor_mismatch')
-  }
-
-  private needsReset(options: GroupEventSocketOptions, reason: string): void {
-    this.http?.close(); this.http = undefined
-    this.publish(options, 'needs-reset', reason)
-    options.onReset(reason)
-  }
-
-  private publish(options: GroupEventSocketOptions, state: RealtimeConnectionState, reason?: string): void {
-    this.state = state
-    options.onState?.(state, reason)
-  }
-}

+ 0 - 169
src/client/api/sessions.ts

@@ -1,169 +0,0 @@
-import type { ChatMessage, JsonValue, SessionSummary } from '@shared/types'
-import { apiRequest, apiUrl, unwrapData } from './client'
-import { normalizeChatMessage, normalizeSession, number, record, values } from '@/utils/normalize'
-
-const EXCLUDED_SOURCES = 'cron,ios_group,yaoyao_workspace'
-
-export interface SessionPage {
-  items: SessionSummary[]
-  nextCursor?: string | null
-  total?: number
-}
-
-export interface MessagePage {
-  session?: SessionSummary
-  messages: ChatMessage[]
-  total: number
-  returned: number
-  hasMore: boolean
-  offset: number
-  limit: number
-}
-
-export async function getSessions(profile?: string, cursor?: string, limit = 100, view: 'chat' | 'history' = 'chat'): Promise<SessionPage> {
-  const offset = Math.max(0, Number.parseInt(cursor ?? '0', 10) || 0)
-  const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions', {
-    profile,
-    offset,
-    limit: Math.max(1, Math.min(200, limit)),
-    order: 'recent',
-    archived: 'exclude',
-    exclude: EXCLUDED_SOURCES,
-    view,
-  })))
-  const source = record(payload)
-  const rawItems = values(source.items ?? source.sessions ?? payload)
-  const items = rawItems.map(item => normalizeSession(item, profile)).filter(session => session.id)
-    .filter(session => !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
-  const total = number(source.total)
-  const nextOffset = offset + items.length
-  return {
-    items,
-    nextCursor: typeof source.nextCursor === 'string'
-      ? source.nextCursor
-      : typeof source.next_cursor === 'string'
-        ? source.next_cursor
-        : total > nextOffset && items.length ? String(nextOffset) : null,
-    total: total || undefined,
-  }
-}
-
-export async function searchSessions(query: string, profile?: string, limit = 100): Promise<SessionSummary[]> {
-  const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions/search', {
-    q: query,
-    profile,
-    limit: Math.max(1, Math.min(200, limit)),
-    exclude: EXCLUDED_SOURCES,
-  })))
-  const source = record(payload)
-  return values(source.items ?? source.sessions ?? source.results ?? payload).map(item => normalizeSession(item, profile))
-    .filter(session => session.id && !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
-}
-
-export async function getSession(id: string, profile?: string): Promise<SessionSummary> {
-  const payload = unwrapData(await apiRequest<unknown>(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile })))
-  const source = record(payload)
-  return normalizeSession(source.session ?? payload, profile)
-}
-
-export async function getMessages(
-  sessionId: string,
-  offset: number,
-  limit = 150,
-  profile?: string,
-  forceRefresh = false,
-  view: 'chat' | 'history' = 'chat',
-): Promise<MessagePage> {
-  const safeOffset = Math.max(0, Math.trunc(offset))
-  const safeLimit = Math.max(1, Math.min(500, Math.trunc(limit)))
-  const url = apiUrl(`/api/app/sessions/${encodeURIComponent(sessionId)}/messages`, {
-    offset: safeOffset,
-    limit: safeLimit,
-    order: 'latest',
-    include_compacted: true,
-    profile,
-    ...(view === 'history' ? {view} : {}),
-  })
-  const payload = unwrapData(await apiRequest<unknown>(url, forceRefresh ? { headers: { 'X-Yaoyao-Cache': 'bypass' } } : {}))
-  const source = record(payload)
-  const pagination = record(source.pagination)
-  const messages = values(source.messages ?? source.items ?? payload).map(message => normalizeChatMessage(message, sessionId, profile))
-  const returned = Math.max(number(pagination.returned), messages.length)
-  const total = Math.max(number(pagination.total ?? source.total), safeOffset + returned)
-  const hasMore = typeof pagination.hasMore === 'boolean'
-    ? pagination.hasMore
-    : typeof pagination.has_more === 'boolean'
-      ? pagination.has_more
-      : safeOffset + returned < total || returned >= safeLimit
-  return {
-    session: source.session ? normalizeSession(source.session, profile) : undefined,
-    messages,
-    total,
-    returned,
-    hasMore,
-    offset: safeOffset,
-    limit: safeLimit,
-  }
-}
-
-export async function createSession(profile: string, title?: string): Promise<SessionSummary> {
-  const payload = unwrapData(await apiRequest<unknown>('/api/app/sessions', {
-    method: 'POST',
-    body: { profile, title: title || null, source: 'web' } as JsonValue,
-  }))
-  const source = record(payload)
-  return normalizeSession(source.session ?? payload, profile)
-}
-
-export async function updateSession(
-  id: string,
-  patch: { title?: string; archived?: boolean; pinned?: boolean },
-  profile?: string,
-): Promise<SessionSummary> {
-  await apiRequest<unknown>(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile }), {
-    method: 'PATCH', body: patch as JsonValue,
-  })
-  return getSession(id, profile)
-}
-
-export async function deleteSession(id: string, profile?: string): Promise<void> {
-  await apiRequest(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile }), { method: 'DELETE' })
-}
-
-export async function requestHistorySync(sessionId:string,profile?:string):Promise<void>{
-  await apiRequest(apiUrl(`/api/app/sessions/${encodeURIComponent(sessionId)}/sync`,{profile}),{method:'POST',body:{}})
-}
-
-export async function getSessionUnread(profile?: string): Promise<Record<string, number>> {
-  const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions/unread', { profile })))
-  const source = record(payload)
-  const sessionRows = values(source.sessions ?? source.items)
-  if (sessionRows.length) {
-    const result: Record<string, number> = {}
-    for (const value of sessionRows) {
-      const item = record(value)
-      const id = typeof item.sessionId === 'string'
-        ? item.sessionId
-        : typeof item.session_id === 'string' ? item.session_id : ''
-      if (id) result[id] = Math.max(0, number(item.final_unread_count ?? item.unreadCount ?? item.unread_count ?? item.count))
-    }
-    return result
-  }
-  const raw = record(source.items ?? source.unread ?? source.counts ?? payload)
-  const result: Record<string, number> = {}
-  for (const [sessionId, value] of Object.entries(raw)) {
-    if (typeof value === 'number' || typeof value === 'string') result[sessionId] = Math.max(0, number(value))
-    else {
-      const item = record(value)
-      const id = typeof item.sessionId === 'string' ? item.sessionId : typeof item.session_id === 'string' ? item.session_id : sessionId
-      result[id] = Math.max(0, number(item.final_unread_count ?? item.unreadCount ?? item.unread_count ?? item.count))
-    }
-  }
-  return result
-}
-
-export async function markSessionRead(sessionId: string, readMessageCount: number, profile?: string): Promise<void> {
-  await apiRequest(apiUrl(`/api/app/sessions/unread/${encodeURIComponent(sessionId)}`, { profile }), {
-    method: 'PATCH', body: { readMessageCount: Math.max(0, Math.trunc(readMessageCount)) },
-  })
-}

+ 29 - 295
src/client/components/app/NodePairingPanel.vue

@@ -3,75 +3,33 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue'
 import QRCode from 'qrcode'
 import AppIcon from '@/components/common/AppIcon.vue'
 import { accountPairingStatus, createAccountPairing, type AccountPairingSession } from '@/api/accountPairing'
-import {
-  createPairing,
-  pairChildNode,
-  pairedDevices,
-  pairingStatus,
-  revokePairedDevice,
-  type NodeScope,
-  type PairedDevice,
-  type PairingSession,
-} from '@/api/pairing'
 
+/** Phone login QR: the phone signs in to this server's account (Bot mode). */
 const props = withDefaults(defineProps<{
   active?: boolean
-  mode: 'account' | 'nodes'
+  mode?: 'account'
   insecureTransport?: boolean
   userName?: string
-  isAdmin?: boolean
 }>(), {
   active: true,
+  mode: 'account',
   insecureTransport: false,
   userName: '',
-  isAdmin: false,
 })
-const emit = defineEmits<{ 'dirty-change': [dirty: boolean] }>()
 
-const ALL_SCOPES: NodeScope[] = [
-  'agents.read', 'history.read', 'sessions.execute', 'groups.read', 'groups.execute',
-]
-const pairing = ref<PairingSession>()
 const accountPairing = ref<AccountPairingSession>()
-const qrImage = ref('')
 const accountQrImage = ref('')
 const accountPairingComplete = ref(false)
-const devices = ref<PairedDevice[]>([])
-const nodeID = ref('')
 const busy = ref(false)
 const error = ref('')
-const childCode = ref('')
-const childName = ref('')
-const scanVideo = ref<HTMLVideoElement>()
-const scanning = ref(false)
-const scanStarting = ref(false)
 const now = ref(Date.now())
-let timer: number | undefined
 let accountTimer: number | undefined
-let scanTimer: number | undefined
-let scanStream: MediaStream | undefined
 let lifecycleToken = 0
-let scanToken = 0
-let nodePolling = false
 let accountPolling = false
 
-type BarcodeDetectorLike = { detect(source: ImageBitmapSource): Promise<Array<{ rawValue?: string }>> }
-type BarcodeDetectorConstructor = new (options: { formats: string[] }) => BarcodeDetectorLike
-
-const secondsRemaining = computed(() => pairing.value
-  ? Math.max(0, Math.ceil((pairing.value.expiresAt - now.value) / 1_000))
-  : 0)
 const accountSecondsRemaining = computed(() => accountPairing.value
   ? Math.max(0, Math.ceil((accountPairing.value.expiresAt - now.value) / 1_000))
   : 0)
-const dirty = computed(() => props.mode === 'nodes' && Boolean(childName.value.trim() || childCode.value.trim()))
-watch(dirty, value => emit('dirty-change', value), { immediate: true })
-
-function stopPolling() {
-  if (timer !== undefined) window.clearInterval(timer)
-  timer = undefined
-  nodePolling = false
-}
 
 function stopAccountPolling() {
   if (accountTimer !== undefined) window.clearInterval(accountTimer)
@@ -79,49 +37,29 @@ function stopAccountPolling() {
   accountPolling = false
 }
 
-function stopScanning() {
-  scanToken += 1
-  scanStarting.value = false
-  if (scanTimer !== undefined) window.clearInterval(scanTimer)
-  scanTimer = undefined
-  scanStream?.getTracks().forEach(track => track.stop())
-  scanStream = undefined
-  scanning.value = false
-}
-
 function resetTransientState() {
   lifecycleToken += 1
-  stopPolling()
   stopAccountPolling()
-  stopScanning()
-  pairing.value = undefined
   accountPairing.value = undefined
-  qrImage.value = ''
   accountQrImage.value = ''
   accountPairingComplete.value = false
-  childCode.value = ''
-  childName.value = ''
   error.value = ''
   busy.value = false
 }
 
-function isCurrent(token: number, mode: 'account' | 'nodes'): boolean {
-  return token === lifecycleToken && props.active && props.mode === mode
-}
-
-function isCurrentScan(token: number, lifecycle: number): boolean {
-  return token === scanToken && isCurrent(lifecycle, 'nodes')
+function isCurrent(token: number): boolean {
+  return token === lifecycleToken && props.active
 }
 
 async function pollAccountPairing(token = lifecycleToken) {
-  if (accountPolling || !isCurrent(token, 'account')) return
+  if (accountPolling || !isCurrent(token)) return
   accountPolling = true
   now.value = Date.now()
   const current = accountPairing.value
   if (!current || accountSecondsRemaining.value <= 0) { stopAccountPolling(); return }
   try {
     const status = await accountPairingStatus(current.pairingId)
-    if (!isCurrent(token, 'account') || accountPairing.value?.pairingId !== current.pairingId) return
+    if (!isCurrent(token) || accountPairing.value?.pairingId !== current.pairingId) return
     if (status.state === 'claimed') {
       accountPairingComplete.value = true
       stopAccountPolling()
@@ -131,7 +69,7 @@ async function pollAccountPairing(token = lifecycleToken) {
 }
 
 async function beginAccountPairing() {
-  if (busy.value || !props.active || props.mode !== 'account') return
+  if (busy.value || !props.active) return
   const token = lifecycleToken
   busy.value = true
   error.value = ''
@@ -139,233 +77,45 @@ async function beginAccountPairing() {
   stopAccountPolling()
   try {
     const created = await createAccountPairing()
-    if (!isCurrent(token, 'account')) return
+    if (!isCurrent(token)) return
     accountPairing.value = created
     now.value = Date.now()
     const image = await QRCode.toDataURL(created.qrPayload, {
       width: 296, margin: 2, errorCorrectionLevel: 'M', color: { dark: '#191918', light: '#ffffff' },
     })
-    if (!isCurrent(token, 'account')) return
+    if (!isCurrent(token)) return
     accountQrImage.value = image
     accountTimer = window.setInterval(() => { void pollAccountPairing(token) }, 1_000)
   } catch (cause) {
-    if (isCurrent(token, 'account')) error.value = cause instanceof Error ? cause.message : '无法创建手机登录二维码'
-  } finally {
-    if (isCurrent(token, 'account')) busy.value = false
-  }
-}
-
-async function startScanning() {
-  if (scanStarting.value || scanning.value || !props.active || props.mode !== 'nodes') return
-  const lifecycle = lifecycleToken
-  const Detector = (window as unknown as { BarcodeDetector?: BarcodeDetectorConstructor }).BarcodeDetector
-  if (!Detector || !navigator.mediaDevices?.getUserMedia) {
-    error.value = '当前浏览器不支持直接扫码,请粘贴配对码。'
-    return
-  }
-  stopScanning()
-  const token = scanToken
-  scanStarting.value = true
-  error.value = ''
-  let ownedStream: MediaStream | undefined
-  const releaseOwnedStream = () => {
-    ownedStream?.getTracks().forEach(track => track.stop())
-    if (scanStream === ownedStream) {
-      scanStream = undefined
-      scanning.value = false
-    }
-  }
-  try {
-    const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
-    ownedStream = stream
-    if (!isCurrentScan(token, lifecycle)) {
-      releaseOwnedStream()
-      return
-    }
-    scanStream = stream
-    scanStarting.value = false
-    scanning.value = true
-    await new Promise(resolve => window.setTimeout(resolve, 0))
-    if (!isCurrentScan(token, lifecycle)) { releaseOwnedStream(); return }
-    if (scanVideo.value) { scanVideo.value.srcObject = stream; await scanVideo.value.play() }
-    if (!isCurrentScan(token, lifecycle)) { releaseOwnedStream(); return }
-    const detector = new Detector({ formats: ['qr_code'] })
-    scanTimer = window.setInterval(() => {
-      if (!isCurrentScan(token, lifecycle)) { releaseOwnedStream(); return }
-      const video = scanVideo.value
-      if (!video || video.readyState < 2) return
-      void detector.detect(video).then(values => {
-        const payload = values.find(value => value.rawValue?.startsWith('yaoyao://pair'))?.rawValue
-        if (payload && isCurrentScan(token, lifecycle)) { childCode.value = payload; stopScanning() }
-      }).catch(() => undefined)
-    }, 350)
-  } catch {
-    if (isCurrentScan(token, lifecycle)) {
-      error.value = '无法使用摄像头,请检查权限或直接粘贴配对码。'
-      stopScanning()
-    } else {
-      releaseOwnedStream()
-    }
+    if (isCurrent(token)) error.value = cause instanceof Error ? cause.message : '无法创建手机登录二维码'
   } finally {
-    if (isCurrentScan(token, lifecycle)) scanStarting.value = false
+    if (isCurrent(token)) busy.value = false
   }
 }
 
-async function refreshDevices(token = lifecycleToken) {
-  const response = await pairedDevices()
-  if (!isCurrent(token, 'nodes')) return
-  devices.value = response.devices
-  nodeID.value = response.nodeId
-}
-
-async function poll(token = lifecycleToken) {
-  if (nodePolling || !isCurrent(token, 'nodes')) return
-  nodePolling = true
-  now.value = Date.now()
-  const current = pairing.value
-  if (!current || secondsRemaining.value <= 0) { stopPolling(); return }
-  try {
-    const status = await pairingStatus(current.pairingId)
-    if (!isCurrent(token, 'nodes') || pairing.value?.pairingId !== current.pairingId) return
-    if (status.state === 'claimed') {
-      pairing.value = undefined
-      qrImage.value = ''
-      stopPolling()
-      await refreshDevices(token)
-    } else if (status.state === 'expired') stopPolling()
-  } catch { /* A transient poll failure must not discard a still-valid QR code. */ }
-  finally { nodePolling = false }
-}
-
-async function beginPairing() {
-  if (!props.isAdmin || busy.value || !props.active || props.mode !== 'nodes') return
-  const token = lifecycleToken
-  busy.value = true
-  error.value = ''
-  stopPolling()
-  try {
-    const created = await createPairing(ALL_SCOPES)
-    if (!isCurrent(token, 'nodes')) return
-    pairing.value = created
-    now.value = Date.now()
-    const image = await QRCode.toDataURL(created.qrPayload, {
-      width: 296, margin: 2, errorCorrectionLevel: 'M', color: { dark: '#191918', light: '#ffffff' },
-    })
-    if (!isCurrent(token, 'nodes')) return
-    qrImage.value = image
-    timer = window.setInterval(() => { void poll(token) }, 1_000)
-  } catch (cause) {
-    if (isCurrent(token, 'nodes')) error.value = cause instanceof Error ? cause.message : '无法创建配对二维码'
-  } finally {
-    if (isCurrent(token, 'nodes')) busy.value = false
-  }
-}
-
-async function addChild() {
-  if (!props.isAdmin || busy.value || !props.active || props.mode !== 'nodes') return
-  const token = lifecycleToken
-  busy.value = true
-  error.value = ''
-  try {
-    await pairChildNode(childCode.value.trim(), childName.value.trim() || undefined)
-    if (!isCurrent(token, 'nodes')) return
-    childCode.value = ''
-    childName.value = ''
-  } catch (cause) {
-    if (isCurrent(token, 'nodes')) error.value = cause instanceof Error ? cause.message : '添加子节点失败'
-  } finally {
-    if (isCurrent(token, 'nodes')) busy.value = false
-  }
-}
-
-async function revoke(device: PairedDevice) {
-  if (!props.isAdmin || !window.confirm(`撤销“${device.name}”的 Hermes 访问权限?`)) return
-  if (busy.value || !props.active || props.mode !== 'nodes') return
-  const token = lifecycleToken
-  busy.value = true
-  error.value = ''
-  try {
-    await revokePairedDevice(device.id)
-    if (!isCurrent(token, 'nodes')) return
-    await refreshDevices(token)
-  } catch (cause) {
-    if (isCurrent(token, 'nodes')) error.value = cause instanceof Error ? cause.message : '撤销设备失败'
-  } finally {
-    if (isCurrent(token, 'nodes')) busy.value = false
-  }
-}
-
-watch(() => [props.active, props.mode] as const, ([active, mode]) => {
+watch(() => props.active, active => {
   resetTransientState()
-  if (!active) return
-  if (mode === 'account') {
-    void beginAccountPairing()
-    return
-  }
-  if (!props.isAdmin) return
-  const token = lifecycleToken
-  busy.value = true
-  void refreshDevices(token)
-    .catch(cause => { if (isCurrent(token, 'nodes')) error.value = cause instanceof Error ? cause.message : '读取配对设备失败' })
-    .finally(() => { if (isCurrent(token, 'nodes')) busy.value = false })
+  if (active) void beginAccountPairing()
 }, { immediate: true })
 
 onBeforeUnmount(resetTransientState)
 </script>
 
 <template>
-  <section class="pairing-panel" :aria-label="mode === 'account' ? '手机登录' : '节点与设备'">
-    <p v-if="mode === 'account'" class="pairing-intro">手机扫描登录二维码后,会把这台 15300 保存为普通服务器账号;不会添加成子节点。</p>
-    <p v-else class="pairing-intro">管理当前 15300 的直接子节点与已授权设备。账号登录设备不会在这里显示。</p>
-    <p v-if="mode === 'account' && insecureTransport" class="pairing-warning"><AppIcon name="alert" :size="16" />当前是局域网 HTTP,二维码免密配对仅适用于可信网络。正式使用请配置 HTTPS/WSS 或 Tailscale。</p>
+  <section class="pairing-panel" aria-label="手机登录">
+    <p class="pairing-intro">手机扫描登录二维码后,会把这台 15300 保存为服务器账号,并以 Bot 模式使用。</p>
+    <p v-if="insecureTransport" class="pairing-warning"><AppIcon name="alert" :size="16" />当前是局域网 HTTP,二维码免密配对仅适用于可信网络。正式使用请配置 HTTPS 或 Tailscale。</p>
     <p v-if="error" class="pairing-error" role="alert">{{ error }}</p>
-
-    <template v-if="mode === 'account'">
-      <div class="device-heading"><strong>扫码登录并添加服务器</strong><small>{{ userName }}</small></div>
-      <section v-if="accountPairing" class="qr-card">
-        <img v-if="accountQrImage" :src="accountQrImage" alt="手机扫码登录并添加服务器" />
-        <strong>{{ accountPairingComplete ? '手机已添加此服务器' : '在 iOS 登录页选择扫码' }}</strong>
-        <span v-if="accountPairingComplete">该二维码已经失效</span>
-        <span v-else-if="accountSecondsRemaining">二维码将在 {{ accountSecondsRemaining }} 秒后失效</span>
-        <span v-else>二维码已失效</span>
-        <button v-if="accountPairingComplete || !accountSecondsRemaining" class="quiet-button" type="button" @click="beginAccountPairing">重新生成</button>
-      </section>
-      <p v-else-if="busy" class="device-empty">正在生成登录二维码…</p>
-    </template>
-
-    <template v-else-if="isAdmin">
-      <section class="device-section device-section--first">
-        <div class="device-heading"><strong>授权为 15300 子节点</strong><small>管理员</small></div>
-        <section v-if="pairing" class="qr-card">
-          <img v-if="qrImage" :src="qrImage" alt="添加此 Hermes 节点的二维码" />
-          <strong>仅用于子节点配对</strong>
-          <span v-if="secondsRemaining">二维码将在 {{ secondsRemaining }} 秒后失效</span>
-          <span v-else>二维码已失效</span>
-          <button v-if="!secondsRemaining" class="quiet-button" type="button" @click="beginPairing">重新生成</button>
-        </section>
-        <button v-else class="solid-button create-pairing" type="button" :disabled="busy" @click="beginPairing"><AppIcon name="users" :size="17" />{{ busy ? '正在准备…' : '生成子节点配对二维码' }}</button>
-      </section>
-
-      <section class="device-section">
-        <div class="device-heading"><strong>已授权设备</strong><small v-if="nodeID">节点 {{ nodeID.slice(0, 8) }}</small></div>
-        <p v-if="!busy && !devices.length" class="device-empty">还没有已授权设备。</p>
-        <div v-for="device in devices" :key="device.id" class="device-row">
-          <span><b>{{ device.name }}</b><small>{{ device.scopes.includes('history.read') ? 'Bots、历史与团队' : '受限访问' }}</small></span>
-          <button type="button" :disabled="busy" @click="revoke(device)">撤销</button>
-        </div>
-      </section>
-
-      <section class="device-section child-section">
-        <div class="device-heading"><strong>添加 15300 子节点</strong><small>只管理直接子节点</small></div>
-        <label><span>节点名称(可选)</span><input v-model="childName" :disabled="busy" placeholder="例如:办公室 Mac" /></label>
-        <label><span>子节点配对码</span><textarea v-model="childCode" rows="3" :disabled="busy" placeholder="粘贴子节点生成的 yaoyao://pair…" /></label>
-        <video v-if="scanning" ref="scanVideo" class="scanner-video" muted playsinline />
-        <div class="child-actions">
-          <button class="quiet-button" type="button" :disabled="busy || scanStarting" @click="scanning ? stopScanning() : startScanning()">{{ scanStarting ? '正在打开摄像头…' : scanning ? '停止扫码' : '使用摄像头扫码' }}</button>
-          <button class="solid-button" type="button" :disabled="busy || !childCode.trim()" @click="addChild">验证并添加子节点</button>
-        </div>
-      </section>
-    </template>
+    <div class="device-heading"><strong>扫码登录并添加服务器</strong><small>{{ userName }}</small></div>
+    <section v-if="accountPairing" class="qr-card">
+      <img v-if="accountQrImage" :src="accountQrImage" alt="手机扫码登录并添加服务器" />
+      <strong>{{ accountPairingComplete ? '手机已添加此服务器' : '在 iOS 登录页选择扫码' }}</strong>
+      <span v-if="accountPairingComplete">该二维码已经失效</span>
+      <span v-else-if="accountSecondsRemaining">二维码将在 {{ accountSecondsRemaining }} 秒后失效</span>
+      <span v-else>二维码已失效</span>
+      <button v-if="accountPairingComplete || !accountSecondsRemaining" class="quiet-button" type="button" @click="beginAccountPairing">重新生成</button>
+    </section>
+    <p v-else-if="busy" class="device-empty">正在生成登录二维码…</p>
   </section>
 </template>
 
@@ -383,25 +133,9 @@ onBeforeUnmount(resetTransientState)
 .qr-card img { width: min(260px, 100%); aspect-ratio: 1; }
 .qr-card strong { font-size: 14px; }
 .qr-card span { color: #686865; font-size: 12px; }
-.device-section { display: grid; gap: 10px; padding-top: 20px; border-top: 1px solid var(--line); }
-.device-section--first { padding-top: 0; border-top: 0; }
-.device-row { display: flex; min-height: 54px; align-items: center; gap: 12px; padding: 8px 2px; border-bottom: 1px solid var(--line); }
-.device-row span { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 4px; }
-.device-row b { overflow: hidden; font-size: 14px; text-overflow: ellipsis; white-space: nowrap; }
-.device-row small { color: var(--text-muted); font-size: 12px; }
-.device-row button { border: 0; background: transparent; color: var(--danger); font-size: 13px; cursor: pointer; }
-.child-section label { display: grid; gap: 6px; color: var(--text-secondary); font-size: 13px; font-weight: 600; }
-.child-section input,.child-section textarea { padding: 10px 12px; border: 1px solid var(--line); border-radius: 9px; outline: 0; background: var(--surface-soft); color: var(--text-primary); font: inherit; resize: vertical; }
-.child-section input:focus,.child-section textarea:focus { border-color: var(--line-strong); box-shadow: 0 0 0 3px var(--focus-ring); }
-.scanner-video { width: 100%; max-height: 260px; border-radius: 11px; background: #111; object-fit: cover; }
-.child-actions { display: flex; justify-content: flex-end; gap: 10px; }
-.quiet-button,.solid-button { display: inline-flex; min-height: 40px; align-items: center; justify-content: center; gap: 7px; padding: 0 14px; border: 0; border-radius: 9px; cursor: pointer; font: 600 13px var(--font-ui); }
-.quiet-button { border: 1px solid var(--line); background: var(--surface-raised); color: var(--text-secondary); }
-.solid-button { background: var(--accent); color: var(--text-on-solid); }
-.create-pairing { width: 100%; min-height: 44px; }
+.quiet-button,.quiet-button { border: 1px solid var(--line); background: var(--surface-raised); color: var(--text-secondary); }
 button:disabled { cursor: not-allowed; opacity: .5; }
 @media (max-width: 700px) {
   .qr-card { width: 100%; box-sizing: border-box; }
-  .child-actions { align-items: stretch; flex-direction: column; }
-}
+  }
 </style>

+ 8 - 16
src/client/components/app/SettingsCenterDialog.vue

@@ -63,7 +63,7 @@ const props = withDefaults(defineProps<{
   identityError?: string
   identityResetVersion?: number
 }>(), {
-  initialPage: 'agent-identity',
+  initialPage: 'account-profile',
   userName: '',
   userAvatar: '',
   pairingUserName: '',
@@ -86,13 +86,12 @@ const emit = defineEmits<{
   'select-profile': [profile: string]
   'save-identity': [input: ProfileIdentityInput]
   'set-theme': [theme: ThemePreference]
-  'switch-mode': []
 }>()
 
 const dialog = ref<HTMLElement>()
 const contentTitle = ref<HTMLElement>()
 const settingsAgentTrigger = ref<HTMLButtonElement>()
-const activePage = ref<SettingsPage>('agent-identity')
+const activePage = ref<SettingsPage>('account-profile')
 const profileMenuOpen = ref(false)
 const mobileDetailOpen = ref(false)
 const updateLocked = ref(false)
@@ -101,14 +100,12 @@ const dirtyPages = reactive<Partial<Record<SettingsPage, boolean>>>({})
 const settingsQuery = ref('')
 const desktopModesAvailable = Boolean(window.yaoyaoDesktop?.modeState && window.yaoyaoDesktop?.switchMode)
 
-const agentItems = computed<NavigationItem[]>(() => !props.isAdmin || props.botMode ? [] : [
-  { key: 'agent-identity', label: '身份与头像', icon: 'users' },
-  ...(props.isAdmin ? [{ key: 'agent-models', label: '模型与 Provider', icon: 'model' } satisfies NavigationItem] : []),
-])
+// Bot mode is the only interface: base Profile identity and models are managed per Bot.
+const agentItems = computed<NavigationItem[]>(() => [])
 const accountItems = computed<NavigationItem[]>(() => [
   { key: 'account-profile', label: '账号资料', icon: 'users' },
   { key: 'account-security', label: '登录与安全', icon: 'settings' },
-  ...(props.botMode ? [{ key:'credential-vault',label:'密码管理',icon:'settings' } satisfies NavigationItem] : []),
+  { key:'credential-vault',label:'密码管理',icon:'settings' },
   ...(desktopModesAvailable ? [{ key: 'desktop-mode', label: '运行模式', icon: 'monitor' } satisfies NavigationItem] : []),
   { key: 'appearance', label: '外观', icon: 'sun' },
   ...(props.isAdmin ? [{ key: 'account-mobile', label: '手机登录', icon: 'panel' } satisfies NavigationItem] : []),
@@ -152,7 +149,7 @@ const activeTitle = computed(() => ({
   'system-update': '更新与回滚',
 })[activePage.value])
 const accountName = computed(() => props.pairingUserName || props.userName || '当前账号')
-const showAgentSelector = computed(() => !props.botMode && activePage.value.startsWith('agent-'))
+const showAgentSelector = computed(() => false)
 const activeScope = computed(() => {
   if (activePage.value.startsWith('agent-')) return `正在设置:${profileTitle(props.activeProfile)} / ${props.activeProfile?.name || '未选择'}`
   if (activePage.value === 'account-profile') return '管理你的账号头像与服务器名称。'
@@ -271,17 +268,13 @@ watch(() => [props.open, props.initialPage, props.botMode, props.isAdmin] as con
   }
   activePage.value = allAllowedPages.value.has(initialPage)
     ? initialPage
-    : !props.botMode && props.isAdmin && props.activeProfile ? 'agent-identity' : 'account-profile'
+    : 'account-profile'
   settingsQuery.value = ''
   for (const key of Object.keys(dirtyPages) as SettingsPage[]) dirtyPages[key] = false
   profileMenuOpen.value = false
   mobileDetailOpen.value = false
   void nextTick(() => dialog.value?.focus())
 }, { immediate: true })
-function requestModeSwitch() {
-  if (updateLocked.value || !confirmDiscard()) return
-  emit('switch-mode')
-}
 </script>
 
 <template>
@@ -335,7 +328,6 @@ function requestModeSwitch() {
                     <h3>基础机器人</h3>
                     <button v-for="item in visibleAgents" :key="item.key" type="button" :class="{ active: (activePage === item.key || (item.key === 'appearance' && activePage === 'chat-appearance')) }" :aria-current="(activePage === item.key || (item.key === 'appearance' && activePage === 'chat-appearance')) ? 'page' : undefined" @click="selectPage(item.key)"><AppIcon :name="item.icon" :size="18" /><span>{{ item.label }}</span></button>
                   </section>
-                  <section v-if="isAdmin && !settingsQuery"><button type="button" :disabled="updateLocked" @click="requestModeSwitch"><AppIcon :name="botMode ? 'chat' : 'users'" :size="18" /><span>{{ botMode ? '进入聊天模式' : '进入 Bot 模式' }}</span></button></section>
                   <p v-if="!visibleAccounts.length && (!isAdmin || !visibleSystems.length) && !visibleAgents.length" class="settings-search-empty">没有匹配的设置</p>
                 </nav>
               </div>
@@ -362,7 +354,7 @@ function requestModeSwitch() {
                 />
                 <p v-else-if="activePage === 'agent-identity'" class="settings-empty">尚未选择机器人。</p>
                 <ModelServicesPanel v-else-if="activePage === 'agent-models' && activeProfile && isAdmin && !botMode" :key="activeProfile.name" :profile="activeProfile.name" @dirty-change="setDirty('agent-models', $event)" />
-                <CredentialVaultPanel v-else-if="activePage === 'credential-vault' && botMode" />
+                <CredentialVaultPanel v-else-if="activePage === 'credential-vault'" />
                 <AccountSecurityPanel
                   v-else-if="activePage === 'account-security' || activePage === 'account-profile'"
                   :key="activePage"

+ 2 - 6
src/client/components/app/SystemOverviewPanel.vue

@@ -3,7 +3,6 @@ import { computed, ref, watch } from 'vue'
 import AppIcon from '@/components/common/AppIcon.vue'
 import { listUsers, type ManagedUser } from '@/api/admin'
 import { getDuplexVoiceSettings, type DuplexVoiceSettings } from '@/api/agentManagement'
-import { pairedDevices, type PairedDevicesResponse } from '@/api/pairing'
 import { getPushSystemStatus, type PushSystemStatus } from '@/api/push'
 import { systemUpdateStatus, type SystemUpdateStatus } from '@/api/systemUpdate'
 
@@ -22,7 +21,6 @@ const emit = defineEmits<{ navigate: [destination: Destination] }>()
 
 const users = ref<ManagedUser[]>()
 const push = ref<PushSystemStatus>()
-const devices = ref<PairedDevicesResponse>()
 const voice = ref<DuplexVoiceSettings>()
 const update = ref<SystemUpdateStatus>()
 const checking = ref(false)
@@ -49,16 +47,14 @@ async function refresh() {
   const results = await Promise.allSettled([
     listUsers(),
     getPushSystemStatus(),
-    pairedDevices(),
     getDuplexVoiceSettings(),
     // Publish local update status immediately, without waiting for 9119 panels.
     systemUpdateStatus().then(value => { update.value = value; return value }),
   ])
   if (results[0]?.status === 'fulfilled') users.value = results[0].value
   if (results[1]?.status === 'fulfilled') push.value = results[1].value
-  if (results[2]?.status === 'fulfilled') devices.value = results[2].value
-  if (results[3]?.status === 'fulfilled') voice.value = results[3].value
-  if (results[4]?.status === 'fulfilled') update.value = results[4].value
+  if (results[2]?.status === 'fulfilled') voice.value = results[2].value
+  if (results[3]?.status === 'fulfilled') update.value = results[3].value
   const failed = results.filter(result => result.status === 'rejected').length
   if (failed) error.value = failed === results.length ? '无法读取系统状态' : `${failed} 项状态暂时无法读取,可进入对应页面重试。`
   checking.value = false

+ 24 - 288
src/client/components/app/WorkspaceShell.vue

@@ -10,7 +10,6 @@ import type { ProfileIdentityInput } from '@/api/profiles'
 import AppIcon from '@/components/common/AppIcon.vue'
 import BrandMark from '@/components/common/BrandMark.vue'
 import SettingsCenterDialog from '@/components/app/SettingsCenterDialog.vue'
-import { rememberInterfacePath } from '@/utils/interfaceMode'
 import YaoYaoSidebarIcon from '@/components/common/YaoYaoSidebarIcon.vue'
 import DesktopUpdateEntry from './DesktopUpdateEntry.vue'
 import { useDesktopUpdate } from '@/composables/useDesktopUpdate'
@@ -19,13 +18,6 @@ const UpdateCheckDialog = defineAsyncComponent(() => import('./UpdateCheckDialog
 const BotPluginsDialog = defineAsyncComponent(() => import('@/components/workspace/BotPluginsDialog.vue'))
 const BotSettingsDialog = defineAsyncComponent(() => import('@/components/workspace/BotSettingsDialog.vue'))
 
-type NavItem = {
-  key: 'chat' | 'history' | 'groups' | 'files'
-  label: string
-  path: string
-  icon: 'chat' | 'history' | 'groups' | 'board' | 'files'
-}
-
 type SettingsPage =
   | 'agent-identity'
   | 'agent-models'
@@ -41,7 +33,6 @@ type SettingsPage =
   | 'system-voice'
   | 'system-update'
 
-const SIDEBAR_COLLAPSED_KEY = 'hermes-yaoyao:sidebar-collapsed'
 const SIDEBAR_SEARCH_EVENT = 'hermes-yaoyao:sidebar-search'
 const SIDEBAR_SEARCH_CLOSE_EVENT = 'hermes-yaoyao:sidebar-search-close'
 
@@ -112,7 +103,6 @@ function openUnread(event: MouseEvent) {
   const entry = unreadTrigger.getBoundingClientRect()
   const sidebar = unreadTrigger.closest('aside')!.getBoundingClientRect()
   unreadAnchor.value = { left: sidebar.right + 12, top: entry.top }
-  profileMenuOpen.value = false
   createMenuOpen.value = false
   settingsMenuOpen.value = false
   toolsMenuOpen.value = false
@@ -126,7 +116,6 @@ function closeUnread() {
 const route = useRoute()
 const router = useRouter()
 const mobileDrawerOpen = ref(false)
-const profileMenuOpen = ref(false)
 const settingsOpen = ref(false)
 const standalone = ref<'plugins' | 'about' | 'update' | 'bot-settings' | null>(null)
 const botSettingsPage = ref<'projects' | 'vm'>('projects')
@@ -135,8 +124,6 @@ const settingsPage = ref<SettingsPage>('agent-identity')
 const settingsReturnFocus = ref<HTMLButtonElement>()
 const mobileNavigationTrigger = ref<HTMLButtonElement>()
 const mobileDrawerClose = ref<HTMLButtonElement>()
-const profileMenuTrigger = ref<HTMLButtonElement>()
-const sidebarCollapsed = ref(false)
 const sidebarSearchOpen = ref(false)
 const createMenuOpen = ref(false)
 const createMenu = ref<HTMLElement | null>(null)
@@ -160,40 +147,8 @@ let toolsTrigger: HTMLButtonElement | null = null
 const desktopSidebarContext = ref<HTMLElement | null>(null)
 const mobileSidebarContext = ref<HTMLElement | null>(null)
 
-function profileTitle(profile?: Profile): string {
-  return profile?.agentName || profile?.displayName || profile?.name || '未选择机器人'
-}
-
-const navItems: NavItem[] = [
-  { key: 'chat', label: '聊天', path: '/chat', icon: 'chat' },
-  { key: 'history', label: '历史记录', path: '/history', icon: 'history' },
-  { key: 'groups', label: '聊天', path: '/conversations', icon: 'groups' },
-  { key: 'files', label: '文件库', path: '/files', icon: 'files' },
-]
-
-// The active workspace is already represented by its main canvas and sidebar
-// context. Keep this strip focused on destinations the user can switch to.
-const featureNavItems = computed(() => !props.isAdmin ? [] : navItems.filter(item => item.key !== 'groups' && item.key !== activeNav.value.key
- ))
-
-const applicationWorkspace = computed(() => route.path.startsWith('/conversations'))
-const activeNav = computed(() => {
-  const item = navItems.find(entry => route.path.startsWith(entry.path))
-  return item ?? navItems[0]
-})
-
-const contextHeading = computed(() => ({
-  chat: '聊天',
-  history: '历史记录',
-  groups: '聊天列表',
-  files: '历史记录',
-})[activeNav.value.key])
-
-const hasPrimaryAction = computed(() => ['chat', 'groups', 'files'].includes(activeNav.value.key))
-
 async function navigate(path: string) {
   mobileDrawerOpen.value = false
-  rememberInterfacePath(path)
   await router.push(path)
 }
 
@@ -209,7 +164,6 @@ function closeMobileDrawer() {
 
 function closeMenus(event: MouseEvent) {
   const target = event.target as HTMLElement
-  if (!target.closest('.sidebar-account-switcher')) profileMenuOpen.value = false
   if (!target.closest('.workspace-create-menu, .sidebar-create-trigger')) createMenuOpen.value = false
   if (!target.closest('.workspace-settings-menu, .sidebar-settings-trigger')) settingsMenuOpen.value = false
   if (!target.closest('.workspace-tools-menu, .sidebar-tools-trigger')) toolsMenuOpen.value = false
@@ -223,7 +177,6 @@ async function openCreateMenu(event: Event) {
   createTrigger = event.currentTarget as HTMLElement
   const rect = createTrigger.getBoundingClientRect()
   createPosition.value = { left: `${Math.max(8, Math.min(rect.left, window.innerWidth - 192))}px`, top: `${Math.max(8, Math.min(rect.bottom + 6, window.innerHeight - 96))}px` }
-  profileMenuOpen.value = false
   createMenuOpen.value = true
   await nextTick()
   createMenu.value?.querySelector<HTMLButtonElement>('[role="menuitem"]')?.focus()
@@ -252,7 +205,6 @@ async function openSettingsMenu(event: MouseEvent) {
   const rect = settingsTrigger.getBoundingClientRect()
   const height = ((props.isAdmin ? 4 : 3) + Number(canCheckUpdates.value)) * (window.innerWidth < 768 ? 44 : 36) + 18
   settingsMenuPosition.value = { left: `${Math.max(8, Math.min(rect.right - 180, window.innerWidth - 188))}px`, top: `${Math.max(8, rect.top - height)}px` }
-  profileMenuOpen.value = false
   createMenuOpen.value = false
   toolsMenuOpen.value = false
   updateError.value = ''
@@ -286,9 +238,8 @@ function openUpdateSettings() {
   standalone.value = null
   openSettings('system-update')
 }
-function chooseSettingsAction(action: 'settings' | 'bots' | 'about') {
+function chooseSettingsAction(action: 'settings' | 'about') {
   settingsMenuOpen.value = false
-  if (action === 'bots') { switchInterfaceMode(); return }
   settingsReturnFocus.value = settingsTrigger?.closest('.mobile-drawer')
     ? mobileNavigationTrigger.value : settingsTrigger ?? undefined
   if (action === 'about') {
@@ -297,12 +248,11 @@ function chooseSettingsAction(action: 'settings' | 'bots' | 'about') {
     standalone.value = 'about'
     return
   }
-  openSettings(applicationWorkspace.value ? 'account-profile' : 'agent-identity')
+  openSettings('account-profile')
 }
 function closeStandalone() { standalone.value = null; void nextTick(() => standaloneReturnFocus.value?.isConnected && standaloneReturnFocus.value.focus()) }
 function closeToolsMenu() { toolsMenuOpen.value = false; void nextTick(() => toolsTrigger?.isConnected && toolsTrigger.focus()) }
 async function openToolsMenu(event: MouseEvent) {
-  if (!applicationWorkspace.value) return
   if (toolsMenuOpen.value) { closeToolsMenu(); return }
   toolsTrigger = event.currentTarget as HTMLButtonElement
   const rect = toolsTrigger.getBoundingClientRect()
@@ -319,63 +269,20 @@ function chooseTool(page: 'apps' | 'automations' | 'bot-settings') {
   botSettingsPage.value = 'projects'
   standalone.value = page === 'bot-settings' ? 'bot-settings' : 'plugins'
 }
-function switchInterfaceMode() {
-  if (!props.isAdmin) return
-  settingsOpen.value = false
-  void navigate(applicationWorkspace.value ? '/chat' : '/conversations')
-}
 function workspaceKeydown(event: KeyboardEvent) {
-  if (!applicationWorkspace.value || !(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 'k' || settingsOpen.value || document.querySelector('dialog[open]')) return
+  if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 'k' || settingsOpen.value || document.querySelector('dialog[open]')) return
   event.preventDefault()
   if (sidebarSearchOpen.value) document.dispatchEvent(new CustomEvent(SIDEBAR_SEARCH_CLOSE_EVENT))
   else void openSidebarSearch(null)
 }
 
-function toggleProfileMenu(event: MouseEvent) {
-  const trigger = event.currentTarget
-  if (trigger instanceof HTMLButtonElement) profileMenuTrigger.value = trigger
-  profileMenuOpen.value = !profileMenuOpen.value
-  if (!profileMenuOpen.value) return
-  void nextTick(() => {
-    trigger instanceof HTMLElement
-      && trigger.closest('.sidebar-account-switcher')?.querySelector<HTMLButtonElement>('.profile-menu [role="option"][aria-selected="true"]')?.focus()
-  })
-}
-
-function chooseProfile(name: string) {
-  emit('selectProfile', name)
-  profileMenuOpen.value = false
-  void nextTick(() => profileMenuTrigger.value?.focus())
-}
-
-function handleProfileMenuKeydown(event: KeyboardEvent) {
-  const options = [...(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="option"]')]
-  if (!options.length) return
-  const current = Math.max(0, options.indexOf(document.activeElement as HTMLButtonElement))
-  let next: number | undefined
-  if (event.key === 'ArrowDown') next = (current + 1) % options.length
-  else if (event.key === 'ArrowUp') next = (current - 1 + options.length) % options.length
-  else if (event.key === 'Home') next = 0
-  else if (event.key === 'End') next = options.length - 1
-  else if (event.key === 'Escape') {
-    event.preventDefault()
-    profileMenuOpen.value = false
-    void nextTick(() => profileMenuTrigger.value?.focus())
-    return
-  }
-  if (next === undefined) return
-  event.preventDefault()
-  options[next]?.focus()
-}
-
-function openSettings(page: SettingsPage = 'agent-identity', event?: MouseEvent) {
+function openSettings(page: SettingsPage = 'account-profile', event?: MouseEvent) {
   const trigger = event?.currentTarget
   if (trigger instanceof HTMLButtonElement) {
     settingsReturnFocus.value = trigger.closest('.mobile-drawer')
       ? mobileNavigationTrigger.value
       : trigger
   }
-  profileMenuOpen.value = false
   toolsMenuOpen.value = false
   settingsMenuOpen.value = false
   mobileDrawerOpen.value = false
@@ -388,33 +295,10 @@ function closeSettings() {
   void nextTick(() => settingsReturnFocus.value?.focus())
 }
 
-function toggleSidebar() {
+async function openSidebarSearch(_host: HTMLElement | null) {
   createMenuOpen.value = false
-  settingsMenuOpen.value = false
-  sidebarCollapsed.value = !sidebarCollapsed.value
-  try { localStorage.setItem(SIDEBAR_COLLAPSED_KEY, sidebarCollapsed.value ? '1' : '0') } catch { /* optional persistence */ }
-}
-
-function navIcon(key: NavItem['key']): 'chat' | 'history' | 'folder' | 'people' | 'board' {
-  return key === 'groups' ? 'people' : key === 'files' ? 'folder' : key === 'history' ? 'history' : 'chat'
-}
-
-async function openSidebarSearch(host: HTMLElement | null) {
-  if (applicationWorkspace.value) {
-    createMenuOpen.value = false
-    sidebarSearchOpen.value = true
-    document.dispatchEvent(new CustomEvent(SIDEBAR_SEARCH_EVENT, { detail: { section: 'groups' } }))
-    return
-  }
-  if (sidebarCollapsed.value) {
-    sidebarCollapsed.value = false
-    try { localStorage.setItem(SIDEBAR_COLLAPSED_KEY, '0') } catch { /* optional persistence */ }
-    await nextTick()
-  }
   sidebarSearchOpen.value = true
-  document.dispatchEvent(new CustomEvent(SIDEBAR_SEARCH_EVENT, { detail: { section: activeNav.value.key } }))
-  await nextTick()
-  host?.querySelector<HTMLInputElement>('input[type="search"]')?.focus()
+  document.dispatchEvent(new CustomEvent(SIDEBAR_SEARCH_EVENT, { detail: { section: 'groups' } }))
 }
 
 async function closeSidebarSearch(host: HTMLElement | null, clear = false, restoreFocus = false) {
@@ -445,10 +329,6 @@ function handleSidebarFocusout(event: FocusEvent) {
 function handleSidebarSearchClosed() { sidebarSearchOpen.value = false }
 
 watch(() => route.fullPath, () => { mobileDrawerOpen.value = false; createMenuOpen.value = false; settingsMenuOpen.value = false; toolsMenuOpen.value = false; standalone.value = null })
-watch(() => activeNav.value.key, () => {
-  sidebarSearchOpen.value = false
-  profileMenuOpen.value = false
-})
 
 function showLocalVmSettings(){
   if(!props.isAdmin)return
@@ -458,7 +338,6 @@ function showLocalVmSettings(){
 }
 onMounted(() => {
   window.addEventListener('yaoyao:local-vm-settings',showLocalVmSettings)
-  try { sidebarCollapsed.value = localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1' } catch { /* optional persistence */ }
   document.addEventListener('mousedown', closeMenus)
   document.addEventListener(SIDEBAR_SEARCH_CLOSE_EVENT, handleSidebarSearchClosed)
   document.addEventListener('keydown', workspaceKeydown)
@@ -473,12 +352,12 @@ defineExpose({openLocalVm:showLocalVmSettings})
 </script>
 
 <template>
-  <div class="workspace-shell" :data-desktop-update-inline="desktopUpdate.supported ? '' : undefined" :class="{ 'workspace-shell--collapsed': sidebarCollapsed && !applicationWorkspace, 'workspace-shell--sidebar-focused': sidebarFocusMode, 'workspace-shell--conversations': applicationWorkspace, 'workspace-shell--conversation-open': applicationWorkspace && !!route.params.id }" :inert="(unreadOpen || settingsOpen || !!standalone || (applicationWorkspace && sidebarSearchOpen)) ? true : undefined">
+  <div class="workspace-shell" :data-desktop-update-inline="desktopUpdate.supported ? '' : undefined" :class="{ 'workspace-shell--sidebar-focused': sidebarFocusMode, 'workspace-shell--conversations': true, 'workspace-shell--conversation-open': !!route.params.id }" :inert="(unreadOpen || settingsOpen || !!standalone || sidebarSearchOpen) ? true : undefined">
     <header class="mobile-header" :inert="mobileDrawerOpen">
       <button ref="mobileNavigationTrigger" class="icon-button" type="button" aria-label="打开导航" @click="openMobileDrawer">
         <AppIcon name="menu" :size="20" />
       </button>
-      <button class="mobile-brand" type="button" aria-label="返回聊天" @click="navigate(applicationWorkspace ? '/conversations' : '/chat')">
+      <button class="mobile-brand" type="button" aria-label="返回聊天" @click="navigate('/conversations')">
         <BrandMark :size="28" compact />
       </button>
       <button class="icon-button" type="button" :aria-label="theme === 'dark' ? '切换浅色主题' : '切换深色主题'" @click="emit('toggleTheme')">
@@ -488,11 +367,10 @@ defineExpose({openLocalVm:showLocalVmSettings})
 
     <aside
       class="desktop-sidebar rail"
-      :class="{ 'desktop-sidebar--collapsed': sidebarCollapsed && !applicationWorkspace }"
       aria-label="主导航"
       :inert="mobileDrawerOpen"
     >
-      <div v-if="applicationWorkspace" class="bot-list-header">
+      <div class="bot-list-header">
         <button class="bot-logo-trigger sidebar-brand" type="button" aria-label="返回 Bot 列表" title="夭夭 AI" @click="navigate('/conversations')"><BrandMark :size="32" :label="false" compact bare /></button>
         <span class="bot-list-header__spacer" />
         <button class="bot-list-toolbar-button unread-entry" type="button" :aria-label="`未读消息,${unread.total} 条`" aria-haspopup="dialog" aria-controls="unread-center" :aria-expanded="unreadOpen" title="未读消息" @click="openUnread">
@@ -503,65 +381,10 @@ defineExpose({openLocalVm:showLocalVmSettings})
         <button class="bot-list-toolbar-button sidebar-search-trigger" type="button" aria-label="搜索" :aria-expanded="sidebarSearchOpen" @click="openSidebarSearch(desktopSidebarContext)"><AppIcon name="search" :size="21" /></button>
         <button class="bot-list-toolbar-button sidebar-create-trigger" type="button" aria-label="新建" aria-haspopup="menu" :aria-expanded="createMenuOpen" @click="openCreateMenu"><AppIcon name="plus" :size="23" /></button>
       </div>
-      <div v-else class="sidebar-brand-row">
-        <button class="rail__brand sidebar-brand" type="button" aria-label="返回聊天" title="夭夭 AI" @click="navigate(applicationWorkspace ? '/conversations' : '/chat')">
-          <BrandMark :size="sidebarCollapsed ? 26 : 32" :label="false" compact bare />
-        </button>
-        <div class="sidebar-status-actions">
-          <button class="unread-entry" type="button" :aria-label="`未读消息,${unread.total} 条`" aria-haspopup="dialog" aria-controls="unread-center" :aria-expanded="unreadOpen" title="未读消息" @click="openUnread">
-            <AppIcon name="bell" :size="20" />
-            <b v-if="unread.total" class="unread-entry__count" aria-hidden="true">{{ unread.total > 99 ? '99+' : unread.total }}</b>
-          </button>
-          <DesktopUpdateEntry v-if="desktopUpdate.supported && desktopUpdateVisible" :state="desktopUpdateState" :pending="desktopUpdatePending" :error="desktopUpdateError" @activate="desktopUpdate.run()" />
-        </div>
-      </div>
-      <button
-        v-if="!applicationWorkspace"
-        class="sidebar-collapse"
-        :class="{ 'sidebar-collapse--collapsed': sidebarCollapsed }"
-        type="button"
-        :aria-label="sidebarCollapsed ? '展开侧边栏' : '折叠侧边栏'"
-        :title="sidebarCollapsed ? '展开侧边栏' : '折叠侧边栏'"
-        @click="toggleSidebar"
-      >
-        <AppIcon name="chevron-left" :size="18" />
-      </button>
 
 
-      <button
-        v-if="!applicationWorkspace && activeNav.key !== 'files'"
-        class="sidebar-search-trigger"
-        :class="{ 'sidebar-search-trigger--searching': sidebarSearchOpen && !applicationWorkspace }"
-        type="button"
-        aria-label="搜索"
-        title="搜索"
-        :aria-expanded="sidebarSearchOpen"
-        :aria-hidden="sidebarSearchOpen && !applicationWorkspace ? 'true' : undefined"
-        :tabindex="sidebarSearchOpen && !applicationWorkspace ? -1 : 0"
-        @click="openSidebarSearch(desktopSidebarContext)"
-      >
-        <YaoYaoSidebarIcon name="search" />
-        <span>搜索</span>
-      </button>
 
-      <div v-if="hasPrimaryAction && !applicationWorkspace" class="sidebar-primary-action">
-        <slot name="sidebar-action" />
-      </div>
 
-      <nav v-if="!applicationWorkspace" class="sidebar-feature-nav" aria-label="功能入口">
-        <button
-          v-for="item in featureNavItems"
-          :key="item.key"
-          type="button"
-          :class="{ active: activeNav.key === item.key }"
-          :aria-current="activeNav.key === item.key ? 'page' : undefined"
-          :title="item.label"
-          @click="navigate(item.path)"
-        >
-          <YaoYaoSidebarIcon :name="navIcon(item.key)" />
-          <span>{{ item.label }}</span>
-        </button>
-      </nav>
 
       <section
         ref="desktopSidebarContext"
@@ -572,48 +395,21 @@ defineExpose({openLocalVm:showLocalVmSettings})
         @focusout.capture="handleSidebarFocusout"
       >
         <slot name="sidebar-before-heading" />
-        <header v-if="!applicationWorkspace" class="sidebar-context__heading">
-          <strong>{{ sidebarContextTitle || contextHeading }}</strong>
-          <span v-if="sidebarSubtitle">{{ sidebarSubtitle }}</span>
-        </header>
         <div class="sidebar-context__body">
           <slot name="sidebar" />
         </div>
       </section>
 
       <div class="sidebar-footer">
-        <button v-if="applicationWorkspace" class="sidebar-tools-trigger" type="button" aria-haspopup="menu" :aria-expanded="toolsMenuOpen" @click="openToolsMenu"><YaoYaoSidebarIcon name="tools" :size="18" /><span>工具</span><AppIcon name="chevron-down" :size="15" /></button>
+        <button class="sidebar-tools-trigger" type="button" aria-haspopup="menu" :aria-expanded="toolsMenuOpen" @click="openToolsMenu"><YaoYaoSidebarIcon name="tools" :size="18" /><span>工具</span><AppIcon name="chevron-down" :size="15" /></button>
         <div class="sidebar-account-switcher">
-          <button class="sidebar-account-switcher__main" type="button" :title="applicationWorkspace ? '当前账号' : `切换机器人:${profileTitle(activeProfile)}`" :aria-haspopup="applicationWorkspace ? 'menu' : 'listbox'" :aria-expanded="applicationWorkspace ? settingsMenuOpen : profileMenuOpen" @click="applicationWorkspace ? openSettingsMenu($event) : toggleProfileMenu($event)">
-            <AccountInitialAvatar v-if="applicationWorkspace" :name="userName" :image-url="userAvatar" :size="30" />
-            <AgentAvatar v-else :name="profileTitle(activeProfile)" :avatar="activeProfile?.agentAvatar || ''" :size="30" />
+          <button class="sidebar-account-switcher__main" type="button" :title="'当前账号'" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu($event)">
+            <AccountInitialAvatar :name="userName" :image-url="userAvatar" :size="30" />
             <span class="account-copy">
-              <strong>{{ applicationWorkspace ? userName : profileTitle(activeProfile) }}</strong>
-              <span>{{ serverName || (applicationWorkspace ? '当前账号' : activeProfile?.name || userName || '未选择机器人') }}</span>
+              <strong>{{ userName }}</strong>
+              <span>{{ serverName || '当前账号' }}</span>
             </span>
-            <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
           </button>
-          <button v-if="!applicationWorkspace" class="sidebar-settings-trigger" type="button" title="设置与模式" aria-label="设置与模式" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu">
-            <AppIcon name="settings" :size="17" />
-          </button>
-          <Transition name="menu-fade">
-            <div v-if="profileMenuOpen" class="profile-menu" role="listbox" aria-label="切换机器人" @keydown="handleProfileMenuKeydown">
-              <strong class="profile-menu__heading">切换机器人</strong>
-              <button
-                v-for="profile in profiles"
-                :key="profile.name"
-                type="button"
-                role="option"
-                :class="{ active: profile.name === activeProfile?.name }"
-                :aria-selected="profile.name === activeProfile?.name"
-                @click="chooseProfile(profile.name)"
-              >
-                <AgentAvatar :name="profileTitle(profile)" :avatar="profile.agentAvatar || ''" :size="24" />
-                <strong>{{ profileTitle(profile) }}</strong>
-                <AppIcon v-if="profile.name === activeProfile?.name" name="check" :size="15" />
-              </button>
-            </div>
-          </Transition>
         </div>
       </div>
     </aside>
@@ -629,47 +425,16 @@ defineExpose({openLocalVm:showLocalVmSettings})
       :inert="!mobileDrawerOpen"
     >
       <div class="mobile-drawer__header">
-        <button class="sidebar-brand" type="button" aria-label="返回聊天" @click="navigate(applicationWorkspace ? '/conversations' : '/chat')">
+        <button class="sidebar-brand" type="button" aria-label="返回聊天" @click="navigate('/conversations')">
           <BrandMark :size="32" compact />
         </button>
         <div class="mobile-drawer__actions"><DesktopUpdateEntry v-if="desktopUpdate.supported && desktopUpdateVisible" :state="desktopUpdateState" :pending="desktopUpdatePending" :error="desktopUpdateError" @activate="desktopUpdate.run()" /><button ref="mobileDrawerClose" class="icon-button" type="button" aria-label="关闭导航" @click="closeMobileDrawer">
           <AppIcon name="close" />
-        </button><button v-if="applicationWorkspace" class="sidebar-create-trigger" type="button" aria-label="新建" title="新建" aria-haspopup="menu" :aria-expanded="createMenuOpen" @click="openCreateMenu"><AppIcon name="plus" :size="19" /></button></div>
+        </button><button class="sidebar-create-trigger" type="button" aria-label="新建" title="新建" aria-haspopup="menu" :aria-expanded="createMenuOpen" @click="openCreateMenu"><AppIcon name="plus" :size="19" /></button></div>
       </div>
 
-      <button
-        v-if="!applicationWorkspace && activeNav.key !== 'files'"
-        class="sidebar-search-trigger"
-        :class="{ 'sidebar-search-trigger--searching': sidebarSearchOpen && !applicationWorkspace }"
-        type="button"
-        aria-label="搜索"
-        title="搜索"
-        :aria-expanded="sidebarSearchOpen"
-        :aria-hidden="sidebarSearchOpen && !applicationWorkspace ? 'true' : undefined"
-        :tabindex="sidebarSearchOpen && !applicationWorkspace ? -1 : 0"
-        @click="openSidebarSearch(mobileSidebarContext)"
-      >
-        <AppIcon name="search" :size="18" />
-        <span>搜索</span>
-      </button>
 
-      <div v-if="hasPrimaryAction && !applicationWorkspace" class="sidebar-primary-action">
-        <slot name="sidebar-action" />
-      </div>
 
-      <nav v-if="!applicationWorkspace" class="sidebar-feature-nav" aria-label="功能入口">
-        <button
-          v-for="item in featureNavItems"
-          :key="item.key"
-          type="button"
-          :class="{ active: activeNav.key === item.key }"
-          :aria-current="activeNav.key === item.key ? 'page' : undefined"
-          @click="navigate(item.path)"
-        >
-          <AppIcon :name="item.icon" :size="18" />
-          <span>{{ item.label }}</span>
-        </button>
-      </nav>
 
       <section
         ref="mobileSidebarContext"
@@ -680,48 +445,21 @@ defineExpose({openLocalVm:showLocalVmSettings})
         @focusout.capture="handleSidebarFocusout"
       >
         <slot name="sidebar-before-heading" />
-        <header v-if="!applicationWorkspace" class="sidebar-context__heading">
-          <strong>{{ sidebarContextTitle || contextHeading }}</strong>
-          <span v-if="sidebarSubtitle">{{ sidebarSubtitle }}</span>
-        </header>
         <div class="sidebar-context__body">
           <slot name="mobile-sidebar" />
         </div>
       </section>
 
       <div class="sidebar-footer mobile-drawer__footer">
-        <button v-if="applicationWorkspace" class="sidebar-tools-trigger" type="button" aria-haspopup="menu" :aria-expanded="toolsMenuOpen" @click="openToolsMenu"><YaoYaoSidebarIcon name="tools" :size="18" /><span>工具</span><AppIcon name="chevron-down" :size="15" /></button>
+        <button class="sidebar-tools-trigger" type="button" aria-haspopup="menu" :aria-expanded="toolsMenuOpen" @click="openToolsMenu"><YaoYaoSidebarIcon name="tools" :size="18" /><span>工具</span><AppIcon name="chevron-down" :size="15" /></button>
         <div class="sidebar-account-switcher">
-          <button class="sidebar-account-switcher__main" type="button" :title="applicationWorkspace ? '当前账号' : `切换机器人:${profileTitle(activeProfile)}`" :aria-haspopup="applicationWorkspace ? 'menu' : 'listbox'" :aria-expanded="applicationWorkspace ? settingsMenuOpen : profileMenuOpen" @click="applicationWorkspace ? openSettingsMenu($event) : toggleProfileMenu($event)">
-            <AccountInitialAvatar v-if="applicationWorkspace" :name="userName" :image-url="userAvatar" :size="30" />
-            <AgentAvatar v-else :name="profileTitle(activeProfile)" :avatar="activeProfile?.agentAvatar || ''" :size="30" />
+          <button class="sidebar-account-switcher__main" type="button" :title="'当前账号'" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu($event)">
+            <AccountInitialAvatar :name="userName" :image-url="userAvatar" :size="30" />
             <span class="account-copy">
-              <strong>{{ applicationWorkspace ? userName : profileTitle(activeProfile) }}</strong>
-              <span>{{ serverName || (applicationWorkspace ? '当前账号' : activeProfile?.name || userName || '未选择机器人') }}</span>
+              <strong>{{ userName }}</strong>
+              <span>{{ serverName || '当前账号' }}</span>
             </span>
-            <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
-          </button>
-          <button v-if="!applicationWorkspace" class="sidebar-settings-trigger" type="button" title="设置与模式" aria-label="设置与模式" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu">
-            <AppIcon name="settings" :size="17" />
           </button>
-          <Transition name="menu-fade">
-            <div v-if="profileMenuOpen" class="profile-menu" role="listbox" aria-label="切换机器人" @keydown="handleProfileMenuKeydown">
-              <strong class="profile-menu__heading">切换机器人</strong>
-              <button
-                v-for="profile in profiles"
-                :key="profile.name"
-                type="button"
-                role="option"
-                :class="{ active: profile.name === activeProfile?.name }"
-                :aria-selected="profile.name === activeProfile?.name"
-                @click="chooseProfile(profile.name)"
-              >
-                <AgentAvatar :name="profileTitle(profile)" :avatar="profile.agentAvatar || ''" :size="24" />
-                <strong>{{ profileTitle(profile) }}</strong>
-                <AppIcon v-if="profile.name === activeProfile?.name" name="check" :size="15" />
-              </button>
-            </div>
-          </Transition>
         </div>
       </div>
     </aside>
@@ -743,12 +481,11 @@ defineExpose({openLocalVm:showLocalVmSettings})
 
     <AboutDialog v-if="standalone === 'about'" @close="closeStandalone" />
     <UpdateCheckDialog v-if="standalone === 'update' && isAdmin" @close="closeStandalone" @manage="openUpdateSettings" />
-    <BotPluginsDialog v-if="standalone === 'plugins' && applicationWorkspace" @close="closeStandalone" />
+    <BotPluginsDialog v-if="standalone === 'plugins'" @close="closeStandalone" />
     <BotSettingsDialog v-if="standalone === 'bot-settings'" :is-admin="isAdmin" :initial-page="botSettingsPage" @close="closeStandalone" @changed="emit('botSettingsChanged')" />
     <SettingsCenterDialog
       :open="settingsOpen"
-      :bot-mode="applicationWorkspace"
-      @switch-mode="switchInterfaceMode"
+      :bot-mode="true"
       :initial-page="settingsPage"
       :user-name="userName"
       :user-avatar="userAvatar"
@@ -780,10 +517,9 @@ defineExpose({openLocalVm:showLocalVmSettings})
           <p v-if="updateError" class="update-menu-error" role="alert">{{ updateError }}</p>
           <p v-if="desktopUpdate.supported && (desktopUpdateError || desktopUpdateState?.error)" class="update-menu-error" role="alert">{{ desktopUpdateError || desktopUpdateState?.error }}</p>
           <a role="menuitem" href="https://yaoyao.samien.cn" target="_blank" rel="noopener noreferrer" @click="closeSettingsMenu"><AppIcon name="external" :size="17" />帮助</a>
-          <button v-if="isAdmin" type="button" role="menuitem" @click="chooseSettingsAction('bots')"><AppIcon :name="applicationWorkspace ? 'chat' : 'users'" :size="17" />{{ applicationWorkspace ? '进入聊天模式' : '进入 Bot 模式' }}</button>
         </div>
       </div>
-      <div v-if="toolsMenuOpen && applicationWorkspace" class="workspace-create-dismiss" @pointerdown.self="closeToolsMenu" @keydown.esc.prevent.stop="closeToolsMenu"><div ref="toolsMenu" class="workspace-create-menu workspace-tools-menu" :style="toolsPosition" role="menu" aria-label="工具" @keydown="actionMenuKeydown"><button type="button" role="menuitem" @click="chooseTool('bot-settings')"><AppIcon name="settings" :size="17" />Bot 设置</button><button type="button" role="menuitem" @click="chooseTool('automations')"><AppIcon name="clock" :size="17" />自动化</button><button type="button" role="menuitem" @click="chooseTool('apps')"><AppIcon name="link" :size="17" />已连接应用</button></div></div>
+      <div v-if="toolsMenuOpen" class="workspace-create-dismiss" @pointerdown.self="closeToolsMenu" @keydown.esc.prevent.stop="closeToolsMenu"><div ref="toolsMenu" class="workspace-create-menu workspace-tools-menu" :style="toolsPosition" role="menu" aria-label="工具" @keydown="actionMenuKeydown"><button type="button" role="menuitem" @click="chooseTool('bot-settings')"><AppIcon name="settings" :size="17" />Bot 设置</button><button type="button" role="menuitem" @click="chooseTool('automations')"><AppIcon name="clock" :size="17" />自动化</button><button type="button" role="menuitem" @click="chooseTool('apps')"><AppIcon name="link" :size="17" />已连接应用</button></div></div>
       <div v-if="createMenuOpen" class="workspace-create-dismiss" @pointerdown.self="closeCreateMenu" @keydown.esc.prevent.stop="closeCreateMenu">
         <div ref="createMenu" class="workspace-create-menu" :style="createPosition" role="menu" aria-label="新建聊天" @keydown="actionMenuKeydown">
           <button type="button" role="menuitem" @click="chooseCreate('agent')"><AppIcon name="users" :size="17" />新建 Bot</button>

+ 0 - 6
src/client/components/common/types.ts

@@ -1,6 +0,0 @@
-export type ChoiceOption = {
-  id: string
-  label: string
-  description?: string
-  disabled?: boolean
-}

+ 0 - 150
src/client/components/composer/ModelChoiceDialog.vue

@@ -1,150 +0,0 @@
-<script setup lang="ts">
-import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
-import type { ModelOption } from '@shared/types'
-import AppIcon from '@/components/common/AppIcon.vue'
-
-const props = withDefaults(defineProps<{
-  open: boolean
-  options: ModelOption[]
-  selectedId?: string
-  busy?: boolean
-}>(), { selectedId: '', busy: false })
-
-const emit = defineEmits<{ close: []; select: [id: string] }>()
-const search = ref('')
-const searchInput = ref<HTMLInputElement | null>(null)
-const collapsedProviders = ref<Record<string, boolean>>({})
-
-const PROVIDER_LABELS: Record<string, string> = {
-  anthropic: 'Anthropic', google: 'Google', groq: 'Groq', minimax: 'MiniMax',
-  mistral: 'Mistral', ollama: 'Ollama', openai: 'OpenAI', openrouter: 'OpenRouter', xai: 'xAI',
-}
-
-function modelId(option: ModelOption): string { return `${option.provider}:${option.id}` }
-
-function providerLabel(provider: string): string {
-  const key = provider.toLocaleLowerCase()
-  return PROVIDER_LABELS[key] || provider.replace(/[-_]+/g, ' ').replace(/\b\w/g, value => value.toLocaleUpperCase())
-}
-
-const groups = computed(() => {
-  const query = search.value.trim().toLocaleLowerCase()
-  const grouped = new Map<string, ModelOption[]>()
-  for (const option of props.options) {
-    const haystack = `${option.name} ${option.id} ${option.provider}`.toLocaleLowerCase()
-    if (query && !haystack.includes(query)) continue
-    const items = grouped.get(option.provider) ?? []
-    items.push(option)
-    grouped.set(option.provider, items)
-  }
-  return [...grouped].map(([provider, models]) => ({ provider, label: providerLabel(provider), models }))
-})
-
-function close(): void { if (!props.busy) emit('close') }
-
-function toggleProvider(provider: string): void {
-  if (props.busy) return
-  collapsedProviders.value = { ...collapsedProviders.value, [provider]: !collapsedProviders.value[provider] }
-}
-
-function onKeydown(event: KeyboardEvent): void {
-  if (props.open && event.key === 'Escape') close()
-}
-
-watch(() => props.open, async open => {
-  if (!open) return
-  search.value = ''
-  collapsedProviders.value = {}
-  await nextTick()
-  searchInput.value?.focus()
-})
-
-onMounted(() => window.addEventListener('keydown', onKeydown))
-onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
-</script>
-
-<template>
-  <Teleport to="body">
-    <Transition name="model-dialog-fade">
-      <div v-if="open" class="model-dialog-layer" role="presentation" @mousedown.self="close">
-        <section class="model-dialog" role="dialog" aria-modal="true" aria-labelledby="model-dialog-title" :aria-busy="busy">
-          <header class="model-dialog__header">
-            <h2 id="model-dialog-title">选择模型</h2>
-            <button class="icon-button" type="button" aria-label="关闭模型选择" :disabled="busy" @click="close"><AppIcon name="close" :size="15" /></button>
-          </header>
-
-          <label class="model-dialog__search">
-            <AppIcon name="search" :size="14" />
-            <input ref="searchInput" v-model="search" type="search" placeholder="搜索模型名称或 ID" :disabled="busy" autocomplete="off" />
-          </label>
-
-          <div class="model-dialog__list">
-            <section v-for="group in groups" :key="group.provider" class="model-dialog__group">
-              <button class="model-dialog__group-header" type="button" :aria-expanded="!collapsedProviders[group.provider]" :disabled="busy" @click="toggleProvider(group.provider)">
-                <AppIcon class="model-dialog__chevron" :class="{ collapsed: collapsedProviders[group.provider] }" name="chevron-down" :size="13" />
-                <strong>{{ group.label }}</strong><span>{{ group.models.length }}</span>
-              </button>
-              <div v-show="!collapsedProviders[group.provider]" class="model-dialog__items">
-                <button v-for="model in group.models" :key="modelId(model)" class="model-dialog__item" :class="{ 'model-dialog__item--active': modelId(model) === selectedId }" type="button" :disabled="busy" @click="emit('select', modelId(model))">
-                  <span class="model-dialog__item-label">
-                    <strong>{{ model.name || model.id }}</strong>
-                    <small v-if="model.name && model.name !== model.id">{{ model.id }}</small>
-                  </span>
-                  <span v-if="model.isDefault" class="model-dialog__badge">默认</span>
-                  <span v-if="model.supportsReasoning" class="model-dialog__badge model-dialog__badge--quiet">推理</span>
-                  <AppIcon v-if="modelId(model) === selectedId" class="model-dialog__check" name="check" :size="15" />
-                </button>
-              </div>
-            </section>
-            <p v-if="!groups.length" class="model-dialog__empty">没有匹配的模型</p>
-          </div>
-          <p v-if="busy" class="model-dialog__status" role="status">正在切换模型…</p>
-        </section>
-      </div>
-    </Transition>
-  </Teleport>
-</template>
-
-<style scoped>
-.model-dialog-layer { position: fixed; z-index: 230; inset: 0; display: grid; place-items: center; padding: 16px; background: var(--scrim); backdrop-filter: blur(4px); }
-.model-dialog { display: flex; width: min(480px, calc(100vw - 32px)); max-height: min(650px, calc(100dvh - 32px)); padding: 12px; overflow: hidden; border: 1px solid var(--line); border-radius: 16px; background: var(--surface-raised); box-shadow: var(--shadow-float); flex-direction: column; }
-.model-dialog__header { display: flex; min-height: 42px; align-items: center; justify-content: space-between; padding: 0 2px 7px 8px; }
-.model-dialog__header h2 { margin: 0; color: var(--text-primary); font-size: 14px; font-weight: 650; letter-spacing: -.02em; }
-.model-dialog__header .icon-button { display: grid; width: 32px; height: 32px; place-items: center; padding: 0; border: 0; border-radius: 9px; background: transparent; color: var(--text-muted); cursor: pointer; }
-.model-dialog__header .icon-button:hover { background: var(--surface-soft); color: var(--text-primary); }
-.model-dialog__header .icon-button:disabled { cursor: wait; opacity: .45; }
-.model-dialog__search { display: flex; min-height: 38px; align-items: center; gap: 8px; margin: 0 4px 10px; padding: 0 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); color: var(--text-muted); transition: border-color 120ms ease, box-shadow 120ms ease; }
-.model-dialog__search:focus-within { border-color: var(--input-border-focus-color); box-shadow: 0 0 0 3px var(--focus-ring); }
-.model-dialog__search input { min-width: 0; flex: 1; padding: 0; border: 0; outline: 0; background: transparent; color: var(--text-primary); font: 12px var(--font-ui); }
-.model-dialog__search input::placeholder { color: var(--input-placeholder-color); }
-.model-dialog__list { min-height: 148px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; }
-.model-dialog__group { margin-bottom: 4px; }
-.model-dialog__group-header { display: flex; width: 100%; min-height: 34px; align-items: center; gap: 6px; padding: 6px 8px; border: 0; border-radius: 8px; background: transparent; color: var(--text-secondary); cursor: pointer; text-align: left; }
-.model-dialog__group-header:hover { background: var(--surface-soft); }
-.model-dialog__group-header:disabled { cursor: wait; }
-.model-dialog__group-header strong { min-width: 0; flex: 1; font-size: 11px; font-weight: 650; }
-.model-dialog__group-header span { color: var(--text-muted); font-size: 10px; font-weight: 450; }
-.model-dialog__chevron { flex: 0 0 auto; transition: transform 120ms ease; }
-.model-dialog__chevron.collapsed { transform: rotate(-90deg); }
-.model-dialog__items { padding-left: 8px; }
-.model-dialog__item { display: flex; width: 100%; min-height: 40px; align-items: center; gap: 7px; padding: 6px 10px; border: 0; border-radius: 8px; background: transparent; color: var(--text-secondary); cursor: pointer; text-align: left; transition: background-color 120ms ease, color 120ms ease; }
-.model-dialog__item:hover { background: color-mix(in srgb, #1677ff 7%, transparent); color: var(--text-primary); }
-.model-dialog__item:disabled { cursor: wait; opacity: .58; }
-.model-dialog__item--active { color: #1677ff; font-weight: 550; }
-.dark .model-dialog__item--active { color: #69a7ff; }
-.model-dialog__item-label { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 2px; }
-.model-dialog__item-label strong, .model-dialog__item-label small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--font-code); }
-.model-dialog__item-label strong { font-size: 11px; font-weight: inherit; }
-.model-dialog__item-label small { color: var(--text-muted); font-size: 9px; font-weight: 400; }
-.model-dialog__badge { flex: 0 0 auto; padding: 2px 5px; border-radius: 4px; background: #1677ff; color: #fff; font-size: 8px; font-weight: 650; }
-.model-dialog__badge--quiet { border: 1px solid var(--line); background: transparent; color: var(--text-muted); }
-.model-dialog__check { flex: 0 0 auto; color: currentColor; }
-.model-dialog__empty { margin: 0; padding: 32px 10px; color: var(--text-muted); font-size: 11px; text-align: center; }
-.model-dialog__status { margin: 7px 8px 0; color: var(--text-muted); font-size: 9px; text-align: right; }
-.model-dialog-fade-enter-active, .model-dialog-fade-leave-active { transition: opacity 130ms ease; }
-.model-dialog-fade-enter-active .model-dialog, .model-dialog-fade-leave-active .model-dialog { transition: transform 160ms var(--ease-out); }
-.model-dialog-fade-enter-from, .model-dialog-fade-leave-to { opacity: 0; }
-.model-dialog-fade-enter-from .model-dialog, .model-dialog-fade-leave-to .model-dialog { transform: translateY(7px) scale(.99); }
-@media (max-width: 600px) { .model-dialog-layer { padding: 12px; }.model-dialog { width: min(480px, calc(100vw - 24px)); max-height: calc(100dvh - 24px); }.model-dialog__items { padding-left: 3px; } }
-@media (prefers-reduced-motion: reduce) { .model-dialog-fade-enter-active, .model-dialog-fade-leave-active, .model-dialog-fade-enter-active .model-dialog, .model-dialog-fade-leave-active .model-dialog, .model-dialog__chevron { transition: none; } }
-</style>

+ 0 - 97
src/client/components/library/LibraryGrid.vue

@@ -1,97 +0,0 @@
-<script setup lang="ts">
-import AppIcon from '@/components/common/AppIcon.vue'
-import EmptyState from '@/components/common/EmptyState.vue'
-import type { UiLibraryItem } from './types'
-
-withDefaults(defineProps<{
-  items: UiLibraryItem[]
-  selectedId?: string
-  loading?: boolean
-  hasMore?: boolean
-  emptyTitle?: string
-  emptyDescription?: string
-  kind?: 'files' | 'artifacts'
-}>(), {
-  selectedId: '', loading: false, hasMore: false, emptyTitle: '暂无文件', emptyDescription: '这里会显示来自 Hermes 的文件。', kind: 'files',
-})
-
-const emit = defineEmits<{
-  select: [item: UiLibraryItem]
-  loadMore: []
-  addToComposer: [item: UiLibraryItem]
-  source: [item: UiLibraryItem]
-}>()
-
-function iconFor(item: UiLibraryItem) {
-  if (item.kind === 'document' || item.kind === 'pdf' || item.kind === 'code' || item.kind === 'text') return 'file'
-  return item.kind
-}
-
-function kindLabel(item: UiLibraryItem) {
-  return ({ image: '图片', video: '视频', audio: '音频', pdf: '文档', document: '文档', code: '文档', text: '文档', link: '网页', file: '其他' } as const)[item.kind]
-}
-
-function formatSize(size?: number) {
-  if (size === undefined) return ''
-  if (size < 1024) return `${size} B`
-  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
-  return `${(size / 1024 / 1024).toFixed(1)} MB`
-}
-
-function formatDate(value?: string | number | Date) {
-  if (!value) return ''
-  const date = value instanceof Date ? value : new Date(value)
-  if (Number.isNaN(date.getTime())) return ''
-  return new Intl.DateTimeFormat('zh-CN', { month: 'short', day: 'numeric' }).format(date)
-}
-</script>
-
-<template>
-  <div class="library-scroll">
-    <div v-if="loading && !items.length" class="library-skeleton">
-      <i v-for="n in 10" :key="n" :style="{ opacity: .95 - n * .04 }" />
-    </div>
-    <EmptyState v-else-if="!items.length" :icon="kind === 'files' ? 'files' : 'artifacts'" :title="emptyTitle" :description="emptyDescription" />
-    <div v-else class="library-grid">
-      <article
-        v-for="item in items"
-        :key="item.id"
-        :class="{ selected: item.id === selectedId }"
-        tabindex="0"
-        @click="emit('select', item)"
-        @keydown.enter="emit('select', item)"
-      >
-        <div class="library-thumb" :class="`library-thumb--${item.kind}`">
-          <img v-if="item.kind === 'image' && item.previewUrl" :src="item.previewUrl" :alt="item.name" loading="lazy" />
-          <video v-else-if="item.kind === 'video' && item.previewUrl" :src="item.previewUrl" muted preload="metadata" />
-          <span v-else><AppIcon :name="iconFor(item)" :size="36" /><em>{{ item.name.split('.').at(-1)?.slice(0, 5).toUpperCase() }} · {{ kindLabel(item) }}</em></span>
-          <div class="library-thumb__actions">
-            <button type="button" title="加入输入框" aria-label="加入输入框" @click.stop="emit('addToComposer', item)"><AppIcon name="plus" :size="14" /></button>
-            <button v-if="item.sourceSessionId" type="button" title="查看来源" aria-label="查看来源" @click.stop="emit('source', item)"><AppIcon name="external" :size="14" /></button>
-          </div>
-        </div>
-        <div class="library-copy">
-          <strong :title="item.name">{{ item.title || item.name }}</strong>
-          <span><small>{{ item.sourceLabel || formatSize(item.size) || item.kind }}</small><time>{{ formatDate(item.updatedAt || item.createdAt) }}</time></span>
-        </div>
-      </article>
-    </div>
-    <button v-if="hasMore" class="load-more" type="button" :disabled="loading" @click="emit('loadMore')">{{ loading ? '加载中…' : '加载更多' }}</button>
-  </div>
-</template>
-
-<style scoped>
-.library-scroll { min-height: 0; flex: 1; overflow-y: auto; padding: 20px clamp(18px, 3vw, 36px) 32px; }
-.library-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px 12px; }
-article { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: var(--surface); cursor: pointer; outline: 0; transition: border-color 140ms ease, box-shadow 140ms ease, transform 140ms ease; } article:focus-visible, article.selected { border-color: var(--line-strong); box-shadow: 0 0 0 2px var(--focus-ring); } article:hover { border-color: var(--line-strong); box-shadow: 0 8px 22px rgba(0,0,0,.07); transform: translateY(-1px); }
-.library-thumb { position: relative; display: grid; height: 154px; place-items: center; overflow: hidden; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: var(--surface-soft); color: var(--text-muted); }
-.library-thumb img, .library-thumb video { width: 100%; height: 100%; object-fit: cover; }
-.library-thumb > span { display: flex; flex-direction: column; align-items: center; gap: 7px; }.library-thumb > span em { max-width: 150px; overflow: hidden; color: var(--text-muted); font-size: 11px; font-style: normal; letter-spacing: .02em; text-overflow: ellipsis; text-transform: capitalize; }
-.library-thumb--code, .library-thumb--text { background: linear-gradient(135deg, var(--surface-soft), var(--surface-raised)); }.library-thumb--link { border-style: dashed; }
-.library-thumb__actions { position: absolute; top: 6px; right: 6px; display: flex; gap: 4px; opacity: 0; transform: translateY(-3px); transition: opacity 120ms ease, transform 140ms var(--ease-out); }.library-thumb:hover .library-thumb__actions, article:focus-within .library-thumb__actions { opacity: 1; transform: translateY(0); }.library-thumb__actions button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 1px solid rgba(255,255,255,.32); border-radius: 8px; background: rgba(25,25,24,.72); color: #fff; cursor: pointer; backdrop-filter: blur(8px); }
-.library-copy { padding: 10px 12px 9px; }.library-copy strong { display: block; overflow: hidden; font-size: 13px; font-weight: 550; text-overflow: ellipsis; white-space: nowrap; }.library-copy > span { display: flex; margin-top: 5px; justify-content: space-between; gap: 8px; color: var(--text-muted); font-size: 11px; line-height: 1.4; }.library-copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.library-copy time { flex: 0 0 auto; }
-.load-more { display: block; margin: 28px auto 0; padding: 7px 12px; border: 1px solid var(--line); border-radius: 9px; background: transparent; color: var(--text-secondary); cursor: pointer; font-size: 10px; }.load-more:hover { background: var(--surface-hover); }
-.library-skeleton { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px 12px; }.library-skeleton i { height: 208px; border-radius: 11px; background: linear-gradient(90deg, var(--surface-soft), var(--surface-hover), var(--surface-soft)); background-size: 200% 100%; animation: shimmer 1.5s linear infinite; }
-@keyframes shimmer { to { background-position: -200% 0; } }
-@media (max-width: 600px) { .library-scroll { padding: 16px 12px 30px; }.library-grid, .library-skeleton { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 9px; }.library-thumb { height: 122px; }.library-thumb__actions { opacity: 1; transform: none; }.library-copy { padding: 8px 9px; }.library-copy strong { font-size: 11px; }.library-copy > span { font-size: 9px; } }
-</style>

+ 0 - 415
src/client/components/messages/MessageTimeline.vue

@@ -1,415 +0,0 @@
-<script setup lang="ts">
-import {useVisibleMessages} from '@/utils/visibleMessages'
-import { useChatAppearance } from '@/stores/chatAppearance'
-import { bubbleVariables } from '@/utils/chatAppearance'
-import '@/styles/chat-bubbles.css'
-import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
-import ServiceWarnings from './ServiceWarnings.vue'
-import AppIcon from '@/components/common/AppIcon.vue'
-import MessageFailureNotice from '@/components/messages/MessageFailureNotice.vue'
-import { messageFailure } from '@/utils/messageFailure'
-import TaskResultNotice from '@/components/workspace/TaskResultNotice.vue'
-import MessageSystemEvent from '@/components/messages/MessageSystemEvent.vue'
-import { systemMessageNotice } from '@/utils/systemMessageNotice'
-import AgentAvatar from '@/components/common/AgentAvatar.vue'
-import EmptyState from '@/components/common/EmptyState.vue'
-import TypingIndicator from '@/components/common/TypingIndicator.vue'
-import InteractionCard from './InteractionCard.vue'
-import MarkdownContent from './MarkdownContent.vue'
-import ToolTrace from './ToolTrace.vue'
-import TurnTrace from './TurnTrace.vue'
-import type { UiInteraction, UiLocalFileLink, UiMessage } from './types'
-import { buildMessageTimelineRows } from '@/utils/turnTrace'
-import { copyTextToClipboard } from '@/utils/clipboard'
-import { displayContentForMessage } from '@/utils/messageDisplay'
-import { formatMessageTime } from '@/utils/messageTime'
-
-const { appearance } = useChatAppearance()
-
-const props = withDefaults(defineProps<{
-  messages: UiMessage[]
-  title?: string
-  subtitle?: string
-  emptyTitle?: string
-  emptyDescription?: string
-  emptyLogo?: boolean
-  transparentHeader?: boolean
-  forkSourceTitle?: string
-  loading?: boolean
-  loadingOlder?: boolean
-  hasOlder?: boolean
-  connected?: boolean
-  synced?: boolean
-  showTools?: boolean
-  showAssistantIdentity?: boolean
-  interaction?: UiInteraction | null
-  mentionNames?: string[]
-  agentAvatars?: Record<string, string>
-  agentStates?: Record<string, 'idle' | 'working' | 'waiting' | 'loading' | 'success' | 'failure' | 'notifying'>
-  thinking?: boolean
-  allowBranch?: boolean
-  readOnly?: boolean
-}>(), {
-  title: '',
-  subtitle: '',
-  emptyTitle: '开始一段新对话',
-  emptyDescription: '从下方输入框发送消息,或选择左侧的历史会话。',
-  emptyLogo: false,
-  transparentHeader: false,
-  forkSourceTitle: '',
-  loading: false,
-  loadingOlder: false,
-  hasOlder: false,
-  connected: false,
-  synced: false,
-  showTools: true,
-  showAssistantIdentity: true,
-  interaction: null,
-  mentionNames: () => [],
-  agentAvatars: () => ({}),
-  agentStates: () => ({}),
-  thinking: false,
-  allowBranch: true,
-  readOnly: false,
-})
-
-const emit = defineEmits<{
-  visibleMessages: [ids:string[]]
-  loadOlder: []
-  quote: [message: UiMessage]
-  branch: [message: UiMessage]
-  preview: [attachment: NonNullable<UiMessage['attachments']>[number]]
-  previewFile: [file: UiLocalFileLink]
-  approve: [approved: boolean]
-  clarify: [text: string]
-}>()
-
-const scroller = ref<HTMLElement | null>(null)
-useVisibleMessages(scroller,ids=>emit('visibleMessages',ids))
-const pinnedToBottom = ref(true)
-const showJump = ref(false)
-const copiedMessageId = ref('')
-const copyFailedMessageId = ref('')
-const timelineRows = computed(() => buildMessageTimelineRows(props.messages))
-const showThinkingIndicator = computed(() => props.thinking)
-const thinkingAgent = computed(() =>
-  [...props.messages].reverse().find(message => message.role === 'assistant' && message.status === 'streaming')
-    ?? [...props.messages].reverse().find(message => message.role === 'assistant'),
-)
-const thinkingAvatarName = computed(() => thinkingAgent.value?.author || thinkingAgent.value?.profile || '夭')
-const thinkingAvatar = computed(() => {
-  const profile = thinkingAgent.value?.profile
-  return profile ? props.agentAvatars[profile] || '' : ''
-})
-let copyResetTimer: number | undefined
-
-const formatTime = formatMessageTime
-
-function avatarState(message: UiMessage): 'idle' | 'working' | 'waiting' | 'loading' | 'success' | 'failure' | 'notifying' {
-  if (message.status === 'streaming') return (message.profile && props.agentStates[message.profile]) || 'working'
-  if (message.status === 'pending' || message.status === 'unknown-receipt') return 'waiting'
-  if (message.status === 'failed') return 'failure'
-  const outcome = message.profile ? props.agentStates[message.profile] : undefined
-  if ((outcome === 'success' || outcome === 'failure') && [...props.messages].reverse().find(m => m.profile === message.profile && m.role === 'assistant')?.id === message.id) return outcome
-  return 'idle'
-}
-
-function onScroll() {
-  const el = scroller.value
-  if (!el) return
-  const distance = el.scrollHeight - el.scrollTop - el.clientHeight
-  pinnedToBottom.value = distance < 100
-  showJump.value = distance > 240
-}
-
-function scrollToBottom(behavior: ScrollBehavior = 'smooth') {
-  const el = scroller.value
-  if (!el) return
-  el.scrollTo({ top: el.scrollHeight, behavior })
-}
-
-function onMarkdownRendered() {
-  if (pinnedToBottom.value) scrollToBottom('auto')
-}
-
-function scrollToMessage(id: string): boolean {
-  const root = scroller.value
-  if (!root) return false
-  const message = root.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(id)}"]`)
-  if (!message) return false
-  pinnedToBottom.value=false
-  message.scrollIntoView({ block: 'center', behavior: 'smooth' })
-  message.classList.remove('message--revealed')
-  requestAnimationFrame(() => message.classList.add('message--revealed'))
-  window.setTimeout(() => message.classList.remove('message--revealed'), 1800)
-  return true
-}
-
-function scrollToAnchor(messageId: string, anchorId: string): boolean {
-  const root = scroller.value
-  if (!root) return false
-  const message = root.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(messageId)}"]`)
-  if (!message) return false
-  const target = anchorId ? message.querySelector<HTMLElement>(`#${CSS.escape(anchorId)}`) : null
-  ;(target || message).scrollIntoView({ block: target ? 'start' : 'center', behavior: 'smooth' })
-  message.classList.remove('message--revealed')
-  requestAnimationFrame(() => message.classList.add('message--revealed'))
-  window.setTimeout(() => message.classList.remove('message--revealed'), 1800)
-  return true
-}
-
-async function copyMessage(message: UiMessage) {
-  const text = displayContentForMessage(message.role, message.content)
-  const copied = await copyTextToClipboard(text)
-  copiedMessageId.value = copied ? message.id : ''
-  copyFailedMessageId.value = copied ? '' : message.id
-  if (copyResetTimer !== undefined) window.clearTimeout(copyResetTimer)
-  copyResetTimer = window.setTimeout(() => {
-    copiedMessageId.value = ''
-    copyFailedMessageId.value = ''
-    copyResetTimer = undefined
-  }, 1400)
-}
-
-function hasConversationActions(message: UiMessage): boolean {
-  return message.role === 'user' || (message.role === 'assistant' && Boolean(message.content.trim()))
-}
-
-function deliveryLabel(status?: UiMessage['status']): string {
-  return ({
-    preparing: '正在准备附件',
-    attached: '附件已就绪',
-    pending: '正在发送',
-    accepted: '已发送',
-    failed: '发送失败',
-    'unknown-receipt': '回执未知,请检查后重试',
-  } as Partial<Record<NonNullable<UiMessage['status']>, string>>)[status || 'settled'] || ''
-}
-
-watch(() => props.messages.length, async () => {
-  if (!pinnedToBottom.value) return
-  await nextTick()
-  scrollToBottom('auto')
-})
-
-watch(() => props.messages.at(-1)?.content, async () => {
-  if (!pinnedToBottom.value) return
-  await nextTick()
-  scrollToBottom('auto')
-})
-
-onMounted(() => nextTick(() => scrollToBottom('auto')))
-onBeforeUnmount(() => {
-  if (copyResetTimer !== undefined) window.clearTimeout(copyResetTimer)
-})
-
-defineExpose({ scrollToMessage, scrollToAnchor, scrollToBottom, isFollowingBottom: () => pinnedToBottom.value })
-</script>
-
-<template>
-  <section class="timeline-frame" :class="{ 'timeline-frame--transparent': transparentHeader }">
-    <header v-if="title || transparentHeader" class="timeline-header" :class="{ 'timeline-header--transparent': transparentHeader }">
-      <slot name="header-leading" />
-      <div v-if="!transparentHeader"><h2>{{ title }}</h2><p v-if="subtitle">{{ subtitle }}</p></div>
-      <div v-if="!transparentHeader" class="timeline-state" :title="connected ? (synced ? '实时连接与历史均已同步' : '实时连接已就绪,历史同步中') : '实时连接未就绪'">
-        <span class="status-dot" :class="connected ? (synced ? 'status-dot--online' : 'status-dot--working') : ''" />
-        {{ connected ? (synced ? '已同步' : '同步中') : '离线' }}
-      </div>
-      <slot name="header-actions" />
-    </header>
-
-    <div ref="scroller" class="timeline" @scroll.passive="onScroll">
-      <div v-if="loading && !messages.length" class="message-skeletons" aria-label="正在加载消息">
-        <div v-for="n in 4" :key="n" :class="{ user: n % 2 === 0 }"><i /><span /></div>
-      </div>
-      <div v-else-if="!messages.length && emptyLogo" class="new-chat-empty">
-        <img class="new-chat-empty__logo" src="/brand/AppIcon-1024.png" width="1024" height="1024" alt="" aria-hidden="true" />
-        <p>聊点什么</p>
-      </div>
-      <EmptyState v-else-if="!messages.length" icon="chat" :title="emptyTitle" :description="emptyDescription" />
-      <div v-else class="message-stack" :class="{ 'message-stack--interaction': interaction }">
-        <div v-if="forkSourceTitle" class="fork-divider" role="separator">
-          <span><AppIcon name="branch" :size="13" />FORK 来源 <strong>{{ forkSourceTitle }}</strong></span>
-        </div>
-        <button v-if="hasOlder" class="load-older" type="button" :disabled="loadingOlder" @click="emit('loadOlder')">
-          {{ loadingOlder ? '正在加载…' : '加载更早消息' }}
-        </button>
-
-        <template v-for="row in timelineRows" :key="row.id">
-        <TurnTrace v-if="row.kind === 'trace' && showTools" :group="row" />
-        <template v-else-if="row.kind === 'message'">
-        <article
-          v-for="message in [row.message]"
-          :key="message.id"
-          :data-message-id="message.id"
-          class="message"
-          :class="[`message--${message.role}`, {
-            'message--failed': message.status === 'failed',
-            'message--failure-notice': messageFailure(message)?.replacesContent && !message.attachments?.length,
-            'message--has-failure': !!messageFailure(message),
-            'message--notice': !!systemMessageNotice(message),
-            'message--tool-only': message.role === 'assistant' && !message.content && !message.reasoning && Boolean(message.tools?.length),
-            'message--assistant-internal': message.role === 'assistant' && !message.content.trim(),
-            'message--assistant-anonymous': message.role === 'assistant' && !showAssistantIdentity,
-          }]"
-        >
-          <AgentAvatar v-if="message.role !== 'user' && (message.role !== 'assistant' || showAssistantIdentity)" class="message__avatar" :name="message.author || message.profile || (message.role === 'assistant' ? '夭' : '系')" :avatar="message.profile ? agentAvatars[message.profile] || '' : ''" :size="27" :state="avatarState(message)" />
-          <div class="message__body">
-            <MessageFailureNotice v-if="messageFailure(message)?.replacesContent && !message.attachments?.length" :failure="messageFailure(message)!" />
-            <TaskResultNotice v-else-if="message.role === 'system' && message.taskReference" :content="message.content" :task-reference="message.taskReference" />
-            <MessageSystemEvent v-else-if="systemMessageNotice(message)" :message="message" />
-            <template v-else>
-            <div v-if="message.role !== 'assistant' || showAssistantIdentity" class="message__meta">
-              <strong><AppIcon v-if="message.isRemoteAgent" class="message__remote-agent" name="globe" :size="12" />{{ message.role === 'user' ? '你' : message.author || message.profile || (message.role === 'assistant' ? '机器人' : '系统') }}</strong>
-              <span v-if="message.metadata" class="message__execution">{{ message.metadata }}</span>
-              <time>{{ formatTime(message.createdAt) }}</time>
-              <span v-if="message.status && !['settled', 'streaming'].includes(message.status)">{{ { preparing: '准备中', attached: '附件已就绪', pending: '等待回执', accepted: '已接收', streaming: '生成中', settled: '已完成', failed: message.role === 'user' ? '发送失败' : '回复中断', 'unknown-receipt': '回执未知' }[message.status] }}</span>
-            </div>
-
-            <details v-if="message.reasoning" class="message__reasoning">
-              <summary><AppIcon name="brain" :size="13" />思考过程 · {{ message.reasoning.length }} 字</summary>
-              <MarkdownContent process-content :content="message.reasoning" :streaming="message.status === 'streaming'" @rendered="onMarkdownRendered" />
-            </details>
-
-            <div v-if="!messageFailure(message)?.replacesContent" class="message__content"  :style="(message.role === 'user' || message.role === 'assistant') ? bubbleVariables(appearance[message.role], message.role) : undefined">
-              <MarkdownContent
-                :separate-media="message.role === 'user' || message.role === 'assistant' || !!message.communication"
-                :bubble="(message.role === 'user' || message.role === 'assistant') && !!message.content.trim()"
-                :attachments="message.attachments"
-                :content-parts="message.contentParts"
-                @preview="item => item.id && message.attachments?.some(a => a.id === item.id) ? emit('preview', item) : emit('previewFile', { name: item.name, url: item.url! })"
-                :file-profile="message.profile"
-                :content="displayContentForMessage(message.role, message.content)"
-                :streaming="message.status === 'streaming'"
-                :legacy-media="message.role === 'assistant'"
-                :plain="message.role === 'user'"
-                :mention-names="mentionNames"
-                :outline-prefix="message.role === 'assistant' ? `outline-${message.id}` : ''"
-                :file-cards="message.role === 'user' || message.role === 'assistant'"
-                :process-content="message.role !== 'user' && message.role !== 'assistant'"
-                @rendered="onMarkdownRendered"
-                @file-link="(name, url) => emit('previewFile', { name, url })"
-              />
-            </div>
-
-            <div
-              v-if="message.role === 'user' && deliveryLabel(message.status)"
-              class="message__delivery"
-              :class="`message__delivery--${message.status}`"
-              role="status"
-              aria-live="polite"
-            >
-              <AppIcon :name="message.status === 'accepted' ? 'check' : message.status === 'failed' || message.status === 'unknown-receipt' ? 'alert' : 'dots'" :size="11" />
-              {{ deliveryLabel(message.status) }}
-            </div>
-
-            <div v-if="showTools && message.tools?.length" class="message__tools">
-              <ToolTrace v-for="tool in message.tools" :key="tool.id" :tool="tool" />
-            </div>
-
-
-            <div v-if="hasConversationActions(message)" class="message__actions">
-              <time v-if="message.role === 'assistant' && !showAssistantIdentity && message.createdAt" class="message__action-time">{{ formatTime(message.createdAt) }}</time>
-              <button
-                type="button"
-                :class="{
-                  'message-action--copied': copiedMessageId === message.id,
-                  'message-action--copy-failed': copyFailedMessageId === message.id,
-                }"
-                :title="copiedMessageId === message.id ? '已复制' : copyFailedMessageId === message.id ? '复制失败' : '复制'"
-                :aria-label="copiedMessageId === message.id ? '已复制' : copyFailedMessageId === message.id ? '复制失败' : '复制消息'"
-                @click="copyMessage(message)"
-              ><AppIcon :name="copiedMessageId === message.id ? 'check' : copyFailedMessageId === message.id ? 'alert' : 'copy'" :size="13" /></button>
-              <button v-if="!readOnly" type="button" title="引用" aria-label="引用消息" @click="emit('quote', message)"><AppIcon name="quote" :size="13" /></button>
-              <button v-if="!readOnly && allowBranch && message.role === 'assistant'" type="button" title="从这里分支" aria-label="从这里分支" @click="emit('branch', message)"><AppIcon name="branch" :size="13" /></button>
-            </div>
-            </template>
-            <ServiceWarnings v-if="message.serviceWarnings?.length" :warnings="message.serviceWarnings"/>
-          </div>
-          <MessageFailureNotice v-if="messageFailure(message) && (!messageFailure(message)?.replacesContent || !!message.attachments?.length)" :failure="messageFailure(message)!" />
-        </article>
-        </template>
-        </template>
-
-        <TypingIndicator
-          v-if="showThinkingIndicator"
-          :avatar-name="thinkingAvatarName"
-          :avatar="thinkingAvatar"
-        />
-
-        <InteractionCard
-          v-if="interaction"
-          :interaction="interaction"
-          @approve="emit('approve', $event)"
-          @clarify="emit('clarify', $event)"
-        />
-      </div>
-    </div>
-
-    <Transition name="view-fade">
-      <button v-if="showJump" class="jump-bottom" type="button" @click="scrollToBottom()">
-        <AppIcon name="chevron-down" :size="15" />回到底部
-      </button>
-    </Transition>
-  </section>
-</template>
-
-<style scoped>
-.message--has-failure { flex-wrap: wrap; }
-.message--has-failure > .failure-notice { flex: 0 0 100%; }
-.message.message--notice, .message.message--failure-notice { justify-content: center; }
-.message--notice .message__avatar, .message--failure-notice .message__avatar { display: none; }
-.message.message--notice .message__body, .message.message--failure-notice .message__body { width: 100%; max-width: 100%; margin: 0; padding: 0; border: 0; background: transparent; }
-
-.timeline-frame { position: relative; display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; }
-.timeline-header { display: flex; z-index: 6; min-height: 62px; align-items: center; gap: 13px; padding: 10px 18px; border-bottom: 1px solid var(--line); background: color-mix(in srgb, var(--canvas) 92%, transparent); backdrop-filter: blur(16px); }
-.timeline-header--transparent { position: absolute; top: 0; right: 0; left: 0; min-height: 0; justify-content: flex-end; padding: 11px 14px; border: 0; background: transparent; backdrop-filter: none; pointer-events: none; }
-.timeline-header--transparent > * { pointer-events: auto; }
-.timeline-header > div:first-child { min-width: 0; flex: 1; }.timeline-header h2 { overflow: hidden; margin: 0; font-size: 14px; font-weight: 630; letter-spacing: -.02em; text-overflow: ellipsis; white-space: nowrap; }.timeline-header p { overflow: hidden; margin: 3px 0 0; color: var(--text-muted); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
-.timeline-state { display: flex; align-items: center; gap: 6px; color: var(--text-muted); font-size: 9px; }
-.timeline { min-height: 0; flex: 1; overflow-y: auto; overscroll-behavior: contain; background: var(--conversation-canvas); }
-.message-stack { width: min(780px, 100%); min-height: 100%; margin: 0 auto; padding: 24px 24px 36px; }
-.message-stack--interaction { padding-bottom: 10px; }
-.timeline-frame--transparent .message-stack { padding-top: 58px; }
-.load-older { display: block; margin: 0 auto 18px; padding: 5px 9px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: var(--text-muted); cursor: pointer; font-size: 10px; }.load-older:hover { background: var(--surface-soft); color: var(--text-secondary); }
-.message { position: relative; display: flex; max-width: 100%; gap: 10px; margin: 0 0 21px; }
-.message__avatar { display: grid; place-items: center; width: 27px; height: 27px; flex: 0 0 27px; background: transparent; color: var(--text-secondary); font-size: 11px; font-weight: 700; }
-.message__body { position: relative; min-width: 0; max-width: min(680px, calc(100% - 37px)); }
-.message__meta { display: flex; min-height: 20px; align-items: center; gap: 7px; color: var(--text-muted); font-size: 10px; }.message__meta strong { display: inline-flex; align-items: center; color: var(--text-primary); font-size: 12px; font-weight: 600; }.message__remote-agent { margin-right: 4px; color: var(--accent); }.message__meta span { color: var(--warning); }.message__meta .message__execution { overflow: hidden; max-width: 230px; color: var(--text-secondary); font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }
-.message__content { color: var(--text-primary); }
-.message__content :deep(.plain-text), .message__content :deep(.markdown) { font-size: 15px; }
-.message__content :deep(.code-lang), .message__content :deep(.code-copy) { font-size: 10px; }
-.message__content :deep(.code-block code) { font-size: 12px; }
-.message__content :deep(.file-link-card)::after { font-size: 10px; }
-.message--user { justify-content: flex-end; margin-top: 27px; }
-.message--user .message__body { max-width: min(610px, 76%); padding: 0; background: transparent; }
-
-.message--user :deep(.message-parts) { align-items: flex-end; }
-.message--user .message__meta { display: none; }
-.message__delivery { display: flex; min-height: 18px; align-items: center; justify-content: flex-end; gap: 4px; margin: 5px 1px -4px; color: var(--text-muted); font-size: 10px; }.message__delivery--accepted { color: var(--success); }.message__delivery--failed, .message__delivery--unknown-receipt { color: var(--danger); }
-.message--tool-only { margin-block: 4px; }.message--tool-only .message__avatar, .message--tool-only .message__meta, .message--tool-only .message__actions { display: none; }.message--tool-only .message__body { max-width: 100%; }
-.message--assistant-internal { margin-bottom: 6px; }.message--assistant-internal .message__reasoning { margin-bottom: 4px; padding-bottom: 4px; }.message--assistant-internal .message__tools { margin-top: 4px; }
-.message--assistant-anonymous .message__body { max-width: min(680px, 100%); }
-.message__reasoning { max-width: 420px; margin: 3px 0 10px; padding: 0 0 8px; border: 0; border-bottom: 1px dashed var(--line-strong); color: var(--text-secondary); font-size: 12px; }.message__reasoning summary { display: flex; align-items: center; gap: 5px; list-style: none; color: var(--text-muted); cursor: pointer; font-size: 10px; }.message__reasoning summary::-webkit-details-marker { display: none; }.message__reasoning summary::before { content: '›'; color: var(--text-muted); font-size: 14px; line-height: 1; transition: transform 120ms ease; }.message__reasoning[open] summary::before { transform: rotate(90deg); }.message__reasoning :deep(.markdown) { margin-top: 8px; }
-.fork-divider { display: flex; align-items: center; gap: 12px; margin: 8px 0 28px; color: var(--text-muted); font-size: 11px; }.fork-divider::before, .fork-divider::after { height: 1px; flex: 1; background: var(--line); content: ''; }.fork-divider > span { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-raised); white-space: nowrap; }.fork-divider strong { max-width: 180px; overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; }
-.message__tools { margin-top: 9px; }
-.message__actions { display: flex; position: absolute; left: -3px; top: 100%; gap: 2px; padding-top: 2px; opacity: 0; transition: opacity 120ms ease; }.message:hover .message__actions, .message:focus-within .message__actions { opacity: 1; }.message--user .message__actions { right: 0; left: auto; }.message__actions button { display: grid; place-items: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--text-muted); cursor: pointer; }.message__actions button:hover { background: var(--surface-soft); color: var(--text-primary); }.message__actions .message-action--copied { color: var(--success); }.message__actions .message-action--copy-failed { color: var(--danger); }
-.message--assistant-anonymous .message__actions { align-items: center; }.message__action-time { min-width: 36px; padding: 0 4px 0 3px; color: var(--text-muted); font-size: 10px; font-variant-numeric: tabular-nums; }
-.message--failed .message__body { border-color: color-mix(in srgb, var(--danger) 35%, var(--line)); }
-.message--revealed .message__body { animation: reveal-message 1.8s ease; }
-@keyframes reveal-message { 0%, 28% { box-shadow: 0 0 0 5px var(--focus-ring); } 100% { box-shadow: 0 0 0 0 transparent; } }
-.jump-bottom { display: flex; position: absolute; z-index: 8; bottom: 8px; left: 50%; align-items: center; gap: 5px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-raised); color: var(--text-secondary); cursor: pointer; font-size: 10px; box-shadow: 0 6px 18px rgba(0,0,0,.1); transform: translateX(-50%); }
-.new-chat-empty { display: flex; min-height: 100%; align-items: center; justify-content: center; gap: 18px; padding: 12vh 24px; box-sizing: border-box; flex-direction: column; color: var(--text-muted); text-align: center; }
-.new-chat-empty__logo { display: block; width: min(180px, 34vw); height: auto; aspect-ratio: 1; opacity: .18; filter: grayscale(1); }
-.new-chat-empty p { margin: 0; color: var(--text-secondary); font-size: 17px; font-weight: 520; letter-spacing: .02em; }
-.message-skeletons { width: min(760px, 100%); margin: 0 auto; padding: 35px 24px; }.message-skeletons div { display: flex; gap: 10px; margin: 0 0 25px; }.message-skeletons div.user { justify-content: flex-end; }.message-skeletons i { width: 27px; height: 27px; border-radius: 9px; background: var(--surface-hover); }.message-skeletons span { width: min(480px, 70%); height: 64px; border-radius: 12px; background: linear-gradient(90deg, var(--surface-soft), var(--surface-hover), var(--surface-soft)); background-size: 200% 100%; animation: shimmer 1.5s linear infinite; }.message-skeletons .user i { display: none; }.message-skeletons .user span { width: 44%; height: 46px; }
-@keyframes shimmer { to { background-position: -200% 0; } }
-
-
-@media (max-width: 768px) {
-  .timeline-header { min-height: 54px; padding: 8px 12px; }.timeline-state { font-size: 0; }.timeline-state .status-dot { width: 7px; height: 7px; }
-  .new-chat-empty { gap: 15px; padding-block: 9vh; }.new-chat-empty__logo { width: min(150px, 42vw); }.new-chat-empty p { font-size: 16px; }
-  .message-stack { padding: 18px 14px 30px; }.message-stack--interaction { padding-bottom: 8px; }.message { margin-bottom: 18px; }.message__body { max-width: calc(100% - 37px); }.message--user .message__body { max-width: 88%; }
-  .message__actions { opacity: .65; }.message__meta time { display: none; }
-}
-</style>

+ 0 - 67
src/client/components/messages/SessionOutline.vue

@@ -1,67 +0,0 @@
-<script setup lang="ts">
-import { computed } from 'vue'
-import type { UiMessage } from './types'
-import { buildSessionOutline, type SessionOutlineItem } from '@/utils/sessionOutline'
-
-const props = defineProps<{ messages: UiMessage[]; hasOlder?: boolean }>()
-const emit = defineEmits<{ navigate: [target: { messageId: string; anchorId: string }] }>()
-
-const items = computed(() => buildSessionOutline(props.messages))
-
-function formatTime(value?: UiMessage['createdAt']) {
-  if (!value) return ''
-  const date = value instanceof Date ? value : new Date(value)
-  if (Number.isNaN(date.getTime())) return ''
-  return new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit' }).format(date)
-}
-
-function navigate(item: SessionOutlineItem) {
-  emit('navigate', { messageId: item.messageId, anchorId: item.anchorId })
-}
-</script>
-
-<template>
-  <nav class="session-outline" aria-label="会话大纲">
-    <header>
-      <div><strong>会话大纲</strong><span>{{ items.length }} 项</span></div>
-      <p>按问题与回答标题快速定位</p>
-    </header>
-    <div class="session-outline__content">
-      <template v-if="items.length">
-        <button
-          v-for="item in items"
-          :key="item.id"
-          type="button"
-          class="outline-item"
-          :class="[`outline-item--${item.type}`, `outline-item--level-${item.level}`]"
-          :aria-label="`跳转到 ${item.content}`"
-          @click="navigate(item)"
-        >
-          <template v-if="item.type === 'user'">
-            <b>Q</b><span>{{ item.content }}</span><time v-if="formatTime(item.createdAt)">{{ formatTime(item.createdAt) }}</time>
-          </template>
-          <template v-else>
-            <i aria-hidden="true" /><span>{{ item.content }}</span>
-          </template>
-        </button>
-      </template>
-      <div v-else class="session-outline__empty">
-        <strong>还没有大纲</strong>
-        <p>发送问题,或让回答使用 Markdown 标题后会显示在这里。</p>
-      </div>
-    </div>
-    <footer v-if="hasOlder">当前大纲基于已加载的消息</footer>
-  </nav>
-</template>
-
-<style scoped>
-.session-outline { display: flex; height: 100%; min-height: 0; flex-direction: column; background: var(--surface); }
-.session-outline > header { flex: 0 0 auto; min-height: 60px; padding: 13px 48px 10px 15px; border-bottom: 1px solid var(--line); }.session-outline > header > div { display: flex; align-items: baseline; gap: 8px; }.session-outline > header strong { font-size: 13px; font-weight: 620; }.session-outline > header span { color: var(--text-muted); font-size: 9px; }.session-outline > header p { margin: 4px 0 0; color: var(--text-muted); font-size: 9px; }
-.session-outline__content { min-height: 0; flex: 1; padding: 10px; overflow-y: auto; }
-.outline-item { display: flex; width: 100%; min-width: 0; align-items: flex-start; gap: 7px; margin: 0 0 3px; padding: 6px 8px; border: 0; border-radius: 7px; background: transparent; color: var(--text-secondary); cursor: pointer; font: inherit; text-align: left; transition: background-color 100ms ease, color 100ms ease; }.outline-item:hover, .outline-item:focus-visible { outline: 0; background: var(--surface-soft); color: var(--text-primary); }.outline-item span { min-width: 0; overflow: hidden; font-size: 11px; line-height: 1.45; overflow-wrap: anywhere; }.outline-item time { flex: 0 0 auto; margin-left: auto; color: var(--text-muted); font-size: 8px; font-variant-numeric: tabular-nums; }
-.outline-item--user { margin: 6px 0; padding: 8px 9px; border-radius: 9px; background: var(--surface-soft); color: var(--text-primary); }.outline-item--user:first-child { margin-top: 0; }.outline-item--user b { display: grid; width: 19px; height: 19px; flex: 0 0 19px; place-items: center; border-radius: 6px; background: var(--surface-raised); color: var(--text-secondary); font-size: 9px; font-weight: 650; }.outline-item--user span { font-size: 11.5px; font-weight: 520; }
-.outline-item--heading i { width: 4px; height: 4px; flex: 0 0 4px; margin-top: 6px; border-radius: 50%; background: currentColor; opacity: .45; }.outline-item--level-1 { padding-left: 10px; color: var(--text-primary); }.outline-item--level-1 span { font-weight: 560; }.outline-item--level-2 { padding-left: 22px; }.outline-item--level-3 { padding-left: 34px; color: var(--text-muted); }.outline-item--level-3 span { font-size: 10.5px; }
-.session-outline__empty { display: flex; min-height: 220px; align-items: center; justify-content: center; padding: 24px; flex-direction: column; color: var(--text-muted); text-align: center; }.session-outline__empty strong { color: var(--text-secondary); font-size: 12px; }.session-outline__empty p { max-width: 220px; margin: 6px 0 0; font-size: 10px; line-height: 1.55; }
-.session-outline > footer { flex: 0 0 auto; padding: 8px 12px; border-top: 1px solid var(--line); color: var(--text-muted); font-size: 8px; text-align: center; }
-@media (prefers-reduced-motion: reduce) { .outline-item { transition: none; } }
-</style>

+ 0 - 93
src/client/components/workspace/WorkspaceView.vue

@@ -1,93 +0,0 @@
-<script setup lang="ts">
-import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
-import WorkspaceShell from '@/components/app/WorkspaceShell.vue'
-import { updateProfileIdentity, type ProfileIdentityInput } from '@/api/profiles'
-import { useAuthStore } from '@/stores/auth'
-import { useThemeStore } from '@/stores/theme'
-
-withDefaults(defineProps<{
-  sidebarTitle: string
-  sidebarSubtitle?: string
-  sidebarContextTitle?: string
-  sidebarFocusMode?: boolean
-  inspectorOpen?: boolean
-  inspectorCloseLabel?: string
-}>(), { sidebarSubtitle: '', sidebarContextTitle: '', sidebarFocusMode: false, inspectorOpen: false, inspectorCloseLabel: '关闭预览' })
-
-const emit = defineEmits<{ closeInspector: [] }>()
-const auth = useAuthStore()
-const theme = useThemeStore()
-
-const userName = computed(() => auth.user?.displayName || auth.user?.username || '')
-const identityBusy = ref(false)
-const identityError = ref('')
-const identityResetVersion = ref(0)
-
-async function logout() { await auth.logout() }
-function selectProfile(name: string) { auth.selectProfile(name) }
-async function saveIdentity(input: ProfileIdentityInput) {
-  const profile = auth.activeProfile
-  if (!profile) return
-  identityBusy.value = true
-  identityError.value = ''
-  try {
-    await updateProfileIdentity(profile, input)
-    await auth.refreshProfiles()
-    await auth.refreshProfileAvatars()
-    identityError.value = ''
-    identityResetVersion.value += 1
-  } catch (cause) {
-    identityError.value = cause instanceof Error ? cause.message : '保存机器人身份失败'
-  } finally {
-    identityBusy.value = false
-  }
-}
-async function refreshOnFocus() {
-  await auth.refreshProfiles()
-  await auth.refreshProfileAvatars()
-}
-function refreshOnWindowFocus() { void refreshOnFocus().catch(() => undefined) }
-onMounted(() => {
-  window.addEventListener('focus', refreshOnWindowFocus)
-  void auth.refreshProfileAvatars().catch(() => undefined)
-})
-onBeforeUnmount(() => window.removeEventListener('focus', refreshOnWindowFocus))
-</script>
-
-<template>
-  <WorkspaceShell :server-name="auth.serverIdentity?.displayName"
-    :user-name="userName"
-    :user-avatar="auth.user?.avatar"
-    :pairing-user-name="auth.user?.username || ''"
-    :active-profile="auth.activeProfile"
-    :profiles="auth.profiles"
-    :theme="theme.resolvedTheme"
-    :theme-preference="theme.theme"
-    :insecure-transport="auth.insecureLan"
-    :is-admin="auth.user?.role === 'admin'"
-    :upstream-ready="auth.upstreamReady"
-    :upstream-error="auth.upstreamError"
-    :identity-busy="identityBusy"
-    :identity-error="identityError"
-    :identity-reset-version="identityResetVersion"
-    :sidebar-title="sidebarTitle"
-    :sidebar-subtitle="sidebarSubtitle"
-    :sidebar-context-title="sidebarContextTitle"
-    :sidebar-focus-mode="sidebarFocusMode"
-    :inspector-open="inspectorOpen"
-    :inspector-close-label="inspectorCloseLabel"
-    @logout="logout"
-    @toggle-theme="theme.toggle"
-    @set-theme="theme.setTheme"
-    @select-profile="selectProfile"
-    @save-identity="saveIdentity"
-    @close-inspector="emit('closeInspector')"
-  >
-    <template #sidebar-action><slot name="sidebar-action" /></template>
-    <template #sidebar-before-heading><slot name="sidebar-before-heading" /></template>
-    <template #sidebar><slot name="sidebar" /></template>
-    <template #mobile-sidebar><slot name="sidebar" /></template>
-    <template #default><slot /></template>
-    <template #inspector><slot name="inspector" /></template>
-  </WorkspaceShell>
-</template>

+ 0 - 40
src/client/components/workspace/pendingComposer.ts

@@ -1,40 +0,0 @@
-import type { UiLibraryItem } from '@/components/library/types'
-
-const KEY = 'hermes-yaoyao:pending-composer-item'
-
-type PendingItem = { name: string; url: string; mimeType?: string }
-
-type ComposerFileSource = Pick<UiLibraryItem, 'name' | 'previewUrl' | 'downloadUrl' | 'mimeType'>
-
-export function queueLibraryItemForComposer(item: UiLibraryItem): boolean {
-  const url = item.downloadUrl || item.previewUrl
-  if (!url) return false
-  const pending: PendingItem = { name: item.name, url, mimeType: item.mimeType }
-  sessionStorage.setItem(KEY, JSON.stringify(pending))
-  return true
-}
-
-export async function loadComposerFile(item: ComposerFileSource): Promise<File | null> {
-  const url = item.downloadUrl || item.previewUrl
-  if (!url || !item.name) return null
-  try {
-    const response = await fetch(url, { credentials: 'same-origin' })
-    if (!response.ok) throw new Error(`下载文件失败(${response.status})`)
-    const blob = await response.blob()
-    return new File([blob], item.name, { type: item.mimeType || blob.type || 'application/octet-stream' })
-  } catch {
-    return null
-  }
-}
-
-export async function consumeLibraryItemForComposer(): Promise<File | null> {
-  const raw = sessionStorage.getItem(KEY)
-  if (!raw) return null
-  sessionStorage.removeItem(KEY)
-  try {
-    const pending = JSON.parse(raw) as PendingItem
-    return await loadComposerFile({ name: pending.name, downloadUrl: pending.url, mimeType: pending.mimeType })
-  } catch {
-    return null
-  }
-}

+ 7 - 8
src/client/router/index.ts

@@ -1,21 +1,20 @@
 import { createRouter, createWebHistory } from 'vue-router'
-import { rememberInterfacePath, savedInterfacePath } from '@/utils/interfaceMode'
 
 const router = createRouter({
   history: createWebHistory(),
   routes: [
-    { path: '/', redirect: () => savedInterfacePath() },
-    { path: '/chat/:sessionId?', name: 'chat', component: () => import('@/views/ChatView.vue') },
-    { path: '/history/:sessionId?', name: 'history', component: () => import('@/views/HistoryView.vue') },
+    // Bot mode is the only interface; retired ordinary-mode URLs land on the Bot list.
+    { path: '/', redirect: '/conversations' },
+    { path: '/chat/:sessionId?', redirect: '/conversations' },
+    { path: '/history/:sessionId?', redirect: '/conversations' },
     { path: '/conversations/computer/:agentId', name: 'computer', component: () => import('@/views/ComputerViewerView.vue') },
     { path: '/conversations/automations', name: 'bot-automations', component: () => import('@/views/BotAutomationsView.vue') },
     { path: '/conversations/:id?', name: 'conversations', component: () => import('@/views/ConversationsView.vue') },
-    { path: '/files', name: 'files', component: () => import('@/views/FilesView.vue') },
-    { path: '/artifacts', redirect: '/chat' },
-    { path: '/:pathMatch(.*)*', redirect: '/chat' },
+    { path: '/files', redirect: '/conversations' },
+    { path: '/artifacts', redirect: '/conversations' },
+    { path: '/:pathMatch(.*)*', redirect: '/conversations' },
   ],
   scrollBehavior: () => ({ top: 0 }),
 })
-router.afterEach(to => { if (to.name !== 'computer') rememberInterfacePath(to.path) })
 
 export default router

+ 0 - 1105
src/client/stores/chat.ts

@@ -1,1105 +0,0 @@
-import { computed, reactive, ref, watch } from 'vue'
-import { defineStore } from 'pinia'
-import type {
-  ApprovalRequest, ChatAttachment, ChatMessage, ChatRouteState, JsonValue, ModelOption, RealtimeConnectionState, SessionSummary,
-} from '@shared/types'
-import {
-  deleteSession as deleteSessionApi, getMessages, getSession, getSessions, getSessionUnread, markSessionRead, updateSession, requestHistorySync,
-} from '@/api/sessions'
-import { getModels } from '@/api/profiles'
-import { ChatRpcSocket, RpcError } from '@/api/realtime'
-import { ChatTranscriptClient } from '@/api/chatTranscript'
-import type { TranscriptMessage, TranscriptSnapshot } from '@shared/chatTranscript'
-import { ApiError } from '@/api/client'
-import { encodeAttachment, imageAttachmentReference } from '@/utils/attachments'
-import { ScopedCache } from '@/utils/cache'
-import { createId, routeKey } from '@/utils/id'
-import { applyChatEvent, chatHasUnfinishedOutput, mergeChatMessages, settleChatMessages } from '@/utils/messageReducer'
-import { reconcileChatHistory } from '@/utils/chatHistory'
-import { bool, normalizeChatMessage, number, record, string, values } from '@/utils/normalize'
-import { appendSessionPage, pinnedSessionsFirst } from '@/utils/sessionOrder'
-import { modelForSession, modelSelectionFromSessionInfo } from '@/utils/sessionModel'
-import { moveSessionFastMode, readSessionFastMode, writeSessionFastMode } from '@/utils/sessionPreferences'
-import { normalizeChatUsage } from '@/utils/contextUsage'
-import { useAuthStore } from './auth'
-
-interface CachedHistory { messages: ChatMessage[]; total: number; savedAt: number; transcript?: Omit<TranscriptSnapshot,'messages'> }
-const historyCache = new ScopedCache<CachedHistory>('chat-history-v1')
-const INFLIGHT_SESSION_STORAGE_PREFIX = 'hermes-yaoyao:inflight-chat-sessions:'
-const SESSION_LIST_REFRESH_DEBOUNCE_MS = 200
-
-interface InflightSessionMarker {
-  profile: string
-  sessionId: string
-}
-
-function sessionStorageForInFlightSessions(): Storage | undefined {
-  if (typeof window === 'undefined') return undefined
-  try { return window.sessionStorage } catch { return undefined }
-}
-
-function readInflightSessionMarkers(accountId: string): InflightSessionMarker[] {
-  const storage = sessionStorageForInFlightSessions()
-  if (!storage) return []
-  try {
-    const value: unknown = JSON.parse(storage.getItem(`${INFLIGHT_SESSION_STORAGE_PREFIX}${accountId}`) ?? '[]')
-    if (!Array.isArray(value)) return []
-    return value.flatMap(item => {
-      const marker = record(item)
-      const profile = string(marker.profile)
-      const sessionId = string(marker.sessionId)
-      return profile && sessionId ? [{ profile, sessionId }] : []
-    })
-  } catch { return [] }
-}
-
-function writeInflightSessionMarkers(accountId: string, markers: InflightSessionMarker[]): void {
-  const storage = sessionStorageForInFlightSessions()
-  if (!storage) return
-  try {
-    const key = `${INFLIGHT_SESSION_STORAGE_PREFIX}${accountId}`
-    if (markers.length) storage.setItem(key, JSON.stringify(markers))
-    else storage.removeItem(key)
-  } catch { /* Storage can be unavailable in privacy-restricted browsers. */ }
-}
-
-function emptyRoute(profile: string, sessionId: string): ChatRouteState {
-  return {
-    route: { profile, sessionId }, messages: [], historySynced: false, hasMoreBefore: false,
-    loadedMessageCount: 0, messageTotal: 0, isLoadingHistory: false, isStreaming: false,
-    isQueued: false, generation: 0,
-  }
-}
-
-function errorMessage(cause: unknown): string {
-  return cause instanceof Error ? cause.message : '聊天请求失败'
-}
-
-function resultRecord(value: JsonValue): Record<string, unknown> { return record(value) }
-
-function optionalBoolean(value: unknown): boolean | undefined {
-  if (typeof value === 'boolean') return value
-  if (value === 'true' || value === 'fast') return true
-  if (value === 'false' || value === 'normal') return false
-  return undefined
-}
-
-export const useChatStore = defineStore('chat', () => {
-  const auth = useAuthStore()
-  const sessions = ref<SessionSummary[]>([])
-  const activeSessionId = ref<string>()
-  const activeProfileName = ref<string>()
-  const routes = reactive<Record<string, ChatRouteState>>({})
-  const connectionState = ref<RealtimeConnectionState>('idle')
-  const historySynced = computed(() => activeRouteState.value?.historySynced ?? false)
-  const isLoading = ref(false)
-  const isLoadingMoreSessions = ref(false)
-  const hasMoreSessions = ref(false)
-  const isSending = ref(false)
-  const error = ref<string>()
-  const models = ref<ModelOption[]>([])
-  const unreadCounts = ref<Record<string, number>>({})
-  const contextUsageRequests = new Map<string, number>()
-  const selectedModel = ref<ModelOption>()
-  const reasoningEffort = ref<string>()
-  const socket = new ChatRpcSocket()
-  const runtimeRoutes = new Map<string, string>()
-  const desiredModelRoutes = new Set<string>()
-  // Model selection warnings are local config.set replies, not transcript approvals.
-  // Keep them separate so another viewer's transcript cannot dismiss them.
-  const pendingModelConfirmations = reactive(new Map<string, { routeKey: string; model: ModelOption; approval: ApprovalRequest }>())
-  let connectPromise: Promise<void> | undefined
-  let reconnectTimer: number | undefined
-  let reconnectAttempt = 0
-  let sessionLoadGeneration = 0
-  let sessionListProfile: string | undefined
-  let sessionListRefreshTimer: number | undefined
-  let nextSessionCursor: string | undefined
-  let modelLoadGeneration = 0
-  let unreadLoadGeneration = 0
-  let historyLoadGeneration = 0
-  let reconnectResumePromise: Promise<unknown> | undefined
-  let persistedRecoveryPromise: Promise<void> | undefined
-  const runtimePromises = new Map<string, Promise<ChatRouteState>>()
-  const transcriptSupported = ref(false)
-  const outboxCache = new ScopedCache<ChatMessage[]>('ordinary-outbox-v2')
-  let transcript: ChatTranscriptClient | undefined
-  let transcriptGeneration = 0
-
-  function startTranscript(): void {
-    const generation=++transcriptGeneration
-    transcript?.close();transcript=undefined
-    const profile=activeProfileName.value,id=activeSessionId.value,owner=accountId()
-    if(!transcriptSupported.value||!profile||!id||id.startsWith('draft-')||sessionView==='history'||!sessions.value.some(s=>s.id===id&&s.owned===true))return
-    const key=routeKey(profile,id),state=ensureRoute(profile,id),scope=cacheScope(profile)
-    const current=()=>generation===transcriptGeneration&&owner===accountId()?routes[key]:undefined
-    void (async()=>{
-      const [cached,outbox]=await Promise.all([historyCache.get(scope,id),outboxCache.get(scope,id)])
-      if(!current())return
-      if(!state.messages.length&&cached?.messages.length)state.messages=cached.messages
-      if(outbox?.length)state.messages=mergeChatMessages(state.messages,outbox)
-      const client=new ChatTranscriptClient(profile,id,async value=>{
-        const initial=current();if(!initial)return
-        const canonical=value.messages.map(message=>{
-          const mapped=normalizeChatMessage(message,id,profile)
-          const local=initial.messages.find(m=>m.role==='user'&&mapped.clientMessageId&&m.clientMessageId===mapped.clientMessageId)
-          if(!mapped.attachments?.length&&local?.attachments?.length)mapped.attachments=local.attachments
-          if(message.status==='pending')mapped.stage='pending'
-          return mapped
-        })
-        const ids=new Set(canonical.flatMap(m=>[m.id,m.clientMessageId].filter(Boolean)))
-        const pending=initial.messages.filter(m=>m.role==='user'&&m.stage!=='settled'&&!ids.has(m.id)&&!ids.has(m.clientMessageId))
-        // Unsent local inputs keep their original time among server messages;
-        // appending the outbox would move old failures below every new reply.
-        const messages=mergeChatMessages(canonical,pending)
-        const {messages:_,...checkpoint}=value
-        await historyCache.set(scope,id,{messages,total:value.total,savedAt:Date.now(),transcript:checkpoint},true)
-        const beforeOutbox=current();if(!beforeOutbox)return
-        const newerPending=beforeOutbox.messages.filter(m=>m.role==='user'&&m.stage!=='settled'&&!ids.has(m.id)&&!ids.has(m.clientMessageId))
-        await outboxCache.set(scope,id,newerPending,true)
-        // Usage events replace the route while storage is pending. Commit to
-        // the current route after both writes, preserving any newer local send.
-        const latest=current();if(!latest)return
-        const usage=normalizeChatUsage(value.session)
-        if(usage && (['contextTokens','contextLimit','percentUsed'] as const)
-          .some(field => latest.usage?.[field] === undefined && usage[field] !== undefined)) {
-          latest.usage={...usage,...latest.usage}
-        }
-        const latestPending=latest.messages.filter(m=>m.role==='user'&&m.stage!=='settled'&&!ids.has(m.id)&&!ids.has(m.clientMessageId))
-        latest.messages=mergeChatMessages(canonical,latestPending);latest.messageTotal=value.total;latest.loadedMessageCount=canonical.length
-        const approval=value.pendingApproval,clarification=value.pendingClarification
-        latest.pendingApproval=approval?{id:string(approval.request_id??approval.id),sessionId:id,message:string(approval.message??approval.prompt),toolName:string(approval.tool_name),choices:values(approval.choices).map(String),payload:approval as Record<string,JsonValue>}:undefined
-        latest.pendingClarification=clarification?{id:string(clarification.request_id??clarification.id),sessionId:id,question:string(clarification.question??clarification.prompt),payload:clarification as Record<string,JsonValue>}:undefined
-        latest.liveStatus=value.liveStatus??undefined
-        latest.hasMoreBefore=value.hasOlder;latest.historySynced=true;latest.isLoadingHistory=false;latest.error=value.error??undefined
-        const wasStreaming=latest.isStreaming
-        latest.isStreaming=value.running??canonical.some(m=>m.isStreaming||chatHasUnfinishedOutput([m]));latest.isQueued=value.queued??false
-        if(wasStreaming&&!latest.isStreaming)void refreshContextUsage(latest).catch(()=>{})
-        if(!latest.isStreaming)latest.liveStatus=undefined
-        updateInflightMarker(latest)
-      },error=>{const latest=current();if(latest){latest.error=error.message;latest.historySynced=false}},Math.max(150,state.messages.length))
-      if(cached?.transcript?.protocol==='ordinary-chat-transcript-v2'){
-        const canonical=cached.messages.map(m=>m.raw as unknown as TranscriptMessage).filter(m=>m?.id&&Number.isSafeInteger(m.revision)&&Number.isSafeInteger(m.seq))
-        client.restore({...cached.transcript,messages:canonical})
-      }
-      transcript=client;await client.run()
-    })().catch(error=>{const latest=current();if(latest)latest.error=errorMessage(error)})
-  }
-  watch(()=>[activeSessionId.value,activeProfileName.value,transcriptSupported.value,auth.user?.id],startTranscript)
-
-  const activeRouteState = computed(() => {
-    if (!activeSessionId.value || !activeProfileName.value) return undefined
-    return routes[routeKey(activeProfileName.value, activeSessionId.value)]
-  })
-  const fastMode = computed(() => activeRouteState.value?.fastMode ?? false)
-  const activeSession = computed(() => sessions.value.find(session => session.id === activeSessionId.value
-    && (!activeProfileName.value || session.profile === activeProfileName.value)))
-  const messages = computed(() => activeRouteState.value?.messages ?? [])
-  const hasMoreBefore = computed(() => activeRouteState.value?.hasMoreBefore ?? false)
-  const isStreaming = computed(() => activeRouteState.value?.isStreaming ?? false)
-  const isQueued = computed(() => activeRouteState.value?.isQueued ?? false)
-  const contextUsage = computed(() => activeRouteState.value?.usage)
-  const pendingApproval = computed(() => {
-    const state = activeRouteState.value
-    if (!state) return undefined
-    const key = routeKey(state.route.profile, state.route.sessionId)
-    return [...pendingModelConfirmations.values()].find(value => value.routeKey === key)?.approval ?? state.pendingApproval
-  })
-  const pendingClarification = computed(() => activeRouteState.value?.pendingClarification)
-
-  function ensureRoute(profile: string, sessionId: string): ChatRouteState {
-    const key = routeKey(profile, sessionId)
-    if (!routes[key]) {
-      routes[key] = emptyRoute(profile, sessionId)
-      routes[key].fastMode = readSessionFastMode(auth.user?.id ?? 'local', profile, sessionId)
-    }
-    return routes[key]
-  }
-
-  function persistFastMode(state: ChatRouteState): void {
-    writeSessionFastMode(auth.user?.id ?? 'local', state.route.profile, state.route.sessionId, state.fastMode ?? false)
-  }
-
-  function syncSelectedModel(model?: string, provider?: string): void {
-    const resolved = modelForSession(models.value, model, provider)
-    if (resolved) selectedModel.value = resolved
-  }
-
-  function restoreSelectedSessionModel(key: string): void {
-    const activeKey = activeSessionId.value && activeProfileName.value
-      ? routeKey(activeProfileName.value, activeSessionId.value)
-      : undefined
-    if (key === activeKey) syncSelectedModel(activeSession.value?.model, activeSession.value?.provider)
-  }
-
-  function reconcileSessionModel(profile: string, sessionId: string, model: string, provider?: string): void {
-    const key = routeKey(profile, sessionId)
-    const sessionIndex = sessions.value.findIndex(session => session.id === sessionId && session.profile === profile)
-    if (sessionIndex >= 0) {
-      sessions.value.splice(sessionIndex, 1, {
-        ...sessions.value[sessionIndex], model, provider,
-      })
-    }
-    const activeKey = activeSessionId.value && activeProfileName.value
-      ? routeKey(activeProfileName.value, activeSessionId.value)
-      : undefined
-    if (key === activeKey && !desiredModelRoutes.has(key)) syncSelectedModel(model, provider)
-  }
-
-  function reconcileSessionTitle(profile: string | undefined, sessionId: string, title: string): void {
-    const normalized = title.trim()
-    if (!sessionId || !normalized) return
-    const index = sessions.value.findIndex(session => session.id === sessionId
-      && (!profile || !session.profile || session.profile === profile))
-    if (index < 0 || sessions.value[index].title === normalized) return
-    sessions.value.splice(index, 1, { ...sessions.value[index], title: normalized })
-  }
-
-  function cancelSessionListRefresh(): void {
-    if (sessionListRefreshTimer === undefined) return
-    window.clearTimeout(sessionListRefreshTimer)
-    sessionListRefreshTimer = undefined
-  }
-
-  function scheduleSessionListRefresh(): void {
-    if (auth.status !== 'authenticated') return
-    cancelSessionListRefresh()
-    sessionListRefreshTimer = window.setTimeout(() => {
-      sessionListRefreshTimer = undefined
-      void loadSessions(sessionListProfile ?? auth.activeProfile?.name, sessionView).catch(() => undefined)
-    }, SESSION_LIST_REFRESH_DEBOUNCE_MS)
-  }
-
-  function cacheScope(profile: string): string {
-    return `${auth.user?.id ?? 'anonymous'}:${profile}`
-  }
-
-  function scheduleReconnect(): void {
-    if (!auth.isAuthenticated || reconnectTimer !== undefined) return
-    const delay = Math.min(15_000, 500 * 2 ** Math.min(reconnectAttempt, 5))
-    reconnectAttempt += 1
-    connectionState.value = 'reconnecting'
-    reconnectTimer = window.setTimeout(() => {
-      reconnectTimer = undefined
-      void connect().catch(() => scheduleReconnect())
-    }, delay)
-  }
-
-  function accountId(): string { return auth.user?.id ?? 'anonymous' }
-
-  function updateInflightMarker(state: ChatRouteState): void {
-    const markers = readInflightSessionMarkers(accountId())
-    const matches = (marker: InflightSessionMarker) => marker.profile === state.route.profile
-      && marker.sessionId === state.route.sessionId
-    const shouldKeep = state.isStreaming || state.isQueued || Boolean(state.pendingApproval) || Boolean(state.pendingClarification)
-    const next = shouldKeep
-      ? [...markers.filter(marker => !matches(marker)), { profile: state.route.profile, sessionId: state.route.sessionId }]
-      : markers.filter(marker => !matches(marker))
-    writeInflightSessionMarkers(accountId(), next)
-  }
-
-  function clearInflightMarker(profile: string, sessionId: string): void {
-    const markers = readInflightSessionMarkers(accountId())
-    writeInflightSessionMarkers(accountId(), markers.filter(marker => marker.profile !== profile || marker.sessionId !== sessionId))
-  }
-
-  function recoverPersistedInflightSessions(): Promise<void> | undefined {
-    if (!auth.isAuthenticated || persistedRecoveryPromise) return persistedRecoveryPromise
-    const markers = readInflightSessionMarkers(accountId())
-    if (!markers.length) return undefined
-    const operation = Promise.all(markers.map(async marker => {
-      const state = ensureRoute(marker.profile, marker.sessionId)
-      try {
-        const resumed = await ensureRuntime(state)
-        updateInflightMarker(resumed)
-      } catch {
-        // Keep the marker. A transient reconnect failure must not turn into an
-        // accidental interruption before Hermes's disconnect grace expires.
-      }
-    })).then(() => undefined)
-    persistedRecoveryPromise = operation.finally(() => { persistedRecoveryPromise = undefined })
-    return persistedRecoveryPromise
-  }
-
-  socket.onState((state, reason) => {
-    connectionState.value = state
-    if (state === 'ready') {
-      reconnectAttempt = 0
-      const active = activeRouteState.value
-      if (active?.historySynced && (active.isStreaming || activeSession.value?.owned === true)
-        && !active.route.sessionId.startsWith('draft-') && !active.runtimeSessionId && !reconnectResumePromise) {
-        reconnectResumePromise = ensureRuntime(active)
-          .then(current => refreshContextUsage(current))
-          .catch(cause => { active.error = errorMessage(cause) })
-          .finally(() => { reconnectResumePromise = undefined })
-      }
-      void recoverPersistedInflightSessions()
-    }
-    if (state === 'failed') {
-      runtimeRoutes.clear()
-      for (const route of Object.values(routes)) {
-        route.runtimeSessionId = undefined
-        route.serverFastMode = undefined
-      }
-      error.value = reason || '聊天实时连接已断开'
-      scheduleReconnect()
-    }
-  })
-
-  function migrateRoute(oldKey: string, storedSessionId: string, runtimeSessionId: string): ChatRouteState {
-    const oldState = routes[oldKey]
-    if (!oldState) throw new Error('会话状态已经失效')
-    const newKey = routeKey(oldState.route.profile, storedSessionId)
-    const target = routes[newKey]
-    const migrated: ChatRouteState = {
-      ...(target ?? oldState),
-      route: { profile: oldState.route.profile, sessionId: storedSessionId },
-      messages: target ? mergeChatMessages(target.messages, oldState.messages) : oldState.messages,
-      runtimeSessionId,
-    }
-    routes[newKey] = migrated
-    if (newKey !== oldKey) delete routes[oldKey]
-    if (desiredModelRoutes.delete(oldKey)) desiredModelRoutes.add(newKey)
-    runtimeRoutes.set(runtimeSessionId, newKey)
-    if (activeSessionId.value === oldState.route.sessionId && activeProfileName.value === oldState.route.profile) {
-      activeSessionId.value = storedSessionId
-    }
-    if (newKey !== oldKey) {
-      moveSessionFastMode(auth.user?.id ?? 'local', oldState.route.profile, oldState.route.sessionId, storedSessionId, migrated.fastMode ?? false)
-    }
-    const draftIndex = sessions.value.findIndex(session => session.id === oldState.route.sessionId && session.profile === oldState.route.profile)
-    const now = Date.now() / 1000
-    const summary: SessionSummary = draftIndex >= 0
-      ? { ...sessions.value[draftIndex], id: storedSessionId, owned: true,
-          updatedAt: newKey === oldKey ? sessions.value[draftIndex].updatedAt : now }
-      : { id: storedSessionId, profile: oldState.route.profile, source: 'web', owned: true, title: '新会话', messageCount: 0, toolCallCount: 0, startedAt: now, updatedAt: now }
-    if (draftIndex >= 0) sessions.value.splice(draftIndex, 1, summary)
-    else sessions.value.unshift(summary)
-    return routes[newKey]
-  }
-
-  socket.onEvent(event => {
-    if (event.type === 'gateway.ready') return
-    const payload = record(event.payload)
-    if (event.type === 'sessions.changed') {
-      if(!transcriptSupported.value && payload.reason==='cache.synced' && typeof payload.profile==='string' && typeof payload.session_id==='string'){
-        const state=routes[routeKey(payload.profile,payload.session_id)]
-        if(state){
-          state.historySyncRevision=(state.historySyncRevision??0)+1
-          state.historySynced=false
-        }
-        if(state && state===activeRouteState.value && !state.isLoadingHistory)
-          void loadHistory(state).catch(()=>{})
-      }
-      scheduleSessionListRefresh()
-      return
-    }
-    const runtimeId = string(event.session_id ?? payload.session_id ?? payload.sessionId)
-    let key = runtimeRoutes.get(runtimeId)
-    if (!key) key = Object.keys(routes).find(candidate => routes[candidate].runtimeSessionId === runtimeId
-      || routes[candidate].route.sessionId === runtimeId)
-    if (event.type === 'session.title' || event.type === 'session.title.updated') {
-      const state = key ? routes[key] : undefined
-      const storedSessionId = state?.route.sessionId
-        || string(payload.stored_session_id ?? payload.storedSessionId ?? payload.session_key
-          ?? payload.session_id ?? payload.sessionId)
-      const profile = state?.route.profile || string(event.profile ?? payload.profile) || undefined
-      reconcileSessionTitle(profile, storedSessionId, string(payload.title))
-      scheduleSessionListRefresh()
-      if (!key) return
-    }
-    if (!key) return
-    let state = routes[key]
-    if(sessionView==='chat'&&(
-      /^(message\.|tool\.|reasoning\.|thinking\.)/.test(event.type)
-      || ['run.started','run.completed','run.failed','run.peer_user_message','peer.user.message'].includes(event.type))){
-      // All ordinary message bodies and execution state come from the durable
-      // transcript. Raw upstream frames cannot create a second representation.
-      return
-    }
-    if (event.type === 'session.info') {
-      const storedId = string(payload.stored_session_id ?? payload.storedSessionId ?? payload.session_key)
-      if (storedId && storedId !== state.route.sessionId) {
-        state = migrateRoute(key, storedId, runtimeId)
-        key = routeKey(state.route.profile, storedId)
-      }
-      const liveSelection = modelSelectionFromSessionInfo(payload)
-      if (liveSelection) {
-        reconcileSessionModel(state.route.profile, state.route.sessionId, liveSelection.model, liveSelection.provider)
-      }
-      const usage = normalizeChatUsage(payload)
-      if (usage) state.usage = { ...state.usage, ...usage }
-    }
-    const info = record(payload.info)
-    const liveFastMode = optionalBoolean(payload.fast ?? info.fast)
-    if (liveFastMode !== undefined && (event.type === 'session.info' || (event.type === 'session.command' && payload.action === 'fast'))) {
-      state.serverFastMode = liveFastMode
-      if (!state.fastModeDirty) state.fastMode = liveFastMode
-      persistFastMode(state)
-    }
-    if(sessionView==='chat'&&!['session.usage','usage.update','context.update'].includes(event.type))return
-    const attributedPayload = { ...payload, session_id: state.route.sessionId } as JsonValue
-    const updated = applyChatEvent(state, {
-      ...event, session_id: state.route.sessionId, profile: state.route.profile, payload: attributedPayload,
-    })
-    routes[key] = updated
-    updateInflightMarker(updated)
-    if (['message.complete', 'run.completed'].includes(event.type)) {
-      void refreshContextUsage(updated).catch(() => undefined)
-    }
-  })
-
-  async function connect(): Promise<void> {
-    if (['connected', 'ready'].includes(connectionState.value)) return
-    if (connectPromise) return connectPromise
-    if (reconnectTimer !== undefined) {
-      window.clearTimeout(reconnectTimer)
-      reconnectTimer = undefined
-    }
-    connectPromise = socket.connect().then(()=>{if(auth.isAuthenticated)transcriptSupported.value=socket.transcriptSupported===true}).catch(cause => {
-      connectionState.value = 'failed'
-      error.value = errorMessage(cause)
-      throw cause
-    }).finally(() => { connectPromise = undefined })
-    return connectPromise
-  }
-
-  function disconnect(): void {
-    transcriptGeneration++;transcript?.close();transcript=undefined;transcriptSupported.value=false
-    if (reconnectTimer !== undefined) window.clearTimeout(reconnectTimer)
-    reconnectTimer = undefined
-    socket.close()
-    runtimeRoutes.clear()
-    runtimePromises.clear()
-    desiredModelRoutes.clear()
-    pendingModelConfirmations.clear()
-    cancelSessionListRefresh()
-    for (const state of Object.values(routes)) {
-      state.runtimeSessionId = undefined
-      state.serverFastMode = undefined
-    }
-  }
-
-  function switchProfile(profile: string): void {
-    sessionLoadGeneration += 1
-    modelLoadGeneration += 1
-    unreadLoadGeneration += 1
-    disconnect()
-    activeSessionId.value = undefined
-    activeProfileName.value = profile
-    nextSessionCursor = undefined
-    hasMoreSessions.value = false
-    isLoadingMoreSessions.value = false
-    error.value = undefined
-  }
-
-  function clearAccountState(): void {
-    sessions.value = []
-    nextSessionCursor = undefined
-    hasMoreSessions.value = false
-    isLoadingMoreSessions.value = false
-    activeSessionId.value = undefined
-    activeProfileName.value = undefined
-    sessionListProfile = undefined
-    cancelSessionListRefresh()
-    runtimeRoutes.clear()
-    for (const key of Object.keys(routes)) delete routes[key]
-    unreadCounts.value = {}
-    error.value = undefined
-  }
-
-  watch(() => auth.status, status => {
-    if (status !== 'authenticated') {
-      disconnect()
-      clearAccountState()
-    }
-  })
-
-  let sessionView: 'chat' | 'history' = 'chat'
-  async function loadSessions(profile?: string, view: 'chat' | 'history' = sessionView): Promise<void> {
-    sessionView = view
-    const requestedProfile = profile || undefined
-    sessionListProfile = requestedProfile
-    const loadGeneration = ++sessionLoadGeneration
-    isLoading.value = true
-    error.value = undefined
-    try {
-      const page = await getSessions(requestedProfile, undefined, 100, sessionView)
-      if (loadGeneration !== sessionLoadGeneration
-        || (requestedProfile && auth.activeProfile?.name !== requestedProfile)) return
-      // 9119 owns recency within each bucket. Pinning is an explicit user
-      // command, so pinned sessions always form the visible top partition.
-      sessions.value = pinnedSessionsFirst(page.items)
-      nextSessionCursor = page.nextCursor ?? undefined
-      hasMoreSessions.value = Boolean(nextSessionCursor)
-    } catch (cause) {
-      if (loadGeneration === sessionLoadGeneration) error.value = errorMessage(cause)
-      throw cause
-    } finally {
-      if (loadGeneration === sessionLoadGeneration) isLoading.value = false
-    }
-  }
-
-  async function loadMoreSessions(profile = auth.activeProfile?.name): Promise<void> {
-    const cursor = nextSessionCursor
-    const requestedProfile = profile || undefined
-    if (!cursor || isLoadingMoreSessions.value) return
-    const loadGeneration = sessionLoadGeneration
-    isLoadingMoreSessions.value = true
-    try {
-      const page = await getSessions(requestedProfile, cursor, 100, sessionView)
-      if (loadGeneration !== sessionLoadGeneration
-        || (requestedProfile && auth.activeProfile?.name !== requestedProfile)) return
-      sessions.value = appendSessionPage(sessions.value, page.items)
-      nextSessionCursor = page.nextCursor ?? undefined
-      hasMoreSessions.value = Boolean(nextSessionCursor)
-    } catch (cause) {
-      if (loadGeneration === sessionLoadGeneration) error.value = errorMessage(cause)
-      throw cause
-    } finally {
-      if (loadGeneration === sessionLoadGeneration) isLoadingMoreSessions.value = false
-    }
-  }
-
-  async function loadUnread(profile?: string): Promise<void> {
-    const loadGeneration = ++unreadLoadGeneration
-    const loaded = await getSessionUnread(profile)
-    if (loadGeneration === unreadLoadGeneration && (!profile || auth.activeProfile?.name === profile)) {
-      unreadCounts.value = loaded
-    }
-  }
-
-  async function markRead(sessionId = activeSessionId.value, profile = activeProfileName.value): Promise<void> {
-    if (!sessionId) return
-    const state = profile ? routes[routeKey(profile, sessionId)] : undefined
-    const summaryCount = sessions.value.find(session => session.id === sessionId)?.messageCount ?? 0
-    const count = Math.max(state?.messageTotal ?? 0, summaryCount)
-    await markSessionRead(sessionId, count, profile)
-    unreadCounts.value = { ...unreadCounts.value, [sessionId]: 0 }
-  }
-
-  async function loadHistory(state: ChatRouteState, forceRefresh = false): Promise<void> {
-    if(sessionView==='chat'&&sessions.value.some(s=>s.id===state.route.sessionId&&s.owned===true)){
-      const cached=await historyCache.get(cacheScope(state.route.profile),state.route.sessionId)
-      if(!state.messages.length&&cached?.messages.length)state.messages=cached.messages
-      await connect()
-      if(!transcriptSupported.value)throw new Error('普通聊天需要升级服务端后继续')
-      if(state===activeRouteState.value)startTranscript()
-      return
-    }
-    const key = routeKey(state.route.profile, state.route.sessionId)
-    const generation = ++historyLoadGeneration
-    state.generation = generation
-    const syncRevision = state.historySyncRevision ?? 0
-    // SSE replaces a route state object. Resolve the current object after each
-    // await so history merges into its live tail instead of a detached copy.
-    const current = () => routes[key]?.generation === generation ? routes[key] : undefined
-    state.isLoadingHistory = true
-    state.error = undefined
-    const scope = cacheScope(state.route.profile)
-    const cached = await historyCache.get(scope, state.route.sessionId)
-    let latest = current()
-    if (!latest) return
-    if (cached?.messages.length) {
-      latest.messages = mergeChatMessages(latest.messages, cached.messages, 'snapshot')
-      latest.messageTotal = cached.total
-      latest.loadedMessageCount = cached.messages.length
-    }
-    try {
-      const page = await getMessages(state.route.sessionId, 0, 150, state.route.profile, false, sessionView)
-      latest = current()
-      if (!latest || (latest.historySyncRevision ?? 0) !== syncRevision) return
-      if (forceRefresh && latest.isStreaming) {
-        throw new Error('正在回复,请结束后再刷新历史')
-      }
-      const retained = forceRefresh ? latest.messages.filter(message => message.role === 'user' && message.stage !== 'settled') : latest.messages
-      latest.messages = reconcileChatHistory(retained, page.messages, latest.isStreaming)
-      latest.messageTotal = page.total
-      latest.loadedMessageCount = page.returned
-      latest.hasMoreBefore = page.hasMore
-      latest.historySynced = true
-      if (page.session) {
-        const index = sessions.value.findIndex(session => session.id === page.session!.id && session.profile === page.session!.profile)
-        if (index >= 0) sessions.value.splice(index, 1, page.session)
-      }
-      await historyCache.set(scope, state.route.sessionId, { messages: latest.messages, total: page.total, savedAt: Date.now() })
-    } catch (cause) {
-      latest = current()
-      if (latest) latest.error = errorMessage(cause)
-      if(cause instanceof ApiError && cause.code==='CHAT_HISTORY_SYNC_PENDING')return
-      throw cause
-    } finally {
-      latest = current()
-      if (latest) {
-        latest.isLoadingHistory = false
-        if ((latest.historySyncRevision ?? 0) !== syncRevision && latest === activeRouteState.value)
-          void loadHistory(latest).catch(() => {})
-      }
-    }
-  }
-
-  async function selectSession(sessionId: string, profile?: string): Promise<void> {
-    const session = sessions.value.find(item => item.id === sessionId && (!profile || item.profile === profile))
-    const selectedProfile = profile ?? session?.profile ?? auth.activeProfile?.name ?? 'default'
-    activeSessionId.value = sessionId
-    activeProfileName.value = selectedProfile
-    const state = ensureRoute(selectedProfile, sessionId)
-    syncSelectedModel(session?.model, session?.provider)
-    // REST owns history, but an owned chat also needs a runtime subscription:
-    // another device can start a turn while this viewer has never sent one.
-    // History-only sessions and unsent drafts must remain unattached.
-    if (sessionId.startsWith('draft-')) state.historySynced = true
-    else if (!state.historySynced) await loadHistory(state)
-    const refreshed = sessions.value.find(item => item.id === sessionId && item.profile === selectedProfile)
-    syncSelectedModel(refreshed?.model, refreshed?.provider)
-    if (refreshed?.owned === true && !sessionId.startsWith('draft-')
-      && activeSessionId.value === sessionId && activeProfileName.value === selectedProfile) {
-      const current = await ensureRuntime(routes[routeKey(selectedProfile, sessionId)] ?? state).catch(cause => {
-        const current = routes[routeKey(selectedProfile, sessionId)]
-        if (current) current.error = errorMessage(cause)
-      })
-      if (current) void refreshContextUsage(current).catch(() => undefined)
-    }
-  }
-
-  async function forceRefreshHistory(): Promise<void> {
-    const state = activeRouteState.value
-    if (!state || state.isLoadingHistory || state.isStreaming || state.isQueued || state.pendingApproval || state.pendingClarification || state.route.sessionId.startsWith('draft-')) return
-    if(sessionView==='history'){await loadHistory(state);return}
-    await requestHistorySync(state.route.sessionId,state.route.profile)
-    state.error='历史正在后台补齐,完成后会自动更新'
-  }
-
-  async function loadOlder(): Promise<void> {
-    if(sessionView==='chat'&&activeSession.value?.owned===true){await transcript?.loadOlder();return}
-    const state = activeRouteState.value
-    if (!state || state.isLoadingHistory || !state.hasMoreBefore) return
-    const key = routeKey(state.route.profile, state.route.sessionId)
-    const generation = state.generation
-    const syncRevision = state.historySyncRevision ?? 0
-    const current = () => routes[key]?.generation === generation ? routes[key] : undefined
-    state.isLoadingHistory = true
-    try {
-      const page = await getMessages(state.route.sessionId, state.loadedMessageCount, 150, state.route.profile, false, sessionView)
-      const latest = current()
-      if (!latest) return
-      latest.messages = mergeChatMessages(latest.messages, page.messages, 'prepend')
-      latest.loadedMessageCount += page.returned
-      latest.messageTotal = Math.max(latest.messageTotal, page.total)
-      latest.hasMoreBefore = page.hasMore
-      await historyCache.set(cacheScope(state.route.profile), state.route.sessionId, {
-        messages: latest.messages, total: latest.messageTotal, savedAt: Date.now(),
-      })
-    } catch (cause) { const latest = current(); if (latest) latest.error = errorMessage(cause) }
-    finally {
-      const latest = current()
-      if (latest) {
-        latest.isLoadingHistory = false
-        if ((latest.historySyncRevision ?? 0) !== syncRevision && latest === activeRouteState.value)
-          void loadHistory(latest).catch(() => {})
-      }
-    }
-  }
-
-  function createSession(profile = auth.activeProfile?.name ?? 'default'): string {
-    const id = `draft-${createId('session')}`
-    const now = Date.now() / 1000
-    sessions.value.unshift({ id, profile, source: 'web', title: '新会话', messageCount: 0, toolCallCount: 0, startedAt: now, updatedAt: now })
-    ensureRoute(profile, id)
-    activeSessionId.value = id
-    activeProfileName.value = profile
-    return id
-  }
-  function clearSelection(): void { activeSessionId.value = undefined }
-
-  async function performEnsureRuntime(initialState: ChatRouteState): Promise<ChatRouteState> {
-    if (initialState.runtimeSessionId) return initialState
-    await connect()
-    const initialKey = routeKey(initialState.route.profile, initialState.route.sessionId)
-    if (initialState.route.sessionId.startsWith('draft-')) {
-      const params: Record<string, JsonValue> = {
-        profile: initialState.route.profile, source: 'web', close_on_disconnect: false,
-      }
-      if (reasoningEffort.value) params.reasoning_effort = reasoningEffort.value
-      params.fast = initialState.fastMode ?? false
-      const result = resultRecord(await socket.request('session.create', params))
-      const runtimeId = string(result.session_id ?? result.sessionId)
-      const storedId = string(result.stored_session_id ?? result.storedSessionId ?? result.session_key)
-      if (!runtimeId || !storedId) throw new Error('Hermes 未返回新会话标识')
-      const migrated = migrateRoute(initialKey, storedId, runtimeId)
-      const info = record(result.info)
-      const usage = normalizeChatUsage(result)
-      if (usage) migrated.usage = { ...migrated.usage, ...usage }
-      if (!desiredModelRoutes.has(routeKey(migrated.route.profile, migrated.route.sessionId))) {
-        syncSelectedModel(string(result.model ?? info.model), string(result.provider ?? info.provider))
-      }
-      const liveFastMode = optionalBoolean(result.fast ?? info.fast)
-      migrated.serverFastMode = liveFastMode ?? migrated.fastMode ?? false
-      if (!migrated.fastModeDirty && liveFastMode !== undefined) migrated.fastMode = liveFastMode
-      migrated.fastModeDirty = false
-      persistFastMode(migrated)
-      return migrated
-    }
-    const result = resultRecord(await socket.request('session.resume', {
-      session_id: initialState.route.sessionId,
-      profile: initialState.route.profile,
-      source: 'web',
-      omit_messages: true,
-    }))
-    const runtimeId = string(result.session_id ?? result.sessionId)
-    if (!runtimeId) throw new Error('Hermes 未返回运行会话标识')
-    const storedId = string(result.stored_session_id ?? result.storedSessionId ?? result.session_key, initialState.route.sessionId)
-    const migrated = migrateRoute(initialKey, storedId, runtimeId)
-    migrated.error = undefined
-    const info = record(result.info)
-    const usage = normalizeChatUsage(result)
-    if (usage) migrated.usage = { ...migrated.usage, ...usage }
-    if (!desiredModelRoutes.has(routeKey(migrated.route.profile, migrated.route.sessionId))) {
-      syncSelectedModel(string(result.model ?? info.model), string(result.provider ?? info.provider))
-    }
-    const liveFastMode = optionalBoolean(result.fast ?? info.fast)
-    migrated.serverFastMode = liveFastMode
-    if (!migrated.fastModeDirty && liveFastMode !== undefined) migrated.fastMode = liveFastMode
-    persistFastMode(migrated)
-    // session.resume restores the execution route only. The server ingests its
-    // snapshot into the canonical turn before clients receive transcript events.
-    if (storedId !== initialState.route.sessionId) clearInflightMarker(initialState.route.profile, initialState.route.sessionId)
-    updateInflightMarker(migrated)
-    return migrated
-  }
-
-  async function ensureRuntime(initialState: ChatRouteState): Promise<ChatRouteState> {
-    if (initialState.runtimeSessionId) return initialState
-    const key = routeKey(initialState.route.profile, initialState.route.sessionId)
-    const existing = runtimePromises.get(key)
-    if (existing) return existing
-    let operation: Promise<ChatRouteState>
-    // Register the operation before connect can publish ready and re-enter.
-    operation = Promise.resolve().then(() => performEnsureRuntime(initialState)).finally(() => {
-      if (runtimePromises.get(key) === operation) runtimePromises.delete(key)
-    })
-    runtimePromises.set(key, operation)
-    return operation
-  }
-
-  function updateDelivery(state: ChatRouteState, clientMessageId: string, patch: Partial<ChatMessage>): void {
-    state.messages = state.messages.map(message => message.clientMessageId === clientMessageId || message.id === clientMessageId
-      ? { ...message, ...patch, stage: message.stage === 'settled' && patch.stage === 'accepted' ? 'settled' : patch.stage ?? message.stage }
-      : message)
-  }
-
-  async function send(
-    text: string,
-    files: File[] = [],
-    mode: 'submit' | 'queue' | 'steer' = 'submit',
-  ): Promise<void> {
-    let state = activeRouteState.value
-    if (!state) {
-      createSession()
-      state = activeRouteState.value!
-    }
-    const trimmed = text.trim()
-    if (!trimmed && !files.length) return
-    const clientMessageId = createId('message')
-    const attachments: ChatAttachment[] = files.map((file, index) => ({
-      id: `${clientMessageId}:${index}`, name: file.name, mimeType: file.type || 'application/octet-stream',
-      size: file.size, kind: file.type.startsWith('image/') ? 'image' : file.type === 'application/pdf' ? 'pdf' : 'file',
-    }))
-    const optimistic: ChatMessage = {
-      id: clientMessageId, clientMessageId, sessionId: state.route.sessionId, profile: state.route.profile,
-      role: 'user', content: trimmed, timestamp: Date.now() / 1000, stage: 'preparing', attachments,
-    }
-    state.messages = mergeChatMessages(state.messages, [optimistic])
-    isSending.value = true
-    error.value = undefined
-    let submitted = false
-    try {
-      state = await ensureRuntime(state)
-      const runtimeId = state.runtimeSessionId!
-      if (!await applyDesiredModel(state)) throw new Error('请先确认模型切换,再重新发送消息')
-      if (reasoningEffort.value) {
-        await socket.request('config.set', {
-          session_id: runtimeId, key: 'reasoning', value: reasoningEffort.value, scope: 'session',
-        })
-      }
-      const desiredFastMode = state.fastMode ?? false
-      if (state.serverFastMode !== desiredFastMode) {
-        await socket.request('config.set', {
-          session_id: runtimeId, key: 'fast', value: desiredFastMode ? 'fast' : 'normal', scope: 'session',
-        })
-        state.serverFastMode = desiredFastMode
-        state.fastModeDirty = false
-        persistFastMode(state)
-      }
-      const parts = trimmed ? [trimmed] : []
-      for (const [index, file] of files.entries()) {
-        const encoded = await encodeAttachment(file)
-        if (encoded.kind === 'image') {
-          const result = resultRecord(await socket.request('image.attach_bytes', {
-            session_id: runtimeId, content_base64: encoded.base64, filename: encoded.name, ext: encoded.extension,
-          }))
-          const path = string(result.image_path) || string(result.path) || string(result.ref_path)
-          const reference = imageAttachmentReference(path, state.route.profile)
-          if (reference) {
-            attachments[index] = { ...attachments[index]!, ...reference }
-            updateDelivery(state, clientMessageId, { attachments: [...attachments] })
-          }
-          parts.push([`[用户附加图片:${encoded.name}]`, path ? `@image:${path}` : '', '[screenshot]'].filter(Boolean).join('\n'))
-        } else if (encoded.kind === 'pdf') {
-          await socket.request('pdf.attach', { session_id: runtimeId, content_base64: encoded.base64, filename: encoded.name })
-          parts.push(`[用户附加 PDF:${encoded.name}]`)
-        } else {
-          const result = resultRecord(await socket.request('file.attach', {
-            session_id: runtimeId, name: encoded.name, data_url: encoded.dataUrl,
-          }))
-          parts.push(`[用户附加文件:${encoded.name}]${string(result.ref_text) ? `\n${string(result.ref_text)}` : ''}`)
-        }
-      }
-      updateDelivery(state, clientMessageId, { stage: files.length ? 'attached' : 'pending', sessionId: state.route.sessionId })
-      updateDelivery(state, clientMessageId, { stage: 'pending' })
-      await outboxCache.set(cacheScope(state.route.profile),state.route.sessionId,state.messages.filter(m=>m.role==='user'&&m.stage!=='settled'),true)
-      submitted = true
-      const effectiveMode = mode === 'steer' && files.length ? 'queue' : mode
-      const method = effectiveMode === 'steer' ? 'session.steer' : 'prompt.submit'
-      const result = resultRecord(await socket.request(method, {
-        session_id: runtimeId,
-        text: parts.join('\n\n'),
-        ...(effectiveMode === 'queue' ? { queued: true } : {}),
-      }, 120_000, `web:prompt:${clientMessageId}`))
-      const status = string(result.status, 'accepted').toLowerCase()
-      if (effectiveMode === 'steer' && !['accepted', 'queued', 'steered', 'streaming'].includes(status)) {
-        throw new RpcError(string(result.error ?? result.message, 'Hermes 拒绝了 Steer 请求'), status)
-      }
-      updateDelivery(state, clientMessageId, { stage: 'accepted' })
-      // A delayed HTTP receipt confirms the input, not a newer execution state.
-      // The transcript may already contain the completed reply at this point.
-      updateInflightMarker(state)
-      // The optimistic row remains local, but the sidebar is refreshed only
-      // after a 9119 receipt and keeps the order returned by the server.
-      void loadSessions(state.route.profile).catch(() => undefined)
-    } catch (cause) {
-      const explicitRejection = cause instanceof RpcError
-      const stage = submitted && !explicitRejection ? 'unknown-receipt' : 'failed'
-      updateDelivery(state, clientMessageId, { stage, error: errorMessage(cause) })
-      state.error = errorMessage(cause)
-      throw cause
-    } finally { isSending.value = false }
-  }
-
-  async function interrupt(): Promise<void> {
-    const state = activeRouteState.value
-    if (!state) return
-    const current = await ensureRuntime(state)
-    await socket.request('session.interrupt', { session_id: current.runtimeSessionId! }, 15_000)
-    current.isStreaming = false
-    current.isQueued = false
-    current.messages = settleChatMessages(current.messages)
-    clearInflightMarker(current.route.profile, current.route.sessionId)
-  }
-
-  async function respondToApproval(requestId: string, approved: boolean | 'once' | 'session' | 'always' | 'deny'): Promise<void> {
-    const state = activeRouteState.value
-    if (!state) return
-    const choice = typeof approved === 'boolean' ? approved ? 'once' : 'deny' : approved
-    const modelConfirmation = pendingModelConfirmations.get(requestId)
-    if (modelConfirmation) {
-      pendingModelConfirmations.delete(requestId)
-      const target = routes[modelConfirmation.routeKey]
-      if (!target) throw new Error('模型确认请求已失效')
-      const modelState = await ensureRuntime(target)
-      if (choice === 'deny') {
-        desiredModelRoutes.delete(modelConfirmation.routeKey)
-        restoreSelectedSessionModel(modelConfirmation.routeKey)
-      } else {
-        try {
-          if (await configureModel(modelState, modelConfirmation.model, true)) {
-            desiredModelRoutes.delete(modelConfirmation.routeKey)
-          }
-        } catch (cause) {
-          desiredModelRoutes.delete(modelConfirmation.routeKey)
-          restoreSelectedSessionModel(modelConfirmation.routeKey)
-          throw cause
-        }
-      }
-      return
-    }
-    if (state.pendingApproval?.id !== requestId) return
-    const current = await ensureRuntime(state)
-    await socket.request('approval.respond', { session_id: current.runtimeSessionId!, choice })
-    if (current.pendingApproval?.id === requestId) current.pendingApproval = undefined
-  }
-
-  async function respondToClarification(requestId: string, response: string): Promise<void> {
-    const state = activeRouteState.value
-    if (!state) return
-    const current = await ensureRuntime(state)
-    await socket.request('clarify.respond', { session_id: current.runtimeSessionId!, request_id: requestId, answer: response })
-    if (current.pendingClarification?.id === requestId) current.pendingClarification = undefined
-  }
-
-  async function branchSession(): Promise<string | undefined> {
-    const state = activeRouteState.value
-    if (!state) return
-    const current = await ensureRuntime(state)
-    const result = resultRecord(await socket.request('session.branch', { session_id: current.runtimeSessionId! }))
-    const runtimeId = string(result.session_id ?? result.sessionId)
-    const storedId = string(result.stored_session_id ?? result.storedSessionId)
-    if (!runtimeId || !storedId) throw new Error('Hermes 未返回分支会话标识')
-    const next = emptyRoute(current.route.profile, storedId)
-    next.runtimeSessionId = runtimeId
-    routes[routeKey(current.route.profile, storedId)] = next
-    runtimeRoutes.set(runtimeId, routeKey(current.route.profile, storedId))
-    activeSessionId.value = storedId
-    activeProfileName.value = current.route.profile
-    // The branch was created by 9119, but its position remains server-owned.
-    void loadSessions(current.route.profile).catch(() => undefined)
-    return storedId
-  }
-
-  async function renameSession(id: string, title: string, profile?: string): Promise<void> {
-    await updateSession(id, { title }, profile)
-    await loadSessions(profile)
-  }
-
-  async function setSessionPinned(id: string, pinned: boolean, profile?: string): Promise<void> {
-    await updateSession(id, { pinned }, profile)
-    await loadSessions(profile)
-  }
-
-  async function removeSession(id: string, profile?: string): Promise<void> {
-    if (!id.startsWith('draft-')) await deleteSessionApi(id, profile)
-    sessions.value = sessions.value.filter(session => session.id !== id || (profile && session.profile !== profile))
-    if (activeSessionId.value === id && (!profile || activeProfileName.value === profile)) {
-      activeSessionId.value = undefined
-      activeProfileName.value = undefined
-    }
-  }
-
-  async function loadModels(profile = auth.activeProfile?.name): Promise<void> {
-    const loadGeneration = ++modelLoadGeneration
-    const loaded = await getModels(profile)
-    if (loadGeneration !== modelLoadGeneration || (profile && auth.activeProfile?.name !== profile)) return
-    models.value = loaded
-    selectedModel.value = modelForSession(models.value, activeSession.value?.model, activeSession.value?.provider)
-      ?? models.value.find(model => model.isDefault) ?? models.value[0]
-  }
-
-  async function refreshActiveSessionModel(): Promise<void> {
-    const state = activeRouteState.value
-    if (!state || state.route.sessionId.startsWith('draft-')) return
-    const expectedKey = routeKey(state.route.profile, state.route.sessionId)
-    const refreshed = await getSession(state.route.sessionId, state.route.profile)
-    const current = activeRouteState.value
-    if (!current || routeKey(current.route.profile, current.route.sessionId) !== expectedKey || !refreshed.model) return
-    reconcileSessionModel(current.route.profile, current.route.sessionId, refreshed.model, refreshed.provider)
-  }
-
-  async function configureModel(state: ChatRouteState, model: ModelOption, confirmsExpensiveModel: boolean): Promise<boolean> {
-    const result = resultRecord(await socket.request('config.set', {
-      session_id: state.runtimeSessionId!,
-      key: 'model',
-      value: `${model.id} --provider ${model.provider} --session`,
-      ...(confirmsExpensiveModel ? { confirm_expensive_model: true } : {}),
-    }))
-    if (bool(result.confirm_required ?? result.confirmRequired)) {
-      const requestId = createId('expensive-model')
-      const approval: ApprovalRequest = {
-        id: requestId,
-        sessionId: state.route.sessionId,
-        message: string(result.confirm_message ?? result.confirmMessage ?? result.warning, '此模型可能产生较高费用,请确认后使用。'),
-        choices: ['once', 'deny'],
-        payload: result as Record<string, JsonValue>,
-      }
-      pendingModelConfirmations.set(requestId, { routeKey: routeKey(state.route.profile, state.route.sessionId), model, approval })
-      return false
-    }
-    // Match iOS: switching a model invalidates the cached fast-mode server
-    // state, so the desired mode is re-applied before the next prompt.
-    state.serverFastMode = undefined
-    return true
-  }
-
-  async function applyDesiredModel(state: ChatRouteState): Promise<boolean> {
-    const key = routeKey(state.route.profile, state.route.sessionId)
-    if (!desiredModelRoutes.has(key) || !selectedModel.value || !state.runtimeSessionId) return true
-    if ([...pendingModelConfirmations.values()].some(value => value.routeKey === key)) return false
-    const applied = await configureModel(state, selectedModel.value, false)
-    if (applied) desiredModelRoutes.delete(key)
-    return applied
-  }
-
-  async function setModel(model: ModelOption): Promise<void> {
-    selectedModel.value = model
-    const state = activeRouteState.value
-    if (!state) return
-    const key = routeKey(state.route.profile, state.route.sessionId)
-    for (const [id, pending] of pendingModelConfirmations) {
-      if (pending.routeKey === key) pendingModelConfirmations.delete(id)
-    }
-    desiredModelRoutes.add(key)
-    if (!state.runtimeSessionId) return
-    try {
-      if (await configureModel(state, model, false)) desiredModelRoutes.delete(key)
-    } catch (cause) {
-      desiredModelRoutes.delete(key)
-      restoreSelectedSessionModel(key)
-      throw cause
-    }
-  }
-
-  async function setFastMode(enabled: boolean): Promise<void> {
-    const state = activeRouteState.value
-    if (!state) return
-    const previous = state.fastMode ?? false
-    state.fastMode = enabled
-    state.fastModeDirty = true
-    persistFastMode(state)
-    if (!state.runtimeSessionId || state.isStreaming || !['connected', 'ready'].includes(connectionState.value)) return
-    try {
-      await socket.request('config.set', {
-        session_id: state.runtimeSessionId, key: 'fast', value: enabled ? 'fast' : 'normal', scope: 'session',
-      })
-      state.serverFastMode = enabled
-      state.fastModeDirty = false
-    } catch (cause) {
-      state.fastMode = previous
-      state.fastModeDirty = false
-      persistFastMode(state)
-      error.value = `快速模式未同步:${errorMessage(cause)}`
-      throw cause
-    }
-  }
-
-  async function refreshContextUsage(initialState = activeRouteState.value): Promise<void> {
-    // Opening history is read-only. Resuming an old session merely to fetch
-    // usage updates Hermes' last_active timestamp and incorrectly moves it
-    // into today's sidebar group.
-    if (!initialState || initialState.route.sessionId.startsWith('draft-') || !initialState.runtimeSessionId || initialState.isStreaming) return
-    const key = routeKey(initialState.route.profile, initialState.route.sessionId)
-    const runtimeId = initialState.runtimeSessionId
-    const generation = initialState.generation
-    const previousUsage = initialState.usage
-    const request = (contextUsageRequests.get(key) ?? 0) + 1
-    contextUsageRequests.set(key, request)
-    // Use the same source order as mobile. Breakdown can supply the gauge when
-    // session.usage only contains cumulative billing counters.
-    const results = await Promise.allSettled([
-      socket.request('session.usage', { session_id: runtimeId }, 15_000),
-      socket.request('session.context_breakdown', { session_id: runtimeId }, 15_000),
-    ])
-    const current = routes[key]
-    if (!current || current.generation !== generation || current.runtimeSessionId !== runtimeId
-      || current.usage !== previousUsage || contextUsageRequests.get(key) !== request) return
-    const usage = normalizeChatUsage(...results.flatMap(result => result.status === 'fulfilled' ? [result.value] : []))
-    if (usage) current.usage = { ...current.usage, ...usage }
-  }
-
-  return {
-    sessions, activeSessionId, activeProfileName, activeSession, routes, activeRouteState, messages,
-    connectionState, historySynced, hasMoreBefore, isLoading, isLoadingMoreSessions, hasMoreSessions, isSending, isStreaming, isQueued,
-    error, models, selectedModel, reasoningEffort, fastMode, contextUsage, pendingApproval, pendingClarification, unreadCounts,
-    loadSessions, loadMoreSessions, selectSession, loadOlder, forceRefreshHistory, createSession, clearSelection, connect, disconnect, send, interrupt,
-    respondToApproval, respondToClarification, branchSession, renameSession, setSessionPinned, removeSession,
-    loadModels, setModel, setFastMode, refreshActiveSessionModel, refreshContextUsage, loadUnread, markRead, switchProfile,
-  }
-})

+ 0 - 81
src/client/stores/files.ts

@@ -1,81 +0,0 @@
-import { computed, ref, shallowRef, watch } from 'vue'
-import { defineStore } from 'pinia'
-import type { FileKind, FileLibraryItem } from '@shared/types'
-import { getFiles } from '@/api/files'
-import { useAuthStore } from './auth'
-
-export const useFilesStore = defineStore('files', () => {
-  const auth = useAuthStore()
-  const items = shallowRef<FileLibraryItem[]>([])
-  const nextCursor = ref<string>()
-  const hasMore = ref(true)
-  const isLoading = ref(false)
-  const error = ref<string>()
-  const query = ref('')
-  const kindFilter = ref<FileKind | 'all'>('all')
-  const profile = ref<string>()
-  const visitedCursors = new Set<string>()
-  let loadGeneration = 0
-
-  const filteredItems = computed<FileLibraryItem[]>(() => items.value.filter(item => kindFilter.value === 'all' || item.kind === kindFilter.value))
-
-  async function load(reset = true): Promise<void> {
-    if (isLoading.value && !reset) return
-    const generation = ++loadGeneration
-    if (reset) {
-      items.value = []
-      nextCursor.value = undefined
-      hasMore.value = true
-      visitedCursors.clear()
-    } else if (!hasMore.value) return
-    isLoading.value = true
-    error.value = undefined
-    try {
-      const existing = new Map(items.value.map(item => [item.id, item]))
-      let cursor = reset ? undefined : nextCursor.value
-      let pages = 0
-      while (pages < 20) {
-        const cursorKey = cursor ?? '<first-page>'
-        if (visitedCursors.has(cursorKey)) {
-          hasMore.value = false
-          error.value = '文件分页返回了重复游标,已停止加载'
-          break
-        }
-        visitedCursors.add(cursorKey)
-        const page = await getFiles({
-          search: query.value.trim() || undefined,
-          kind: kindFilter.value,
-          profile: profile.value,
-          cursor,
-          limit: 50,
-        })
-        if (generation !== loadGeneration) return
-        for (const item of page.items) existing.set(item.id, item)
-        pages += 1
-        cursor = page.nextCursor ?? undefined
-        nextCursor.value = cursor
-        hasMore.value = Boolean(cursor)
-        const matching = [...existing.values()].filter(item => kindFilter.value === 'all' || item.kind === kindFilter.value).length
-        if (!cursor || kindFilter.value === 'all' || matching >= 50) break
-      }
-      items.value = [...existing.values()]
-    } catch (cause) {
-      if (generation === loadGeneration) error.value = cause instanceof Error ? cause.message : '文件库加载失败'
-    } finally {
-      if (generation === loadGeneration) isLoading.value = false
-    }
-  }
-
-  const reset = () => load(true)
-  watch(() => auth.user?.id, () => {
-    loadGeneration += 1
-    items.value = []
-    profile.value = undefined
-    nextCursor.value = undefined
-    visitedCursors.clear()
-    isLoading.value = false
-    error.value = undefined
-  }, { flush: 'sync' })
-  const loadMore = () => load(false)
-  return { items, filteredItems, nextCursor, hasMore, isLoading, error, query, kindFilter, profile, load, reset, loadMore }
-})

+ 0 - 53
src/client/utils/cache.ts

@@ -1,53 +0,0 @@
-import { openDB, type IDBPDatabase } from 'idb'
-
-const memory = new Map<string, unknown>()
-let databasePromise: Promise<IDBPDatabase | null> | undefined
-
-async function database(): Promise<IDBPDatabase | null> {
-  if (typeof indexedDB === 'undefined') return null
-  databasePromise ??= openDB('hermes-yaoyao-cache', 1, {
-    upgrade(database) {
-      if (!database.objectStoreNames.contains('records')) database.createObjectStore('records')
-    },
-  }).catch(() => null)
-  return databasePromise
-}
-
-export class ScopedCache<T> {
-  constructor(private readonly namespace: string, private readonly maximumBytes = 16 * 1024 * 1024) {}
-
-  private key(scope: string, key: string): string { return `${this.namespace}:${scope}:${key}` }
-
-  async get(scope: string, key: string): Promise<T | undefined> {
-    const storageKey = this.key(scope, key)
-    const db = await database()
-    if (!db) return memory.get(storageKey) as T | undefined
-    try { return await db.get('records', storageKey) as T | undefined } catch { return memory.get(storageKey) as T | undefined }
-  }
-
-  async set(scope: string, key: string, value: T, durable = false): Promise<void> {
-    const serialized = JSON.stringify(value)
-    if (new Blob([serialized]).size > this.maximumBytes) {
-      if(durable)throw new Error('聊天缓存超出容量,未推进同步位置')
-      return
-    }
-    // Cache records are JSON snapshots. Detach reactive proxies before IndexedDB
-    // structured-clones them, and keep the memory fallback equally immutable.
-    const snapshot = JSON.parse(serialized) as T
-    const storageKey = this.key(scope, key)
-    const db = await database()
-    if(durable&&typeof indexedDB!=='undefined'&&!db)throw new Error('聊天缓存不可写,未推进同步位置')
-    if (db) {
-      if(durable)await db.put('records',snapshot,storageKey)
-      else await db.put('records', snapshot, storageKey).catch(() => undefined)
-    }
-    memory.set(storageKey, snapshot)
-  }
-
-  async delete(scope: string, key: string): Promise<void> {
-    const storageKey = this.key(scope, key)
-    memory.delete(storageKey)
-    const db = await database()
-    if (db) await db.delete('records', storageKey).catch(() => undefined)
-  }
-}

+ 0 - 40
src/client/utils/chatHistory.ts

@@ -1,40 +0,0 @@
-import type { ChatMessage } from '@shared/types'
-import { mergeChatMessages } from './messageReducer'
-
-const projectedID = /^(?:stream:|resume:|event:|history-)/
-
-/** Replace completed live projections only inside an identified history turn. */
-export function reconcileChatHistory(existing: ChatMessage[], history: ChatMessage[], running: boolean): ChatMessage[] {
-  const aliases = new Map<string, string>()
-  for (const message of history) if (message.role === 'user') {
-    aliases.set(message.id, message.id)
-    if (message.clientMessageId) aliases.set(message.clientMessageId, message.id)
-  }
-  const userKey = (message: ChatMessage) => aliases.get(message.clientMessageId || '') ?? aliases.get(message.id) ?? message.id
-  // A queued user message can appear after the currently executing assistant.
-  // Protect the owner of that live segment, rather than the newest queue entry.
-  let liveIndex = -1
-  for (let index = existing.length - 1; index >= 0; index -= 1) {
-    if (existing[index]!.role === 'assistant' && existing[index]!.isStreaming) { liveIndex = index; break }
-  }
-  const activeUser = [...existing.slice(0, liveIndex < 0 ? undefined : liveIndex)].reverse().find(message => message.role === 'user')
-  const active = running && activeUser ? userKey(activeUser) : ''
-  const canonical = new Map(history.filter(message => message.serverMessageId && !projectedID.test(message.id)).map(message => [message.id, message]))
-  const completedTurns = new Set<string>()
-  let turn = ''
-  for (const message of history) {
-    if (message.role === 'user') turn = userKey(message)
-    if (turn && (!running || active) && turn !== active && canonical.has(message.id) && message.role === 'assistant'
-      && !message.isStreaming && message.content.trim() && !message.toolCalls?.length) completedTurns.add(turn)
-  }
-  turn = ''
-  const retained = existing.flatMap(message => {
-    if (message.role === 'user') turn = userKey(message)
-    if (message.role !== 'assistant') return [message]
-    const persisted = canonical.get(message.id)
-    if (persisted && (!message.isStreaming || completedTurns.has(turn))) return [persisted]
-    if (completedTurns.has(turn) && projectedID.test(message.id)) return []
-    return [message]
-  })
-  return mergeChatMessages(retained, history, 'snapshot')
-}

+ 0 - 33
src/client/utils/contextUsage.ts

@@ -1,33 +0,0 @@
-import type { ChatUsage, JsonValue } from '@shared/types'
-import { record } from './normalize'
-
-/** Match mobile: context is the latest prompt occupancy, never cumulative usage
- * or the full (possibly compacted/paginated) visible transcript. */
-export function normalizeChatUsage(...sources: unknown[]): ChatUsage | undefined {
-  const fields: [Exclude<keyof ChatUsage, 'raw'>, string[]][] = [
-    ['inputTokens', ['input_tokens', 'inputTokens', 'input', 'prompt']],
-    ['outputTokens', ['output_tokens', 'outputTokens', 'output', 'completion']],
-    ['totalTokens', ['total_tokens', 'totalTokens', 'total']],
-    ['contextTokens', ['context_used', 'contextUsed', 'context_tokens', 'contextTokens']],
-    ['contextLimit', ['context_max', 'contextMax', 'context_limit', 'contextLimit', 'context_length', 'contextLength', 'effective_context_length']],
-    ['percentUsed', ['context_percent', 'contextPercent', 'percent_used', 'percentUsed']],
-  ]
-  const usage: ChatUsage = {}
-  for (const source of sources) {
-    const root = record(source)
-    for (const value of [record(root.usage), record(record(root.info).usage), root, record(root.info)]) {
-      for (const [field, aliases] of fields) {
-        if (usage[field] !== undefined) continue
-        for (const alias of aliases) {
-          const raw = value[alias]
-          if (typeof raw !== 'number' && (typeof raw !== 'string' || !raw.trim())) continue
-          const number = Number(raw)
-          if (!Number.isFinite(number) || number < 0 || (field === 'contextLimit' && number === 0)) continue
-          usage[field] = number
-          break
-        }
-      }
-    }
-  }
-  return Object.keys(usage).length ? { ...usage, raw: sources[0] as JsonValue } : undefined
-}

+ 0 - 14
src/client/utils/interfaceMode.ts

@@ -1,14 +0,0 @@
-export type InterfaceMode = 'chat' | 'bots'
-const KEY = 'hermes-yaoyao:interface-mode'
-
-export function savedInterfacePath(): '/chat' | '/conversations' {
-  try { return localStorage.getItem(KEY) === 'chat' ? '/chat' : '/conversations' }
-  catch { return '/conversations' }
-}
-
-export function rememberInterfacePath(path: string): void {
-  const mode: InterfaceMode | undefined = /^\/conversations(?:\/|$)/.test(path) ? 'bots'
-    : /^\/chat(?:\/|$)/.test(path) ? 'chat' : undefined
-  if (!mode) return
-  try { localStorage.setItem(KEY, mode) } catch { /* storage may be unavailable */ }
-}

+ 0 - 397
src/client/utils/messageReducer.ts

@@ -1,397 +0,0 @@
-import type {
-  ApprovalRequest, ChatMessage, ChatRouteState, ClarificationRequest, JsonValue, RpcEventFrame, ToolCall,
-} from '@shared/types'
-import { createId } from './id'
-import { toolStatus } from '@shared/chatTools'
-import { bool, number, record, string } from './normalize'
-import { normalizeChatUsage } from './contextUsage'
-
-type MergePosition = 'append' | 'prepend' | 'snapshot'
-
-function messageTime(message: ChatMessage): number {
-  return message.timestamp < 10_000_000_000 ? message.timestamp * 1000 : message.timestamp
-}
-
-/**
- * Keep the conversation in its canonical chronological order even when a
- * history snapshot races a realtime event.  Sequence is preferred when both
- * rows carry one; otherwise timestamps retain the order supplied by Hermes.
- */
-export function orderChatMessages(messages: ChatMessage[]): ChatMessage[] {
-  return messages
-    .map((message, index) => ({ message, index }))
-    .sort((left, right) => {
-      const leftSequence = left.message.sequence
-      const rightSequence = right.message.sequence
-      if (leftSequence !== undefined && rightSequence !== undefined && leftSequence !== rightSequence) {
-        return leftSequence - rightSequence
-      }
-      const timeDelta = messageTime(left.message) - messageTime(right.message)
-      return timeDelta || left.index - right.index
-    })
-    .map(({ message }) => message)
-}
-
-function sameMessage(left: ChatMessage, right: ChatMessage): boolean {
-  if (left.id && right.id && left.id === right.id) return true
-  return Boolean(left.clientMessageId && right.clientMessageId && left.clientMessageId === right.clientMessageId)
-}
-
-function mergeOne(previous: ChatMessage, incoming: ChatMessage): ChatMessage {
-  const persistedUser = (message: ChatMessage) => message.role === 'user' && message.stage === 'settled'
-    && message.serverMessageId === message.id && message.id !== message.clientMessageId && !message.id.startsWith('user:')
-  // A late receipt or a cached optimistic row must not demote persisted history.
-  if (persistedUser(previous) && !persistedUser(incoming)) [previous, incoming] = [incoming, previous]
-  const replacesContent = Boolean(incoming.content) || Boolean(incoming.attachments?.length)
-  return {
-    ...previous,
-    ...incoming,
-    id: incoming.serverMessageId || incoming.stage === 'settled' ? incoming.id : previous.id,
-    clientMessageId: incoming.clientMessageId ?? previous.clientMessageId,
-    serverMessageId: incoming.serverMessageId ?? previous.serverMessageId,
-    content: replacesContent ? incoming.content : previous.content,
-    reasoning: incoming.reasoning ?? previous.reasoning,
-    attachments: incoming.attachments?.length ? incoming.attachments : previous.attachments,
-    toolCalls: incoming.toolCalls?.length ? incoming.toolCalls : previous.toolCalls,
-  }
-}
-
-/** Merge only by server/client identity. Repeated text is always retained. */
-export function mergeChatMessages(existing: ChatMessage[], incoming: ChatMessage[], position: MergePosition = 'append'): ChatMessage[] {
-  const base = position === 'prepend' || position === 'snapshot' ? [...incoming, ...existing] : [...existing, ...incoming]
-  const result: ChatMessage[] = []
-  for (const message of base) {
-    let merged = message
-    let index: number
-    let insertionIndex = result.length
-    // An enriched history row can bridge both an old server row and its local
-    // echo already in the cache. Consume every identity match, not just the first.
-    while ((index = result.findIndex(candidate => sameMessage(candidate, merged))) >= 0) {
-      insertionIndex = Math.min(insertionIndex, index)
-      merged = mergeOne(result.splice(index, 1)[0]!, merged)
-    }
-    result.splice(insertionIndex, 0, merged)
-  }
-  return orderChatMessages(result)
-}
-
-function payloadRecord(event: RpcEventFrame['params']): Record<string, unknown> {
-  return record(event.payload)
-}
-
-function eventSessionId(event: RpcEventFrame['params'], fallback: string): string {
-  const payload = payloadRecord(event)
-  return string(event.session_id ?? payload.session_id ?? payload.sessionId, fallback)
-}
-
-function eventMessageId(payload: Record<string, unknown>, fallback: string): string {
-  return string(payload.message_id ?? payload.messageId ?? payload.id ?? payload.run_id ?? payload.runId, fallback)
-}
-
-function lastUserMessage(messages: ChatMessage[]): ChatMessage | undefined {
-  return [...messages].reverse().find(message => message.role === 'user')
-}
-
-function lastStreamingAssistant(messages: ChatMessage[], afterLatestUser = false): ChatMessage | undefined {
-  let latestUserIndex = -1
-  if (afterLatestUser) {
-    for (let index = messages.length - 1; index >= 0; index -= 1) {
-      if (messages[index].role === 'user') {
-        latestUserIndex = index
-        break
-      }
-    }
-  }
-  return messages.slice(latestUserIndex + 1).reverse()
-    .find(message => message.role === 'assistant' && message.isStreaming)
-}
-
-export function chatHasUnfinishedOutput(messages: ChatMessage[]): boolean {
-  return messages.some(message => message.role === 'assistant'
-    && message.toolCalls?.some(tool => ['pending', 'running'].includes(tool.status)))
-}
-
-export function settleChatMessages(messages: ChatMessage[], current?: ChatMessage, interruptUnfinishedTools = true): ChatMessage[] {
-  return messages.map(message => message.role === 'assistant' && message !== current
-    ? { ...message, stage: message.stage === 'streaming' ? 'settled' : message.stage, isStreaming: false,
-      toolCalls: message.toolCalls?.map(tool => interruptUnfinishedTools && ['running', 'pending'].includes(tool.status)
-        ? { ...tool, status: 'interrupted' }
-        : tool) }
-    : message)
-}
-
-function streamingSegmentId(state: ChatRouteState): string {
-  const latestUser = lastUserMessage(state.messages)
-  return `stream:${state.route.profile}:${state.route.sessionId}:${latestUser?.id ?? 'orphan'}:${createId('segment')}`
-}
-
-function sealInterimMessage(state: ChatRouteState, payload: Record<string, unknown>): ChatMessage[] {
-  const content = string(payload.output ?? payload.text ?? payload.content)
-  if (!content.trim()) return state.messages
-
-  const current = lastStreamingAssistant(state.messages)
-  const occurredAt = number(payload.timestamp ?? payload.created_at, Date.now() / 1000)
-  const sealedId = current?.id ?? streamingSegmentId(state)
-  const sealed: ChatMessage = {
-    ...(current ?? {}),
-    id: sealedId,
-    clientMessageId: current?.clientMessageId ?? (sealedId.startsWith('stream:') ? sealedId : undefined),
-    sessionId: state.route.sessionId,
-    profile: state.route.profile,
-    role: 'assistant',
-    content,
-    timestamp: current?.timestamp ?? occurredAt,
-    stage: 'settled',
-    isStreaming: false,
-    raw: payload as JsonValue,
-  }
-  const nextId = streamingSegmentId(state)
-  const next: ChatMessage = {
-    id: nextId,
-    clientMessageId: nextId,
-    sessionId: state.route.sessionId,
-    profile: state.route.profile,
-    role: 'assistant',
-    content: '',
-    timestamp: occurredAt,
-    stage: 'streaming',
-    isStreaming: true,
-    raw: { stream_interim_continuation: true },
-  }
-  return mergeChatMessages(mergeChatMessages(state.messages, [sealed]), [next])
-}
-
-function toolFromEvent(payload: Record<string, unknown>, status: ToolCall['status']): ToolCall {
-  return {
-    id: string(payload.tool_call_id ?? payload.toolCallId ?? payload.tool_id ?? payload.id, createId('tool')),
-    name: string(payload.name ?? payload.tool_name, '工具'),
-    status,
-    arguments: (payload.arguments ?? payload.args ?? payload.context) as JsonValue | undefined,
-    result: (payload.result ?? payload.output) as JsonValue | undefined,
-    preview: string(payload.preview ?? payload.summary ?? payload.args_text) || undefined,
-    error: string(payload.error) || undefined,
-    durationSeconds: number(payload.duration_seconds ?? payload.duration_s) || undefined,
-  }
-}
-
-function updateStreamingMessage(
-  state: ChatRouteState,
-  payload: Record<string, unknown>,
-  mode: 'start' | 'delta' | 'reasoning' | 'complete' | 'failed',
-): ChatMessage[] {
-  // A start event belongs to the turn after the latest user row. An interrupted
-  // turn may never receive a terminal event, so reusing any older streaming row
-  // would make the new answer render above the new prompt.
-  const current = lastStreamingAssistant(state.messages, mode === 'start')
-  const fallbackId = current?.id ?? streamingSegmentId(state)
-  const id = eventMessageId(payload, fallbackId)
-  const existing = state.messages.find(message => message.id === id) ?? current
-  const delta = string(payload.delta ?? payload.text_delta ?? payload.content_delta)
-  const full = string(payload.output ?? payload.text ?? payload.content)
-  const emptyInterimContinuation = mode === 'complete'
-    && existing === current
-    && bool(record(current?.raw).stream_interim_continuation)
-    && !current?.content.trim()
-    && !current?.reasoning?.trim()
-    && !current?.toolCalls?.length
-  if (emptyInterimContinuation && current) {
-    const currentIndex = state.messages.indexOf(current)
-    const previous = state.messages.slice(0, currentIndex).reverse()
-      .find(message => message.role === 'assistant')
-    const previousContent = previous?.content.trim() ?? ''
-    const continuesPrevious = Boolean(full && previousContent
-      && (full === previousContent || full.startsWith(previousContent) || previousContent.startsWith(full)))
-    if (previous && (!full || bool(payload.response_previewed) || continuesPrevious)) {
-      return orderChatMessages(state.messages
-        .filter(message => message !== current)
-        .map(message => message === previous && full
-          ? { ...message, content: full, stage: 'settled', isStreaming: false, raw: payload as JsonValue }
-          : message))
-    }
-  }
-  let content = existing?.content ?? ''
-  let reasoning = existing?.reasoning
-  if (mode === 'delta') content += delta || full
-  if (mode === 'complete') content = bool(payload.authoritative_output) && full ? full : full || content
-  if (mode === 'reasoning') reasoning = `${reasoning ?? ''}${delta || full}`
-  const message: ChatMessage = {
-    id,
-    // Keep a stable local identity while Hermes promotes a synthetic stream ID
-    // to its authoritative message/run ID on a later event.
-    clientMessageId: existing?.clientMessageId
-      ?? (existing?.id.startsWith('stream:') ? existing.id : id.startsWith('stream:') ? id : undefined),
-    serverMessageId: id.startsWith('stream:') ? undefined : id,
-    sessionId: state.route.sessionId,
-    profile: state.route.profile,
-    role: 'assistant',
-    content,
-    reasoning,
-    timestamp: number(payload.timestamp ?? payload.created_at, existing?.timestamp ?? Date.now() / 1000),
-    stage: mode === 'complete' ? 'settled' : mode === 'failed' ? 'failed' : 'streaming',
-    isStreaming: !['complete', 'failed'].includes(mode),
-    error: mode === 'failed' ? string(payload.error ?? payload.message, '运行失败') : undefined,
-    toolCalls: existing?.toolCalls,
-    raw: payload as JsonValue,
-  }
-  const messages = mode === 'start' ? settleChatMessages(state.messages, current) : state.messages
-  return mergeChatMessages(messages, [message])
-}
-
-export function applyChatEvent(state: ChatRouteState, event: RpcEventFrame['params']): ChatRouteState {
-  if (event.type === 'gateway.ready') return state
-  const payload = payloadRecord(event)
-  if (eventSessionId(event, state.route.sessionId) !== state.route.sessionId) return state
-  const next: ChatRouteState = { ...state, error: undefined }
-  switch (event.type) {
-    case 'run.peer_user_message':
-    case 'peer.user.message': {
-      const id=string(payload.message_id),clientMessageId=string(payload.client_message_id ?? payload.queue_id)
-      const existing=state.messages.find(m=>m.id===id||m.clientMessageId===clientMessageId)
-      const stage=payload.status==='failed'?'failed':payload.status==='accepted'?'accepted':existing?.stage??'pending'
-      next.messages=mergeChatMessages(state.messages,[{...existing,id,clientMessageId,sessionId:state.route.sessionId,profile:state.route.profile,
-        role:'user',content:string(payload.text ?? payload.content),timestamp:existing?.timestamp??number(payload.timestamp,Date.now()/1000),stage}])
-      break
-    }
-    case 'message.start':
-    case 'run.started':
-      next.messages = updateStreamingMessage(state, payload, 'start')
-      next.isStreaming = true
-      next.isQueued = false
-      break
-    case 'message.delta':
-    case 'content.delta':
-    case 'assistant.delta':
-      next.messages = updateStreamingMessage(state, payload, 'delta')
-      next.isStreaming = true
-      break
-    case 'message.interim':
-      // Hermes emits this after commentary that precedes a tool call. Seal the
-      // visible text in place and start a fresh segment, otherwise later deltas
-      // keep rewriting the older bubble until message.complete replaces it.
-      next.messages = sealInterimMessage(state, payload)
-      next.isStreaming = true
-      break
-    case 'reasoning.delta':
-      next.messages = updateStreamingMessage(state, payload, 'reasoning')
-      next.isStreaming = true
-      break
-    case 'thinking.delta':
-    case 'status.update':
-      next.liveStatus = string(payload.text ?? payload.message ?? payload.status) || undefined
-      break
-    case 'message.complete':
-    case 'run.completed': {
-      const terminalStatus = string(payload.status).trim().toLowerCase()
-      const failed = terminalStatus === 'error' || terminalStatus === 'failed' || Boolean(payload.error)
-      next.messages = updateStreamingMessage(state, payload, failed ? 'failed' : 'complete')
-      const waitingForOutput = !failed && chatHasUnfinishedOutput(next.messages)
-      next.messages = settleChatMessages(next.messages, undefined, !waitingForOutput)
-      next.isStreaming = waitingForOutput
-      next.isQueued = false
-      next.liveStatus = undefined
-      const usage = normalizeChatUsage(payload)
-      if (usage) next.usage = { ...next.usage, ...usage }
-      if (failed) next.error = string(payload.error ?? payload.text ?? payload.message, '运行失败')
-      break
-    }
-    case 'error':
-    case 'run.failed':
-      next.messages = updateStreamingMessage(state, payload, 'failed')
-      next.messages = settleChatMessages(next.messages)
-      next.isStreaming = false
-      next.isQueued = false
-      next.error = string(payload.error ?? payload.message, '运行失败')
-      break
-    case 'run.queued':
-      next.isQueued = true
-      break
-    case 'run.steered':
-    case 'submission.acknowledged':
-      next.isQueued = false
-      break
-    case 'session.usage':
-    case 'usage.update':
-    case 'context.update': {
-      const usage = normalizeChatUsage(payload)
-      if (usage) next.usage = { ...next.usage, ...usage }
-      break
-    }
-    case 'tool.start':
-    case 'tool.progress':
-    case 'tool.started':
-    case 'tool.generating': {
-      const id = string(payload.tool_call_id ?? payload.toolCallId ?? payload.tool_id ?? payload.id)
-      if (!id) {
-        next.liveStatus = `正在准备 ${string(payload.name ?? payload.tool_name, '工具')}`
-        break
-      }
-      const current = lastStreamingAssistant(next.messages)
-        ?? [...next.messages].reverse().find(message => message.role === 'assistant'
-          && (message.toolCalls?.some(tool => tool.id === id)
-            || message.toolCalls?.some(tool => ['pending', 'running'].includes(tool.status))))
-        ?? [...next.messages].reverse().find(message => message.role === 'assistant')
-      if (!current) break
-      const tool = toolFromEvent(payload, 'running')
-      const tools = [...(current.toolCalls ?? [])]
-      const index = tools.findIndex(item => item.id === tool.id)
-      if (index >= 0) tools[index] = { ...tools[index], ...tool,
-        result: tool.result ?? tools[index].result,
-        status: ['completed', 'failed'].includes(tools[index].status) ? tools[index].status : tool.status }
-      else tools.push(tool)
-      next.messages = mergeChatMessages(next.messages, [{ ...current, toolCalls: tools }])
-      next.isStreaming = true
-      next.liveStatus = undefined
-      break
-    }
-    case 'tool.complete':
-    case 'tool.completed':
-    case 'tool.failed': {
-      const id = string(payload.tool_call_id ?? payload.toolCallId ?? payload.tool_id ?? payload.id)
-      if (!id) break
-      const current = [...next.messages].reverse().find(message => message.role === 'assistant' && message.toolCalls?.some(tool => tool.id === id))
-        ?? lastStreamingAssistant(next.messages)
-      if (!current) break
-      const tool = toolFromEvent(payload, toolStatus(event.type, payload.result ?? payload.output, payload.error))
-      const tools = [...(current.toolCalls ?? [])]
-      const index = tools.findIndex(item => item.id === tool.id)
-      if (index >= 0) tools[index] = { ...tools[index], ...tool }
-      else tools.push(tool)
-      next.messages = mergeChatMessages(next.messages, [{ ...current, toolCalls: tools }])
-      if (!chatHasUnfinishedOutput(next.messages) && !next.messages.some(message => message.isStreaming)) {
-        next.isStreaming = false
-        next.isQueued = false
-        next.liveStatus = undefined
-      }
-      break
-    }
-    case 'approval.request':
-    case 'approval.requested': {
-      const id = string(payload.request_id ?? payload.requestId ?? payload.id)
-      if (id) next.pendingApproval = {
-        id, sessionId: state.route.sessionId, message: string(payload.message ?? payload.prompt) || undefined,
-        toolName: string(payload.tool_name ?? payload.tool) || undefined,
-        choices: Array.isArray(payload.choices) ? payload.choices.map(String) : undefined,
-        payload: payload as Record<string, JsonValue>,
-      } satisfies ApprovalRequest
-      break
-    }
-    case 'approval.resolved':
-      next.pendingApproval = undefined
-      break
-    case 'clarify.request':
-    case 'clarify.requested': {
-      const id = string(payload.request_id ?? payload.requestId ?? payload.id)
-      if (id) next.pendingClarification = {
-        id, sessionId: state.route.sessionId, question: string(payload.question ?? payload.message ?? payload.prompt, '需要补充信息'),
-        choices: Array.isArray(payload.choices) ? payload.choices.map(String) : undefined,
-        payload: payload as Record<string, JsonValue>,
-      } satisfies ClarificationRequest
-      break
-    }
-    case 'clarify.expire':
-    case 'clarify.resolved':
-      next.pendingClarification = undefined
-      break
-  }
-  return next
-}

+ 0 - 42
src/client/utils/sessionModel.ts

@@ -1,42 +0,0 @@
-import type { ModelOption } from '@shared/types'
-import { record, string } from '@/utils/normalize'
-
-export interface SessionModelSelection {
-  model: string
-  provider?: string
-}
-
-/**
- * The model chooser uses this exact value for its option IDs. Providers may
- * themselves contain colons, so callers must compare the whole value instead
- * of splitting it back into provider and model parts.
- */
-export function modelChoiceId(option: Pick<ModelOption, 'id' | 'provider'>): string {
-  return `${option.provider}:${option.id}`
-}
-
-export function modelForChoiceId(options: ModelOption[], choiceId: string): ModelOption | undefined {
-  return options.find(option => modelChoiceId(option) === choiceId)
-}
-
-export function modelForSession(options: ModelOption[], model?: string, provider?: string): ModelOption | undefined {
-  const id = model?.trim()
-  if (!id) return undefined
-  const normalizedId = id.toLocaleLowerCase()
-  const normalizedProvider = provider?.trim().toLocaleLowerCase() || ''
-  const exact = options.find(option => option.id.toLocaleLowerCase() === normalizedId
-    && (!normalizedProvider || option.provider.toLocaleLowerCase() === normalizedProvider))
-  if (exact) return exact
-  const byId = options.find(option => option.id.toLocaleLowerCase() === normalizedId)
-  if (byId) return byId
-  return { id, name: id, provider: provider?.trim() || '' }
-}
-
-export function modelSelectionFromSessionInfo(payload: unknown): SessionModelSelection | undefined {
-  const source = record(payload)
-  const info = record(source.info)
-  const model = string(source.model ?? info.model).trim()
-  if (!model) return undefined
-  const provider = string(source.provider ?? info.provider).trim()
-  return { model, provider: provider || undefined }
-}

+ 0 - 19
src/client/utils/sessionOrder.ts

@@ -1,19 +0,0 @@
-import type { SessionSummary } from '@shared/types'
-
-/** Keeps 9119's relative order inside each partition while honoring a pin. */
-export function pinnedSessionsFirst(sessions: SessionSummary[]): SessionSummary[] {
-  const pinned: SessionSummary[] = []
-  const regular: SessionSummary[] = []
-  for (const session of sessions) (session.pinned ? pinned : regular).push(session)
-  return [...pinned, ...regular]
-}
-
-export function appendSessionPage(existing: SessionSummary[], next: SessionSummary[]): SessionSummary[] {
-  const seen = new Set(existing.map(session => `${session.profile}\u0000${session.id}`))
-  return pinnedSessionsFirst([...existing, ...next.filter(session => {
-    const key = `${session.profile}\u0000${session.id}`
-    if (seen.has(key)) return false
-    seen.add(key)
-    return true
-  })])
-}

+ 0 - 72
src/client/utils/sessionOutline.ts

@@ -1,72 +0,0 @@
-import type { UiMessage } from '@/components/messages/types'
-
-export type SessionOutlineItem = {
-  id: string
-  type: 'user' | 'heading'
-  content: string
-  messageId: string
-  level: 0 | 1 | 2 | 3
-  anchorId: string
-  createdAt?: UiMessage['createdAt']
-}
-
-function cleanMessageText(value: string): string {
-  return value.replace(/<think>[\s\S]*?<\/think>/gi, '').trim()
-}
-
-function userQuestion(message: UiMessage): string {
-  const firstLine = cleanMessageText(message.content).split('\n').map(line => line.trim()).find(Boolean) || '用户消息'
-  return firstLine.length > 50 ? `${firstLine.slice(0, 50)}…` : firstLine
-}
-
-function assistantHeadings(message: UiMessage): SessionOutlineItem[] {
-  const result: SessionOutlineItem[] = []
-  let headingIndex = 0
-  let fence = ''
-  for (const line of cleanMessageText(message.content).split('\n')) {
-    const trimmed = line.trim()
-    const fenceMatch = trimmed.match(/^(```+|~~~+)/)
-    if (fenceMatch) {
-      fence = fence ? '' : fenceMatch[1]![0]!
-      continue
-    }
-    if (fence) continue
-    const match = trimmed.match(/^(#{1,3})\s+(.+?)\s*#*$/)
-    if (!match) continue
-    headingIndex += 1
-    const level = match[1]!.length as 1 | 2 | 3
-    result.push({
-      id: `outline-${message.id}-heading-${headingIndex}`,
-      type: 'heading',
-      content: match[2]!.trim(),
-      messageId: message.id,
-      level,
-      anchorId: `outline-${message.id}-heading-${headingIndex}`,
-      createdAt: message.createdAt,
-    })
-  }
-  return result
-}
-
-/** Builds the loaded-session outline from user turns and assistant Markdown headings. */
-export function buildSessionOutline(messages: UiMessage[]): SessionOutlineItem[] {
-  const visible = messages.filter(message => (message.role === 'user' || message.role === 'assistant') && !message.timelineKind)
-  const items: SessionOutlineItem[] = []
-  for (let index = 0; index < visible.length; index += 1) {
-    const message = visible[index]!
-    if (message.role !== 'user') continue
-    items.push({
-      id: `outline-user-${message.id}`,
-      type: 'user',
-      content: userQuestion(message),
-      messageId: message.id,
-      level: 0,
-      anchorId: `message-${message.id}`,
-      createdAt: message.createdAt,
-    })
-    for (let replyIndex = index + 1; replyIndex < visible.length && visible[replyIndex]?.role !== 'user'; replyIndex += 1) {
-      items.push(...assistantHeadings(visible[replyIndex]!))
-    }
-  }
-  return items
-}

+ 0 - 10
src/client/utils/sessionOwnership.ts

@@ -1,10 +0,0 @@
-import type { SessionSummary } from '@shared/types'
-
-/**
- * The 15300 registry owns chat membership. A local Web draft is the only
- * pre-registration row allowed on the chat surface.
- */
-export function isOwnedChatSession(session: Pick<SessionSummary, 'id' | 'owned'>): boolean {
-  return session.owned === true
-    || (session.owned === undefined && session.id.startsWith('draft-'))
-}

+ 0 - 31
src/client/utils/sessionPreferences.ts

@@ -1,31 +0,0 @@
-const FAST_MODE_PREFIX = 'hermes-yaoyao:fast-mode'
-const THINKING_PREFIX = 'hermes-yaoyao:show-thinking'
-
-function scopedKey(prefix: string, userId: string, profile: string, sessionId?: string): string {
-  return [prefix, userId || 'local', profile || 'default', sessionId || ''].map(encodeURIComponent).join('|')
-}
-
-export function readSessionFastMode(userId: string, profile: string, sessionId: string): boolean {
-  try { return localStorage.getItem(scopedKey(FAST_MODE_PREFIX, userId, profile, sessionId)) === '1' } catch { return false }
-}
-
-export function writeSessionFastMode(userId: string, profile: string, sessionId: string, enabled: boolean): void {
-  try {
-    const key = scopedKey(FAST_MODE_PREFIX, userId, profile, sessionId)
-    if (enabled) localStorage.setItem(key, '1')
-    else localStorage.removeItem(key)
-  } catch { /* optional local mirror */ }
-}
-
-export function moveSessionFastMode(userId: string, profile: string, fromSessionId: string, toSessionId: string, enabled: boolean): void {
-  writeSessionFastMode(userId, profile, fromSessionId, false)
-  writeSessionFastMode(userId, profile, toSessionId, enabled)
-}
-
-export function readAgentShowThinking(userId: string, profile: string): boolean {
-  try { return localStorage.getItem(scopedKey(THINKING_PREFIX, userId, profile)) === '1' } catch { return false }
-}
-
-export function writeAgentShowThinking(userId: string, profile: string, visible: boolean): void {
-  try { localStorage.setItem(scopedKey(THINKING_PREFIX, userId, profile), visible ? '1' : '0') } catch { /* optional preference */ }
-}

+ 0 - 596
src/client/views/ChatView.vue

@@ -1,596 +0,0 @@
-<script setup lang="ts">
-import {useUnreadStore} from '@/stores/unread'
-import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
-import { useRoute, useRouter } from 'vue-router'
-import AppIcon from '@/components/common/AppIcon.vue'
-import YaoYaoSidebarIcon from '@/components/common/YaoYaoSidebarIcon.vue'
-import StandaloneDialog from '@/components/common/StandaloneDialog.vue'
-import type { SessionSummary } from '@shared/types'
-import type { ChoiceOption } from '@/components/common/types'
-import ComposerShell from '@/components/composer/ComposerShell.vue'
-import ModelChoiceDialog from '@/components/composer/ModelChoiceDialog.vue'
-import type { ComposerOption, ComposerReference, ComposerSubmit } from '@/components/composer/types'
-import PreviewInspector from '@/components/library/PreviewInspector.vue'
-import PreviewModal from '@/components/library/PreviewModal.vue'
-import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
-import type { PreviewMedia } from '@/components/library/ImagePreviewLightbox.vue'
-import type { UiLibraryItem } from '@/components/library/types'
-import { mediaItemsFromMessages, mediaUrlIdentity, previewItemFromUrl } from '@/components/library/mediaSequence'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
-import SessionOutline from '@/components/messages/SessionOutline.vue'
-import type { UiMessage } from '@/components/messages/types'
-import ResourceSidebar from '@/components/app/ResourceSidebar.vue'
-import FloatingResourceSearch from '@/components/app/FloatingResourceSearch.vue'
-import WorkspaceView from '@/components/workspace/WorkspaceView.vue'
-import { chatInteraction, chatMessagesToUi, sessionSidebarItem } from '@/components/workspace/viewModels'
-import { consumeLibraryItemForComposer, loadComposerFile } from '@/components/workspace/pendingComposer'
-import { readAgentShowThinking, writeAgentShowThinking } from '@/utils/sessionPreferences'
-import { modelChoiceId, modelForChoiceId } from '@/utils/sessionModel'
-import { MODEL_CATALOG_CHANGED_EVENT, modelCatalogChangedProfile } from '@/utils/modelCatalogEvents'
-import { isOwnedChatSession } from '@/utils/sessionOwnership'
-import { useAuthStore } from '@/stores/auth'
-import { useChatStore } from '@/stores/chat'
-import { getSession } from '@/api/sessions'
-
-const unread=useUnreadStore()
-const auth = useAuthStore()
-const chat = useChatStore()
-const route = useRoute()
-const router = useRouter()
-const quoted = ref<UiMessage | null>(null)
-const preview = ref<UiLibraryItem | null>(null)
-const filePreview = ref<UiLibraryItem | null>(null)
-const mediaPreviewIndex = ref<number | null>(null)
-const outlineOpen = ref(false)
-const modelDialog = ref(false)
-const modelSwitching = ref(false)
-const showThinking = ref(false)
-const queueMode = ref(false)
-const actionSessionId = ref('')
-const renaming = ref(false)
-const pendingDeleteSession = ref<Pick<SessionSummary, 'id' | 'profile' | 'title'> | null>(null)
-const deletingSession = ref(false)
-const deleteSessionError = ref('')
-const renameValue = ref('')
-const actionMenuPosition = ref({ x: 8, y: 8 })
-const composer = ref<InstanceType<typeof ComposerShell> | null>(null)
-const timeline = ref<InstanceType<typeof MessageTimeline> | null>(null)
-const headerSessionMenuButton = ref<HTMLButtonElement | null>(null)
-const restoringRouteProfile = ref('')
-
-function handleModelCatalogChanged(event: Event) {
-  const profile = modelCatalogChangedProfile(event)
-  if (profile && profile === auth.activeProfile?.name) void chat.loadModels(profile).catch(() => undefined)
-}
-
-const sessions = computed(() => [...chat.sessions]
-  .filter(isOwnedChatSession))
-const agentNames = computed(() => new Map(auth.profiles.map(profile => [
-  profile.name,
-  profile.agentName || profile.displayName || profile.name,
-])))
-const agentAvatars = computed(() => Object.fromEntries(auth.profiles.flatMap(profile =>
-  profile.agentAvatar ? [[profile.name, profile.agentAvatar] as const] : []
-)))
-const sidebarItems = computed(() => sessions.value.map(session => sessionSidebarItem(
-  session,
-  unread.snapshot.conversations.find(c=>c.mode==='chat'&&c.id===session.id&&c.profile===session.profile)?.count ?? 0,
-  agentNames.value.get(session.profile || auth.activeProfile?.name || ''),
-)))
-const messages = computed(() => chatMessagesToUi(chat.messages, profile => profile ? agentNames.value.get(profile) : undefined))
-const conversationMediaItems = computed(() => mediaItemsFromMessages(messages.value))
-const lightboxMedia = computed(() => conversationMediaItems.value.map(item => ({ url: item.previewUrl || item.downloadUrl || '', name: item.name, type: item.kind as 'image' | 'video' })).filter(item => item.url))
-const activeSession = computed(() => chat.activeSession)
-const actionSession = computed(() => chat.sessions.find(session => session.id === actionSessionId.value))
-const connected = computed(() => ['connected', 'ready'].includes(chat.connectionState))
-const interaction = computed(() => chatInteraction(chat.pendingApproval, chat.pendingClarification))
-const reference = computed<ComposerReference | null>(() => quoted.value ? { id: quoted.value.id, content: quoted.value.content, author: quoted.value.author } : null)
-const forkSourceTitle = computed(() => {
-  const parentId = activeSession.value?.parentSessionId
-  if (!parentId) return ''
-  return chat.sessions.find(session => session.id === parentId && session.profile === activeSession.value?.profile)?.title || parentId
-})
-const selectedModelId = computed(() => chat.selectedModel ? modelChoiceId(chat.selectedModel) : '')
-const reasoningOptions: ChoiceOption[] = [
-  { id: '', label: '默认', description: '使用模型或 Profile 的默认强度' },
-  { id: 'none', label: '关闭', description: '不使用额外推理' },
-  { id: 'low', label: '低', description: '更快的轻量推理' },
-  { id: 'medium', label: '中', description: '速度与深度平衡' },
-  { id: 'high', label: '高', description: '更深入地分析复杂问题' },
-  { id: 'xhigh', label: '极高', description: '适用于最复杂的任务' },
-]
-const reasoningComposerOptions = computed<ComposerOption[]>(() => reasoningOptions.map(option => ({
-  id: option.id,
-  label: option.label,
-  detail: option.description,
-})))
-const reasoningLabel = computed(() => reasoningOptions.find(option => option.id === (chat.reasoningEffort || ''))?.label || '默认')
-const actionMenuStyle = computed(() => ({ left: `${actionMenuPosition.value.x}px`, top: `${actionMenuPosition.value.y}px` }))
-
-function routeProfile(): string {
-  const value = typeof route.query.profile === 'string' ? route.query.profile : ''
-  return auth.profiles.some(profile => profile.name === value) ? value : ''
-}
-
-function sessionLocation(id: string, profile: string) {
-  return { path: `/chat/${encodeURIComponent(id)}`, query: { profile } }
-}
-
-async function findLegacySessionProfile(sessionId: string): Promise<string> {
-  for (const profile of auth.profiles) {
-    try {
-      const session = await getSession(sessionId, profile.name)
-      if (session.id === sessionId) return profile.name
-    } catch { /* Try the next profile: 9119 returns 404 for a foreign session. */ }
-  }
-  return auth.activeProfile?.name || ''
-}
-
-async function ensureRouteProfile(profile: string): Promise<void> {
-  if (!profile || auth.activeProfile?.name === profile) return
-  chat.switchProfile(profile)
-  restoringRouteProfile.value = profile
-  auth.selectProfile(profile)
-  await nextTick()
-}
-
-async function refreshSessions() {
-  const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
-  const profile = routeProfile() || (requestedId ? await findLegacySessionProfile(requestedId) : auth.activeProfile?.name || '')
-  if (profile && auth.activeProfile?.name !== profile) {
-    if (requestedId) await router.replace(sessionLocation(requestedId, profile))
-    await ensureRouteProfile(profile)
-  }
-  // The session route is the authoritative navigation target. A secondary
-  // unread-count request must never prevent its history from being restored.
-  await chat.loadSessions(profile, 'chat')
-  if (requestedId) {
-    const target = await getSession(requestedId, profile).catch(() => undefined)
-    if (target && !isOwnedChatSession(target)) {
-      await router.replace({ path: `/history/${encodeURIComponent(requestedId)}`, query: { profile } })
-      return
-    }
-  }
-  if (requestedId && chat.activeSessionId !== requestedId) await chat.selectSession(requestedId, profile)
-  if (requestedId && profile && routeProfile() !== profile) await router.replace(sessionLocation(requestedId, profile))
-  void chat.loadUnread(profile).catch(() => undefined)
-  if (!requestedId && chat.activeSession && !isOwnedChatSession(chat.activeSession)) {
-    chat.clearSelection()
-  }
-}
-
-const readPending=new Set<string>()
-async function markVisible(ids:string[]){
- if(preview.value||filePreview.value||outlineOpen.value||modelDialog.value||!chat.activeSessionId||typeof route.query.unread==='string')return
- const session=chat.activeSessionId,profile=chat.activeProfileName,key=`${profile}:${session}:${ids.join(',')}`
- if(readPending.has(key))return
- readPending.add(key);try{await unread.visible('chat',session,profile,ids)}catch{}finally{readPending.delete(key)}
-}
-let unreadNavigation=0
-watch(()=>[route.params.id,route.query.unread,chat.messages.length],async()=>{
- const id=route.query.unread;if(typeof id!=='string'||!chat.activeSessionId)return
- const own=++unreadNavigation
- for(let i=0;i<100&&own===unreadNavigation;i++){
-  await nextTick();if(timeline.value?.scrollToMessage(id)){const query={...route.query};delete query.unread;await router.replace({query});return}
-  if(!chat.hasMoreBefore)return
-  const before=chat.messages.length;await chat.loadOlder();if(chat.messages.length===before)return
- }
-},{flush:'post'})
-async function chooseSession(id: string) {
-  outlineOpen.value = false
-  preview.value = null
-  const session = chat.sessions.find(item => item.id === id)
-  const profile = session?.profile || auth.activeProfile?.name || 'default'
-  await router.push(sessionLocation(id, profile))
-  await ensureRouteProfile(profile)
-    if (chat.activeProfileName !== profile) await chat.loadSessions(profile, 'chat')
-  await chat.selectSession(id, profile)
-
-  quoted.value = null
-}
-
-async function createSession() {
-  outlineOpen.value = false
-  preview.value = null
-  const id = chat.createSession(auth.activeProfile?.name)
-  await router.push(sessionLocation(id, auth.activeProfile?.name || 'default'))
-}
-
-async function send(payload: ComposerSubmit) {
-  try {
-    await chat.send(payload.text, payload.files, queueMode.value ? 'queue' : chat.isStreaming ? 'steer' : 'submit')
-    composer.value?.clearAfterSend()
-  } catch { /* store exposes the error and the composer keeps its draft */ }
-}
-
-function openAttachment(attachment: NonNullable<UiMessage['attachments']>[number]) {
-  const item = previewItemFromUrl(attachment.name, attachment.url || '', attachment.id, attachment.kind)
-  item.size = attachment.size
-  if (item.kind === 'image' || item.kind === 'video') openMedia(item)
-  else { outlineOpen.value = false; preview.value = null; filePreview.value = item }
-}
-
-function openMedia(item: UiLibraryItem) {
-  const target = mediaUrlIdentity(item.previewUrl || item.downloadUrl || '')
-  const index = lightboxMedia.value.findIndex(media => mediaUrlIdentity(media.url) === target)
-  mediaPreviewIndex.value = index >= 0 ? index : null
-}
-
-function openLocalFile({ name, url }: { name: string; url: string }) {
-  const item = previewItemFromUrl(name, url)
-  if (item.kind === 'image' || item.kind === 'video') openMedia(item)
-  else { outlineOpen.value = false; filePreview.value = item }
-}
-
-async function addPreviewToComposer(item: UiLibraryItem) {
-  const file = await loadComposerFile(item)
-  if (!file || !composer.value) return
-  composer.value.attachFiles([file])
-  preview.value = null
-  filePreview.value = null
-  mediaPreviewIndex.value = null
-  await nextTick()
-  composer.value?.focus()
-}
-
-async function addMediaToComposer(media: PreviewMedia) {
-  await addPreviewToComposer(previewItemFromUrl(media.name, media.url, `preview:${media.url}`, media.type))
-}
-
-async function selectModel(id: string) {
-  if (id === selectedModelId.value) {
-    modelDialog.value = false
-    return
-  }
-  const model = modelForChoiceId(chat.models, id)
-  if (!model || modelSwitching.value) return
-  modelSwitching.value = true
-  try {
-    await chat.setModel(model)
-    modelDialog.value = false
-  } finally {
-    modelSwitching.value = false
-  }
-}
-
-function selectReasoning(id: string) {
-  chat.reasoningEffort = id || undefined
-}
-
-async function toggleFastMode(enabled: boolean) {
-  try { await chat.setFastMode(enabled) } catch { /* store restores the acknowledged state */ }
-}
-
-function restoreShowThinking(profile = auth.activeProfile?.name || 'default') {
-  showThinking.value = readAgentShowThinking(auth.user?.id ?? 'local', profile)
-}
-
-function toggleShowThinking() {
-  showThinking.value = !showThinking.value
-  writeAgentShowThinking(auth.user?.id ?? 'local', auth.activeProfile?.name || 'default', showThinking.value)
-}
-
-function openSessionActions(id: string, event?: MouseEvent) {
-  actionSessionId.value = id
-  const session = chat.sessions.find(item => item.id === id)
-  renameValue.value = session?.title || ''
-  renaming.value = false
-  const menuWidth = 208
-  const menuHeight = 210
-  const inset = 8
-  const anchor = event?.currentTarget instanceof HTMLElement ? event.currentTarget.getBoundingClientRect() : null
-  const requestedX = event?.type === 'contextmenu' ? event.clientX : anchor ? anchor.right - menuWidth : window.innerWidth - menuWidth - 14
-  const requestedY = event?.type === 'contextmenu' ? event.clientY : anchor ? anchor.bottom + 5 : 46
-  actionMenuPosition.value = {
-    x: Math.max(inset, Math.min(requestedX, window.innerWidth - menuWidth - inset)),
-    y: Math.max(inset, Math.min(requestedY, window.innerHeight - menuHeight - inset)),
-  }
-}
-
-function closeSessionActions() {
-  actionSessionId.value = ''
-  renaming.value = false
-}
-
-async function forceRefreshHistory() {
-  closeSessionActions()
-  try { await chat.forceRefreshHistory() }
-  catch { /* The chat store displays the refresh error without clearing messages. */ }
-}
-
-function handleSessionActionPointer(event: PointerEvent) {
-  if (!actionSessionId.value || (event.target as HTMLElement).closest('.session-actions')) return
-  closeSessionActions()
-}
-
-function handleSessionActionKey(event: KeyboardEvent) {
-  if (event.key === 'Escape' && actionSessionId.value) closeSessionActions()
-}
-
-async function saveRename() {
-  const session = chat.sessions.find(item => item.id === actionSessionId.value)
-  if (!session || !renameValue.value.trim()) return
-  await chat.renameSession(session.id, renameValue.value.trim(), session.profile)
-  closeSessionActions()
-}
-
-async function toggleSessionPinned() {
-  const session = actionSession.value
-  if (!session) return
-  await chat.setSessionPinned(session.id, !session.pinned, session.profile)
-  closeSessionActions()
-}
-
-async function openSessionOutline() {
-  const session = actionSession.value
-  if (!session) return
-  closeSessionActions()
-  if (session.id !== chat.activeSessionId || session.profile !== chat.activeProfileName) await chooseSession(session.id)
-  preview.value = null
-  outlineOpen.value = true
-}
-
-function closeInspector() {
-  const restoreMenuFocus = outlineOpen.value
-  preview.value = null
-  outlineOpen.value = false
-  if (restoreMenuFocus) void nextTick(() => headerSessionMenuButton.value?.focus())
-}
-
-function navigateOutline(target: { messageId: string; anchorId: string }) {
-  timeline.value?.scrollToAnchor(target.messageId, target.anchorId)
-  if (window.matchMedia('(max-width: 900px)').matches) closeInspector()
-}
-
-function confirmDeleteSession() {
-  const session = actionSession.value
-  if (!session) return
-  pendingDeleteSession.value = { id: session.id, profile: session.profile, title: session.title }
-  deleteSessionError.value = ''
-  closeSessionActions()
-}
-
-function cancelDeleteSession() {
-  if (deletingSession.value) return
-  pendingDeleteSession.value = null
-  deleteSessionError.value = ''
-  void nextTick(() => headerSessionMenuButton.value?.focus())
-}
-
-async function deleteSession() {
-  const session = pendingDeleteSession.value
-  if (!session || deletingSession.value) return
-  deletingSession.value = true
-  deleteSessionError.value = ''
-  try {
-    await chat.removeSession(session.id, session.profile)
-    if (route.params.sessionId === session.id) await router.replace({ path: '/chat', query: { profile: session.profile } })
-    pendingDeleteSession.value = null
-  } catch (cause) {
-    deleteSessionError.value = cause instanceof Error ? cause.message : '删除失败,请重试'
-  } finally {
-    deletingSession.value = false
-  }
-}
-
-async function branch() {
-  const id = await chat.branchSession()
-  if (id) await router.push(sessionLocation(id, chat.activeProfileName || auth.activeProfile?.name || 'default'))
-}
-
-async function revealSourceMessage() {
-  const messageId = typeof route.query.message === 'string' ? route.query.message : ''
-  if (!messageId) return
-  await nextTick()
-  for (let attempt = 0; attempt < 10; attempt += 1) {
-    if (timeline.value?.scrollToMessage(messageId)) return
-    if (!chat.hasMoreBefore) return
-    await chat.loadOlder()
-    await nextTick()
-  }
-}
-
-onMounted(async () => {
-  restoreShowThinking()
-  document.addEventListener('pointerdown', handleSessionActionPointer)
-  document.addEventListener('keydown', handleSessionActionKey)
-  window.addEventListener(MODEL_CATALOG_CHANGED_EVENT, handleModelCatalogChanged)
-  await refreshSessions()
-  await Promise.allSettled([chat.loadModels(auth.activeProfile?.name), chat.connect()])
-  void chat.refreshActiveSessionModel().catch(() => undefined)
-  await revealSourceMessage()
-  const pendingFile = await consumeLibraryItemForComposer()
-  if (pendingFile) composer.value?.attachFiles([pendingFile])
-})
-
-onBeforeUnmount(() => {
-  document.removeEventListener('pointerdown', handleSessionActionPointer)
-  document.removeEventListener('keydown', handleSessionActionKey)
-  window.removeEventListener(MODEL_CATALOG_CHANGED_EVENT, handleModelCatalogChanged)
-})
-
-watch(() => auth.activeProfile?.name, async (profile, previous) => {
-  if (!profile || profile === previous) return
-  restoreShowThinking(profile)
-  outlineOpen.value = false
-  preview.value = null
-  if (restoringRouteProfile.value === profile) {
-    restoringRouteProfile.value = ''
-    return
-  }
-  chat.switchProfile(profile)
-  const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
-  if (requestedId && routeProfile() === profile) {
-    await Promise.allSettled([chat.loadSessions(profile, 'chat'), chat.loadModels(profile), chat.loadUnread(profile), chat.connect()])
-    await chat.selectSession(requestedId, profile)
-    return
-  }
-  await router.replace({ path: '/chat', query: { profile } })
-  await Promise.allSettled([chat.loadSessions(profile, 'chat'), chat.loadModels(profile), chat.loadUnread(profile), chat.connect()])
-})
-
-watch(() => chat.activeSessionId, async id => {
-  const profile = chat.activeProfileName || auth.activeProfile?.name || ''
-  if (id) void chat.refreshActiveSessionModel().catch(() => undefined)
-  if (!id || (route.params.sessionId === id && routeProfile() === profile)) return
-  await router.replace(sessionLocation(id, profile))
-})
-</script>
-
-<template>
-  <WorkspaceView sidebar-title="对话" :sidebar-subtitle="`${sessions.length} 个会话`" :inspector-open="!!preview || outlineOpen" :inspector-close-label="outlineOpen ? '关闭会话大纲' : '关闭预览'" @close-inspector="closeInspector">
-    <template #sidebar-action>
-      <button class="sidebar-primary-action" type="button" title="新建聊天" aria-label="新建聊天" @click="createSession">
-        <YaoYaoSidebarIcon name="add" />
-        <span>新建聊天</span>
-      </button>
-    </template>
-    <template #sidebar>
-      <ResourceSidebar
-        :items="sidebarItems"
-        :active-id="chat.activeSessionId"
-        :loading="chat.isLoading"
-        external-search
-        single-line
-        :has-more="chat.hasMoreSessions"
-        :loading-more="chat.isLoadingMoreSessions"
-        search-placeholder="搜索会话"
-        empty-title="还没有会话"
-        empty-description="新建会话后,从输入框开始聊天。"
-        @load-more="chat.loadMoreSessions(auth.activeProfile?.name)"
-        @select="chooseSession"
-        @more="openSessionActions"
-        @context-menu="openSessionActions"
-      />
-    </template>
-
-    <div class="chat-workspace">
-      <MessageTimeline
-        @visible-messages="markVisible"
-        ref="timeline"
-        :messages="messages"
-        :title="activeSession?.title || '新会话'"
-        :subtitle="activeSession ? `${activeSession.profile || auth.activeProfile?.name || ''} · ${activeSession.model || chat.selectedModel?.name || '默认模型'}` : '选择会话或直接开始输入'"
-        :loading="chat.activeRouteState?.isLoadingHistory"
-        :loading-older="chat.activeRouteState?.isLoadingHistory"
-        :has-older="chat.hasMoreBefore"
-        :connected="connected"
-        :synced="chat.historySynced"
-        :show-tools="showThinking"
-        :thinking="chat.isSending || chat.isStreaming"
-        :show-assistant-identity="false"
-        :agent-avatars="agentAvatars"
-        :interaction="interaction"
-        empty-logo
-        transparent-header
-        :fork-source-title="forkSourceTitle"
-        @load-older="chat.loadOlder"
-        @quote="quoted = $event"
-        @branch="branch"
-        @preview="openAttachment"
-        @preview-file="openLocalFile"
-        @approve="interaction && chat.respondToApproval(interaction.id, $event)"
-        @clarify="interaction && chat.respondToClarification(interaction.id, $event)"
-      >
-        <template #header-actions>
-          <button v-if="activeSession" ref="headerSessionMenuButton" class="icon-button header-session-menu" type="button" title="会话操作" aria-label="会话操作" @click="openSessionActions(activeSession.id, $event)"><AppIcon name="dots" :size="18" /></button>
-        </template>
-      </MessageTimeline>
-      <p v-if="chat.error" class="chat-error" role="alert"><AppIcon name="alert" :size="13" />{{ chat.error }}</p>
-      <ComposerShell
-        ref="composer"
-        mode="chat"
-        :draft-key="`${auth.user?.id || 'local'}:${auth.activeProfile?.name || 'default'}:${chat.activeSessionId || 'new'}`"
-        :disabled="chat.connectionState === 'failed'"
-        :streaming="chat.isStreaming"
-        :sending="chat.isSending"
-        :model-label="chat.selectedModel?.name || '选择模型'"
-        :fast-mode="chat.fastMode"
-        :fast-mode-disabled="!chat.activeSessionId"
-        :reasoning-effort="reasoningLabel"
-        :reasoning-value="chat.reasoningEffort || ''"
-        :reasoning-options="reasoningComposerOptions"
-        show-context
-        :context-used="chat.contextUsage?.contextTokens"
-        :context-limit="chat.contextUsage?.contextLimit"
-        :context-percent="chat.contextUsage?.percentUsed"
-        :queue-mode="queueMode || chat.isQueued"
-        :tool-trace-visible="showThinking"
-        :reference="reference"
-        :slash-commands="[
-          { id: 'fork', label: 'fork', detail: '从当前会话创建分支' },
-          { id: 'compact', label: 'compact', detail: '压缩当前会话上下文' },
-          { id: 'model', label: 'model', detail: '切换模型' },
-        ]"
-        @send="send"
-        @stop="chat.interrupt"
-        @model-click="modelDialog = true"
-        @fast-mode-toggle="toggleFastMode"
-        @reasoning-change="selectReasoning"
-        @settings-click="toggleShowThinking"
-        @queue-toggle="queueMode = !queueMode"
-        @clear-reference="quoted = null"
-      />
-    </div>
-
-    <template #inspector>
-      <SessionOutline v-if="outlineOpen" :messages="messages" :has-older="chat.hasMoreBefore" @navigate="navigateOutline" />
-      <PreviewInspector v-else-if="preview" :item="preview" @close="preview = null" @add-to-composer="addPreviewToComposer" />
-    </template>
-  </WorkspaceView>
-
-  <FloatingResourceSearch section="chat" label="搜索会话" :items="sidebarItems" @select="chooseSession" />
-  <PreviewModal v-if="filePreview" :item="filePreview" :items="conversationMediaItems" @close="filePreview = null" @add-to-composer="addPreviewToComposer" @source="filePreview = null" />
-  <ImagePreviewLightbox v-model="mediaPreviewIndex" :images="lightboxMedia" @add="addMediaToComposer" />
-
-  <ModelChoiceDialog :open="modelDialog" :options="chat.models" :selected-id="selectedModelId" :busy="modelSwitching" @close="modelDialog = false" @select="selectModel" />
-
-  <StandaloneDialog v-if="pendingDeleteSession" title="删除会话" compact :before-close="() => !deletingSession" @close="cancelDeleteSession">
-    <div class="session-delete" :aria-busy="deletingSession">
-      <p>确定删除「{{ pendingDeleteSession.title || '新会话' }}」吗?删除后无法恢复。</p>
-      <p v-if="deleteSessionError" class="session-delete-error" role="alert">{{ deleteSessionError }}</p>
-      <div class="session-delete-actions">
-        <button class="quiet-button" type="button" :disabled="deletingSession" @click="cancelDeleteSession">取消</button>
-        <button class="solid-button session-delete-confirm" type="button" :disabled="deletingSession" @click="deleteSession">{{ deletingSession ? '删除中…' : '删除' }}</button>
-      </div>
-    </div>
-  </StandaloneDialog>
-
-  <Teleport to="body">
-    <Transition name="session-menu">
-      <section v-if="actionSessionId" class="session-actions" :style="actionMenuStyle" role="menu" aria-label="会话操作" @contextmenu.prevent>
-        <template v-if="renaming">
-          <label>会话名称<input v-model="renameValue" maxlength="120" autofocus @keydown.enter="saveRename" /></label>
-          <div><button class="quiet-button" type="button" @click="renaming = false">取消</button><button class="solid-button" type="button" @click="saveRename">保存</button></div>
-        </template>
-        <template v-else>
-          <button class="action-row" role="menuitem" type="button" @click="openSessionOutline"><AppIcon name="menu" :size="14" />会话大纲</button>
-          <button v-if="actionSessionId === chat.activeSessionId" class="action-row" role="menuitem" type="button" :disabled="chat.isStreaming || chat.isQueued || chat.isSending || chat.activeRouteState?.isLoadingHistory" @click="forceRefreshHistory"><AppIcon name="refresh" :size="14" />强制刷新历史</button>
-          <button class="action-row" role="menuitem" type="button" @click="toggleSessionPinned"><AppIcon :name="actionSession?.pinned ? 'pin-off' : 'pin'" :size="14" />{{ actionSession?.pinned ? '取消置顶' : '置顶会话' }}</button>
-          <button class="action-row" role="menuitem" type="button" @click="renaming = true"><AppIcon name="edit" :size="14" />重命名</button>
-          <button class="action-row danger" role="menuitem" type="button" @click="confirmDeleteSession"><AppIcon name="trash" :size="14" />删除会话</button>
-        </template>
-      </section>
-    </Transition>
-  </Teleport>
-</template>
-
-<style scoped>
-.chat-workspace { display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; }
-.session-delete p { margin: 0; font-size: 14px; line-height: 1.6; overflow-wrap: anywhere; }
-.session-delete .session-delete-error { margin-top: 12px; color: var(--danger); }
-.session-delete-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
-.session-delete-actions button { min-width: 80px; min-height: 44px; font-size: 14px; }
-.session-delete-confirm { border-color: var(--danger); background: var(--danger); color: var(--text-on-solid); }
-.session-delete-confirm:hover { transform: none; filter: brightness(.95); }
-.session-delete-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
-.session-delete-actions button:disabled { opacity: .6; cursor: wait; }
-.sidebar-primary-action { display: flex; width: 100%; min-height: 40px; align-items: center; gap: 10px; padding: 0 11px; border: 0; border-radius: 9px; background: transparent; color: var(--text-primary); cursor: pointer; font-size: 12px; font-weight: 610; text-align: left; transition: background-color 120ms ease; }
-.sidebar-primary-action:hover, .sidebar-primary-action:focus-visible { background: var(--surface-hover); outline: 0; }
-.sidebar-primary-action:focus-visible { box-shadow: inset 0 0 0 1px var(--line-strong); }
-.header-session-menu { color: var(--text-muted); background: transparent; }.header-session-menu:hover { color: var(--text-primary); background: var(--surface-soft); }
-.chat-error { display: flex; width: min(760px, calc(100% - 32px)); margin: 0 auto 4px; align-items: center; gap: 6px; color: var(--danger); font-size: 9px; }
-.session-actions { position: fixed; z-index: 205; width: 208px; box-sizing: border-box; padding: 6px; border: 1px solid var(--line); border-radius: 11px; background: var(--surface-raised); box-shadow: 0 12px 34px rgba(0,0,0,.16); }.action-row { display: flex; width: 100%; min-height: 34px; align-items: center; gap: 8px; padding: 0 9px; border: 0; border-radius: 7px; background: transparent; color: var(--text-secondary); cursor: pointer; font-size: 11px; text-align: left; }.action-row:hover, .action-row:focus-visible { outline: 0; background: var(--surface-soft); color: var(--text-primary); }.action-row.danger { color: var(--danger); }.session-actions label { display: flex; flex-direction: column; gap: 6px; padding: 4px; color: var(--text-muted); font-size: 9px; }.session-actions input { width: 100%; height: 32px; box-sizing: border-box; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; outline: 0; background: var(--surface-soft); color: var(--text-primary); font-size: 11px; }.session-actions input:focus { border-color: var(--line-strong); box-shadow: 0 0 0 3px var(--focus-ring); }.session-actions > div { display: flex; justify-content: flex-end; gap: 5px; margin-top: 7px; padding: 0 4px 3px; }.session-actions :deep(.quiet-button), .session-actions :deep(.solid-button) { min-height: 29px; padding-inline: 10px; font-size: 10px; }
-.session-menu-enter-active, .session-menu-leave-active { transition: opacity 100ms ease, transform 120ms var(--ease-out); transform-origin: top right; }.session-menu-enter-from, .session-menu-leave-to { opacity: 0; transform: translateY(-3px) scale(.98); }
-@media (prefers-reduced-motion: reduce) { .sidebar-primary-action, .session-menu-enter-active, .session-menu-leave-active { transition: none; } }
-</style>

+ 0 - 25
src/client/views/ConversationsView.vue

@@ -43,7 +43,6 @@ import { workspaceAgentActivity, workspaceAvatarMembers, workspaceAvatarState, w
 import { useAuthStore } from '@/stores/auth'
 import { useThemeStore } from '@/stores/theme'
 import { apiRequest, ApiError } from '@/api/client'
-import { updateProfileIdentity, type ProfileIdentityInput } from '@/api/profiles'
 import { encodeAgentAvatar, randomAgentIdentity } from '@shared/agentIdentity'
 import type { JsonValue } from '@shared/types'
 import {
@@ -92,9 +91,6 @@ const text = ref(''),
   files = ref<WorkspaceFile[]>([]),
   mentions = ref<string[]>([]),
   older = ref(true)
-const identityBusy = ref(false),
-  identityError = ref(''),
-  identityResetVersion = ref(0)
 const respondingInteractionId = ref(''), interactionError = ref('')
 watch(() => `${route.params.id}:${interactions.value[0]?.id}`, () => { interactionError.value = '' })
 const agentActivity = computed(() => workspaceAgentActivity(conversations.value))
@@ -278,22 +274,6 @@ const thinkingIdentity = computed(() => {
 })
 const isAgentDialog = computed(() => dialog.value === 'agent' || dialog.value === 'editAgent')
 const body = (v: unknown) => v as JsonValue
-async function saveProfileIdentity(input: ProfileIdentityInput) {
-  const profile = auth.activeProfile
-  if (!profile) return
-  identityBusy.value = true
-  identityError.value = ''
-  try {
-    await updateProfileIdentity(profile, input)
-    await auth.refreshProfiles()
-    await auth.refreshProfileAvatars()
-    identityResetVersion.value += 1
-  } catch (cause) {
-    identityError.value = cause instanceof Error ? cause.message : '保存机器人身份失败'
-  } finally {
-    identityBusy.value = false
-  }
-}
 async function refresh() {
   const startedAtCursor = transcriptStore.cursor
   const owner = auth.user?.id
@@ -996,16 +976,11 @@ onBeforeUnmount(() => {
     :upstream-error="auth.upstreamError"
     :theme="theme.resolvedTheme"
     :theme-preference="theme.theme"
-    :identity-busy="identityBusy"
-    :identity-error="identityError"
-    :identity-reset-version="identityResetVersion"
     sidebar-title="聊天"
     sidebar-context-title="聊天列表"
     @logout="auth.logout"
-    @select-profile="auth.selectProfile"
     @toggle-theme="theme.toggle"
     @set-theme="theme.setTheme"
-    @save-identity="saveProfileIdentity"
     @create-agent="openDialog('agent')"
     @create-group="openDialog('group')"
     @bot-settings-changed="knowledgeChanged"

+ 0 - 156
src/client/views/FilesView.vue

@@ -1,156 +0,0 @@
-<script setup lang="ts">
-import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
-import { useRouter } from 'vue-router'
-import type { FileKind } from '@shared/types'
-import AppIcon from '@/components/common/AppIcon.vue'
-import LibraryGrid from '@/components/library/LibraryGrid.vue'
-import PreviewModal from '@/components/library/PreviewModal.vue'
-import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
-import type { PreviewMedia } from '@/components/library/ImagePreviewLightbox.vue'
-import type { LibraryFilterOption, UiLibraryItem } from '@/components/library/types'
-import ResourceSidebar from '@/components/app/ResourceSidebar.vue'
-import WorkspaceView from '@/components/workspace/WorkspaceView.vue'
-import { fileToUi, sessionSidebarItem } from '@/components/workspace/viewModels'
-import { useFilesStore } from '@/stores/files'
-import { useAuthStore } from '@/stores/auth'
-import { useChatStore } from '@/stores/chat'
-
-const files = useFilesStore()
-const auth = useAuthStore()
-const chat = useChatStore()
-const router = useRouter()
-const selected = ref<UiLibraryItem | null>(null)
-const mediaIndex = ref<number | null>(null)
-const historySearch = ref('')
-let searchTimer: number | undefined
-
-const items = computed(() => files.filteredItems.map(fileToUi))
-const lightboxMedia = computed(() => items.value.filter(item => item.kind === 'image' || item.kind === 'video').map(item => ({ url: item.previewUrl || item.downloadUrl || '', name: item.name, type: item.kind as 'image' | 'video' })).filter(item => item.url))
-const agentNames = computed(() => new Map(auth.profiles.map(profile => [profile.name, profile.agentName || profile.displayName || profile.name])))
-const historyItems = computed(() => chat.sessions
-  .filter(session => !['cron', 'ios_group'].includes(session.source))
-  .filter(session => !historySearch.value.trim() || `${session.title} ${session.preview || ''}`.toLocaleLowerCase().includes(historySearch.value.trim().toLocaleLowerCase()))
-  .map(session => sessionSidebarItem(session, chat.unreadCounts[session.id] ?? 0, agentNames.value.get(session.profile || auth.activeProfile?.name || ''))))
-const options = computed<LibraryFilterOption[]>(() => {
-  const count = (kind: string) => files.items.filter(item => item.kind === kind).length
-  return [
-    { id: 'all', label: '全部', count: files.items.length, icon: 'files' },
-    { id: 'image', label: '图片', count: count('image'), icon: 'image' },
-    { id: 'video', label: '视频', count: count('video'), icon: 'video' },
-    { id: 'audio', label: '音频', count: count('audio'), icon: 'audio' },
-    { id: 'document', label: '文档', count: count('document'), icon: 'file' },
-    { id: 'other', label: '其他', count: count('other'), icon: 'file' },
-  ]
-})
-
-function updateSearch(value: string) {
-  files.query = value
-  window.clearTimeout(searchTimer)
-  searchTimer = window.setTimeout(() => void files.load(true), 260)
-}
-
-function updateFilter(value: string) {
-  files.kindFilter = value as FileKind | 'all'
-  void files.load(true)
-}
-
-async function openSource(item: UiLibraryItem) {
-  if (item.sourceWorkspaceConversationId) {
-    await router.push(`/conversations/${encodeURIComponent(item.sourceWorkspaceConversationId)}`)
-    return
-  }
-  if (!item.sourceSessionId) return
-  if (item.sourceProfile && auth.profiles.some(profile => profile.name === item.sourceProfile)) {
-    auth.selectProfile(item.sourceProfile)
-  }
-  await router.push({
-    path: `/chat/${encodeURIComponent(item.sourceSessionId)}`,
-    query: {
-      ...(item.sourceMessageId ? { message: item.sourceMessageId } : {}),
-      ...(item.sourceProfile ? { profile: item.sourceProfile } : {}),
-    },
-  })
-}
-
-function selectFile(item: UiLibraryItem) {
-  if (item.kind === 'image' || item.kind === 'video') {
-    const index = lightboxMedia.value.findIndex(media => media.url === (item.previewUrl || item.downloadUrl))
-    mediaIndex.value = index >= 0 ? index : null
-    return
-  }
-  selected.value = item
-}
-
-async function selectSession(id: string) {
-  const session = chat.sessions.find(item => item.id === id)
-  const profile = session?.profile || auth.activeProfile?.name
-  await router.push({ path: `/chat/${encodeURIComponent(id)}`, query: profile ? { profile } : {} })
-}
-
-onMounted(() => {
-  files.profile = undefined
-  void files.load(true)
-  void chat.loadSessions(auth.activeProfile?.name)
-  void chat.loadUnread(auth.activeProfile?.name)
-})
-onBeforeUnmount(() => window.clearTimeout(searchTimer))
-watch(() => files.items, () => {
-  if (selected.value && !files.items.some(item => item.id === selected.value?.id)) selected.value = null
-})
-watch(() => auth.activeProfile?.name, profile => {
-  selected.value = null
-  files.profile = profile
-  void files.load(true)
-  void chat.loadSessions(profile)
-  void chat.loadUnread(profile)
-})
-</script>
-
-<template>
-  <WorkspaceView sidebar-title="历史记录" :sidebar-subtitle="`${chat.sessions.length} 个会话`">
-    <template #sidebar>
-      <ResourceSidebar
-        :items="historyItems"
-        :active-id="chat.activeSessionId"
-        :loading="chat.isLoading"
-        :search="historySearch"
-        single-line
-        search-placeholder="搜索会话"
-        empty-title="还没有会话"
-        empty-description="原生 Hermes 会话会在这里以只读历史显示。"
-        @search="historySearch = $event"
-        @select="selectSession"
-      />
-    </template>
-    <section class="library-workspace">
-      <header class="library-header">
-        <div><h2>文件库</h2><span><AppIcon name="files" :size="15" />{{ items.length }}</span></div>
-        <label class="file-search"><AppIcon name="search" :size="15" /><input :value="files.query" type="search" placeholder="搜索文件名、路径或会话" @input="updateSearch(($event.target as HTMLInputElement).value)" /></label>
-      </header>
-      <nav class="file-tabs" aria-label="文件类型筛选">
-        <button v-for="option in options" :key="option.id" type="button" :class="{ active: option.id === files.kindFilter }" @click="updateFilter(option.id)">{{ option.label }}<small v-if="option.count !== undefined">{{ option.count }}</small></button>
-        <div class="file-tabs__status"><span v-if="files.error" class="error"><AppIcon name="alert" :size="13" />{{ files.error }}</span><span v-else>{{ files.nextCursor ? '还有更多文件可加载' : items.length ? '已同步到最新' : '' }}</span><button class="icon-button" type="button" aria-label="刷新文件库" title="刷新文件库" :disabled="files.isLoading" @click="files.load(true)"><AppIcon name="refresh" :size="15" /></button></div>
-      </nav>
-      <LibraryGrid
-        :items="items"
-        :selected-id="selected?.id"
-        :loading="files.isLoading"
-        :has-more="files.hasMore"
-        empty-title="文件库还是空的"
-        empty-description="聊天中的图片、文档和附件会出现在这里。"
-        @select="selectFile"
-        @load-more="files.loadMore"
-        @source="openSource"
-      />
-    </section>
-  </WorkspaceView>
-  <PreviewModal v-if="selected" :item="selected" :items="items" :can-add-to-composer="false" @close="selected = null" @source="openSource" />
-  <ImagePreviewLightbox v-model="mediaIndex" :images="lightboxMedia" :can-add="false" />
-</template>
-
-<style scoped>
-.library-workspace { display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; }
-.library-header { display: flex; min-height: 58px; align-items: center; justify-content: space-between; gap: 16px; padding: 0 22px; border-bottom: 1px solid var(--line); }.library-header > div { display: flex; align-items: center; gap: 10px; }.library-header h2 { margin: 0; font-size: 15px; letter-spacing: -.02em; }.library-header span { display: flex; align-items: center; gap: 5px; color: var(--text-muted); font-size: 10px; }.file-search { display: flex; width: min(280px, 38vw); min-height: 32px; align-items: center; gap: 7px; padding: 0 9px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); color: var(--text-muted); }.file-search:focus-within { border-color: var(--line-strong); }.file-search input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; color: var(--text-primary); font-size: 11px; }
-.file-tabs { display: flex; min-height: 46px; align-items: center; gap: 4px; padding: 0 22px; border-bottom: 1px solid var(--line); overflow-x: auto; }.file-tabs > button { min-height: 28px; padding: 0 10px; border: 0; border-radius: 7px; background: transparent; color: var(--text-muted); cursor: pointer; font-size: 10px; white-space: nowrap; }.file-tabs > button:hover, .file-tabs > button.active { background: var(--surface-soft); color: var(--text-primary); }.file-tabs > button.active { font-weight: 650; }.file-tabs > button small { margin-left: 4px; color: var(--text-muted); font-size: 8px; }.file-tabs__status { display: flex; min-width: 0; align-items: center; gap: 7px; margin-left: auto; color: var(--text-muted); font-size: 9px; white-space: nowrap; }.file-tabs__status > span { overflow: hidden; text-overflow: ellipsis; }.file-tabs__status .error { color: var(--danger); }.file-tabs__status .icon-button { display: grid; width: 28px; height: 28px; flex: 0 0 auto; place-items: center; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--text-muted); cursor: pointer; }.file-tabs__status .icon-button:hover { background: var(--surface-soft); color: var(--text-primary); }
-@media (max-width: 600px) { .library-header { min-height: 52px; padding: 0 13px; }.library-header h2 { font-size: 14px; }.file-search { width: min(180px, 52vw); }.file-tabs { padding: 0 13px; }.file-tabs__status { display: none; } }
-</style>

+ 0 - 466
src/client/views/HistoryView.vue

@@ -1,466 +0,0 @@
-<script setup lang="ts">
-import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
-import { useRoute, useRouter } from 'vue-router'
-import AppIcon from '@/components/common/AppIcon.vue'
-import YaoYaoSidebarIcon from '@/components/common/YaoYaoSidebarIcon.vue'
-import type { ChoiceOption } from '@/components/common/types'
-import ComposerShell from '@/components/composer/ComposerShell.vue'
-import ModelChoiceDialog from '@/components/composer/ModelChoiceDialog.vue'
-import type { ComposerOption, ComposerReference, ComposerSubmit } from '@/components/composer/types'
-import PreviewInspector from '@/components/library/PreviewInspector.vue'
-import PreviewModal from '@/components/library/PreviewModal.vue'
-import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
-import type { PreviewMedia } from '@/components/library/ImagePreviewLightbox.vue'
-import type { UiLibraryItem } from '@/components/library/types'
-import { mediaItemsFromMessages, mediaUrlIdentity, previewItemFromUrl } from '@/components/library/mediaSequence'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
-import SessionOutline from '@/components/messages/SessionOutline.vue'
-import type { UiMessage } from '@/components/messages/types'
-import ResourceSidebar from '@/components/app/ResourceSidebar.vue'
-import FloatingResourceSearch from '@/components/app/FloatingResourceSearch.vue'
-import WorkspaceView from '@/components/workspace/WorkspaceView.vue'
-import { chatInteraction, chatMessagesToUi, sessionSidebarItem } from '@/components/workspace/viewModels'
-import { consumeLibraryItemForComposer, loadComposerFile } from '@/components/workspace/pendingComposer'
-import { readAgentShowThinking, writeAgentShowThinking } from '@/utils/sessionPreferences'
-import { modelChoiceId, modelForChoiceId } from '@/utils/sessionModel'
-import { MODEL_CATALOG_CHANGED_EVENT, modelCatalogChangedProfile } from '@/utils/modelCatalogEvents'
-import { isOwnedChatSession } from '@/utils/sessionOwnership'
-import { useAuthStore } from '@/stores/auth'
-import { useChatStore } from '@/stores/chat'
-import { getSession } from '@/api/sessions'
-
-const auth = useAuthStore()
-const chat = useChatStore()
-const route = useRoute()
-const router = useRouter()
-const quoted = ref<UiMessage | null>(null)
-const preview = ref<UiLibraryItem | null>(null)
-const filePreview = ref<UiLibraryItem | null>(null)
-const mediaPreviewIndex = ref<number | null>(null)
-const outlineOpen = ref(false)
-const modelDialog = ref(false)
-const modelSwitching = ref(false)
-const showThinking = ref(false)
-const queueMode = ref(false)
-const actionSessionId = ref('')
-const renaming = ref(false)
-const renameValue = ref('')
-const actionMenuPosition = ref({ x: 8, y: 8 })
-const composer = ref<InstanceType<typeof ComposerShell> | null>(null)
-const timeline = ref<InstanceType<typeof MessageTimeline> | null>(null)
-const headerSessionMenuButton = ref<HTMLButtonElement | null>(null)
-const restoringRouteProfile = ref('')
-let modelSyncTimer: number | undefined
-
-function handleModelCatalogChanged(event: Event) {
-  const profile = modelCatalogChangedProfile(event)
-  if (profile && profile === auth.activeProfile?.name) void chat.loadModels(profile).catch(() => undefined)
-}
-
-const sessions = computed(() => [...chat.sessions]
-  .filter(session => !isOwnedChatSession(session)
-    && !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source)))
-const agentNames = computed(() => new Map(auth.profiles.map(profile => [
-  profile.name,
-  profile.agentName || profile.displayName || profile.name,
-])))
-const agentAvatars = computed(() => Object.fromEntries(auth.profiles.flatMap(profile =>
-  profile.agentAvatar ? [[profile.name, profile.agentAvatar] as const] : []
-)))
-const sidebarItems = computed(() => sessions.value.map(session => sessionSidebarItem(
-  session,
-  chat.unreadCounts[session.id] ?? 0,
-  agentNames.value.get(session.profile || auth.activeProfile?.name || ''),
-)))
-const messages = computed(() => chatMessagesToUi(chat.messages, profile => profile ? agentNames.value.get(profile) : undefined))
-const conversationMediaItems = computed(() => mediaItemsFromMessages(messages.value))
-const lightboxMedia = computed(() => conversationMediaItems.value.map(item => ({ url: item.previewUrl || item.downloadUrl || '', name: item.name, type: item.kind as 'image' | 'video' })).filter(item => item.url))
-const activeSession = computed(() => chat.activeSession)
-const actionSession = computed(() => chat.sessions.find(session => session.id === actionSessionId.value))
-const connected = computed(() => ['connected', 'ready'].includes(chat.connectionState))
-const interaction = computed(() => chatInteraction(chat.pendingApproval, chat.pendingClarification))
-const reference = computed<ComposerReference | null>(() => quoted.value ? { id: quoted.value.id, content: quoted.value.content, author: quoted.value.author } : null)
-const forkSourceTitle = computed(() => {
-  const parentId = activeSession.value?.parentSessionId
-  if (!parentId) return ''
-  return chat.sessions.find(session => session.id === parentId && session.profile === activeSession.value?.profile)?.title || parentId
-})
-const selectedModelId = computed(() => chat.selectedModel ? modelChoiceId(chat.selectedModel) : '')
-const reasoningOptions: ChoiceOption[] = [
-  { id: '', label: '默认', description: '使用模型或 Profile 的默认强度' },
-  { id: 'none', label: '关闭', description: '不使用额外推理' },
-  { id: 'low', label: '低', description: '更快的轻量推理' },
-  { id: 'medium', label: '中', description: '速度与深度平衡' },
-  { id: 'high', label: '高', description: '更深入地分析复杂问题' },
-  { id: 'xhigh', label: '极高', description: '适用于最复杂的任务' },
-]
-const reasoningComposerOptions = computed<ComposerOption[]>(() => reasoningOptions.map(option => ({
-  id: option.id,
-  label: option.label,
-  detail: option.description,
-})))
-const reasoningLabel = computed(() => reasoningOptions.find(option => option.id === (chat.reasoningEffort || ''))?.label || '默认')
-const actionMenuStyle = computed(() => ({ left: `${actionMenuPosition.value.x}px`, top: `${actionMenuPosition.value.y}px` }))
-
-function routeProfile(): string {
-  const value = typeof route.query.profile === 'string' ? route.query.profile : ''
-  return auth.profiles.some(profile => profile.name === value) ? value : ''
-}
-
-function sessionLocation(id: string, profile: string) {
-  return { path: `/history/${encodeURIComponent(id)}`, query: { profile } }
-}
-
-async function findLegacySessionProfile(sessionId: string): Promise<string> {
-  for (const profile of auth.profiles) {
-    try {
-      const session = await getSession(sessionId, profile.name)
-      if (session.id === sessionId) return profile.name
-    } catch { /* Try the next profile: 9119 returns 404 for a foreign session. */ }
-  }
-  return auth.activeProfile?.name || ''
-}
-
-async function ensureRouteProfile(profile: string): Promise<void> {
-  if (!profile || auth.activeProfile?.name === profile) return
-  chat.switchProfile(profile)
-  restoringRouteProfile.value = profile
-  auth.selectProfile(profile)
-  await nextTick()
-}
-
-async function refreshSessions() {
-  const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
-  const profile = routeProfile() || (requestedId ? await findLegacySessionProfile(requestedId) : auth.activeProfile?.name || '')
-  if (profile && auth.activeProfile?.name !== profile) {
-    if (requestedId) await router.replace(sessionLocation(requestedId, profile))
-    await ensureRouteProfile(profile)
-  }
-  // The session route is the authoritative navigation target. A secondary
-  // unread-count request must never prevent its history from being restored.
-  await chat.loadSessions(profile, 'history')
-  if (requestedId) {
-    const target = await getSession(requestedId, profile).catch(() => undefined)
-    if (target && isOwnedChatSession(target)) {
-      await router.replace({ path: `/chat/${encodeURIComponent(requestedId)}`, query: { profile } })
-      return
-    }
-  }
-  if (requestedId && chat.activeSessionId !== requestedId) await chat.selectSession(requestedId, profile)
-  if (requestedId && profile && routeProfile() !== profile) await router.replace(sessionLocation(requestedId, profile))
-  void chat.loadUnread(profile).catch(() => undefined)
-  if (!requestedId && chat.activeSession && isOwnedChatSession(chat.activeSession)) {
-    chat.clearSelection()
-  }
-}
-
-async function chooseSession(id: string) {
-  outlineOpen.value = false
-  preview.value = null
-  const session = chat.sessions.find(item => item.id === id)
-  const profile = session?.profile || auth.activeProfile?.name || 'default'
-  await router.push(sessionLocation(id, profile))
-  await ensureRouteProfile(profile)
-  if (chat.activeProfileName !== profile) await chat.loadSessions(profile, 'history')
-  await chat.selectSession(id, profile)
-  await chat.markRead(id, profile).catch(() => undefined)
-  quoted.value = null
-}
-
-async function createSession() {
-  outlineOpen.value = false
-  preview.value = null
-  const id = chat.createSession(auth.activeProfile?.name)
-  await router.push(sessionLocation(id, auth.activeProfile?.name || 'default'))
-}
-
-async function send(payload: ComposerSubmit) {
-  try {
-    await chat.send(payload.text, payload.files, queueMode.value ? 'queue' : chat.isStreaming ? 'steer' : 'submit')
-    composer.value?.clearAfterSend()
-  } catch { /* store exposes the error and the composer keeps its draft */ }
-}
-
-function openAttachment(attachment: NonNullable<UiMessage['attachments']>[number]) {
-  const item = previewItemFromUrl(attachment.name, attachment.url || '', attachment.id, attachment.kind)
-  item.size = attachment.size
-  if (item.kind === 'image' || item.kind === 'video') openMedia(item)
-  else { outlineOpen.value = false; preview.value = null; filePreview.value = item }
-}
-
-function openMedia(item: UiLibraryItem) {
-  const target = mediaUrlIdentity(item.previewUrl || item.downloadUrl || '')
-  const index = lightboxMedia.value.findIndex(media => mediaUrlIdentity(media.url) === target)
-  mediaPreviewIndex.value = index >= 0 ? index : null
-}
-
-function openLocalFile({ name, url }: { name: string; url: string }) {
-  const item = previewItemFromUrl(name, url)
-  if (item.kind === 'image' || item.kind === 'video') openMedia(item)
-  else { outlineOpen.value = false; filePreview.value = item }
-}
-
-async function addPreviewToComposer(item: UiLibraryItem) {
-  const file = await loadComposerFile(item)
-  if (!file || !composer.value) return
-  composer.value.attachFiles([file])
-  preview.value = null
-  filePreview.value = null
-  mediaPreviewIndex.value = null
-  await nextTick()
-  composer.value?.focus()
-}
-
-async function addMediaToComposer(media: PreviewMedia) {
-  await addPreviewToComposer(previewItemFromUrl(media.name, media.url, `preview:${media.url}`, media.type))
-}
-
-async function selectModel(id: string) {
-  if (id === selectedModelId.value) {
-    modelDialog.value = false
-    return
-  }
-  const model = modelForChoiceId(chat.models, id)
-  if (!model || modelSwitching.value) return
-  modelSwitching.value = true
-  try {
-    await chat.setModel(model)
-    modelDialog.value = false
-  } finally {
-    modelSwitching.value = false
-  }
-}
-
-function selectReasoning(id: string) {
-  chat.reasoningEffort = id || undefined
-}
-
-async function toggleFastMode(enabled: boolean) {
-  try { await chat.setFastMode(enabled) } catch { /* store restores the acknowledged state */ }
-}
-
-function restoreShowThinking(profile = auth.activeProfile?.name || 'default') {
-  showThinking.value = readAgentShowThinking(auth.user?.id ?? 'local', profile)
-}
-
-function toggleShowThinking() {
-  showThinking.value = !showThinking.value
-  writeAgentShowThinking(auth.user?.id ?? 'local', auth.activeProfile?.name || 'default', showThinking.value)
-}
-
-function openSessionActions(id: string, event?: MouseEvent) {
-  actionSessionId.value = id
-  const session = chat.sessions.find(item => item.id === id)
-  renameValue.value = session?.title || ''
-  renaming.value = false
-  const menuWidth = 208
-  const menuHeight = 176
-  const inset = 8
-  const anchor = event?.currentTarget instanceof HTMLElement ? event.currentTarget.getBoundingClientRect() : null
-  const requestedX = event?.type === 'contextmenu' ? event.clientX : anchor ? anchor.right - menuWidth : window.innerWidth - menuWidth - 14
-  const requestedY = event?.type === 'contextmenu' ? event.clientY : anchor ? anchor.bottom + 5 : 46
-  actionMenuPosition.value = {
-    x: Math.max(inset, Math.min(requestedX, window.innerWidth - menuWidth - inset)),
-    y: Math.max(inset, Math.min(requestedY, window.innerHeight - menuHeight - inset)),
-  }
-}
-
-function closeSessionActions() {
-  actionSessionId.value = ''
-  renaming.value = false
-}
-
-function handleSessionActionPointer(event: PointerEvent) {
-  if (!actionSessionId.value || (event.target as HTMLElement).closest('.session-actions')) return
-  closeSessionActions()
-}
-
-function handleSessionActionKey(event: KeyboardEvent) {
-  if (event.key === 'Escape' && actionSessionId.value) closeSessionActions()
-}
-
-async function saveRename() {
-  const session = chat.sessions.find(item => item.id === actionSessionId.value)
-  if (!session || !renameValue.value.trim()) return
-  await chat.renameSession(session.id, renameValue.value.trim(), session.profile)
-  closeSessionActions()
-}
-
-async function toggleSessionPinned() {
-  const session = actionSession.value
-  if (!session) return
-  await chat.setSessionPinned(session.id, !session.pinned, session.profile)
-  closeSessionActions()
-}
-
-async function openSessionOutline() {
-  const session = actionSession.value
-  if (!session) return
-  closeSessionActions()
-  if (session.id !== chat.activeSessionId || session.profile !== chat.activeProfileName) await chooseSession(session.id)
-  preview.value = null
-  outlineOpen.value = true
-}
-
-function closeInspector() {
-  const restoreMenuFocus = outlineOpen.value
-  preview.value = null
-  outlineOpen.value = false
-  if (restoreMenuFocus) void nextTick(() => headerSessionMenuButton.value?.focus())
-}
-
-function navigateOutline(target: { messageId: string; anchorId: string }) {
-  timeline.value?.scrollToAnchor(target.messageId, target.anchorId)
-  if (window.matchMedia('(max-width: 900px)').matches) closeInspector()
-}
-
-async function deleteSession() {
-  const session = chat.sessions.find(item => item.id === actionSessionId.value)
-  if (!session) return
-  await chat.removeSession(session.id, session.profile)
-  closeSessionActions()
-  if (route.params.sessionId === session.id) await router.replace('/chat')
-}
-
-async function branch() {
-  const id = await chat.branchSession()
-  if (id) await router.push(sessionLocation(id, chat.activeProfileName || auth.activeProfile?.name || 'default'))
-}
-
-async function revealSourceMessage() {
-  const messageId = typeof route.query.message === 'string' ? route.query.message : ''
-  if (!messageId) return
-  await nextTick()
-  for (let attempt = 0; attempt < 10; attempt += 1) {
-    if (timeline.value?.scrollToMessage(messageId)) return
-    if (!chat.hasMoreBefore) return
-    await chat.loadOlder()
-    await nextTick()
-  }
-}
-
-onMounted(async () => {
-  restoreShowThinking()
-  document.addEventListener('pointerdown', handleSessionActionPointer)
-  document.addEventListener('keydown', handleSessionActionKey)
-  window.addEventListener(MODEL_CATALOG_CHANGED_EVENT, handleModelCatalogChanged)
-  await refreshSessions()
-  await revealSourceMessage()
-})
-
-onBeforeUnmount(() => {
-  document.removeEventListener('pointerdown', handleSessionActionPointer)
-  document.removeEventListener('keydown', handleSessionActionKey)
-  window.removeEventListener(MODEL_CATALOG_CHANGED_EVENT, handleModelCatalogChanged)
-  if (modelSyncTimer !== undefined) window.clearInterval(modelSyncTimer)
-})
-
-watch(() => auth.activeProfile?.name, async (profile, previous) => {
-  if (!profile || profile === previous) return
-  restoreShowThinking(profile)
-  outlineOpen.value = false
-  preview.value = null
-  if (restoringRouteProfile.value === profile) {
-    restoringRouteProfile.value = ''
-    return
-  }
-  chat.switchProfile(profile)
-  const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
-  if (requestedId && routeProfile() === profile) {
-    await Promise.allSettled([chat.loadSessions(profile, 'history'), chat.loadUnread(profile)])
-    await chat.selectSession(requestedId, profile)
-    return
-  }
-  await router.replace({ path: '/history', query: { profile } })
-  await Promise.allSettled([chat.loadSessions(profile, 'history'), chat.loadUnread(profile)])
-})
-
-watch(() => chat.activeSessionId, async id => {
-  const profile = chat.activeProfileName || auth.activeProfile?.name || ''
-  if (!id || (route.params.sessionId === id && routeProfile() === profile)) return
-  await router.replace(sessionLocation(id, profile))
-})
-</script>
-
-<template>
-  <WorkspaceView sidebar-title="历史记录" :sidebar-subtitle="`${sessions.length} 个会话`" :inspector-open="!!preview || outlineOpen" :inspector-close-label="outlineOpen ? '关闭会话大纲' : '关闭预览'" @close-inspector="closeInspector">
-    <template #sidebar>
-      <ResourceSidebar
-        :items="sidebarItems"
-        :active-id="chat.activeSessionId"
-        :loading="chat.isLoading"
-        external-search
-        single-line
-        :has-more="chat.hasMoreSessions"
-        :loading-more="chat.isLoadingMoreSessions"
-        search-placeholder="搜索会话"
-        empty-title="还没有历史会话"
-        empty-description="Hermes 会话会在这里以只读历史显示。"
-        @load-more="chat.loadMoreSessions(auth.activeProfile?.name)"
-        @select="chooseSession"
-        @more="openSessionActions"
-        @context-menu="openSessionActions"
-      />
-    </template>
-
-    <div class="chat-workspace">
-      <MessageTimeline
-        ref="timeline"
-        :messages="messages"
-        :title="activeSession?.title || '历史记录'"
-        :subtitle="activeSession ? `${activeSession.profile || auth.activeProfile?.name || ''} · ${activeSession.model || '默认模型'}` : '选择左侧会话查看历史'"
-        :loading="chat.activeRouteState?.isLoadingHistory || chat.isLoading"
-        :loading-older="chat.activeRouteState?.isLoadingHistory"
-        :has-older="chat.hasMoreBefore"
-        :connected="false"
-        :synced="chat.historySynced"
-        :show-tools="showThinking"
-        :thinking="false"
-        :show-assistant-identity="false"
-        :agent-avatars="agentAvatars"
-        :allow-branch="false"
-        empty-title="选择历史记录"
-        empty-description="从左侧选择一条 Hermes 历史会话查看。"
-        read-only
-        transparent-header
-        @load-older="chat.loadOlder"
-        @preview="openAttachment"
-        @preview-file="openLocalFile"
-      >
-        <template #header-actions>
-          <button v-if="activeSession" ref="headerSessionMenuButton" class="icon-button header-session-menu" type="button" title="会话操作" aria-label="会话操作" @click="openSessionActions(activeSession.id, $event)"><AppIcon name="dots" :size="18" /></button>
-        </template>
-      </MessageTimeline>
-      <p v-if="chat.error" class="chat-error" role="alert"><AppIcon name="alert" :size="13" />{{ chat.error }}</p>
-    </div>
-
-    <template #inspector>
-      <SessionOutline v-if="outlineOpen" :messages="messages" :has-older="chat.hasMoreBefore" @navigate="navigateOutline" />
-      <PreviewInspector v-else-if="preview" :item="preview" :can-add-to-composer="false" @close="preview = null" />
-    </template>
-  </WorkspaceView>
-
-  <FloatingResourceSearch section="chat" label="搜索会话" :items="sidebarItems" @select="chooseSession" />
-  <PreviewModal v-if="filePreview" :item="filePreview" :items="conversationMediaItems" :can-add-to-composer="false" @close="filePreview = null" @source="filePreview = null" />
-  <ImagePreviewLightbox v-model="mediaPreviewIndex" :images="lightboxMedia" :can-add="false" />
-
-  <Teleport to="body">
-    <Transition name="session-menu">
-      <section v-if="actionSessionId" class="session-actions" :style="actionMenuStyle" role="menu" aria-label="会话操作" @contextmenu.prevent>
-        <button class="action-row" role="menuitem" type="button" @click="openSessionOutline"><AppIcon name="menu" :size="14" />会话大纲</button>
-      </section>
-    </Transition>
-  </Teleport>
-</template>
-
-<style scoped>
-.chat-workspace { display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; }
-.sidebar-primary-action { display: flex; width: 100%; min-height: 40px; align-items: center; gap: 10px; padding: 0 11px; border: 0; border-radius: 9px; background: transparent; color: var(--text-primary); cursor: pointer; font-size: 12px; font-weight: 610; text-align: left; transition: background-color 120ms ease; }
-.sidebar-primary-action:hover, .sidebar-primary-action:focus-visible { background: var(--surface-hover); outline: 0; }
-.sidebar-primary-action:focus-visible { box-shadow: inset 0 0 0 1px var(--line-strong); }
-.header-session-menu { color: var(--text-muted); background: transparent; }.header-session-menu:hover { color: var(--text-primary); background: var(--surface-soft); }
-.chat-error { display: flex; width: min(760px, calc(100% - 32px)); margin: 0 auto 4px; align-items: center; gap: 6px; color: var(--danger); font-size: 9px; }
-.session-actions { position: fixed; z-index: 205; width: 208px; box-sizing: border-box; padding: 6px; border: 1px solid var(--line); border-radius: 11px; background: var(--surface-raised); box-shadow: 0 12px 34px rgba(0,0,0,.16); }.action-row { display: flex; width: 100%; min-height: 34px; align-items: center; gap: 8px; padding: 0 9px; border: 0; border-radius: 7px; background: transparent; color: var(--text-secondary); cursor: pointer; font-size: 11px; text-align: left; }.action-row:hover, .action-row:focus-visible { outline: 0; background: var(--surface-soft); color: var(--text-primary); }.action-row.danger { color: var(--danger); }.session-actions label { display: flex; flex-direction: column; gap: 6px; padding: 4px; color: var(--text-muted); font-size: 9px; }.session-actions input { width: 100%; height: 32px; box-sizing: border-box; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; outline: 0; background: var(--surface-soft); color: var(--text-primary); font-size: 11px; }.session-actions input:focus { border-color: var(--line-strong); box-shadow: 0 0 0 3px var(--focus-ring); }.session-actions > div { display: flex; justify-content: flex-end; gap: 5px; margin-top: 7px; padding: 0 4px 3px; }.session-actions :deep(.quiet-button), .session-actions :deep(.solid-button) { min-height: 29px; padding-inline: 10px; font-size: 10px; }
-.session-menu-enter-active, .session-menu-leave-active { transition: opacity 100ms ease, transform 120ms var(--ease-out); transform-origin: top right; }.session-menu-enter-from, .session-menu-leave-to { opacity: 0; transform: translateY(-3px) scale(.98); }
-@media (prefers-reduced-motion: reduce) { .sidebar-primary-action, .session-menu-enter-active, .session-menu-leave-active { transition: none; } }
-</style>

+ 14 - 118
src/server/app.ts

@@ -5,7 +5,6 @@ import {CredentialVaultCoordinator} from './credentialVault/coordinator.js'
 import {createCredentialVaultClient} from './credentialVault/localClient.js'
 import {ManagedBrowsers} from './managedBrowsers.js'
 import { isWorkspaceAccountPath } from './subaccountAccess.js'
-import { chatTranscriptRouter } from './chatTranscriptApi.js'
 import {DesktopEnvironments} from './desktopEnvironments.js'
 import {DesktopHostHub} from './desktopHosts.js'
 import type {GrokAuth} from './grokAuth.js'
@@ -14,9 +13,6 @@ import {WorkspaceInspector} from './workspaceInspector.js'
 import {WorkspaceRoutines} from './workspaceRoutines.js'
 import {WorkspaceRoutineTools} from './workspaceRoutineTools.js'
 import { WorkspacePlugins } from './botPlugins/workspacePlugins.js'
-import { nativeMessageFileText } from '../shared/messageFiles.js'
-import { hermesBotRelay } from './hermesBotRelay.js'
-import { remoteAgentExports } from './workspaceRemoteAgents.js'
 import { randomBytes, createHash } from 'node:crypto'
 import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
 import { createServer as createHttpServer, type Server as HttpServer } from 'node:http'
@@ -24,7 +20,6 @@ import { createServer as createHttpsServer } from 'node:https'
 import { join } from 'node:path'
 import { bodyParser } from '@koa/bodyparser'
 import Koa from 'koa'
-import { RealtimeAPI } from './realtimeApi.js'
 import type { ServerConfig } from './config.js'
 import { loadServerConfig } from './config.js'
 import { errorMessage, HttpError } from './errors.js'
@@ -62,16 +57,10 @@ import {
 import { OpenVikingConfigurationManager } from './openVikingConfiguration.js'
 import { OpenVikingService } from './openVikingService.js'
 import { OpenVikingSessionSync } from './openVikingSessionSync.js'
-import { PushCoordinatorEventAdapter } from './pushEventAdapter.js'
 import {
   AllowedHostsConfigurationManager,
   type AllowedHostsConfigurationSnapshot,
 } from './allowedHostsConfiguration.js'
-import {
-  ChatPushJobManager,
-  HermesChatNotificationResolver,
-} from './pushEvents.js'
-import { ChatCacheCoordinator, ChatCacheStore } from './chatCache.js'
 import {LocalVmService} from './localVm.js'
 import {SharedComputers} from './sharedComputers.js'
 import {ComputerControlService} from './computerControls.js'
@@ -97,7 +86,6 @@ export interface ApplicationOptions {
   fcmConfiguration?: FCMConfigurationManager
   openVikingConfiguration?: OpenVikingConfigurationManager
   allowedHostsConfiguration?: AllowedHostsConfigurationManager
-  chatCache?: ChatCacheCoordinator
 }
 
 export interface ApplicationRuntime {
@@ -105,7 +93,6 @@ export interface ApplicationRuntime {
   runners: RunnerHub
   workspace: WorkspaceStore
   workspaceRuntime: WorkspaceRuntime
-  realtime: RealtimeAPI
   app: Koa
   config: ServerConfig
   csrf: CsrfProtection
@@ -125,9 +112,6 @@ export interface ApplicationRuntime {
   openVikingService: OpenVikingService
   openVikingSessionSync: OpenVikingSessionSync
   allowedHostsConfiguration: AllowedHostsConfigurationManager
-  pushEventCoordinator: PushCoordinatorEventAdapter
-  chatPushJobs: ChatPushJobManager
-  chatCache?: ChatCacheCoordinator
   desktopEnvironments:DesktopEnvironments
   desktopHosts:DesktopHostHub
   grokAuth:GrokAuth
@@ -195,17 +179,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     upstream,
     () => auth.upstreamCredentials(configuredUpstreamCredentials),
   )
-  let chatCache = options.chatCache
-  if (!chatCache) {
-    chatCache = new ChatCacheCoordinator(
-      new ChatCacheStore(
-        config.home,
-        auth.soleUserIDForLegacyMigration(),
-      ),
-      upstreamSession,
-      config.chatCacheMode ?? 'prefer-local',
-    )
-  }
   const accountPairings = options.accountPairings ?? new AccountLoginPairingStore()
   const profileIdentities = options.profileIdentities
     ?? new UpstreamProfileIdentityService(config, upstreamSession)
@@ -252,16 +225,9 @@ export function createApplication(options: ApplicationOptions = {}): Application
     isUserActive: userID => auth.isUserActive(userID),
     userAuthorizationVersion: userID => auth.pushAuthorizationVersion(userID),
   })
-  const pushEventCoordinator = new PushCoordinatorEventAdapter(push)
-  const chatPushJobs = new ChatPushJobManager(config, upstreamSession, pushEventCoordinator, {
-    resolver: new HermesChatNotificationResolver(
-      upstreamSession,
-      (localUserID, prompt) => push.promptDigest(localUserID, prompt),
-    ),
-  })
   // The application owns group events. No Dashboard plugin is queried.
   const workspace = new WorkspaceStore(config.home)
-  push.setUnreadCounter(owner => unreadSnapshot(workspace, chatCache!.store, owner,(node,profile)=>auth.canUseSource(owner,node,profile)).total)
+  push.setUnreadCounter(owner => unreadSnapshot(workspace, owner,(node,profile)=>auth.canUseSource(owner,node,profile)).total)
   const openVikingService = new OpenVikingService(workspace, openVikingConfiguration)
   const workspaceNodes = new WorkspaceNodes(workspace, config, { url: config.upstream, client: upstream, session: upstreamSession, ...(upstream.embedded ? { embedded: hermes.gateway } : {}) }, pairings.nodeID)
   workspaceNodes.sourceAllowed = (owner, nodeId, profile) => auth.canUseSource(owner, nodeId, profile)
@@ -324,45 +290,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     if (c.kind === 'group' && !push.isGroupSubscribed(owner,c.id)) return
     push.enqueueNotification({ kind: interaction ? interaction.kind === 'approval' ? 'chat.approval.requested' : 'chat.clarification.requested' : run.status === 'failed' ? 'chat.failed' : 'chat.completed', eventID: `workspace:${interaction?.id ?? run.id}`, localUserID: owner, title: c.name, body: (interaction?.message || message?.content || run.error || '回复完成').slice(0,180), collapseID: `workspace:${c.id}:${run.conversationTaskId ?? 'direct'}`, data: { conversationId:c.id, ...(run.conversationTaskId ? { conversationTaskId: run.conversationTaskId } : {}), workspace:'1' }, ...(c.kind === 'group' ? {roomID:c.id} : {}) })
   }
-  const realtime = new RealtimeAPI(config, auth, csrf, pairings, upstream, upstreamSession, {
-    coordinator: pushEventCoordinator,
-    resolver: new HermesChatNotificationResolver(upstreamSession, (user, prompt) => push.promptDigest(user, prompt)),
-  }, (owner, profile, sessionID) =>
-    chatCache?.store.ownsSession(owner, profile, sessionID) ?? false)
-  if (upstream.embedded) realtime.gateway = hermes.gateway
-  realtime.broker.protectedSession = id => workspace.ownsUpstream(id)
-  realtime.transcriptsAvailable = chatCache.store.transcripts.enabled
-  realtime.broker.onNativeEvent = (owner, profile, storedId, frame) => {
-    chatCache?.observe(owner, profile, storedId, frame)
-    if (owner.startsWith('device:')) return
-    if (!['message.complete', 'attachment.staged'].includes(frame.type)) return
-    const data = frame.payload ?? {}, text = frame.type === 'attachment.staged' ? JSON.stringify(data) : nativeMessageFileText(data)
-    const messageId = String(chatCache.store.projectedMessageID(owner,profile,storedId) ?? data.row_id ?? data.message_id ?? data.id ?? createHash('sha256').update(text).digest('hex'))
-    void workspaceAssets.archiveText(owner, text, 'local', profile, storedId, messageId, frame.type === 'attachment.staged' ? 'user' : 'agent').catch(() => {})
-  }
-  workspace.nativeMessageForFile = (owner, file) => {
-    const message = chatCache?.store.fileSourceMessage(owner, file.profile ?? 'default', file.conversationId ?? '', file.messageId ?? '')
-    if (!message) return undefined
-    return {
-      id: file.messageId!, conversationId: file.conversationId!, seq: 0,
-      role: message.role === 'assistant' ? 'assistant' : message.role === 'user' ? 'user' : 'system',
-      content: nativeMessageFileText(message), reasoning: '', status: 'complete',
-      attachments: [], tools: [], createdAt: file.createdAt,
-    }
-  }
-  realtime.broker.onNativeGlobalEvent = (owner, type, upstreamInvalidation) => chatCache?.observeGlobal(owner, type, upstreamInvalidation)
-  chatCache.onSynchronized = (owner, profile, sessionID) => {
-    realtime.broker.publishOwnerSessionsChanged(owner, 'cache.synced', profile, sessionID)
-  }
-  realtime.broker.onNativeCommand = (owner, profile, storedId, method, params) => {
-    chatCache?.command(owner, profile, storedId, method, params)
-  }
-  realtime.broker.nativeSourceCursor = (owner,profile,id,runtime,epoch)=>chatCache.store.transcripts.sourceCursor(owner,profile,id,runtime,epoch)
-  realtime.broker.onNativeRoute = (owner, profile, storedId, runtimeId, running, snapshot) => {
-    chatCache?.route(owner, profile, storedId, runtimeId, snapshot?undefined:running)
-    if(snapshot)chatCache.store.recordEvent(owner,profile,storedId,{type:'route.resumed',payload:snapshot})
-  }
-  chatPushJobs.setTransportFactory(realtime.recoveryTransport, job => realtime.ownsPushJob(job.id))
   try {
     uploads.cleanupUncommitted()
   } catch {
@@ -432,9 +359,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     }
     await next()
   })
-  app.use(hermesBotRelay(workspaceNodes, auth, csrf))
-  app.use(remoteAgentExports(workspace,workspaceNodes,pairings,auth))
-  app.use(realtime.middleware())
   const parseBody = (limit: string) => bodyParser({
     encoding: 'utf-8',
     enableTypes: ['json'],
@@ -507,28 +431,9 @@ export function createApplication(options: ApplicationOptions = {}): Application
   app.use(applicationRouter.routes())
   app.use(async (ctx, next) => {
     if (ctx.path.includes('/plugins/yaoyao') || ctx.path.startsWith('/api/app/groups')) throw new HttpError(410, '请使用新版聊天接口', 'retired_plugin_api')
-    const id = /\/sessions\/([^/]+)/.exec(ctx.path)?.[1]
-    if (id && workspace.ownsUpstream(decodeURIComponent(id))) throw new HttpError(404, '会话不存在', 'session_not_found')
     await next()
-    // Native history is a separate surface, including search and profile projections.
-    if (ctx.path.includes('/sessions') || ctx.path.endsWith('/profiles')) {
-      let value: any = ctx.body
-      const buffered = Buffer.isBuffer(value)
-      try {
-        if (buffered) value = JSON.parse(value.toString())
-        const filter = (v: any): any => {
-          if (Array.isArray(v)) return v.filter(x => !x || typeof x !== 'object' || (x.source !== 'yaoyao_workspace' && !workspace.ownsUpstream(String(x.id ?? x.session_id ?? x.sessionId ?? '')))).map(filter)
-          if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k,x]) => [k, filter(x)]))
-          return v
-        }
-        ctx.body = buffered ? Buffer.from(JSON.stringify(filter(value))) : filter(value)
-      } catch { /* Preserve non-JSON error responses. */ }
-    }
   })
-  app.use(chatTranscriptRouter(chatCache, auth).routes())
   const router = createApiRouter({
-    onChatListChanged: (owner,profile,id) => realtime.broker.publishOwnerSessionsChanged(owner,'local-state',profile,id),
-    onServerIdentityChanged: identity => realtime.broker.publishServerIdentity(identity, config.upstream.href),
     onUserAccessChanged: async owner => {
       for (const c of workspace.list<{ id: string }>(owner, 'conversation')) await workspaceRuntime.stopConversation(owner, c.id)
     },
@@ -551,7 +456,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     openVikingService,
     openVikingSessionSync,
     allowedHostsConfiguration,
-    chatCache,
   })
   app.use(router.routes())
   app.use(router.allowedMethods({ throw: false }))
@@ -576,7 +480,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     desktopEnvironments,
     desktopHosts,
     grokAuth:grokCloud.authorization,
-    realtime,
     app,
     config,
     csrf,
@@ -596,9 +499,6 @@ export function createApplication(options: ApplicationOptions = {}): Application
     openVikingService,
     openVikingSessionSync,
     allowedHostsConfiguration,
-    pushEventCoordinator,
-    chatPushJobs,
-    chatCache,
     startBackground,
     close: () => {
       credentialVault.close()
@@ -618,13 +518,9 @@ export function createApplication(options: ApplicationOptions = {}): Application
       workspaceNodes.close()
       upstream.close()
       if (!options.hermes) hermes.close()
-      realtime.close()
-      chatPushJobs.stop()
       push.close()
       uploads.close()
       workspace.close()
-      chatCache?.close()
-      chatCache?.store.close()
     },
   }
 }
@@ -644,14 +540,6 @@ export function createNodeServer(runtime: ApplicationRuntime, options: { deferBa
       }, runtime.app.callback())
     : createHttpServer(runtime.app.callback())
   let backgroundStarted = false, localVmStarted = false, closed = false
-  const synchronizePushObservers = (enabled = runtime.push.isAnyProviderEnabled()) => {
-    if (!backgroundStarted || closed) return
-    if (enabled) {
-      runtime.chatPushJobs.start()
-    } else {
-      runtime.chatPushJobs.stop()
-    }
-  }
   const startLocalVm = () => {
     if (!backgroundStarted || localVmStarted || closed) return
     const address = server.address()
@@ -667,22 +555,18 @@ export function createNodeServer(runtime: ApplicationRuntime, options: { deferBa
     runtime.workspaceRuntime.start()
     runtime.workspaceRoutines.start()
     runtime.grokAuth.start()
-    synchronizePushObservers()
     startLocalVm()
   }
   server.once('listening', startLocalVm)
   if (!options.deferBackground) startBackground()
-  const removePushConfigurationListener = runtime.push.onEnabledChange(synchronizePushObservers)
-  const removeWebSockets = runtime.realtime.rejectLegacyUpgrades(server)
+  const removeWebSockets = rejectWebSocketUpgrades(server, config.production)
   return {
     server,
     startBackground,
     close: async (closeConnections = false) => {
       closed = true
       await runtime.localVm.close()
-      removePushConfigurationListener()
       removeWebSockets()
-      runtime.realtime.close()
       if (closeConnections) server.closeAllConnections()
       await new Promise<void>((resolve, reject) => {
         if (!server.listening) {
@@ -695,3 +579,15 @@ export function createNodeServer(runtime: ApplicationRuntime, options: { deferBa
     },
   }
 }
+
+/** Clients use HTTP; reject WebSocket upgrades explicitly (Vite owns HMR sockets in development). */
+function rejectWebSocketUpgrades(server: HttpServer, production: boolean): () => void {
+  const upgrade = (request: import('node:http').IncomingMessage, socket: import('node:stream').Duplex) => {
+    const path = (request.url ?? '/').split('?')[0]!
+    if (!production && !path.startsWith('/api/') && !path.startsWith('/node/') && !path.startsWith('/ws/')) return
+    const body = JSON.stringify({ code: 'http_required', error: 'WebSockets are not supported; use HTTP' })
+    socket.end('HTTP/1.1 410 Gone\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ' + Buffer.byteLength(body) + '\r\n\r\n' + body)
+  }
+  server.on('upgrade', upgrade)
+  return () => server.off('upgrade', upgrade)
+}

+ 0 - 1577
src/server/chatCache.ts

@@ -1,1577 +0,0 @@
-import { ChatTranscriptStore } from './chatTranscriptStore.js'
-import { sessionForList } from './chatPresentation.js'
-import { isFinalChatResult } from './chatUnread.js'
-import { HttpError } from './errors.js'
-import { createHash, randomUUID } from 'node:crypto'
-import { chmodSync, createReadStream, existsSync, mkdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import type { UpstreamResponse } from './upstream.js'
-import type { UpstreamServiceSession } from './localAuth.js'
-
-export type ChatCacheMode = 'upstream-only' | 'shadow' | 'prefer-local'
-export type ChatCacheState = 'current' | 'stale' | 'syncing' | 'gap'
-export type ChatCacheSource = 'local' | 'upstream'
-
-interface StoredSnapshot {
-  response: UpstreamResponse
-  state: ChatCacheState
-}
-
-interface MessagePage {
-  response: UpstreamResponse
-  state: ChatCacheState
-}
-
-function object(value: unknown): Record<string, unknown> | undefined {
-  return value && typeof value === 'object' && !Array.isArray(value)
-    ? value as Record<string, unknown> : undefined
-}
-
-function parseResponse(response: UpstreamResponse): Record<string, unknown> | undefined {
-  if (response.status < 200 || response.status >= 300) return undefined
-  try { return object(JSON.parse(response.body.toString('utf8'))) } catch { return undefined }
-}
-
-function headerRecord(headers: Headers): string {
-  return JSON.stringify(Object.fromEntries([...headers.entries()].filter(([name]) => name.toLowerCase() !== 'set-cookie')))
-}
-
-function responseFromRow(row: Record<string, unknown>): UpstreamResponse {
-  return {
-    status: Number(row.status),
-    headers: new Headers(JSON.parse(String(row.headers)) as Record<string, string>),
-    body: Buffer.from(String(row.body), 'base64'),
-  }
-}
-
-function profileOf(value: Record<string, unknown>, fallback = ''): string {
-  return String(value.profile ?? value.profile_name ?? fallback).trim()
-}
-
-function sessionIDOf(value: Record<string, unknown>): string {
-  return String(value.id ?? value.session_id ?? value.sessionId ?? '').trim()
-}
-
-function sessionSource(value: Record<string, unknown>): string {
-  return String(value.source ?? '').trim()
-}
-
-function sessionTitle(value: Record<string, unknown>): string {
-  return String(value.title ?? '').trim()
-}
-
-// Hermes uses Unix seconds; local route registration uses milliseconds. Keep
-// the public summary in seconds so Web and iOS compare the same activity time.
-function timestampSeconds(value: unknown): number | undefined {
-  if (typeof value !== 'number' && typeof value !== 'string') return undefined
-  const numeric = Number(value)
-  const seconds = Number.isFinite(numeric)
-    ? numeric > 10_000_000_000 ? numeric / 1_000 : numeric
-    : typeof value === 'string' ? Date.parse(value) / 1_000 : NaN
-  return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined
-}
-
-function firstTimestamp(value: Record<string, unknown>, keys: string[]): number | undefined {
-  for (const key of keys) {
-    const timestamp = timestampSeconds(value[key])
-    if (timestamp !== undefined) return timestamp
-  }
-  return undefined
-}
-
-const START_TIME_KEYS = ['started_at', 'startedAt', 'session_started', 'created_at', 'createdAt']
-const ACTIVITY_TIME_KEYS = ['last_active', 'last_active_at', 'last_activity_at', 'lastActive', 'updated_at', 'updatedAt']
-
-function mergeSessionMetadata(previous: Record<string, unknown>, incoming: Record<string, unknown>): Record<string, unknown> {
-  const summary = { ...previous, ...incoming }
-  // A messages response can carry title/model metadata, but its envelope is
-  // not a replacement for the session detail.
-  delete summary.messages
-  delete summary.pagination
-  const started = firstTimestamp(incoming, START_TIME_KEYS) ?? firstTimestamp(previous, START_TIME_KEYS)
-  const activity = firstTimestamp(incoming, ACTIVITY_TIME_KEYS) ?? firstTimestamp(previous, ACTIVITY_TIME_KEYS)
-  if (started !== undefined) summary.started_at = started
-  if (activity !== undefined) summary.last_active = activity
-  return summary
-}
-
-function messageTimeBounds(messages: Record<string, unknown>[]): { first?: number; last?: number } {
-  let first: number | undefined
-  let last: number | undefined
-  for (const message of messages) {
-    const time = firstTimestamp(message, ['timestamp', 'created_at', 'createdAt'])
-    if (time === undefined) continue
-    first = Math.min(first ?? time, time)
-    last = Math.max(last ?? time, time)
-  }
-  return { first, last }
-}
-
-function isPlaceholderTitle(value: string): boolean {
-  return new Set([
-    '', '新对话', '新会话', '未命名对话', '未命名会话', 'new conversation', 'new session', 'untitled',
-  ]).has(value.trim().toLowerCase())
-}
-
-function messageID(value: Record<string, unknown>, fallback: string): string {
-  const id = String(value.id ?? value.row_id ?? value.message_id ?? value.messageId ?? '').trim()
-  return id || createHash('sha256').update(JSON.stringify(value) + fallback).digest('hex')
-}
-
-function bool(value: unknown): boolean {
-  return value === true || value === 1 || value === '1' || value === 'true'
-}
-
-const PATH_PATTERN = /(?:file:\/\/)?(\/(?:Users|private|var|tmp)\/[^\s<>'"`)\]}]+\.[A-Za-z0-9]{1,12})/g
-
-function referencedPaths(value: unknown, output = new Set<string>()): Set<string> {
-  if (typeof value === 'string') {
-    for (const match of value.matchAll(PATH_PATTERN)) output.add(match[1]!)
-  } else if (Array.isArray(value)) {
-    for (const child of value) referencedPaths(child, output)
-  } else {
-    const record = object(value)
-    if (record) for (const child of Object.values(record)) referencedPaths(child, output)
-  }
-  return output
-}
-
-export class ChatCacheStore {
-  private synchronizingHistory = false
-  readonly db: DatabaseSync
-  readonly assetsRoot: string
-  readonly transcripts: ChatTranscriptStore
-  private closed = false
-  get isClosed(): boolean { return this.closed }
-
-  constructor(home: string, legacySingleUserID?: string) {
-    mkdirSync(home, { recursive: true, mode: 0o700 })
-    const path = join(home, 'chat-cache.sqlite3')
-    this.db = new DatabaseSync(path)
-    chmodSync(path, 0o600)
-    this.assetsRoot = join(home, 'chat-cache-assets')
-    mkdirSync(this.assetsRoot, { recursive: true, mode: 0o700 })
-    this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
-      CREATE TABLE IF NOT EXISTS chat_sessions(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-        runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL, authoritative_title TEXT,
-        authoritative_title_at INTEGER NOT NULL DEFAULT 0,
-        owned_at INTEGER, ownership_evidence TEXT,
-        sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
-        last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
-        PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_messages(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-        message_id TEXT NOT NULL, position INTEGER NOT NULL, data TEXT NOT NULL,
-        content_hash TEXT NOT NULL, PRIMARY KEY(owner,profile,session_id,message_id));
-      CREATE INDEX IF NOT EXISTS chat_messages_position ON chat_messages(owner,profile,session_id,position);
-      CREATE TABLE IF NOT EXISTS chat_events(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-        event_seq INTEGER NOT NULL, event_type TEXT NOT NULL, payload TEXT NOT NULL,
-        received_at INTEGER NOT NULL, PRIMARY KEY(owner,profile,session_id,event_seq,event_type));
-      CREATE TABLE IF NOT EXISTS chat_attachments(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-        source_path TEXT NOT NULL, sha256 TEXT, mime_type TEXT, size INTEGER,
-        local_path TEXT, state TEXT NOT NULL DEFAULT 'pending', updated_at INTEGER NOT NULL,
-        PRIMARY KEY(owner,profile,session_id,source_path));
-      CREATE INDEX IF NOT EXISTS chat_attachments_source ON chat_attachments(owner,source_path);
-      CREATE TABLE IF NOT EXISTS chat_sync_cursors(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, generation TEXT,
-        event_cursor INTEGER NOT NULL DEFAULT 0, sync_state TEXT NOT NULL DEFAULT 'stale',
-        last_synced_at INTEGER NOT NULL, PRIMARY KEY(owner,profile));
-      CREATE TABLE IF NOT EXISTS chat_snapshots(
-        owner TEXT NOT NULL, cache_key TEXT NOT NULL, kind TEXT NOT NULL,
-        profile TEXT NOT NULL, session_id TEXT, status INTEGER NOT NULL,
-        headers TEXT NOT NULL, body TEXT NOT NULL, sync_state TEXT NOT NULL,
-        saved_at INTEGER NOT NULL, PRIMARY KEY(owner,cache_key));
-      CREATE TABLE IF NOT EXISTS chat_meta(
-        key TEXT PRIMARY KEY, value TEXT NOT NULL);`)
-    this.db.exec(`CREATE TABLE IF NOT EXISTS chat_local_state(
-      owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-      pinned INTEGER, read_count INTEGER NOT NULL DEFAULT 0,
-      assistant_id TEXT, PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_session_aliases(owner TEXT NOT NULL,profile TEXT NOT NULL,alias_id TEXT NOT NULL,session_id TEXT NOT NULL,PRIMARY KEY(owner,profile,alias_id));
-      CREATE TABLE IF NOT EXISTS chat_recovery_jobs(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,force INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_event_receipts(
-      owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL, event_id TEXT NOT NULL,
-      PRIMARY KEY(owner,profile,session_id,event_id));
-      CREATE TABLE IF NOT EXISTS chat_message_identities(
-        owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
-        message_id TEXT NOT NULL, client_message_id TEXT NOT NULL,
-        PRIMARY KEY(owner,profile,session_id,message_id),
-        UNIQUE(owner,profile,session_id,client_message_id));`)
-    const localColumns=this.db.prepare('PRAGMA table_info(chat_local_state)').all() as {name:string}[]
-    for(const [name,type] of [['title','TEXT'],['archived','INTEGER'],['read_initialized','INTEGER NOT NULL DEFAULT 0'],['final_read_count','INTEGER']]){
-      if(!localColumns.some(c=>c.name===name))this.db.exec(`ALTER TABLE chat_local_state ADD COLUMN ${name} ${type}`)
-    }
-    const sessionColumns = this.db.prepare('PRAGMA table_info(chat_sessions)').all() as Array<{ name: string }>
-    this.db.exec('BEGIN IMMEDIATE')
-    try {
-      if (!sessionColumns.some(column => column.name === 'sync_revision')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN sync_revision INTEGER NOT NULL DEFAULT 0')
-      }
-      if (!sessionColumns.some(column => column.name === 'message_total')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN message_total INTEGER')
-      }
-      if (!sessionColumns.some(column => column.name === 'metadata_complete')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN metadata_complete INTEGER NOT NULL DEFAULT 0')
-        this.db.exec("UPDATE chat_sessions SET metadata_complete=1 WHERE json_valid(data) AND (json_type(data,'$.message_count') IS NOT NULL OR json_type(data,'$.model') IS NOT NULL)")
-      }
-      if (!sessionColumns.some(column => column.name === 'authoritative_title')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title TEXT')
-      }
-      if (!sessionColumns.some(column => column.name === 'authoritative_title_at')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title_at INTEGER NOT NULL DEFAULT 0')
-      }
-      if (!sessionColumns.some(column => column.name === 'owned_at')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN owned_at INTEGER')
-      }
-      if (!sessionColumns.some(column => column.name === 'ownership_evidence')) {
-        this.db.exec('ALTER TABLE chat_sessions ADD COLUMN ownership_evidence TEXT')
-      }
-      this.db.exec(`CREATE INDEX IF NOT EXISTS chat_sessions_owned
-        ON chat_sessions(owner,profile,owned_at,last_synced_at)`)
-      const ownershipMigration = this.db.prepare(
-        "SELECT value FROM chat_meta WHERE key='ownership-registry-v1'",
-      ).get() as { value?: string } | undefined
-      if (!ownershipMigration) {
-        // A single cached owner is trusted only when the persisted local user
-        // database independently confirms the same sole identity.
-        const legacyOwners = this.db.prepare(
-          'SELECT DISTINCT owner FROM chat_sessions ORDER BY owner',
-        ).all() as Array<{ owner: string }>
-        if (legacyOwners.length === 1 && legacyOwners[0]!.owner === legacySingleUserID) {
-          this.db.exec(`UPDATE chat_sessions SET
-            owned_at=COALESCE(owned_at,last_synced_at),
-            ownership_evidence=COALESCE(ownership_evidence,'legacy-single-user')`)
-        }
-      }
-      // Recover interrupted/new-schema writes only from explicit command proof.
-      this.db.exec(`UPDATE chat_sessions SET
-        owned_at=COALESCE(owned_at,(
-          SELECT MIN(chat_events.received_at) FROM chat_events
-          WHERE chat_events.owner=chat_sessions.owner
-            AND chat_events.profile=chat_sessions.profile
-            AND chat_events.session_id=chat_sessions.session_id
-            AND chat_events.event_type IN ('command:session.create','command:session.branch')
-        )),
-        ownership_evidence=COALESCE(ownership_evidence,'command-migration')
-        WHERE EXISTS (
-          SELECT 1 FROM chat_events
-          WHERE chat_events.owner=chat_sessions.owner
-            AND chat_events.profile=chat_sessions.profile
-            AND chat_events.session_id=chat_sessions.session_id
-            AND chat_events.event_type IN ('command:session.create','command:session.branch')
-        )`)
-      const legacyTitles = this.db.prepare(`SELECT owner,profile,session_id,data FROM chat_sessions
-        WHERE authoritative_title IS NULL`).all() as Array<{
-          owner: string; profile: string; session_id: string; data: string
-        }>
-      const backfillTitle = this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?
-        WHERE owner=? AND profile=? AND session_id=? AND authoritative_title IS NULL`)
-      for (const row of legacyTitles) {
-        let summary: Record<string, unknown> = {}
-        try { summary = object(JSON.parse(row.data)) ?? {} } catch { continue }
-        const title = sessionTitle(summary)
-        if (!isPlaceholderTitle(title)) backfillTitle.run(title, row.owner, row.profile, row.session_id)
-      }
-      if (!this.db.prepare("SELECT 1 FROM chat_meta WHERE key='session-activity-v1'").get()) {
-        const rows = this.db.prepare(`SELECT owner,profile,session_id,source,data,owned_at,message_total
-          FROM chat_sessions WHERE owned_at IS NOT NULL`).all() as Array<{
-            owner: string; profile: string; session_id: string; source: string; data: string
-            owned_at: number; message_total: number | null
-          }>
-        const update = this.db.prepare(`UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?`)
-        for (const row of rows) {
-          let stored: Record<string, unknown>
-          try { stored = object(JSON.parse(row.data)) ?? {} } catch { continue }
-          const summary = mergeSessionMetadata({}, stored)
-          if (Array.isArray(stored.messages) || !firstTimestamp(summary, START_TIME_KEYS)
-            || !firstTimestamp(summary, ACTIVITY_TIME_KEYS)) {
-            const messages = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`)
-              .all(row.owner, row.profile, row.session_id) as Array<{ data: string }>
-            const bounds = messageTimeBounds(messages.flatMap(message => {
-              try { return [object(JSON.parse(message.data)) ?? {}] } catch { return [] }
-            }))
-            summary.started_at = firstTimestamp(summary, START_TIME_KEYS) ?? bounds.first ?? timestampSeconds(row.owned_at)
-            summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0,
-              bounds.last ?? 0) || summary.started_at
-            if (row.message_total !== null) summary.message_count = row.message_total
-          }
-          summary.id = row.session_id
-          summary.profile = row.profile
-          summary.source = sessionSource(summary) || row.source
-          update.run(JSON.stringify(summary), row.owner, row.profile, row.session_id)
-        }
-        this.db.prepare("INSERT INTO chat_meta(key,value) VALUES('session-activity-v1','complete')").run()
-      }
-      // List bodies written before ownership became an explicit projection do
-      // not carry `owned` and may have been filtered by `source`. Rebuild them on
-      // first use after every restart instead of serving a semantically old page.
-      this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE kind='list'").run()
-      this.db.prepare(`INSERT INTO chat_meta(key,value) VALUES('ownership-registry-v1','complete')
-        ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run()
-    this.db.prepare(`INSERT OR IGNORE INTO chat_local_state(owner,profile,session_id)
-      SELECT owner,profile,session_id FROM chat_sessions WHERE owned_at IS NOT NULL`).run()
-      this.db.exec('COMMIT')
-    } catch (error) {
-      this.db.exec('ROLLBACK')
-      throw error
-    }
-    this.transcripts = new ChatTranscriptStore(this.db,(owner,profile,id,rows)=>this.userMessageIdentities(owner,profile,id,rows,false))
-  }
-
-  close(): void { this.closed = true; this.transcripts.close(); this.db.close() }
-
-  stats(): Record<string, number> {
-    const count = (table: string) => Number((this.db.prepare(`SELECT COUNT(*) count FROM ${table}`).get() as { count: number }).count)
-    const bytes = Number((this.db.prepare(`SELECT COALESCE(SUM(size),0) bytes FROM chat_attachments WHERE state='cached'`).get() as { bytes: number }).bytes)
-    return {
-      sessions: Number((this.db.prepare(`SELECT COUNT(*) count FROM chat_sessions
-        WHERE owned_at IS NOT NULL`).get() as { count: number }).count),
-      messages: count('chat_messages'),
-      events: count('chat_events'),
-      attachments: count('chat_attachments'),
-      attachmentBytes: bytes,
-    }
-  }
-
-  snapshot(owner: string, key: string): StoredSnapshot | undefined {
-    const row = this.db.prepare('SELECT status,headers,body,sync_state FROM chat_snapshots WHERE owner=? AND cache_key=?')
-      .get(owner, key) as Record<string, unknown> | undefined
-    return row ? { response: responseFromRow(row), state: String(row.sync_state) as ChatCacheState } : undefined
-  }
-
-  localList(owner: string, profile: string, page: { offset?: number; limit?: number; archived?: string }): UpstreamResponse {
-    const offset = Math.max(0, Math.trunc(page.offset ?? 0)), limit = Math.max(1, Math.min(200, Math.trunc(page.limit ?? 100)))
-    const where = `s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
-      AND s.source NOT IN ('cron','ios_group','yaoyao_workspace')
-      AND (?='include' OR COALESCE(l.archived,json_extract(s.data,'$.archived'),json_extract(s.data,'$.is_archived'),0)=CASE WHEN ?='only' THEN 1 ELSE 0 END)`
-    const args = [owner, profile, profile, page.archived ?? 'exclude', page.archived ?? 'exclude']
-    const total = Number((this.db.prepare(`SELECT count(*) n FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}`).get(...args) as {n:number}).n)
-    const rows = this.db.prepare(`SELECT s.profile,s.session_id,s.data,s.sync_state,s.complete,l.title local_title,
-      COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0) pin
-      FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}
-      ORDER BY pin DESC, COALESCE(json_extract(s.data,'$.last_active'),0) DESC, s.session_id
-      LIMIT ? OFFSET ?`).all(...args, limit, offset) as Array<Record<string,any>>
-    const unread = new Map(this.unread(owner, profile).sessions.map(row => [JSON.stringify([row.profile, row.session_id]), row.final_unread_count]))
-    return {status:200,headers:new Headers({'content-type':'application/json'}),body:Buffer.from(JSON.stringify({
-      sessions:rows.map(r=>({...sessionForList(JSON.parse(r.data)),...(r.local_title!=null?{title:r.local_title}:{}),id:r.session_id,profile:r.profile,owned:true,pinned:!!r.pin,
-        final_unread_count:unread.get(JSON.stringify([r.profile,r.session_id]))??0,
-        sync_state:r.sync_state,history_complete:!!r.complete})), total,offset,limit,
-      sync_state:this.needsListMetadata(owner,profile)?'syncing':'current'
-    }))}
-  }
-
-  missingSessions(owner: string, profile: string): Array<{profile:string;session_id:string}> {
-    return (this.db.prepare(`SELECT profile,session_id FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
-      AND (?='' OR profile=?) AND (metadata_complete=0 OR complete=0) LIMIT 100`)
-      .all(owner,profile,profile) as {profile:string;session_id:string}[])
-  }
-
-  pins(owner: string, profile: string): string[] {
-    return (this.db.prepare(`SELECT s.session_id FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
-      WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
-      AND COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0)=1 ORDER BY s.last_synced_at DESC`)
-      .all(owner,profile,profile) as {session_id:string}[]).map(r=>r.session_id)
-  }
-
-  unread(owner: string, profile: string) {
-    const sessions = (this.db.prepare(`SELECT s.profile,s.session_id,COALESCE(s.message_total,0) message_count,
-      CASE WHEN COALESCE(l.read_initialized,0)=1 THEN COALESCE(l.final_read_count,l.read_count) ELSE COALESCE(s.message_total,0) END final_read_count,
-      CASE WHEN COALESCE(l.read_initialized,0)=1 THEN l.read_count ELSE COALESCE(s.message_total,0) END read_message_count FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
-      WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)`).all(owner,profile,profile) as any[])
-      .map(({final_read_count,...r})=>{
-        this.transcripts.seed(owner,r.profile,r.session_id)
-        r.message_count=this.transcripts.total(owner,r.profile,r.session_id)
-        return {...r,updated_at:Date.now(),unread_count:Math.max(0,r.message_count-r.read_message_count),
-          final_unread_count:this.transcripts.unread(owner,r.profile,r.session_id)}
-      })
-    return {profile,supported:true,total_unread:sessions.reduce((n,r)=>n+r.unread_count,0),sessions}
-  }
-
-  markRead(owner: string, profile: string, id: string, count?: number) {
-    id=this.canonicalSessionID(owner,profile,id)
-    this.requireOwned(owner,profile,id)
-    this.transcripts.seed(owner,profile,id)
-    const total = this.transcripts.total(owner,profile,id)
-    const read = Math.max(0,Math.min(total, count ?? total))
-    // Reading a streaming placeholder must not consume its future final answer.
-    // Keep the original cursor untouched for existing consumers.
-    const pending = this.db.prepare(`SELECT MIN(position) position FROM chat_messages
-      WHERE owner=? AND profile=? AND session_id=? AND position<?
-      AND message_id=(SELECT assistant_id FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?)
-      AND json_extract(data,'$.role')='assistant' AND json_extract(data,'$.status')='streaming'`)
-      .get(owner,profile,id,read,owner,profile,id) as {position:number|null}
-    const finalRead = pending.position ?? read
-    this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_count,final_read_count,read_initialized) VALUES(?,?,?,?,?,1)
-      ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_count=MAX(read_count,excluded.read_count),
-      final_read_count=MAX(COALESCE(final_read_count,read_count),excluded.final_read_count),read_initialized=1`).run(owner,profile,id,read,finalRead)
-    this.transcripts.seed(owner,profile,id)
-    this.transcripts.markRead(owner,profile,id,count??Infinity)
-    return this.unread(owner,profile).sessions.find(r=>r.session_id===id)!
-  }
-
-  requireOwned(owner: string, profile: string, id: string): void {
-    if (!this.ownsSession(owner,profile,id)) throw new HttpError(404,'会话不存在','session_not_found')
-  }
-
-  patchLocal(owner: string, profile: string, id: string, patch: Record<string,unknown>): void {
-    id=this.canonicalSessionID(owner,profile,id)
-    this.requireOwned(owner,profile,id)
-    this.db.exec('SAVEPOINT local_chat_patch')
-    try {
-      if (typeof patch.pinned==='boolean') this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,pinned) VALUES(?,?,?,?)
-        ON CONFLICT(owner,profile,session_id) DO UPDATE SET pinned=excluded.pinned`).run(owner,profile,id,patch.pinned?1:0)
-      const row = this.localDetail(owner,profile,id)!
-      const data = {...JSON.parse(row.response.body.toString()),...patch}
-      this.db.prepare("UPDATE chat_sessions SET data=?,sync_state=CASE WHEN sync_state='gap' THEN sync_state WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(JSON.stringify(data),owner,profile,id)
-      for(const key of ['title','archived'] as const)if(patch[key]!==undefined){
-        const value=key==='archived'?(patch[key]?1:0):String(patch[key])
-        this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,${key}) VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET ${key}=excluded.${key}`).run(owner,profile,id,value)
-      }
-      if(typeof patch.title==='string') this.recordAuthoritativeTitle(owner,profile,id,patch.title)
-      this.db.prepare("UPDATE chat_sessions SET sync_state=CASE WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id)
-      this.transcripts.sessionChanged(owner,profile,id,{eventType:'session.info',payload:data})
-      this.db.exec('RELEASE local_chat_patch')
-    } catch(e) {this.db.exec('ROLLBACK TO local_chat_patch; RELEASE local_chat_patch');throw e}
-  }
-
-  projectedMessageID(owner:string,profile:string,id:string):string|undefined {
-    return this.transcripts.head(owner,profile,id).current
-  }
-
-  private updateTranscriptSummary(owner:string,profile:string,id:string):void {
-    const total=this.transcripts.total(owner,profile,id)
-    const lastRow=this.db.prepare('SELECT data FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0 ORDER BY seq DESC LIMIT 1').get(owner,profile,id)
-    const last=lastRow?JSON.parse(String(lastRow.data)):undefined
-    const row=this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id)
-    if(!row)return
-    const data=JSON.parse(String(row.data))
-    data.message_count=total
-    if(last){data.last_active=last.timestamp;if(typeof last.content==='string'&&last.content.trim())data.preview=last.content.slice(0,160)}
-    this.db.prepare("UPDATE chat_sessions SET data=?,sync_state=CASE WHEN sync_state='gap' THEN sync_state WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(JSON.stringify(data),owner,profile,id)
-    const currentID=this.transcripts.head(owner,profile,id).current
-    const current=currentID?this.transcripts.message(owner,profile,id,currentID):undefined
-    for(const message of [last,current].filter(Boolean))for(const path of referencedPaths(message!))this.db.prepare(`INSERT OR IGNORE INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at) VALUES(?,?,?,?,'pending',?)`).run(owner,profile,id,path,Date.now())
-  }
-
-  needsListMetadata(owner: string, profile: string): boolean {
-    return Boolean(this.db.prepare(`SELECT 1 FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
-      AND (?='' OR profile=?) AND metadata_complete=0 LIMIT 1`).get(owner, profile, profile))
-  }
-
-  localDetail(owner: string, profile: string, sessionID: string): StoredSnapshot | undefined {
-    const row = this.db.prepare(`SELECT data,sync_state FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
-      .get(owner, profile, sessionID) as { data: string; sync_state: ChatCacheState } | undefined
-    if (!row) return undefined
-    const local=this.db.prepare('SELECT title,archived,pinned FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionID) as any
-    return { response: { status: 200, headers: new Headers({ 'content-type': 'application/json' }),
-      body: Buffer.from(JSON.stringify({...JSON.parse(row.data),...(local?.title!=null?{title:local.title}:{}),...(local?.archived!=null?{archived:!!local.archived}:{}),owned:true,pinned:local?.pinned!=null?!!local.pinned:bool(JSON.parse(row.data).pinned),sync_state:row.sync_state})) }, state: row.sync_state }
-  }
-
-  revision(owner: string, profile: string, sessionID: string): number {
-    return Number((this.db.prepare('SELECT sync_revision FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
-      .get(owner, profile, sessionID) as { sync_revision?: number } | undefined)?.sync_revision ?? 0)
-  }
-
-  hasMessage(owner: string, profile: string, sessionID: string, message: Record<string, unknown>, position: number): boolean {
-    const id = messageID(message, String(position))
-    const row = this.db.prepare('SELECT position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
-      .get(owner, profile, sessionID, id) as { position: number } | undefined
-    if (row && row.position !== position) throw new Error('Stored history changed; explicit refresh is required')
-    return Boolean(row)
-  }
-
-  putSnapshot(owner: string, key: string, kind: string, profile: string, sessionID: string | undefined,
-    response: UpstreamResponse, ownedList = false, requestStartedAt = Date.now(),
-    metadataResponse: UpstreamResponse = response): boolean {
-    const payload = parseResponse(response)
-    if (!payload) return false
-    if (kind === 'list' && !ownedList) return false
-    const isOwnedChat = ownedList || this.payloadBelongsToOwnedChat(owner, profile, sessionID, payload)
-    if (!isOwnedChat) return false
-    const now = Date.now()
-    this.db.exec('SAVEPOINT chat_snapshot')
-    try {
-      // Hydrate all registered sessions from the unsliced upstream list, while
-      // persisting only the owner-filtered page as the public response snapshot.
-      this.ingestPayload(owner, profile, sessionID, parseResponse(metadataResponse) ?? payload, now, kind, requestStartedAt)
-      if(kind==='messages'&&sessionID&&!this.synchronizingHistory&&!this.transcripts.head(owner,profile,sessionID).running){this.transcripts.reconcile(owner,profile,sessionID);this.updateTranscriptSummary(owner,profile,sessionID)}
-      this.db.prepare(`INSERT INTO chat_snapshots(owner,cache_key,kind,profile,session_id,status,headers,body,sync_state,saved_at)
-        VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,cache_key) DO UPDATE SET status=excluded.status,headers=excluded.headers,
-        body=excluded.body,sync_state='current',saved_at=excluded.saved_at`)
-        .run(owner, key, kind, profile, sessionID ?? null, response.status, headerRecord(response.headers),
-          response.body.toString('base64'), 'current', now)
-      this.db.exec('RELEASE chat_snapshot')
-      return true
-    } catch (error) {
-      this.db.exec('ROLLBACK TO chat_snapshot; RELEASE chat_snapshot')
-      throw error
-    }
-  }
-
-  applySync(owner: string, profile: string, sessionID: string, revision: number,
-    pages: Array<{ key: string; kind: string; response: UpstreamResponse; startedAt: number }>, force: boolean): boolean {
-    if (this.revision(owner, profile, sessionID) !== revision || this.transcripts.head(owner,profile,sessionID).running) return false
-    this.db.exec('SAVEPOINT history_sync')
-    this.synchronizingHistory=true
-    try {
-      this.transcripts.archive([owner,profile,sessionID])
-      if (force) this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=?').run(owner, profile, sessionID)
-      // Recovery promotes locally generated stream identities to upstream row IDs.
-      // Remove only replaced rows inside the verified window; keep older coverage.
-      if(!force){
-        const windows=pages.filter(p=>p.kind==='messages').map(p=>parseResponse(p.response)).filter(Boolean) as Record<string,any>[]
-        for(const window of windows){
-          const pagination=window.pagination??{},messages=window.messages as Record<string,any>[]
-          if(!Array.isArray(messages)||!Number.isSafeInteger(pagination.total))continue
-          const identified = this.userMessageIdentities(owner, profile, sessionID, messages, false)
-          const end=pagination.total-Number(pagination.offset??0),start=end-messages.length
-          const ids=new Set(messages.map((m,index)=>messageID(m,String(start+index))))
-          const existing=this.db.prepare('SELECT message_id,data,position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND position>=? AND position<?').all(owner,profile,sessionID,start,end) as {message_id:string;data:string;position:number}[]
-          for(const row of existing){
-            if(ids.has(row.message_id))continue
-            const value=JSON.parse(row.data)
-            const incoming=messages[row.position-start]
-            if(incoming&&value.role==='assistant'&&incoming.role==='assistant'&&/^event:/.test(row.message_id)
-              &&typeof value.content==='string'&&value.content.length>0&&value.content===incoming.content)
-              this.transcripts.promote(owner,profile,sessionID,row.message_id,messageID(incoming,String(row.position)))
-            if(value.role==='user'&&value.status==='pending'&&!identified.some(m=>m.role==='user'
-              && value.client_message_id && m.client_message_id===value.client_message_id))
-              throw new Error('Unconfirmed submission must be reconciled before history replacement')
-            this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(owner,profile,sessionID,row.message_id)
-          }
-        }
-      }
-      this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND profile=? AND session_id=? AND kind='messages'").run(owner, profile, sessionID)
-      for (const page of pages) this.putSnapshot(owner, page.key, page.kind, profile, sessionID, page.response, false, page.startedAt)
-      // Resolve legacy identities only after all pages are stored. Resolving
-      // pages individually could consume a send before seeing an ambiguous row.
-      const coverage = this.db.prepare('SELECT complete,message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
-        .get(owner, profile, sessionID) as {complete: number} | undefined
-      if (coverage?.complete) this.userMessageIdentities(owner, profile, sessionID, pages.flatMap(page => {
-        const messages = page.kind === 'messages' ? parseResponse(page.response)?.messages : undefined
-        return Array.isArray(messages) ? messages.flatMap(value => object(value) ? [object(value)!] : []) : []
-      }))
-      const latest=this.db.prepare("SELECT message_id FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND json_extract(data,'$.role')='assistant' ORDER BY position DESC LIMIT 1").get(owner,profile,sessionID) as {message_id:string}|undefined
-      if(latest)this.db.prepare('UPDATE chat_local_state SET assistant_id=? WHERE owner=? AND profile=? AND session_id=?').run(latest.message_id,owner,profile,sessionID)
-      this.transcripts.reconcile(owner,profile,sessionID)
-      this.updateTranscriptSummary(owner,profile,sessionID)
-      this.transcripts.sessionChanged(owner,profile,sessionID,{eventType:'history.synced'})
-      this.synchronizingHistory=false
-      this.db.exec('RELEASE history_sync')
-      return true
-    } catch (error) {
-      this.synchronizingHistory=false
-      this.db.exec('ROLLBACK TO history_sync; RELEASE history_sync')
-      throw error
-    }
-  }
-
-  private userMessageIdentities(owner: string, profile: string, sessionID: string,
-    messages: Record<string, unknown>[], recoverLegacy = true): Record<string, unknown>[] {
-    const scope = [owner, profile, sessionID]
-    const bindings = this.db.prepare(`SELECT message_id,client_message_id FROM chat_message_identities
-      WHERE owner=? AND profile=? AND session_id=?`).all(...scope) as {message_id: string; client_message_id: string}[]
-    const byServer = new Map(bindings.map(row => [row.message_id, row.client_message_id]))
-    const byClient = new Map(bindings.map(row => [row.client_message_id, row.message_id]))
-    const serverID = (message: Record<string, unknown>) => {
-      const id = String(message.id ?? message.message_id ?? '').trim()
-      return message.role === 'user' && id && !id.startsWith('user:') ? id : ''
-    }
-    const bind = (id: string, client: string) => {
-      if (!id || !client || byServer.has(id) || byClient.has(client)) return
-      this.db.prepare('INSERT INTO chat_message_identities VALUES(?,?,?,?,?)').run(...scope, id, client)
-      byServer.set(id, client)
-      byClient.set(client, id)
-    }
-    for (const message of messages) {
-      bind(serverID(message), String(message.client_message_id ?? message.clientMessageId ?? ''))
-    }
-    if (recoverLegacy && messages.some(message => serverID(message) && !byServer.has(serverID(message)))) {
-      // Older gateways omit client IDs. Recover only a mutually unique match
-      // inside a confirmed, non-queued submission's time window. Never dedupe
-      // by text or position alone, and include other pages when testing uniqueness.
-      const events = this.db.prepare(`SELECT event_type,payload,received_at FROM chat_events
-        WHERE owner=? AND profile=? AND session_id=?
-        AND event_type IN ('command:prompt.submit','command:session.steer','command.confirmed','command.rejected','message.start')
-        ORDER BY received_at,event_seq`)
-        .all(...scope) as {event_type: string; payload: string; received_at: number}[]
-      const confirmed = new Map<string, number>(), rejected = new Set<string>()
-      for (const event of events) {
-        const payload = JSON.parse(event.payload)
-        if (event.event_type === 'command.confirmed' && payload.status !== 'queued') confirmed.set(payload.delivery_id, event.received_at)
-        if (event.event_type === 'command.rejected') rejected.add(payload.delivery_id)
-      }
-      const stored = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
-        AND json_extract(data,'$.role')='user'`).all(...scope) as {data: string}[]
-      const candidates = new Map<string, Record<string, unknown>>()
-      for (const message of [...stored.map(row => JSON.parse(row.data)), ...messages]) {
-        const id = serverID(message)
-        if (id && !byServer.has(id)) candidates.set(id, message)
-      }
-      const matches = new Map<string, string[]>(), claims = new Map<string, number>()
-      const submissions = events.filter(event => event.event_type === 'command:prompt.submit' || event.event_type === 'command:session.steer')
-      for (const [index, event] of submissions.entries()) {
-        if (event.event_type !== 'command:prompt.submit') continue
-        const payload = JSON.parse(event.payload), delivery = String(payload._delivery_id ?? '')
-        const client = delivery.replace(/^(web|ios):prompt:/, '')
-        const acceptedAt = confirmed.get(delivery)
-        if (!client || byClient.has(client) || payload.queued || rejected.has(delivery) || acceptedAt === undefined) continue
-        const start = event.received_at / 1000
-        const nextStart = submissions[index + 1]?.received_at ?? Infinity
-        const runStart = events.find(candidate => candidate.event_type === 'message.start'
-          && candidate.received_at >= event.received_at && candidate.received_at < nextStart)
-        // The receipt can precede the gateway's DB insert by a few milliseconds.
-        // A deferred agent build may start later; the next submission always
-        // closes this window, including when users rapidly repeat the same text.
-        const end = Math.min((runStart?.received_at ?? acceptedAt) + 1000, event.received_at + 120_000) / 1000
-        const ids = [...candidates].flatMap(([id, message]) => {
-          const time = firstTimestamp(message, ['timestamp', 'created_at', 'createdAt'])
-          return time !== undefined && time >= start && time <= end && time < nextStart / 1000
-            && message.content === (payload.text ?? payload.input ?? '') ? [id] : []
-        })
-        matches.set(client, ids)
-        for (const id of ids) claims.set(id, (claims.get(id) ?? 0) + 1)
-      }
-      for (const [client, ids] of matches) {
-        if (ids.length === 1 && claims.get(ids[0]!) === 1) bind(ids[0]!, client)
-      }
-    }
-    return messages.map(message => {
-      const client = byServer.get(serverID(message))
-      return client ? { ...message, client_message_id: client } : message
-    })
-  }
-
-  messagePage(owner: string, profile: string, sessionID: string, offset: number, limit: number): MessagePage | undefined {
-    if(!this.ownsSession(owner,profile,sessionID))return this.sourceMessagePage(owner,profile,sessionID,offset,limit)
-    this.transcripts.seed(owner,profile,sessionID)
-    const known=this.db.prepare('SELECT complete,message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionID)
-    if(!known?.complete&&!this.transcripts.total(owner,profile,sessionID))return undefined
-    const all=this.transcripts.all(owner,profile,sessionID),end=Math.max(0,all.length-offset),start=Math.max(0,end-limit)
-    const total=known?.complete?all.length:Math.max(all.length,Number(known?.message_total??0))
-    if(!known?.complete&&offset>=all.length&&offset<total)return undefined
-    const detail=this.localDetail(owner,profile,sessionID)!
-    return {state:detail.state,response:{status:200,headers:new Headers({'content-type':'application/json'}),body:Buffer.from(JSON.stringify({
-      session_id:sessionID,session:JSON.parse(detail.response.body.toString()),messages:all.slice(start,end),
-      pagination:{total,returned:end-start,offset,limit,has_more:start>0||total>all.length}
-    }))}}
-  }
-
-  sourceMessagePage(owner: string, profile: string, sessionID: string, offset: number, limit: number): MessagePage | undefined {
-    const session = this.db.prepare(`SELECT data,sync_state,complete,message_total FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as Record<string, unknown> | undefined
-    if (!session) return undefined
-    const totalRow = this.db.prepare('SELECT COUNT(*) count, MAX(position)+1 extent FROM chat_messages WHERE owner=? AND profile=? AND session_id=?')
-      .get(owner, profile, sessionID) as { count: number; extent: number | null }
-    if (session.message_total == null && !bool(session.complete)) return undefined
-    const total = Number(session.message_total ?? totalRow.extent ?? 0)
-    const end = Math.max(0, total - offset)
-    const start = Math.max(0, end - limit)
-    const rows = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
-      AND position>=? AND position<? ORDER BY position`).all(owner, profile, sessionID, start, end) as Array<{ data: string }>
-    if (rows.length !== end - start) return undefined // Fetch only an actually missing page.
-    const messages = this.userMessageIdentities(owner, profile, sessionID, rows.map(row => JSON.parse(row.data)), bool(session.complete))
-    const body = Buffer.from(JSON.stringify({
-      session_id: sessionID,
-      session: JSON.parse(this.localDetail(owner,profile,sessionID)!.response.body.toString()),
-      messages,
-      pagination: {
-        total,
-        returned: messages.length,
-        offset,
-        limit,
-        has_more: start > 0,
-      },
-    }))
-    return {
-      response: { status: 200, headers: new Headers({ 'content-type': 'application/json; charset=utf-8' }), body },
-      state: String(session.sync_state) as ChatCacheState,
-    }
-  }
-
-  recordEvent(owner: string, profile: string, sessionID: string, frame: Record<string, unknown>): boolean {
-    const rawSeq = Number(frame.seq ?? frame.sequence ?? 0)
-    const type = String(frame.type ?? 'unknown')
-    const payload = JSON.stringify(frame.payload ?? {})
-    const eventID = String(frame.delivery_id ?? (rawSeq > 0 ? `${frame.epoch ?? ''}:${rawSeq}:${type}` : randomUUID()))
-    const seq = Number.parseInt(createHash('sha256').update(eventID).digest('hex').slice(0,12),16)
-    const now = Date.now()
-    this.db.exec('SAVEPOINT live_event')
-    try {
-    const receipt=this.db.prepare('INSERT OR IGNORE INTO chat_event_receipts VALUES(?,?,?,?)').run(owner,profile,sessionID,eventID)
-    if(!receipt.changes){this.db.exec('RELEASE live_event');return false}
-    const previous = this.db.prepare(`SELECT last_event_seq FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as { last_event_seq?: number } | undefined
-    const lastSeen = Number(previous?.last_event_seq ?? 0)
-    const inserted = this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
-      VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, Number.isSafeInteger(seq) ? seq : 0, type, payload, now)
-    if (!inserted.changes) {this.db.exec('RELEASE live_event');return false}
-    const state: ChatCacheState = type === 'gateway.reset' || type.includes('reset')
-      || (!frame.epoch && rawSeq > 0 && lastSeen > 0 && rawSeq > lastSeen + 1) ? 'gap' : 'stale'
-    const metadataOnly = ['session.info', 'session.title', 'session.title.updated', 'session.usage', 'gateway.ready'].includes(type) && state !== 'gap'
-    this.db.prepare(`UPDATE chat_sessions SET sync_state=CASE WHEN ? THEN sync_state WHEN sync_state='gap' THEN 'gap' ELSE ? END,
-      sync_revision=sync_revision+?,last_event_seq=MAX(last_event_seq,?),last_synced_at=?
-      WHERE owner=? AND profile=? AND session_id=?`).run(metadataOnly ? 1 : 0, state, metadataOnly ? 0 : 1, rawSeq > 0 ? rawSeq : lastSeen, now, owner, profile, sessionID)
-    if (type === 'session.info') {
-      const payload = object(frame.payload) ?? {}
-      const info = object(payload.info) ?? payload
-      const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
-        .get(owner, profile, sessionID) as { data: string } | undefined
-      if (row) {
-        const summary = object(JSON.parse(row.data)) ?? {}
-        for (const field of ['model', 'provider', 'fast']) if (info[field] !== undefined) summary[field] = info[field]
-        this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
-          .run(JSON.stringify(summary), owner, profile, sessionID)
-      }
-    }
-    if (type === 'session.title' || type === 'session.title.updated') {
-      const title = String(object(frame.payload)?.title ?? frame.title ?? '').trim()
-      if (title) this.updateOwnedSessionTitle(owner, profile, sessionID, title, now)
-    }
-    this.db.prepare(`UPDATE chat_snapshots SET sync_state=? WHERE owner=? AND (session_id=? OR kind='list')
-      AND (?=0 OR kind<>'messages')`).run(state, owner, sessionID, metadataOnly ? 1 : 0)
-    this.db.prepare(`INSERT INTO chat_sync_cursors(owner,profile,event_cursor,sync_state,last_synced_at)
-      VALUES(?,?,?,?,?) ON CONFLICT(owner,profile) DO UPDATE SET event_cursor=MAX(event_cursor,excluded.event_cursor),
-      sync_state=excluded.sync_state,last_synced_at=excluded.last_synced_at`)
-      .run(owner, profile, rawSeq > 0 ? rawSeq : lastSeen, state, now)
-    if(this.ownsSession(owner,profile,sessionID)){
-      this.transcripts.recordSource([owner,profile,sessionID],frame)
-      this.transcripts.reduce(owner,profile,sessionID,type,object(frame.payload)??{})
-      this.updateTranscriptSummary(owner,profile,sessionID)
-    }
-    this.db.exec('RELEASE live_event')
-    return true
-    }catch(e){this.db.exec('ROLLBACK TO live_event; RELEASE live_event');throw e}
-  }
-
-  canonicalSessionID(owner:string,profile:string,id:string):string {
-    let current=id
-    const seen=new Set<string>()
-    for(let n=0;n<32&&!seen.has(current);n++){
-      seen.add(current)
-      const row=this.db.prepare('SELECT session_id FROM chat_session_aliases WHERE owner=? AND profile=? AND alias_id=?').get(owner,profile,current) as {session_id:string}|undefined
-      if(!row)break
-      current=row.session_id
-    }
-    return current
-  }
-  private migrateRuntimeSession(owner:string,profile:string,id:string,runtime:string):void {
-    const old=this.db.prepare('SELECT session_id FROM chat_sessions WHERE owner=? AND profile=? AND runtime_id=? AND session_id<>? AND owned_at IS NOT NULL').get(owner,profile,runtime,id) as {session_id:string}|undefined
-    if(!old||this.ownsSession(owner,profile,id))return
-    this.db.exec('SAVEPOINT migrate_live_route')
-    try{
-      for(const table of ['chat_sessions','chat_messages','chat_events','chat_snapshots','chat_attachments','chat_local_state','chat_event_receipts','chat_recovery_jobs','chat_message_identities'])
-        this.db.prepare(`UPDATE ${table} SET session_id=? WHERE owner=? AND profile=? AND session_id=?`).run(id,owner,profile,old.session_id)
-      this.db.prepare('INSERT OR REPLACE INTO chat_session_aliases VALUES(?,?,?,?)').run(owner,profile,old.session_id,id)
-      this.db.prepare('UPDATE chat_session_aliases SET session_id=? WHERE owner=? AND profile=? AND session_id=?').run(id,owner,profile,old.session_id)
-      this.db.prepare("UPDATE chat_sessions SET data=json_set(data,'$.id',?) WHERE owner=? AND profile=? AND session_id=?").run(id,owner,profile,id)
-      this.transcripts.migrate(owner,profile,old.session_id,id)
-      this.db.exec('RELEASE migrate_live_route')
-    }catch(e){this.db.exec('ROLLBACK TO migrate_live_route; RELEASE migrate_live_route');throw e}
-  }
-
-  recordRoute(owner: string, profile: string, sessionID: string, runtimeID: string, running?: boolean): void {
-    this.db.exec('SAVEPOINT chat_route')
-    try {
-    this.migrateRuntimeSession(owner,profile,sessionID,runtimeID)
-    const now = Date.now()
-    const summary = { id: sessionID, profile, source: 'unknown', title: '新对话', started_at: now, last_active: now }
-    this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
-      VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET runtime_id=excluded.runtime_id,
-      last_synced_at=excluded.last_synced_at,owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
-      ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
-      .run(owner, profile, sessionID, runtimeID, 'unknown', JSON.stringify(summary), 'stale', 0, now, now, 'route-confirmed')
-    this.markListsStale(owner)
-    if (running !== undefined) this.transcripts.sessionChanged(owner,profile,sessionID,{eventType:'route.resumed',payload:{running}})
-    this.db.exec('RELEASE chat_route')
-    } catch(error) { this.db.exec('ROLLBACK TO chat_route; RELEASE chat_route'); throw error }
-  }
-
-  recordCommand(owner: string, profile: string, sessionID: string, method: string,
-    params: Record<string, unknown>): void {
-    this.db.exec('SAVEPOINT chat_command')
-    try {
-    const now = Date.now()
-    const source = sessionSource(params) || 'unknown'
-    const establishesOwnership = method === 'session.create' || method === 'session.branch'
-    const summary = { id: sessionID, profile, source, title: '新对话', started_at: now, last_active: now }
-    this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
-      VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET
-      source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
-      sync_state=CASE WHEN chat_sessions.sync_state='gap' THEN 'gap' ELSE 'stale' END,sync_revision=chat_sessions.sync_revision+1,last_synced_at=excluded.last_synced_at,
-      owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
-      ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
-      .run(owner, profile, sessionID, source, JSON.stringify(summary), 'stale', 0, now,
-        establishesOwnership ? now : null, establishesOwnership ? `command:${method}` : null)
-    if(method==='session.create') this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_initialized) VALUES(?,?,?,1) ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_initialized=1`).run(owner,profile,sessionID)
-    if(method==='session.create') this.db.prepare(`UPDATE chat_sessions SET complete=1,metadata_complete=1,message_total=0,sync_state='current' WHERE owner=? AND profile=? AND session_id=? AND message_total IS NULL`).run(owner,profile,sessionID)
-    this.transcripts.seed(owner,profile,sessionID)
-    if((method==='prompt.submit'||method==='session.steer') && params._delivery_id){
-      this.transcripts.reduce(owner,profile,sessionID,'command.submitted',{...params,method,delivery_id:params._delivery_id})
-      this.updateTranscriptSummary(owner,profile,sessionID)
-    }
-    const payload = JSON.stringify(params)
-    const seq = Number.parseInt(createHash('sha256').update(`${method}:${payload}`).digest('hex').slice(0, 12), 16)
-    this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
-      VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, seq, `command:${method}`, payload, now)
-    this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND (session_id=? OR kind='list')")
-      .run(owner, sessionID)
-    this.db.exec('RELEASE chat_command')
-    } catch(error) { this.db.exec('ROLLBACK TO chat_command; RELEASE chat_command'); throw error }
-  }
-
-  fileSourceMessage(owner: string, profile: string, sessionID: string, messageID: string): Record<string, unknown> | undefined {
-    const canonical=this.transcripts.resolveMessage(owner,profile,sessionID,messageID)
-    if(canonical)return canonical
-    const row = this.db.prepare('SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
-      .get(owner, profile, sessionID, messageID)
-    return row ? JSON.parse(String(row.data)) : undefined
-  }
-
-  markListsStale(owner: string): void {
-    this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND kind='list'").run(owner)
-  }
-
-  invalidateOwnedMetadata(owner: string): Array<{profile:string;session_id:string}> {
-    return this.db.prepare(`UPDATE chat_sessions SET metadata_complete=0,sync_revision=sync_revision+1
-      WHERE owner=? AND owned_at IS NOT NULL AND source NOT IN ('cron','ios_group','yaoyao_workspace')
-      RETURNING profile,session_id`).all(owner) as Array<{profile:string;session_id:string}>
-  }
-
-  refreshMetadata(owner:string,profile:string,id:string,revision:number,response:UpstreamResponse,startedAt:number):boolean {
-    const payload=parseResponse(response),summary=object(payload?.session)??payload
-    const total=summary?.message_count??summary?.messageCount
-    const row=this.db.prepare('SELECT metadata_complete,complete,message_total,sync_state FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
-      .get(owner,profile,id) as {metadata_complete:number;complete:number;message_total:number;sync_state:string}|undefined
-    if(!row||row.metadata_complete||!row.complete||total==null||Number(total)!==row.message_total||this.revision(owner,profile,id)!==revision)return false
-    this.db.exec('SAVEPOINT metadata_refresh')
-    try {
-      const metadata={...summary};delete metadata.messages
-      const headers=new Headers(response.headers);headers.delete('content-length')
-      const metadataResponse={...response,headers,body:Buffer.from(JSON.stringify(metadata))}
-      if(!this.putSnapshot(owner,`detail:${profile}:${id}`,'detail',profile,id,metadataResponse,false,startedAt))throw new Error('Invalid conversation metadata')
-      // A metadata invalidation must not replace or downgrade the durable live tail.
-      this.db.prepare('UPDATE chat_sessions SET sync_state=? WHERE owner=? AND profile=? AND session_id=?').run(row.sync_state,owner,profile,id)
-      this.db.exec('RELEASE metadata_refresh');return true
-    }catch(error){this.db.exec('ROLLBACK TO metadata_refresh; RELEASE metadata_refresh');throw error}
-  }
-
-  recordAuthoritativeTitle(owner: string, profile: string, sessionID: string, title: string): void {
-    const normalized = title.trim()
-    if (!normalized) return
-    this.updateOwnedSessionTitle(owner, profile, sessionID, normalized, Date.now())
-    this.db.prepare(`UPDATE chat_snapshots SET sync_state='stale'
-      WHERE owner=? AND (session_id=? OR kind='list')`).run(owner, sessionID)
-  }
-
-  deleteSession(owner: string, profile: string, sessionID: string): void {
-    const assets = this.db.prepare(`SELECT DISTINCT local_path FROM chat_attachments
-      WHERE owner=? AND profile=? AND session_id=? AND local_path IS NOT NULL`)
-      .all(owner, profile, sessionID) as Array<{ local_path: string }>
-    this.db.exec('BEGIN IMMEDIATE')
-    try {
-      for (const table of ['chat_messages', 'chat_events', 'chat_attachments', 'chat_local_state', 'chat_event_receipts', 'chat_recovery_jobs', 'chat_session_aliases', 'chat_message_identities', 'chat_sessions']) {
-        this.db.prepare(`DELETE FROM ${table} WHERE owner=? AND profile=? AND session_id=?`).run(owner, profile, sessionID)
-      }
-      this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND ((profile=? AND session_id=?) OR kind='list')")
-        .run(owner, profile, sessionID)
-      this.transcripts.remove(owner,profile,sessionID)
-      this.db.exec('COMMIT')
-      for (const asset of assets) {
-        const referenced = this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE local_path=? LIMIT 1').get(asset.local_path)
-        if (!referenced) try { unlinkSync(asset.local_path) } catch { /* Already absent. */ }
-      }
-    } catch (error) { this.db.exec('ROLLBACK'); throw error }
-  }
-
-  attachment(owner: string, sourcePath: string): { localPath: string; mimeType?: string } | undefined {
-    const row = this.db.prepare(`SELECT local_path,mime_type FROM chat_attachments
-      WHERE owner=? AND source_path=? AND state='cached' ORDER BY updated_at DESC LIMIT 1`).get(owner, sourcePath) as Record<string, unknown> | undefined
-    const localPath = row?.local_path ? String(row.local_path) : ''
-    return localPath && existsSync(localPath) ? { localPath, ...(row?.mime_type ? { mimeType: String(row.mime_type) } : {}) } : undefined
-  }
-
-  knowsAttachment(owner: string, sourcePath: string): boolean {
-    return Boolean(this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE owner=? AND source_path=? LIMIT 1').get(owner, sourcePath))
-  }
-
-  ownsSession(owner: string, profile: string, sessionID: string): boolean {
-    sessionID=this.canonicalSessionID(owner,profile,sessionID)
-    return Boolean(this.db.prepare(
-      'SELECT 1 ok FROM chat_sessions WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL',
-    ).get(owner, profile, sessionID))
-  }
-
-  ownedSessionMetadata(owner: string, profile: string, sessionID: string): {
-    owned: boolean
-    authoritativeTitle?: string
-  } {
-    const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
-      .get(owner, profile, sessionID) as { authoritative_title?: string | null } | undefined
-    const local=this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionID) as {title?:string}|undefined
-    const authoritativeTitle = String(local?.title ?? row?.authoritative_title ?? '').trim()
-    return {
-      owned: Boolean(row),
-      ...(authoritativeTitle ? { authoritativeTitle } : {}),
-    }
-  }
-
-  mergeOwnedSessionsIntoList(
-    owner: string,
-    fallbackProfile: string,
-    response: UpstreamResponse,
-    page: { offset?: number; limit?: number; archived?: string } = {},
-  ): UpstreamResponse {
-    const payload = parseResponse(response)
-    if (!payload) return response
-    const collectionKey = Array.isArray(payload.items)
-      ? 'items'
-      : Array.isArray(payload.sessions) ? 'sessions' : undefined
-    if (!collectionKey) return response
-
-    const rows = (fallbackProfile
-      ? this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
-          WHERE owner=? AND profile=? AND owned_at IS NOT NULL`)
-          .all(owner, fallbackProfile)
-      : this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
-          WHERE owner=? AND owned_at IS NOT NULL`).all(owner)) as Array<{
-            profile: string
-            session_id: string
-            source: string
-            data: string
-            authoritative_title: string | null
-            last_synced_at: number
-          }>
-    const owned = new Map(rows.map(row => [
-      `${row.profile}\u0000${row.session_id}`,
-      row,
-    ]))
-    const merged = new Map<string, Record<string, unknown>>()
-    for (const [key, row] of owned) {
-      let stored: Record<string, unknown> = {}
-      try { stored = object(JSON.parse(row.data)) ?? {} } catch { /* Ignore damaged display metadata. */ }
-      const storedSource = sessionSource(stored)
-      merged.set(key, {
-        ...stored,
-        id: row.session_id,
-        profile: row.profile,
-        source: storedSource && storedSource !== 'unknown' ? storedSource : row.source,
-        ...(row.authoritative_title?.trim() ? { title: row.authoritative_title.trim() } : {}),
-        _yaoyao_registry_activity: row.last_synced_at,
-        owned: true,
-      })
-    }
-    for (const value of payload[collectionKey] as unknown[]) {
-      const session = object(value)
-      if (!session) continue
-      const id = sessionIDOf(session)
-      const profile = profileOf(session, fallbackProfile) || 'default'
-      if (!id) continue
-      const key = `${profile}\u0000${id}`
-      const row = owned.get(key)
-      if (row) {
-        const title = row.authoritative_title?.trim()
-        merged.set(key, {
-          ...mergeSessionMetadata(merged.get(key) ?? {}, session),
-          ...(title ? { title } : {}),
-          _yaoyao_registry_activity: row.last_synced_at,
-          owned: true,
-        })
-      }
-    }
-    const activity = (session: Record<string, unknown>): number =>
-      firstTimestamp(session, ACTIVITY_TIME_KEYS) ?? firstTimestamp(session, START_TIME_KEYS) ?? 0
-    const archived = (session: Record<string, unknown>): boolean => bool(
-      session.is_archived ?? session.isArchived ?? session.archived,
-    )
-    const pinned = (session: Record<string, unknown>): boolean => bool(
-      session.is_pinned ?? session.isPinned ?? session.pinned,
-    )
-    const archivedMode = page.archived ?? 'exclude'
-    const allSessions = [...merged.values()]
-      .filter(session => archivedMode === 'include'
-        || (archivedMode === 'only' ? archived(session) : !archived(session)))
-      .sort((left, right) => Number(pinned(right)) - Number(pinned(left))
-        || activity(right) - activity(left))
-    const offset = Math.max(0, Math.trunc(page.offset ?? 0))
-    const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)))
-    const sessions = allSessions.slice(offset, offset + limit).map((session) => {
-      const publicSession = mergeSessionMetadata({}, session)
-      delete publicSession._yaoyao_registry_activity
-      return publicSession
-    })
-    const body = Buffer.from(JSON.stringify({
-      ...payload,
-      [collectionKey]: sessions,
-      total: allSessions.length,
-      offset,
-      limit,
-    }))
-    const headers = new Headers(response.headers)
-    headers.delete('content-length')
-    return { ...response, headers, body }
-  }
-
-  excludeOwnedSessionsFromList(
-    owner: string,
-    fallbackProfile: string,
-    response: UpstreamResponse,
-    page: { offset?: number; limit?: number } = {},
-  ): UpstreamResponse {
-    const payload = parseResponse(response)
-    if (!payload) return response
-    const collectionKey = Array.isArray(payload.items)
-      ? 'items'
-      : Array.isArray(payload.sessions) ? 'sessions' : undefined
-    if (!collectionKey) return response
-    const allSessions = (payload[collectionKey] as unknown[]).filter((value) => {
-      const session = object(value)
-      if (!session) return true
-      const id = sessionIDOf(session)
-      const profile = profileOf(session, fallbackProfile) || 'default'
-      return !id || !this.ownsSession(owner, profile, id)
-    })
-    const offset = Math.max(0, Math.trunc(page.offset ?? 0))
-    const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)))
-    const sessions = allSessions.slice(offset, offset + limit).map(value => object(value) ? sessionForList(object(value)!) : value)
-    const headers = new Headers(response.headers)
-    headers.delete('content-length')
-    return {
-      ...response,
-      headers,
-      body: Buffer.from(JSON.stringify({
-        ...payload,
-        [collectionKey]: sessions,
-        total: allSessions.length,
-        offset,
-        limit,
-      })),
-    }
-  }
-
-  markSessionOwnership(
-    owner: string,
-    fallbackProfile: string,
-    sessionID: string,
-    response: UpstreamResponse,
-  ): UpstreamResponse {
-    const payload = parseResponse(response)
-    if (!payload) return response
-    const session = object(payload.session)
-    const candidate = session ?? payload
-    const id = sessionIDOf(candidate) || sessionID
-    const profile = profileOf(candidate, fallbackProfile) || fallbackProfile || 'default'
-    const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, id) as { authoritative_title?: string | null } | undefined
-    const owned = Boolean(row)
-    const local=this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id) as {title?:string}|undefined
-    const title = String(local?.title ?? row?.authoritative_title ?? '').trim()
-    const body = session
-      ? Buffer.from(JSON.stringify({
-          ...payload,
-          session: { ...session, ...(title ? { title } : {}), owned },
-          owned,
-        }))
-      : Buffer.from(JSON.stringify({ ...payload, ...(title ? { title } : {}), owned }))
-    const headers = new Headers(response.headers)
-    headers.delete('content-length')
-    return { ...response, headers, body }
-  }
-
-  markOwnedSearchResults(
-    owner: string,
-    fallbackProfile: string,
-    response: UpstreamResponse,
-    view?: 'chat' | 'history',
-    limit = 100,
-  ): UpstreamResponse {
-    const payload = parseResponse(response)
-    if (!payload || !Array.isArray(payload.results)) return response
-    const marked = payload.results.map((value) => {
-      const session = object(value)
-      if (!session) return value
-      const id = sessionIDOf(session)
-      const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default'
-      const metadata = id
-        ? this.ownedSessionMetadata(owner, profile, id)
-        : { owned: false }
-      return {
-        ...session,
-        ...(metadata.authoritativeTitle ? { title: metadata.authoritativeTitle } : {}),
-        owned: metadata.owned,
-      }
-    })
-    const projected = marked.filter((value) => {
-      if (!view) return true
-      const session = object(value)
-      if (!session) return false
-      return view === 'chat' ? session.owned === true : session.owned !== true
-    })
-    const results = projected.slice(0, Math.max(1, Math.min(100, Math.trunc(limit))))
-    const headers = new Headers(response.headers)
-    headers.delete('content-length')
-    return {
-      ...response,
-      headers,
-      body: Buffer.from(JSON.stringify({ ...payload, results, total: projected.length })),
-    }
-  }
-
-  storeAttachment(owner: string, sourcePath: string, response: UpstreamResponse): string | undefined {
-    if (response.status !== 200 || !response.body.length) return undefined
-    const sha256 = createHash('sha256').update(response.body).digest('hex')
-    const directory = join(this.assetsRoot, sha256.slice(0, 2))
-    mkdirSync(directory, { recursive: true, mode: 0o700 })
-    const target = join(directory, sha256)
-    if (!existsSync(target)) {
-      const temporary = `${target}.${process.pid}.tmp`
-      writeFileSync(temporary, response.body, { mode: 0o600 })
-      renameSync(temporary, target)
-    }
-    const mimeType = response.headers.get('content-type')?.split(';', 1)[0]
-    this.db.prepare(`UPDATE chat_attachments SET sha256=?,mime_type=?,size=?,local_path=?,state='cached',updated_at=?
-      WHERE owner=? AND source_path=?`).run(sha256, mimeType ?? null, response.body.length, target, Date.now(), owner, sourcePath)
-    return target
-  }
-
-  assetStream(path: string): { stream: ReturnType<typeof createReadStream>; size: number } {
-    return { stream: createReadStream(path), size: statSync(path).size }
-  }
-
-  private payloadBelongsToOwnedChat(owner: string, profile: string, sessionID: string | undefined,
-    payload: Record<string, unknown>): boolean {
-    const session = object(payload.session) ?? (sessionID ? payload : undefined)
-    if (session) {
-      const id = sessionIDOf(session) || sessionID || ''
-      const sessionProfile = profileOf(session, profile) || profile || 'default'
-      if (id && this.ownsSession(owner, sessionProfile, id)) return true
-    }
-    const sessions = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : []
-    if (sessions.some(value => {
-      const candidate = object(value)
-      if (!candidate) return false
-      const id = sessionIDOf(candidate)
-      const sessionProfile = profileOf(candidate, profile) || profile || 'default'
-      return Boolean(id && this.ownsSession(owner, sessionProfile, id))
-    })) return true
-    return Boolean(sessionID && this.ownsSession(owner, profile || 'default', sessionID))
-  }
-
-  private ingestPayload(owner: string, fallbackProfile: string, sessionID: string | undefined,
-    payload: Record<string, unknown>, now: number, kind: string, requestStartedAt: number): void {
-    const candidates: Record<string, unknown>[] = []
-    const direct = object(payload.session)
-    if (direct) candidates.push(direct)
-    const listed = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : []
-    for (const value of listed) if (object(value)) candidates.push(object(value)!)
-    if (sessionID && !direct && (sessionIDOf(payload) || sessionSource(payload) || typeof payload.title === 'string')) {
-      candidates.push(payload)
-    }
-    for (const session of candidates) {
-      const id = sessionIDOf(session) || sessionID || ''
-      if (!id) continue
-      const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default'
-      const registered = this.ownsSession(owner, profile, id)
-      const source = sessionSource(session)
-      if (!registered) continue
-      const titleRow = this.db.prepare(`SELECT data,authoritative_title,authoritative_title_at FROM chat_sessions
-        WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, id) as {
-          data: string; authoritative_title?: string | null; authoritative_title_at?: number
-        } | undefined
-      const authoritativeTitle = String(titleRow?.authoritative_title ?? '').trim()
-      const authoritativeTitleAt = Number(titleRow?.authoritative_title_at ?? 0)
-      const incomingTitle = sessionTitle(session)
-      const preservesAuthoritativeTitle = Boolean(authoritativeTitle)
-        && (kind !== 'detail' || isPlaceholderTitle(incomingTitle)
-          || requestStartedAt <= authoritativeTitleAt)
-      let previous: Record<string, unknown> = {}
-      try { previous = object(JSON.parse(titleRow?.data ?? '{}')) ?? {} } catch { /* Recover from incoming metadata. */ }
-      const storedSession = mergeSessionMetadata(previous, session)
-      if (preservesAuthoritativeTitle) storedSession.title = authoritativeTitle
-      const metadataComplete = kind !== 'messages' || direct ? 1 : 0
-      this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,metadata_complete)
-        VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET data=excluded.data,
-        metadata_complete=MAX(chat_sessions.metadata_complete,excluded.metadata_complete),
-        source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
-        sync_state='current',last_synced_at=excluded.last_synced_at`)
-        .run(owner, profile, id, null, source || 'unknown', JSON.stringify(storedSession), 'current', 0, now, metadataComplete)
-      const acceptedTitle = sessionTitle(storedSession)
-      if (acceptedTitle && !isPlaceholderTitle(acceptedTitle)
-        && (!authoritativeTitle || kind === 'detail')) {
-        this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?,authoritative_title_at=?
-          WHERE owner=? AND profile=? AND session_id=?`).run(
-            acceptedTitle,
-            Math.max(requestStartedAt, authoritativeTitleAt),
-            owner,
-            profile,
-            id,
-          )
-      }
-    }
-    const messages = Array.isArray(payload.messages) ? payload.messages.flatMap(value => object(value) ? [object(value)!] : []) : []
-    if (!Array.isArray(payload.messages) || !sessionID) return
-    const profile = fallbackProfile || profileOf(direct ?? {}, 'default') || 'default'
-    const pagination = object(payload.pagination) ?? {}
-    const offset = Math.max(0, Number(pagination.offset ?? payload.offset ?? 0) || 0)
-    const storedDetail = this.localDetail(owner, profile, sessionID)
-    const storedSummary = storedDetail ? parseResponse(storedDetail.response) ?? {} : {}
-    const total = Math.max(offset + messages.length,
-      Number(pagination.total ?? payload.total ?? storedSummary.message_count ?? storedSummary.messageCount ?? 0) || 0)
-    const start = Math.max(0, total - offset - messages.length)
-    this.userMessageIdentities(owner, profile, sessionID, messages, false).forEach((message, index) => {
-      const data = JSON.stringify(message)
-      this.db.prepare(`INSERT INTO chat_messages(owner,profile,session_id,message_id,position,data,content_hash)
-        VALUES(?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,message_id) DO UPDATE SET position=excluded.position,
-        data=excluded.data,content_hash=excluded.content_hash
-        WHERE chat_messages.content_hash<>excluded.content_hash OR chat_messages.position<>excluded.position`)
-        .run(owner, profile, sessionID, messageID(message, String(start + index)), start + index, data,
-          createHash('sha256').update(data).digest('hex'))
-      for (const sourcePath of referencedPaths(message)) {
-        this.db.prepare(`INSERT INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at)
-          VALUES(?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,source_path) DO UPDATE SET updated_at=excluded.updated_at`)
-          .run(owner, profile, sessionID, sourcePath, 'pending', now)
-      }
-    })
-    const coverage = this.db.prepare(`SELECT COUNT(*) count, COUNT(DISTINCT position) positions, MIN(position) first, MAX(position) last
-      FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as Record<string, number>
-    const complete = total === 0 ? coverage.count === 0
-      : coverage.count === total && coverage.positions === total && coverage.first === 0 && coverage.last === total - 1
-    const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
-      .get(owner, profile, sessionID) as { data: string }
-    const summary = mergeSessionMetadata({}, object(JSON.parse(row.data)) ?? {})
-    const bounds = messageTimeBounds(messages)
-    if (!firstTimestamp(summary, START_TIME_KEYS) && bounds.first !== undefined) summary.started_at = bounds.first
-    if (bounds.last !== undefined) {
-      summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0, bounds.last)
-    }
-    summary.message_count = total
-    this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
-      .run(JSON.stringify(summary), owner, profile, sessionID)
-    this.db.prepare(`UPDATE chat_sessions SET complete=?,message_total=?,sync_state='current',last_synced_at=?
-      WHERE owner=? AND profile=? AND session_id=?`).run(complete ? 1 : 0, total, now, owner, profile, sessionID)
-  }
-
-  private updateOwnedSessionTitle(owner: string, profile: string, sessionID: string, title: string, now: number): void {
-    const row = this.db.prepare(`SELECT source,data FROM chat_sessions
-      WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, sessionID) as Record<string, unknown> | undefined
-    if (!row) return
-    let summary: Record<string, unknown> = {}
-    try { summary = object(JSON.parse(String(row.data))) ?? {} } catch { /* Rebuild damaged display metadata below. */ }
-    const storedSource = sessionSource(summary)
-    const source = storedSource && storedSource !== 'unknown'
-      ? storedSource
-      : String(row.source || 'unknown')
-    this.db.prepare(`UPDATE chat_sessions SET data=?,authoritative_title=?,authoritative_title_at=?,sync_state='stale',last_synced_at=?
-      WHERE owner=? AND profile=? AND session_id=?`).run(JSON.stringify({
-      ...summary,
-      id: sessionID,
-      profile,
-      source,
-      title,
-    }), title, now, now, owner, profile, sessionID)
-  }
-}
-
-export class ChatCacheCoordinator {
-  private reconciling = new Map<string, Promise<void>>()
-  onSynchronized: (owner: string, profile: string, sessionID: string) => void = () => {}
-  constructor(readonly store: ChatCacheStore, readonly upstream: UpstreamServiceSession,
-    readonly mode: ChatCacheMode = 'prefer-local') {
-      const timer=setTimeout(()=>{
-        this.retryTimers.delete(timer)
-        if(this.store.isClosed||this.stopped)return
-        void this.restoreReadPositions()
-        for(const row of this.store.db.prepare("SELECT owner,profile,session_id FROM chat_sessions WHERE owned_at IS NOT NULL").all() as any[]){this.store.transcripts.seed(row.owner,row.profile,row.session_id)}
-        for(const row of this.store.db.prepare("SELECT * FROM chat_transcript_repairs WHERE status='pending'").all() as any[])this.schedule(row.owner,row.profile,row.session_id,true)
-        for(const row of this.store.db.prepare('SELECT * FROM chat_recovery_jobs').all() as any[])this.schedule(row.owner,row.profile,row.session_id,!!row.force)
-      },0);timer.unref();this.retryTimers.add(timer)
-    }
-
-  readonly diagnostics = {localReads:0, recoveryAttempts:0, recoveryFailures:0, recoveryCompleted:0}
-  private async restoreReadPositions():Promise<void>{
-    if(this.stopped||this.store.isClosed)return
-    const scopes=this.store.db.prepare('SELECT DISTINCT owner,profile FROM chat_local_state WHERE read_initialized=0').all() as {owner:string;profile:string}[]
-    let failed=false
-    for(let i=0;i<scopes.length;i+=2)await Promise.all(scopes.slice(i,i+2).map(async({owner,profile})=>{
-      if(this.stopped||this.store.isClosed)return
-      try{
-        const response=await this.upstream.request('/api/session-unread',{search:new URLSearchParams({profile})})
-        if(this.stopped||this.store.isClosed)return
-        if(response.status>=500)throw new Error('Read-position import unavailable')
-        const payload=parseResponse(response),rows=Array.isArray(payload?.sessions)?payload.sessions:[]
-        this.store.db.exec('SAVEPOINT read_position_import')
-        try{
-          for(const raw of rows){const r=object(raw);if(!r)continue;const id=String(r.session_id??r.sessionId??'')
-            const count=Math.max(0,Number(r.read_message_count??r.readMessageCount??0)||0)
-            this.store.db.prepare('UPDATE chat_local_state SET read_count=?,read_initialized=1 WHERE owner=? AND profile=? AND session_id=? AND read_initialized=0').run(count,owner,profile,id)
-          }
-          this.store.db.prepare(`UPDATE chat_local_state SET read_count=COALESCE((SELECT message_total FROM chat_sessions s WHERE s.owner=chat_local_state.owner AND s.profile=chat_local_state.profile AND s.session_id=chat_local_state.session_id),0),read_initialized=1 WHERE owner=? AND profile=? AND read_initialized=0`).run(owner,profile)
-          this.store.db.exec('RELEASE read_position_import')
-        }catch(e){this.store.db.exec('ROLLBACK TO read_position_import; RELEASE read_position_import');throw e}
-      }catch{failed=true}
-    }))
-    if(failed&&!this.stopped&&!this.store.isClosed){const timer=setTimeout(()=>{this.retryTimers.delete(timer);void this.restoreReadPositions()},30_000);timer.unref();this.retryTimers.add(timer)}
-  }
-  private jobs = new Map<string,{owner:string;profile:string;id:string;force:boolean;attempt:number}>()
-  private activeJobs = new Set<string>()
-  private retryTimers = new Set<ReturnType<typeof setTimeout>>()
-  private stopped = false
-  close(): void {this.stopped=true;for(const timer of this.retryTimers)clearTimeout(timer);this.retryTimers.clear();this.jobs.clear()}
-
-  schedule(owner:string,profile:string,id:string,force=false): void {
-    if(this.stopped||this.store.isClosed||!this.store.ownsSession(owner,profile,id))return
-    const key=JSON.stringify([owner,profile,id]),previous=this.jobs.get(key)
-    if(previous){previous.force ||= force;if(force)this.store.db.prepare('UPDATE chat_recovery_jobs SET force=1 WHERE owner=? AND profile=? AND session_id=?').run(owner,profile,id);return}
-    this.store.db.prepare('INSERT INTO chat_recovery_jobs VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET force=MAX(force,excluded.force)').run(owner,profile,id,force?1:0)
-    this.jobs.set(key,{owner,profile,id,force,attempt:0})
-    const timer=setTimeout(()=>{this.retryTimers.delete(timer);this.drain()},0);timer.unref();this.retryTimers.add(timer)
-  }
-  private drain(): void {
-    if(this.stopped||this.store.isClosed)return
-    for(const [key,job] of this.jobs){
-      if(this.activeJobs.size>=2)break
-      if(this.activeJobs.has(key)||job.attempt<0)continue
-      this.activeJobs.add(key)
-      this.diagnostics.recoveryAttempts++
-      const force=job.force;job.force=false
-      void this.reconcile(job.owner,job.profile,job.id,force).then(()=>{
-        if(this.stopped||this.store.isClosed)return
-        if(job.force){job.attempt=0;return}
-        this.diagnostics.recoveryCompleted++
-        this.jobs.delete(key)
-        this.store.db.prepare('DELETE FROM chat_recovery_jobs WHERE owner=? AND profile=? AND session_id=?').run(job.owner,job.profile,job.id)
-      }).catch(()=>{
-        if(this.stopped||this.store.isClosed)return
-        this.diagnostics.recoveryFailures++
-        job.force ||= force
-        const attempt=Math.abs(job.attempt)+1;job.attempt=-attempt
-        const timer=setTimeout(()=>{this.retryTimers.delete(timer);job.attempt=attempt;this.drain()},Math.min(30_000,1000*2**Math.min(attempt-1,5)))
-        timer.unref();this.retryTimers.add(timer)
-      }).finally(()=>{this.activeJobs.delete(key);this.drain()})
-    }
-  }
-  readLocal(owner:string,kind:'list'|'detail'|'messages',profile:string,id:string|undefined,
-    page:{offset?:number;limit?:number;archived?:string},force=false): {response:UpstreamResponse;source:ChatCacheSource;state:ChatCacheState} {
-    this.diagnostics.localReads++
-    if(id)id=this.store.canonicalSessionID(owner,profile,id)
-    if(kind==='list'){
-      for(const row of this.store.missingSessions(owner,profile)) this.schedule(owner,row.profile,row.session_id,force)
-      return {response:this.store.localList(owner,profile,page),source:'local',state:this.store.needsListMetadata(owner,profile)?'syncing':'current'}
-    }
-    this.store.requireOwned(owner,profile,id!)
-    const local=kind==='detail'?this.store.localDetail(owner,profile,id!):this.store.messagePage(owner,profile,id!,page.offset??0,page.limit??100)
-    if(force||!local||local.state==='gap')this.schedule(owner,profile,id!,force)
-    if(!local)throw new HttpError(409,'历史正在后台补齐,请稍后重试','CHAT_HISTORY_SYNC_PENDING')
-    return {response:local.response,source:'local',state:this.jobs.has(JSON.stringify([owner,profile,id]))?'syncing':local.state}
-  }
-
-  async read(owner: string, key: string, kind: string, profile: string, sessionID: string | undefined,
-    load: () => Promise<UpstreamResponse>, ownedList = false,
-    listPage: { offset?: number; limit?: number; archived?: string } = {}): Promise<{ response: UpstreamResponse; source: ChatCacheSource; state: ChatCacheState }> {
-    if (this.mode === 'upstream-only') {
-      const upstreamResponse = await load()
-      return {
-        response: kind === 'list' && ownedList
-          ? this.store.mergeOwnedSessionsIntoList(owner, profile, upstreamResponse, listPage)
-          : upstreamResponse,
-        source: 'upstream',
-        state: 'current',
-      }
-    }
-    if (this.mode === 'prefer-local' && kind === 'list' && ownedList && !this.store.needsListMetadata(owner, profile)) {
-      return { response: this.store.localList(owner, profile, listPage), source: 'local', state: 'current' }
-    }
-    const local = kind === 'list' && ownedList && this.store.needsListMetadata(owner, profile) ? undefined : kind === 'detail' && sessionID
-      ? this.store.localDetail(owner, profile, sessionID) ?? this.store.snapshot(owner, key)
-      : this.store.snapshot(owner, key)
-    const projectedLocal = local && kind === 'list' && ownedList
-      ? {
-          ...local,
-          response: this.store.mergeOwnedSessionsIntoList(owner, profile, local.response, listPage),
-        }
-      : local
-    if (this.mode === 'prefer-local' && local) {
-      return { response: projectedLocal!.response, source: 'local', state: local.state }
-    }
-    try {
-      const requestStartedAt = Date.now()
-      const upstreamResponse = await load()
-      if (this.mode === 'prefer-local' && local && upstreamResponse.status >= 500) {
-        return { response: projectedLocal!.response, source: 'local', state: 'stale' }
-      }
-      const response = kind === 'list' && ownedList
-        ? this.store.mergeOwnedSessionsIntoList(
-            owner,
-            profile,
-            upstreamResponse,
-            listPage,
-          )
-        : upstreamResponse
-      this.store.putSnapshot(owner, key, kind, profile, sessionID, response, ownedList, requestStartedAt, upstreamResponse)
-      return { response, source: 'upstream', state: 'current' }
-    } catch (error) {
-      if (this.mode === 'prefer-local' && local) return { response: projectedLocal!.response, source: 'local', state: 'stale' }
-      throw error
-    }
-  }
-
-  async messages(owner: string, key: string, profile: string, sessionID: string, offset: number, limit: number,
-    load: () => Promise<UpstreamResponse>): Promise<{ response: UpstreamResponse; source: ChatCacheSource; state: ChatCacheState }> {
-    if (this.mode === 'prefer-local') {
-      // A completion may still be committing its authoritative tail. Join it for
-      // the latest page; older, already stored pages never wait for the network.
-      if (offset === 0) await this.reconciling.get(JSON.stringify([owner, profile, sessionID]))?.catch(() => {})
-      const page = this.store.messagePage(owner, profile, sessionID, offset, limit)
-      if (page) return { response: page.response, source: 'local', state: page.state }
-    }
-    return this.read(owner, key, 'messages', profile, sessionID, load)
-  }
-
-  observe(owner: string, profile: string, sessionID: string, frame: Record<string, unknown>): void {
-    if (!this.store.recordEvent(owner, profile, sessionID, frame)) return
-    if (String(frame.type).includes('reset') || this.store.localDetail(owner,profile,sessionID)?.state==='gap'
-      || (['message.complete','run.completed'].includes(String(frame.type)) && this.store.localDetail(owner,profile,sessionID)?.state!=='current')) {
-      this.schedule(owner, profile, sessionID)
-    }
-  }
-
-  observeGlobal(owner: string, type: string, upstreamInvalidation=false): void {
-    if (type !== 'sessions.changed' || this.stopped || this.store.isClosed) return
-    this.store.markListsStale(owner)
-    if(upstreamInvalidation)for(const row of this.store.invalidateOwnedMetadata(owner))this.schedule(owner,row.profile,row.session_id)
-  }
-
-  command(owner: string, profile: string, sessionID: string, method: string,
-    params: Record<string, unknown>): void {
-    this.store.recordCommand(owner, profile, sessionID, method, params)
-  }
-
-  route(owner: string, profile: string, sessionID: string, runtimeID: string, running?: boolean): void {
-    this.store.recordRoute(owner, profile, sessionID, runtimeID, running)
-  }
-
-  async reconcile(owner: string, profile: string, sessionID: string, force = false): Promise<void> {
-    if(this.store.isClosed)return
-    sessionID=this.store.canonicalSessionID(owner,profile,sessionID)
-    if (this.stopped || this.store.isClosed || !this.store.ownsSession(owner, profile, sessionID)) return
-    const key = JSON.stringify([owner, profile, sessionID])
-    const pending = this.reconciling.get(key)
-    if (pending) {
-      const failed=await pending.then(()=>false,()=>true)
-      if (failed || force || this.store.localDetail(owner, profile, sessionID)?.state !== 'current') {
-        return this.reconcile(owner, profile, sessionID, force)
-      }
-      return
-    }
-    const task = (async () => {
-      if(this.store.transcripts.head(owner,profile,sessionID).running)throw new Error('Conversation is running; defer history repair')
-      const repair=this.store.db.prepare("SELECT 1 FROM chat_transcript_repairs WHERE owner=? AND profile=? AND session_id=? AND status='pending'").get(owner,profile,sessionID)
-      force ||= !!repair
-      const revision = this.store.revision(owner, profile, sessionID)
-      const previous = this.store.sourceMessagePage(owner, profile, sessionID, 0, 1)
-      const previousTotal = previous ? Number(object(parseResponse(previous.response)?.pagination)?.total ?? 0) : 0
-      const detailPath = `/api/sessions/${encodeURIComponent(sessionID)}`
-      const detailStartedAt = Date.now()
-      const detail = await this.upstream.request(detailPath, { search: new URLSearchParams({ profile }), cache: 'reload' })
-      if (this.stopped || this.store.isClosed) return
-      if (detail.status !== 200) throw new Error('Unable to synchronize conversation metadata')
-      if(!force&&this.store.refreshMetadata(owner,profile,sessionID,revision,detail,detailStartedAt)) {
-        this.onSynchronized(owner,profile,sessionID)
-        return
-      }
-      const detailPayload = parseResponse(detail) ?? {}
-      const detailSummary = object(detailPayload.session) ?? detailPayload
-      const summaryTotal = Math.max(0, Number(detailSummary.message_count ?? detailSummary.messageCount ?? previousTotal) || 0)
-      const pages = [{ key: `detail:${profile}:${sessionID}`, kind: 'detail', response: detail, startedAt: detailStartedAt, offset: 0 }]
-      let offset = 0
-      let done = false
-      let expectedTotal: number | undefined
-      let resolvedTotal = summaryTotal
-      // Stop as soon as the authoritative tail overlaps durable messages. Only
-      // explicit refresh (or uncached history) walks all the way to the beginning.
-      for (let page = 0; page < 1_000; page++) {
-        const search = new URLSearchParams({ profile, offset: String(offset), limit: '100', order: 'latest', include_compacted: 'true' })
-        const startedAt = Date.now()
-        const response = await this.upstream.request(`${detailPath}/messages`, { search, cache: 'reload' })
-        if (this.stopped || this.store.isClosed) return
-        const payload = parseResponse(response)
-        if (response.status !== 200 || !Array.isArray(payload?.messages)) throw new Error('Unable to synchronize conversation messages')
-        const messages = payload.messages.flatMap(value => object(value) ? [object(value)!] : [])
-        const pagination = object(payload.pagination) ?? {}
-        const explicitTotal = pagination.total ?? payload.total
-        const total = Math.max(offset + messages.length, Number(explicitTotal ?? summaryTotal) || 0)
-        if (!force && total < previousTotal) throw new Error('Stored history changed; explicit refresh is required')
-        if (explicitTotal !== undefined) {
-          if (expectedTotal !== undefined && expectedTotal !== total) throw new Error('Conversation changed during synchronization')
-          expectedTotal = total
-        }
-        const anchors = !force ? messages.map((message, index) =>
-          this.store.hasMessage(owner, profile, sessionID, message, total - offset - messages.length + index)) : []
-        const overlap = anchors.some(Boolean)
-        pages.push({ key: `messages:${profile}:${sessionID}:${offset}:100`, kind: 'messages', response, startedAt, offset })
-        const more = pagination.hasMore ?? pagination.has_more ?? payload.hasMore ?? payload.has_more
-        const hasMore = more === undefined ? messages.length >= 100 : bool(more)
-        if (overlap || !hasMore) {
-          if (!overlap && expectedTotal !== undefined && expectedTotal !== offset + messages.length) throw new Error('Conversation pagination ended before its declared total')
-          resolvedTotal = overlap ? total : offset + messages.length
-          done = true
-          break
-        }
-        if (!messages.length) break
-        offset += messages.length
-      }
-      if (!done) throw new Error('Conversation synchronization is incomplete')
-      // Newer Hermes omits total/has_more. Once the end is known, project the
-      // same verified total onto every page before assigning absolute positions.
-      for (let index = 0; index < pages.length; index++) {
-        const entry = pages[index]!
-        const payload = parseResponse(entry.response)!
-        if (entry.kind === 'detail') {
-          const summary = object(payload.session) ?? payload
-          summary.message_count = resolvedTotal
-        } else {
-          const pagination = object(payload.pagination) ?? {}
-          const pageOffset = entry.offset
-          payload.pagination = { ...pagination, total: resolvedTotal, offset: pageOffset,
-            has_more: pageOffset + (payload.messages as unknown[]).length < resolvedTotal }
-        }
-        const headers = new Headers(entry.response.headers)
-        headers.delete('content-length')
-        entry.response = { ...entry.response, headers, body: Buffer.from(JSON.stringify(payload)) }
-      }
-      if (!this.store.applySync(owner, profile, sessionID, revision, pages, force)) {
-        // Preserve the invalidation when a newer event arrived during the read.
-        // Its completion joins this flight and schedules the next tail read.
-        throw new Error('Conversation changed during refresh; retry after the reply completes')
-      } else {
-        if(this.store.db.prepare("SELECT 1 FROM chat_transcript_repairs WHERE owner=? AND profile=? AND session_id=? AND status='pending'").get(owner,profile,sessionID))
-          throw new Error('History identity is not yet confirmed; preserve the existing conversation')
-        this.onSynchronized(owner, profile, sessionID)
-      }
-    })().finally(() => { if (this.reconciling.get(key) === task) this.reconciling.delete(key) })
-    this.reconciling.set(key, task)
-    return task
-  }
-
-  async cacheAttachment(owner: string, sourcePath: string): Promise<void> {
-    if (this.mode === 'upstream-only' || !this.store.knowsAttachment(owner, sourcePath) || this.store.attachment(owner, sourcePath)) return
-    try {
-      const response = await this.upstream.request('/api/files/download', {
-        search: new URLSearchParams({ path: sourcePath }), maxResponseBytes: 100 * 1_024 * 1_024,
-      })
-      this.store.storeAttachment(owner, sourcePath, response)
-    } catch { /* The next authorized request can retry. */ }
-  }
-}
-
-export function chatCacheKey(kind: string, profile: string, sessionID: string | undefined, search: URLSearchParams): string {
-  const normalized = new URLSearchParams(search)
-  normalized.sort()
-  return [kind, profile, sessionID ?? '', normalized.toString()].join(':')
-}

+ 0 - 86
src/server/chatTranscriptApi.ts

@@ -1,86 +0,0 @@
-import Router from '@koa/router'
-import type Koa from 'koa'
-import type { ChatCacheCoordinator } from './chatCache.js'
-import type { LocalAuthStore } from './localAuth.js'
-import { HttpError } from './errors.js'
-import { CHAT_TRANSCRIPT_FEATURE } from '../shared/chatTranscript.js'
-import { sessionForList } from './chatPresentation.js'
-
-export function chatTranscriptRouter(cache:ChatCacheCoordinator,auth:LocalAuthStore):Router {
-  const router=new Router(),store=cache.store,transcripts=store.transcripts
-  const scope=(ctx:Koa.Context)=>{
-    const owner=auth.require(ctx).id,profile=String(ctx.query.profile??'default'),requested=ctx.params.id
-    if(!profile||profile.length>256||!requested||requested.length>256)throw new HttpError(400,'会话标识无效','invalid_session')
-    const id=store.canonicalSessionID(owner,profile,requested)
-    store.requireOwned(owner,profile,id)
-    if(!auth.canUseSource(owner,'local',profile))throw new HttpError(403,'没有此 Profile 的权限','profile_forbidden')
-    ctx.set('Cache-Control','no-store')
-    return {owner,profile,id}
-  }
-  router.get('/api/app/chat/capabilities',ctx=>{auth.require(ctx);ctx.set('Cache-Control','no-store');ctx.body={features:transcripts.enabled?[CHAT_TRANSCRIPT_FEATURE]:[],epoch:transcripts.epoch}})
-  router.get('/api/app/chat/sessions/:id/snapshot',ctx=>{
-    const {owner,profile,id}=scope(ctx)
-    const before=ctx.query.before===undefined?Number.MAX_SAFE_INTEGER:Number(ctx.query.before),limit=ctx.query.limit===undefined?150:Number(ctx.query.limit)
-    if(!Number.isSafeInteger(before)||before<1||!Number.isSafeInteger(limit)||limit<1||limit>500)throw new HttpError(400,'历史分页参数无效','invalid_page')
-    const coverage=store.db.prepare('SELECT complete FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id)
-    if(!coverage?.complete||store.needsListMetadata(owner,profile)||store.localDetail(owner,profile,id)?.state==='gap')cache.schedule(owner,profile,id)
-    store.db.exec('SAVEPOINT transcript_snapshot')
-    try{
-      transcripts.seed(owner,profile,id)
-      const detail=store.localDetail(owner,profile,id)!
-      ctx.body=transcripts.snapshot(owner,profile,id,sessionForList(JSON.parse(detail.response.body.toString())),detail.state,before,limit)
-      store.db.exec('RELEASE transcript_snapshot')
-    }catch(error){store.db.exec('ROLLBACK TO transcript_snapshot; RELEASE transcript_snapshot');throw error}
-  })
-  router.get('/api/app/chat/sessions/:id/events',ctx=>{
-    const {owner,profile,id}=scope(ctx),version=auth.pushAuthorizationVersion(owner),cookie=ctx.get('cookie')
-    const raw=ctx.get('last-event-id')||String(ctx.query.after??''),parts=raw.split(':')
-    let cursor=Number(parts.at(-1)),closed=false,lastFlush=0,ready=false
-    transcripts.seed(owner,profile,id)
-    const epoch=transcripts.epochFor(owner,profile,id)
-    if(parts.length!==2||parts[0]!==epoch||!Number.isSafeInteger(cursor)||cursor<0||cursor>transcripts.cursor(owner,profile,id))throw new HttpError(409,'聊天事件需要重新同步','transcript_reset')
-    const res=ctx.res
-    let timer:ReturnType<typeof setTimeout>|undefined,heartbeat:ReturnType<typeof setInterval>|undefined,off=()=>{}
-    const valid=()=>!store.isClosed&&auth.isUserActive(owner)&&auth.pushAuthorizationVersion(owner)===version&&auth.currentFromCookieHeader(cookie)?.id===owner&&store.ownsSession(owner,profile,id)&&auth.canUseSource(owner,'local',profile)
-    const close=()=>{if(closed)return;closed=true;clearTimeout(timer);clearInterval(heartbeat);off();if(!res.writableEnded)res.end()}
-    const write=(value:string)=>{
-      if(closed||res.destroyed||!valid()){close();return false}
-      if(res.writableLength+Buffer.byteLength(value)>4*1024*1024){res.write('event: reset\ndata: {}\n\n');close();return false}
-      res.write(value);return true
-    }
-    const control=()=>({epoch,cursor,...transcripts.control(owner,profile,id)})
-    const flush=()=>{
-      clearTimeout(timer);timer=undefined
-      if(closed)return
-      if(!valid()){close();return}
-      if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
-      const events=transcripts.events(owner,profile,id,cursor)
-      for(const event of events){if(event.epoch!==epoch){write('event: reset\ndata: {}\n\n');close();return}if(!write(`id: ${epoch}:${event.cursor}\nevent: transcript\ndata: ${JSON.stringify(event)}\n\n`))return;cursor=event.cursor}
-      if(events.length)lastFlush=Date.now()
-      if(events.length===250){timer=setTimeout(flush,0);return}
-      // A control frame must never acknowledge events still waiting in another page.
-      if(cursor!==transcripts.cursor(owner,profile,id)){write('event: reset\ndata: {}\n\n');close();return}
-      if(!ready){ready=true;write(`event: ready\ndata: ${JSON.stringify(control())}\n\n`)}
-    }
-    const changed=()=>{
-      if(closed)return
-      const events=transcripts.events(owner,profile,id,cursor)
-      if(!events.length)return
-      if(events.some(event=>event.type!=='message.patch')||Date.now()-lastFlush>=33)flush()
-      else if(timer===undefined)timer=setTimeout(flush,Math.max(0,33-(Date.now()-lastFlush)))
-    }
-    ctx.respond=false
-    res.writeHead(200,{'Content-Type':'text/event-stream; charset=utf-8','Cache-Control':'no-store','X-Accel-Buffering':'no'})
-    res.flushHeaders();res.once('close',close);res.once('error',close)
-    off=transcripts.subscribe(changed)
-    flush()
-    if(closed)return
-    heartbeat=setInterval(()=>{
-      if(!valid()){close();return}
-      if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
-      flush()
-      if(!closed&&ready&&timer===undefined)write(`event: state\ndata: ${JSON.stringify(control())}\n\n`)
-    },5_000);heartbeat.unref()
-  })
-  return router
-}

+ 0 - 1209
src/server/chatTranscriptStore.ts

@@ -1,1209 +0,0 @@
-import { randomUUID } from 'node:crypto'
-import type { DatabaseSync } from 'node:sqlite'
-import {
-  CHAT_TRANSCRIPT_FEATURE,
-  type TranscriptEvent,
-  type TranscriptControlState,
-  type TranscriptMessage,
-  type TranscriptSnapshot,
-} from '../shared/chatTranscript.js'
-import { toolStatus } from '../shared/chatTools.js'
-import { isFinalChatResult } from './chatUnread.js'
-
-type Scope = [string, string, string]
-type Data = Record<string, any>
-interface TurnHead {
-  turn?: string
-  current?: string
-  preview?: boolean
-  terminal?: boolean
-  running: boolean
-  queued: boolean
-  queue: Array<{ turn: string; user: string; delivery: string }>
-  tools: Record<string, string>
-  pending: Record<string, { user: string; turn: string; previousRunning: boolean }>
-  pendingApproval?: Data | null
-  pendingClarification?: Data | null
-  liveStatus?: string | null
-  resyncing?: boolean
-  error?: string | null
-  stagedAttachments?: Data[]
-  localReadEstablished?: boolean
-  importedReadPosition?: number
-}
-const emptyHead = (): TurnHead => ({ running: false, queued: false, queue: [], tools: {}, pending: {} })
-const text = (p: Data): string => String(p.output ?? p.text ?? p.content ?? '')
-const controlState = (head: TurnHead): TranscriptControlState => ({
-  running: head.running,
-  queued: head.queued,
-  pendingApproval: head.pendingApproval ?? null,
-  pendingClarification: head.pendingClarification ?? null,
-  liveStatus: head.liveStatus ?? null,
-  error: head.error ?? null,
-})
-
-/** The sole ordinary-chat writer. Raw history is an import source, never a live projection. */
-export class ChatTranscriptStore {
-  readonly enabled = true
-  readonly epoch: string
-  private listeners = new Set<() => void>()
-  private scheduled = false
-  private closed = false
-  constructor(
-    readonly db: DatabaseSync,
-    readonly enrich: (
-      owner: string,
-      profile: string,
-      sessionId: string,
-      rows: Record<string, any>[],
-    ) => Record<string, any>[] = (_o, _p, _s, rows) => rows,
-  ) {
-    db.exec(`CREATE TABLE IF NOT EXISTS chat_transcript_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
-      CREATE TABLE IF NOT EXISTS chat_transcript_scopes(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_transcript_execution(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_transcript_messages(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,
-        id TEXT NOT NULL,seq INTEGER NOT NULL,revision INTEGER NOT NULL,data TEXT NOT NULL,deleted INTEGER NOT NULL DEFAULT 0,
-        PRIMARY KEY(owner,profile,session_id,id));
-      CREATE INDEX IF NOT EXISTS chat_transcript_order ON chat_transcript_messages(owner,profile,session_id,seq);
-      CREATE TABLE IF NOT EXISTS chat_transcript_aliases(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,
-        source TEXT NOT NULL,id TEXT NOT NULL,PRIMARY KEY(owner,profile,session_id,source));
-      CREATE TABLE IF NOT EXISTS chat_transcript_events(cursor INTEGER PRIMARY KEY AUTOINCREMENT,owner TEXT NOT NULL,
-        profile TEXT NOT NULL,session_id TEXT NOT NULL,type TEXT NOT NULL,data TEXT NOT NULL,created_at INTEGER NOT NULL);
-      CREATE INDEX IF NOT EXISTS chat_transcript_replay ON chat_transcript_events(owner,profile,session_id,cursor);`)
-    db.exec(`CREATE TABLE IF NOT EXISTS chat_transcript_heads(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,epoch TEXT NOT NULL,data TEXT NOT NULL,
-      PRIMARY KEY(owner,profile,session_id));
-      CREATE TABLE IF NOT EXISTS chat_transcript_archives(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,epoch TEXT NOT NULL,data TEXT NOT NULL,created_at INTEGER NOT NULL,
-      PRIMARY KEY(owner,profile,session_id,epoch));
-      CREATE TABLE IF NOT EXISTS chat_transcript_reads(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,id TEXT NOT NULL,PRIMARY KEY(owner,profile,session_id,id));
-      CREATE TABLE IF NOT EXISTS chat_transcript_source_cursors(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,runtime TEXT NOT NULL,epoch TEXT NOT NULL,seq INTEGER NOT NULL,
-      PRIMARY KEY(owner,profile,session_id,runtime,epoch));
-      CREATE TABLE IF NOT EXISTS chat_transcript_repairs(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,status TEXT NOT NULL DEFAULT 'pending',
-      PRIMARY KEY(owner,profile,session_id));`)
-    db.prepare("INSERT OR IGNORE INTO chat_transcript_meta VALUES('epoch',?)").run(randomUUID())
-    this.epoch = String(db.prepare("SELECT value FROM chat_transcript_meta WHERE key='epoch'").get()!.value)
-  }
-  close() {
-    this.closed = true
-    this.listeners.clear()
-  }
-  subscribe(listener: () => void) {
-    this.listeners.add(listener)
-    return () => {
-      this.listeners.delete(listener)
-    }
-  }
-  private notify() {
-    if (this.scheduled || this.closed) return
-    this.scheduled = true
-    // All enclosing cache savepoints finish synchronously. Read committed log
-    // rows in subscribers; a rolled-back notification therefore emits nothing.
-    queueMicrotask(() => {
-      this.scheduled = false
-      if (!this.closed)
-        for (const listener of this.listeners) {
-          try {
-            listener()
-          } catch {}
-        }
-    })
-  }
-  private event(
-    owner: string,
-    profile: string,
-    sessionId: string,
-    type: TranscriptEvent['type'],
-    data: unknown,
-  ) {
-    const previousCursor = this.cursor(owner, profile, sessionId)
-    const envelope = {
-      data,
-      previousCursor,
-      epoch: this.epochFor(owner, profile, sessionId),
-      total: this.total(owner, profile, sessionId),
-    }
-    this.db
-      .prepare(
-        'INSERT INTO chat_transcript_events(owner,profile,session_id,type,data,created_at) VALUES(?,?,?,?,?,?)',
-      )
-      .run(owner, profile, sessionId, type, JSON.stringify(envelope), Date.now())
-    this.notify()
-  }
-  private alias(owner: string, profile: string, sessionId: string, key: string): string | undefined {
-    return (
-      this.db
-        .prepare(
-          'SELECT id FROM chat_transcript_aliases WHERE owner=? AND profile=? AND session_id=? AND source=?',
-        )
-        .get(owner, profile, sessionId, key) as { id: string } | undefined
-    )?.id
-  }
-  promote(owner: string, profile: string, sessionId: string, oldSource: string, newSource: string) {
-    const id = this.alias(owner, profile, sessionId, `source:${oldSource}`)
-    if (id && !this.alias(owner, profile, sessionId, `source:${newSource}`))
-      this.db
-        .prepare('INSERT INTO chat_transcript_aliases VALUES(?,?,?,?,?)')
-        .run(owner, profile, sessionId, `source:${newSource}`, id)
-  }
-  upsert(
-    owner: string,
-    profile: string,
-    sessionId: string,
-    source: Record<string, any>,
-    position: number,
-  ): TranscriptMessage | undefined {
-    const sourceID = String(source.id ?? source.message_id ?? '')
-    if (!sourceID) return
-    const keys = [`source:${sourceID}`]
-    if (source.role === 'user' && source.client_message_id) keys.unshift(`client:${source.client_message_id}`)
-    if (source.role === 'tool' && source.tool_call_id)
-      keys.unshift(`tool:${source.turn_id ?? ''}:${source.tool_call_id}`)
-    const id =
-      this.message(owner, profile, sessionId, sourceID)?.id ??
-      keys.map((key) => this.alias(owner, profile, sessionId, key)).find(Boolean) ??
-      randomUUID()
-    for (const duplicate of new Set(
-      keys
-        .map((key) => this.alias(owner, profile, sessionId, key))
-        .filter((value): value is string => !!value && value !== id),
-    )) {
-      const old = this.db
-        .prepare(
-          'SELECT revision,deleted FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND id=?',
-        )
-        .get(owner, profile, sessionId, duplicate) as { revision: number; deleted: number } | undefined
-      this.db
-        .prepare(
-          'UPDATE chat_transcript_aliases SET id=? WHERE owner=? AND profile=? AND session_id=? AND id=?',
-        )
-        .run(id, owner, profile, sessionId, duplicate)
-      if (old && !old.deleted) {
-        this.db
-          .prepare(
-            'UPDATE chat_transcript_messages SET deleted=1,revision=revision+1 WHERE owner=? AND profile=? AND session_id=? AND id=?',
-          )
-          .run(owner, profile, sessionId, duplicate)
-        this.event(owner, profile, sessionId, 'message.deleted', {
-          id: duplicate,
-          revision: old.revision + 1,
-        })
-      }
-    }
-    const row = this.db
-      .prepare(
-        'SELECT data,revision,deleted FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND id=?',
-      )
-      .get(owner, profile, sessionId, id) as { data: string; revision: number; deleted: number } | undefined
-    const old: TranscriptMessage | undefined = row ? JSON.parse(row.data) : undefined
-    const next: TranscriptMessage = {
-      ...source,
-      id,
-      source_message_id: source.source_message_id ?? old?.source_message_id ?? sourceID,
-      seq: old?.seq ?? position + 1,
-      revision: row?.revision ?? 0,
-      role: String(source.role ?? 'assistant'),
-      content: source.content ?? '',
-      reasoning: String(source.reasoning ?? source.reasoning_content ?? ''),
-    }
-    if (!next.client_message_id && old?.client_message_id) next.client_message_id = old.client_message_id
-    for (const key of keys)
-      this.db
-        .prepare(
-          'INSERT INTO chat_transcript_aliases VALUES(?,?,?,?,?) ON CONFLICT(owner,profile,session_id,source) DO UPDATE SET id=excluded.id',
-        )
-        .run(owner, profile, sessionId, key, id)
-    if (old && !row?.deleted && JSON.stringify(old) === JSON.stringify(next)) return old
-    next.revision++
-    this.db
-      .prepare(
-        'INSERT INTO chat_transcript_messages VALUES(?,?,?,?,?,?,?,0) ON CONFLICT(owner,profile,session_id,id) DO UPDATE SET seq=excluded.seq,revision=excluded.revision,data=excluded.data,deleted=0',
-      )
-      .run(owner, profile, sessionId, id, next.seq, next.revision, JSON.stringify(next))
-    let patch: Record<string, unknown> | undefined
-    if (
-      old &&
-      !row?.deleted &&
-      old.status === 'streaming' &&
-      next.status === 'streaming' &&
-      typeof old.content === 'string' &&
-      typeof next.content === 'string' &&
-      next.content.startsWith(old.content) &&
-      next.reasoning!.startsWith(String(old.reasoning ?? ''))
-    ) {
-      const { content: a, reasoning: b, revision: c, ...oldMeta } = old
-      const { content: d, reasoning: e, revision: f, ...newMeta } = next
-      if (JSON.stringify(oldMeta) === JSON.stringify(newMeta))
-        patch = {
-          id,
-          seq: next.seq,
-          baseRevision: old.revision,
-          revision: next.revision,
-          contentAppend: next.content.slice(old.content.length),
-          reasoningAppend: next.reasoning!.slice(String(old.reasoning ?? '').length),
-        }
-    }
-    this.event(owner, profile, sessionId, patch ? 'message.patch' : 'message.upsert', patch ?? next)
-    return next
-  }
-  reconcile(owner: string, profile: string, sessionId: string) {
-    const scope: Scope = [owner, profile, sessionId]
-    this.seed(...scope)
-    if (this.head(...scope).running) throw new Error('Conversation is running; defer history repair')
-    this.importHistory(scope, true)
-  }
-  seed(owner: string, profile: string, sessionId: string) {
-    const scope: Scope = [owner, profile, sessionId]
-    if (
-      this.db
-        .prepare('SELECT 1 FROM chat_transcript_heads WHERE owner=? AND profile=? AND session_id=?')
-        .get(...scope)
-    )
-      return
-    this.db.exec('SAVEPOINT transcript_seed')
-    try {
-      this.archive(scope)
-      // v1 records were projections of the legacy writer. Preserve their source
-      // for verification; do not mix their IDs/checkpoints with a v2 generation.
-      for (const table of [
-        'chat_transcript_messages',
-        'chat_transcript_aliases',
-        'chat_transcript_execution',
-      ])
-        this.db.prepare(`DELETE FROM ${table} WHERE owner=? AND profile=? AND session_id=?`).run(...scope)
-      this.db
-        .prepare('INSERT INTO chat_transcript_heads VALUES(?,?,?,?,?)')
-        .run(...scope, randomUUID(), JSON.stringify(emptyHead()))
-      this.db.prepare('INSERT OR IGNORE INTO chat_transcript_scopes VALUES(?,?,?)').run(...scope)
-      this.importHistory(scope, false)
-      const active = this.all(...scope)
-        .reverse()
-        .find((m) => m.status === 'streaming' && m.role === 'assistant')
-      if (active)
-        this.db
-          .prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?')
-          .run(
-            JSON.stringify({ ...emptyHead(), turn: active.turn_id, current: active.id, running: true }),
-            ...scope,
-          )
-      if (this.total(...scope))
-        this.db
-          .prepare('INSERT OR IGNORE INTO chat_transcript_repairs VALUES(?,?,?,?)')
-          .run(...scope, 'pending')
-      this.db.exec('RELEASE transcript_seed')
-    } catch (error) {
-      this.db.exec('ROLLBACK TO transcript_seed; RELEASE transcript_seed')
-      throw error
-    }
-  }
-  sessionChanged(owner: string, profile: string, sessionId: string, data: Record<string, unknown>) {
-    this.reduce(owner, profile, sessionId, String(data.eventType), (data.payload ?? {}) as Data)
-  }
-  epochFor(...scope: Scope): string {
-    return String(
-      this.db
-        .prepare('SELECT epoch FROM chat_transcript_heads WHERE owner=? AND profile=? AND session_id=?')
-        .get(...scope)?.epoch ?? this.epoch,
-    )
-  }
-  head(...scope: Scope): TurnHead {
-    const row = this.db
-      .prepare('SELECT data FROM chat_transcript_heads WHERE owner=? AND profile=? AND session_id=?')
-      .get(...scope)
-    return row ? JSON.parse(String(row.data)) : emptyHead()
-  }
-  control(...scope: Scope): TranscriptControlState {
-    return controlState(this.head(...scope))
-  }
-  message(owner: string, profile: string, sessionId: string, id: string): TranscriptMessage | undefined {
-    const row = this.db
-      .prepare(
-        'SELECT data FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND id=? AND deleted=0',
-      )
-      .get(owner, profile, sessionId, id)
-    return row ? JSON.parse(String(row.data)) : undefined
-  }
-  resolveMessage(
-    owner: string,
-    profile: string,
-    sessionId: string,
-    id: string,
-  ): TranscriptMessage | undefined {
-    return (
-      this.message(owner, profile, sessionId, id) ??
-      this.message(owner, profile, sessionId, this.alias(owner, profile, sessionId, `source:${id}`) ?? '')
-    )
-  }
-  all(...scope: Scope): TranscriptMessage[] {
-    return this.db
-      .prepare(
-        'SELECT data FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0 ORDER BY seq,id',
-      )
-      .all(...scope)
-      .map((row) => JSON.parse(String(row.data)))
-  }
-  total(...scope: Scope): number {
-    return Number(
-      this.db
-        .prepare(
-          'SELECT COUNT(*) n FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0',
-        )
-        .get(...scope)!.n,
-    )
-  }
-  private parkOpenAnswer(scope: Scope, state: TurnHead) {
-    if (!state.current) return
-    const active = this.message(...scope, state.current)
-    const visible = Boolean(
-      active &&
-        (String(active.content ?? '').trim() ||
-          String(active.reasoning ?? '').trim() ||
-          (Array.isArray(active.tool_calls) && active.tool_calls.length)),
-    )
-    if (active && visible) this.put(scope, { ...active, status: 'complete', final_result: false })
-    else if (active) {
-      const revision = active.revision + 1
-      this.db
-        .prepare(
-          'UPDATE chat_transcript_messages SET deleted=1,revision=? WHERE owner=? AND profile=? AND session_id=? AND id=?',
-        )
-        .run(revision, ...scope, active.id)
-      this.event(...scope, 'message.deleted', { id: active.id, revision })
-    }
-    state.current = undefined
-    state.preview = false
-  }
-  /** A later completion often repeats the whole turn. Keep only the part written after this row. */
-  private placedOutput(scope: Scope, row: TranscriptMessage | undefined, turn: string | undefined, output: unknown, fallback: unknown): unknown {
-    if (typeof output !== 'string') return output ?? fallback
-    if (!output || !turn) return output || fallback
-    const prefix = this.all(...scope)
-      .filter((message) => message.role === 'assistant' && message.turn_id === turn && message.id !== row?.id && (!row || message.seq < row.seq))
-      .sort((left, right) => left.seq - right.seq)
-      .map((message) => String(message.content ?? ''))
-      .join('')
-    if (!prefix || !output.startsWith(prefix)) return output
-    return output.slice(prefix.length) || fallback
-  }
-  private put(scope: Scope, value: Data): TranscriptMessage {
-    const position = Number(
-      this.db
-        .prepare(
-          'SELECT COALESCE(MAX(seq),0) n FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=?',
-        )
-        .get(...scope)!.n,
-    )
-    return this.upsert(
-      ...scope,
-      { timestamp: Date.now() / 1000, ...value, id: value.id ?? randomUUID() },
-      position,
-    )!
-  }
-  private bind(scope: Scope, source: string, id: string) {
-    if (source)
-      this.db
-        .prepare(
-          'INSERT INTO chat_transcript_aliases VALUES(?,?,?,?,?) ON CONFLICT(owner,profile,session_id,source) DO UPDATE SET id=excluded.id',
-        )
-        .run(...scope, `source:${source}`, id)
-  }
-  archive(scope: Scope) {
-    const data = {
-      messages: this.all(...scope),
-      head: this.head(...scope),
-      rawMessages: this.db
-        .prepare(
-          'SELECT message_id,position,data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? ORDER BY position',
-        )
-        .all(...scope),
-      aliases: this.db
-        .prepare('SELECT source,id FROM chat_transcript_aliases WHERE owner=? AND profile=? AND session_id=?')
-        .all(...scope),
-    }
-    if (data.messages.length || data.rawMessages.length)
-      this.db
-        .prepare('INSERT OR IGNORE INTO chat_transcript_archives VALUES(?,?,?,?,?,?)')
-        .run(...scope, this.epochFor(...scope), JSON.stringify(data), Date.now())
-  }
-  private importHistory(scope: Scope, verified: boolean) {
-    if (verified) this.archive(scope)
-    const raw = this.db
-      .prepare(
-        'SELECT data,position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? ORDER BY position',
-      )
-      .all(...scope) as { data: string; position: number }[]
-    const incoming = this.enrich(
-      ...scope,
-      raw.map((row) => JSON.parse(row.data)),
-    )
-    const existing = this.all(...scope),
-      retained = new Set<string>(),
-      wasRead = new Set(
-        this.db
-          .prepare('SELECT id FROM chat_transcript_reads WHERE owner=? AND profile=? AND session_id=?')
-          .all(...scope)
-          .map((row) => String(row.id)),
-      )
-    if (
-      verified &&
-      existing.some(
-        (m) =>
-          m.role === 'user' &&
-          m.status === 'complete' &&
-          m.client_message_id &&
-          m.source_message_id.startsWith('user:') &&
-          !incoming.some(
-            (source) =>
-              source.role === 'user' &&
-              (source.client_message_id === m.client_message_id ||
-                String(source.id ?? source.message_id) === m.source_message_id),
-          ),
-      )
-    ) {
-      this.db
-        .prepare(
-          "INSERT INTO chat_transcript_repairs VALUES(?,?,?,'pending') ON CONFLICT(owner,profile,session_id) DO UPDATE SET status='pending'",
-        )
-        .run(...scope)
-      return // The archive is available for verification; ambiguous live turns remain untouched.
-    }
-    const legacyRead = this.db
-      .prepare(
-        'SELECT COALESCE(final_read_count,read_count) n,read_initialized FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?',
-      )
-      .get(...scope)
-    const boundary = legacyRead?.read_initialized ? Number(legacyRead.n) : Infinity
-    let turn = 'history:orphan',
-      ordinal = 0
-    for (const [index, source] of incoming.entries()) {
-      const sourceID = String(source.id ?? source.message_id ?? raw[index]!.position)
-      let known = this.resolveMessage(...scope, sourceID)
-      if (source.role === 'user' && source.client_message_id)
-        known ??= existing.find((m) => m.client_message_id === source.client_message_id)
-      if (source.role === 'user') turn = known?.turn_id ?? `history:${sourceID}`
-      const nextUser = incoming.findIndex((m, i) => i > index && m.role === 'user')
-      const rest = incoming.slice(index + 1, nextUser < 0 ? undefined : nextUser)
-      const final =
-        isFinalChatResult(source) &&
-        (source.final_result === true || !rest.some((message) => isFinalChatResult(message)))
-      // Only a proven user identity can associate an upstream final with the
-      // one live final of that turn. Content similarity is never an identity.
-      if (!known && verified && final) {
-        const candidates = existing.filter(
-          (m) => m.turn_id === turn && m.final_result === true && !retained.has(m.id),
-        )
-        if (candidates.length === 1) known = candidates[0]
-      }
-      const value = this.upsert(
-        ...scope,
-        {
-          ...source,
-          id: known?.id ?? sourceID,
-          source_message_id: sourceID,
-          turn_id: turn,
-          segment_kind:
-            source.role === 'user'
-              ? 'input'
-              : source.role === 'tool'
-                ? 'tool'
-                : final
-                  ? 'answer'
-                  : 'commentary',
-          final_result: final,
-        },
-        verified ? ordinal++ : raw[index]!.position,
-      )!
-      this.bind(scope, sourceID, value.id)
-      retained.add(value.id)
-      if (wasRead.has(known?.id ?? '') || raw[index]!.position < boundary)
-        this.db.prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)').run(...scope, value.id)
-    }
-    if (!verified) return
-    // An unconfirmed local send is not disproven by a history snapshot.
-    for (const message of existing)
-      if (message.role === 'user' && message.status === 'pending') retained.add(message.id)
-    let structural = [...retained].some((id) => !existing.some((message) => message.id === id))
-    for (const message of existing)
-      if (!retained.has(message.id)) {
-        structural = true
-        this.db
-          .prepare(
-            'UPDATE chat_transcript_messages SET deleted=1,revision=revision+1 WHERE owner=? AND profile=? AND session_id=? AND id=?',
-          )
-          .run(...scope, message.id)
-        this.event(...scope, 'message.deleted', { id: message.id, revision: message.revision + 1 })
-      }
-    // Rebuild order only at an explicit generation boundary. Old pages/events
-    // cannot be merged into this generation, even while a client is paging.
-    const ordered = [...retained]
-    for (const [index, id] of ordered.entries()) {
-      const message = this.message(...scope, id)!
-      if (message.seq !== index + 1) {
-        structural = true
-        this.db
-          .prepare(
-            'UPDATE chat_transcript_messages SET seq=?,revision=revision+1,data=? WHERE owner=? AND profile=? AND session_id=? AND id=?',
-          )
-          .run(
-            index + 1,
-            JSON.stringify({ ...message, seq: index + 1, revision: message.revision + 1 }),
-            ...scope,
-            id,
-          )
-      }
-    }
-    if (structural) {
-      this.db
-        .prepare('UPDATE chat_transcript_heads SET epoch=? WHERE owner=? AND profile=? AND session_id=?')
-        .run(randomUUID(), ...scope)
-      this.event(...scope, 'session.changed', {
-        eventType: 'history.rebuilt',
-        ...controlState(this.head(...scope)),
-      })
-    }
-    this.db
-      .prepare(
-        "UPDATE chat_transcript_repairs SET status='complete' WHERE owner=? AND profile=? AND session_id=?",
-      )
-      .run(...scope)
-  }
-  markRead(owner: string, profile: string, sessionId: string, count = Infinity) {
-    const head = this.head(owner, profile, sessionId)
-    head.localReadEstablished = true
-    this.db
-      .prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?')
-      .run(JSON.stringify(head), owner, profile, sessionId)
-    for (const m of this.all(owner, profile, sessionId))
-      if (m.seq <= count && isFinalChatResult(m))
-        this.db
-          .prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)')
-          .run(owner, profile, sessionId, m.id)
-  }
-  unreadMessages(...scope: Scope): TranscriptMessage[] {
-    this.unread(...scope)
-    return this.db.prepare(`SELECT m.data FROM chat_transcript_messages m LEFT JOIN chat_transcript_reads r USING(owner,profile,session_id,id)
-      WHERE m.owner=? AND m.profile=? AND m.session_id=? AND m.deleted=0 AND r.id IS NULL ORDER BY m.seq,m.id`).all(...scope)
-      .map(row=>JSON.parse(String(row.data)) as TranscriptMessage).filter(m=>m.final_result===true && isFinalChatResult(m))
-  }
-  markMessagesRead(owner:string,profile:string,sessionId:string,ids:string[]):void {
-    const selected=new Set(ids)
-    const head=this.head(owner,profile,sessionId);head.localReadEstablished=true
-    this.db.prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?').run(JSON.stringify(head),owner,profile,sessionId)
-    for(const m of this.unreadMessages(owner,profile,sessionId))if(selected.has(m.id))
-      this.db.prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)').run(owner,profile,sessionId,m.id)
-    this.notify()
-  }
-  unread(...scope: Scope): number {
-    // Legacy read cursors can finish importing after the initial local snapshot.
-    // Map only persisted source rows, never consume a live streaming result.
-    const legacy = this.db
-      .prepare(
-        'SELECT COALESCE(final_read_count,read_count) n FROM chat_local_state WHERE owner=? AND profile=? AND session_id=? AND read_initialized=1',
-      )
-      .get(...scope)
-    const head = this.head(...scope)
-    if (legacy && !head.localReadEstablished && Number(legacy.n) > (head.importedReadPosition ?? -1)) {
-      for (const row of this.db
-        .prepare(
-          'SELECT message_id FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND position<?',
-        )
-        .all(...scope, Number(legacy.n))) {
-        const m = this.resolveMessage(...scope, String(row.message_id))
-        if (m && isFinalChatResult(m))
-          this.db.prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)').run(...scope, m.id)
-      }
-      head.importedReadPosition = Number(legacy.n)
-      this.db
-        .prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?')
-        .run(JSON.stringify(head), ...scope)
-    }
-    return this.db
-      .prepare(
-        `SELECT m.data FROM chat_transcript_messages m LEFT JOIN chat_transcript_reads r USING(owner,profile,session_id,id)
-      WHERE m.owner=? AND m.profile=? AND m.session_id=? AND m.deleted=0 AND r.id IS NULL AND json_extract(m.data,'$.final_result')=1`,
-      )
-      .all(...scope)
-      .filter((row) => isFinalChatResult(JSON.parse(String(row.data)))).length
-  }
-  sourceCursor(owner: string, profile: string, sessionId: string, runtime: string, epoch: string): number {
-    return Number(
-      this.db
-        .prepare(
-          'SELECT seq FROM chat_transcript_source_cursors WHERE owner=? AND profile=? AND session_id=? AND runtime=? AND epoch=?',
-        )
-        .get(owner, profile, sessionId, runtime, epoch)?.seq ?? 0,
-    )
-  }
-  recordSource(scope: Scope, frame: Data) {
-    if (frame.epoch && frame.session_id && Number.isSafeInteger(frame.seq))
-      this.db
-        .prepare(
-          'INSERT INTO chat_transcript_source_cursors VALUES(?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,runtime,epoch) DO UPDATE SET seq=MAX(seq,excluded.seq)',
-        )
-        .run(...scope, frame.session_id, frame.epoch, frame.seq)
-  }
-
-  /** Caller holds the transaction containing the input receipt and raw event. */
-  reduce(owner: string, profile: string, sessionId: string, type: string, p: Data) {
-    type =
-      (
-        {
-          'message.started': 'message.start',
-          'message.completed': 'message.complete',
-          'run.complete': 'run.completed',
-          'reasoning.completed': 'reasoning.complete',
-          'peer.user.message': 'message.user',
-          peer_user_message: 'message.user',
-          'run.peer_user_message': 'message.user',
-        } as Record<string, string>
-      )[type] ?? type
-    const scope: Scope = [owner, profile, sessionId]
-    this.seed(...scope)
-    const state = this.head(...scope)
-    const before = JSON.stringify(state)
-    const sourceID = String(p.message_id ?? p.message?.id ?? '')
-    const upstreamRun = String(p.run_id ?? p.runId ?? p.inflight?.run_id ?? '')
-    const knownTurn = upstreamRun ? this.alias(...scope, `source:turn:${upstreamRun}`) : undefined
-    if (
-      knownTurn &&
-      (knownTurn !== state.turn || state.terminal) &&
-      ['run.started', 'run.start', 'message.start'].includes(type)
-    )
-      return
-    const known =
-      (sourceID ? this.resolveMessage(...scope, sourceID) : undefined) ??
-      (knownTurn && knownTurn !== state.turn
-        ? this.all(...scope)
-            .reverse()
-            .find((m) => m.turn_id === knownTurn && m.role === 'assistant')
-        : undefined)
-    if (
-      known &&
-      state.turn &&
-      known.turn_id !== state.turn &&
-      ['message.complete', 'run.completed', 'message.delta', 'message.interim'].includes(type)
-    ) {
-      const terminal = ['message.complete', 'run.completed'].includes(type)
-      this.put(scope, {
-        ...known,
-        content:
-          type === 'message.delta'
-            ? String(known.content ?? '') + String(p.delta ?? p.text ?? '')
-            : text(p) || known.content,
-        ...(terminal ? { status: 'complete', final_result: true } : {}),
-      })
-      return
-    }
-    const current = () => (state.current ? this.message(...scope, state.current) : undefined)
-    const begin = () => {
-      if (!state.turn || state.terminal) {
-        const queued = state.queue.shift()
-        state.turn = queued?.turn ?? randomUUID()
-        state.current = undefined
-        state.preview = false
-        state.terminal = false
-        state.tools = {}
-        state.error = null
-      }
-      if (upstreamRun) this.bind(scope, `turn:${upstreamRun}`, state.turn!)
-      state.running = true
-      state.queued = state.queue.length > 0
-    }
-    const assistant = (): TranscriptMessage => {
-      begin()
-      const old = current()
-      if (old) return old
-      const created = this.put(scope, {
-        role: 'assistant',
-        turn_id: state.turn,
-        segment_kind: 'answer',
-        content: '',
-        reasoning: '',
-        status: 'streaming',
-        final_result: false,
-      })
-      state.current = created.id
-      return created
-    }
-    const saveAssistant = (value: Data) => {
-      const old = assistant(),
-        source = String(p.message_id ?? p.message?.id ?? '')
-      const attachments = p.attachments ?? p.message?.attachments
-      const saved = this.put(scope, {
-        ...old,
-        ...value,
-        ...(attachments ? { attachments } : {}),
-        ...(source ? { source_message_id: source } : {}),
-      })
-      this.bind(scope, source, saved.id)
-      return saved
-    }
-    if (type === 'command.submitted') {
-      const delivery = String(p.delivery_id),
-        client = String(p.client_message_id ?? delivery.replace(/^(web|ios|android):prompt:/, ''))
-      if (!this.alias(...scope, `client:${client}`)) {
-        const previousRunning = state.running,
-          steer = p.method === 'session.steer' && state.running
-        // The open answer already has a sequence. Parking it here lets the
-        // inserted user row land at this moment, and the rest of the reply
-        // continues in a later row.
-        if (steer) this.parkOpenAnswer(scope, state)
-        const turn = steer ? state.turn! : randomUUID()
-        const user = this.put(scope, {
-          id: `user:${delivery}`,
-          role: 'user',
-          turn_id: turn,
-          segment_kind: 'input',
-          client_message_id: client,
-          content: p.text ?? '',
-          status: 'pending',
-          ...(state.stagedAttachments?.length ? { attachments: state.stagedAttachments } : {}),
-        })
-        state.stagedAttachments = []
-        state.error = null
-        state.pending[delivery] = { user: user.id, turn, previousRunning }
-        if (previousRunning && !steer) {
-          state.queue.push({ turn, user: user.id, delivery })
-          state.queued = true
-        } else if (!steer) {
-          state.turn = turn
-          state.current = undefined
-          state.preview = false
-          state.terminal = false
-          state.tools = {}
-        }
-        state.running = true
-      }
-    } else if (type === 'command.confirmed' || type === 'command.rejected') {
-      const pending = state.pending[String(p.delivery_id)]
-      if (pending) {
-        const user = this.message(...scope, pending.user)
-        if (user)
-          this.put(scope, {
-            ...user,
-            status: type === 'command.rejected' ? 'failed' : 'complete',
-            ...(p.error ? { error: p.error } : {}),
-          })
-        if (type === 'command.rejected') {
-          state.queue = state.queue.filter((q) => q.delivery !== p.delivery_id)
-          if (state.turn === pending.turn && !state.current) state.terminal = true
-          state.running = !state.terminal || state.queue.length > 0
-        } else if (p.status !== 'queued') {
-          // The upstream accepted this prompt for immediate execution. A local
-          // queue entry only exists because `state.running` looked busy at
-          // submit time (e.g. a stale background flag or a missed terminal);
-          // the upstream knows nothing about that entry, so nothing would ever
-          // drain it except a later `session.resume`. Drop it now and adopt
-          // its turn so the imminent run events attach to this user row.
-          const queued = state.queue.filter((q) => q.delivery !== p.delivery_id)
-          if (queued.length !== state.queue.length) {
-            state.queue = queued
-            if (state.terminal) {
-              state.turn = pending.turn
-              state.current = undefined
-              state.preview = false
-              state.terminal = false
-              state.tools = {}
-            }
-          }
-        }
-        delete state.pending[String(p.delivery_id)]
-        state.queued = state.queue.length > 0
-      }
-    } else if (type === 'message.user') {
-      const client = String(p.client_message_id ?? p.queue_id ?? '').replace(/^(web|ios|android):prompt:/, '')
-      const source = String(p.message_id ?? p.id ?? '')
-      const old =
-        (client
-          ? this.all(...scope).find((m) => m.role === 'user' && m.client_message_id === client)
-          : undefined) ?? (source ? this.resolveMessage(...scope, source) : undefined)
-      if (source || client) {
-        const turn = old?.turn_id ?? (p.steer ? state.turn : undefined) ?? randomUUID()
-        const user = this.put(scope, {
-          ...old,
-          id: old?.id || source || randomUUID(),
-          role: 'user',
-          turn_id: turn,
-          segment_kind: 'input',
-          content: p.text ?? p.content ?? '',
-          status: p.status === 'failed' ? 'failed' : 'complete',
-          ...(client ? { client_message_id: client } : {}),
-        })
-        if (!old && p.status !== 'failed') {
-          if (state.running && !p.steer) {
-            state.queue.push({ turn, user: user.id, delivery: client || source })
-            state.queued = true
-          } else if (!p.steer) {
-            state.turn = turn
-            state.current = undefined
-            state.terminal = false
-            state.preview = false
-          }
-        }
-      }
-    } else if (['message.start', 'run.started', 'run.start'].includes(type)) {
-      const old = current()
-      if (
-        type === 'message.start' &&
-        sourceID &&
-        old &&
-        old.source_message_id !== sourceID &&
-        !this.resolveMessage(...scope, sourceID) &&
-        (old.content || old.reasoning || old.tool_calls)
-      ) {
-        this.put(scope, { ...old, status: 'complete', segment_kind: 'commentary', final_result: false })
-        state.current = undefined
-        state.preview = false
-      }
-      const row = assistant()
-      if (sourceID) {
-        this.bind(scope, sourceID, row.id)
-        this.put(scope, { ...row, source_message_id: sourceID })
-      }
-    } else if (['message.delta', 'content.delta', 'assistant.delta'].includes(type) && !state.resyncing) {
-      if (state.preview) {
-        state.current = undefined
-        state.preview = false
-      }
-      const old = assistant()
-      saveAssistant({
-        content:
-          String(old.content ?? '') +
-          String(p.delta ?? p.text_delta ?? p.content_delta ?? p.text ?? p.content ?? ''),
-        status: 'streaming',
-      })
-    } else if (type === 'message.interim') {
-      saveAssistant({
-        content: text(p) || current()?.content || '',
-        status: 'streaming',
-        segment_kind: 'commentary',
-        final_result: false,
-      })
-      state.preview = true
-    } else if (type.startsWith('reasoning.') || type === 'thinking.delta' || type === 'thinking.complete') {
-      const old = assistant(),
-        full = p.reasoning ?? p.text ?? p.content ?? p.delta ?? ''
-      saveAssistant({
-        reasoning: type.endsWith('delta')
-          ? String(old.reasoning ?? '') + String(p.delta ?? full)
-          : String(full),
-      })
-    } else if (type.startsWith('tool.')) {
-      const toolID = String(p.tool_call_id ?? p.tool_id ?? p.id ?? '')
-      if (toolID) {
-        let target = state.tools[toolID] ? this.message(...scope, state.tools[toolID]!) : undefined
-        if (!target && /complete|failed/.test(type)) {
-          const candidates = this.all(...scope).filter((m) =>
-            (m.tool_calls as Data[] | undefined)?.some((t) => t.id === toolID),
-          )
-          if (candidates.length === 1) target = candidates[0]
-        }
-        if (!target) {
-          if (state.preview) {
-            const old = current()
-            if (old) this.put(scope, { ...old, status: 'complete' })
-            state.current = undefined
-            state.preview = false
-          }
-          target = assistant()
-          state.tools[toolID] = target.id
-        }
-        const tools = Array.isArray(target.tool_calls) ? ([...target.tool_calls] as Data[]) : [],
-          index = tools.findIndex((t) => t.id === toolID)
-        const old = index < 0 ? {} : tools[index]!,
-          status = toolStatus(type, p.result ?? p.output, p.error)
-        const tool = {
-          ...old,
-          ...p,
-          id: toolID,
-          status: ['completed', 'failed'].includes(old.status) && status === 'running' ? old.status : status,
-        }
-        if (index < 0) tools.push(tool)
-        else tools[index] = tool
-        this.put(scope, { ...target, tool_calls: tools })
-      } else state.liveStatus = p.name ? `正在准备 ${p.name}` : state.liveStatus
-    } else if (['message.complete', 'run.completed', 'run.complete', 'run.failed', 'error'].includes(type)) {
-      // A replayed terminal snapshot updates the terminal slot. It never starts
-      // another turn (the next run.started/delta owns advancing the queue).
-      // Hermes also closes each model segment with message.complete, including
-      // a tool round. That is not the end of the user-visible turn.
-      const old = current()
-      const wasTerminal = state.terminal
-      const failed =
-        ['run.failed', 'error'].includes(type) || p.error || ['failed', 'error'].includes(p.status)
-      const interrupted = ['interrupted', 'cancelled', 'canceled'].includes(p.status)
-      const finish = String(
-        p.finish_reason ?? p.finishReason ?? p.message?.finish_reason ?? p.message?.finishReason ?? '',
-      ).toLowerCase()
-      const payloadCalls = p.tool_calls ?? p.message?.tool_calls
-      const openTools =
-        !!state.turn &&
-        this.all(...scope).some(
-          (m) =>
-            m.turn_id === state.turn &&
-            (m.tool_calls as Data[] | undefined)?.some((t) =>
-              ['running', 'pending'].includes(String(t.status)),
-            ),
-        )
-      const explicitStop = ['stop', 'end', 'end_turn', 'length', 'content_filter'].includes(finish)
-      const toolRound =
-        ['tool_calls', 'tool_use', 'function_call'].includes(finish) ||
-        (Array.isArray(payloadCalls) && payloadCalls.length > 0)
-      const continues =
-        type === 'message.complete' && !failed && !interrupted && !explicitStop && (toolRound || openTools)
-      const output = p.output ?? p.text ?? p.content ?? p.message?.content
-      if (continues) {
-        const placed = this.placedOutput(scope, old, state.turn, output, old?.content ?? '')
-        const hasPlaced = typeof placed === 'string' ? placed.length > 0 : Boolean(placed)
-        if (old || hasPlaced || p.attachments)
-          saveAssistant({
-            content: placed,
-            status: 'streaming',
-            final_result: false,
-          })
-        state.running = true
-        state.terminal = false
-        state.queued = state.queue.length > 0 || Number(p.queue_remaining ?? 0) > 0
-      } else {
-      state.terminal = false
-      const placed = this.placedOutput(scope, old, state.turn, output, old?.content ?? '')
-      const hasPlaced = typeof placed === 'string' ? placed.length > 0 : Boolean(placed)
-      if (old || hasPlaced || p.attachments)
-        saveAssistant({
-          content: placed,
-          status: failed ? 'failed' : interrupted ? 'interrupted' : 'complete',
-          segment_kind: 'answer',
-          final_result: !failed && !interrupted,
-          ...(failed ? { error: p.error ?? p.message ?? '运行失败' } : {}),
-        })
-      state.error = failed ? String(p.error ?? p.message ?? '运行失败') : null
-      for (const m of this.all(...scope))
-        if (m.turn_id === state.turn) {
-          const calls = (m.tool_calls as Data[] | undefined)?.map((t) =>
-            ['running', 'pending'].includes(t.status) ? { ...t, status: 'interrupted' } : t,
-          )
-          if (m.status === 'streaming' || calls)
-            this.put(scope, {
-              ...m,
-              status: m.status === 'streaming' ? 'complete' : m.status,
-              ...(calls ? { tool_calls: calls } : {}),
-            })
-        }
-      state.terminal = true
-      state.preview = false
-      state.queued = state.queue.length > 0 || Number(p.queue_remaining ?? 0) > 0
-      state.running = state.queued || Number(p.background_pending ?? 0) > 0
-      state.resyncing = false
-      state.pendingApproval = null
-      state.pendingClarification = null
-      state.liveStatus = null
-      if (wasTerminal && state.queue.length === 0) state.running = false
-      }
-    } else if (type === 'route.resumed') {
-      const inflight = p.inflight ?? {},
-        running = p.running === true || p.info?.running === true || inflight.streaming === true
-      if (running) {
-        const hadCurrent = !!current()
-        begin()
-        if (typeof inflight.assistant === 'string' && (!hadCurrent || state.resyncing))
-          saveAssistant({ content: inflight.assistant, status: 'streaming' })
-        else assistant()
-      } else if (p.running === false) {
-        const old = current()
-        if (old && typeof inflight.assistant === 'string' && inflight.assistant)
-          this.put(scope, {
-            ...old,
-            content: inflight.assistant,
-            status: 'complete',
-            final_result: true,
-            segment_kind: 'answer',
-          })
-        state.running = false
-        state.terminal = true
-        state.resyncing = false
-        state.queued = Boolean(p.queued?.user) || Number(p.queue_length ?? p.info?.queue_length ?? 0) > 0
-        if (!state.queued) state.queue = []
-        for (const m of this.all(...scope))
-          if (m.status === 'streaming') this.put(scope, { ...m, status: 'complete' })
-      }
-      state.pendingApproval = p.pending_approval ?? inflight.pending_approval ?? null
-      state.pendingClarification = p.pending_clarify ?? inflight.pending_clarify ?? null
-    } else if (type === 'attachment.staged') {
-      const attachment = p.attachment ?? p.file ?? p
-      if (attachment.path || attachment.url)
-        state.stagedAttachments = [...(state.stagedAttachments ?? []), attachment]
-    } else if (type === 'gateway.reset') {
-      // Without a replay barrier, a resume body can overlap deferred deltas.
-      // Accept full snapshots until the terminal boundary, never append bytes
-      // whose position cannot be established. The idle history job fills gaps.
-      state.resyncing = true
-      state.liveStatus = '正在恢复回复'
-    } else if (['approval.request', 'approval.requested'].includes(type)) {
-      state.pendingApproval = p
-      state.running = true
-    } else if (type === 'approval.resolved') state.pendingApproval = null
-    else if (['clarify.request', 'clarify.requested'].includes(type)) {
-      state.pendingClarification = p
-      state.running = true
-    } else if (['clarify.resolved', 'clarify.expire'].includes(type)) state.pendingClarification = null
-    else if (type === 'status.update') {
-      state.liveStatus = text(p)
-      if (p.kind === 'warn') {
-        const source = `status:${state.turn ?? 'session'}:warning`
-        this.put(scope, {
-          id: this.alias(...scope, `source:${source}`) ?? source,
-          role: 'system',
-          turn_id: state.turn,
-          segment_kind: 'system',
-          content: text(p),
-          status: 'complete',
-          display_kind: 'live_warning',
-          final_result: false,
-        })
-      }
-    } else if (
-      [
-        'compression.started',
-        'compression.completed',
-        'session.command',
-        'session.workspace.updated',
-      ].includes(type)
-    ) {
-      const source = `system:${state.turn ?? 'session'}:${type.startsWith('compression.') ? 'compression' : type}`
-      const content =
-        type === 'compression.started'
-          ? '正在压缩上下文…'
-          : type === 'compression.completed'
-            ? '上下文压缩完成,继续回复'
-            : text(p)
-      if (content)
-        this.put(scope, {
-          id: this.alias(...scope, `source:${source}`) ?? source,
-          role: 'system',
-          turn_id: state.turn,
-          segment_kind: 'system',
-          content,
-          status: type.endsWith('started') ? 'streaming' : 'complete',
-          display_kind: type.startsWith('compression.') ? 'live_compression' : 'live_status',
-          final_result: false,
-        })
-    }
-    if (type === 'session.info') state.liveStatus = state.liveStatus ?? null
-    this.db
-      .prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?')
-      .run(JSON.stringify(state), ...scope)
-    if (before !== JSON.stringify(state) || ['session.info', 'history.synced'].includes(type))
-      this.event(...scope, 'session.changed', {
-        eventType: type,
-        payload: type === 'session.info' ? p : {},
-        ...controlState(state),
-      })
-  }
-  migrate(owner: string, profile: string, oldID: string, newID: string) {
-    this.event(owner, profile, oldID, 'session.migrated', { sessionId: newID })
-    for (const table of [
-      'chat_transcript_messages',
-      'chat_transcript_aliases',
-      'chat_transcript_scopes',
-      'chat_transcript_execution',
-      'chat_transcript_heads',
-      'chat_transcript_reads',
-      'chat_transcript_source_cursors',
-      'chat_transcript_repairs',
-      'chat_transcript_archives',
-    ])
-      this.db
-        .prepare(`UPDATE ${table} SET session_id=? WHERE owner=? AND profile=? AND session_id=?`)
-        .run(newID, owner, profile, oldID)
-  }
-  remove(owner: string, profile: string, sessionId: string) {
-    this.event(owner, profile, sessionId, 'session.deleted', { sessionId })
-    for (const table of [
-      'chat_transcript_messages',
-      'chat_transcript_aliases',
-      'chat_transcript_scopes',
-      'chat_transcript_execution',
-      'chat_transcript_heads',
-      'chat_transcript_reads',
-      'chat_transcript_source_cursors',
-      'chat_transcript_repairs',
-      'chat_transcript_archives',
-    ])
-      this.db
-        .prepare(`DELETE FROM ${table} WHERE owner=? AND profile=? AND session_id=?`)
-        .run(owner, profile, sessionId)
-  }
-  cursor(owner: string, profile: string, sessionId: string): number {
-    return Number(
-      this.db
-        .prepare(
-          'SELECT COALESCE(MAX(cursor),0) cursor FROM chat_transcript_events WHERE owner=? AND profile=? AND session_id=?',
-        )
-        .get(owner, profile, sessionId)!.cursor,
-    )
-  }
-  events(owner: string, profile: string, sessionId: string, after: number, limit = 250): TranscriptEvent[] {
-    return (
-      this.db
-        .prepare(
-          'SELECT cursor,type,data FROM chat_transcript_events WHERE owner=? AND profile=? AND session_id=? AND cursor>? ORDER BY cursor LIMIT ?',
-        )
-        .all(owner, profile, sessionId, after, limit) as {
-        cursor: number
-        type: TranscriptEvent['type']
-        data: string
-      }[]
-    ).map((row) => ({ ...row, profile, sessionId, ...JSON.parse(row.data) }))
-  }
-  snapshot(
-    owner: string,
-    profile: string,
-    sessionId: string,
-    session: Record<string, unknown>,
-    state: string,
-    before = Number.MAX_SAFE_INTEGER,
-    limit = 150,
-  ): TranscriptSnapshot {
-    const run = this.control(owner, profile, sessionId)
-    const coverage = this.db
-      .prepare(
-        'SELECT complete,message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?',
-      )
-      .get(owner, profile, sessionId)
-    const incomplete = coverage?.complete === 0
-    const rows = this.db
-      .prepare(
-        'SELECT data FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0 AND seq<? ORDER BY seq DESC,id DESC LIMIT ?',
-      )
-      .all(owner, profile, sessionId, before, limit + 1) as { data: string }[]
-    return {
-      protocol: CHAT_TRANSCRIPT_FEATURE,
-      epoch: this.epochFor(owner, profile, sessionId),
-      cursor: this.cursor(owner, profile, sessionId),
-      profile,
-      sessionId,
-      running: run.running,
-      queued: run.queued,
-      pendingApproval: run.pendingApproval,
-      pendingClarification: run.pendingClarification,
-      liveStatus: run.liveStatus,
-      error: run.error,
-      messages: rows
-        .slice(0, limit)
-        .reverse()
-        .map((row) => JSON.parse(row.data)),
-      session,
-      state,
-      deletedIds: (
-        this.db
-          .prepare(
-            'SELECT id FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=1',
-          )
-          .all(owner, profile, sessionId) as { id: string }[]
-      ).map((row) => row.id),
-      hasOlder: rows.length > limit || (incomplete && before > 1),
-      total: Math.max(
-        this.total(owner, profile, sessionId),
-        incomplete ? Number(coverage?.message_total ?? 0) : 0,
-      ),
-    }
-  }
-}

+ 0 - 26
src/server/chatUnread.ts

@@ -1,26 +0,0 @@
-/** List badges count completed results; transport rows and progress never count. */
-export function isFinalChatResult(message: Record<string, any>): boolean {
-  if (message.role !== 'assistant' || message.error || message.is_streaming || message.isStreaming) return false
-  if (message.final_result === false || message.is_interim || message.display_kind || message.displayKind) return false
-  const status = message.status ?? message.finish_reason ?? message.finishReason
-  if (['streaming', 'pending', 'running', 'interim', 'failed', 'error', 'cancelled', 'interrupted', 'tool_calls', 'function_call'].includes(status)) return false
-  // Live projections retain tool traces on the final answer. Historical tool
-  // invocation rows have no explicit completion marker and must be excluded.
-  if (message.final_result !== true) {
-    let tools = message.tool_calls ?? message.toolCalls ?? message.tools
-    if (typeof tools === 'string') {
-      try { tools = JSON.parse(tools) } catch { return false }
-    }
-    if ((Array.isArray(tools) ? tools.length > 0 : !!tools) || message.function_call) return false
-    if (Array.isArray(message.content) && message.content.some(block =>
-      ['tool_use', 'tool_call', 'function_call'].includes(block?.type))) return false
-  }
-  const content = message.content ?? message.text
-  const visible = (value: unknown) => typeof value === 'string'
-    && value.replace(/<(think|thinking|reasoning)\b[^>]*>[\s\S]*?(?:<\/\1>|$)/gi, '').trim().length > 0
-  return visible(content)
-    || (Array.isArray(content) && content.some(block => block && (
-      ['text', 'output_text'].includes(block.type) && visible(block.text)
-      || ['image', 'image_url', 'file', 'audio', 'video'].includes(block.type))))
-    || (Array.isArray(message.attachments) && message.attachments.length > 0)
-}

+ 0 - 11
src/server/config.ts

@@ -11,7 +11,6 @@ import {
   loadAllowedHostsConfiguration,
   type AllowedHostsConfigurationSnapshot,
 } from './allowedHostsConfiguration.js'
-import type { ChatCacheMode } from './chatCache.js'
 import {parseComposeDesktops} from './composeDesktops.js'
 import type {ComposeDesktop} from '../shared/composeDesktops.js'
 export { DEFAULT_APNS_TOPIC } from './apnsConfiguration.js'
@@ -60,7 +59,6 @@ export interface ServerConfig {
   fcmConfigurationError?: string
   fcmSettings?: FCMConfigurationSnapshot
   allowedHostsSettings?: AllowedHostsConfigurationSnapshot
-  chatCacheMode?: ChatCacheMode
 }
 
 export { DEFAULT_RELEASE_SOURCE as DEFAULT_YAOYAO_RELEASE_SOURCE } from '../../bin/lib/release-source.mjs'
@@ -77,13 +75,6 @@ function parsePort(value: string | undefined): number {
   return port
 }
 
-function parseChatCacheMode(value: string | undefined): ChatCacheMode {
-  const mode = value?.trim() || 'prefer-local'
-  if (!['upstream-only', 'shadow', 'prefer-local'].includes(mode)) {
-    throw new Error('HERMES_YAOYAO_CHAT_CACHE_MODE must be upstream-only, shadow, or prefer-local')
-  }
-  return mode as ChatCacheMode
-}
 
 function parseUpstream(value: string | undefined): URL {
   const upstream = new URL(value ?? 'http://127.0.0.1:9119')
@@ -171,7 +162,6 @@ export function loadServerConfig(
   const production = env.NODE_ENV === 'production'
   const localVmHost = env.HERMES_YAOYAO_LOCAL_VM_HOST?.trim() || 'server'
   if(localVmHost!=='server'&&localVmHost!=='runner')throw new Error('HERMES_YAOYAO_LOCAL_VM_HOST must be server or runner')
-  const chatCacheMode = parseChatCacheMode(env.HERMES_YAOYAO_CHAT_CACHE_MODE)
   const releaseSource = parseReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE)
   const releaseRoot = resolve(env.HERMES_YAOYAO_RELEASE_ROOT?.trim() || `${homedir()}/.local/share/hermes-yaoyao`)
   const allowRemoteUpdate = flag(env.HERMES_YAOYAO_ALLOW_REMOTE_UPDATE)
@@ -213,7 +203,6 @@ export function loadServerConfig(
     production,
     localVmHost,
     composeDesktops:parseComposeDesktops(env.HERMES_YAOYAO_COMPOSE_DESKTOPS),
-    chatCacheMode,
     releaseSource,
     releaseRoot,
     allowRemoteUpdate,

+ 0 - 62
src/server/hermes/socket.ts

@@ -1,62 +0,0 @@
-import { EventEmitter } from 'node:events'
-import { randomUUID } from 'node:crypto'
-import { HttpError } from '../errors.js'
-import type { EmbeddedGateway, GatewayChannel } from './gateway.js'
-
-const OPEN = 1, CLOSED = 3
-/** One replay epoch per server process: a restart forces clients to resynchronise from transcripts. */
-const EPOCH = randomUUID()
-
-/**
- * WebSocket-shaped adapter over the in-process gateway, so the realtime broker keeps its JSON-RPC
- * framing (`{id, method, params}` → `{id, result|error}`, events as `{method: 'event', params}`)
- * without a network hop. Only the subset of `ws` the broker uses is implemented.
- */
-export class EmbeddedSocket extends EventEmitter {
-  static readonly OPEN = OPEN
-  readyState = OPEN
-  readonly bufferedAmount = 0
-  private readonly channel: GatewayChannel
-
-  constructor(gateway: EmbeddedGateway) {
-    super()
-    this.channel = gateway.open(frame => {
-      if (this.readyState !== OPEN) return
-      const params = frame.type === 'gateway.ready' ? { ...frame, payload: { ...(frame.payload ?? {}), replay_epoch: EPOCH } } : frame
-      this.deliver({ jsonrpc: '2.0', method: 'event', params })
-    }, () => this.terminate())
-  }
-
-  private deliver(value: unknown) {
-    const data = Buffer.from(JSON.stringify(value))
-    queueMicrotask(() => { if (this.readyState === OPEN) this.emit('message', data, false) })
-  }
-
-  send(data: string, callback?: (error?: Error) => void): void {
-    if (this.readyState !== OPEN) { callback?.(new Error('socket closed')); return }
-    let frame: { id?: unknown; method?: unknown; params?: unknown }
-    try { frame = JSON.parse(data) } catch { callback?.(new Error('invalid frame')); return }
-    callback?.()
-    if (typeof frame.method !== 'string') return
-    const id = frame.id
-    void this.channel.rpc(frame.method, (frame.params ?? {}) as Record<string, unknown>).then(
-      result => { if (id !== undefined) this.deliver({ jsonrpc: '2.0', id, result }) },
-      error => {
-        if (id === undefined) return
-        const code = error instanceof HttpError && error.status === 404 ? 'session_not_found' : -32000
-        this.deliver({ jsonrpc: '2.0', id, error: { code, message: error instanceof Error ? error.message : 'Hermes 请求失败' } })
-      },
-    )
-  }
-
-  ping(): void { queueMicrotask(() => { if (this.readyState === OPEN) this.emit('pong') }) }
-
-  terminate(): void {
-    if (this.readyState === CLOSED) return
-    this.readyState = CLOSED
-    this.channel.close()
-    queueMicrotask(() => this.emit('close'))
-  }
-
-  close(): void { this.terminate() }
-}

+ 0 - 90
src/server/hermesBotRelay.ts

@@ -1,90 +0,0 @@
-import type Koa from 'koa'
-import { Readable } from 'node:stream'
-import type { LocalAuthStore } from './localAuth.js'
-import type { CsrfProtection } from './security.js'
-import { WorkspaceGateway, type WorkspaceNodes, type WorkspaceNode } from './workspaceGateway.js'
-import { HttpError } from './errors.js'
-
-/** Native Hermes transport, scoped to a primary account's paired child node.
- * Never imports a Profile or creates a workspace Agent/group. */
-export function hermesBotRelay(nodes: WorkspaceNodes, auth: LocalAuthStore, csrf: CsrfProtection): Koa.Middleware {
-  return async (ctx, next) => {
-    const native = /^(?:\/api\/app\/hermes-bot\/local|\/node\/([0-9a-f-]{36})\/api\/hermes-bot)(\/api\/.*)$/.exec(ctx.path)
-    if (native) {
-      const path = native[2]!
-      const allowed = path.startsWith('/api/realtime/') || (ctx.method === 'GET' &&
-        /^\/api\/(?:profiles(?:\/sessions)?|sessions(?:\/[^/]+(?:\/messages)?)?|files\/download)$/.test(path))
-      if (!allowed) throw new HttpError(403, '不支持的原生机器人操作', 'hermes_bot_path_forbidden')
-      if (!native[1]) auth.require(ctx)
-      ctx.state.hermesBotNative = true
-      ctx.path = native[1] ? `/node/${native[1]}${path}` : path
-      return next()
-    }
-    if (ctx.path === '/api/app/hermes-bot/roster' && ctx.method === 'GET') {
-      const owner = auth.require(ctx).id
-      const nodesList = nodes.store.list<WorkspaceNode>(owner, 'node').filter(n => n.transport === 'paired-web')
-      const roster = await Promise.all(nodesList.map(async node => {
-        const gateway = new WorkspaceGateway(nodes.target(owner, node.id))
-        try {
-          await gateway.connect()
-          const snapshot = await gateway.rpc('profiles.list', {include_sessions: true})
-          return {id: node.id, name: node.name, remoteNodeId: node.remoteNodeId, fingerprint: node.fingerprint, snapshot}
-        } catch { return {id: node.id, name: node.name, remoteNodeId: node.remoteNodeId, error: '节点不可用,请检查连接或扫码授权'} }
-        finally { gateway.close() }
-      }))
-      ctx.set('Cache-Control', 'no-store'); ctx.body = {nodes: roster}; return
-    }
-    const match = /^\/api\/app\/hermes-bot\/nodes\/([0-9a-f-]{36})(\/native)?(\/api\/.*)$/.exec(ctx.path)
-    if (!match) return next()
-    const owner = auth.require(ctx).id, nodeID = match[1]!, path = match[3]!
-    const node = nodes.store.require<WorkspaceNode>(owner, 'node', nodeID)
-    if (node.transport !== 'paired-web') throw new HttpError(409, '请重新扫码授权 15300 子节点', 'paired_node_required')
-    const realtime = /^\/api\/realtime\/(?:capabilities|channels(?:\/[0-9a-f-]{36}(?:\/(?:commands|events))?)?|commands\/[A-Za-z0-9:_-]{1,200})$/.test(path)
-    const read = /^\/api\/(?:profiles(?:\/sessions)?|sessions(?:\/[^/]+(?:\/messages)?)?|files\/download)$/.test(path)
-    if (!realtime && !(read && ctx.method === 'GET')) throw new HttpError(403, '不支持的 Hermes Bot 操作', 'hermes_bot_path_forbidden')
-    const target = nodes.target(owner, nodeID)
-    if (!target.pairedToken) throw new HttpError(409, '请重新扫码授权子节点', 'paired_node_required')
-    let body: Buffer | undefined
-    if (!['GET', 'HEAD', 'DELETE'].includes(ctx.method)) {
-      if (!ctx.is('application/json')) throw new HttpError(415, 'JSON body required', 'invalid_content_type')
-      const chunks: Buffer[] = []; let length = 0
-      for await (const chunk of ctx.req) {
-        length += Buffer.byteLength(chunk)
-        if (length > 15 * 1024 * 1024) throw new HttpError(413, '请求过大', 'body_too_large')
-        chunks.push(Buffer.from(chunk))
-      }
-      body = Buffer.concat(chunks)
-    }
-    const controller = new AbortController()
-    const timeout = setTimeout(() => controller.abort(), 30_000)
-    ctx.res.once('close', () => controller.abort())
-    let response: Response
-    try {
-      response = await target.client.fetchImpl(new URL(`${target.url.href.replace(/\/$/, '')}${match[2] ? '/api/hermes-bot' : ''}${path}${ctx.search}`), {
-        method: ctx.method, redirect: 'error', signal: controller.signal,
-        headers: { Authorization: `Bearer ${target.pairedToken}`, 'Content-Type': 'application/json',
-          'X-Hermes-Profile': ctx.get('x-hermes-profile'),
-          'Last-Event-ID': ctx.get('last-event-id'), 'Idempotency-Key': ctx.get('idempotency-key') },
-        ...(body ? { body: new Uint8Array(body) } : {}),
-      })
-    } finally { clearTimeout(timeout) }
-    ctx.status = response.status
-    ctx.set('Cache-Control', 'no-store')
-    for (const name of ['content-type', 'content-disposition']) {
-      const value = response.headers.get(name); if (value) ctx.set(name, value)
-    }
-    if (response.headers.get('content-type')?.startsWith('text/event-stream') && response.body) {
-      const timer = setInterval(() => {
-        try {
-          if (auth.require(ctx).id !== owner || nodes.store.get<WorkspaceNode>(owner, 'node', nodeID)?.secret !== node.secret) controller.abort()
-        } catch { controller.abort() }
-      }, 5_000); timer.unref()
-      const stream = Readable.fromWeb(response.body as any)
-      const clear = () => clearInterval(timer)
-      stream.once('close', clear); stream.once('error', clear); ctx.res.once('close', clear)
-      ctx.body = stream
-    } else if (path === '/api/realtime/capabilities' && response.ok) {
-      ctx.body = { ...await response.json() as object, csrfToken: csrf.issue(ctx) }
-    } else if (response.status !== 204) ctx.body = Buffer.from(await response.arrayBuffer())
-  }
-}

+ 1 - 2
src/server/index.ts

@@ -49,8 +49,7 @@ const desktopActivation = new DesktopActivation(config.home, process.env.HERMES_
 let closeFrontend = async (): Promise<void> => undefined
 // Native update admission runs before routes (including streamed requests).
 // The capability is loopback-only and never shared with the Web renderer.
-runtime.app.middleware.unshift(instance.middleware(shutdown, () => runtime.realtime.broker.idleForUpdate
-  && runtime.runners.idleForUpdate && runtime.workspaceRuntime.idleForUpdate && runtime.desktopEnvironments.idleForUpdate && runtime.hermes.gateway.idle, ctx=>runtime.desktopEnvironments.bridge(ctx), desktopActivation, ctx => {
+runtime.app.middleware.unshift(instance.middleware(shutdown, () => runtime.runners.idleForUpdate && runtime.workspaceRuntime.idleForUpdate && runtime.desktopEnvironments.idleForUpdate && runtime.hermes.gateway.idle, ctx=>runtime.desktopEnvironments.bridge(ctx), desktopActivation, ctx => {
     const user = runtime.auth.localDesktopSession(ctx)
     ctx.body = { user, setCookies: ctx.response.get('set-cookie') }
   }))

+ 0 - 36
src/server/pushEventAdapter.ts

@@ -1,36 +0,0 @@
-import type {
-  ChatPushJob,
-  ChatPushObservation,
-  PushEventCoordinator,
-  PushNotificationCandidate,
-} from './pushEvents.js'
-import { PushCoordinator } from './pushCoordinator.js'
-
-/** Chat notifications and workspace events use Web-owned persistence. */
-export class PushCoordinatorEventAdapter implements PushEventCoordinator {
-  constructor(readonly push: PushCoordinator) {}
-  observeChat(_observation: ChatPushObservation): void {}
-  saveChatJob(job: ChatPushJob): void {
-    if (this.push.isAnyProviderEnabled()) this.push.saveChatJob(job)
-  }
-  completeChatJob(jobID: string): void {
-    this.push.completeChatJob(jobID)
-  }
-  pendingChatJobs(): readonly ChatPushJob[] {
-    return this.push.isAnyProviderEnabled() ? this.push.pendingChatJobs() : []
-  }
-  promptDigest(localUserID: string, prompt: string): string {
-    return this.push.promptDigest(localUserID, prompt)
-  }
-  canRecoverChatJob(job: ChatPushJob): boolean {
-    return this.push.chatJobRecoveryAllowed(job)
-  }
-  enqueueNotification(candidate: PushNotificationCandidate): 'enqueued' | 'duplicate' | 'ignored' {
-    if (
-      'roomID' in candidate &&
-      !this.push.isGroupSubscribed(candidate.localUserID, candidate.roomID)
-    )
-      return 'ignored'
-    return this.push.isAnyProviderEnabled() ? this.push.enqueueNotification(candidate) : 'ignored'
-  }
-}

+ 0 - 1416
src/server/pushEvents.ts

@@ -1,1416 +0,0 @@
-import { createHash, randomUUID } from 'node:crypto'
-import WebSocket, { type RawData } from 'ws'
-import { isSupportedGroupProtocolVersion } from '../shared/types.js'
-import type { ServerConfig } from './config.js'
-import type { UpstreamServiceSession } from './localAuth.js'
-import type { PushCoordinator as PersistentPushCoordinator } from './pushCoordinator.js'
-import { notificationPlainText } from './notificationText.js'
-
-type MaybePromise<T> = T | Promise<T>
-type JsonRecord = Record<string, unknown>
-
-export interface ChatRelayIdentity {
-  localUserID: string
-  connectionID?: string
-  accountKey?: string
-  source: 'web' | 'gateway' | 'paired'
-}
-
-interface ChatObservationBase {
-  localUserID: string
-  connectionID: string
-  accountKey?: string
-  source: ChatRelayIdentity['source']
-  observedAt: number
-}
-
-export type ChatPushObservation = ChatObservationBase & (
-  | {
-    type: 'chat.session_opened'
-    action: 'create' | 'resume'
-    profile: string
-    runtimeSessionID: string
-    storedSessionID: string
-  }
-  | {
-    type: 'chat.prompt'
-    phase: 'submitted' | 'accepted' | 'rejected'
-    requestID: string
-    profile?: string
-    runtimeSessionID: string
-    storedSessionID?: string
-    queued: boolean
-    status?: string
-    error?: string
-  }
-  | {
-    type: 'chat.rpc_event'
-    eventType: string
-    profile?: string
-    runtimeSessionID?: string
-    storedSessionID?: string
-    payload: JsonRecord
-  }
-  | {
-    type: 'chat.disconnected'
-    activeSessions: Array<{
-      profile: string
-      runtimeSessionID: string
-      storedSessionID: string
-    }>
-  }
-)
-
-type ChatObservationPayload = ChatPushObservation extends infer Observation
-  ? Observation extends ChatObservationBase
-    ? Omit<Observation, keyof ChatObservationBase>
-    : never
-  : never
-
-export interface GroupWatchAnchor {
-  epoch: string
-  cursor: number
-}
-
-export interface GroupWatchReset extends GroupWatchAnchor {
-  reason: string
-}
-
-export interface ChatPushJob {
-  id: string
-  localUserID: string
-  profile?: string
-  runtimeSessionID: string
-  storedSessionID?: string
-  requestID: string
-  queued: boolean
-  phase: 'submitted' | 'accepted' | 'watching'
-  submittedAt: number
-  expiresAt: number
-  metadata?: Record<string, unknown>
-}
-
-interface NotificationCandidateBase {
-  eventID: string
-  localUserID: string
-  title: string
-  body: string
-  collapseID: string
-  data: Record<string, string>
-}
-
-export interface ChatPushCandidate extends NotificationCandidateBase {
-  kind: 'chat.completed' | 'chat.failed' | 'chat.approval.requested' | 'chat.clarification.requested'
-  jobID: string
-  profile?: string
-  sessionID?: string
-  requestID?: string
-}
-
-export interface GroupPushCandidate {
-  eventID: NotificationCandidateBase['eventID']
-  localUserID: NotificationCandidateBase['localUserID']
-  title: NotificationCandidateBase['title']
-  body: NotificationCandidateBase['body']
-  collapseID: NotificationCandidateBase['collapseID']
-  data: NotificationCandidateBase['data']
-  kind: 'group.message.completed' | 'group.message.failed' | 'group.interaction.requested'
-  epoch?: string
-  cursor?: number
-  roomID: string
-  topicID?: string
-  messageID?: string
-  messageSequence?: number
-  interactionID?: string
-  interactionKind?: 'approval' | 'clarification' | 'unknown'
-  senderName?: string
-  content?: string
-  error?: string
-  occurredAt?: number
-}
-
-export type PushNotificationCandidate = ChatPushCandidate | GroupPushCandidate
-
-/**
- * Persistence and delivery boundary used by the relay and the group watcher.
- * Implementations must durably deduplicate `enqueueNotification` by
- * `localUserID + eventID`. `advanceGroupCursor` is called only after every
- * candidate for that cursor has been durably accepted by the outbox.
- */
-export interface PushEventCoordinator {
-  observeChat?(observation: ChatPushObservation): MaybePromise<void>
-  saveChatJob(job: ChatPushJob): MaybePromise<void>
-  completeChatJob(jobID: string): MaybePromise<void>
-  pendingChatJobs(): MaybePromise<readonly ChatPushJob[]>
-  recoverChatJob?(job: ChatPushJob): MaybePromise<void>
-  promptDigest?(localUserID: string, prompt: string): MaybePromise<string>
-  canRecoverChatJob?(job: ChatPushJob): MaybePromise<boolean>
-  enqueueNotification(candidate: PushNotificationCandidate): MaybePromise<'enqueued' | 'duplicate' | 'ignored' | void>
-}
-
-/** Keep the event pipeline decoupled from the concrete persistent coordinator. */
-export function createPushEventCoordinator(push: PersistentPushCoordinator): PushEventCoordinator {
-  return {
-    saveChatJob: job => { push.saveChatJob(job) },
-    completeChatJob: jobID => { push.completeChatJob(jobID) },
-    pendingChatJobs: () => push.pendingChatJobs(),
-    promptDigest: (localUserID, prompt) => push.promptDigest(localUserID, prompt),
-    canRecoverChatJob: job => push.chatJobRecoveryAllowed(job),
-    enqueueNotification: candidate => push.enqueueNotification(candidate),
-  }
-}
-
-function record(value: unknown): JsonRecord {
-  return value && typeof value === 'object' && !Array.isArray(value)
-    ? value as JsonRecord
-    : {}
-}
-
-function string(value: unknown): string {
-  return typeof value === 'string' ? value.trim() : ''
-}
-
-function requestID(value: unknown): string {
-  return typeof value === 'string' || typeof value === 'number' ? String(value) : ''
-}
-
-function errorMessage(value: unknown): string {
-  const source = record(value)
-  return string(source.message ?? source.error) || (value == null ? '' : String(value))
-}
-
-function summary(value: unknown, fallback: string): string {
-  return notificationPlainText(value, { fallback, maximum: 180 })
-}
-
-function eventTimestamp(value: unknown): number | undefined {
-  if (typeof value === 'number' && Number.isFinite(value)) {
-    return value < 10_000_000_000 ? value * 1_000 : value
-  }
-  if (typeof value !== 'string' || !value.trim()) return undefined
-  const numeric = Number(value)
-  if (Number.isFinite(numeric)) return numeric < 10_000_000_000 ? numeric * 1_000 : numeric
-  const parsed = Date.parse(value)
-  return Number.isNaN(parsed) ? undefined : parsed
-}
-
-function collapseID(prefix: string, value: string): string {
-  return `${prefix}:${createHash('sha256').update(value, 'utf8').digest('base64url').slice(0, 32)}`
-}
-
-function notificationData(
-  eventID: string,
-  kind: PushNotificationCandidate['kind'],
-  localUserID: string,
-  values: Record<string, string | undefined>,
-): Record<string, string> {
-  return Object.fromEntries(Object.entries({
-    version: '1', eventId: eventID, kind, clientAccountId: localUserID, ...values,
-  }).filter((entry): entry is [string, string] => typeof entry[1] === 'string' && Boolean(entry[1])))
-}
-
-interface SessionIdentity {
-  profile: string
-  runtimeSessionID: string
-  storedSessionID: string
-  baseline?: ChatMessageBaseline
-  baselinePromise?: Promise<ChatMessageBaseline>
-}
-
-interface PendingSessionOpen {
-  action: 'create' | 'resume'
-  profile: string
-  requestedStoredSessionID: string
-}
-
-interface PendingPrompt {
-  requestID: string
-  runtimeSessionID: string
-  storedSessionID?: string
-  profile?: string
-  queued: boolean
-  job: ChatPushJob
-}
-
-export interface ChatTerminalContent {
-  title?: string
-  body?: string
-  messageID?: string
-  timestamp?: number
-  confirmed?: boolean
-  failed?: boolean
-  error?: string
-  correlated?: boolean
-}
-
-export interface ChatMessageBaseline {
-  messageID?: string
-  sequence?: number
-  total: number
-  assistantCount: number
-  lastRowSequence?: number
-}
-
-export interface ChatNotificationResolver {
-  captureBaseline?(job: ChatPushJob): Promise<ChatMessageBaseline>
-  resolveTerminal(job: ChatPushJob, eventType: string, payload: JsonRecord): Promise<ChatTerminalContent>
-}
-
-/** Observes one already-authorized chat relay without changing its protocol. */
-export class ChatPushRelayObserver {
-  readonly #connectionID: string
-  readonly #sessions = new Map<string, SessionIdentity>()
-  readonly #pendingSessionOpens = new Map<string, PendingSessionOpen>()
-  readonly #pendingPrompts = new Map<string, PendingPrompt>()
-  readonly #jobsByRuntimeSession = new Map<string, ChatPushJob[]>()
-  readonly #terminalJobIDs = new Set<string>()
-  #closed = false
-  #delivery = Promise.resolve()
-
-  constructor(
-    readonly coordinator: PushEventCoordinator,
-    readonly identity: ChatRelayIdentity,
-    readonly now: () => number = Date.now,
-    readonly notificationResolver?: ChatNotificationResolver,
-  ) {
-    this.#connectionID = identity.connectionID ?? randomUUID().toLowerCase()
-  }
-
-  observeClientFrame(frameText: string): void {
-    if (this.#closed) return
-    let frame: JsonRecord
-    try { frame = record(JSON.parse(frameText)) } catch { return }
-    const method = string(frame.method)
-    const id = requestID(frame.id)
-    const params = record(frame.params)
-    if ((method === 'session.create' || method === 'session.resume') && id) {
-      this.#pendingSessionOpens.set(id, {
-        action: method === 'session.create' ? 'create' : 'resume',
-        profile: string(params.profile),
-        requestedStoredSessionID: method === 'session.resume' ? string(params.session_id) : '',
-      })
-      return
-    }
-    if (method !== 'prompt.submit' || !id) return
-    const runtimeSessionID = string(params.session_id)
-    if (!runtimeSessionID) return
-    const session = this.#sessions.get(runtimeSessionID)
-    let job: ChatPushJob = {
-      id: randomUUID().toLowerCase(),
-      localUserID: this.identity.localUserID,
-      profile: session?.profile,
-      runtimeSessionID,
-      storedSessionID: session?.storedSessionID,
-      requestID: id,
-      queued: params.queued === true,
-      phase: 'submitted',
-      submittedAt: this.now(),
-      expiresAt: this.now() + 24 * 60 * 60 * 1_000,
-    }
-    if (this.coordinator.promptDigest) {
-      try {
-        const digest = this.coordinator.promptDigest(
-          this.identity.localUserID,
-          string(params.text),
-        )
-        if (typeof digest === 'string' && digest) {
-          job = { ...job, metadata: { ...job.metadata, promptDigest: digest } }
-        }
-      } catch { /* Missing correlation fails closed without blocking chat. */ }
-    }
-    if (session?.baseline) {
-      const baseline = session.baseline
-      job = {
-        ...job,
-        metadata: {
-          ...job.metadata,
-          baselineCaptured: true,
-          baselineMessageID: baseline.messageID,
-          baselineSequence: baseline.sequence,
-          baselineTotal: baseline.total,
-          baselineAssistantCount: baseline.assistantCount,
-          baselineRowSequence: baseline.lastRowSequence,
-        },
-      }
-    } else {
-      job = { ...job, metadata: { ...job.metadata, baselineCaptured: false } }
-    }
-    const prompt: PendingPrompt = {
-      requestID: id,
-      runtimeSessionID,
-      storedSessionID: session?.storedSessionID,
-      profile: session?.profile,
-      queued: params.queued === true,
-      job,
-    }
-    this.#pendingPrompts.set(id, prompt)
-    this.#jobsByRuntimeSession.set(runtimeSessionID, [
-      ...(this.#jobsByRuntimeSession.get(runtimeSessionID) ?? []),
-      prompt.job,
-    ])
-    this.#enqueue(() => this.coordinator.saveChatJob(prompt.job))
-    if (!session?.baseline && session?.baselinePromise) {
-      void session.baselinePromise.then(baseline => {
-        this.#applyBaseline(runtimeSessionID, prompt.job.id, baseline)
-      }).catch(() => undefined)
-    }
-    this.#emit({
-      type: 'chat.prompt',
-      phase: 'submitted',
-      requestID: prompt.requestID,
-      runtimeSessionID: prompt.runtimeSessionID,
-      storedSessionID: prompt.storedSessionID,
-      profile: prompt.profile,
-      queued: prompt.queued,
-    })
-  }
-
-  ownsJob(jobID: string): boolean {
-    return !this.#closed && [...this.#jobsByRuntimeSession.values()].some(jobs => jobs.some(job => job.id === jobID))
-  }
-
-  observeUpstreamFrame(data: RawData, isBinary: boolean): void {
-    if (this.#closed || isBinary) return
-    let frame: JsonRecord
-    try { frame = record(JSON.parse(Buffer.from(data as Uint8Array).toString('utf8'))) } catch { return }
-    const id = requestID(frame.id)
-    if (id) {
-      const pendingOpen = this.#pendingSessionOpens.get(id)
-      if (pendingOpen) {
-        this.#pendingSessionOpens.delete(id)
-        if (!frame.error) {
-          const result = record(frame.result)
-          const runtimeSessionID = string(result.session_id ?? result.sessionId)
-          const storedSessionID = string(
-            result.stored_session_id ?? result.storedSessionId ?? result.session_key,
-          ) || pendingOpen.requestedStoredSessionID
-          if (runtimeSessionID && storedSessionID && pendingOpen.profile) {
-            const session: SessionIdentity = {
-              profile: pendingOpen.profile,
-              runtimeSessionID,
-              storedSessionID,
-              ...(pendingOpen.action === 'create'
-                ? { baseline: { total: 0, assistantCount: 0, lastRowSequence: 0 } }
-                : {}),
-            }
-            this.#sessions.set(runtimeSessionID, session)
-            if (pendingOpen.action === 'resume' && this.notificationResolver?.captureBaseline) {
-              const baselineJob: ChatPushJob = {
-                id: `baseline:${this.#connectionID}:${runtimeSessionID}`,
-                localUserID: this.identity.localUserID,
-                profile: session.profile,
-                runtimeSessionID,
-                storedSessionID,
-                requestID: 'baseline',
-                queued: false,
-                phase: 'submitted',
-                submittedAt: this.now(),
-                expiresAt: this.now() + 60_000,
-              }
-              const baselinePromise = this.notificationResolver.captureBaseline(baselineJob)
-              session.baselinePromise = baselinePromise
-              void baselinePromise.then(baseline => {
-                if (this.#sessions.get(runtimeSessionID) === session) session.baseline = baseline
-              }).catch(() => undefined)
-            }
-            this.#emit({
-              type: 'chat.session_opened',
-              profile: session.profile,
-              runtimeSessionID,
-              storedSessionID,
-              action: pendingOpen.action,
-            })
-          }
-        }
-      }
-      const pendingPrompt = this.#pendingPrompts.get(id)
-      if (pendingPrompt) {
-        this.#pendingPrompts.delete(id)
-        const result = record(frame.result)
-        const status = string(result.status) || (frame.error ? 'rejected' : 'accepted')
-        this.#emit({
-          type: 'chat.prompt',
-          phase: frame.error ? 'rejected' : 'accepted',
-          requestID: pendingPrompt.requestID,
-          runtimeSessionID: pendingPrompt.runtimeSessionID,
-          storedSessionID: pendingPrompt.storedSessionID,
-          profile: pendingPrompt.profile,
-          queued: pendingPrompt.queued,
-          status,
-          ...(frame.error ? { error: errorMessage(frame.error) || 'Hermes rejected the prompt' } : {}),
-        })
-        if (this.#terminalJobIDs.has(pendingPrompt.job.id)) {
-          // A terminal event can legally overtake its JSON-RPC receipt.
-          // Never recreate a job that is already being completed.
-        } else if (frame.error) {
-          this.#removeJob(pendingPrompt.job)
-          this.#enqueue(() => this.coordinator.completeChatJob(pendingPrompt.job.id))
-        } else {
-          const runID = string(result.run_id ?? result.runId ?? result.turn_id ?? result.turnId)
-          const accepted: ChatPushJob = {
-            ...pendingPrompt.job,
-            phase: 'accepted',
-            ...(runID ? { metadata: { ...pendingPrompt.job.metadata, runID } } : {}),
-          }
-          this.#replaceJob(accepted)
-          this.#enqueue(() => this.coordinator.saveChatJob(accepted))
-        }
-      }
-    }
-    if (string(frame.method) !== 'event') return
-    const params = record(frame.params)
-    const eventType = string(params.type)
-    if (!eventType || eventType === 'gateway.ready') return
-    const runtimeSessionID = string(params.session_id)
-    const session = runtimeSessionID ? this.#sessions.get(runtimeSessionID) : undefined
-    this.#emit({
-      type: 'chat.rpc_event',
-      eventType,
-      profile: string(params.profile) || session?.profile || undefined,
-      runtimeSessionID: runtimeSessionID || undefined,
-      storedSessionID: session?.storedSessionID,
-      payload: record(params.payload),
-    })
-    if (runtimeSessionID) this.#observeRPCEvent(
-      eventType,
-      runtimeSessionID,
-      record(params.payload),
-    )
-  }
-
-  disconnected(): void {
-    if (this.#closed) return
-    this.#closed = true
-    this.#emit({
-      type: 'chat.disconnected',
-      activeSessions: [...this.#sessions.values()],
-    })
-    for (const jobs of this.#jobsByRuntimeSession.values()) {
-      for (const job of [...jobs]) {
-        if (this.#terminalJobIDs.has(job.id)) continue
-        const disconnectedJob: ChatPushJob = {
-          ...job,
-          metadata: { ...job.metadata, disconnectedAt: this.now() },
-        }
-        this.#replaceJob(disconnectedJob)
-        this.#enqueue(() => this.coordinator.saveChatJob(disconnectedJob))
-        if (this.coordinator.recoverChatJob) {
-          this.#enqueue(() => this.coordinator.recoverChatJob!(disconnectedJob))
-        }
-      }
-    }
-  }
-
-  async flush(): Promise<void> {
-    await Promise.allSettled(
-      [...this.#sessions.values()].flatMap(session => session.baselinePromise ? [session.baselinePromise] : []),
-    )
-    await Promise.resolve()
-    await this.#delivery
-  }
-
-  #emit(observation: ChatObservationPayload): void {
-    const event = {
-      ...observation,
-      localUserID: this.identity.localUserID,
-      connectionID: this.#connectionID,
-      accountKey: this.identity.accountKey,
-      source: this.identity.source,
-      observedAt: this.now(),
-    } as ChatPushObservation
-    if (this.coordinator.observeChat) this.#enqueue(() => this.coordinator.observeChat!(event))
-  }
-
-  #enqueue(operation: () => MaybePromise<void>): void {
-    this.#delivery = this.#delivery.then(operation).catch(() => undefined)
-  }
-
-  #replaceJob(job: ChatPushJob): void {
-    const jobs = this.#jobsByRuntimeSession.get(job.runtimeSessionID) ?? []
-    const index = jobs.findIndex(candidate => candidate.id === job.id)
-    if (index >= 0) jobs[index] = job
-    else jobs.push(job)
-    this.#jobsByRuntimeSession.set(job.runtimeSessionID, jobs)
-  }
-
-  #applyBaseline(runtimeSessionID: string, jobID: string, baseline: ChatMessageBaseline): void {
-    const jobs = this.#jobsByRuntimeSession.get(runtimeSessionID) ?? []
-    const index = jobs.findIndex(job => job.id === jobID)
-    if (index < 0 || this.#terminalJobIDs.has(jobID)) return
-    const current = jobs[index]!
-    const updated: ChatPushJob = {
-      ...current,
-      metadata: {
-        ...current.metadata,
-        baselineCaptured: true,
-        baselineMessageID: baseline.messageID,
-        baselineSequence: baseline.sequence,
-        baselineTotal: baseline.total,
-        baselineAssistantCount: baseline.assistantCount,
-        baselineRowSequence: baseline.lastRowSequence,
-      },
-    }
-    jobs[index] = updated
-    for (const pending of this.#pendingPrompts.values()) {
-      if (pending.job.id === jobID) pending.job = updated
-    }
-    this.#enqueue(() => this.coordinator.saveChatJob(updated))
-  }
-
-  #removeJob(job: ChatPushJob): void {
-    const jobs = (this.#jobsByRuntimeSession.get(job.runtimeSessionID) ?? [])
-      .filter(candidate => candidate.id !== job.id)
-    if (jobs.length) this.#jobsByRuntimeSession.set(job.runtimeSessionID, jobs)
-    else this.#jobsByRuntimeSession.delete(job.runtimeSessionID)
-  }
-
-  #observeRPCEvent(eventType: string, runtimeSessionID: string, payload: JsonRecord): void {
-    const jobs = this.#jobsByRuntimeSession.get(runtimeSessionID) ?? []
-    const eventRunID = string(payload.run_id ?? payload.runId ?? payload.turn_id ?? payload.turnId)
-    let job = eventRunID
-      ? jobs.find(candidate => string(candidate.metadata?.runID) === eventRunID)
-        ?? jobs.find(candidate => !string(candidate.metadata?.runID))
-      : jobs[0]
-    if (!job) return
-    if (eventRunID && !string(job.metadata?.runID)) {
-      job = { ...job, metadata: { ...job.metadata, runID: eventRunID } }
-      this.#replaceJob(job)
-      const boundJob = job
-      this.#enqueue(() => this.coordinator.saveChatJob(boundJob))
-    }
-    if (['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(eventType)) {
-      const requestIDValue = string(payload.request_id ?? payload.requestId ?? payload.id)
-      if (!requestIDValue) return
-      const clarification = eventType.startsWith('clarify.')
-      const kind: ChatPushCandidate['kind'] = clarification
-        ? 'chat.clarification.requested' : 'chat.approval.requested'
-      const eventID = `chat-interaction:${job.id}:${requestIDValue}`
-      const candidate: ChatPushCandidate = {
-        eventID,
-        localUserID: job.localUserID,
-        kind,
-        jobID: job.id,
-        profile: job.profile,
-        sessionID: job.storedSessionID,
-        requestID: requestIDValue,
-        title: clarification ? '机器人需要补充信息' : '机器人请求审批',
-        body: summary(payload.question ?? payload.message ?? payload.prompt, clarification ? '请打开夭夭继续处理' : '请打开夭夭审批'),
-        collapseID: collapseID('chat-interaction', `${job.storedSessionID ?? runtimeSessionID}:${requestIDValue}`),
-        data: notificationData(eventID, kind, job.localUserID, {
-          profile: job.profile, sessionId: job.storedSessionID, requestId: requestIDValue,
-        }),
-      }
-      this.#enqueue(async () => {
-        if (!await this.#jobOwnershipAllowed(job)) return
-        if (!eventRunID) {
-          let ownership: ChatTerminalContent = {}
-          try {
-            ownership = await this.notificationResolver?.resolveTerminal(job, eventType, payload) ?? {}
-          } catch { return }
-          if (ownership.correlated !== true) return
-        }
-        await this.coordinator.enqueueNotification(candidate)
-      })
-      return
-    }
-    const terminal = ['message.complete', 'run.completed', 'run.failed', 'error'].includes(eventType)
-    if (!terminal) return
-    if (this.#terminalJobIDs.has(job.id)) return
-    this.#terminalJobIDs.add(job.id)
-    this.#enqueue(async () => {
-      if (!await this.#jobOwnershipAllowed(job)) return
-      let resolved: ChatTerminalContent | undefined
-      if (!eventRunID) {
-        try { resolved = await this.notificationResolver?.resolveTerminal(job, eventType, payload) ?? {} } catch { resolved = {} }
-        const failed = eventType === 'run.failed' || eventType === 'error' || Boolean(payload.error)
-        if (resolved.confirmed !== true && !(failed && resolved.correlated === true)) {
-          this.#terminalJobIDs.delete(job.id)
-          return
-        }
-      }
-      const candidate = await chatTerminalCandidate(job, eventType, payload, this.notificationResolver, resolved)
-      await this.coordinator.enqueueNotification(candidate)
-      await this.coordinator.completeChatJob(job.id)
-      this.#removeJob(job)
-    })
-  }
-
-  async #jobOwnershipAllowed(job: ChatPushJob): Promise<boolean> {
-    if (!this.coordinator.canRecoverChatJob) return true
-    try { return await this.coordinator.canRecoverChatJob(job) } catch { return false }
-  }
-}
-
-export interface GroupEventEnvelope {
-  type: 'group.ready' | 'group.event' | 'group.heartbeat' | 'group.reset_required'
-  epoch?: string
-  cursor?: number
-  heartbeatSeconds?: number
-  roomId?: string
-  event?: string
-  payload?: unknown
-  reason?: string
-}
-
-function canonicalAnchor(value: GroupWatchAnchor): GroupWatchAnchor {
-  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.epoch)
-    || !Number.isSafeInteger(value.cursor) || value.cursor < 0) {
-    throw new Error('Invalid Yaoyao group event anchor')
-  }
-  return { epoch: value.epoch, cursor: value.cursor }
-}
-
-function eventRoomID(envelope: GroupEventEnvelope, payload: JsonRecord): string {
-  return string(envelope.roomId ?? payload.roomId ?? payload.room_id)
-}
-
-function terminalGroupCandidate(
-  envelope: GroupEventEnvelope,
-  anchor: GroupWatchAnchor,
-): Omit<GroupPushCandidate, 'localUserID' | 'data'> | undefined {
-  if (envelope.type !== 'group.event') return undefined
-  const payload = record(envelope.payload)
-  const roomID = eventRoomID(envelope, payload)
-  if (!roomID) return undefined
-  if (envelope.event === 'message.upsert') {
-    const senderKind = string(payload.senderKind ?? payload.sender_kind).toLowerCase()
-    const status = string(payload.status).toLowerCase()
-    const messageID = string(payload.id)
-    if (senderKind !== 'agent' || !messageID || (status !== 'completed' && status !== 'failed')) return undefined
-    const kind: GroupPushCandidate['kind'] = status === 'completed'
-      ? 'group.message.completed' : 'group.message.failed'
-    const eventID = `group-message:${messageID}:${status}`
-    const content = string(payload.content)
-    const error = string(payload.error)
-    return {
-      eventID,
-      kind,
-      epoch: anchor.epoch,
-      cursor: anchor.cursor + 1,
-      roomID,
-      topicID: string(payload.topicId ?? payload.topic_id) || undefined,
-      messageID,
-      messageSequence: Number.isSafeInteger(Number(payload.seq ?? payload.sequence))
-        ? Number(payload.seq ?? payload.sequence) : undefined,
-      senderName: string(payload.senderName ?? payload.sender_name) || undefined,
-      content: content || undefined,
-      error: error || undefined,
-      occurredAt: eventTimestamp(payload.updatedAt ?? payload.updated_at ?? payload.createdAt ?? payload.created_at),
-      title: status === 'completed'
-        ? `${string(payload.senderName ?? payload.sender_name) || '机器人'} 已回复`
-        : `${string(payload.senderName ?? payload.sender_name) || '机器人'} 执行失败`,
-      body: summary(error || content, status === 'completed' ? '打开夭夭查看团队消息' : '打开夭夭查看失败详情'),
-      collapseID: collapseID('group-message', messageID),
-    }
-  }
-  if (envelope.event !== 'interaction.requested') return undefined
-  const interactionID = string(payload.id)
-  const status = string(payload.status).toLowerCase()
-  if (!interactionID || (status && status !== 'pending')) return undefined
-  const rawKind = string(payload.kind).toLowerCase()
-  const interactionKind = rawKind === 'approval' || rawKind === 'clarification' ? rawKind : 'unknown'
-  const interactionPayload = record(payload.payload)
-  const eventID = `group-interaction:${interactionID}`
-  const content = string(interactionPayload.question ?? interactionPayload.message ?? interactionPayload.prompt)
-  return {
-    eventID,
-    kind: 'group.interaction.requested',
-    epoch: anchor.epoch,
-    cursor: anchor.cursor + 1,
-    roomID,
-    topicID: string(payload.topicId ?? payload.topic_id) || undefined,
-    interactionID,
-    interactionKind,
-    content: content || undefined,
-    occurredAt: eventTimestamp(payload.updatedAt ?? payload.updated_at ?? payload.createdAt ?? payload.created_at),
-    title: interactionKind === 'clarification' ? '团队机器人需要补充信息' : '团队机器人请求审批',
-    body: summary(content, '请打开夭夭继续处理'),
-    collapseID: collapseID('group-interaction', interactionID),
-  }
-}
-
-export type GroupEnvelopeResult = 'ready' | 'heartbeat' | 'advanced' | 'ignored' | 'reset'
-
-export interface GroupEventConnection {
-  close(): void
-}
-
-export interface GroupEventSource {
-  currentAnchor(): Promise<GroupWatchAnchor>
-  connect(
-    anchor: GroupWatchAnchor,
-    handlers: {
-      onEnvelope(envelope: GroupEventEnvelope): void
-      onClose(error?: Error): void
-    },
-  ): Promise<GroupEventConnection>
-}
-
-function parseUpstreamJSON(body: Buffer): JsonRecord {
-  try { return record(JSON.parse(body.toString('utf8'))) } catch { throw new Error('Hermes returned invalid JSON') }
-}
-
-function values(value: unknown): unknown[] {
-  if (Array.isArray(value)) return value
-  const source = record(value)
-  const data = source.data
-  return Array.isArray(data) ? data : []
-}
-
-function messageContent(value: unknown): string {
-  if (typeof value === 'string') return value.trim()
-  if (!Array.isArray(value)) return ''
-  return value.map(item => {
-    if (typeof item === 'string') return item
-    const part = record(item)
-    return string(part.text ?? part.content)
-  }).filter(Boolean).join('\n').trim()
-}
-
-function messageTimestamp(value: unknown): number | undefined {
-  if (typeof value === 'number' && Number.isFinite(value)) return value < 1_000_000_000_000 ? value * 1_000 : value
-  if (typeof value === 'string' && value.trim()) {
-    const numeric = Number(value)
-    if (Number.isFinite(numeric)) return numeric < 1_000_000_000_000 ? numeric * 1_000 : numeric
-    const parsed = Date.parse(value)
-    if (!Number.isNaN(parsed)) return parsed
-  }
-  return undefined
-}
-
-interface ChatHistoryRow {
-  role: string
-  content: string
-  messageID?: string
-  runID?: string
-  sequence: number
-  timestamp?: number
-  failed: boolean
-  error?: string
-}
-
-export class HermesChatNotificationResolver implements ChatNotificationResolver {
-  private readonly titleCache = new Map<string, { value: string; expiresAt: number }>()
-
-  constructor(
-    readonly upstreamSession: UpstreamServiceSession,
-    readonly digestPrompt?: (localUserID: string, prompt: string) => MaybePromise<string>,
-  ) {}
-
-  private async snapshot(job: ChatPushJob): Promise<{
-    title?: string
-    total: number
-    rows: ChatHistoryRow[]
-    assistants: ChatHistoryRow[]
-    latest?: ChatHistoryRow
-  }> {
-    if (!job.storedSessionID) return { total: 0, rows: [], assistants: [] }
-    const search = new URLSearchParams({
-      offset: '0', limit: '500', order: 'latest', include_compacted: 'true',
-    })
-    if (job.profile) search.set('profile', job.profile)
-    const response = await this.upstreamSession.request(
-      `/api/sessions/${encodeURIComponent(job.storedSessionID)}/messages`,
-      { search },
-    )
-    if (response.status < 200 || response.status >= 300) throw new Error(`Hermes history failed (${response.status})`)
-    const source = parseUpstreamJSON(response.body)
-    const session = record(source.session)
-    const messages = values(source.messages ?? source.items ?? source.data ?? source)
-    const rows = messages.map((raw, index): ChatHistoryRow => {
-      const message = record(raw)
-      const role = string(message.role ?? message.senderKind ?? message.sender_kind).toLowerCase()
-      const content = messageContent(message.content ?? message.text ?? message.message)
-      const error = string(message.error)
-      const status = string(message.status).toLowerCase()
-      const rowID = Number(message.id)
-      const explicitSequence = Number(message.sequence ?? message.seq ?? message.index)
-      const rawSequence = Number.isFinite(rowID)
-        ? rowID : Number.isFinite(explicitSequence) ? explicitSequence : index
-      return {
-        role,
-        content: content || error,
-        messageID: requestID(message.id ?? message.message_id ?? message.messageId) || undefined,
-        runID: string(message.run_id ?? message.runId ?? message.turn_id ?? message.turnId) || undefined,
-        sequence: rawSequence,
-        timestamp: messageTimestamp(message.timestamp ?? message.createdAt ?? message.created_at),
-        failed: status === 'failed' || status === 'error' || Boolean(error),
-        ...(error ? { error } : {}),
-      }
-    }).sort((left, right) => left.sequence - right.sequence || (left.timestamp ?? 0) - (right.timestamp ?? 0))
-    const assistants = rows.filter(row => (row.role === 'assistant' || row.role === 'agent') && Boolean(row.content))
-    const pagination = record(source.pagination)
-    const totalValue = Number(pagination.total ?? source.total ?? messages.length)
-    let title = string(session.title ?? source.title) || undefined
-    if (!title) title = await this.sessionTitle(job)
-    return {
-      title,
-      total: Number.isSafeInteger(totalValue) && totalValue >= 0 ? totalValue : messages.length,
-      rows,
-      assistants,
-      latest: assistants.at(-1),
-    }
-  }
-
-  private async sessionTitle(job: ChatPushJob): Promise<string | undefined> {
-    if (!job.storedSessionID) return undefined
-    const key = `${job.profile ?? 'default'}:${job.storedSessionID}`
-    const cached = this.titleCache.get(key)
-    if (cached && cached.expiresAt > Date.now()) return cached.value
-    const search = new URLSearchParams()
-    if (job.profile) search.set('profile', job.profile)
-    try {
-      const response = await this.upstreamSession.request(
-        `/api/sessions/${encodeURIComponent(job.storedSessionID)}`,
-        { search },
-      )
-      if (response.status < 200 || response.status >= 300) return undefined
-      const payload = parseUpstreamJSON(response.body)
-      const data = record(payload.data)
-      const session = record(payload.session ?? data.session ?? payload.data ?? payload)
-      const title = string(session.title)
-      if (!title) return undefined
-      this.titleCache.set(key, { value: title, expiresAt: Date.now() + 5 * 60 * 1_000 })
-      return title
-    } catch {
-      return undefined
-    }
-  }
-
-  async captureBaseline(job: ChatPushJob): Promise<ChatMessageBaseline> {
-    if (!job.storedSessionID) {
-      return { total: 0, assistantCount: 0, lastRowSequence: 0 }
-    }
-    const search = new URLSearchParams({
-      offset: '0', limit: '1', order: 'latest', include_compacted: 'true',
-    })
-    if (job.profile) search.set('profile', job.profile)
-    const response = await this.upstreamSession.request(
-      `/api/sessions/${encodeURIComponent(job.storedSessionID)}/messages`,
-      { search },
-    )
-    if (response.status < 200 || response.status >= 300) throw new Error(`Hermes history failed (${response.status})`)
-    const source = parseUpstreamJSON(response.body)
-    const messages = values(source.messages ?? source.items ?? source.data ?? source)
-    const raw = messages.at(-1)
-    const message = record(raw)
-    const role = string(message.role ?? message.senderKind ?? message.sender_kind).toLowerCase()
-    const rowID = Number(message.id)
-    const explicitSequence = Number(message.sequence ?? message.seq ?? message.index)
-    const sequence = Number.isFinite(rowID)
-      ? rowID : Number.isFinite(explicitSequence) ? explicitSequence : 0
-    const pagination = record(source.pagination)
-    const totalValue = Number(pagination.total ?? source.total ?? messages.length)
-    return {
-      messageID: role === 'assistant' || role === 'agent'
-        ? requestID(message.id ?? message.message_id ?? message.messageId) || undefined
-        : undefined,
-      sequence: role === 'assistant' || role === 'agent' ? sequence : undefined,
-      total: Number.isSafeInteger(totalValue) && totalValue >= 0 ? totalValue : messages.length,
-      assistantCount: role === 'assistant' || role === 'agent' ? 1 : 0,
-      lastRowSequence: sequence,
-    }
-  }
-
-  async resolveTerminal(job: ChatPushJob, _eventType: string, _payload: JsonRecord): Promise<ChatTerminalContent> {
-    const snapshot = await this.snapshot(job)
-    const expectedRunID = string(job.metadata?.runID)
-    if (expectedRunID) {
-      const latest = snapshot.assistants.filter(candidate => candidate.runID === expectedRunID).at(-1)
-      const baselineSequence = Number(job.metadata?.baselineSequence)
-      const baselineRowSequence = Number(job.metadata?.baselineRowSequence)
-      const baselineMessageID = string(job.metadata?.baselineMessageID)
-      const confirmed = job.metadata?.baselineCaptured === true && Boolean(latest) && (
-        (Number.isFinite(baselineSequence) && latest!.sequence > baselineSequence)
-          || (Number.isFinite(baselineRowSequence) && latest!.sequence > baselineRowSequence)
-          || Boolean(baselineMessageID && latest!.messageID && latest!.messageID !== baselineMessageID)
-      )
-      return this.terminalContent(snapshot.title, latest, confirmed, confirmed)
-    }
-
-    const promptDigest = string(job.metadata?.promptDigest)
-    const baselineRowSequence = Number(job.metadata?.baselineRowSequence)
-    if (!this.digestPrompt || !promptDigest || !Number.isFinite(baselineRowSequence)) {
-      return { title: snapshot.title, confirmed: false, correlated: false }
-    }
-    const matchingUsers: ChatHistoryRow[] = []
-    for (const row of snapshot.rows) {
-      if (row.role !== 'user' || row.sequence <= baselineRowSequence || !row.content) continue
-      let digest = ''
-      try { digest = await this.digestPrompt(job.localUserID, row.content) } catch { continue }
-      if (digest === promptDigest) matchingUsers.push(row)
-    }
-    if (matchingUsers.length !== 1) {
-      return { title: snapshot.title, confirmed: false, correlated: false }
-    }
-    const userRow = matchingUsers[0]!
-    const nextUser = snapshot.rows.find(row => row.role === 'user' && row.sequence > userRow.sequence)
-    const latest = snapshot.assistants
-      .filter(row => row.sequence > userRow.sequence && (!nextUser || row.sequence < nextUser.sequence))
-      .at(-1)
-    return this.terminalContent(snapshot.title, latest, Boolean(latest), true)
-  }
-
-  private terminalContent(
-    title: string | undefined,
-    latest: ChatHistoryRow | undefined,
-    confirmed: boolean,
-    correlated: boolean,
-  ): ChatTerminalContent {
-    return {
-      title,
-      body: latest?.content,
-      messageID: latest?.messageID,
-      timestamp: latest?.timestamp,
-      confirmed,
-      correlated,
-      ...(latest?.failed ? { failed: true } : {}),
-      ...(latest?.error ? { error: latest.error } : {}),
-    }
-  }
-}
-
-function chatInteractionCandidate(
-  job: ChatPushJob,
-  eventType: string,
-  payload: JsonRecord,
-): ChatPushCandidate | undefined {
-  const requestIDValue = string(payload.request_id ?? payload.requestId ?? payload.id)
-  if (!requestIDValue) return undefined
-  const clarification = eventType.startsWith('clarify.')
-    || string(payload.kind).toLowerCase() === 'clarification'
-  const kind: ChatPushCandidate['kind'] = clarification
-    ? 'chat.clarification.requested' : 'chat.approval.requested'
-  const eventID = `chat-interaction:${job.id}:${requestIDValue}`
-  return {
-    eventID,
-    localUserID: job.localUserID,
-    kind,
-    jobID: job.id,
-    profile: job.profile,
-    sessionID: job.storedSessionID,
-    requestID: requestIDValue,
-    title: clarification ? '机器人需要补充信息' : '机器人请求审批',
-    body: summary(payload.question ?? payload.message ?? payload.prompt, clarification ? '请打开夭夭继续处理' : '请打开夭夭审批'),
-    collapseID: collapseID('chat-interaction', `${job.storedSessionID ?? job.runtimeSessionID}:${requestIDValue}`),
-    data: notificationData(eventID, kind, job.localUserID, {
-      profile: job.profile, sessionId: job.storedSessionID, requestId: requestIDValue,
-    }),
-  }
-}
-
-async function chatTerminalCandidate(
-  job: ChatPushJob,
-  eventType: string,
-  payload: JsonRecord,
-  resolver?: ChatNotificationResolver,
-  suppliedContent?: ChatTerminalContent,
-): Promise<ChatPushCandidate> {
-  const terminalStatus = string(payload.status).toLowerCase()
-  const failed = eventType === 'run.failed' || eventType === 'error'
-    || terminalStatus === 'failed' || terminalStatus === 'error' || Boolean(payload.error)
-  let resolved: ChatTerminalContent = suppliedContent ?? {}
-  if (!suppliedContent) {
-    try { resolved = await resolver?.resolveTerminal(job, eventType, payload) ?? {} } catch { /* payload fallback */ }
-  }
-  const kind: ChatPushCandidate['kind'] = failed ? 'chat.failed' : 'chat.completed'
-  const eventID = `chat-terminal:${job.id}:${failed ? 'failed' : 'completed'}`
-  const authoritativeBody = resolved.confirmed === true ? resolved.body : undefined
-  return {
-    eventID,
-    localUserID: job.localUserID,
-    kind,
-    jobID: job.id,
-    profile: job.profile,
-    sessionID: job.storedSessionID,
-    title: resolved.title || (failed ? '任务执行失败' : '任务已完成'),
-    body: failed
-      ? summary(payload.error ?? payload.message ?? authoritativeBody, '打开夭夭查看失败详情')
-      : summary(authoritativeBody ?? payload.text ?? payload.message, '打开夭夭查看结果'),
-    collapseID: collapseID('chat', job.storedSessionID ?? job.runtimeSessionID),
-    data: notificationData(eventID, kind, job.localUserID, {
-      profile: job.profile, sessionId: job.storedSessionID,
-    }),
-  }
-}
-
-/**
- * Server-owned recovery connection for one persisted chat job. The caller
- * controls the number of concurrently started watchers.
- */
-export interface ChatPushRecoveryTransport {
-  start(): void
-  send(data: string): void
-  close(code?: number, reason?: string): void
-}
-export type ChatPushTransportFactory = (job: ChatPushJob, onFrame: (frame: string) => void, onClose: () => void) => Promise<ChatPushRecoveryTransport>
-
-export class HermesChatPushJobWatcher {
-  #job: ChatPushJob
-  #running = false
-  #generation = 0
-  #retryAttempt = 0
-  #retryTimer?: ReturnType<typeof setTimeout>
-  #socket?: WebSocket | ChatPushRecoveryTransport
-  #resumeRequestID = ''
-  #frames = Promise.resolve()
-  #finished = false
-
-  constructor(
-    job: ChatPushJob,
-    readonly config: ServerConfig,
-    readonly upstreamSession: UpstreamServiceSession,
-    readonly coordinator: PushEventCoordinator,
-    readonly resolver: ChatNotificationResolver = new HermesChatNotificationResolver(upstreamSession),
-    readonly now: () => number = Date.now,
-    readonly onFinished?: (jobID: string) => void,
-    readonly transportFactory?: ChatPushTransportFactory,
-  ) {
-    this.#job = { ...job }
-  }
-
-  start(): void {
-    if (this.#running) return
-    this.#running = true
-    this.#generation += 1
-    void this.#connect(this.#generation)
-  }
-
-  stop(): void {
-    this.#running = false
-    this.#generation += 1
-    if (this.#retryTimer) clearTimeout(this.#retryTimer)
-    this.#retryTimer = undefined
-    this.#socket?.close(1000, 'chat push watcher close')
-    this.#socket = undefined
-  }
-
-  async #connect(generation: number): Promise<void> {
-    if (!this.#job.storedSessionID || this.#job.expiresAt <= this.now()) {
-      await this.coordinator.completeChatJob(this.#job.id)
-      this.stop()
-      this.#notifyFinished()
-      return
-    }
-    try {
-      if (this.transportFactory) {
-        const transport = await this.transportFactory(this.#job,
-          frame => this.#queueFrame(generation, Buffer.from(frame), false),
-          () => this.#scheduleReconnect(generation))
-        if (!this.#running || generation !== this.#generation) { transport.close(); return }
-        this.#socket = transport
-        transport.start()
-        return
-      }
-      const credential = await this.upstreamSession.webSocketCredential()
-      if (!this.#running || generation !== this.#generation) return
-      const url = new URL(this.config.upstream)
-      url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
-      const prefix = this.config.upstream.pathname === '/' ? '' : this.config.upstream.pathname.replace(/\/$/, '')
-      url.pathname = `${prefix}/api/ws`
-      url.search = ''
-      url.searchParams.set(credential.name, credential.value)
-      const socket = new WebSocket(url, {
-        agent: this.upstreamSession.client.directAgent,
-        headers: { Origin: this.config.upstream.origin },
-        maxPayload: 36 * 1_024 * 1_024,
-        handshakeTimeout: 15_000,
-      })
-      this.#socket = socket
-      socket.on('message', (data, isBinary) => this.#queueFrame(generation, data, isBinary))
-      socket.once('error', () => {
-        if (socket.readyState !== WebSocket.OPEN) this.#scheduleReconnect(generation)
-      })
-      socket.once('close', () => this.#scheduleReconnect(generation))
-    } catch {
-      this.#scheduleReconnect(generation)
-    }
-  }
-
-  #queueFrame(generation: number, data: RawData, isBinary: boolean): void {
-    this.#frames = this.#frames.then(async () => {
-      if (!this.#running || generation !== this.#generation || isBinary) return
-      let frame: JsonRecord
-      try { frame = record(JSON.parse(Buffer.from(data as Uint8Array).toString('utf8'))) } catch { return }
-      if (string(frame.method) === 'event') {
-        const params = record(frame.params)
-        const eventType = string(params.type)
-        if (eventType === 'gateway.ready') {
-          this.#resumeRequestID = `push-resume:${this.#job.id}:${generation}`
-          this.#socket?.send(JSON.stringify({
-            jsonrpc: '2.0',
-            id: this.#resumeRequestID,
-            method: 'session.resume',
-            params: {
-              session_id: this.#job.storedSessionID,
-              profile: this.#job.profile,
-              source: 'web',
-              close_on_disconnect: false,
-              omit_messages: true,
-              cols: 80,
-            },
-          }))
-          return
-        }
-        const runtimeSessionID = string(params.session_id)
-        if (runtimeSessionID && this.#job.runtimeSessionID && runtimeSessionID !== this.#job.runtimeSessionID) return
-        const payload = record(params.payload)
-        const expectedRunID = string(this.#job.metadata?.runID)
-        const eventRunID = string(payload.run_id ?? payload.runId ?? payload.turn_id ?? payload.turnId)
-        if (expectedRunID && eventRunID !== expectedRunID) return
-        if (['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(eventType)) {
-          if (!await this.#ownershipStillAllowed()) return
-          if (!expectedRunID) {
-            let ownership: ChatTerminalContent = {}
-            try { ownership = await this.resolver.resolveTerminal(this.#job, eventType, payload) } catch { return }
-            if (ownership.correlated !== true) return
-          }
-          const candidate = chatInteractionCandidate(this.#job, eventType, payload)
-          if (candidate) await this.coordinator.enqueueNotification(candidate)
-          return
-        }
-        if (['message.complete', 'run.completed', 'run.failed', 'error'].includes(eventType)) {
-          await this.#finishTerminal(eventType, payload)
-        }
-        return
-      }
-      if (requestID(frame.id) !== this.#resumeRequestID) return
-      if (frame.error) throw new Error(errorMessage(frame.error) || 'Unable to resume chat push job')
-      const result = record(frame.result)
-      const runtimeSessionID = string(result.session_id ?? result.sessionId)
-      const storedSessionID = string(result.stored_session_id ?? result.storedSessionId ?? result.session_key)
-        || this.#job.storedSessionID
-      const resumedRunID = string(result.run_id ?? result.runId ?? result.turn_id ?? result.turnId)
-      const expectedRunID = string(this.#job.metadata?.runID)
-      if (!runtimeSessionID) throw new Error('Hermes resume did not return a runtime session ID')
-      const promptDigest = string(this.#job.metadata?.promptDigest)
-      if ((!expectedRunID && !promptDigest) || (expectedRunID && resumedRunID && resumedRunID !== expectedRunID)) {
-        this.#socket?.close(1012, 'push run ownership is not confirmed')
-        return
-      }
-      this.#job = {
-        ...this.#job,
-        runtimeSessionID,
-        storedSessionID,
-        phase: 'watching',
-        metadata: {
-          ...this.#job.metadata,
-          ...(expectedRunID ? { runID: expectedRunID } : {}),
-        },
-      }
-      await this.coordinator.saveChatJob(this.#job)
-      const approval = record(result.pending_approval)
-      const clarification = record(result.pending_clarify)
-      const pending = string(approval.request_id ?? approval.requestId ?? approval.id)
-        ? chatInteractionCandidate(this.#job, 'approval.requested', approval)
-        : string(clarification.request_id ?? clarification.requestId ?? clarification.id)
-          ? chatInteractionCandidate(this.#job, 'clarify.requested', clarification)
-          : undefined
-      if (pending) {
-        if (!await this.#ownershipStillAllowed()) return
-        if (!expectedRunID) {
-          let ownership: ChatTerminalContent = {}
-          try { ownership = await this.resolver.resolveTerminal(this.#job, 'interaction.requested', result) } catch { return }
-          if (ownership.correlated !== true) return
-        }
-        await this.coordinator.enqueueNotification(pending)
-        return
-      }
-      const inflight = record(result.inflight ?? result.active_run)
-      const queued = record(result.queued)
-      const running = result.running === true || inflight.streaming === true
-        || Boolean(string(queued.user ?? queued.text))
-      if (running && expectedRunID && !resumedRunID) {
-        this.#socket?.close(1012, 'active push run lacks ownership identity')
-        return
-      }
-      if (running) this.#retryAttempt = 0
-      if (!running) {
-        const resumeError = string(result.error ?? inflight.error)
-        if (resumeError) {
-          await this.#finishTerminal('run.failed', { ...result, error: resumeError })
-          return
-        }
-        let resolved: ChatTerminalContent = {}
-        try { resolved = await this.resolver.resolveTerminal(this.#job, 'run.completed', result) } catch { /* retry below */ }
-        if (resolved.confirmed !== true) {
-          this.#socket?.close(1012, 'awaiting authoritative terminal message')
-          return
-        }
-        await this.#finishTerminal(
-          resolved.failed ? 'run.failed' : 'run.completed',
-          resolved.failed ? { ...result, error: resolved.error ?? resolved.body } : result,
-          resolved,
-        )
-      }
-    }).catch(() => {
-      if (!this.#running || generation !== this.#generation) return
-      this.#socket?.close(1011, 'chat push watcher frame failed')
-      this.#scheduleReconnect(generation)
-    })
-  }
-
-  async #finishTerminal(eventType: string, payload: JsonRecord, resolved?: ChatTerminalContent): Promise<void> {
-    if (!this.#running) return
-    if (!await this.#ownershipStillAllowed()) {
-      this.stop()
-      this.#notifyFinished()
-      return
-    }
-    let ownership = resolved
-    if (!ownership) {
-      try { ownership = await this.resolver.resolveTerminal(this.#job, eventType, payload) } catch { ownership = {} }
-    }
-    const expectedRunID = string(this.#job.metadata?.runID)
-    const eventRunID = string(payload.run_id ?? payload.runId ?? payload.turn_id ?? payload.turnId)
-    const ownedByRun = Boolean(expectedRunID && eventRunID === expectedRunID)
-    const failed = eventType === 'run.failed' || eventType === 'error' || Boolean(payload.error)
-    if (ownership.confirmed !== true && !ownedByRun && !(failed && ownership.correlated === true)) {
-      this.#socket?.close(1012, 'terminal push ownership is not confirmed')
-      return
-    }
-    const candidate = await chatTerminalCandidate(this.#job, eventType, payload, this.resolver, ownership)
-    await this.coordinator.enqueueNotification(candidate)
-    await this.coordinator.completeChatJob(this.#job.id)
-    this.stop()
-    this.#notifyFinished()
-  }
-
-  #scheduleReconnect(generation: number): void {
-    if (!this.#running || generation !== this.#generation || this.#retryTimer) return
-    this.#socket = undefined
-    const delay = Math.min(60_000, 1_000 * 2 ** Math.min(this.#retryAttempt++, 6))
-    this.#retryTimer = setTimeout(() => {
-      this.#retryTimer = undefined
-      if (this.#running && generation === this.#generation) void this.#connect(generation)
-    }, delay)
-    this.#retryTimer.unref()
-  }
-
-  async #ownershipStillAllowed(): Promise<boolean> {
-    if (!this.coordinator.canRecoverChatJob) return true
-    try { return await this.coordinator.canRecoverChatJob(this.#job) } catch { return false }
-  }
-
-  #notifyFinished(): void {
-    if (this.#finished) return
-    this.#finished = true
-    this.onFinished?.(this.#job.id)
-  }
-}
-
-export interface ChatPushJobManagerOptions {
-  transportFactory?: ChatPushTransportFactory
-  maximumConcurrent?: number
-  reconcileMilliseconds?: number
-  now?: () => number
-  resolver?: ChatNotificationResolver
-}
-
-/** Starts and bounds the server-owned recovery sockets for persisted jobs. */
-export class ChatPushJobManager {
-  private transportFactory?: ChatPushTransportFactory
-  private brokerOwnsJob?: (job: ChatPushJob) => boolean
-  readonly #watchers = new Map<string, HermesChatPushJobWatcher>()
-  readonly #maximumConcurrent: number
-  readonly #reconcileMilliseconds: number
-  readonly #now: () => number
-  readonly #resolver: ChatNotificationResolver
-  #running = false
-  #timer?: ReturnType<typeof setInterval>
-  #activeReconcile?: Promise<void>
-
-  constructor(
-    readonly config: ServerConfig,
-    readonly upstreamSession: UpstreamServiceSession,
-    readonly coordinator: PushEventCoordinator,
-    options: ChatPushJobManagerOptions = {},
-  ) {
-    this.#maximumConcurrent = Math.max(1, Math.min(64, Math.trunc(options.maximumConcurrent ?? 16)))
-    this.#reconcileMilliseconds = Math.max(250, Math.trunc(options.reconcileMilliseconds ?? 1_000))
-    this.#now = options.now ?? Date.now
-    this.#resolver = options.resolver ?? new HermesChatNotificationResolver(upstreamSession)
-    this.transportFactory = options.transportFactory
-  }
-
-  setTransportFactory(factory: ChatPushTransportFactory, ownsJob?: (job: ChatPushJob) => boolean): void {
-    this.transportFactory = factory; this.brokerOwnsJob = ownsJob
-  }
-
-  start(): void {
-    if (this.#running) return
-    this.#running = true
-    void this.reconcile().catch(() => undefined)
-    this.#timer = setInterval(() => {
-      void this.reconcile().catch(() => undefined)
-    }, this.#reconcileMilliseconds)
-    this.#timer.unref()
-  }
-
-  stop(): void {
-    this.#running = false
-    if (this.#timer) clearInterval(this.#timer)
-    this.#timer = undefined
-    for (const watcher of this.#watchers.values()) watcher.stop()
-    this.#watchers.clear()
-  }
-
-  reconcile(): Promise<void> {
-    if (this.#activeReconcile) return this.#activeReconcile
-    const operation = this.#reconcile()
-    const tracked = operation.finally(() => {
-      if (this.#activeReconcile === tracked) this.#activeReconcile = undefined
-    })
-    this.#activeReconcile = tracked
-    return tracked
-  }
-
-  async #reconcile(): Promise<void> {
-    if (!this.#running) return
-    const pending = [...await this.coordinator.pendingChatJobs()]
-    const now = this.#now()
-    for (const job of pending) {
-      if (job.expiresAt <= now) await this.coordinator.completeChatJob(job.id)
-    }
-    const jobs: ChatPushJob[] = []
-    for (const job of pending) {
-      const structurallyEligible = job.expiresAt > now
-        && job.metadata?.baselineCaptured === true
-        && (Boolean(this.transportFactory) || Number.isFinite(Number(job.metadata?.disconnectedAt)))
-        && Boolean(string(job.metadata?.runID) || string(job.metadata?.promptDigest))
-        && (job.phase === 'submitted' || job.phase === 'accepted' || job.phase === 'watching')
-      if (!structurallyEligible) continue
-      if (this.brokerOwnsJob?.(job)) continue
-      if (this.coordinator.canRecoverChatJob
-        && !await this.coordinator.canRecoverChatJob(job)) continue
-      jobs.push(job)
-    }
-    jobs.sort((left, right) => left.submittedAt - right.submittedAt)
-    if (!this.#running) return
-    const pendingIDs = new Set(jobs.map(job => job.id))
-    for (const [jobID, watcher] of this.#watchers) {
-      if (pendingIDs.has(jobID)) continue
-      watcher.stop()
-      this.#watchers.delete(jobID)
-    }
-    for (const job of jobs) {
-      if (!this.#running || this.#watchers.size >= this.#maximumConcurrent) break
-      if (this.#watchers.has(job.id)) continue
-      const watcher = new HermesChatPushJobWatcher(
-        job,
-        this.config,
-        this.upstreamSession,
-        this.coordinator,
-        this.#resolver,
-        this.#now,
-        jobID => {
-          this.#watchers.delete(jobID)
-          if (this.#running) void this.reconcile()
-        },
-        this.transportFactory,
-      )
-      this.#watchers.set(job.id, watcher)
-      watcher.start()
-    }
-  }
-}

+ 0 - 261
src/server/realtimeApi.ts

@@ -1,261 +0,0 @@
-import type { AgentExportContext } from './workspaceRemoteAgents.js'
-import { randomBytes } from 'node:crypto'
-import type { Server, IncomingMessage } from 'node:http'
-import type { Duplex } from 'node:stream'
-import type Koa from 'koa'
-import { RealtimeBroker, type RealtimePrincipal, type RealtimeChannel } from './realtimeBroker.js'
-import type { ServerConfig } from './config.js'
-import { LocalAuthStore, UpstreamServiceSession } from './localAuth.js'
-import { NodePairingStore } from './pairing.js'
-import { CookieJar, UpstreamClient } from './upstream.js'
-import { CsrfProtection, isAllowedHostHeader, isExactOrigin } from './security.js'
-import { HttpError } from './errors.js'
-import { configuredWorkingDirectory } from './sessionWorkingDirectory.js'
-import { canonicalEpoch, groupCursor } from './realtimeProtocol.js'
-import { CHAT_MAX_PAYLOAD } from './realtimeProtocol.js'
-import { CHAT_TRANSCRIPT_FEATURE } from '../shared/chatTranscript.js'
-import { ChatPushRelayObserver, type ChatNotificationResolver, type PushEventCoordinator, type ChatPushTransportFactory } from './pushEvents.js'
-
-export class RealtimeAPI {
-  transcriptsAvailable = false
-  /** Embedded Hermes gateway used for local chats (set by the application). */
-  gateway?: import('./hermes/gateway.js').EmbeddedGateway
-  readonly broker: RealtimeBroker
-  private observers = new Map<string, ChatPushRelayObserver>()
-  constructor(readonly config: ServerConfig, readonly auth: LocalAuthStore, readonly csrf: CsrfProtection,
-    readonly pairings: NodePairingStore, readonly upstream: UpstreamClient, readonly session: UpstreamServiceSession,
-    readonly push?: { coordinator: PushEventCoordinator; resolver: ChatNotificationResolver },
-    readonly ownsSession?: (owner: string, profile: string, sessionId: string) => boolean) {
-    this.broker = new RealtimeBroker(config.home, Date.now, change => {
-      upstream.observeRealtime(change)
-      if (change.kind === 'reset') session.invalidateAuthentication()
-    })
-  }
-  private async canResume(profile: string, sessionId: string, _jar?: CookieJar, owner?: string): Promise<boolean> {
-    return owner ? this.ownsSession?.(owner, profile, sessionId) ?? false : false
-  }
-  private principal(ctx: Koa.Context, device?: string): RealtimePrincipal {
-    const exported=ctx.state.workspaceAgentExport as AgentExportContext | undefined
-    const upstream=exported?.target.client ?? this.upstream
-    const endpoint=exported?.target.url ?? this.config.upstream
-    let key: string
-    let valid: () => boolean
-    let authorize: RealtimePrincipal['authorize']
-    let jar: CookieJar | undefined
-    let owner: string | undefined
-    let observer: ChatPushRelayObserver | undefined
-    if (device) {
-      const bearer = ctx.get('authorization').match(/^Bearer\s+(.+)$/i)?.[1] ?? ''
-      jar = new CookieJar(this.pairings.authorize(device, bearer))
-      key = `device:${device}${exported ? ':agent:'+exported.id : ''}`
-      owner = key
-      valid = () => this.pairings.hasDevice(device) && (!exported || exported.valid())
-      authorize = (kind, method) => {
-        this.pairings.authorize(device, bearer, kind === 'groups' ? 'groups.read'
-          : method === 'profiles.list' || method === 'profiles.get_asset' ? 'agents.read' : 'sessions.execute')
-      }
-    } else {
-      const user = this.auth.require(ctx)
-      owner = user.id
-      const cookie = ctx.get('cookie')
-      key = `user:${user.id}:${this.auth.pushAuthorizationVersion(user.id)}`
-      valid = () => { try { return this.auth.currentFromCookieHeader(cookie)?.id === user.id } catch { return false } }
-      if (this.push) {
-        observer = this.observers.get(key)
-        if (!observer) {
-          observer = new ChatPushRelayObserver(this.push.coordinator, { localUserID: user.id, source: 'web' }, Date.now, this.push.resolver)
-          this.observers.set(key, observer)
-        }
-      }
-    }
-    const nativeBot = ctx.state.hermesBotNative === true
-    if (nativeBot) key = `native:${key}`
-    const embedded = !exported && this.upstream.embedded ? this.gateway : undefined
-    return {
-      ...(embedded ? { embedded } : {}),
-      key, nativeBot, instanceKey: endpoint.href, upstreamKey: `${endpoint.href}:${device ? key : 'service'}`, paired: Boolean(device), valid, authorize,
-      canResume: (profile, sessionId) => this.canResume(profile, sessionId, jar, owner),
-      configuredWorkingDirectory: profile => configuredWorkingDirectory((path, options) => {
-        if (!valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-        if (exported && endpoint.href !== this.config.upstream.href) return exported.target.session.request(path, options)
-        if (jar) return this.upstream.request(path, jar, options)
-        return this.session.request(path, options)
-      }, profile),
-      agent: upstream.directAgent,
-      observeCommand: f => observer?.observeClientFrame(f),
-      observeEvent: f => observer?.observeUpstreamFrame(Buffer.from(f), false),
-      url: async (kind, anchor) => {
-        if (device && !valid()) throw new HttpError(401, 'Device revoked', 'authentication_required')
-        // Paired devices retain their delegated identity; never upgrade a device
-        // cookie into the local service's loopback authorization.
-        let credential: { name: string; value: string }
-        if (exported && endpoint.href !== this.config.upstream.href) credential = await exported.target.session.webSocketCredential()
-        else if (jar) {
-          const response = await this.upstream.request('/api/auth/ws-ticket', jar, { method: 'POST' })
-          if (response.status !== 200) throw new HttpError(502, 'Upstream authentication failed', 'upstream_auth_failed')
-          const ticket = JSON.parse(response.body.toString()).ticket
-          if (typeof ticket !== 'string' || !ticket) throw new HttpError(502, 'Invalid upstream ticket', 'invalid_ticket')
-          credential = { name: 'ticket', value: ticket }
-        } else credential = await this.session.webSocketCredential()
-        const url = new URL(endpoint)
-        url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
-        url.pathname = `${url.pathname.replace(/\/$/, '')}/api/ws`
-        url.search = ''; url.searchParams.set(credential.name, credential.value)
-        if (anchor) { url.searchParams.set('epoch', anchor.epoch); url.searchParams.set('cursor', String(anchor.cursor)) }
-        return url
-      },
-    }
-  }
-  recoveryTransport: ChatPushTransportFactory = async (job, onFrame, onClose) => {
-    const principal: RealtimePrincipal = {
-      key: `push:${job.localUserID}:${this.auth.pushAuthorizationVersion(job.localUserID)}`,
-      upstreamKey: `${this.config.upstream.href}:service`, paired: false,
-      instanceKey: this.config.upstream.href,
-      agent: this.upstream.directAgent,
-      ...(this.upstream.embedded && this.gateway ? { embedded: this.gateway } : {}),
-      valid: () => this.auth.isUserActive(job.localUserID),
-      url: async () => {
-        const credential = await this.session.webSocketCredential()
-        const url = new URL(this.config.upstream)
-        url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
-        url.pathname = `${url.pathname.replace(/\/$/, '')}/api/ws`
-        url.search = ''; url.searchParams.set(credential.name, credential.value)
-        return url
-      },
-    }
-    const channel = await this.broker.create(principal, 'chat')
-    let off = () => {}, closed = false
-    return {
-      start: () => { off = this.broker.subscribe(channel, undefined, entry => { if (entry.event === 'reset') onClose(); else onFrame(entry.data) }) },
-      send: raw => {
-        const frame = JSON.parse(raw)
-        void Promise.resolve().then(() => this.broker.command(channel, randomBytes(24).toString('hex'), frame)).then(receipt => {
-          if (!closed) onFrame(JSON.stringify({ id: frame.id, ...(receipt.response ?? { error: { message: 'Submission uncertain' } }) }))
-        }).catch(onClose)
-      },
-      close: () => { closed = true; off(); this.broker.release(channel) },
-    }
-  }
-  ownsPushJob(jobID: string): boolean { return [...this.observers.values()].some(observer => observer.ownsJob(jobID)) }
-  private checkMutation(ctx: Koa.Context, paired: boolean): void {
-    if (paired || ['GET', 'HEAD'].includes(ctx.method)) return
-    if (!isExactOrigin(ctx.get('origin'), ctx.get('host'), ctx.secure || Boolean(this.config.tlsCert), this.config.allowedHosts)
-      || !this.csrf.verify(ctx.get('cookie'), ctx.get('x-csrf-token'))) {
-      throw new HttpError(403, 'Origin or CSRF token is invalid', 'invalid_csrf')
-    }
-  }
-  private async body(ctx: Koa.Context, limit = 2 * 1024 * 1024): Promise<Record<string, any>> {
-    if (!ctx.is('application/json')) throw new HttpError(415, 'JSON body required', 'invalid_content_type')
-    let bytes = 0
-    const chunks: Buffer[] = []
-    const timeout = setTimeout(() => ctx.req.destroy(), 30_000)
-    timeout.unref()
-    try {
-      for await (const chunk of ctx.req) {
-        bytes += Buffer.byteLength(chunk)
-        if (bytes > limit) throw new HttpError(413, 'Request body too large', 'body_too_large')
-        chunks.push(Buffer.from(chunk))
-      }
-      const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))
-      if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not object')
-      return value as Record<string, any>
-    } catch (e) { if (e instanceof HttpError) throw e; throw new HttpError(400, 'Invalid JSON', 'invalid_json_body') }
-    finally { clearTimeout(timeout) }
-  }
-  middleware(): Koa.Middleware {
-    return async (ctx, next) => {
-      const match = /^(?:\/node\/([0-9a-f-]{36}))?\/api\/realtime(\/.*)$/.exec(ctx.path)
-      if (/^(?:\/node\/[^/]+)?\/api\/(?:auth\/ws-ticket|ws|plugins\/yaoyao\/v1\/events)$/.test(ctx.path)
-        || ctx.path === '/api/app/realtime-leases' || /^\/ws\/(?:chat|groups)$/.test(ctx.path)) {
-        throw new HttpError(410, 'Legacy realtime endpoints were removed; use HTTP+SSE', 'http_sse_required')
-      }
-      if (!match) return next()
-      const device = match[1]
-      const principal = this.principal(ctx, device)
-      ctx.set('Cache-Control', 'no-store')
-      const path = match![2]!
-      if (ctx.method === 'GET' && path === '/capabilities') {
-        ctx.body = { protocolVersion: 1, channels: ['chat'], brokerEpoch: this.broker.epoch,
-          features: this.transcriptsAvailable && !device && !ctx.state.hermesBotNative && !ctx.state.workspaceAgentExport ? [CHAT_TRANSCRIPT_FEATURE] : [],
-          ...(device ? {} : { csrfToken: this.csrf.issue(ctx) }) }
-        return
-      }
-      this.checkMutation(ctx, Boolean(device))
-      if (ctx.method === 'POST' && path === '/channels') {
-        const body = await this.body(ctx)
-        if (ctx.state.workspaceAgentExport && body.channel !== 'chat') throw new HttpError(403,'机器人仅支持聊天通道','invalid_channel')
-        if (body.channel !== 'chat' && body.channel !== 'groups') throw new HttpError(400, 'Invalid channel', 'invalid_channel')
-        if(this.transcriptsAvailable&&body.channel==='chat'&&!device&&!principal.nativeBot&&!ctx.state.workspaceAgentExport&&body.chatProtocol!==CHAT_TRANSCRIPT_FEATURE)
-          throw new HttpError(426,'普通聊天协议已升级,请更新客户端后继续','ordinary_chat_upgrade_required')
-        const c = await this.broker.create(principal, body.channel, body.channel === 'groups'
-          ? { epoch: canonicalEpoch(body.epoch), cursor: groupCursor(body.cursor) } : undefined)
-        ctx.status = 201; ctx.body = { id: c.id, brokerEpoch: this.broker.epoch }; return
-      }
-      const receipt = /^\/commands\/([^/]+)$/.exec(path)
-      if (receipt && ctx.method === 'GET') {
-        let id: string
-        try { id = decodeURIComponent(receipt[1]!) } catch { throw new HttpError(400, 'Invalid request ID', 'invalid_request_id') }
-        if (!/^[A-Za-z0-9:_-]{1,200}$/.test(id)) throw new HttpError(400, 'Invalid request ID', 'invalid_request_id')
-        ctx.body = this.broker.receipt(principal, id); return
-      }
-      const channel = /^\/channels\/([0-9a-f-]{36})(?:\/(commands|events))?$/.exec(path)
-      if (!channel) throw new HttpError(404, 'Realtime route not found', 'not_found')
-      const c = this.broker.get(principal, channel[1]!)
-      if (ctx.method === 'DELETE' && !channel[2]) { this.broker.detach(principal, c.id); ctx.status = 204; return }
-      if (ctx.method === 'POST' && channel[2] === 'commands') {
-        let body = await this.body(ctx, CHAT_MAX_PAYLOAD)
-        const exported=ctx.state.workspaceAgentExport as AgentExportContext | undefined
-        if (exported) body=exported.transform(body)
-        ctx.body = await this.broker.command(c, ctx.get('idempotency-key'), body)
-        return
-      }
-      if (ctx.method === 'GET' && channel[2] === 'events') { this.stream(ctx, c); return }
-      throw new HttpError(405, 'Method not allowed', 'method_not_allowed')
-    }
-  }
-  private stream(ctx: Koa.Context, c: RealtimeChannel): void {
-    const res = ctx.res
-    const initial: string[] = []
-    let started = false
-    let closed = false
-    let congested: ReturnType<typeof setTimeout> | undefined
-    let heartbeat: ReturnType<typeof setInterval> | undefined
-    let off = () => {}
-    const close = () => { if (closed) return; closed = true; clearInterval(heartbeat); clearTimeout(congested); off(); if (!res.writableEnded) res.end() }
-    const write = (text: string) => {
-      if (!started) { initial.push(text); return }
-      if (res.destroyed || res.writableEnded) return close()
-      if (res.writableLength + Buffer.byteLength(text) > 1024 * 1024) return close()
-      if (!res.write(text) && !congested) { congested = setTimeout(close, 15_000); congested.unref() }
-    }
-    off = this.broker.subscribe(c, ctx.get('last-event-id') || undefined, entry => {
-      write(`id: ${entry.id}\nevent: ${entry.event}\ndata: ${entry.data}\n\n`)
-      if (entry.event === 'reset' && started) close()
-    })
-    ctx.respond = false
-    res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' })
-    res.flushHeaders(); started = true
-    write(`event: ready\ndata: ${JSON.stringify({ channelId: c.id, brokerEpoch: this.broker.epoch })}\n\n`)
-    for (const text of initial) write(text)
-    heartbeat = setInterval(() => { if (!c.principal.valid()) close(); else write(': heartbeat\n\n') }, 15_000)
-    heartbeat.unref()
-    res.on('drain', () => { clearTimeout(congested); congested = undefined })
-    res.once('close', close)
-    res.once('error', close)
-  }
-
-  rejectLegacyUpgrades(server: Server): () => void {
-    const upgrade = (request: IncomingMessage, socket: Duplex) => {
-      const path = (request.url ?? '/').split('?')[0]!
-      if (!this.config.production && !path.startsWith('/api/') && !path.startsWith('/node/') && !path.startsWith('/ws/')) return
-      const body = JSON.stringify({ code: 'http_sse_required', error: 'Client WebSockets are no longer supported; use HTTP+SSE' })
-      socket.end('HTTP/1.1 410 Gone\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ' + Buffer.byteLength(body) + '\r\n\r\n' + body)
-    }
-    server.on('upgrade', upgrade)
-    return () => server.off('upgrade', upgrade)
-  }
-  close(): void {
-    for (const observer of this.observers.values()) observer.disconnected()
-    this.observers.clear(); this.broker.close()
-  }
-}

+ 0 - 666
src/server/realtimeBroker.ts

@@ -1,666 +0,0 @@
-import { randomUUID } from 'node:crypto'
-import WebSocket from 'ws'
-import { EmbeddedSocket } from './hermes/socket.js'
-import { HttpError } from './errors.js'
-import { checkedChatFrame, CHAT_MAX_PAYLOAD, GroupFrameValidator } from './realtimeProtocol.js'
-import { RealtimeReceipts, type CommandReceipt } from './realtimeReceipts.js'
-import { applyWorkingDirectory, type AppliedWorkingDirectory } from './sessionWorkingDirectory.js'
-
-type Frame = Record<string, any>
-export interface RealtimeActivity { kind: 'command' | 'event' | 'group' | 'reset'; name: string; sessionId?: string; roomId?: string }
-export interface RealtimePrincipal {
-  key: string
-  upstreamKey: string
-  instanceKey?: string
-  paired: boolean
-  nativeBot?: boolean
-  agent?: WebSocket.ClientOptions['agent']
-  valid(): boolean
-  authorize?(kind: 'chat' | 'groups', method?: string): void
-  canResume?(profile: string, sessionId: string): Promise<boolean>
-  configuredWorkingDirectory?(profile: string): Promise<string | undefined>
-  url(channel: 'chat' | 'groups', anchor?: { epoch: string; cursor: number }): Promise<URL>
-  /** In-process Hermes gateway; when set the broker never opens a network socket. */
-  embedded?: import('./hermes/gateway.js').EmbeddedGateway
-  observeCommand?(frame: string): void
-  observeEvent?(frame: string): void
-}
-export interface StreamEntry { id: string; event: 'frame' | 'reset'; data: string; at: number; bytes: number }
-export interface RealtimeChannel {
-  id: string; kind: 'chat' | 'groups'; principal: RealtimePrincipal
-  seq: number; droppedThrough: number; entries: StreamEntry[]; routes: Set<string>
-  listeners: Set<(entry: StreamEntry) => void>; touched: number; bytes: number
-  group?: { epoch: string; cursor: number }; socket?: WebSocket
-}
-interface Route { profile: string; stored: string; runtime: string; active: boolean; seq: number; observers: Map<string, RealtimePrincipal>; cwd?: string; workingDirectory?: AppliedWorkingDirectory }
-interface Pending { resolve(frame: Frame): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }
-interface Upstream {
-  principal: RealtimePrincipal; socket?: WebSocket; connecting?: Promise<void>; ready?: Frame
-  pending: Map<string, Pending>; routes: Map<string, Route>; byRuntime: Map<string, Route>
-  tails: Map<string, Promise<unknown>>; early: Map<string, Frame[]>; earlyBytes: number
-  retry?: ReturnType<typeof setTimeout>; attempts: number; epoch?: string; recovering: boolean
-  lastUsed: number; ping?: ReturnType<typeof setInterval>
-  deferred: Frame[]
-  recovery?: Promise<void>
-}
-
-/** Server-owned WS transports. Downstream detach never tears down an active upstream. */
-export class RealtimeBroker {
-  get idleForUpdate(): boolean {
-    return this.commands.size === 0 && [...this.upstreams.values()].every(upstream => upstream.pending.size === 0 && [...upstream.routes.values()].every(route => !route.active))
-  }
-  protectedSession: (id: string) => boolean = () => false
-  assertCanCommand:()=>void=()=>{}
-  onNativeEvent: (owner: string, profile: string, storedId: string, frame: Frame) => void = () => {}
-  onNativeGlobalEvent: (owner: string, type: string, upstreamInvalidation?: boolean) => void = () => {}
-  onNativeCommand: (owner: string, profile: string, storedId: string, method: string, params: Frame) => void = () => {}
-  onNativeRoute: (owner: string, profile: string, storedId: string, runtimeId: string, running?: boolean, snapshot?: Frame) => void = () => {}
-  nativeSourceCursor: (owner:string,profile:string,storedId:string,runtimeId:string,epoch:string)=>number = () => 0
-  readonly epoch = randomUUID()
-  readonly channels = new Map<string, RealtimeChannel>()
-  private upstreams = new Map<string, Upstream>()
-  private commands = new Map<string, Promise<CommandReceipt>>()
-  private completed = new Map<string, { receipt: CommandReceipt; at: number; bytes: number }>()
-  private receipts: RealtimeReceipts
-  private timer: ReturnType<typeof setInterval>
-  private closed = false
-  constructor(home: string, readonly now = Date.now, readonly onActivity: (activity: RealtimeActivity) => void = () => {}) {
-    this.receipts = new RealtimeReceipts(home)
-    this.timer = setInterval(() => this.sweep(), 5_000)
-    this.timer.unref()
-  }
-
-  async create(principal: RealtimePrincipal, kind: 'chat' | 'groups', group?: { epoch: string; cursor: number }): Promise<RealtimeChannel> {
-    if (String(kind) === 'groups') throw new HttpError(410, '请使用新版聊天事件接口', 'retired_group_stream')
-    if (this.closed) throw new HttpError(503, 'Realtime broker is stopping', 'broker_stopping')
-    principal.authorize?.(kind)
-    if (!principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-    // Closed pages leave resumable channels behind. They must not consume the live-stream
-    // quota; evict oldest detached handles under pressure, never a running upstream.
-    let own = [...this.channels.values()].filter(c => c.principal.key === principal.key)
-    while (own.length >= 32) {
-      const stale = own.filter(c => !c.listeners.size).sort((a, b) => a.touched - b.touched)[0]
-      if (!stale) break
-      this.remove(stale); own = own.filter(c => c !== stale)
-    }
-    if (own.length >= 32 || this.channels.size >= 512) {
-      throw new HttpError(429, 'Too many realtime channels', 'channel_limit')
-    }
-    const c: RealtimeChannel = { id: randomUUID(), kind, principal, seq: 0, droppedThrough: 0,
-      entries: [], routes: new Set(), listeners: new Set(), touched: this.now(), bytes: 0, group }
-    this.channels.set(c.id, c)
-    try {
-      {
-        const u = this.upstream(principal)
-        await this.connect(u)
-        this.emit(c, 'frame', u.ready!)
-      }
-      return c
-    } catch (e) { this.remove(c); throw e }
-  }
-
-  get(principal: RealtimePrincipal, id: string): RealtimeChannel {
-    const c = this.channels.get(id)
-    if (!c || c.principal.key !== principal.key) throw new HttpError(404, 'Channel not found', 'channel_not_found')
-    if (!principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-    c.touched = this.now()
-    return c
-  }
-  detach(principal: RealtimePrincipal, id: string): void { this.remove(this.get(principal, id)) }
-  release(c: RealtimeChannel): void { if (this.channels.get(c.id) === c) this.remove(c) }
-  private remove(c: RealtimeChannel): void {
-    this.channels.delete(c.id)
-    c.socket?.close()
-    for (const listener of c.listeners) {
-      try { listener({ id: '', event: 'reset', data: '{"reason":"channel_closed"}', at: this.now(), bytes: 0 }) } catch { /* a closed consumer must not affect the upstream */ }
-    }
-    c.listeners.clear()
-  }
-  subscribe(c: RealtimeChannel, cursor: string | undefined, listener: (entry: StreamEntry) => void): () => void {
-    if ([...this.channels.values()].filter(v => v.principal.key === c.principal.key).reduce((n, v) => n + v.listeners.size, 0) >= 8) {
-      throw new HttpError(429, 'Too many active event streams', 'stream_limit')
-    }
-    this.trim(c)
-    let seq = 0
-    if (cursor) {
-      const prefix = `${this.epoch}:`
-      if (!cursor.startsWith(prefix) || !/^\d+$/.test(cursor.slice(prefix.length))) {
-        throw new HttpError(409, 'Stream epoch changed', 'reset_required')
-      }
-      seq = Number(cursor.slice(prefix.length))
-    }
-    if (!Number.isSafeInteger(seq) || seq < c.droppedThrough || seq > c.seq) {
-      throw new HttpError(409, 'Replay window expired', 'reset_required')
-    }
-    c.listeners.add(listener)
-    for (const entry of c.entries) if (Number(entry.id.split(':').at(-1)) > seq) listener(entry)
-    return () => { c.listeners.delete(listener); c.touched = this.now() }
-  }
-  receipt(p: RealtimePrincipal, id: string): CommandReceipt {
-    if (!p.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-    const receipt = this.completed.get(`${p.key}:${id}`)?.receipt ?? this.receipts.lookup(p.key, id)
-    if (!receipt) throw new HttpError(404, 'Receipt not found; do not automatically resubmit an attempted command', 'receipt_not_found')
-    return receipt
-  }
-
-  command(c: RealtimeChannel, requestId: string, input: Frame): Promise<CommandReceipt> {
-    if (this.closed) throw new HttpError(503, 'Realtime broker is stopping', 'broker_stopping')
-    this.assertCanCommand()
-    if (c.kind !== 'chat') throw new HttpError(403, 'Group event channel is read-only', 'read_only')
-    const normalized = checkedChatFrame(Buffer.from(JSON.stringify(input)), false, c.principal.paired)
-    const frame = JSON.parse(normalized) as Frame
-    if (Object.values(frame.params?.preferred_session_ids ?? {}).some(id => typeof id === 'string' && this.protectedSession(id))) {
-      throw new HttpError(404, '会话不存在', 'session_not_found')
-    }
-    c.principal.authorize?.('chat', String(frame.method))
-    delete frame.id
-    const fingerprint = JSON.stringify(frame)
-    if (!this.receipts.lookup(c.principal.key, requestId) && (this.commands.size >= 1024
-      || [...this.commands.keys()].filter(k => k.startsWith(`${c.principal.key}:`)).length >= 32)) {
-      throw new HttpError(429, 'Too many pending commands', 'command_limit')
-    }
-    const existing = this.receipts.reserve(c.principal.key, requestId, fingerprint)
-    const key = `${c.principal.key}:${requestId}`
-    if (existing) return this.commands.get(key) ?? Promise.resolve(this.completed.get(key)?.receipt ?? existing)
-    const work = this.perform(c, frame, requestId).then(response => {
-      const state = response.error ? 'rejected' : 'confirmed'
-      this.receipts.finish(c.principal.key, requestId, state, response, frame)
-      return { requestId, state, response } as CommandReceipt
-    }, (error: unknown) => {
-      if (error instanceof HttpError) {
-        const response = { error: { code: error.code, message: error.message } }
-        this.receipts.finish(c.principal.key, requestId, 'rejected', response)
-        return { requestId, state: 'rejected', response } as CommandReceipt
-      }
-      this.receipts.finish(c.principal.key, requestId, 'unknown')
-      return { requestId, state: 'unknown' } as CommandReceipt
-    })
-    this.commands.set(key, work)
-    void work.then(receipt => {
-      this.commands.delete(key)
-      this.completed.set(key, { receipt, at: this.now(), bytes: Buffer.byteLength(JSON.stringify(receipt)) })
-      while (this.completed.size > 10_000 || [...this.completed.values()].reduce((n, x) => n + x.bytes, 0) > 32 * 1024 * 1024) this.completed.delete(this.completed.keys().next().value!)
-    })
-    return work
-  }
-
-  private async perform(c: RealtimeChannel, frame: Frame, deliveryID: string): Promise<Frame> {
-    const u = this.upstream(c.principal)
-    const p = frame.params as Frame
-    if (p.session_id && this.protectedSession(String(p.session_id))) throw new HttpError(404, '会话不存在', 'session_not_found')
-    const method = String(frame.method)
-    const opening = method === 'session.create' || method === 'session.resume'
-    if (opening && (c.routes.size >= 128 || u.routes.size >= 512)) throw new HttpError(429, 'Route capacity reached', 'route_limit')
-    let route = p.session_id ? u.byRuntime.get(p.session_id) : undefined
-    if (!opening && !method.startsWith('profiles.')) {
-      if (!route && (method === 'approval.respond' || method === 'clarify.respond')) {
-        // These RPCs use request_id rather than session_id; resolve only a pending interaction seen by this channel.
-        const match = [...c.routes].map(k => u.routes.get(k)).find(r => r && this.interactions.get(`${u.principal.upstreamKey}:${p.request_id}`) === r.runtime)
-        route = match
-      }
-      if (!route || !c.routes.has(this.routeKey(route.profile, route.stored))) throw new HttpError(403, 'Session is not subscribed', 'route_forbidden')
-      if (['approval.respond', 'clarify.respond'].includes(method)
-        && this.interactions.get(`${u.principal.upstreamKey}:${p.request_id}`) !== route.runtime) {
-        throw new HttpError(403, 'Interaction does not belong to this session', 'interaction_forbidden')
-      }
-    }
-    const routeKey = opening ? this.routeKey(String(p.profile), String(p.session_id ?? c.id))
-      : route ? this.routeKey(route.profile, route.stored) : 'profiles'
-    const execute = async () => {
-      if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-      if (method === 'session.resume') {
-        let permitted = !c.principal.canResume || await c.principal.canResume(String(p.profile), String(p.session_id))
-        if (c.principal.nativeBot) {
-          await this.connect(u)
-          const roster = await this.rpc(u, 'profiles.list', {include_sessions: false})
-          const profiles = roster.result?.profiles
-          const bot = Array.isArray(profiles) ? profiles.find((value: Frame) => value.name === p.profile) : undefined
-          permitted = !roster.error && typeof p.session_id === 'string' && p.session_id.length > 0 &&
-            bot?.ui_meta?.['hermes-bots']?.chat === p.session_id
-        }
-        if (!permitted) {
-          throw new HttpError(403, '此会话属于历史记录,不能继续聊天', 'history_session_read_only')
-        }
-        const ownerKey = JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, p.profile, p.session_id])
-        const owner = this.routeOwners.get(ownerKey)
-        if (owner && owner !== c.principal.upstreamKey) throw new HttpError(409, 'Session is attached through another credential scope', 'session_scope_conflict')
-        this.routeOwners.set(ownerKey, c.principal.upstreamKey)
-      }
-      await this.connect(u)
-      await u.recovery
-      if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-      if (!c.principal.nativeBot && c.principal.configuredWorkingDirectory) {
-        if (method === 'session.create') {
-          const cwd = await c.principal.configuredWorkingDirectory(String(p.profile))
-          // Client cwd is never authoritative, including paired mobile clients.
-          delete p.cwd
-          if (cwd) p.cwd = cwd
-        } else if (route && !route.active && ['prompt.submit', 'file.attach', 'image.attach_bytes', 'pdf.attach'].includes(method)) {
-          const cwd = await c.principal.configuredWorkingDirectory(route.profile)
-          if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-          route.workingDirectory = await applyWorkingDirectory(async (method, params) => {
-            const response = await this.rpc(u, method, params)
-            if (response.error) throw new HttpError(502, response.error.message || '无法切换到机器人工作目录', 'working_directory_rejected')
-            return response.result
-          }, route.runtime, cwd, route.workingDirectory, route.cwd)
-          if (route.workingDirectory) route.cwd = route.workingDirectory.resolved
-        }
-        if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-      }
-      const submittedAt = this.now()/1000
-      const previouslyActive = route?.active ?? false
-      if (route && (method === 'prompt.submit' || method === 'session.steer')) route.active = true
-      const nativeOwner = this.nativeOwner(c.principal)
-      if (nativeOwner && route && ['prompt.submit', 'session.steer'].includes(method)) {
-        this.onNativeCommand(nativeOwner, route.profile, route.stored, method, {...p,_delivery_id:deliveryID})
-        const peer={jsonrpc:'2.0',method:'event',params:{type:'run.peer_user_message',session_id:route.runtime,profile:route.profile,
-          payload:{message_id:`user:${deliveryID}`,queue_id:deliveryID.replace(/^(web|ios):prompt:/,''),client_message_id:deliveryID.replace(/^(web|ios):prompt:/,''),text:p.text??'',timestamp:submittedAt}}}
-        for(const channel of this.channels.values())if(channel.routes.has(this.routeKey(route.profile,route.stored))&&channel.principal.valid()&&this.nativeOwner(channel.principal)===nativeOwner)this.emit(channel,'frame',peer)
-      }
-      const activity: RealtimeActivity = { kind: 'command', name: method, sessionId: route?.stored }
-      this.onActivity(activity)
-      const response = await this.rpc(u, method, p, f => c.principal.observeEvent?.(JSON.stringify(f)), f => c.principal.observeCommand?.(JSON.stringify(f)))
-        .finally(() => this.onActivity(activity))
-      if (nativeOwner && route && ['prompt.submit','session.steer'].includes(method)) {
-        this.onNativeEvent(nativeOwner,route.profile,route.stored,{type:response.error?'command.rejected':'command.confirmed',
-          delivery_id:`command-result:${deliveryID}`,payload:{delivery_id:deliveryID,error:response.error?.message,status:response.result?.status}})
-        const peer={jsonrpc:'2.0',method:'event',params:{type:'run.peer_user_message',session_id:route.runtime,profile:route.profile,
-          payload:{message_id:`user:${deliveryID}`,queue_id:deliveryID.replace(/^(web|ios):prompt:/,''),client_message_id:deliveryID.replace(/^(web|ios):prompt:/,''),text:p.text??'',status:response.error?'failed':'accepted',timestamp:submittedAt}}}
-        for(const channel of this.channels.values())if(channel.routes.has(this.routeKey(route.profile,route.stored))&&channel.principal.valid()&&this.nativeOwner(channel.principal)===nativeOwner)this.emit(channel,'frame',peer)
-
-      }
-      if (response.error && route && (method === 'prompt.submit' || method === 'session.steer')) route.active = previouslyActive
-      if (!response.error && route && (method === 'prompt.submit' || method === 'session.steer')) route.active = true
-      if ((opening || method === 'session.branch') && response.result) {
-        const result = response.result as Frame
-        const info = result.info ?? {}
-        const runtime = String(result.session_id ?? '')
-        const stored = String(result.stored_session_id ?? result.session_key ?? info.stored_session_id ?? p.session_id ?? runtime)
-        if (!runtime || !stored) throw new Error('Invalid upstream session identity')
-        const profile = String(p.profile ?? route?.profile ?? 'default')
-        const key = this.routeKey(profile, stored)
-        this.routeOwners.set(JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, profile, stored]), c.principal.upstreamKey)
-        const r: Route = u.routes.get(key) ?? { profile, stored, runtime, active: false, seq: 0, observers: new Map() }
-        u.byRuntime.delete(r.runtime)
-        r.runtime = runtime
-        r.active = result.running === true || info.running === true
-        // Resume/reconnect may have restored a historical cwd or another runtime.
-        r.workingDirectory = undefined
-        r.cwd = typeof info.cwd === 'string' ? info.cwd : undefined
-        u.routes.set(key, r); u.byRuntime.set(runtime, r); c.routes.add(key)
-        r.observers.set(c.principal.key, c.principal)
-        if (nativeOwner) {
-          r.seq=Math.max(r.seq,this.nativeSourceCursor(nativeOwner,profile,stored,runtime,u.epoch??''))
-          this.onNativeRoute(nativeOwner, profile, stored, runtime, r.active, result)
-        }
-        if (nativeOwner && (method === 'session.create' || method === 'session.branch')) {
-          this.onNativeCommand(nativeOwner, profile, stored, method, {...p,_delivery_id:deliveryID})
-        }
-        for (const pending of [result.pending_approval, result.pending_clarify, result.inflight?.pending_approval, result.inflight?.pending_clarify]) {
-          if (pending?.request_id) this.interactions.set(`${u.principal.upstreamKey}:${pending.request_id}`, runtime)
-        }
-        const early = u.early.get(runtime) ?? []
-        u.early.delete(runtime)
-        for (const e of early) { u.earlyBytes -= Buffer.byteLength(JSON.stringify(e)); this.event(u, e) }
-      }
-      if (method === 'session.close' && route && !response.error) {
-        u.byRuntime.delete(route.runtime); u.routes.delete(this.routeKey(route.profile, route.stored))
-        this.routeOwners.delete(JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, route.profile, route.stored]))
-      }
-      if (route && response.result && ['file.attach','image.attach_bytes','pdf.attach'].includes(method) && c.principal.key.startsWith('user:')) {
-        this.onNativeEvent(c.principal.key.split(':')[1]!, route.profile, route.stored, { type:'attachment.staged', payload:response.result })
-      }
-      u.lastUsed = this.now()
-      return this.withoutProtectedSessions(response) ?? { result: {} }
-    }
-    if (['session.interrupt', 'approval.respond', 'clarify.respond', 'session.steer'].includes(method)) return execute()
-    const work = (u.tails.get(routeKey) ?? Promise.resolve()).catch(() => {}).then(execute)
-    u.tails.set(routeKey, work)
-    void work.finally(() => { if (u.tails.get(routeKey) === work) u.tails.delete(routeKey) }).catch(() => {})
-    return work
-  }
-
-  private interactions = new Map<string, string>()
-  private routeOwners = new Map<string, string>()
-  private routeKey(profile: string, stored: string): string { return JSON.stringify([profile, stored]) }
-  private upstream(p: RealtimePrincipal): Upstream {
-    let u = this.upstreams.get(p.upstreamKey)
-    if (!u) {
-      if (this.upstreams.size >= 64) throw new HttpError(429, 'Upstream capacity reached', 'upstream_limit')
-      u = { principal: p, pending: new Map(), routes: new Map(), byRuntime: new Map(), tails: new Map(),
-        early: new Map(), earlyBytes: 0, attempts: 0, recovering: false, deferred: [], lastUsed: this.now() }
-      this.upstreams.set(p.upstreamKey, u)
-    }
-    return u
-  }
-  private authorized(p: RealtimePrincipal): boolean {
-    try { if (!p.valid()) return false; p.authorize?.('chat'); return true } catch { return false }
-  }
-  private connectionPrincipal(u: Upstream): RealtimePrincipal | undefined {
-    if (this.authorized(u.principal)) return u.principal
-    // A service transport may outlive its first browser session and serve other users.
-    const candidates = [
-      ...[...this.channels.values()].filter(c => c.principal.upstreamKey === u.principal.upstreamKey).map(c => c.principal),
-      ...[...u.routes.values()].flatMap(r => [...r.observers.values()]),
-    ]
-    const principal = candidates.find(p => this.authorized(p))
-    if (principal) u.principal = principal
-    return principal
-  }
-  private scheduleReconnect(u: Upstream): void {
-    if (this.closed || this.upstreams.get(u.principal.upstreamKey) !== u || u.retry || !this.connectionPrincipal(u)) return
-    u.retry = setTimeout(() => {
-      u.retry = undefined
-      void this.connect(u).catch(() => {})
-    }, Math.min(15_000, 500 * 2 ** Math.min(u.attempts++, 5)))
-    u.retry.unref()
-  }
-  private connect(u: Upstream): Promise<void> {
-    if (this.closed || this.upstreams.get(u.principal.upstreamKey) !== u) return Promise.reject(new Error('Broker transport closed'))
-    if (u.connecting) return u.connecting
-    if (u.socket?.readyState === WebSocket.OPEN && u.ready) return Promise.resolve()
-    clearTimeout(u.retry); u.retry = undefined
-    u.connecting = (async () => {
-      // Let the previous socket's recovery unwind before starting another generation.
-      await u.recovery?.catch(() => {})
-      const principal = this.connectionPrincipal(u)
-      if (!principal) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-      const url = principal.embedded ? undefined : await principal.url('chat')
-      if (this.closed || this.upstreams.get(principal.upstreamKey) !== u) throw new Error('Broker transport closed')
-      if (!this.authorized(principal)) throw new HttpError(401, 'Authentication expired', 'authentication_required')
-      await new Promise<void>((resolve, reject) => {
-        const ws = principal.embedded ? new EmbeddedSocket(principal.embedded) as unknown as WebSocket
-          : new WebSocket(url!, { agent: principal.agent, headers: { Origin: `${url!.protocol === 'wss:' ? 'https:' : 'http:'}//${url!.host}` }, maxPayload: CHAT_MAX_PAYLOAD, handshakeTimeout: 15_000 })
-        u.socket = ws
-        const timeout = setTimeout(() => { reject(new Error('Upstream ready timeout')); ws.terminate() }, 20_000)
-        let ready = false
-        ws.on('message', (data, binary) => {
-          if (u.socket !== ws || binary) return
-          let f: Frame
-          try { f = JSON.parse(data.toString()) } catch { ws.terminate(); return }
-          if (f.method === 'event' && f.params?.type === 'gateway.ready') {
-            if (ready) return
-            clearTimeout(timeout); ready = true; u.ready = f
-            const epoch = f.params.payload?.replay_epoch
-            const changed = u.epoch !== undefined && epoch !== u.epoch
-            u.epoch = epoch
-            const recovery = u.routes.size ? this.recover(u, changed) : Promise.resolve()
-            u.recovery = recovery
-            void recovery.then(() => {
-              if (this.closed || u.socket !== ws || ws.readyState !== WebSocket.OPEN) throw new Error('Upstream disconnected during recovery')
-              u.attempts = 0
-              resolve()
-            }).catch(error => { reject(error); ws.terminate() }).finally(() => {
-              if (u.recovery === recovery) u.recovery = undefined
-            })
-          } else if (f.id !== undefined) {
-            const pending = u.pending.get(String(f.id))
-            if (pending) { clearTimeout(pending.timer); u.pending.delete(String(f.id)); pending.resolve(f) }
-          } else if (f.method === 'event') this.event(u, f)
-        })
-        let alive = true
-        ws.on('pong', () => { alive = true })
-        const ping = setInterval(() => { if (!alive) ws.terminate(); else if (ws.readyState === WebSocket.OPEN) { alive = false; ws.ping() } }, 25_000)
-        u.ping = ping; ping.unref()
-        ws.on('error', () => { if (!ready) reject(new Error('Upstream connection failed')) })
-        ws.on('close', () => {
-          clearTimeout(timeout); clearInterval(ping)
-          if (u.socket !== ws) return
-          u.socket = undefined; u.ready = undefined
-          reject(new Error('Upstream disconnected'))
-          for (const pending of u.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('Upstream disconnected; result unknown')) }
-          u.pending.clear()
-          this.scheduleReconnect(u)
-        })
-      })
-    })().catch(error => {
-      // Credentials and readiness can fail before any WebSocket close callback exists.
-      this.scheduleReconnect(u)
-      throw error
-    }).finally(() => { u.connecting = undefined })
-    return u.connecting
-  }
-  private rpc(u: Upstream, method: string, params: Frame, observed?: (frame: Frame) => void, sent?: (frame: Frame) => void): Promise<Frame> {
-    const id = randomUUID()
-    if (u.socket?.readyState !== WebSocket.OPEN || u.socket.bufferedAmount > 8 * 1024 * 1024 || u.pending.size >= 128) throw new Error('Upstream unavailable or congested')
-    const frame = { jsonrpc: '2.0', id, method, params }
-    sent?.(frame)
-    return new Promise((resolve, reject) => {
-      const timer = setTimeout(() => { u.pending.delete(id); reject(new Error('Upstream command result unknown')) }, 120_000)
-      timer.unref()
-      u.pending.set(id, { timer, reject, resolve: response => { observed?.(response); resolve(response) } })
-      u.socket!.send(JSON.stringify(frame), error => { if (error) { clearTimeout(timer); u.pending.delete(id); reject(error) } })
-    })
-  }
-  private event(u: Upstream, f: Frame, replay = false): void {
-    if (this.closed) return
-    if (u.recovering && !replay) {
-      if (u.deferred.length >= 512 || Buffer.byteLength(JSON.stringify([...u.deferred, f])) > 1024 * 1024) { u.deferred = []; this.reset(u, 'recovery_overflow') }
-      else u.deferred.push(f)
-      return
-    }
-    const p = f.params
-    if (!p || typeof p.type !== 'string') return
-    const sid = String(p.session_id ?? '')
-    const r = u.byRuntime.get(sid)
-    this.onActivity({ kind: 'event', name: p.type, sessionId: r?.stored })
-    if (sid && !r) {
-      const size = Buffer.byteLength(JSON.stringify(f))
-      if (u.earlyBytes + size > 1024 * 1024) { u.early.clear(); u.earlyBytes = 0; this.reset(u, 'unmapped_event_overflow'); return }
-      const list = u.early.get(sid) ?? []; list.push(f); u.early.set(sid, list); u.earlyBytes += size
-      return
-    }
-    if (r) {
-      if (Number.isSafeInteger(p.seq)) {
-        if (p.seq <= r.seq) return
-        if (r.seq > 0 && p.seq > r.seq + 1) this.reset(u, 'upstream_sequence_gap')
-        r.seq = p.seq
-      }
-      if(p.type==='session.info'){
-        const stored=p.payload?.stored_session_id??p.payload?.session_key??p.payload?.info?.stored_session_id
-        if(typeof stored==='string'&&stored&&stored!==r.stored){
-          const oldKey=this.routeKey(r.profile,r.stored),newKey=this.routeKey(r.profile,stored)
-          if(!u.routes.has(newKey)){
-            this.routeOwners.delete(JSON.stringify([u.principal.instanceKey??u.principal.upstreamKey,r.profile,r.stored]));
-            this.routeOwners.set(JSON.stringify([u.principal.instanceKey??u.principal.upstreamKey,r.profile,stored]),u.principal.upstreamKey);
-            u.routes.delete(oldKey);r.stored=stored;u.routes.set(newKey,r)
-            for(const channel of this.channels.values())if(channel.principal.upstreamKey===u.principal.upstreamKey&&channel.routes.delete(oldKey))channel.routes.add(newKey)
-            for(const principal of r.observers.values()){
-              const owner=this.nativeOwner(principal)
-              if(owner&&principal.valid())this.onNativeRoute(owner,r.profile,r.stored,r.runtime,r.active)
-            }
-          }
-        }
-      }
-      if (p.type === 'session.info' && typeof p.payload?.cwd === 'string') {
-        r.cwd = p.payload.cwd
-        if (r.cwd !== r.workingDirectory?.resolved) r.workingDirectory = undefined
-      }
-      if (['message.start', 'approval.request', 'clarify.request'].includes(p.type)) r.active = true
-      if (p.type === 'message.complete') r.active = false
-      if (p.payload?.request_id) this.interactions.set(`${u.principal.upstreamKey}:${p.payload.request_id}`, sid)
-      while (this.interactions.size > 10_000) this.interactions.delete(this.interactions.keys().next().value!)
-    }
-    const deliveryID = Number.isSafeInteger(p.seq) ? `${u.epoch??this.epoch}:${sid}:${p.seq}` : randomUUID()
-    const persistedOwners = new Set<string>()
-    if (r) for (const principal of r.observers.values()) {
-      if (principal.valid()) {
-        principal.observeEvent?.(JSON.stringify(f))
-        const owner = this.nativeOwner(principal)
-        if (owner && !persistedOwners.has(owner)) { persistedOwners.add(owner); this.onNativeEvent(owner, r.profile, r.stored, {...p,delivery_id:deliveryID,epoch:u.epoch??this.epoch}) }
-      }
-    }
-    if (!r && p.type === 'sessions.changed') {
-      const owners = new Set([...this.channels.values()].flatMap(channel => {
-        const owner = this.nativeOwner(channel.principal)
-        return owner && channel.principal.valid() ? [owner] : []
-      }))
-      for (const owner of owners) this.onNativeGlobalEvent(owner, p.type, true)
-    }
-    for (const c of this.channels.values()) {
-      if (c.kind !== 'chat' || c.principal.upstreamKey !== u.principal.upstreamKey || !c.principal.valid()) continue
-      if (r && !c.routes.has(this.routeKey(r.profile, r.stored))) continue
-      if (!r && !['profiles.changed', 'sessions.changed', 'models.changed', 'pet.changed'].includes(p.type)) continue
-      this.emit(c, 'frame', f)
-    }
-    if (r && (p.type === 'session.title' || p.type === 'session.title.updated')) {
-      const owners = new Set([...r.observers.values()].flatMap(principal => {
-        const owner = principal.valid() ? this.nativeOwner(principal) : undefined
-        return owner ? [owner] : []
-      }))
-      for (const owner of owners) this.publishOwnerSessionsChanged(owner)
-    }
-  }
-  publishOwnerSessionsChanged(owner: string, reason = 'session.title', profile?: string, sessionID?: string): void {
-    if (this.closed) return
-    this.onNativeGlobalEvent(owner, 'sessions.changed')
-    const frame = {
-      jsonrpc: '2.0',
-      method: 'event',
-      params: { type: 'sessions.changed', payload: { reason, profile, session_id: sessionID } },
-    }
-    for (const channel of this.channels.values()) {
-      if (channel.kind !== 'chat' || !channel.principal.valid()
-        || this.nativeOwner(channel.principal) !== owner) continue
-      this.emit(channel, 'frame', frame)
-    }
-  }
-  private nativeOwner(principal: RealtimePrincipal): string | undefined {
-    const device = /^device:[^:]+(?::agent:[^:]+)?$/.test(principal.key)
-    if (device) return principal.key
-    const match = /^(?:user|push):([^:]+)/.exec(principal.key)
-    return match?.[1]
-  }
-  private async recover(u: Upstream, changed: boolean): Promise<void> {
-    if (u.recovering) return
-    u.recovering = true
-    try {
-      for (const r of u.routes.values()) {
-        const lastSeen = r.seq
-        const resumed = await this.rpc(u, 'session.resume', { session_id: r.stored, profile: r.profile, close_on_disconnect: false, omit_messages: true })
-        if (resumed.error?.code === 4007 || resumed.error?.code === 'session_not_found') {
-          // Hermes' session.resume uses 4007 for a missing stored session. Retire
-          // only that route; a deleted session must not reconnect the whole service forever.
-          this.reset(u, 'upstream_session_missing')
-          this.event(u, { method: 'event', params: { type: 'error', session_id: r.runtime,
-            payload: { code: 'session_not_found', message: 'Hermes 中的原会话已不存在,无法恢复。' } } }, true)
-          r.active = false
-          const key = this.routeKey(r.profile, r.stored)
-          u.routes.delete(key); u.byRuntime.delete(r.runtime)
-          this.routeOwners.delete(JSON.stringify([u.principal.instanceKey ?? u.principal.upstreamKey, r.profile, r.stored]))
-          for (const c of this.channels.values()) if (c.principal.upstreamKey === u.principal.upstreamKey) c.routes.delete(key)
-          for (const [id, runtime] of this.interactions) if (id.startsWith(`${u.principal.upstreamKey}:`) && runtime === r.runtime) this.interactions.delete(id)
-          continue
-        }
-        if (resumed.error || typeof resumed.result?.session_id !== 'string' || !resumed.result.session_id) {
-          throw new Error('Upstream session recovery failed')
-        }
-        r.workingDirectory = undefined
-        r.cwd = typeof resumed.result?.info?.cwd === 'string' ? resumed.result.info.cwd : undefined
-        if (typeof resumed.result?.running === 'boolean') r.active = resumed.result.running
-        const restore=(snapshot:boolean)=>{
-          for(const principal of r.observers.values()){
-            const owner=this.nativeOwner(principal)
-            if(owner&&principal.valid()&&resumed.result)this.onNativeRoute(owner,r.profile,r.stored,String(resumed.result.session_id??r.runtime),r.active,
-              snapshot?resumed.result:{...resumed.result,inflight:undefined})
-          }
-        }
-        if (resumed.result.session_id !== r.runtime || changed) {
-          if (resumed.result?.session_id) { u.byRuntime.delete(r.runtime); r.runtime = resumed.result.session_id; u.byRuntime.set(r.runtime, r) }
-          r.seq = 0; this.reset(u, 'upstream_reset'); restore(true); continue
-        }
-        const replay = await this.rpc(u, 'session.events.since', { session_id: r.runtime, last_seen: lastSeen })
-        if (replay.error || replay.result?.truncated || replay.result?.epoch !== u.epoch) {this.reset(u, 'upstream_replay_unavailable');restore(true)}
-        else {for (const p of replay.result?.events ?? []) this.event(u, { jsonrpc: '2.0', method: 'event', params: p }, true);restore(false)}
-      }
-    } catch (error) { this.reset(u, 'upstream_recovery_failed'); throw error }
-    finally {
-      u.recovering = false
-      const deferred = u.deferred; u.deferred = []
-      for (const frame of deferred) this.event(u, frame)
-    }
-  }
-  private reset(u: Upstream, reason: string): void {
-    this.onActivity({ kind: 'reset', name: reason })
-    for (const route of u.routes.values()) {
-      for (const principal of route.observers.values()) {
-        const owner = this.nativeOwner(principal)
-        if (owner && principal.valid()) {
-          this.onNativeEvent(owner, route.profile, route.stored, {
-            type: 'gateway.reset', payload: { reason }, seq: route.seq,
-          })
-        }
-      }
-    }
-    for (const c of this.channels.values()) if (c.kind === 'chat' && c.principal.upstreamKey === u.principal.upstreamKey) this.emit(c, 'reset', { reason })
-  }
-  publishServerIdentity(identity: import('../shared/serverIdentity.js').ServerIdentity, instanceKey: string): void {
-    for (const channel of this.channels.values()) {
-      if (channel.principal.valid() && channel.principal.instanceKey === instanceKey) {
-        this.emit(channel, 'frame', { jsonrpc: '2.0', method: 'event', params: { type: 'server.identity.changed', payload: identity } })
-      }
-    }
-  }
-  private emit(c: RealtimeChannel, event: StreamEntry['event'], value: Frame): void {
-    const publicValue = this.withoutProtectedSessions(value)
-    if (!publicValue) return
-    const data = JSON.stringify(publicValue)
-    const entry: StreamEntry = { id: `${this.epoch}:${++c.seq}`, event, data, at: this.now(), bytes: Buffer.byteLength(data) }
-    c.entries.push(entry); c.bytes += entry.bytes
-    this.trim(c)
-    for (const listener of [...c.listeners]) {
-      try { listener(entry) } catch { c.listeners.delete(listener) }
-    }
-  }
-  private withoutProtectedSessions(value: any): any {
-    if (Array.isArray(value)) return value.map(v => this.withoutProtectedSessions(v)).filter(v => v !== undefined)
-    if (!value || typeof value !== 'object') return value
-    if (value.source === 'yaoyao_workspace' || ['id','session_id','sessionId','stored_session_id','session_key'].some(k => typeof value[k] === 'string' && this.protectedSession(value[k]))) return undefined
-    return Object.fromEntries(Object.entries(value).map(([k,v]) => [k,this.withoutProtectedSessions(v)]).filter(([,v]) => v !== undefined))
-  }
-  private trim(c: RealtimeChannel): void {
-    const own = [...this.channels.values()].filter(v => v.principal.key === c.principal.key)
-    while (own.reduce((n, v) => n + v.bytes, 0) > 8 * 1024 * 1024 || own.reduce((n, v) => n + v.entries.length, 0) > 10_000) {
-      const oldest = own.filter(v => v.entries.length).sort((a, b) => a.entries[0]!.at - b.entries[0]!.at)[0]
-      if (!oldest) break
-      this.evict(oldest)
-    }
-    while (c.entries[0] && c.entries[0].at < this.now() - 600_000) this.evict(c)
-    while ([...this.channels.values()].reduce((n, v) => n + v.bytes, 0) > 128 * 1024 * 1024) {
-      const oldest = [...this.channels.values()].filter(v => v.entries.length).sort((a, b) => a.entries[0]!.at - b.entries[0]!.at)[0]
-      if (!oldest) break
-      this.evict(oldest)
-    }
-  }
-  private evict(c: RealtimeChannel): void {
-    const entry = c.entries.shift()!
-    c.bytes -= entry.bytes; c.droppedThrough = Number(entry.id.split(':').at(-1))
-  }
-  private sweep(): void {
-    for (const [key, item] of this.completed) if (item.at < this.now() - 600_000) this.completed.delete(key)
-    for (const c of this.channels.values()) {
-      if (!c.principal.valid() || (!c.listeners.size && this.now() - c.touched > 600_000)) this.remove(c)
-      else this.trim(c)
-    }
-    for (const [key, u] of this.upstreams) {
-      if (u.pending.size || u.tails.size || [...u.routes.values()].some(r => r.active)) { u.lastUsed = this.now(); continue }
-      if ([...this.channels.values()].some(c => c.principal.upstreamKey === key)) { u.lastUsed = this.now(); continue }
-      if (this.now() - u.lastUsed > 300_000) {
-        this.upstreams.delete(key); clearTimeout(u.retry); clearInterval(u.ping); u.socket?.close()
-        for (const [route, owner] of this.routeOwners) if (owner === key) this.routeOwners.delete(route)
-      }
-    }
-  }
-  close(): void {
-    if (this.closed) return
-    this.closed = true; clearInterval(this.timer)
-    for (const c of [...this.channels.values()]) this.remove(c)
-    for (const u of this.upstreams.values()) {
-      clearTimeout(u.retry); clearInterval(u.ping)
-      for (const p of u.pending.values()) { clearTimeout(p.timer); p.reject(new Error('Broker stopped')) }
-      u.pending.clear(); u.socket?.terminate()
-    }
-    // Pending command continuations may still update their receipts in the next microtask.
-    void Promise.allSettled(this.commands.values()).then(() => this.receipts.close())
-  }
-}

+ 0 - 354
src/server/realtimeProtocol.ts

@@ -1,354 +0,0 @@
-import type { RawData } from 'ws'
-import { HttpError } from './errors.js'
-
-export const CHAT_MAX_PAYLOAD = 36 * 1_024 * 1_024
-const CHAT_METHODS = new Set([
-  'approval.respond',
-  'clarify.respond',
-  'config.set',
-  'file.attach',
-  'image.attach_bytes',
-  'pdf.attach',
-  'profiles.configure',
-  'profiles.get_asset',
-  'profiles.list',
-  'profiles.set_asset',
-  'prompt.submit',
-  'session.branch',
-  'session.close',
-  'session.context_breakdown',
-  'session.create',
-  'session.interrupt',
-  'session.resume',
-  'session.steer',
-  'session.usage',
-])
-const SESSION_ID_REQUIRED_METHODS = new Set([
-  'config.set',
-  'file.attach',
-  'image.attach_bytes',
-  'pdf.attach',
-  'prompt.submit',
-  'session.branch',
-  'session.close',
-  'session.context_breakdown',
-  'session.interrupt',
-  'session.resume',
-  'session.steer',
-  'session.usage',
-])
-
-function safeString(value: unknown, label: string, required = false): string | undefined {
-  if (value === undefined && !required) return undefined
-  if (typeof value !== 'string') throw new HttpError(400, `${label} must be a string`)
-  const normalized = value.trim()
-  if ((!normalized && required) || normalized.length > 256 || /[\u0000-\u001f\u007f]/.test(normalized)) {
-    throw new HttpError(400, `${label} is invalid`)
-  }
-  return normalized
-}
-
-function normalizedCreateSource(value: unknown, fallback = 'web'): 'web' | 'ios' {
-  const source = safeString(value, 'source') ?? fallback
-  if (source !== 'web' && source !== 'ios') {
-    throw new HttpError(400, 'source must be web or ios', 'invalid_source')
-  }
-  return source
-}
-
-function normalizedConfigParams(params: Record<string, unknown>): Record<string, unknown> {
-  const sessionID = safeString(params.session_id, 'session_id', true)!
-  const key = safeString(params.key, 'config key', true)
-  if (key === 'model') {
-    const value = typeof params.value === 'string' ? params.value.trim() : ''
-    if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,511} --provider [A-Za-z0-9][A-Za-z0-9._:-]{0,127}( --session)?$/.test(value)) {
-      throw new HttpError(400, 'Model selection is invalid')
-    }
-    return {
-      session_id: sessionID,
-      key,
-      value,
-      ...(params.confirm_expensive_model === true ? { confirm_expensive_model: true } : {}),
-    }
-  }
-  if (key === 'reasoning') {
-    const value = safeString(params.value, 'reasoning value', true)!
-    if (!new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']).has(value)) {
-      throw new HttpError(400, 'Reasoning value is invalid')
-    }
-    return { session_id: sessionID, key, value, scope: 'session' }
-  }
-  if (key === 'fast') {
-    const value = safeString(params.value, 'fast value', true)!
-    if (value !== 'fast' && value !== 'normal') throw new HttpError(400, 'Fast value is invalid')
-    return { session_id: sessionID, key, value, scope: 'session' }
-  }
-  throw new HttpError(403, 'Config key is not allowed')
-}
-
-function normalizedSessionOpenParams(
-  method: 'session.create' | 'session.resume',
-  params: Record<string, unknown>,
-): Record<string, unknown> {
-  const profile = safeString(params.profile, 'profile', true)!
-  const columns = typeof params.cols === 'number' && Number.isInteger(params.cols)
-    ? Math.min(500, Math.max(20, params.cols))
-    : 80
-  if (method === 'session.resume') {
-    return {
-      session_id: safeString(params.session_id, 'session_id', true)!,
-      profile,
-      close_on_disconnect: false,
-      omit_messages: params.omit_messages === true,
-      cols: columns,
-    }
-  }
-  const source = normalizedCreateSource(params.source)
-  const title = safeString(params.title, 'title')
-  const reasoning = safeString(params.reasoning_effort, 'reasoning effort')
-  const allowedReasoning = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
-  if (reasoning && !allowedReasoning.has(reasoning)) throw new HttpError(400, 'Reasoning effort is invalid')
-  return {
-    profile,
-    source,
-    close_on_disconnect: false,
-    cols: columns,
-    ...(title ? { title } : {}),
-    ...(reasoning ? { reasoning_effort: reasoning } : {}),
-    ...(typeof params.fast === 'boolean' ? { fast: params.fast } : {}),
-  }
-}
-
-function normalizedPairedSessionOpenParams(
-  method: 'session.create' | 'session.resume',
-  params: Record<string, unknown>,
-): Record<string, unknown> {
-  const profile = safeString(params.profile, 'profile', true)!
-  const columns = typeof params.cols === 'number' && Number.isInteger(params.cols)
-    ? Math.min(500, Math.max(20, params.cols))
-    : 80
-  if (method === 'session.resume') {
-    return {
-      session_id: safeString(params.session_id, 'session_id', true)!,
-      profile,
-      close_on_disconnect: false,
-      omit_messages: params.omit_messages === true,
-      cols: columns,
-    }
-  }
-  const source = safeString(params.source, 'source') ?? 'mobile'
-  const title = safeString(params.title, 'title')
-  const cwd = typeof params.cwd === 'string' && params.cwd.length <= 4_096 ? params.cwd : ''
-  const reasoning = safeString(params.reasoning_effort, 'reasoning effort')
-  const allowedReasoning = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
-  if (reasoning && !allowedReasoning.has(reasoning)) throw new HttpError(400, 'Reasoning effort is invalid')
-  const model = safeString(params.model, 'model')
-  const provider = safeString(params.provider, 'provider')
-  if ((model === undefined) !== (provider === undefined)) {
-    throw new HttpError(400, 'Model and provider must be set together')
-  }
-  const messages = params.messages
-  if (messages !== undefined && (!Array.isArray(messages) || messages.length > 256)) {
-    throw new HttpError(400, 'Seed messages are invalid')
-  }
-  return {
-    profile,
-    source,
-    close_on_disconnect: false,
-    cols: columns,
-    cwd,
-    hidden: params.hidden === true,
-    ...(title ? { title } : {}),
-    ...(reasoning ? { reasoning_effort: reasoning } : {}),
-    ...(model && provider ? { model, provider } : {}),
-    ...(typeof params.fast === 'boolean' ? { fast: params.fast } : {}),
-    ...(messages !== undefined ? { messages } : {}),
-  }
-}
-
-export function checkedChatFrame(data: RawData, isBinary: boolean, paired = false): string {
-  if (isBinary) throw new HttpError(400, 'Binary chat frames are not accepted')
-  const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer)
-  if (bytes.byteLength > CHAT_MAX_PAYLOAD) throw new HttpError(413, 'Chat frame is too large')
-  let value: unknown
-  try {
-    value = JSON.parse(bytes.toString('utf8'))
-  } catch {
-    throw new HttpError(400, 'Chat frame must be JSON')
-  }
-  if (!value || typeof value !== 'object' || Array.isArray(value)) {
-    throw new HttpError(400, 'Chat frame must be a JSON-RPC object')
-  }
-  const request = value as Record<string, unknown>
-  if (typeof request.method !== 'string' || !CHAT_METHODS.has(request.method)) {
-    throw new HttpError(403, 'Chat RPC method is not allowed')
-  }
-  if (request.id !== undefined && typeof request.id !== 'string' && typeof request.id !== 'number') {
-    throw new HttpError(400, 'Chat RPC id is invalid')
-  }
-  if (!request.params || typeof request.params !== 'object' || Array.isArray(request.params)) {
-    throw new HttpError(400, 'Chat RPC params must be an object')
-  }
-  let params = { ...(request.params as Record<string, unknown>) }
-  safeString(params.session_id, 'session_id', SESSION_ID_REQUIRED_METHODS.has(request.method))
-  const profileRequired = request.method === 'session.create' || request.method === 'session.resume'
-  safeString(params.profile, 'profile', profileRequired)
-  if (request.method === 'session.create' || request.method === 'session.resume') {
-    params = paired
-      ? normalizedPairedSessionOpenParams(request.method, params)
-      : normalizedSessionOpenParams(request.method, params)
-  }
-  if (request.method === 'profiles.list') {
-    const preferred = params.preferred_session_ids
-    if (preferred !== undefined && (!preferred || typeof preferred !== 'object' || Array.isArray(preferred))) {
-      throw new HttpError(400, 'preferred_session_ids must be an object')
-    }
-    params = {
-      ...(typeof params.include_sessions === 'boolean' ? { include_sessions: params.include_sessions } : {}),
-      ...(preferred !== undefined ? { preferred_session_ids: preferred } : {}),
-    }
-  }
-  if (request.method === 'profiles.get_asset') {
-    params = {
-      name: safeString(params.name, 'profile name', true)!,
-      asset: safeString(params.asset, 'profile asset', true)!,
-    }
-  }
-  if (request.method === 'profiles.set_asset') {
-    const clear = params.clear === true
-    const data = typeof params.data === 'string' ? params.data.trim() : ''
-    if (!clear && !data) throw new HttpError(400, 'profile asset data is required')
-    if (data.length > 2_800_000) throw new HttpError(413, 'profile asset exceeds 2 MiB')
-    params = {
-      name: safeString(params.name, 'profile name', true)!,
-      asset: safeString(params.asset, 'profile asset', true)!,
-      ...(clear ? { clear: true } : { data }),
-    }
-  }
-  if (request.method === 'profiles.configure') {
-    if (!params.ui_meta || typeof params.ui_meta !== 'object' || Array.isArray(params.ui_meta)) {
-      throw new HttpError(400, 'ui_meta must be an object')
-    }
-    if (params.ui_meta_expected_revisions !== undefined
-      && (!params.ui_meta_expected_revisions
-        || typeof params.ui_meta_expected_revisions !== 'object'
-        || Array.isArray(params.ui_meta_expected_revisions))) {
-      throw new HttpError(400, 'ui_meta_expected_revisions must be an object')
-    }
-    params = {
-      name: safeString(params.name, 'profile name', true)!,
-      ui_meta: params.ui_meta,
-      ...(params.ui_meta_expected_revisions !== undefined
-        ? { ui_meta_expected_revisions: params.ui_meta_expected_revisions }
-        : {}),
-    }
-  }
-  if (request.method === 'config.set') params = normalizedConfigParams(params)
-  if (request.method === 'prompt.submit' || request.method === 'session.steer') {
-    const text = typeof params.text === 'string' ? params.text.trim() : ''
-    if (!text || text.length > 200_000) throw new HttpError(400, 'Prompt text is invalid')
-    params = {
-      session_id: safeString(params.session_id, 'session_id', true)!,
-      text,
-      ...(request.method === 'prompt.submit' && params.queued === true ? { queued: true } : {}),
-    }
-  }
-
-  if (request.method === 'image.attach_bytes' || request.method === 'pdf.attach') {
-    const encoded = typeof params.content_base64 === 'string' ? params.content_base64 : ''
-    const estimated = Math.floor(encoded.length * 0.75)
-    if (!encoded || estimated > 25 * 1_024 * 1_024) {
-      throw new HttpError(413, 'Attachment exceeds 25 MiB')
-    }
-  }
-  if (request.method === 'file.attach') {
-    const dataURL = typeof params.data_url === 'string' ? params.data_url : ''
-    const marker = dataURL.indexOf(',')
-    if (marker < 0 || Math.floor((dataURL.length - marker - 1) * 0.75) > 25 * 1_024 * 1_024) {
-      throw new HttpError(413, 'Attachment exceeds 25 MiB')
-    }
-  }
-  return JSON.stringify({ ...request, params })
-}
-
-export class GroupFrameValidator {
-  #ready = false
-  #cursor: number
-
-  constructor(readonly epoch: string, cursor: number) {
-    this.#cursor = cursor
-  }
-
-  accept(data: RawData, isBinary: boolean): boolean {
-    if (isBinary) throw new HttpError(400, 'Binary group frames are not accepted')
-    let envelope: Record<string, unknown>
-    try {
-      const value = JSON.parse(Buffer.from(data as Uint8Array).toString('utf8')) as unknown
-      if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object')
-      envelope = value as Record<string, unknown>
-    } catch {
-      throw new HttpError(400, 'Malformed group event frame')
-    }
-    const type = envelope.type
-    const cursor = Number(envelope.cursor)
-    if (type === 'group.ready') {
-      const heartbeat = Number(envelope.heartbeatSeconds)
-      if (this.#ready || envelope.epoch !== this.epoch || !Number.isSafeInteger(cursor)
-        || cursor !== this.#cursor || !Number.isFinite(heartbeat) || heartbeat <= 0) {
-        throw new HttpError(409, 'Invalid group.ready frame')
-      }
-      this.#ready = true
-      return true
-    }
-    if (type === 'group.reset_required') {
-      if (typeof envelope.epoch !== 'string' || !Number.isSafeInteger(cursor)
-        || typeof envelope.reason !== 'string') {
-        throw new HttpError(400, 'Invalid group.reset_required frame')
-      }
-      return true
-    }
-    if (!this.#ready) throw new HttpError(409, 'Group event arrived before group.ready')
-    if (type === 'group.event') {
-      if (envelope.epoch !== this.epoch || !Number.isSafeInteger(cursor) || cursor < 0) {
-        throw new HttpError(409, 'Group event epoch or cursor is invalid')
-      }
-      if (cursor <= this.#cursor) return false
-      if (cursor !== this.#cursor + 1) throw new HttpError(409, 'Group event cursor gap')
-      this.#cursor = cursor
-      return true
-    }
-    if (type === 'group.heartbeat') {
-      if ((envelope.epoch !== undefined && envelope.epoch !== this.epoch)
-        || !Number.isSafeInteger(cursor) || cursor !== this.#cursor) {
-        throw new HttpError(409, 'Group heartbeat cursor mismatch')
-      }
-      return true
-    }
-    throw new HttpError(400, 'Unknown group event frame')
-  }
-
-  resetFrame(reason: string): string {
-    return JSON.stringify({
-      type: 'group.reset_required',
-      epoch: this.epoch,
-      cursor: this.#cursor,
-      reason,
-    })
-  }
-}
-
-export function canonicalEpoch(value: unknown): string {
-  if (typeof value !== 'string'
-    || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
-    throw new HttpError(400, 'epoch must be a canonical lowercase UUID', 'invalid_epoch')
-  }
-  return value
-}
-
-export function groupCursor(value: unknown): number {
-  const cursor = typeof value === 'number' ? value : Number(value ?? 0)
-  if (!Number.isSafeInteger(cursor) || cursor < 0) {
-    throw new HttpError(400, 'cursor must be a non-negative integer', 'invalid_cursor')
-  }
-  return cursor
-}

+ 0 - 92
src/server/realtimeReceipts.ts

@@ -1,92 +0,0 @@
-import { createHash } from 'node:crypto'
-import { chmodSync, mkdirSync } from 'node:fs'
-import { join } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import { HttpError } from './errors.js'
-
-export interface CommandReceipt {
-  requestId: string
-  state: 'pending' | 'confirmed' | 'rejected' | 'unknown'
-  response?: Record<string, unknown>
-}
-
-interface ReceiptCommand { method?: unknown; params?: Record<string, unknown> }
-
-/** Write-ahead admission, not an event/transcript store. Never stores command bodies. */
-export class RealtimeReceipts {
-  private db: DatabaseSync
-  constructor(home: string) {
-    mkdirSync(home, { recursive: true, mode: 0o700 })
-    const path = join(home, 'realtime-receipts.sqlite3')
-    this.db = new DatabaseSync(path)
-    chmodSync(path, 0o600)
-    this.db.exec(`PRAGMA journal_mode=WAL;
-      CREATE TABLE IF NOT EXISTS receipts (
-        owner TEXT NOT NULL, id TEXT NOT NULL, fingerprint TEXT NOT NULL,
-        state TEXT NOT NULL, response TEXT, updated INTEGER NOT NULL,
-        PRIMARY KEY(owner,id));
-      CREATE INDEX IF NOT EXISTS receipt_retention ON receipts(state,updated);
-      CREATE TABLE IF NOT EXISTS receipt_tombstones (
-        owner TEXT NOT NULL, id TEXT NOT NULL, fingerprint TEXT NOT NULL,
-        PRIMARY KEY(owner,id));
-      UPDATE receipts SET state='unknown' WHERE state='pending';`)
-  }
-  lookup(owner: string, id: string): CommandReceipt | undefined {
-    const row = this.db.prepare('SELECT state,response FROM receipts WHERE owner=? AND id=?').get(owner, id)
-    if (!row) return this.db.prepare('SELECT 1 FROM receipt_tombstones WHERE owner=? AND id=?').get(owner, id)
-      ? { requestId: id, state: 'unknown' } : undefined
-    return { requestId: id, state: row.state as CommandReceipt['state'],
-      ...(row.response ? { response: JSON.parse(String(row.response)) as Record<string, unknown> } : {}) }
-  }
-  reserve(owner: string, id: string, frame: string): CommandReceipt | undefined {
-    if (!/^[A-Za-z0-9:_-]{1,200}$/.test(id)) throw new HttpError(400, 'Invalid request ID', 'invalid_request_id')
-    const fingerprint = createHash('sha256').update(frame).digest('hex')
-    const row = this.db.prepare(`SELECT fingerprint FROM receipts WHERE owner=? AND id=?
-      UNION ALL SELECT fingerprint FROM receipt_tombstones WHERE owner=? AND id=?`).get(owner, id, owner, id)
-    if (row) {
-      if (row.fingerprint !== fingerprint) throw new HttpError(409, 'Request ID payload conflict', 'idempotency_conflict')
-      return this.lookup(owner, id)
-    }
-    // Retire results, never admission identities. Old clients may retry years later.
-    // A compact fingerprint tombstone prevents those retries from executing again.
-    this.db.exec('BEGIN IMMEDIATE')
-    try {
-      const cutoff = Date.now() - 86_400_000
-      this.db.prepare(`INSERT OR IGNORE INTO receipt_tombstones
-        SELECT owner,id,fingerprint FROM receipts WHERE updated<? AND state IN ('confirmed','rejected')`).run(cutoff)
-      this.db.prepare("DELETE FROM receipts WHERE updated<? AND state IN ('confirmed','rejected')").run(cutoff)
-      if (Number(this.db.prepare('SELECT count(*) AS n FROM receipts').get()!.n) >= 100_000) {
-        throw new HttpError(429, 'Command receipt capacity reached', 'receipt_capacity')
-      }
-      this.db.prepare('INSERT INTO receipts VALUES(?,?,?,?,NULL,?)').run(owner, id, fingerprint, 'pending', Date.now())
-      this.db.exec('COMMIT')
-    } catch (error) {
-      this.db.exec('ROLLBACK')
-      throw error
-    }
-    return undefined
-  }
-  finish(owner: string, id: string, state: CommandReceipt['state'], response?: Record<string, unknown>, command?: ReceiptCommand): void {
-    // Persist bounded recovery metadata, never command bodies, attachment bytes or history.
-    const result = response?.result as Record<string, unknown> | undefined
-    const safe: Record<string, unknown> = {}
-    for (const key of ['status', 'session_id', 'stored_session_id', 'session_key', 'queued', 'running', 'ok']) {
-      if (result && ['string', 'number', 'boolean'].includes(typeof result[key])) safe[key] = result[key]
-    }
-    const strings = command?.method === 'config.set' && ['model', 'reasoning', 'fast'].includes(String(command.params?.key))
-      ? ['value', 'confirm_message', 'warning']
-      : ['file.attach', 'image.attach_bytes', 'pdf.attach'].includes(String(command?.method))
-        ? ['path', 'image_path', 'ref_path', 'ref_text'] : []
-    for (const key of strings) {
-      if (typeof result?.[key] === 'string' && result[key].length <= 4096) safe[key] = result[key]
-    }
-    if (command?.method === 'config.set') for (const key of ['deferred', 'confirm_required']) {
-      if (typeof result?.[key] === 'boolean') safe[key] = result[key]
-    }
-    const saved = response?.error ? { error: { message: 'Upstream rejected command' } }
-      : response ? { result: safe } : undefined
-    this.db.prepare('UPDATE receipts SET state=?,response=?,updated=? WHERE owner=? AND id=?')
-      .run(state, saved ? JSON.stringify(saved) : null, Date.now(), owner, id)
-  }
-  close(): void { this.db.close() }
-}

+ 6 - 830
src/server/routes.ts

@@ -57,13 +57,11 @@ import {
   canonicalAllowedHosts,
   normalizeAllowedHost,
 } from './allowedHostsConfiguration.js'
-import { chatCacheKey, type ChatCacheCoordinator } from './chatCache.js'
 
 type JsonObject = Record<string, unknown>
 
 export interface RouteDependencies {
   hermes?: import('./hermes/embedded.js').EmbeddedHermes
-  onChatListChanged?: (owner:string,profile:string,id:string)=>void
   onServerIdentityChanged?: (identity: ServerIdentity) => void
   onUserAccessChanged?: (owner: string) => Promise<void>
   workspace: WorkspaceStore
@@ -84,7 +82,6 @@ export interface RouteDependencies {
   openVikingService: OpenVikingService
   openVikingSessionSync: OpenVikingSessionSync
   allowedHostsConfiguration: AllowedHostsConfigurationManager
-  chatCache?: ChatCacheCoordinator
 }
 
 function body(ctx: Koa.Context): JsonObject {
@@ -113,14 +110,6 @@ function parseJson(response: UpstreamResponse): JsonObject {
   }
 }
 
-function parseJsonValue(response: UpstreamResponse): unknown {
-  try {
-    return JSON.parse(response.body.toString('utf8')) as unknown
-  } catch {
-    throw new HttpError(502, 'Hermes returned invalid JSON', 'invalid_upstream_json')
-  }
-}
-
 function requireSuccess(response: UpstreamResponse): JsonObject {
   if (response.status < 200 || response.status >= 300) {
     const decoded = decodeUpstreamError(response)
@@ -313,109 +302,6 @@ function requestOrigin(ctx: Koa.Context, config: ServerConfig): string {
   return `${secure ? 'https' : 'http'}://${ctx.host}`
 }
 
-function pairingScopes(value: unknown): string[] | undefined {
-  if (value === undefined) return undefined
-  if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
-    throw new HttpError(400, 'scopes must be a string array', 'invalid_scope')
-  }
-  return value
-}
-
-function pairedProxyScope(path: string, method: string): NodeScope {
-  if (path === '/profiles' || path.startsWith('/profiles/')) {
-    return path.includes('/sessions') ? 'history.read' : 'agents.read'
-  }
-  if (path === '/sessions' || path.startsWith('/sessions/')) {
-    return ['GET', 'HEAD'].includes(method) ? 'history.read' : 'sessions.execute'
-  }
-  return 'sessions.execute'
-}
-
-function isNativeSessionMutation(path: string, method: string): boolean {
-  if (['GET', 'HEAD'].includes(method)) return false
-  return path === '/sessions'
-    || path.startsWith('/sessions/')
-    || /^\/profiles\/[^/]+\/sessions(?:\/|$)/.test(path)
-}
-
-function nativeSessionsReadOnly(): never {
-  throw new HttpError(
-    410,
-    '原生 Hermes 会话仅供历史查看;请在聊天中开始或继续对话',
-    'native_sessions_read_only',
-  )
-}
-
-function requireWritableOwnedSession(response: UpstreamResponse, locallyOwned = false): void {
-  requireSuccess(response)
-  if (!locallyOwned) nativeSessionsReadOnly()
-}
-
-function isMissingSessionResponse(response: UpstreamResponse): boolean {
-  if (response.status !== 404) return false
-  try {
-    const payload = parseJson(response)
-    if (payload.code === 'session_not_found') return true
-    const detail = payload.detail
-    // Hermes also uses this detail for a stored session absent from its history.
-    if (typeof detail === 'string' && /^not found[.!]?$/i.test(detail.trim())) return true
-    const message = [payload.error, payload.message, detail,
-      detail && typeof detail === 'object' && 'message' in detail ? detail.message : undefined]
-      .find(value => typeof value === 'string')
-    return typeof message === 'string'
-      && /^(session not found|session ?不存在|会话不存在)([.!。!]|\s*[::].*)?$/i
-        .test(message.trim().replace(/\s+/g, ' '))
-  } catch {
-    return false
-  }
-}
-
-function writableSessionPatch(input: JsonObject): JsonObject {
-  const allowed = new Set(['title', 'archived', 'pinned'])
-  const unknown = Object.keys(input).filter(key => !allowed.has(key))
-  if (unknown.length) {
-    throw new HttpError(400, `Session field is not writable: ${unknown[0]}`, 'invalid_session_patch')
-  }
-  const patch: JsonObject = {}
-  if (Object.hasOwn(input, 'title')) {
-    if (typeof input.title !== 'string' || !input.title.trim() || input.title.length > 500) {
-      throw new HttpError(400, 'Session title is invalid', 'invalid_session_patch')
-    }
-    patch.title = input.title.trim()
-  }
-  for (const key of ['archived', 'pinned'] as const) {
-    if (!Object.hasOwn(input, key)) continue
-    if (typeof input[key] !== 'boolean') {
-      throw new HttpError(400, `Session ${key} must be a boolean`, 'invalid_session_patch')
-    }
-    patch[key] = input[key]
-  }
-  if (!Object.keys(patch).length) {
-    throw new HttpError(400, 'Session patch is empty', 'invalid_session_patch')
-  }
-  return patch
-}
-
-function pairedProxyPath(rawPath: string): string {
-  const path = rawPath.startsWith('/') ? rawPath : `/${rawPath}`
-  if (path.includes('\\') || path.includes('\u0000') || path.length > 2_048) {
-    throw new HttpError(400, 'Paired node path is invalid', 'invalid_node_path')
-  }
-  const allowed = path === '/status'
-    || path === '/auth/me'
-    || path === '/profiles'
-    || path.startsWith('/profiles/')
-    || path === '/sessions'
-    || path.startsWith('/sessions/')
-    || path.startsWith('/model/')
-    || path.startsWith('/models/')
-    || path.startsWith('/files/')
-    || path.startsWith('/attachments/')
-
-  if (!allowed) throw new HttpError(404, 'Paired node route is not available', 'node_route_not_found')
-  return `/api${path}`
-}
-
 async function proxy(
   ctx: Koa.Context,
   upstream: UpstreamClient,
@@ -440,64 +326,6 @@ async function proxy(
   })
 }
 
-async function completeSessionList(
-  upstream: UpstreamClient,
-  path: string,
-  jar: CookieJar,
-  baseSearch: URLSearchParams,
-): Promise<UpstreamResponse> {
-  const rows = new Map<string, unknown>()
-  let firstResponse: UpstreamResponse | undefined
-  let firstPayload: JsonObject | undefined
-  let collectionKey: 'items' | 'sessions' | undefined
-  let offset = 0
-  const limit = 100
-  for (let page = 0; page < 1_000; page++) {
-    const search = new URLSearchParams(baseSearch)
-    search.set('offset', String(offset))
-    search.set('limit', String(limit))
-    const response = await upstream.request(path, jar, { search })
-    if (!firstResponse) firstResponse = response
-    if (response.status < 200 || response.status >= 300) return response
-    const payload = parseJson(response)
-    const key = Array.isArray(payload.items) ? 'items'
-      : Array.isArray(payload.sessions) ? 'sessions' : undefined
-    if (!key) return response
-    if (!firstPayload) { firstPayload = payload; collectionKey = key }
-    const values = payload[key] as unknown[]
-    values.forEach((value, index) => {
-      const item = value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : undefined
-      const id = item ? String(item.id ?? item.session_id ?? item.sessionId ?? '') : ''
-      const profile = item ? String(item.profile ?? item.profile_name ?? '') : ''
-      rows.set(id ? `${profile}\u0000${id}` : `${offset}\u0000${index}`, value)
-    })
-    const responseOffset = Math.max(0, Number(payload.offset ?? offset) || offset)
-    const responseLimit = Math.max(1, Number(payload.limit ?? limit) || limit)
-    const total = Math.max(0, Number(payload.total ?? 0) || 0)
-    const nextOffset = responseOffset + responseLimit
-    if (!values.length || (total > 0 && nextOffset >= total)
-      || (total === 0 && values.length < responseLimit)) break
-    if (nextOffset <= offset) throw new HttpError(502, 'Hermes session pagination did not advance', 'invalid_upstream_pagination')
-    offset = nextOffset
-    if (page === 999) throw new HttpError(502, 'Hermes session list is too large to project', 'upstream_pagination_limit')
-  }
-  const response = firstResponse!
-  const payload = firstPayload!
-  const headers = new Headers(response.headers)
-  headers.delete('content-length')
-  return {
-    ...response,
-    headers,
-    body: Buffer.from(JSON.stringify({
-      ...payload,
-      [collectionKey!]: [...rows.values()],
-      total: rows.size,
-      offset: 0,
-      limit: rows.size,
-    })),
-  }
-}
-
 async function proxyAdminFeature(
   ctx: Koa.Context,
   dependencies: RouteDependencies,
@@ -522,78 +350,6 @@ async function proxyAdminFeature(
   })
 }
 
-async function proxyOptionalUnread(
-  ctx: Koa.Context,
-  upstream: UpstreamClient,
-  path: string,
-  options: {
-    search?: URLSearchParams
-    method?: string
-    requestBody?: unknown
-  },
-  fallback: unknown,
-): Promise<void> {
-  await withJar(ctx, async (jar) => {
-    const response = await upstream.request(path, jar, {
-      method: options.method,
-      search: options.search,
-      body: options.requestBody,
-    })
-    if (response.status === 404 || response.status === 405) {
-      json(ctx, 200, fallback)
-      return
-    }
-    sendUpstreamResponse(ctx, response, jar)
-  })
-}
-
-async function cachedChatRead(
-  ctx: Koa.Context,
-  dependencies: RouteDependencies,
-  options: {
-    key: string
-    kind: 'list' | 'detail' | 'messages'
-    profile: string
-    sessionID?: string
-    offset?: number
-    limit?: number
-    archived?: string
-    ownedList?: boolean
-    load: (jar: CookieJar) => Promise<UpstreamResponse>
-  },
-): Promise<void> {
-  const user = dependencies.auth.require(ctx)
-  const load = async () => {
-    await dependencies.upstreamSession.ensure()
-    return options.load(dependencies.upstreamSession.jar)
-  }
-  if (!dependencies.chatCache) {
-    throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
-  }
-  // Explicit native history browsing retains its independent upstream path.
-  if(ctx.query.view==='history' || ctx.state.hermesBotNative || !ctx.path.startsWith('/api/app/')){
-    const response=await load()
-    sendUpstreamResponse(ctx,options.sessionID?dependencies.chatCache.store.markSessionOwnership(user.id,options.profile,options.sessionID,response):response,dependencies.upstreamSession.jar)
-    return
-  }
-  const result = dependencies.chatCache.readLocal(user.id, options.kind, options.profile, options.sessionID,
-    {offset:options.offset,limit:options.limit,archived:options.archived},ctx.get('x-yaoyao-cache').toLowerCase()==='bypass')
-  ctx.set('X-Yaoyao-Data-Source', result.source)
-  ctx.set('X-Yaoyao-Sync-State', result.state)
-  sendUpstreamResponse(
-    ctx,
-    options.sessionID
-      ? dependencies.chatCache.store.markSessionOwnership(
-          user.id,
-          options.profile,
-          options.sessionID,
-          result.response,
-        )
-      : result.response,
-    dependencies.upstreamSession.jar,
-  )
-}
-
 async function bootstrap(
   ctx: Koa.Context,
   dependencies: RouteDependencies,
@@ -691,58 +447,6 @@ async function setup(ctx: Koa.Context, dependencies: RouteDependencies): Promise
   await bootstrap(ctx, dependencies, true)
 }
 
-async function independentPairingCookies(
-  ctx: Koa.Context,
-  dependencies: RouteDependencies,
-  authenticatedJar: CookieJar,
-  request: JsonObject | undefined,
-): Promise<string> {
-  const status = requireSuccess(
-    await dependencies.upstream.request('/api/status', authenticatedJar),
-  )
-  if (!authRequired(status)) {
-    const cookies = authenticatedJar.header || (dependencies.upstream.embedded ? 'yaoyao_embedded=1' : undefined)
-    if (!cookies) throw new HttpError(401, 'Hermes session is unavailable', 'authentication_required')
-    return cookies
-  }
-  const username = typeof request?.username === 'string' ? request.username.trim() : ''
-  const password = typeof request?.password === 'string' ? request.password : ''
-  if (!username || !password || username.length > 320 || password.length > 4_096) {
-    throw new HttpError(
-      400,
-      'Hermes username and password are required to create an independent paired-device session',
-      'pairing_credentials_required',
-    )
-  }
-  const jar = new CookieJar('')
-  const providersBody = requireSuccess(
-    await dependencies.upstream.request('/api/auth/providers', jar),
-  )
-  const providers = Array.isArray(providersBody.providers) ? providersBody.providers : []
-  const provider = providers.find((entry) => Boolean(
-    entry && typeof entry === 'object' && !Array.isArray(entry)
-      && (entry as JsonObject).supports_password === true
-      && String((entry as JsonObject).name).toLowerCase() === 'basic',
-  )) as JsonObject | undefined
-  if (!provider || typeof provider.name !== 'string') {
-    throw new HttpError(
-      403,
-      'Hermes does not offer independent password sessions for QR pairing',
-      'pairing_login_unavailable',
-    )
-  }
-  const response = await dependencies.upstream.request('/auth/password-login', jar, {
-    method: 'POST',
-    body: { provider: provider.name, username, password, next: '' },
-    clientAddress: ctx.req.socket.remoteAddress,
-  })
-  const result = requireSuccess(response)
-  if (result.ok !== true) throw new HttpError(401, 'Hermes rejected the pairing login', 'pairing_login_failed')
-  await requireGatewayAuthentication(ctx, dependencies, jar)
-  if (!jar.header) throw new HttpError(502, 'Hermes did not issue paired-device cookies', 'pairing_session_missing')
-  return jar.header
-}
-
 async function requireGatewayAuthentication(
   ctx: Koa.Context,
   dependencies: RouteDependencies,
@@ -759,80 +463,6 @@ async function requireGatewayAuthentication(
   requireSuccess(identity)
 }
 
-async function searchSessions(ctx: Koa.Context, dependencies: RouteDependencies): Promise<void> {
-  const owner = dependencies.auth.require(ctx).id
-  if (!dependencies.chatCache) {
-    throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
-  }
-  const chatCache = dependencies.chatCache
-  await withJar(ctx, async (jar) => {
-    const view = ctx.query.view === 'chat' || ctx.query.view === 'history'
-      ? ctx.query.view : undefined
-    const query = searchFrom(ctx, ['q', 'limit', 'source', 'profile'])
-    const text = query.get('q')?.trim()
-    if (!text) throw new HttpError(400, 'q is required', 'missing_query')
-    const limit = Math.max(1, Math.min(100, Number(query.get('limit') ?? '50') || 50))
-    query.set('limit', '100')
-    if (view) query.delete('source')
-    if (!query.get('source')) query.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
-    if (query.get('profile')) {
-      const response = await dependencies.upstream.request('/api/sessions/search', jar, { search: query })
-      sendUpstreamResponse(
-        ctx,
-        chatCache.store.markOwnedSearchResults(
-          owner,
-          query.get('profile') || 'default',
-          response,
-          view,
-          limit,
-        ),
-        jar,
-      )
-      return
-    }
-
-    const profilesResponse = await dependencies.upstream.request('/api/profiles', jar)
-    const profileObjects = normalizedProfiles(requireSuccess(profilesResponse))
-    const profiles = profileObjects.flatMap((entry) => {
-      if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return []
-      const name = (entry as JsonObject).name
-      return typeof name === 'string' && name.trim() ? [name.trim()] : []
-    })
-    const results: JsonObject[] = []
-    for (const profile of profiles) {
-      const scoped = new URLSearchParams(query)
-      scoped.set('profile', profile)
-      const response = await dependencies.upstream.request('/api/sessions/search', jar, { search: scoped })
-      const value = requireSuccess(response)
-      for (const raw of Array.isArray(value.results) ? value.results : []) {
-        if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
-          results.push({ profile, ...(raw as JsonObject) })
-        }
-      }
-    }
-    results.sort((left, right) => {
-      const leftRank = Number(left.rank ?? left.last_active ?? left.started_at ?? 0)
-      const rightRank = Number(right.rank ?? right.last_active ?? right.started_at ?? 0)
-      return rightRank - leftRank
-    })
-    const marked = results.map((result) => {
-      const profile = typeof result.profile === 'string' ? result.profile : 'default'
-      const id = String(result.id ?? result.session_id ?? result.sessionId ?? '')
-      const metadata = id
-        ? chatCache.store.ownedSessionMetadata(owner, profile, id)
-        : { owned: false }
-      return {
-        ...result,
-        ...(metadata.authoritativeTitle ? { title: metadata.authoritativeTitle } : {}),
-        owned: metadata.owned,
-      }
-    })
-    const projected = marked.filter(result => !view
-      || (view === 'chat' ? result.owned : !result.owned))
-    json(ctx, 200, { results: projected.slice(0, limit), total: projected.length })
-  })
-}
-
 function localMediaPath(root: string, relativePath: string): string {
   let resolvedRoot: string
   let resolvedFile: string
@@ -909,15 +539,8 @@ function hermesMediaPath(ctx: Koa.Context, rootDirectory = 'cache'): string {
 }
 
 async function proxyHermesMedia(ctx: Koa.Context, dependencies: RouteDependencies, rootDirectory = 'cache'): Promise<void> {
-  const user = dependencies.auth.require(ctx)
+  dependencies.auth.require(ctx)
   const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, hermesMediaPath(ctx, rootDirectory), ctx.params.profile || String(ctx.query.profile || ctx.get('x-hermes-profile') || 'default'))
-  const cached = dependencies.chatCache?.store.attachment(user.id, path)
-  if (cached) {
-    ctx.set('X-Yaoyao-Data-Source', 'local')
-    sendLocalMedia(ctx, cached.localPath, cached.mimeType, basename(path))
-    prepareFilePreview(ctx, basename(path), true)
-    return
-  }
   // Generated media belongs to Hermes, which may run on a different machine
   // or inside a container. Let its file API enforce the managed-root policy.
   const response = await dependencies.upstreamSession.request('/api/files/download', {
@@ -925,34 +548,11 @@ async function proxyHermesMedia(ctx: Koa.Context, dependencies: RouteDependencie
     headers: ctx.get('range') ? { range: ctx.get('range') } : undefined,
     maxResponseBytes: 100 * 1_024 * 1_024,
   })
-  ctx.set('X-Yaoyao-Data-Source', 'upstream')
-  if (!ctx.get('range') && dependencies.chatCache?.store.knowsAttachment(user.id, path)) {
-    dependencies.chatCache.store.storeAttachment(user.id, path, response)
-  } else if (ctx.get('range')) {
-    void dependencies.chatCache?.cacheAttachment(user.id, path)
-  }
   sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
   ctx.set('Cache-Control', 'private, no-store')
   if (response.status >= 200 && response.status < 300) prepareFilePreview(ctx, basename(path))
 }
 
-function pairedLocalMediaPath(config: ServerConfig, rawPath: string): string {
-  if (!rawPath || rawPath.length > 8_192 || rawPath.includes('\u0000')) {
-    throw new HttpError(400, '远程文件路径无效', 'invalid_node_file_path')
-  }
-  let file: string
-  try { file = realpathSync(rawPath) } catch {
-    throw new HttpError(404, '远程文件不存在', 'node_file_not_found')
-  }
-  const roots = [config.mediaRoot, config.attachmentsRoot, config.imagesRoot].flatMap(root => {
-    try { return [realpathSync(root)] } catch { return [] }
-  })
-  if (!roots.some(root => file.startsWith(`${root}${sep}`)) || !statSync(file).isFile()) {
-    throw new HttpError(403, '远程文件不在允许的目录中', 'node_file_forbidden')
-  }
-  return file
-}
-
 export function createApiRouter(dependencies: RouteDependencies): Router {
   const router = new Router()
   const registrations = new RegistrationLimiter()
@@ -1000,12 +600,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
 
   router.get('/healthz', (ctx) => {
     ctx.set('Cache-Control', 'no-store')
-    json(ctx, 200, {
-      ok: true,
-      chatCache: dependencies.chatCache
-        ? { available: true, mode: dependencies.chatCache.mode, ...dependencies.chatCache.store.stats(), reads: dependencies.chatCache.diagnostics }
-        : { available: false, mode: dependencies.config.chatCacheMode ?? 'upstream-only' },
-    })
+    json(ctx, 200, { ok: true })
   })
 
   // Hermes Gateway-compatible authentication surface for native clients.
@@ -1228,189 +823,6 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
     })
   })
 
-  router.post('/api/app/pairings', async (ctx) => {
-    const pairingOwner = dependencies.auth.requireAdmin(ctx)
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      const request = optionalBody(ctx)
-      // Embedded Hermes has no account cookies; the device token alone authorizes paired access.
-      const cookieHeader = jar.header || (dependencies.upstream.embedded ? 'yaoyao_embedded=1' : undefined)
-      if (!cookieHeader) throw new HttpError(503, '9119 服务会话尚未就绪', 'upstream_session_missing')
-      const pairing = dependencies.pairings.create(
-        cookieHeader,
-        pairingScopes(request?.scopes),
-        pairingOwner.id,
-      )
-      const origin = requestOrigin(ctx, dependencies.config)
-      const deepLink = new URL('yaoyao://pair')
-      deepLink.searchParams.set('v', String(NODE_PAIRING_PROTOCOL_VERSION))
-      deepLink.searchParams.set('url', origin)
-      deepLink.searchParams.set('node', pairing.nodeID)
-      deepLink.searchParams.set('id', pairing.id)
-      deepLink.searchParams.set('secret', pairing.secret)
-      deepLink.searchParams.set('fingerprint', pairing.fingerprint)
-      json(ctx, 201, {
-        protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
-        serviceType: 'yaoyao-web',
-        pairingId: pairing.id,
-        nodeId: pairing.nodeID,
-        fingerprint: pairing.fingerprint,
-        scopes: pairing.scopes,
-        expiresAt: pairing.expiresAt,
-        qrPayload: deepLink.toString(),
-      })
-    })
-  })
-
-  router.get('/api/app/pairings/:pairingID', async (ctx) => {
-    dependencies.auth.requireAdmin(ctx)
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      json(ctx, 200, dependencies.pairings.status(ctx.params.pairingID))
-    })
-  })
-
-  router.get('/api/app/paired-devices', async (ctx) => {
-    dependencies.auth.requireAdmin(ctx)
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      json(ctx, 200, {
-        nodeId: dependencies.pairings.nodeID,
-        fingerprint: dependencies.pairings.fingerprint,
-        devices: dependencies.pairings.list(),
-      })
-    })
-  })
-
-  router.delete('/api/app/paired-devices/:deviceID', async (ctx) => {
-    dependencies.auth.requireAdmin(ctx)
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      try {
-        const delegated = new CookieJar(
-          dependencies.pairings.delegatedCookies(ctx.params.deviceID),
-        )
-        await dependencies.upstream.request('/auth/logout', delegated, {
-          method: 'POST', clientAddress: ctx.req.socket.remoteAddress,
-        })
-      } catch {
-        // Revocation of the local delegation remains authoritative even when
-        // Hermes is temporarily unreachable; its cookie is never returned.
-      }
-      if (!dependencies.pairings.revoke(ctx.params.deviceID)) {
-        throw new HttpError(404, 'Paired device was not found', 'paired_device_not_found')
-      }
-      json(ctx, 200, { ok: true })
-    })
-  })
-
-  router.post('/api/pair/v1/claim', (ctx) => {
-    const request = body(ctx)
-    const pairingID = typeof request.pairingId === 'string' ? request.pairingId : ''
-    const secret = typeof request.secret === 'string' ? request.secret : ''
-    const deviceName = typeof request.deviceName === 'string' ? request.deviceName : ''
-    const existingDeviceID = typeof request.existingDeviceId==='string' ? request.existingDeviceId : undefined
-    const claimed = dependencies.pairings.claim({ pairingID, secret, deviceName, existingDeviceID,
-      existingToken: existingDeviceID ? bearerToken(ctx.get('authorization')) : undefined })
-    const origin = requestOrigin(ctx, dependencies.config)
-    json(ctx, 201, {
-      protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
-      serviceType: 'yaoyao-web',
-      nodeId: claimed.nodeID,
-      fingerprint: claimed.fingerprint,
-      deviceId: claimed.device.id,
-      deviceName: claimed.device.name,
-      token: claimed.token,
-      scopes: claimed.scopes,
-      serverUrl: `${origin}/node/${claimed.device.id}`,
-    })
-  })
-
-  router.get('/api/pair/v1/capabilities', (ctx) => {
-    json(ctx, 200, {
-      protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
-      serviceType: 'yaoyao-web',
-      nodeId: dependencies.pairings.nodeID,
-      fingerprint: dependencies.pairings.fingerprint,
-      scopes: [...DEFAULT_NODE_SCOPES],
-      features: ['bots', 'history', 'workspace-agents', 'pair-renewal'],
-    })
-  })
-
-  router.delete('/api/pair/v1/devices/:deviceID', async (ctx) => {
-    const token = bearerToken(ctx.get('authorization'))
-    const cookies = dependencies.pairings.authorize(ctx.params.deviceID, token)
-    try {
-      await dependencies.upstream.request('/auth/logout', new CookieJar(cookies), {
-        method: 'POST', clientAddress: ctx.req.socket.remoteAddress,
-      })
-    } catch {
-      // The paired bearer is revoked locally even if upstream logout fails.
-    }
-    if (!dependencies.pairings.revoke(ctx.params.deviceID)) {
-      throw new HttpError(404, 'Paired device was not found', 'paired_device_not_found')
-    }
-    json(ctx, 200, { ok: true })
-  })
-
-  router.get('/node/:deviceID/api/node-files', (ctx) => {
-    const token = bearerToken(ctx.get('authorization'))
-    dependencies.pairings.authorize(
-      ctx.params.deviceID,
-      token,
-      'history.read',
-    )
-    const value = typeof ctx.query.path === 'string' ? ctx.query.path : ''
-    sendLocalMedia(
-      ctx,
-      pairedLocalMediaPath(dependencies.config, value),
-    )
-  })
-  router.get('/node/:deviceID/api/profile-identities', async (ctx) => {
-    const token = bearerToken(ctx.get('authorization'))
-    dependencies.pairings.authorize(
-      ctx.params.deviceID,
-      token,
-      'agents.read',
-    )
-    json(ctx, 200, { profiles: await dependencies.profileIdentities.load() })
-  })
-
-  router.all('/node/:deviceID/api/*nodePath', async (ctx) => {
-    const rawPath = Array.isArray(ctx.params.nodePath)
-      ? ctx.params.nodePath.join('/')
-      : ctx.params.nodePath
-    const path = pairedProxyPath(rawPath)
-    if (isNativeSessionMutation(path.slice('/api'.length), ctx.method)) {
-      nativeSessionsReadOnly()
-    }
-    const scope = pairedProxyScope(path.slice('/api'.length), ctx.method)
-    const token = bearerToken(ctx.get('authorization'))
-    const cookieHeader = dependencies.pairings.authorize(
-      ctx.params.deviceID,
-      token,
-      scope,
-    )
-    if (ctx.querystring.length > 8_192) {
-      throw new HttpError(414, 'Paired node query is too long', 'node_query_too_long')
-    }
-    const jar = new CookieJar(cookieHeader)
-    if (fileReadRequest(ctx, path)) await authorizeFileQuery(ctx, path, {
-      request: (path, options) => dependencies.upstream.request(path, jar, options),
-    })
-    const response = await dependencies.upstream.withReadScope(`device:${ctx.params.deviceID}`, ctx.get('x-yaoyao-cache') === 'bypass', () => dependencies.upstream.request(path, jar, {
-      method: ctx.method,
-      search: new URLSearchParams(ctx.querystring),
-      body: ['GET', 'HEAD'].includes(ctx.method)
-        ? undefined : optionalBody(ctx),
-      headers: { 'x-yaoyao-node-client': ctx.params.deviceID },
-      clientAddress: path === '/api/auth/ws-ticket'
-        ? undefined : ctx.req.socket.remoteAddress,
-    }))
-    dependencies.pairings.updateCookies(ctx.params.deviceID, jar.header)
-    sendUpstreamResponse(ctx, response, jar)
-  })
-
   // Keep the original URL usable by inline Markdown, the lightbox and downloads.
   // These root/profile cache paths are not files on the Web server itself.
   router.get('/Users/:owner/.hermes/cache/*filePath', ctx => proxyHermesMedia(ctx, dependencies))
@@ -1923,269 +1335,33 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
     search.set('explicit_only', 'true')
     await proxy(ctx, dependencies.upstream, '/api/model/options', { search })
   })
-  router.get('/api/app/sessions/search', async (ctx) => {
-    await searchSessions(ctx, dependencies)
-  })
-  router.get('/api/app/sessions/pins', ctx => {
-    const owner=dependencies.auth.require(ctx).id
-    ctx.body={session_ids:dependencies.chatCache!.store.pins(owner,String(ctx.query.profile??''))}
-  })
   const unreadInput=z.object({items:z.array(z.object({mode:z.enum(['bot','chat']),id:z.string().min(1).max(256),profile:z.string().max(256).optional(),messages:z.array(z.object({id:z.string().min(1).max(512),seq:z.number().int().nonnegative(),version:z.number().int().nonnegative().optional(),taskId:z.string().max(256).optional()}).strict()).max(20000)}).strict()).max(1000)}).strict()
   router.get('/api/app/unread',ctx=>{
     const owner=dependencies.auth.require(ctx).id
     ctx.set('Cache-Control','no-store')
-    ctx.body=unreadSnapshot(dependencies.workspace,dependencies.chatCache!.store,owner,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
+    ctx.body=unreadSnapshot(dependencies.workspace,owner,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
   })
   router.post('/api/app/unread/read',ctx=>{
     const owner=dependencies.auth.require(ctx).id,input=unreadInput.safeParse(body(ctx))
     if(!input.success)throw new HttpError(400,'未读快照格式无效','invalid_unread_snapshot')
-    acknowledgeUnread(dependencies.workspace,dependencies.chatCache!.store,owner,input.data.items,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
-    for(const item of input.data.items)if(item.mode==='chat')dependencies.onChatListChanged?.(owner,item.profile ?? 'default',item.id)
-    ctx.body=unreadSnapshot(dependencies.workspace,dependencies.chatCache!.store,owner,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
-  })
-  router.get('/api/app/sessions/unread', ctx => {
-    const owner=dependencies.auth.require(ctx).id
-    ctx.body=dependencies.chatCache!.store.unread(owner,String(ctx.query.profile??''))
-  })
-  router.patch('/api/app/sessions/unread/:sessionID', ctx => {
-    const owner=dependencies.auth.require(ctx).id,profile=String(ctx.query.profile??'default'),id=safeIdentifier(ctx.params.sessionID,'session ID')
-    const input=body(ctx) as Record<string,unknown>,value=input.readMessageCount??input.read_message_count
-    ctx.body=dependencies.chatCache!.store.markRead(owner,profile,id,typeof value==='number'&&Number.isFinite(value)?value:undefined)
-    dependencies.onChatListChanged?.(owner,profile,id)
-  })
-  router.post('/api/app/sessions/:sessionID/sync',ctx=>{
-    const owner=dependencies.auth.require(ctx).id,profile=String(ctx.query.profile??'default'),id=safeIdentifier(ctx.params.sessionID,'session ID')
-    dependencies.chatCache!.store.requireOwned(owner,profile,id)
-    dependencies.chatCache!.schedule(owner,profile,id,true)
-    ctx.status=202;ctx.body={sync_state:'syncing'}
-  })
-  router.get('/api/app/sessions', async (ctx) => {
-    const view = ctx.query.view === 'history' || ctx.query.view === 'chat' ? ctx.query.view : undefined
-    const search = searchFrom(ctx, ['limit', 'offset', 'order', 'archived', 'profile', 'source'])
-    const offset = Math.max(0, Number(search.get('offset') ?? '0') || 0)
-    const limit = Math.max(1, Math.min(200, Number(search.get('limit') ?? '100') || 100))
-    search.set('offset', String(offset))
-    search.set('limit', String(limit))
-    if (!search.get('order')) search.set('order', 'recent')
-    if (!search.get('archived')) search.set('archived', 'exclude')
-    if (view) search.delete('source')
-    search.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
-    const path = search.get('profile') ? '/api/sessions' : '/api/profiles/sessions'
-    if (view && !dependencies.chatCache) {
-      throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
-    }
-    if (view === 'history' && dependencies.chatCache) {
-      const owner = dependencies.auth.require(ctx).id
-      const profile = search.get('profile') || ''
-      await withJar(ctx, async (jar) => {
-        const response = await completeSessionList(dependencies.upstream, path, jar, search)
-        sendUpstreamResponse(
-          ctx,
-          dependencies.chatCache!.store.excludeOwnedSessionsFromList(
-            owner,
-            profile,
-            response,
-            { offset, limit },
-          ),
-          jar,
-        )
-      })
-      return
-    }
-    if (view !== 'chat') {
-      await proxy(ctx, dependencies.upstream, path, { search })
-      return
-    }
-    const profile = search.get('profile') || ''
-    const upstreamSearch = new URLSearchParams(search)
-    upstreamSearch.set('offset', '0')
-    upstreamSearch.set('limit', '100')
-    await cachedChatRead(ctx, dependencies, {
-      key: chatCacheKey('list', profile, undefined, search),
-      kind: 'list', profile, ownedList: true, offset, limit,
-      archived: search.get('archived') || 'exclude',
-      load: jar => completeSessionList(dependencies.upstream, path, jar, upstreamSearch),
-    })
-  })
-  router.get('/api/app/sessions/:sessionID/messages', async (ctx) => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const incoming = searchFrom(ctx, ['offset', 'limit', 'profile'])
-    const offset = Math.max(0, Number(incoming.get('offset') ?? '0') || 0)
-    const limit = Math.max(1, Math.min(500, Number(incoming.get('limit') ?? '100') || 100))
-    incoming.set('offset', String(offset))
-    incoming.set('limit', String(limit))
-    incoming.set('order', 'latest')
-    incoming.set('include_compacted', 'true')
-    const profile = incoming.get('profile') || 'default'
-    await cachedChatRead(ctx, dependencies, {
-      key: chatCacheKey('messages', profile, id, incoming),
-      kind: 'messages', profile, sessionID: id, offset, limit,
-      load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}/messages`, jar, { search: incoming }),
-    })
-  })
-  router.get('/api/app/sessions/:sessionID', async (ctx) => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const search = searchFrom(ctx, ['profile'])
-    const profile = search.get('profile') || 'default'
-    await cachedChatRead(ctx, dependencies, {
-      key: chatCacheKey('detail', profile, id, search),
-      kind: 'detail', profile, sessionID: id,
-      load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
-    })
-  })
-  router.patch('/api/app/sessions/:sessionID', async (ctx) => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const search = searchFrom(ctx, ['profile'])
-    const localPatch=writableSessionPatch(body(ctx))
-    if(Object.keys(localPatch).every(key=>['title','pinned','archived'].includes(key))){
-      const owner=dependencies.auth.require(ctx).id,profile=search.get('profile')||'default'
-      if(!dependencies.chatCache!.store.ownsSession(owner,profile,id))throw new HttpError(410,'原生历史只读','native_sessions_read_only')
-      dependencies.chatCache!.store.patchLocal(owner,profile,id,localPatch)
-      dependencies.onChatListChanged?.(owner,profile,id)
-      ctx.body={ok:true};return
-    }
-    await withJar(ctx, async jar => {
-      const profile = search.get('profile') || 'default'
-      const owner = dependencies.auth.require(ctx).id
-      requireWritableOwnedSession(
-        await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
-        dependencies.chatCache?.store.ownsSession(owner, profile, id) ?? false,
-      )
-      const request = writableSessionPatch(body(ctx))
-      const requestedProfile = search.get('profile')
-      if (requestedProfile) request.profile = requestedProfile
-      const response = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { method: 'PATCH', search, body: request })
-      if (response.status >= 200 && response.status < 300) {
-        if (typeof request.title === 'string') {
-          dependencies.chatCache?.store.recordAuthoritativeTitle(
-            owner,
-            profile,
-            id,
-            request.title,
-          )
-        }
-        dependencies.chatCache?.store.markListsStale(owner)
-        void dependencies.chatCache?.reconcile(owner, profile, id).catch(() => {})
-      }
-      sendUpstreamResponse(ctx, response, jar)
-    })
-  })
-  router.delete('/api/app/sessions/:sessionID', async (ctx) => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const search = searchFrom(ctx, ['profile'])
-    await withJar(ctx, async jar => {
-      const profile = search.get('profile') || 'default'
-      const owner = dependencies.auth.require(ctx).id
-      const existing = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search })
-      if (isMissingSessionResponse(existing)) {
-        // Only this account's cached copy remains; no upstream mutation is needed.
-        dependencies.chatCache?.store.deleteSession(owner, profile, id)
-        dependencies.onChatListChanged?.(owner, profile, id)
-        ctx.body = { ok: true }
-        return
-      }
-      requireWritableOwnedSession(
-        existing,
-        dependencies.chatCache?.store.ownsSession(owner, profile, id) ?? false,
-      )
-      const response = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { method: 'DELETE', search })
-      const alreadyMissing = isMissingSessionResponse(response)
-      if ((response.status >= 200 && response.status < 300) || alreadyMissing) {
-        dependencies.chatCache?.store.deleteSession(
-          owner,
-          profile,
-          id,
-        )
-        dependencies.onChatListChanged?.(owner, profile, id)
-      }
-      if (alreadyMissing) {
-        ctx.body = { ok: true }
-        return
-      }
-      sendUpstreamResponse(ctx, response, jar)
-    })
-  })
-
-  for (const listPath of ['/api/sessions', '/api/profiles/sessions']) {
-    router.get(listPath, async ctx => {
-      const search = new URLSearchParams(ctx.querystring)
-      await withJar(ctx, async jar => sendUpstreamResponse(
-        ctx,
-        await dependencies.upstream.request(listPath, jar, { search }),
-        jar,
-      ))
-    })
-  }
-  router.get('/api/sessions/:sessionID/messages', async ctx => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const search = new URLSearchParams(ctx.querystring)
-    const profile = search.get('profile') || 'default'
-    const offset = Math.max(0, Number(search.get('offset') ?? 0) || 0)
-    const limit = Math.max(1, Math.min(500, Number(search.get('limit') ?? 100) || 100))
-    await cachedChatRead(ctx, dependencies, {
-      key: chatCacheKey('messages', profile, id, search),
-      kind: 'messages', profile, sessionID: id, offset, limit,
-      load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}/messages`, jar, { search }),
-    })
-  })
-  router.get('/api/sessions/:sessionID', async ctx => {
-    const id = safeIdentifier(ctx.params.sessionID, 'session ID')
-    const search = new URLSearchParams(ctx.querystring)
-    const profile = search.get('profile') || 'default'
-    await cachedChatRead(ctx, dependencies, {
-      key: chatCacheKey('detail', profile, id, search),
-      kind: 'detail', profile, sessionID: id,
-      load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
-    })
+    acknowledgeUnread(dependencies.workspace,owner,input.data.items,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
+    ctx.body=unreadSnapshot(dependencies.workspace,owner,(node,profile)=>dependencies.auth.canUseSource(owner,node,profile))
   })
   router.get('/api/files/download', async ctx => {
-    const user = dependencies.auth.require(ctx)
+    dependencies.auth.require(ctx)
     const path = typeof ctx.query.path === 'string' ? ctx.query.path : ''
     if (!path) throw new HttpError(400, 'path is required', 'missing_path')
-    const cached = dependencies.chatCache?.store.attachment(user.id, path)
-    if (cached) {
-      ctx.set('X-Yaoyao-Data-Source', 'local')
-      sendLocalMedia(ctx, cached.localPath, cached.mimeType, basename(path))
-      prepareFilePreview(ctx, basename(path), true)
-      return
-    }
     const response = await dependencies.upstreamSession.request('/api/files/download', {
       search: new URLSearchParams({ path }),
       headers: ctx.get('range') ? { range: ctx.get('range') } : undefined,
       maxResponseBytes: 100 * 1_024 * 1_024,
     })
-    ctx.set('X-Yaoyao-Data-Source', 'upstream')
-    if (!ctx.get('range') && dependencies.chatCache?.store.knowsAttachment(user.id, path)) {
-      dependencies.chatCache.store.storeAttachment(user.id, path, response)
-    } else if (ctx.get('range')) {
-      void dependencies.chatCache?.cacheAttachment(user.id, path)
-    }
     sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
     ctx.set('Cache-Control', 'private, no-store')
     ctx.set('X-Content-Type-Options', 'nosniff')
     if (response.status >= 200 && response.status < 300 && ctx.query.preview === '1') prepareFilePreview(ctx, basename(path))
   })
 
-  router.all('/api/*gatewayPath', async (ctx) => {
-    if (ctx.path.startsWith('/api/app/') || ctx.path.startsWith('/api/pair/')) {
-      throw new HttpError(404, 'Route not found', 'not_found')
-    }
-    dependencies.auth.require(ctx, ctx.path === '/api/profiles')
-    const raw = Array.isArray(ctx.params.gatewayPath)
-      ? ctx.params.gatewayPath.join('/')
-      : ctx.params.gatewayPath
-    const upstreamPath = pairedProxyPath(raw)
-    if (isNativeSessionMutation(upstreamPath.slice('/api'.length), ctx.method)) {
-      nativeSessionsReadOnly()
-    }
-    const response = await dependencies.upstreamSession.request(upstreamPath, {
-      method: ctx.method,
-      search: new URLSearchParams(ctx.querystring),
-      body: ['GET', 'HEAD'].includes(ctx.method) ? undefined : optionalBody(ctx),
-    })
-    sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
-  })
-
   return router
 }
 

+ 7 - 31
src/server/unreadCenter.ts

@@ -1,15 +1,10 @@
 import type { WorkspaceStore } from './workspaceStore.js'
-import type { ChatCacheStore } from './chatCache.js'
 import type { WorkspaceAgent, WorkspaceConversation } from '../shared/workspace.js'
 import { emptyUnread, type UnreadSnapshot, type UnreadConversation } from '../shared/unread.js'
 import { notificationPlainText } from './notificationText.js'
 
-function messageTime(value:unknown):number {
- const numeric=Number(value);if(Number.isFinite(numeric))return numeric>0&&numeric<100_000_000_000?numeric*1000:numeric
- const parsed=typeof value==='string'?Date.parse(value):NaN;return Number.isFinite(parsed)?parsed:0
-}
-
-export function unreadSnapshot(workspace:WorkspaceStore, cache:ChatCacheStore, owner:string,
+/** Bot conversations only; `chat` stays 0 for clients that still read the field. */
+export function unreadSnapshot(workspace:WorkspaceStore, owner:string,
   allowed:(node:string,profile:string)=>boolean = ()=>true):UnreadSnapshot {
   const result=emptyUnread()
   for(const c of workspace.list<WorkspaceConversation>(owner,'conversation')) {
@@ -19,18 +14,6 @@ export function unreadSnapshot(workspace:WorkspaceStore, cache:ChatCacheStore, o
     result.conversations.push({mode:'bot',id:c.id,name:c.name,preview:notificationPlainText(messages.at(-1)!.content,{maximum:160,fallback:messages.at(-1)!.attachments[0]?.name ?? '附件'}),count:messages.length,
       updatedAt:messages.at(-1)!.createdAt,messages:messages.map(m=>({id:m.id,seq:m.seq,version:m.chatUnreadVersion,taskId:m.conversationTaskId}))})
   }
-  for(const row of cache.unread(owner,'').sessions) {
-    if(!allowed('local',row.profile))continue
-    const stored=cache.db.prepare('SELECT s.data,l.archived FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE s.owner=? AND s.profile=? AND s.session_id=?').get(owner,row.profile,row.session_id)
-    if(!stored || stored.archived===1)continue
-    const summary=JSON.parse(String(stored.data))
-    if(summary.archived || summary.source==='yaoyao_workspace')continue
-    const messages=cache.transcripts.unreadMessages(owner,row.profile,row.session_id)
-    if(!messages.length)continue
-    const last=messages.at(-1)!
-    result.conversations.push({mode:'chat',id:row.session_id,profile:row.profile,name:summary.title || summary.name || '未命名聊天',preview:notificationPlainText(typeof last.content==='string'?last.content:'',{maximum:160,fallback:'附件'}),count:messages.length,
-      updatedAt:messageTime(last.timestamp ?? last.created_at ?? last.createdAt ?? summary.updated_at ?? 0),messages:messages.map(m=>({id:m.id,seq:m.seq}))})
-  }
   result.conversations.sort((a,b)=>b.updatedAt-a.updatedAt || a.id.localeCompare(b.id))
   for(const row of result.conversations)result[row.mode]+=row.count
   result.total=result.bot+result.chat
@@ -38,19 +21,12 @@ export function unreadSnapshot(workspace:WorkspaceStore, cache:ChatCacheStore, o
 }
 
 /** Only IDs in the user's click/render snapshot are acknowledged; later completions survive. */
-export function acknowledgeUnread(workspace:WorkspaceStore,cache:ChatCacheStore,owner:string,
+export function acknowledgeUnread(workspace:WorkspaceStore,owner:string,
   items:Array<Pick<UnreadConversation,'mode'|'id'|'profile'|'messages'>>,allowed:(node:string,profile:string)=>boolean=()=>true):void {
   for(const item of items) {
-    if(item.mode==='bot') {
-      const c=workspace.require<WorkspaceConversation>(owner,'conversation',item.id)
-      if(!c.memberIds.every(id=>{const a=workspace.get<WorkspaceAgent>(owner,'agent',id);return !a || allowed(a.nodeId,a.profile)}))continue
-      workspace.markChatMessagesRead(owner,c.id,item.messages)
-    } else {
-      const profile=item.profile ?? 'default'
-      if(!allowed('local',profile))continue
-      cache.requireOwned(owner,profile,item.id)
-      cache.transcripts.seed(owner,profile,item.id)
-      cache.transcripts.markMessagesRead(owner,profile,item.id,item.messages.map(m=>m.id))
-    }
+    if(item.mode!=='bot')continue
+    const c=workspace.require<WorkspaceConversation>(owner,'conversation',item.id)
+    if(!c.memberIds.every(id=>{const a=workspace.get<WorkspaceAgent>(owner,'agent',id);return !a || allowed(a.nodeId,a.profile)}))continue
+    workspace.markChatMessagesRead(owner,c.id,item.messages)
   }
 }

+ 0 - 139
src/server/workspaceRemoteAgents.ts

@@ -1,139 +0,0 @@
-import type Koa from 'koa'
-import { Readable } from 'node:stream'
-import { HttpError } from './errors.js'
-import type { LocalAuthStore } from './localAuth.js'
-import type { NodePairingStore } from './pairing.js'
-import type { WorkspaceStore } from './workspaceStore.js'
-import type { WorkspaceNodes, GatewayTarget } from './workspaceGateway.js'
-import type { WorkspaceAgent } from '../shared/workspace.js'
-
-export interface AgentExportContext {
-  id: string
-  target: GatewayTarget
-  valid(): boolean
-  transform(frame: Record<string, any>): Record<string, any>
-}
-const allowedCommands = new Set(['session.create','session.resume','session.close','session.usage','session.interrupt','prompt.submit','session.steer','image.attach_bytes','file.attach','approval.respond','clarify.respond'])
-
-/** A paired device sees only Agents owned by the account that issued its QR grant. */
-export function remoteAgentExports(store: WorkspaceStore, nodes: WorkspaceNodes, pairings: NodePairingStore, auth: LocalAuthStore): Koa.Middleware {
-  return async (ctx,next) => {
-    const match = /^\/node\/([0-9a-f-]{36})\/api\/workspace-agents(?:\/([0-9a-f-]{36})(?:\/gateway(\/api\/.*))?)?$/.exec(ctx.path)
-    if (!match) return next()
-    const device=match[1]!, agentId=match[2], path=match[3], token=ctx.get('authorization').match(/^Bearer\s+(.+)$/i)?.[1] ?? ''
-    const owner=pairings.workspaceOwner(device,token,path ? 'sessions.execute' : 'agents.read')
-    if (!auth.isUserActive(owner)) throw new HttpError(403,'远端授权账号已停用','remote_owner_unavailable')
-    const valid = () => {
-      try { return pairings.workspaceOwner(device,token,'sessions.execute')===owner && auth.isUserActive(owner)
-        && (!agentId || store.get<WorkspaceAgent>(owner,'agent',agentId)?.archived === false) }
-      catch { return false }
-    }
-    ctx.set('Cache-Control','no-store')
-    if (!agentId) {
-      if (ctx.method!=='GET') throw new HttpError(405,'只允许读取远端机器人','method_not_allowed')
-      const agents=store.list<WorkspaceAgent>(owner,'agent').filter(a=>!a.archived)
-      for(const value of agents) if(value.remoteAgentId) void nodes.refreshRemoteAgent(owner,value).catch(()=>{})
-      ctx.body={agents:agents.map(a=>store.agentSummary(a))};return
-    }
-    let agent=store.require<WorkspaceAgent>(owner,'agent',agentId)
-    if (agent.archived) throw new HttpError(410,'远端机器人已归档','remote_agent_archived')
-    if (agent.remoteAgentId) agent=await nodes.refreshRemoteAgent(owner,agent)
-    if (!path) {
-      if (ctx.method!=='GET') throw new HttpError(405,'远端配置只读','method_not_allowed')
-      ctx.body={agent:store.agentSummary(agent)};return
-    }
-    const hops=Number(ctx.get('x-yaoyao-agent-hops')||0)
-    if (!Number.isInteger(hops) || hops<0 || hops>=8) throw new HttpError(508,'远端机器人引用链过长或循环','agent_reference_loop')
-    const target=nodes.targetForAgent(owner,agent), scope=`${device}:${agentId}`
-    const bindingKey=(id:string)=>`${scope}:${id}`
-    const requireBinding=(id:string)=>{
-      const binding=store.get<{profile:string}>(owner,'agent-export-binding',bindingKey(id))
-      if (!binding || binding.profile!==agent.profile) throw new HttpError(403,'会话不属于这个机器人引用','agent_session_forbidden')
-    }
-    const transform=(frame:Record<string,any>)=>{
-      if (!allowedCommands.has(frame.method)) throw new HttpError(403,'不能通过引用修改远端配置','remote_agent_read_only')
-      const params={...frame.params}
-      if (frame.method==='session.create' || frame.method==='session.resume') {
-        if(frame.method==='session.resume') requireBinding(String(params.session_id))
-        params.profile=agent.profile
-        for (const key of ['model','provider','config','cwd','reasoning_effort','fast','messages']) delete params[key]
-      }
-      if ((frame.method==='prompt.submit'||frame.method==='session.steer') && !agent.remoteAgentId) {
-        if (typeof params.text!=='string') throw new HttpError(400,'消息内容无效','invalid_prompt')
-        params.text=`你是 ${agent.name}。远端机器人的角色与规则(版本 ${agent.revision}):\n${agent.instructions}\n\n${params.text}`
-      }
-      const id=ctx.get('idempotency-key')
-      if (id) store.put(owner,'agent-export-command',bindingKey(id),{method:frame.method,profile:agent.profile})
-      return {...frame,params}
-    }
-    const remember=(receipt:any)=>{
-      const id=ctx.get('idempotency-key') || /^\/api\/realtime\/commands\/([^/]+)$/.exec(path)?.[1]
-      const command=id ? store.get<{method:string}>(owner,'agent-export-command',bindingKey(id)) : undefined
-      if (!id || !command || !['session.create','session.resume'].includes(command.method)) return
-      const result=receipt?.state==='confirmed' ? receipt.response?.result : undefined
-      const stored=result?.stored_session_id ?? result?.session_key ?? result?.info?.stored_session_id ?? result?.session_id
-      if (typeof stored==='string' && stored.length<=256) {
-        store.put(owner,'agent-export-binding',bindingKey(stored),{profile:agent.profile})
-      }
-    }
-    if (path==='/api/profiles' && ctx.method==='GET') { ctx.body={profiles:[{name:agent.profile,display_name:agent.name}]};return }
-    if (path.startsWith('/api/realtime/')) {
-      const selectedChannel=/^\/api\/realtime\/channels\/([0-9a-f-]{36})/.exec(path)?.[1]
-      if (selectedChannel && !store.get(owner,'agent-export-channel',bindingKey(selectedChannel)))
-        throw new HttpError(403,'通道不属于这个机器人引用','agent_channel_forbidden')
-      const receiptID=/^\/api\/realtime\/commands\/([^/]+)$/.exec(path)?.[1]
-      if (receiptID && !store.get(owner,'agent-export-command',bindingKey(receiptID)))
-        throw new HttpError(403,'命令不属于这个机器人引用','agent_command_forbidden')
-      const rememberChannel=(body:any)=>{
-        if(ctx.method==='POST' && path==='/api/realtime/channels' && typeof body?.id==='string')
-          store.put(owner,'agent-export-channel',bindingKey(body.id),{createdAt:Date.now()})
-      }
-      if (!target.pairedToken) {
-        ctx.state.workspaceAgentExport={id:agentId,target,valid,transform} satisfies AgentExportContext
-        const previous=ctx.url
-        ctx.url=`/node/${device}${path}${ctx.search}`
-        try { await next(); rememberChannel(ctx.body); remember(ctx.body) } finally { ctx.url=previous }
-        return
-      }
-      const allowed=/^\/api\/realtime\/(capabilities|channels(?:\/[0-9a-f-]{36}(?:\/(events|commands))?)?|commands\/[A-Za-z0-9:_-]{1,200})$/.test(path)
-      if (!allowed) throw new HttpError(404,'机器人实时路径不存在','not_found')
-      let body: any
-      if (ctx.method==='POST') {
-        let size=0;const parts:Buffer[]=[]
-        for await(const part of ctx.req) {size+=part.length;if(size>36*1024*1024) throw new HttpError(413,'请求过大','body_too_large');parts.push(Buffer.from(part))}
-        try {body=JSON.parse(Buffer.concat(parts).toString())} catch {throw new HttpError(400,'JSON 无效','invalid_json')}
-        if(path.endsWith('/commands')) body=transform(body)
-        else if(body.channel!=='chat') throw new HttpError(403,'机器人仅支持聊天通道','invalid_channel')
-      }
-      const abort=new AbortController(), timer=setTimeout(()=>abort.abort(),30_000)
-      ctx.res.once('close',()=>abort.abort())
-      let response: Response
-      try {response=await target.client.fetchImpl(new URL(`${target.url.href.replace(/\/$/,'')}${path}${ctx.search}`),{
-        method:ctx.method,redirect:'error',signal:abort.signal,
-        headers:{Authorization:`Bearer ${target.pairedToken}`,'Content-Type':'application/json','Last-Event-ID':ctx.get('last-event-id'),'Idempotency-Key':ctx.get('idempotency-key'),'x-yaoyao-agent-hops':String(hops+1)},
-        ...(body!==undefined ? {body:JSON.stringify(body)} : {}),
-      })} finally {clearTimeout(timer)}
-      ctx.status=response.status
-      ctx.set('Content-Type',response.headers.get('content-type')||'application/json')
-      if(response.headers.get('content-type')?.startsWith('text/event-stream') && response.body) {
-        const interval=setInterval(()=>{if(!valid())abort.abort()},5000);interval.unref()
-        ctx.res.once('close',()=>clearInterval(interval))
-        const stream=Readable.fromWeb(response.body as any)
-        stream.once('close',()=>clearInterval(interval));stream.once('error',()=>clearInterval(interval))
-        ctx.body=stream
-      }
-      else if(response.status!==204) {ctx.body=await response.json();rememberChannel(ctx.body);remember(ctx.body)}
-      return
-    }
-    if (ctx.method!=='GET') throw new HttpError(405,'机器人引用只允许读取文件与会话','method_not_allowed')
-    pairings.authorize(device,token,'history.read')
-    const history=/^\/api\/sessions\/([^/]+)\/messages$/.exec(path)
-    if (history) requireBinding(decodeURIComponent(history[1]!))
-    else if(path!=='/api/files/download') throw new HttpError(403,'路径不属于机器人引用','agent_path_forbidden')
-    const query=new URLSearchParams(ctx.querystring);query.set('profile',agent.profile)
-    const response=await target.session.request(path,{search:query,maxResponseBytes:25*1024*1024})
-    ctx.status=response.status
-    for(const name of ['content-type','content-disposition']) {const value=response.headers.get(name);if(value)ctx.set(name,value)}
-    ctx.body=response.body
-  }
-}

+ 1 - 11
src/server/workspaceStore.ts

@@ -1072,11 +1072,10 @@ export class WorkspaceStore {
       .map((r) => this.messageForDisplay(owner, JSON.parse(String(r.data)) as Message))
       .reverse()
   }
-  nativeMessageForFile?: (owner: string, file: StoredWorkspaceFile) => Message | undefined
   visibleFiles(owner: string): StoredWorkspaceFile[] {
     const messages = new Map(this.list<Message>(owner, 'message').map(message => [message.id, message]))
     return this.list<StoredWorkspaceFile>(owner, 'file').filter(file =>
-      isVisibleMessageFile(file, messages.get(file.messageId ?? '') ?? this.nativeMessageForFile?.(owner, file)))
+      isVisibleMessageFile(file, messages.get(file.messageId ?? '')))
       .map(file => file.sender === 'user' ? { ...file, name: normalizeUploadName(file.name) } : file)
   }
   messageForDisplay(owner: string, message: Message): Message {
@@ -1236,15 +1235,6 @@ export class WorkspaceStore {
     conversation.avatarSignals = Object.fromEntries(outcomes.filter(turn => Date.now() - turn.updatedAt < 2000).map(turn => [turn.agentId, { id:turn.id, state:turn.status === 'failed' ? 'failure' as const : 'success' as const, at:turn.updatedAt }]))
     conversation.queuedMessageCount = roots.filter(run => run.status === 'queued').length
   }
-  ownsUpstream(id: string): boolean {
-    return Boolean(
-      this.db
-        .prepare(
-          `SELECT 1 FROM workspace_entities WHERE kind='binding' AND (json_extract(data,'$.storedId')=? OR json_extract(data,'$.runtimeId')=? OR EXISTS(SELECT 1 FROM json_each(json_extract(data,'$.aliases')) WHERE value=?)) LIMIT 1`,
-        )
-        .get(id, id, id),
-    )
-  }
   close(): void {
     for (const timer of this.summaryTimers.values()) clearTimeout(timer)
     this.summaryTimers.clear()

+ 0 - 125
src/shared/chatTranscript.ts

@@ -1,125 +0,0 @@
-/** Ordinary-chat display protocol. Upstream identities remain server metadata. */
-export const CHAT_TRANSCRIPT_FEATURE = 'ordinary-chat-transcript-v2'
-export interface TranscriptMessage {
-  id: string
-  seq: number
-  revision: number
-  source_message_id: string
-  client_message_id?: string
-  turn_id?: string
-  segment_kind?: 'input' | 'commentary' | 'answer' | 'tool' | 'system'
-  role: string
-  content: unknown
-  reasoning?: string
-  status?: string
-  [key: string]: unknown
-}
-export interface TranscriptPatch {
-  id: string
-  seq: number
-  baseRevision: number
-  revision: number
-  contentAppend: string
-  reasoningAppend: string
-}
-export interface TranscriptEvent {
-  cursor: number
-  profile: string
-  sessionId: string
-  epoch?: string
-  previousCursor?: number
-  total?: number
-  type:
-    | 'message.upsert'
-    | 'message.patch'
-    | 'message.deleted'
-    | 'session.changed'
-    | 'session.deleted'
-    | 'session.migrated'
-  data: unknown
-}
-export interface TranscriptSnapshot {
-  protocol: typeof CHAT_TRANSCRIPT_FEATURE
-  epoch: string
-  cursor: number
-  profile: string
-  sessionId: string
-  messages: TranscriptMessage[]
-  session: Record<string, unknown>
-  hasOlder: boolean
-  total: number
-  state: string
-  deletedIds?: string[]
-  running?: boolean
-  queued?: boolean
-  pendingApproval?: Record<string, unknown> | null
-  pendingClarification?: Record<string, unknown> | null
-  liveStatus?: string | null
-  error?: string | null
-}
-export interface TranscriptControlState {
-  running: boolean
-  queued: boolean
-  pendingApproval: Record<string, unknown> | null
-  pendingClarification: Record<string, unknown> | null
-  liveStatus: string | null
-  error: string | null
-}
-export interface TranscriptControlEvent extends TranscriptControlState {
-  epoch: string
-  cursor: number
-}
-export class TranscriptGap extends Error {
-  constructor() {
-    super('普通聊天消息版本不连续,需要重新同步')
-  }
-}
-export function applyTranscriptEvent(
-  messages: TranscriptMessage[],
-  event: TranscriptEvent,
-): TranscriptMessage[] {
-  const data = event.data as TranscriptMessage & TranscriptPatch
-  const index = messages.findIndex((message) => message.id === data.id)
-  const old = messages[index]
-  if (event.type === 'message.deleted') {
-    if (!Number.isSafeInteger(data.revision) || data.revision < 1) throw new TranscriptGap()
-    return old && old.revision >= data.revision
-      ? messages
-      : messages.filter((message) => message.id !== data.id)
-  }
-  if (event.type === 'message.upsert') {
-    if (
-      !data.id ||
-      !Number.isSafeInteger(data.seq) ||
-      !Number.isSafeInteger(data.revision) ||
-      data.revision < 1
-    )
-      throw new TranscriptGap()
-    if (old && old.revision >= data.revision) return messages
-    return [...messages.filter((message) => message.id !== data.id), data].sort(
-      (a, b) => a.seq - b.seq || a.id.localeCompare(b.id),
-    )
-  }
-  if (event.type === 'message.patch') {
-    if (old && old.revision >= data.revision) return messages
-    if (
-      !old ||
-      old.revision !== data.baseRevision ||
-      data.revision !== data.baseRevision + 1 ||
-      old.seq !== data.seq ||
-      typeof old.content !== 'string' ||
-      typeof data.contentAppend !== 'string' ||
-      typeof data.reasoningAppend !== 'string'
-    )
-      throw new TranscriptGap()
-    const next = [...messages]
-    next[index] = {
-      ...old,
-      revision: data.revision,
-      content: old.content + data.contentAppend,
-      reasoning: String(old.reasoning ?? '') + data.reasoningAppend,
-    }
-    return next
-  }
-  return messages
-}

+ 0 - 15
tests/client/agentAvatar.test.ts

@@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest'
 import { nextTick } from 'vue'
 import { defaultAgentIdentity, encodeAgentAvatar } from '@shared/agentIdentity'
 import AgentAvatar from '@/components/common/AgentAvatar.vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 
 const transparentPng = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='
 
@@ -81,20 +80,6 @@ describe('AgentAvatar', () => {
     wrapper.unmount()
   })
 
-  it('keeps a group-message image transparent when MessageTimeline adds its fallback class', () => {
-    const wrapper = mount(MessageTimeline, {
-      attachTo: document.body,
-      props: {
-        messages: [{ id: 'assistant-1', role: 'assistant', profile: 'default', author: '丫头', content: '收到,测试正常。' }],
-        agentAvatars: { default: transparentPng },
-      },
-    })
-    const avatar = wrapper.get('.message__avatar')
-
-    expect(avatar.classes()).toEqual(expect.arrayContaining(['agent-avatar--image', 'message__avatar']))
-    expect(getComputedStyle(avatar.element).backgroundColor).toBe('rgba(0, 0, 0, 0)')
-    wrapper.unmount()
-  })
 })
 
 it('parks animation frames for idle, hidden, background and reduced-motion avatars', async () => {

+ 2 - 3
tests/client/chatAppearance.test.ts

@@ -1,6 +1,5 @@
 import { describe, expect, it, afterEach, beforeEach, vi } from 'vitest'
 import { nextTick } from 'vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 import WorkspaceMessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
 import { mount } from '@vue/test-utils'
 import { appearancePreset, bubbleColors, bubbleVariables, contrast, normalizeAppearance } from '@/utils/chatAppearance'
@@ -20,9 +19,9 @@ beforeEach(() => {
 })
 afterEach(() => { vi.restoreAllMocks(); useChatAppearance().selectPreset('current') })
 describe('chat bubble appearance', () => {
-  it.each([MessageTimeline, WorkspaceMessageTimeline])('updates rendered bubbles when a preset changes without replacing messages', async (component) => {
+  it.each([WorkspaceMessageTimeline])('updates rendered bubbles when a preset changes without replacing messages', async (component) => {
     const store = useChatAppearance()
-    const wrapper = mount(component as typeof MessageTimeline, {
+    const wrapper = mount(component as typeof WorkspaceMessageTimeline, {
       props: {identity: 'appearance', messages: [{id:'u',role:'user',content:'问题'}, {id:'a',role:'assistant',content:'长回复'}, {id:'s',role:'system',content:'系统信息'}]},
       global: {stubs: {AgentAvatar:true, AppIcon:true}},
     })

+ 0 - 478
tests/client/chatCrossClientSync.test.ts

@@ -1,478 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { createPinia, setActivePinia } from 'pinia'
-import type { TranscriptSnapshot } from '@shared/chatTranscript'
-import type { RpcEventFrame, RealtimeConnectionState } from '@shared/types'
-const wire = vi.hoisted(() => ({
-  event: undefined as ((e: RpcEventFrame['params']) => void) | undefined,
-  state: undefined as ((s: RealtimeConnectionState) => void) | undefined,
-  request: vi.fn(),
-  clients: [] as any[],
-  owner: 0,
-  supported: true,
-}))
-const api = vi.hoisted(() => ({ messages: vi.fn(), sessions: vi.fn() }))
-vi.mock('@/api/realtime', () => ({
-  RpcError: class extends Error {},
-  ChatRpcSocket: class {
-    get transcriptSupported() {
-      return wire.supported
-    }
-    onEvent(f: typeof wire.event) {
-      wire.event = f
-    }
-    onState(f: typeof wire.state) {
-      wire.state = f
-    }
-    async connect() {
-      wire.state?.('ready')
-    }
-    close() {}
-    async request(...args: unknown[]) {
-      return wire.request(...args)
-    }
-  },
-}))
-vi.mock('@/api/chatTranscript', () => ({
-  ChatTranscriptClient: class {
-    close = vi.fn()
-    loadOlder = vi.fn()
-    restore = vi.fn()
-    run = vi.fn()
-    constructor(
-      readonly profile: string,
-      readonly id: string,
-      readonly changed: (value: TranscriptSnapshot) => Promise<void>,
-      readonly failed: (error: Error) => void,
-    ) {
-      wire.clients.push(this)
-    }
-  },
-}))
-vi.mock('@/api/sessions', () => ({
-  getMessages: api.messages,
-  getSessions: api.sessions,
-  getSession: vi.fn(),
-  deleteSession: vi.fn(),
-  getSessionUnread: vi.fn(),
-  markSessionRead: vi.fn(),
-  updateSession: vi.fn(),
-  requestHistorySync: vi.fn(),
-}))
-vi.mock('@/api/profiles', () => ({ getModels: vi.fn() }))
-vi.mock('@/stores/auth', () => ({
-  useAuthStore: () => ({
-    user: { id: `v2-viewer-${wire.owner}` },
-    activeProfile: { name: 'p' },
-    status: 'authenticated',
-    isAuthenticated: true,
-  }),
-}))
-import { useChatStore } from '@/stores/chat'
-import { ScopedCache } from '@/utils/cache'
-function session(id = 's', owned = true) {
-  return {
-    id,
-    profile: 'p',
-    owned,
-    source: 'web',
-    title: id,
-    messageCount: 0,
-    toolCallCount: 0,
-    startedAt: 1,
-    updatedAt: 1,
-  }
-}
-function snapshot(messages: any[], id = 's', extra: Partial<TranscriptSnapshot> = {}): TranscriptSnapshot {
-  return {
-    protocol: 'ordinary-chat-transcript-v2',
-    epoch: 'test',
-    cursor: 1,
-    profile: 'p',
-    sessionId: id,
-    messages,
-    session: {},
-    hasOlder: false,
-    total: messages.length,
-    state: 'current',
-    running: false,
-    queued: false,
-    ...extra,
-  }
-}
-const answer = (content = '规范正文', extra = {}) => ({
-  id: 'canonical-answer',
-  seq: 2,
-  revision: 1,
-  source_message_id: 'upstream',
-  turn_id: 'turn',
-  role: 'assistant',
-  content,
-  status: 'complete',
-  ...extra,
-})
-function emit(type: string, payload: any = {}) {
-  wire.event?.({ type, session_id: 'runtime', profile: 'p', payload })
-}
-describe('ordinary v2 cross-client store', () => {
-  let chat: ReturnType<typeof useChatStore>
-  beforeEach(() => {
-    setActivePinia(createPinia())
-    wire.owner++
-    wire.clients = []
-    wire.supported = true
-    wire.request
-      .mockReset()
-      .mockResolvedValue({ session_id: 'runtime', stored_session_id: 's', running: false })
-    api.messages.mockReset().mockResolvedValue({ messages: [], total: 0, returned: 0, hasMore: false })
-    api.sessions.mockReset().mockResolvedValue({ items: [session()] })
-    chat = useChatStore()
-    chat.sessions = [session()]
-  })
-  afterEach(() => {
-    chat.disconnect()
-    vi.useRealTimers()
-  })
-  async function open(id = 's') {
-    await chat.selectSession(id, 'p')
-    await vi.waitFor(() => expect(wire.clients.some((c) => c.id === id)).toBe(true))
-    return wire.clients.filter((c) => c.id === id).at(-1)!
-  }
-  it('refreshes an opened owned session with the same gauge source order as mobile', async () => {
-    wire.request.mockImplementation(async (method: string) => {
-      if (method === 'session.resume') return { session_id: 'runtime', stored_session_id: 's' }
-      if (method === 'session.usage') return { input_tokens: 1_800_000, output_tokens: 100_000, total_tokens: 1_900_000 }
-      if (method === 'session.context_breakdown') return { context_used: 12_500, context_max: 114_688, context_percent: 10.9 }
-      return {}
-    })
-    await open()
-    await vi.waitFor(() => expect(chat.contextUsage).toMatchObject({
-      totalTokens: 1_900_000, contextTokens: 12_500, contextLimit: 114_688, percentUsed: 10.9,
-    }))
-    expect(wire.request).toHaveBeenCalledWith('session.usage', { session_id: 'runtime' }, 15_000)
-    expect(wire.request).toHaveBeenCalledWith('session.context_breakdown', { session_id: 'runtime' }, 15_000)
-  })
-
-  it('keeps read-only history unattached when context statistics are unavailable', async () => {
-    chat.sessions = [session('s', false)]
-    await chat.selectSession('s', 'p')
-    expect(wire.request).not.toHaveBeenCalled()
-    expect(chat.contextUsage).toBeUndefined()
-  })
-
-  it('does not let a slow usage response replace a newer realtime gauge', async () => {
-    await open()
-    let finish!: (value: unknown) => void
-    wire.request.mockImplementation((method: string) => method === 'session.usage'
-      ? new Promise(resolve => { finish = resolve }) : Promise.resolve({}))
-    const refreshing = chat.refreshContextUsage()
-    emit('session.usage', { context_used: 4000, context_max: 8000, context_percent: 50 })
-    finish({ context_used: 1000, context_max: 8000, context_percent: 12.5 })
-    await refreshing
-    expect(chat.contextUsage).toMatchObject({ contextTokens: 4000, contextLimit: 8000, percentUsed: 50 })
-  })
-
-  it('refreshes context after a turn completed on another client', async () => {
-    const client = await open()
-    await client.changed(snapshot([answer('处理中', { status: 'streaming' })], 's', { running: true }))
-    wire.request.mockImplementation(async (method: string) => method === 'session.usage'
-      ? { context_used: 4000, context_max: 8000 } : {})
-    await client.changed(snapshot([answer()], 's', { running: false }))
-    await vi.waitFor(() => expect(chat.contextUsage).toMatchObject({ contextTokens: 4000, contextLimit: 8000 }))
-  })
-
-  it('restores a confirmed gauge from session metadata without inventing context from history', async () => {
-    wire.request.mockResolvedValue({ session_id: 'runtime', stored_session_id: 's',
-      info: { usage: { context_used: 2000, context_max: 8000 } } })
-    const client = await open()
-    expect(chat.contextUsage).toMatchObject({ contextTokens: 2000, contextLimit: 8000 })
-    await client.changed(snapshot([answer('很长的旧记录'.repeat(200))], 's', {
-      session: { input_tokens: 1_800_000, output_tokens: 100_000 },
-    }))
-    expect(chat.contextUsage).toMatchObject({ contextTokens: 2000, contextLimit: 8000 })
-  })
-  it.each(['image_path', 'path', 'ref_path'])('preserves uploaded image %s in pending and canonical messages', async field => {
-    const client = await open()
-    const paths = ['/home/user/.hermes/images/照片 one.png', '/tmp/photo-two.png']
-    let uploaded = 0
-    wire.request.mockImplementation((method: string) => Promise.resolve(
-      method === 'image.attach_bytes' ? { [field]: paths[uploaded++] } : {},
-    ))
-    await chat.send('查看图片', paths.map((_, index) => new File(['image'], `photo-${index}.png`, { type: 'image/png' })))
-    const submission = wire.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
-    expect(submission.text).toBe([
-      '查看图片',
-      `[用户附加图片:photo-0.png]\n@image:${paths[0]}\n[screenshot]`,
-      `[用户附加图片:photo-1.png]\n@image:${paths[1]}\n[screenshot]`,
-    ].join('\n\n'))
-    const pending = chat.messages.find(message => message.role === 'user')!
-    expect(pending.attachments?.map(file => file.path)).toEqual(paths)
-    const checkDownloads = () => chat.messages[0]!.attachments?.forEach((file, index) => {
-      const url = new URL(file.url!, 'https://yaoyao.test')
-      expect(url.pathname).toBe('/api/files/download')
-      expect(url.searchParams.get('path')).toBe(paths[index])
-      expect(url.searchParams.get('profile')).toBe('p')
-    })
-    checkDownloads()
-    await client.changed(snapshot([{
-      id: 'canonical-image', seq: 1, revision: 1, role: 'user', status: 'complete',
-      client_message_id: pending.clientMessageId, content: submission.text,
-    }]))
-    expect(chat.messages).toHaveLength(1)
-    expect(chat.messages[0]!.content).toBe('查看图片')
-    expect(chat.messages[0]!.attachments?.map(file => file.path)).toEqual(paths)
-    checkDownloads()
-  })
-  it('does not fabricate an image path when an older upload response omits it', async () => {
-    await open()
-    wire.request.mockResolvedValue({})
-    await chat.send('', [new File(['image'], 'photo.png', { type: 'image/png' })])
-    const submission = wire.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
-    expect(submission.text).toBe('[用户附加图片:photo.png]\n[screenshot]')
-    expect(chat.messages[0]!.attachments?.[0]?.url).toBeUndefined()
-  })
-  it.each(['failed', 'unknown-receipt'] as const)('keeps an older %s input before newer messages through sync and cache restoration', async stage => {
-    const client = await open()
-    const oldAnswer = answer('之前的回复', { timestamp: 10 })
-    await client.changed(snapshot([oldAnswer]))
-    chat.activeRouteState!.messages.push({
-      id: 'local-failed', clientMessageId: 'local-failed', sessionId: 's', profile: 'p',
-      role: 'user', content: '再试试', timestamp: 15, stage,
-    })
-    const newerUser = { id: 'new-user', seq: 3, revision: 1, role: 'user', content: '再试试', timestamp: 20, status: 'complete' }
-    const newerAnswer = answer('新的回复', { id: 'new-answer', seq: 4, timestamp: 21 })
-    const expected = ['canonical-answer', 'local-failed', 'new-user', 'new-answer']
-    await client.changed(snapshot([oldAnswer, newerUser, newerAnswer], 's', { cursor: 2 }))
-    expect(chat.messages.map(m => m.id)).toEqual(expected)
-    await client.changed(snapshot([oldAnswer, newerUser, { ...newerAnswer, revision: 2 }], 's', { cursor: 3 }))
-    expect(chat.messages.map(m => m.id)).toEqual(expected)
-    const cached = await new ScopedCache<{ messages: { id: string }[] }>('chat-history-v1').get(`v2-viewer-${wire.owner}:p`, 's')
-    expect(cached?.messages.map(m => m.id)).toEqual(expected)
-
-    chat.disconnect()
-    setActivePinia(createPinia())
-    chat = useChatStore()
-    chat.sessions = [session()]
-    wire.clients = []
-    const restored = await open()
-    expect(chat.messages.map(m => m.id)).toEqual(expected)
-    await restored.changed(snapshot([oldAnswer, newerUser, newerAnswer], 's', { cursor: 4 }))
-    expect(chat.messages.map(m => m.id)).toEqual(expected)
-    expect(chat.messages.find(m => m.id === 'local-failed')?.stage).toBe(stage)
-  })
-  it('keeps a model-switch confirmation through transcript updates and sends after confirmation', async () => {
-    const client = await open()
-    const model = { id: 'model-b', name: 'Model B', provider: 'provider-b' }
-    chat.models = [model]
-    wire.request.mockImplementation(async (method, params) => {
-      if (method === 'session.resume') return { session_id: 'runtime', stored_session_id: 's', running: false }
-      if (method === 'config.set' && params.key === 'model') return params.confirm_expensive_model
-        ? { value: model.id, scope: 'session' }
-        : { confirm_required: true, confirm_message: 'Switching this long conversation loses its cached input.' }
-      return {}
-    })
-    await chat.setModel(model)
-    await expect(chat.send('待发送')).rejects.toThrow('请先确认模型切换')
-    const confirmation = chat.pendingApproval
-    expect(confirmation?.message).toContain('cached input')
-    await client.changed(snapshot([answer()], 's', { pendingApproval: null }))
-    expect(chat.pendingApproval).toEqual(confirmation)
-
-    await chat.respondToApproval(confirmation!.id, 'once')
-    expect(wire.request).toHaveBeenCalledWith('config.set', expect.objectContaining({
-      key: 'model', confirm_expensive_model: true,
-    }))
-    expect(chat.pendingApproval).toBeUndefined()
-    wire.request.mockClear()
-    await chat.send('确认后继续')
-    expect(wire.request).toHaveBeenCalledWith('prompt.submit', expect.objectContaining({ text: '确认后继续' }), expect.anything(), expect.anything())
-    expect(wire.request.mock.calls.some(([method, params]) => method === 'config.set' && params.key === 'model')).toBe(false)
-  })
-  it('keeps native approvals separate and dismisses a superseded model confirmation', async () => {
-    const client = await open()
-    const first = { id: 'model-b', provider: 'provider', name: 'B' }
-    const second = { id: 'model-c', provider: 'provider', name: 'C' }
-    wire.request.mockImplementation(async (method, params) => method === 'config.set' && params.key === 'model'
-      ? { confirm_required: true, confirm_message: `Confirm ${params.value}` } : {})
-    await chat.setModel(first)
-    const staleId = chat.pendingApproval!.id
-    await chat.setModel(second)
-    const confirmation = chat.pendingApproval!
-    expect(confirmation.id).not.toBe(staleId)
-    await client.changed(snapshot([], 's', { pendingApproval: { request_id: 'tool-approval', message: '允许工具' } }))
-    expect(chat.pendingApproval?.id).toBe(confirmation.id)
-    wire.request.mockClear()
-    await chat.respondToApproval(staleId, 'once')
-    expect(wire.request).not.toHaveBeenCalled()
-    await chat.respondToApproval(confirmation.id, 'deny')
-    expect(chat.pendingApproval?.id).toBe('tool-approval')
-    await chat.respondToApproval('tool-approval', 'once')
-    expect(wire.request).toHaveBeenCalledWith('approval.respond', expect.objectContaining({ choice: 'once' }))
-  })
-  it('renders only canonical messages and ignores raw upstream bodies and completions', async () => {
-    const client = await open()
-    await client.changed(snapshot([answer('前半', { status: 'streaming' })], 's', { running: true }))
-    emit('message.delta', { text: '不应追加' })
-    emit('message.interim', { text: '不应重复' })
-    emit('message.complete', { text: '不应替换' })
-    expect(chat.messages.map((m) => m.content)).toEqual(['前半'])
-    expect(chat.isStreaming).toBe(true)
-    await client.changed(snapshot([answer('完整正文', { revision: 2 })], 's', { cursor: 2 }))
-    expect(chat.messages.map((m) => m.content)).toEqual(['完整正文'])
-    expect(chat.isStreaming).toBe(false)
-    expect(api.messages).not.toHaveBeenCalled()
-  })
-  it('keeps checkpoint state when a usage update replaces the route during outbox persistence', async () => {
-    const client = await open()
-    const original = ScopedCache.prototype.set
-    let entered!: () => void, release!: () => void
-    const started = new Promise<void>(resolve => { entered = resolve })
-    const gate = new Promise<void>(resolve => { release = resolve })
-    const spy = vi.spyOn(ScopedCache.prototype, 'set').mockImplementation(async function(this: ScopedCache<unknown>, scope, key, value, durable) {
-      if ((this as unknown as { namespace: string }).namespace === 'ordinary-outbox-v2') {
-        entered()
-        await gate
-      }
-      await original.call(this, scope, key, value, durable)
-    })
-    const saving = client.changed(snapshot([answer('正在处理', { status: 'streaming' })], 's', {
-      running: true, liveStatus: '正在思考', pendingApproval: { request_id: 'approval-1', message: '请确认' },
-    }))
-    try {
-      await started
-      wire.event?.({ type: 'session.usage', session_id: 's', profile: 'p', payload: { input_tokens: 7 } })
-      release()
-      await saving
-      expect(chat.messages.map(m => m.content)).toEqual(['正在处理'])
-      expect(chat.isStreaming).toBe(true)
-      expect(chat.pendingApproval?.id).toBe('approval-1')
-      expect(chat.contextUsage?.inputTokens).toBe(7)
-    } finally {
-      release()
-      await saving.catch(() => {})
-      spy.mockRestore()
-    }
-  })
-  it('does not materialize a resume snapshot beside the canonical reply', async () => {
-    wire.request.mockResolvedValue({
-      session_id: 'runtime',
-      stored_session_id: 's',
-      running: true,
-      inflight: { assistant: '旧恢复快照' },
-    })
-    const client = await open()
-    await client.changed(snapshot([answer('当前正文')]))
-    expect(chat.messages.map((m) => m.content)).toEqual(['当前正文'])
-    expect(chat.messages[0]!.id).toBe('canonical-answer')
-  })
-  it('restores tools and pending interactions from the canonical snapshot', async () => {
-    const client = await open()
-    await client.changed(
-      snapshot(
-        [
-          answer('', {
-            status: 'streaming',
-            tool_calls: [{ id: 'tool', name: 'terminal', status: 'running' }],
-          }),
-        ],
-        's',
-        {
-          running: true,
-          pendingApproval: { request_id: 'approval', message: '允许执行' },
-          pendingClarification: { request_id: 'clarify', question: '请选择' },
-        },
-      ),
-    )
-    expect(chat.messages[0]!.toolCalls?.[0]?.id).toBe('tool')
-    expect(chat.pendingApproval?.id).toBe('approval')
-    expect(chat.pendingClarification?.id).toBe('clarify')
-    await client.changed(
-      snapshot([answer()], 's', { cursor: 2, pendingApproval: null, pendingClarification: null }),
-    )
-    expect(chat.pendingApproval).toBeUndefined()
-    expect(chat.pendingClarification).toBeUndefined()
-  })
-  it('rejects a closed session callback after switching to another conversation', async () => {
-    const first = await open()
-    chat.sessions.push(session('second'))
-    wire.request.mockResolvedValue({ session_id: 'runtime-2', stored_session_id: 'second' })
-    const second = await open('second')
-    await second.changed(snapshot([answer('第二个会话')], 'second'))
-    await first.changed(snapshot([answer('旧回调')]))
-    expect(chat.activeSessionId).toBe('second')
-    expect(chat.messages[0]!.content).toBe('第二个会话')
-  })
-  it('does not let a late submit receipt re-open a completed turn or duplicate the user', async () => {
-    const client = await open()
-    let accept!: (value: any) => void
-    wire.request.mockImplementation((method: string) =>
-      method === 'prompt.submit'
-        ? new Promise((resolve) => {
-            accept = resolve
-          })
-        : Promise.resolve({}),
-    )
-    const sending = chat.send('问题')
-    await vi.waitFor(() => expect(accept).toBeTypeOf('function'))
-    const local = chat.messages.find((m) => m.role === 'user')!
-    await client.changed(
-      snapshot(
-        [
-          {
-            id: 'canonical-user',
-            seq: 1,
-            revision: 2,
-            source_message_id: 'persisted-user',
-            client_message_id: local.clientMessageId,
-            role: 'user',
-            content: '问题',
-            status: 'complete',
-          },
-          answer(),
-        ],
-        's',
-        { cursor: 3, running: false },
-      ),
-    )
-    accept({ status: 'streaming' })
-    await sending
-    expect(chat.messages.filter((m) => m.role === 'user')).toHaveLength(1)
-    expect(chat.messages[0]!.stage).toBe('settled')
-    expect(chat.isStreaming).toBe(false)
-  })
-  it('keeps a pending local input during a new generation replacement', async () => {
-    const client = await open()
-    let reject!: (error: Error) => void
-    wire.request.mockImplementation((method: string) =>
-      method === 'prompt.submit'
-        ? new Promise((_resolve, r) => {
-            reject = r
-          })
-        : Promise.resolve({}),
-    )
-    const sending = chat.send('待确认').catch(() => {})
-    await vi.waitFor(() => expect(reject).toBeTypeOf('function'))
-    const local = chat.messages[0]!.id
-    await client.changed(snapshot([answer('历史重建')], 's', { epoch: 'rebuilt' }))
-    expect(chat.messages.some((m) => m.id === local)).toBe(true)
-    reject(new Error('connection lost'))
-    await sending
-  })
-  it('uses transcript pagination without requesting legacy message pages', async () => {
-    const client = await open()
-    await client.changed(snapshot([answer()], 's', { hasOlder: true }))
-    await chat.loadOlder()
-    expect(client.loadOlder).toHaveBeenCalledOnce()
-    expect(api.messages).not.toHaveBeenCalled()
-  })
-  it('requires v2 and never falls back to legacy history for owned chat', async () => {
-    wire.supported = false
-    await expect(chat.selectSession('s', 'p')).rejects.toThrow('升级服务端')
-    expect(api.messages).not.toHaveBeenCalled()
-  })
-  it('keeps read-only native history outside the ordinary transcript', async () => {
-    chat.sessions = [session('s', false)]
-    await chat.selectSession('s', 'p')
-    expect(api.messages).toHaveBeenCalledOnce()
-    expect(wire.request).not.toHaveBeenCalled()
-  })
-})

+ 0 - 109
tests/client/chatLifecycle.test.ts

@@ -1,109 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { ChatMessage, ChatRouteState } from '@shared/types'
-import { applyChatEvent, settleChatMessages } from '@/utils/messageReducer'
-import { normalizeChatMessage } from '@/utils/normalize'
-import { reconcileChatHistory } from '@/utils/chatHistory'
-import { chatMessagesToUi } from '@/components/workspace/viewModels'
-import { buildMessageTimelineRows } from '@/utils/turnTrace'
-
-function state(): ChatRouteState { return { route: { sessionId: 's', profile: 'p' }, messages: [], isStreaming: false, isQueued: false,
-  historySynced: true, hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0, isLoadingHistory: false, generation: 1 } }
-const user = (id: string): ChatMessage => ({ id, sessionId: 's', role: 'user', content: 'pwd', timestamp: 1, stage: 'settled' })
-
-describe('ordinary tool lifecycle and authoritative history', () => {
-  it('counts one invocation across generating/start/complete in legacy history presentation', () => {
-    let current = state()
-    for (const [type, payload] of [
-      ['message.start', {}], ['tool.generating', { name: 'terminal' }],
-      ['tool.start', { tool_id: 'call-1', name: 'terminal', args: { command: 'pwd' } }],
-      ['tool.complete', { tool_id: 'call-1', name: 'terminal', result: { output: '/work', exit_code: 0 } }],
-      ['message.complete', { text: '/work', status: 'complete' }],
-    ] as Array<[string, any]>) {
-      current = applyChatEvent(current, { type, payload })
-    }
-    expect(current.messages.flatMap(message => message.toolCalls ?? [])).toHaveLength(1)
-    expect(buildMessageTimelineRows(chatMessagesToUi(current.messages)).filter(row => row.kind === 'trace').map(row => row.status)).toEqual(['success'])
-  })
-
-  it.each(['error', 'run.failed'])('settles every unfinished tool on %s without inventing success', type => {
-    let current = state()
-    for (const [event, payload] of [['message.start', {}], ['tool.start', { tool_id: 'call', name: 'terminal' }], ['message.interim', { text: '稍等' }], [type, { text: '结束' }]] as Array<[string, any]>)
-      current = applyChatEvent(current, { type: event, payload })
-    expect(current.messages.some(message => message.isStreaming)).toBe(false)
-    expect(current.messages.flatMap(message => message.toolCalls ?? []).map(tool => tool.status)).toEqual(['interrupted'])
-    expect(settleChatMessages(current.messages)).toEqual(current.messages)
-  })
-
-  it('keeps a successful terminal turn active until file output tools finish', () => {
-    let current = state()
-    for (const [event, payload] of [
-      ['message.start', {}],
-      ['tool.start', { tool_id: 'file', name: 'write_file' }],
-      ['message.complete', { text: '文件准备中', status: 'complete' }],
-      ['tool.generating', { tool_id: 'file', name: 'write_file' }],
-    ] as Array<[string, any]>) {
-      current = applyChatEvent(current, { type: event, payload })
-    }
-    expect(current.isStreaming).toBe(true)
-    expect(current.messages.flatMap(message => message.toolCalls ?? []).map(tool => tool.status)).toEqual(['running'])
-    expect(current.messages.some(message => message.isStreaming)).toBe(false)
-
-    current = applyChatEvent(current, { type: 'tool.completed', payload: { tool_id: 'file', name: 'write_file', result: { ok: true } } })
-    expect(current.isStreaming).toBe(false)
-    expect(current.messages.flatMap(message => message.toolCalls ?? []).map(tool => tool.status)).toEqual(['completed'])
-  })
-
-  it('reattaches a file tool that is first reported after the terminal message', () => {
-    let current = state()
-    current = applyChatEvent(current, { type: 'message.start', payload: {} })
-    current = applyChatEvent(current, { type: 'message.complete', payload: { text: '正在准备文件', status: 'complete' } })
-    expect(current.isStreaming).toBe(false)
-
-    current = applyChatEvent(current, { type: 'tool.started', payload: { tool_id: 'late-file', name: 'write_file' } })
-    expect(current.isStreaming).toBe(true)
-    expect(current.messages.at(-1)?.toolCalls?.map(tool => tool.status)).toEqual(['running'])
-
-    current = applyChatEvent(current, { type: 'tool.completed', payload: { tool_id: 'late-file', name: 'write_file', result: { ok: true } } })
-    expect(current.isStreaming).toBe(false)
-  })
-
-  it('recognizes persisted event status aliases and nonzero tool exit codes', () => {
-    const message = normalizeChatMessage({ id: '1', role: 'assistant', tool_calls: [
-      { id: 'empty', status: 'tool.complete' }, { id: 'failed', status: 'tool.complete', result: { exit_code: 1, error: null } },
-    ] }, 's')
-    expect(message.toolCalls?.map(tool => tool.status)).toEqual(['completed', 'failed'])
-    const rows = chatMessagesToUi([message, normalizeChatMessage({ id: '2', role: 'tool', tool_call_id: 'empty', content: '{"exit_code":1}' }, 's')])
-    expect(rows[0]!.tools?.every(tool => tool.status === 'error')).toBe(true)
-  })
-
-  it('replaces stale live projections by identified completed turns while retaining real repeated sends and active tail', () => {
-    const first = user('1'), second = user('2')
-    const stale: ChatMessage = { id: 'stream:p:s:1:x', sessionId: 's', role: 'assistant', content: '/work', timestamp: 2, stage: 'streaming', isStreaming: true }
-    const final = normalizeChatMessage({ id: '10', role: 'assistant', content: '/work', timestamp: 2 }, 's')
-    const active = { ...stale, id: 'stream:p:s:2:y', timestamp: 4 }
-    const result = reconcileChatHistory([first, stale, second, active], [first, final], true)
-    expect(result.map(message => message.id)).toEqual(['1', '2', '10', active.id])
-    expect(result.at(-1)?.isStreaming).toBe(true)
-  })
-
-  it('restores a canonical tool row whose text was overwritten by a live final answer', () => {
-    const call = normalizeChatMessage({ id: '1018', role: 'assistant', content: '', tool_calls: [{ id: 'call-2', function: { name: 'terminal' } }] }, 's')
-    const final = normalizeChatMessage({ id: '1020', role: 'assistant', content: '给你图片', timestamp: 3 }, 's')
-    const result = reconcileChatHistory([user('1'), { ...call, content: '给你图片' }], [user('1'), call, final], false)
-    expect(result.filter(message => message.content === '给你图片')).toHaveLength(1)
-    expect(result.find(message => message.id === '1018')?.content).toBe('')
-  })
-  it('keeps an active turn when a newer user message is queued after it', () => {
-    const live: ChatMessage = { id: 'stream:p:s:1:x', role: 'assistant', sessionId: 's', content: '当前输出', timestamp: 2, stage: 'streaming', isStreaming: true }
-    const interim = normalizeChatMessage({ id: '10', role: 'assistant', content: '之前的阶段性说明', timestamp: 1.5 }, 's')
-    expect(reconcileChatHistory([user('1'), live, { ...user('queue'), timestamp: 3 }], [user('1'), interim], true))
-      .toContainEqual(live)
-  })
-  it('counts a stable tool ID once when persisted history overlaps a live projection', () => {
-    const live = normalizeChatMessage({ id: 'stream:p:s:1:x', role: 'assistant', status: 'streaming', tool_calls: [{ id: 'call', name: 'terminal', result: 'done' }] }, 's')
-    const stored = normalizeChatMessage({ id: '10', role: 'assistant', tool_calls: [{ id: 'call', function: { name: 'terminal' } }] }, 's')
-    const tools = chatMessagesToUi([user('1'), live, stored]).flatMap(message => message.tools ?? [])
-    expect(tools).toHaveLength(1)
-    expect(tools[0]).toMatchObject({ id: 'call', status: 'success', output: 'done' })
-  })
-})

+ 0 - 266
tests/client/chatModelSync.test.ts

@@ -1,266 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { createPinia, setActivePinia } from 'pinia'
-import { routeKey } from '@/utils/id'
-
-const realtime = vi.hoisted(() => ({
-  eventHandler: undefined as ((event: unknown) => void) | undefined,
-  request: vi.fn(),
-}))
-const sessionsApi = vi.hoisted(() => ({
-  getSession: vi.fn(),
-  getMessages: vi.fn(),
-  getSessions: vi.fn(),
-  requestHistorySync: vi.fn(),
-}))
-
-vi.mock('@/api/realtime', () => {
-  class RpcError extends Error {}
-  class ChatRpcSocket {
-    onState(): void {}
-    onEvent(handler: (event: unknown) => void): void { realtime.eventHandler = handler }
-    async connect(): Promise<void> {}
-    close(): void {}
-    async request(...args: unknown[]): Promise<unknown> { return realtime.request(...args) }
-  }
-  return { ChatRpcSocket, RpcError }
-})
-
-vi.mock('@/api/sessions', () => ({
-  deleteSession: vi.fn(),
-  getMessages: sessionsApi.getMessages,
-  getSession: sessionsApi.getSession,
-  getSessions: sessionsApi.getSessions,
-  requestHistorySync: sessionsApi.requestHistorySync,
-  getSessionUnread: vi.fn(),
-  markSessionRead: vi.fn(),
-  updateSession: vi.fn(),
-}))
-vi.mock('@/api/profiles', () => ({ getModels: vi.fn() }))
-vi.mock('@/stores/auth', () => ({
-  useAuthStore: () => ({
-    user: { id: 'account-1' },
-    activeProfile: { name: 'alpha' },
-    status: 'authenticated',
-  }),
-}))
-
-import { useChatStore } from '@/stores/chat'
-
-describe('chat model realtime synchronization', () => {
-  beforeEach(() => {
-    realtime.eventHandler = undefined
-    realtime.request.mockReset().mockResolvedValue({})
-    sessionsApi.getMessages.mockReset()
-    sessionsApi.requestHistorySync.mockReset().mockResolvedValue(undefined)
-    sessionsApi.getSession.mockReset()
-    sessionsApi.getSessions.mockReset().mockResolvedValue({ items: [], nextCursor: null })
-    setActivePinia(createPinia())
-  })
-
-  it('keeps an unsent draft in its stable empty state without requesting history', async () => {
-    const chat = useChatStore()
-    const id = chat.createSession('alpha')
-    chat.clearSelection()
-
-    await chat.selectSession(id, 'alpha')
-
-    expect(sessionsApi.getMessages).not.toHaveBeenCalled()
-    expect(chat.activeRouteState?.historySynced).toBe(true)
-    expect(chat.activeRouteState?.isLoadingHistory).toBe(false)
-  })
-
-  it('applies another viewer model switch to the active selector and session summary', () => {
-    const chat = useChatStore()
-    const oldModel = { id: 'model-a', name: 'Model A', provider: 'provider-a' }
-    const newModel = { id: 'model-b', name: 'Model B', provider: 'provider-b' }
-    chat.models = [oldModel, newModel]
-    chat.sessions = [{
-      id: 'session-1', profile: 'alpha', source: 'web', title: '会话',
-      model: oldModel.id, provider: oldModel.provider, messageCount: 0,
-      toolCallCount: 0, startedAt: 1, updatedAt: 1,
-    }]
-    chat.activeSessionId = 'session-1'
-    chat.activeProfileName = 'alpha'
-    chat.routes[routeKey('alpha', 'session-1')] = {
-      route: { profile: 'alpha', sessionId: 'session-1' },
-      runtimeSessionId: 'runtime-1', messages: [], historySynced: true,
-      hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0,
-      isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-    }
-    chat.selectedModel = oldModel
-
-    realtime.eventHandler?.({
-      type: 'session.info', session_id: 'runtime-1',
-      payload: { info: { model: newModel.id, provider: newModel.provider } },
-    })
-
-    expect(chat.selectedModel).toEqual(newModel)
-    expect(chat.sessions[0]).toMatchObject({ model: newModel.id, provider: newModel.provider })
-  })
-
-  it('reconciles the active model through REST when another client owns realtime events', async () => {
-    const chat = useChatStore()
-    const oldModel = { id: 'model-a', name: 'Model A', provider: 'provider-a' }
-    const newModel = { id: 'model-b', name: 'Model B', provider: 'provider-b' }
-    chat.models = [oldModel, newModel]
-    chat.sessions = [{
-      id: 'session-1', profile: 'alpha', source: 'web', title: '会话',
-      model: oldModel.id, provider: oldModel.provider, messageCount: 0,
-      toolCallCount: 0, startedAt: 1, updatedAt: 1,
-    }]
-    chat.activeSessionId = 'session-1'
-    chat.activeProfileName = 'alpha'
-    chat.routes[routeKey('alpha', 'session-1')] = {
-      route: { profile: 'alpha', sessionId: 'session-1' }, messages: [], historySynced: true,
-      hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0,
-      isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-    }
-    chat.selectedModel = oldModel
-    sessionsApi.getSession.mockResolvedValue({
-      ...chat.sessions[0], model: newModel.id, provider: newModel.provider,
-    })
-
-    await chat.refreshActiveSessionModel()
-
-    expect(sessionsApi.getSession).toHaveBeenCalledWith('session-1', 'alpha')
-    expect(chat.selectedModel).toEqual(newModel)
-  })
-
-  it('releases the local model guard after a failed switch', async () => {
-    const chat = useChatStore()
-    const oldModel = { id: 'model-a', name: 'Model A', provider: 'provider-a' }
-    const newModel = { id: 'model-b', name: 'Model B', provider: 'provider-b' }
-    chat.models = [oldModel, newModel]
-    chat.sessions = [{
-      id: 'session-1', profile: 'alpha', source: 'web', title: '会话',
-      model: oldModel.id, provider: oldModel.provider, messageCount: 0,
-      toolCallCount: 0, startedAt: 1, updatedAt: 1,
-    }]
-    chat.activeSessionId = 'session-1'
-    chat.activeProfileName = 'alpha'
-    chat.routes[routeKey('alpha', 'session-1')] = {
-      route: { profile: 'alpha', sessionId: 'session-1' }, runtimeSessionId: 'runtime-1',
-      messages: [], historySynced: true, hasMoreBefore: false, loadedMessageCount: 0,
-      messageTotal: 0, isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-    }
-    chat.selectedModel = oldModel
-    realtime.request.mockRejectedValueOnce(new Error('switch failed'))
-
-    await expect(chat.setModel(newModel)).rejects.toThrow('switch failed')
-    expect(chat.selectedModel).toEqual(oldModel)
-
-    realtime.eventHandler?.({
-      type: 'session.info', session_id: 'runtime-1',
-      payload: { model: newModel.id, provider: newModel.provider },
-    })
-    expect(chat.selectedModel).toEqual(newModel)
-  })
-
-  it('does not resume an old session merely to show its context usage', async () => {
-    const chat = useChatStore()
-    chat.sessions = [{
-      id: 'session-1', profile: 'alpha', source: 'web', title: '旧会话',
-      messageCount: 1, toolCallCount: 0, startedAt: 1, updatedAt: 1,
-    }]
-    chat.routes[routeKey('alpha', 'session-1')] = {
-      route: { profile: 'alpha', sessionId: 'session-1' }, messages: [], historySynced: true,
-      hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0,
-      isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-    }
-
-    await chat.selectSession('session-1', 'alpha')
-    await Promise.resolve()
-
-    expect(realtime.request).not.toHaveBeenCalled()
-  })
-
-  it('debounces global session changes and reloads the visible server projection', async () => {
-    vi.useFakeTimers()
-    try {
-      const chat = useChatStore()
-      sessionsApi.getSessions.mockResolvedValue({
-        items: [{
-          id: 'ios-session', profile: 'alpha', source: 'web', title: 'iOS 新会话',
-          messageCount: 2, toolCallCount: 0, startedAt: 2, updatedAt: 2,
-        }],
-        nextCursor: null,
-      })
-
-      realtime.eventHandler?.({ type: 'sessions.changed', payload: {} })
-      realtime.eventHandler?.({ type: 'sessions.changed', payload: {} })
-      realtime.eventHandler?.({ type: 'sessions.changed', payload: {} })
-
-      expect(sessionsApi.getSessions).not.toHaveBeenCalled()
-      await vi.advanceTimersByTimeAsync(200)
-
-      expect(sessionsApi.getSessions).toHaveBeenCalledTimes(1)
-      expect(sessionsApi.getSessions).toHaveBeenCalledWith('alpha', undefined, 100, 'chat')
-      expect(chat.sessions).toEqual([
-        expect.objectContaining({ id: 'ios-session', title: 'iOS 新会话' }),
-      ])
-    } finally {
-      vi.useRealTimers()
-    }
-  })
-
-  it.each(['session.title', 'session.title.updated'])(
-    'applies %s immediately and schedules one authoritative list refresh',
-    async eventType => {
-      vi.useFakeTimers()
-      try {
-        const chat = useChatStore()
-        chat.sessions = [{
-          id: 'session-1', profile: 'alpha', source: 'web', title: '新会话',
-          messageCount: 2, toolCallCount: 0, startedAt: 1, updatedAt: 1,
-        }]
-        chat.routes[routeKey('alpha', 'session-1')] = {
-          route: { profile: 'alpha', sessionId: 'session-1' }, runtimeSessionId: 'runtime-1',
-          messages: [], historySynced: true, hasMoreBefore: false, loadedMessageCount: 0,
-          messageTotal: 0, isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-        }
-        sessionsApi.getSessions.mockResolvedValue({
-          items: [{ ...chat.sessions[0], title: '服务端自动标题' }],
-          nextCursor: null,
-        })
-
-        realtime.eventHandler?.({
-          type: eventType,
-          session_id: 'runtime-1',
-          payload: { session_id: 'session-1', title: '服务端自动标题' },
-        })
-
-        expect(chat.sessions[0].title).toBe('服务端自动标题')
-        expect(sessionsApi.getSessions).not.toHaveBeenCalled()
-        await vi.advanceTimersByTimeAsync(200)
-        expect(sessionsApi.getSessions).toHaveBeenCalledTimes(1)
-      } finally {
-        vi.useRealTimers()
-      }
-    },
-  )
-  it('uses a synchronized route without history reads and forces refresh only on request', async () => {
-    const chat = useChatStore()
-    const key = routeKey('alpha', 'session-1')
-    chat.activeSessionId = 'session-1'
-    chat.activeProfileName = 'alpha'
-    chat.routes[key] = {
-      route: { profile: 'alpha', sessionId: 'session-1' },
-      messages: [
-        { id: 'old', sessionId: 'session-1', role: 'assistant', content: 'old history', timestamp: 1, stage: 'settled' },
-        { id: 'unsent', sessionId: 'session-1', role: 'user', content: 'keep failed send', timestamp: 2, stage: 'failed' },
-      ], historySynced: true, hasMoreBefore: false, loadedMessageCount: 1, messageTotal: 1,
-      isLoadingHistory: false, isStreaming: false, isQueued: false, generation: 1,
-    }
-    for (let i = 0; i < 5; i++) await chat.selectSession('session-1', 'alpha')
-    expect(sessionsApi.getMessages).not.toHaveBeenCalled()
-    sessionsApi.getMessages.mockResolvedValue({ messages: [
-      { id: 'new', sessionId: 'session-1', role: 'assistant', content: 'authoritative', timestamp: 1, stage: 'settled' },
-    ], returned: 1, total: 1, hasMore: false })
-    await chat.forceRefreshHistory()
-    expect(sessionsApi.requestHistorySync).toHaveBeenCalledWith('session-1','alpha')
-    expect(sessionsApi.getMessages).not.toHaveBeenCalled()
-    expect(chat.messages.map(message => message.id)).toEqual(['old', 'unsent'])
-    expect(chat.routes[key].error).toContain('后台补齐')
-  })
-
-})

+ 0 - 66
tests/client/chatProtocol.test.ts

@@ -1,66 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { ChatRpcSocket, GroupEventSocket } from '@/api/realtime'
-import { setApiCsrfToken } from '@/api/client'
-
-beforeEach(() => { setApiCsrfToken('csrf-test'); vi.stubGlobal('WebSocket', vi.fn()) })
-afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
-
-function httpFixture() {
-  let kind = 'chat', epoch = '', cursor = 0
-  let stream: ReadableStreamDefaultController<Uint8Array> | undefined
-  const send = (frame: object) => stream!.enqueue(new TextEncoder().encode('event: frame\ndata: ' + JSON.stringify(frame) + '\n\n'))
-  const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
-    const path = String(input)
-    if (path.endsWith('/capabilities')) return Response.json({ protocolVersion: 1, csrfToken: 'csrf-test', features:['ordinary-chat-transcript-v2'] })
-    if (init?.method === 'DELETE') return new Response(null, { status: 204 })
-    if (path.endsWith('/channels')) {
-      const body = JSON.parse(String(init?.body)); kind = body.channel; epoch = body.epoch; cursor = body.cursor
-      return Response.json({ id: 'channel-1' }, { status: 201 })
-    }
-    if (path.endsWith('/events')) {
-      const body = new ReadableStream<Uint8Array>({ start(controller) {
-        stream = controller
-        send(kind === 'chat'
-          ? { method: 'event', params: { type: 'gateway.ready', payload: {} } }
-          : { type: 'group.ready', epoch, cursor, heartbeatSeconds: 20 })
-        init?.signal?.addEventListener('abort', () => { try { controller.close() } catch {} }, { once: true })
-      } })
-      return new Response(body, { headers: { 'content-type': 'text/event-stream' } })
-    }
-    return Response.json({ state: 'confirmed', response: { result: { total_tokens: 42 } } })
-  })
-  vi.stubGlobal('fetch', fetchMock)
-  return { fetchMock, send }
-}
-
-describe('HTTP-only realtime protocols', () => {
-  it('waits for SSE ready and submits commands through HTTP without opening a WS', async () => {
-    const f = httpFixture(), socket = new ChatRpcSocket(), events: string[] = []
-    socket.onEvent(event => events.push(event.type))
-    await socket.connect()
-    expect(socket.state).toBe('ready')
-    const result = await socket.request('session.usage', { session_id: 'runtime-1' }, 5000, 'stable-command')
-    expect(result).toEqual({ total_tokens: 42 })
-    const sent = f.fetchMock.mock.calls.find(([path]) => String(path).endsWith('/commands'))![1]!
-    expect(new Headers(sent.headers).get('Idempotency-Key')).toBe('stable-command')
-    expect(JSON.parse(String(sent.body))).toMatchObject({ method: 'session.usage', params: { session_id: 'runtime-1' } })
-    expect(events).toEqual(['gateway.ready'])
-    expect(WebSocket).not.toHaveBeenCalled()
-    socket.close()
-  })
-  it('preserves the group epoch/cursor on the HTTP channel', async () => {
-    const f = httpFixture(), socket = new GroupEventSocket()
-    await socket.connect({ epoch: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', cursor: 12, onEnvelope: () => {}, onReset: () => {} })
-    const sent = f.fetchMock.mock.calls.find(([path]) => String(path).endsWith('/channels'))![1]!
-    expect(JSON.parse(String(sent.body))).toEqual({ channel: 'groups', epoch: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', cursor: 12 })
-    expect(WebSocket).not.toHaveBeenCalled()
-    socket.close()
-  })
-  it.each([401, 404, 405, 410])('does not downgrade after HTTP %s', async status => {
-    vi.stubGlobal('fetch', vi.fn(async () => Response.json({ error: 'unsupported or unauthorized' }, { status })))
-    const socket = new ChatRpcSocket()
-    await expect(socket.connect()).rejects.toThrow()
-    expect(WebSocket).not.toHaveBeenCalled()
-    socket.close()
-  })
-})

+ 0 - 213
tests/client/chatStore.test.ts

@@ -1,213 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { ChatMessage, ChatRouteState, RpcEventFrame } from '@shared/types'
-import { applyChatEvent, mergeChatMessages } from '@/utils/messageReducer'
-
-function message(id: string, content = '相同内容', clientMessageId?: string): ChatMessage {
-  return {
-    id, sessionId: 'session-1', profile: 'yaoyao', role: 'user', content,
-    clientMessageId, timestamp: 1, stage: 'settled',
-  }
-}
-
-function state(): ChatRouteState {
-  return {
-    route: { profile: 'yaoyao', sessionId: 'session-1' }, messages: [], historySynced: true,
-    hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0, isLoadingHistory: false,
-    isStreaming: false, isQueued: false, generation: 1,
-  }
-}
-
-function event(type: string, payload: Record<string, unknown>, sessionId = 'session-1'): RpcEventFrame['params'] {
-  return { type, session_id: sessionId, profile: 'yaoyao', payload: payload as never }
-}
-
-describe('chat message reducer', () => {
-  it('preserves repeated user text when server identities differ', () => {
-    const merged = mergeChatMessages([message('one')], [message('two')])
-    expect(merged).toHaveLength(2)
-    expect(merged.map(item => item.content)).toEqual(['相同内容', '相同内容'])
-  })
-
-  it('reconciles an optimistic row only by client message identity', () => {
-    const optimistic = { ...message('local', 'hello', 'client-1'), stage: 'pending' as const }
-    const persisted = { ...message('server-1', 'hello', 'client-1'), serverMessageId: 'server-1' }
-    const merged = mergeChatMessages([optimistic], [persisted])
-    expect(merged).toHaveLength(1)
-    expect(merged[0].id).toBe('server-1')
-    expect(merged[0].stage).toBe('settled')
-  })
-
-  it.each(['append', 'snapshot', 'prepend'] as const)('repairs both cached echoes when history restores identity (%s)', position => {
-    const local = { ...message('local', '查看服务器情况', 'client-1'), stage: 'accepted' as const }
-    const oldHistory = { ...message('1155', '查看服务器情况'), serverMessageId: '1155', timestamp: 2 }
-    const history = { ...oldHistory, clientMessageId: 'client-1' }
-    const merged = mergeChatMessages([local, oldHistory], [history], position)
-    expect(merged).toHaveLength(1)
-    expect(merged[0]).toMatchObject({ id: '1155', clientMessageId: 'client-1', stage: 'settled', timestamp: 2 })
-  })
-
-  it('keeps persisted identity and delivery state when a peer receipt arrives after history', () => {
-    const current = state()
-    current.messages = [{ ...message('1155', '查看服务器情况', 'client-1'), serverMessageId: '1155' }]
-    const updated = applyChatEvent(current, event('run.peer_user_message', {
-      message_id: 'user:web:prompt:client-1', client_message_id: 'client-1', text: '查看服务器情况', status: 'accepted',
-    }))
-    expect(updated.messages).toHaveLength(1)
-    expect(updated.messages[0]).toMatchObject({ id: '1155', serverMessageId: '1155', stage: 'settled' })
-  })
-
-  it('retains two separate identical submissions while reconciling both echoes', () => {
-    const local = ['first', 'second'].map(id => ({ ...message(id, '查看服务器情况', id), stage: 'accepted' as const }))
-    const history = local.map((row, index) => ({ ...row, id: String(index + 1), serverMessageId: String(index + 1), stage: 'settled' as const }))
-    expect(mergeChatMessages(local, history, 'snapshot').map(row => [row.id, row.clientMessageId, row.stage]))
-      .toEqual([['1', 'first', 'settled'], ['2', 'second', 'settled']])
-  })
-
-  it('keeps history and a realtime assistant reply in chronological order', () => {
-    const optimistic = { ...message('local-user', '新问题', 'client-1'), timestamp: 30, stage: 'pending' as const }
-    const older = { ...message('history-user', '旧问题'), timestamp: 10, sequence: 10 }
-    const newer = {
-      ...message('history-answer', '旧回答'), role: 'assistant' as const, timestamp: 20, sequence: 11,
-    }
-    const streamed = {
-      ...message('stream-answer', '新回答'), role: 'assistant' as const, timestamp: 31, stage: 'streaming' as const, isStreaming: true,
-    }
-
-    const merged = mergeChatMessages([optimistic], [newer, older], 'snapshot')
-    expect(mergeChatMessages(merged, [streamed]).map(item => item.id)).toEqual([
-      'history-user', 'history-answer', 'local-user', 'stream-answer',
-    ])
-  })
-
-  it('replaces a cached iOS marker with an attachment-only normalized message', () => {
-    const cached = message('ios-file', '[用户附加文件:车位.pdf]\n@file:`attachments/车位.pdf`')
-    const normalized = {
-      ...message('ios-file', ''),
-      attachments: [{ id: 'ios-file:0', name: '车位.pdf', mimeType: 'application/pdf', size: 0, kind: 'pdf' as const, url: '/attachments/车位.pdf' }],
-    }
-    const merged = mergeChatMessages([cached], [normalized])
-    expect(merged[0]).toMatchObject({ content: '', attachments: [expect.objectContaining({ name: '车位.pdf' })] })
-  })
-
-  it('ignores events attributed to another route', () => {
-    const original = state()
-    const reduced = applyChatEvent(original, event('message.delta', { delta: 'wrong' }, 'session-2'))
-    expect(reduced).toBe(original)
-    expect(reduced.messages).toEqual([])
-  })
-
-  it('uses terminal authoritative output to repair missed deltas', () => {
-    let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
-    current = applyChatEvent(current, event('message.delta', { message_id: 'assistant-1', delta: '少量' }))
-    current = applyChatEvent(current, event('message.complete', {
-      message_id: 'assistant-1', text: '完整最终回答', authoritative_output: true,
-      usage: { input: 10, output: 20, total: 30 },
-    }))
-    expect(current.messages).toHaveLength(1)
-    expect(current.messages[0].content).toBe('完整最终回答')
-    expect(current.messages[0].stage).toBe('settled')
-    expect(current.usage?.totalTokens).toBe(30)
-  })
-
-  it('starts a new assistant row after a user prompt when an interrupted row is still marked streaming', () => {
-    const interrupted = {
-      ...message('assistant-old', '上一轮残留'), role: 'assistant' as const, timestamp: 20,
-      stage: 'streaming' as const, isStreaming: true,
-    }
-    const prompt = { ...message('user-new', '再试试'), timestamp: 30, stage: 'accepted' as const }
-    const initial = { ...state(), messages: [interrupted, prompt] }
-
-    let current = applyChatEvent(initial, event('run.started', {}))
-    current = applyChatEvent(current, event('message.delta', { delta: '新一轮回答' }))
-
-    expect(current.messages).toHaveLength(3)
-    expect(current.messages.map(item => item.content)).toEqual(['上一轮残留', '再试试', '新一轮回答'])
-    expect(current.messages[0]).toMatchObject({ id: 'assistant-old', isStreaming: false })
-    expect(current.messages[2]).toMatchObject({ role: 'assistant', isStreaming: true })
-  })
-
-  it('promotes a synthetic streaming row to a server message id without duplicating it', () => {
-    const initial = { ...state(), messages: [{ ...message('user-new', '开始'), timestamp: 30 }] }
-    let current = applyChatEvent(initial, event('run.started', {}))
-    current = applyChatEvent(current, event('message.delta', { message_id: 'assistant-new', delta: '回答' }))
-
-    expect(current.messages).toHaveLength(2)
-    expect(current.messages[1]).toMatchObject({ id: 'assistant-new', content: '回答', isStreaming: true })
-  })
-
-  it('seals interim commentary so later streamed text stays at the bottom of the turn', () => {
-    const initial = { ...state(), messages: [{ ...message('user-new', '检查项目'), timestamp: 100 }] }
-    let current = applyChatEvent(initial, event('message.start', {}))
-    current = applyChatEvent(current, event('message.delta', { text: '我先读取配置。', timestamp: 101 }))
-    current = applyChatEvent(current, event('message.interim', { text: '我先读取配置。', timestamp: 102 }))
-    current = applyChatEvent(current, event('tool.start', { tool_id: 'tool-1', name: 'read_file' }))
-    current = applyChatEvent(current, event('tool.complete', { tool_id: 'tool-1', name: 'read_file', result: 'ok' }))
-    current = applyChatEvent(current, event('message.delta', { text: '配置没有问题。', timestamp: 105 }))
-
-    expect(current.messages.map(item => item.content)).toEqual(['检查项目', '我先读取配置。', '配置没有问题。'])
-    expect(current.messages[1]).toMatchObject({ role: 'assistant', isStreaming: false })
-    expect(current.messages[2]).toMatchObject({ role: 'assistant', isStreaming: true })
-    expect(current.messages[2].toolCalls).toEqual([
-      expect.objectContaining({ id: 'tool-1', status: 'completed' }),
-    ])
-  })
-
-  it('preserves interim commentary after the final answer completes', () => {
-    const initial = { ...state(), messages: [{ ...message('user-new', '执行'), timestamp: 100 }] }
-    let current = applyChatEvent(initial, event('message.start', {}))
-    current = applyChatEvent(current, event('message.delta', { text: '开始执行。' }))
-    current = applyChatEvent(current, event('message.interim', { text: '开始执行。' }))
-    current = applyChatEvent(current, event('message.delta', { text: '执行完成。' }))
-    current = applyChatEvent(current, event('message.complete', { text: '执行完成。' }))
-
-    expect(current.messages.map(item => item.content)).toEqual(['执行', '开始执行。', '执行完成。'])
-    expect(current.messages.slice(1).every(item => item.isStreaming === false)).toBe(true)
-  })
-
-  it('settles an identical completion onto the sealed interim instead of duplicating it', () => {
-    const initial = { ...state(), messages: [{ ...message('user-new', '执行'), timestamp: 100 }] }
-    let current = applyChatEvent(initial, event('message.start', {}))
-    current = applyChatEvent(current, event('message.delta', { text: '已经完成。' }))
-    current = applyChatEvent(current, event('message.interim', { text: '已经完成。', already_streamed: true }))
-    current = applyChatEvent(current, event('message.complete', { text: '已经完成。' }))
-
-    expect(current.messages.map(item => item.content)).toEqual(['执行', '已经完成。'])
-    expect(current.messages[1]).toMatchObject({ stage: 'settled', isStreaming: false })
-  })
-
-  it('treats message.complete status=error as a failed terminal row', () => {
-    let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
-    current = applyChatEvent(current, event('message.complete', {
-      message_id: 'assistant-1', status: 'error', text: '工具执行失败', error: 'permission denied',
-    }))
-    expect(current.messages[0]).toMatchObject({ stage: 'failed', isStreaming: false })
-    expect(current.error).toContain('permission denied')
-  })
-
-  it('maps the current 9119 context usage field names', () => {
-    const current = applyChatEvent(state(), event('session.usage', {
-      input: 10, output: 20, total: 30, context_used: 12_500, context_max: 114_688, context_percent: 10.9,
-    }))
-    expect(current.usage).toMatchObject({ contextTokens: 12_500, contextLimit: 114_688, percentUsed: 10.9 })
-  })
-
-  it('retains the context gauge when completion only updates cumulative counters', () => {
-    let current = applyChatEvent(state(), event('session.usage', { context_used: 12_500, context_max: 114_688 }))
-    current = applyChatEvent(current, event('message.complete', { text: '完成', usage: { total_tokens: 1_900_000 } }))
-    expect(current.usage).toMatchObject({ contextTokens: 12_500, contextLimit: 114_688, totalTokens: 1_900_000 })
-    current = applyChatEvent(current, event('usage.update', { input_tokens: 10 }))
-    expect(current.usage).toMatchObject({ contextTokens: 12_500, contextLimit: 114_688, inputTokens: 10 })
-    current = applyChatEvent(current, event('context.update', { context_used: 0, context_percent: 0 }))
-    expect(current.usage).toMatchObject({ contextTokens: 0, percentUsed: 0 })
-  })
-
-  it('tracks approval and clarification independently', () => {
-    let current = applyChatEvent(state(), event('approval.request', { request_id: 'approval-1', message: '允许吗?' }))
-    current = applyChatEvent(current, event('clarify.request', { request_id: 'clarify-1', question: '选哪个?' }))
-    expect(current.pendingApproval?.id).toBe('approval-1')
-    expect(current.pendingClarification?.id).toBe('clarify-1')
-    current = applyChatEvent(current, event('approval.resolved', {}))
-    expect(current.pendingApproval).toBeUndefined()
-    expect(current.pendingClarification?.id).toBe('clarify-1')
-  })
-})

+ 0 - 38
tests/client/contextUsage.test.ts

@@ -1,38 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { normalizeChatUsage } from '@/utils/contextUsage'
-
-describe('context usage shared by web and desktop', () => {
-  it('never treats cumulative billing or an output limit as context occupancy', () => {
-    const usage = normalizeChatUsage({ input_tokens: 1_800_000, output_tokens: 100_000,
-      total_tokens: 1_900_000, max_tokens: 262_144, used: 1_900_000, limit: 262_144 })
-    expect(usage).toMatchObject({ inputTokens: 1_800_000, outputTokens: 100_000, totalTokens: 1_900_000 })
-    expect(usage?.contextTokens).toBeUndefined()
-    expect(usage?.contextLimit).toBeUndefined()
-  })
-
-  it('uses the same last-prompt source order and server percentage as mobile', () => {
-    const usage = normalizeChatUsage({ usage: { context_used: 2000, context_max: 8000, context_percent: 45.5 } },
-      { context_used: 3000, context_max: 16000 })
-    expect(usage).toMatchObject({ contextTokens: 2000, contextLimit: 8000, percentUsed: 45.5 })
-  })
-
-  it('fills missing gauges from context breakdown without using cumulative totals', () => {
-    expect(normalizeChatUsage({ total: 1_900_000 }, { context_used: 12_500, context_max: 114_688 }))
-      .toMatchObject({ totalTokens: 1_900_000, contextTokens: 12_500, contextLimit: 114_688 })
-  })
-
-  it('recognizes nested session metadata and camel-case context fields', () => {
-    expect(normalizeChatUsage({ info: { usage: { contextUsed: 2000, contextMax: 8000, contextPercent: 0 } } }))
-      .toMatchObject({ contextTokens: 2000, contextLimit: 8000, percentUsed: 0 })
-    expect(normalizeChatUsage({ contextTokens: 2000, contextLimit: 8000 }))
-      .toMatchObject({ contextTokens: 2000, contextLimit: 8000 })
-  })
-
-  it('preserves an explicit reset to zero and ignores missing or invalid measurements', () => {
-    expect(normalizeChatUsage({ context_used: 0, context_percent: 0, total: 1_900_000 }))
-      .toMatchObject({ contextTokens: 0, percentUsed: 0 })
-    expect(normalizeChatUsage({ text: '完成', context_used: -1, context_max: 0, context_percent: Number.NaN }))
-      .toBeUndefined()
-    expect(normalizeChatUsage(undefined, {})).toBeUndefined()
-  })
-})

+ 2 - 2
tests/client/csrfRecovery.test.ts

@@ -49,7 +49,7 @@ describe('long-lived desktop CSRF recovery', () => {
     expect(new Headers(mutations[1]![1]?.headers).get('X-CSRF-Token')).not.toBe(old)
   })
 
-  it('shares one refresh across concurrent ordinary-chat and Bot requests', async () => {
+  it('shares one refresh across concurrent Bot and account requests', async () => {
     setApiCsrfToken('expired', 'account-a')
     let release!: (value: Response) => void
     const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
@@ -57,7 +57,7 @@ describe('long-lived desktop CSRF recovery', () => {
       return new Headers(init?.headers).get('X-CSRF-Token') === 'renewed' ? response({ ok: true }) : invalid()
     })
     vi.stubGlobal('fetch', fetchMock)
-    const paths = ['/api/realtime/channels/chat/commands', '/api/app/conversations/bot/messages', '/api/app/account/avatar']
+    const paths = ['/api/app/conversations/group/messages', '/api/app/conversations/bot/messages', '/api/app/account/avatar']
     const jobs = paths.map(path => apiRequest(path, { method: 'POST', body: { requestId: path } }))
     await vi.waitFor(() => expect(fetchMock.mock.calls.filter(([path]) => path === refreshPath)).toHaveLength(1))
     release(response({ csrfToken: 'renewed', userId: 'account-a' }))

+ 0 - 25
tests/client/filesProtocol.test.ts

@@ -1,25 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { getFiles } from '@/api/files'
-
-afterEach(() => vi.unstubAllGlobals())
-
-describe('file library profile routing', () => {
-  it('uses the response/request profile when plugin origins omit it', async () => {
-    vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
-      profile: 'yaoer',
-      items: [{
-        id: 7,
-        name: 'result.pdf',
-        path: '/tmp/result.pdf',
-        mimeType: 'application/pdf',
-        size: 10,
-        origins: [{ profile: '', sessionId: 'session-1', messageId: 'message-1' }],
-      }],
-      nextCursor: null,
-    }), { status: 200, headers: { 'content-type': 'application/json' } })))
-    const page = await getFiles({ profile: 'yaoer' })
-    expect(page.items[0].origins[0].profile).toBe('yaoer')
-    expect(page.items[0].previewUrl).toContain('profile=yaoer')
-    expect(page.items[0].downloadUrl).toContain('profile=yaoer')
-  })
-})

+ 0 - 39
tests/client/httpRealtimeRecovery.test.ts

@@ -1,39 +0,0 @@
-import { afterEach, expect, it, vi } from 'vitest'
-import { HTTPRealtimeChannel } from '@/api/httpRealtime'
-const api = vi.hoisted(() => ({ request: vi.fn() }))
-vi.mock('@/api/client', async importOriginal => ({ ...await importOriginal<typeof import('@/api/client')>(), apiRequest: api.request }))
-afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); api.request.mockReset() })
-
-it('times out response headers on every reconnect and preserves the received cursor', async () => {
-  vi.useFakeTimers()
-  api.request.mockResolvedValue({ id: 'channel' })
-  let firstStream!: ReadableStreamDefaultController<Uint8Array>
-  const attempts: RequestInit[] = []
-  vi.stubGlobal('fetch', vi.fn((_url: unknown, options: RequestInit) => {
-    attempts.push(options)
-    if (attempts.length > 1) return new Promise((_resolve, reject) => {
-      options.signal?.addEventListener('abort', () => reject(new Error('headers timed out')), { once: true })
-    })
-    return Promise.resolve(new Response(new ReadableStream<Uint8Array>({ start(controller) {
-      firstStream = controller
-      controller.enqueue(new TextEncoder().encode('id: epoch:9\nevent: frame\ndata: {"params":{"type":"gateway.ready"}}\n\n'))
-    } }), { headers: { 'content-type': 'text/event-stream' } }))
-  }))
-  const failed = vi.fn(), channel = new HTTPRealtimeChannel(async () => {}, failed)
-  try {
-    await channel.open('chat')
-    firstStream.error(new Error('connection lost'))
-    await vi.advanceTimersByTimeAsync(500)
-    expect(attempts).toHaveLength(2)
-    await vi.advanceTimersByTimeAsync(45_000)
-    expect(attempts[1].signal?.aborted).toBe(true)
-    await vi.advanceTimersByTimeAsync(1000)
-    expect(attempts).toHaveLength(3)
-    expect(attempts[2].headers).toMatchObject({ 'Last-Event-ID': 'epoch:9' })
-    expect(failed).not.toHaveBeenCalled()
-  } finally {
-    channel.close()
-    await vi.advanceTimersByTimeAsync(60_000)
-    expect(attempts).toHaveLength(3)
-  }
-})

+ 0 - 25
tests/client/interfaceMode.test.ts

@@ -1,25 +0,0 @@
-import { beforeEach, describe, expect, it } from 'vitest'
-import { rememberInterfacePath, savedInterfacePath } from '@/utils/interfaceMode'
-
-beforeEach(() => localStorage.clear())
-
-describe('last interface mode', () => {
-  it('opens application-owned chats by default and remembers an explicit history choice', () => {
-    expect(savedInterfacePath()).toBe('/conversations')
-    rememberInterfacePath('/conversations/existing-group')
-    expect(savedInterfacePath()).toBe('/conversations')
-    rememberInterfacePath('/files')
-    expect(savedInterfacePath()).toBe('/conversations')
-    rememberInterfacePath('/history/existing-session')
-    expect(savedInterfacePath()).toBe('/conversations')
-    rememberInterfacePath('/chat/existing-session')
-    expect(savedInterfacePath()).toBe('/chat')
-  })
-
-  it('does not mistake unrelated paths or invalid storage for a mode', () => {
-    localStorage.setItem('hermes-yaoyao:interface-mode', 'invalid')
-    expect(savedInterfacePath()).toBe('/conversations')
-    rememberInterfacePath('/conversations-other')
-    expect(savedInterfacePath()).toBe('/conversations')
-  })
-})

+ 1 - 2
tests/client/messageFailure.test.ts

@@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest'
 import { mount } from '@vue/test-utils'
 import { collapseDuplicateFailures, messageFailure } from '@/utils/messageFailure'
 import MessageFailureNotice from '@/components/messages/MessageFailureNotice.vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 import WorkspaceMessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
 import { workspaceMessagesToUi } from '@/components/workspace/viewModels'
 import type { UiMessage } from '@/components/messages/types'
@@ -43,7 +42,7 @@ describe('conversation failure presentation', () => {
     wrapper.unmount()
   })
 
-  it.each([MessageTimeline, WorkspaceMessageTimeline])('uses the same disclosure and keeps partial content in each timeline', async component => {
+  it.each([WorkspaceMessageTimeline])('uses the same disclosure and keeps partial content in each timeline', async component => {
     vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} })
     Element.prototype.scrollTo = vi.fn()
     const wrapper = mount(component, { props: { messages: [failed, duplicate], identity: 'test' }, global: { stubs: { AgentAvatar: true, MarkdownContent: { props: ['content'], template: '<p class="answer">{{ content }}</p>' } } } })

+ 0 - 41
tests/client/modelChoiceDialog.test.ts

@@ -1,41 +0,0 @@
-import { mount } from '@vue/test-utils'
-import { afterEach, describe, expect, it } from 'vitest'
-import { nextTick } from 'vue'
-import ModelChoiceDialog from '@/components/composer/ModelChoiceDialog.vue'
-
-const options = [
-  { id: 'gpt-5.6-terra', name: 'gpt-5.6-terra', provider: 'openai', supportsReasoning: true, isDefault: true },
-  { id: 'gpt-5.5', name: 'GPT 5.5', provider: 'openai' },
-  { id: 'claude-sonnet', name: 'Claude Sonnet', provider: 'anthropic' },
-]
-
-afterEach(() => { document.body.innerHTML = '' })
-
-describe('ModelChoiceDialog', () => {
-  it('groups and filters models while preserving the selected state', async () => {
-    const wrapper = mount(ModelChoiceDialog, { attachTo: document.body, props: { open: true, options, selectedId: 'openai:gpt-5.6-terra' } })
-    await nextTick()
-    const dialog = document.querySelector('[role="dialog"][aria-labelledby="model-dialog-title"]')
-    expect(dialog?.textContent).toContain('OpenAI')
-    expect(dialog?.textContent).toContain('Anthropic')
-    expect(dialog?.querySelector('.model-dialog__item--active')?.textContent).toContain('gpt-5.6-terra')
-
-    const input = document.querySelector<HTMLInputElement>('input[placeholder="搜索模型名称或 ID"]')!
-    input.value = 'claude'
-    input.dispatchEvent(new Event('input'))
-    await nextTick()
-    expect(dialog?.textContent).toContain('Claude Sonnet')
-    expect(dialog?.textContent).not.toContain('gpt-5.5')
-
-    document.querySelector<HTMLButtonElement>('.model-dialog__item')!.click()
-    expect(wrapper.emitted('select')?.[0]).toEqual(['anthropic:claude-sonnet'])
-    wrapper.unmount()
-  })
-
-  it('closes with Escape when no model switch is running', () => {
-    const wrapper = mount(ModelChoiceDialog, { attachTo: document.body, props: { open: true, options } })
-    window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
-    expect(wrapper.emitted('close')).toHaveLength(1)
-    wrapper.unmount()
-  })
-})

+ 1 - 106
tests/client/nodePairingPanel.test.ts

@@ -3,14 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
 import QRCode from 'qrcode'
 import NodePairingPanel from '@/components/app/NodePairingPanel.vue'
 import { accountPairingStatus, createAccountPairing } from '@/api/accountPairing'
-import {
-  createPairing,
-  pairChildNode,
-  pairedDevices,
-  pairingStatus,
-  revokePairedDevice,
-  type NodeScope,
-} from '@/api/pairing'
 
 vi.mock('qrcode', () => ({
   default: {
@@ -23,21 +15,6 @@ vi.mock('@/api/accountPairing', () => ({
   createAccountPairing: vi.fn(),
 }))
 
-vi.mock('@/api/pairing', () => ({
-  createPairing: vi.fn(),
-  pairChildNode: vi.fn(),
-  pairedDevices: vi.fn(),
-  pairingStatus: vi.fn(),
-  revokePairedDevice: vi.fn(),
-}))
-
-const allScopes: NodeScope[] = [
-  'agents.read',
-  'history.read',
-  'sessions.execute',
-  'groups.read',
-  'groups.execute',
-]
 
 beforeEach(() => {
   vi.useFakeTimers()
@@ -50,23 +27,6 @@ beforeEach(() => {
     qrPayload: 'yaoyao://login?v=1&id=account-pairing-1',
   })
   vi.mocked(accountPairingStatus).mockResolvedValue({ state: 'pending' })
-  vi.mocked(pairedDevices).mockResolvedValue({
-    nodeId: 'node-12345678',
-    fingerprint: 'fingerprint-1',
-    devices: [],
-  })
-  vi.mocked(createPairing).mockResolvedValue({
-    protocolVersion: 1,
-    pairingId: 'node-pairing-1',
-    nodeId: 'node-12345678',
-    fingerprint: 'fingerprint-1',
-    scopes: [...allScopes],
-    expiresAt: Date.now() + 60_000,
-    qrPayload: 'yaoyao://pair?v=1&id=node-pairing-1',
-  })
-  vi.mocked(pairingStatus).mockResolvedValue({ state: 'pending' })
-  vi.mocked(pairChildNode).mockResolvedValue(undefined)
-  vi.mocked(revokePairedDevice).mockResolvedValue(undefined)
 })
 
 afterEach(() => {
@@ -83,7 +43,7 @@ describe('NodePairingPanel', () => {
   it('account 模式只创建账号登录二维码,并在停用时清理轮询', async () => {
     const wrapper = mount(NodePairingPanel, {
       attachTo: document.body,
-      props: { active: true, mode: 'account', isAdmin: true, userName: 'admin' },
+      props: { active: true, mode: 'account', userName: 'admin' },
       global: { stubs: { AppIcon: true } },
     })
     await flushPromises()
@@ -93,8 +53,6 @@ describe('NodePairingPanel', () => {
       'yaoyao://login?v=1&id=account-pairing-1',
       expect.objectContaining({ width: 296, margin: 2, errorCorrectionLevel: 'M' }),
     )
-    expect(pairedDevices).not.toHaveBeenCalled()
-    expect(createPairing).not.toHaveBeenCalled()
     expect(wrapper.text()).toContain('在 iOS 登录页选择扫码')
     expect(vi.getTimerCount()).toBe(1)
 
@@ -105,68 +63,5 @@ describe('NodePairingPanel', () => {
     wrapper.unmount()
   })
 
-  it('nodes 模式先只加载设备,生成二维码时传递完整授权范围,并在卸载时清理轮询', async () => {
-    const wrapper = mount(NodePairingPanel, {
-      attachTo: document.body,
-      props: { active: true, mode: 'nodes', isAdmin: true },
-      global: { stubs: { AppIcon: true } },
-    })
-    await flushPromises()
-
-    expect(pairedDevices).toHaveBeenCalledOnce()
-    expect(createAccountPairing).not.toHaveBeenCalled()
-    expect(createPairing).not.toHaveBeenCalled()
-    expect(QRCode.toDataURL).not.toHaveBeenCalled()
-    expect(wrapper.text()).toContain('还没有已授权设备')
-    expect(vi.getTimerCount()).toBe(0)
-
-    await wrapper.get('button.create-pairing').trigger('click')
-    await flushPromises()
-
-    expect(createPairing).toHaveBeenCalledWith(allScopes)
-    expect(QRCode.toDataURL).toHaveBeenCalledWith(
-      'yaoyao://pair?v=1&id=node-pairing-1',
-      expect.objectContaining({ width: 296, margin: 2, errorCorrectionLevel: 'M' }),
-    )
-    expect(vi.getTimerCount()).toBe(1)
 
-    wrapper.unmount()
-    expect(vi.getTimerCount()).toBe(0)
-  })
-
-  it('stops a camera stream whose startup becomes stale before video playback completes', async () => {
-    let resolvePlay: (() => void) | undefined
-    const play = new Promise<void>(resolve => { resolvePlay = resolve })
-    const track = { stop: vi.fn() }
-    const getUserMedia = vi.fn(async () => ({ getTracks: () => [track] }) as unknown as MediaStream)
-    Object.defineProperty(navigator, 'mediaDevices', { configurable: true, value: { getUserMedia } })
-    vi.stubGlobal('BarcodeDetector', class {
-      detect = vi.fn(async () => [])
-    })
-    const playSpy = vi.spyOn(HTMLMediaElement.prototype, 'play').mockReturnValue(play)
-    const wrapper = mount(NodePairingPanel, {
-      attachTo: document.body,
-      props: { active: true, mode: 'nodes', isAdmin: true },
-      global: { stubs: { AppIcon: true } },
-    })
-    await flushPromises()
-
-    const scan = wrapper.findAll<HTMLButtonElement>('button').find(button => button.text().includes('使用摄像头扫码'))!
-    await scan.trigger('click')
-    await flushPromises()
-    await vi.advanceTimersByTimeAsync(0)
-    await flushPromises()
-    expect(getUserMedia).toHaveBeenCalledOnce()
-    expect(playSpy).toHaveBeenCalledOnce()
-
-    const stop = wrapper.findAll<HTMLButtonElement>('button').find(button => button.text().includes('停止扫码'))!
-    await stop.trigger('click')
-    expect(track.stop).toHaveBeenCalledOnce()
-    resolvePlay?.()
-    await flushPromises()
-
-    expect(vi.getTimerCount()).toBe(0)
-    expect(wrapper.text()).not.toContain('停止扫码')
-    wrapper.unmount()
-  })
 })

+ 0 - 184
tests/client/ordinaryTranscriptV2.test.ts

@@ -1,184 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import fixture from '../fixtures/ordinary-chat-v2/protocol.json'
-import { ChatTranscriptClient } from '@/api/chatTranscript'
-import type { TranscriptSnapshot } from '@shared/chatTranscript'
-const api = vi.hoisted(() => ({ request: vi.fn() }))
-vi.mock('@/api/client', () => ({ apiRequest: api.request }))
-describe('ordinary v2 durable Web replica', () => {
-  beforeEach(() => {
-    api.request.mockReset()
-  })
-  function setup() {
-    const changed = vi.fn().mockResolvedValue(undefined),
-      client = new ChatTranscriptClient('p', 's', changed, vi.fn()) as any
-    client.restore(structuredClone(fixture.snapshot))
-    return { client, changed }
-  }
-  it('converges on the common fixture and does not resurrect a deletion from a delayed page', async () => {
-    const { client, changed } = setup()
-    let release!: (value: unknown) => void
-    api.request.mockImplementation(
-      () =>
-        new Promise((resolve) => {
-          release = resolve
-        }),
-    )
-    const older = client.loadOlder()
-    for (const event of fixture.events) await client.receive(event)
-    release(fixture.stalePage)
-    await older
-    expect(changed.mock.lastCall![0]).toMatchObject({
-      cursor: 4,
-      messages: fixture.expectedMessages,
-      deletedIds: ['old-preview'],
-    })
-  })
-  it('does not advance messages or cursor when persistence fails, and can retry exactly once', async () => {
-    const { client, changed } = setup()
-    changed.mockRejectedValueOnce(new Error('disk full'))
-    await expect(client.receive(fixture.events[0])).rejects.toThrow('disk full')
-    expect(client.snapshot).toEqual(fixture.snapshot)
-    await client.receive(fixture.events[0])
-    await client.receive(fixture.events[0])
-    expect(client.snapshot.messages[0].content).toBe('前半段后半段')
-    expect(client.snapshot.cursor).toBe(2)
-  })
-  it('rejects gaps and old generations without corrupting its checkpoint', async () => {
-    const { client } = setup()
-    await expect(client.receive(fixture.events[2])).rejects.toThrow('版本不连续')
-    await expect(client.receive({ ...fixture.events[0], epoch: 'old' })).rejects.toThrow('版本不连续')
-    expect(client.snapshot).toEqual(fixture.snapshot)
-  })
-  it('discards v1 checkpoints rather than merging them into v2', () => {
-    const client = new ChatTranscriptClient(
-      'p',
-      's',
-      async () => {},
-      () => {},
-    ) as any
-    client.restore({
-      ...fixture.snapshot,
-      protocol: 'ordinary-chat-transcript-v1',
-    } as unknown as TranscriptSnapshot)
-    expect(client.snapshot).toBeUndefined()
-  })
-  it('rejects an ahead control cursor and ignores a delayed control without replacing state', async () => {
-    const { client, changed } = setup()
-    const saved = { ...client.snapshot, running: true, queued: true, liveStatus: '进行中' }
-    client.restore(saved)
-    await expect(client.control({ epoch: saved.epoch, cursor: saved.cursor + 1, running: false, queued: false })).rejects.toThrow('版本不连续')
-    await client.control({ epoch: saved.epoch, cursor: saved.cursor - 1, running: false, queued: false })
-    expect(changed).not.toHaveBeenCalled()
-    expect(client.snapshot).toEqual(saved)
-    client.close()
-  })
-  it.each(['ready', 'state'])('repairs a %s cursor gap with a snapshot instead of skipping messages', async event => {
-    vi.useFakeTimers()
-    const { client, changed } = setup()
-    const repaired = { ...fixture.snapshot, cursor: 3, hasOlder: false,
-      messages: [{ ...fixture.snapshot.messages[0], revision: 3, content: '补齐的消息' }] }
-    api.request.mockResolvedValue(repaired)
-    let attempts = 0
-    vi.stubGlobal('fetch', vi.fn((_url: unknown, options: RequestInit) => {
-      attempts++
-      return Promise.resolve(new Response(new ReadableStream<Uint8Array>({ start(controller) {
-        if (attempts === 1) controller.enqueue(new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify({ epoch: repaired.epoch, cursor: 3, running: false, queued: false })}\n\n`))
-        options.signal?.addEventListener('abort', () => { try { controller.close() } catch {} }, { once: true })
-      } }), { status: 200 }))
-    }))
-    const running = client.run()
-    try {
-      await vi.advanceTimersByTimeAsync(1000)
-      expect(api.request).toHaveBeenCalledWith(expect.stringContaining('/snapshot?'), expect.anything())
-      expect(changed.mock.lastCall![0]).toMatchObject({ cursor: 3, messages: repaired.messages })
-      expect(attempts).toBe(2)
-    } finally {
-      client.close(); await running; vi.unstubAllGlobals(); vi.useRealTimers()
-    }
-  })
-  it('reopens an inactive event connection without dropping the durable cursor', async () => {
-    vi.useFakeTimers()
-    const { client } = setup()
-    const fetchMock = vi.fn(
-      (_url: unknown, options: RequestInit) =>
-        new Promise((_resolve, reject) => {
-          options.signal?.addEventListener('abort', () => reject(new Error('inactive stream')), {
-            once: true,
-          })
-        }),
-    )
-    vi.stubGlobal('fetch', fetchMock)
-    const running = client.run()
-    try {
-      await vi.advanceTimersByTimeAsync(46_000)
-      expect(fetchMock).toHaveBeenCalledTimes(2)
-      expect(client.snapshot.cursor).toBe(1)
-      expect(fetchMock.mock.calls[1]![1].headers).toMatchObject({ 'Last-Event-ID': 'fixture-epoch:1' })
-    } finally {
-      client.close()
-      await running
-      vi.unstubAllGlobals()
-      vi.useRealTimers()
-    }
-  })
-  it('restores running state and interactions before resuming the saved event cursor', async () => {
-    const { client, changed } = setup()
-    const saved = { ...fixture.snapshot, running: true, liveStatus: '正在思考', pendingApproval: { id: 'approval' } }
-    client.restore(saved)
-    const fetchMock = vi.fn((_url: unknown, options: RequestInit) => {
-      expect(changed).toHaveBeenCalledWith(saved)
-      return new Promise((_resolve, reject) => {
-        options.signal?.addEventListener('abort', () => reject(new Error('closed')), { once: true })
-      })
-    })
-    vi.stubGlobal('fetch', fetchMock)
-    const running = client.run()
-    try {
-      await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
-      expect(api.request).not.toHaveBeenCalled()
-      expect(fetchMock.mock.calls[0]![1].headers).toMatchObject({ 'Last-Event-ID': 'fixture-epoch:1' })
-    } finally {
-      client.close()
-      await running
-      vi.unstubAllGlobals()
-    }
-  })
-  it('reconciles a stale running checkpoint from the authoritative SSE ready state', async () => {
-    const { client, changed } = setup()
-    const saved = { ...fixture.snapshot, running: true, queued: false, liveStatus: '正在思考' }
-    client.restore(saved)
-    const fetchMock = vi.fn((_url: unknown, options: RequestInit) => {
-      const stream = new ReadableStream<Uint8Array>({
-        start(controller) {
-          const frame = `event: ready\ndata: ${JSON.stringify({
-            epoch: 'fixture-epoch',
-            cursor: fixture.snapshot.cursor,
-            running: false,
-            queued: false,
-            pendingApproval: null,
-            pendingClarification: null,
-            liveStatus: null,
-            error: null,
-          })}\n\n`
-          controller.enqueue(new TextEncoder().encode(frame))
-          options.signal?.addEventListener('abort', () => controller.close(), { once: true })
-        },
-      })
-      return Promise.resolve(new Response(stream, { status: 200 }))
-    })
-    vi.stubGlobal('fetch', fetchMock)
-    const running = client.run()
-    try {
-      await vi.waitFor(() => expect(changed.mock.lastCall![0]).toMatchObject({
-        cursor: fixture.snapshot.cursor,
-        running: false,
-        queued: false,
-        liveStatus: null,
-      }))
-    } finally {
-      client.close()
-      await running
-      vi.unstubAllGlobals()
-    }
-  })
-})

+ 0 - 40
tests/client/scopedCache.test.ts

@@ -1,40 +0,0 @@
-import { afterEach, expect, it, vi } from 'vitest'
-import { reactive } from 'vue'
-
-const storage = vi.hoisted(() => ({ records: new Map<string, unknown>(), fail: false }))
-vi.mock('idb', () => ({ openDB: async () => ({
-  put: async (_store: string, value: unknown, key: string) => {
-    if (storage.fail) throw new Error('disk unavailable')
-    storage.records.set(key, structuredClone(value))
-  },
-  get: async (_store: string, key: string) => {
-    if (storage.fail) throw new Error('disk unavailable')
-    return structuredClone(storage.records.get(key))
-  },
-}) }))
-
-afterEach(() => { storage.records.clear(); storage.fail = false; vi.unstubAllGlobals(); vi.resetModules() })
-
-it('durably stores reactive pending messages as detached snapshots', async () => {
-  vi.stubGlobal('indexedDB', {})
-  const { ScopedCache } = await import('../../src/client/utils/cache')
-  const cache = new ScopedCache<{ messages: Array<{ content: string }>; cursor: number }>('reactive')
-  const pending = reactive({ content: 'pending input' })
-  const value = reactive({ messages: [pending], cursor: 3 })
-  await cache.set('account', 'session', value, true)
-  pending.content = 'later edit'
-  value.cursor = 4
-  expect(await cache.get('account', 'session')).toEqual({ messages: [{ content: 'pending input' }], cursor: 3 })
-})
-
-it('does not advance the memory checkpoint when durable storage fails', async () => {
-  vi.stubGlobal('indexedDB', {})
-  const { ScopedCache } = await import('../../src/client/utils/cache')
-  const cache = new ScopedCache<{ cursor: number }>('failed-write')
-  const value = reactive({ cursor: 3 })
-  await cache.set('account', 'session', value, true)
-  storage.fail = true
-  value.cursor = 4
-  await expect(cache.set('account', 'session', value, true)).rejects.toThrow('disk unavailable')
-  expect(await cache.get('account', 'session')).toEqual({ cursor: 3 })
-})

+ 2 - 3
tests/client/serviceWarnings.test.ts

@@ -2,7 +2,6 @@ import { afterEach, expect, it, vi } from 'vitest'
 import { flushPromises, mount } from '@vue/test-utils'
 import { createPinia } from 'pinia'
 import WorkspaceTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 import { workspaceMessagesToUi } from '@/components/workspace/viewModels'
 import { WorkspaceTranscriptStore } from '@/components/workspace/transcriptStore'
 import { buildMessageTimelineRows } from '@/utils/turnTrace'
@@ -24,13 +23,13 @@ it('keeps warning-only messages visible independently of tool trace aggregation
   expect(textOnly?.serviceWarnings).toBeUndefined()
 })
 
-it.each(['workspace','session'])('shows non-blocking, escaped service notices with tools hidden in the %s timeline',async(timeline)=>{
+it.each(['workspace'])('shows non-blocking, escaped service notices with tools hidden in the %s timeline',async(timeline)=>{
   vi.stubGlobal('ResizeObserver',class {observe(){}disconnect(){}})
   const scrollTo=HTMLElement.prototype.scrollTo
   HTMLElement.prototype.scrollTo=vi.fn()
   const unsafe={code:'plugin_unavailable',service:'<img src=x onerror="alert(1)">',message:'<script>alert(2)</script> [修复](javascript:alert(3))'}
   const messages=workspaceMessagesToUi([{...message,serviceWarnings:[warning,unsafe]}])
-  const wrapper=mount(timeline==='workspace'?WorkspaceTimeline:MessageTimeline,{props:{identity:'chat',messages,showTools:false},global:{plugins:[createPinia()],stubs:{AppIcon:true,AgentAvatar:true,MarkdownContent:{props:['content'],template:'<div class="fixture-content">{{content}}</div>'}}}})
+  const wrapper=mount(WorkspaceTimeline,{props:{identity:'chat',messages,showTools:false},global:{plugins:[createPinia()],stubs:{AppIcon:true,AgentAvatar:true,MarkdownContent:{props:['content'],template:'<div class="fixture-content">{{content}}</div>'}}}})
   try{
     await flushPromises()
     const notices=wrapper.get('[aria-label="服务状态提示"]')

+ 0 - 55
tests/client/sessionModel.test.ts

@@ -1,55 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { modelForChoiceId, modelForSession, modelSelectionFromSessionInfo } from '@/utils/sessionModel'
-import { normalizeSession } from '@/utils/normalize'
-import { isOwnedChatSession } from '@/utils/sessionOwnership'
-
-const models = [
-  { id: 'gpt-5.6-terra', name: 'GPT 5.6 Terra', provider: 'custom' },
-  { id: 'glm-5.3', name: 'GLM 5.3', provider: 'custom', isDefault: true },
-]
-
-describe('session model selection', () => {
-  it('restores the saved model case-insensitively instead of the profile default', () => {
-    expect(modelForSession(models, 'GPT-5.6-terra', 'CUSTOM')).toEqual(models[0])
-  })
-
-  it('keeps an unavailable stored model visible until the user chooses another', () => {
-    expect(modelForSession(models, 'archived-model', 'legacy')).toEqual({ id: 'archived-model', name: 'archived-model', provider: 'legacy' })
-  })
-
-  it('reads model changes from both session.info payload shapes', () => {
-    expect(modelSelectionFromSessionInfo({ model: 'gpt-5.6-sol', provider: 'openai-codex' })).toEqual({
-      model: 'gpt-5.6-sol', provider: 'openai-codex',
-    })
-    expect(modelSelectionFromSessionInfo({ info: { model: 'MiniMax-M3', provider: 'minimax' } })).toEqual({
-      model: 'MiniMax-M3', provider: 'minimax',
-    })
-    expect(modelSelectionFromSessionInfo({ info: { provider: 'minimax' } })).toBeUndefined()
-  })
-
-  it('restores the provider from Hermes model_config session details', () => {
-    expect(normalizeSession({
-      id: 'session-1', model: 'omni',
-      model_config: JSON.stringify({ model: 'omni', provider: 'custom:tingly' }),
-    })).toMatchObject({ model: 'omni', provider: 'custom:tingly' })
-  })
-
-  it('uses server ownership rather than source to separate chats from history', () => {
-    const ownedIOS = normalizeSession({
-      id: 'owned-ios', source: 'ios', owned: true, title: '跨端聊天',
-    })
-    const unownedWeb = normalizeSession({
-      id: 'native-web', source: 'web', owned: false, title: '原生历史',
-    })
-
-    expect(isOwnedChatSession(ownedIOS)).toBe(true)
-    expect(isOwnedChatSession(unownedWeb)).toBe(false)
-    expect(isOwnedChatSession({ id: 'draft-local', owned: undefined })).toBe(true)
-    expect(isOwnedChatSession({ id: 'draft-server-history', owned: false })).toBe(false)
-  })
-
-  it('finds a chosen model when its provider contains a colon', () => {
-    const tinglyModel = { id: 'omni', name: 'Omni', provider: 'Custom:Tingly' }
-    expect(modelForChoiceId([tinglyModel], 'Custom:Tingly:omni')).toEqual(tinglyModel)
-  })
-})

+ 0 - 19
tests/client/sessionOrder.test.ts

@@ -1,19 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { SessionSummary } from '@shared/types'
-import { appendSessionPage, pinnedSessionsFirst } from '@/utils/sessionOrder'
-
-function session(id: string, pinned = false): SessionSummary {
-  return { id, profile: 'yaoyao', source: 'web', title: id, pinned, messageCount: 0, toolCallCount: 0, startedAt: 0, updatedAt: 0 }
-}
-
-describe('session sidebar order', () => {
-  it('puts pinned conversations first without reordering either server bucket', () => {
-    expect(pinnedSessionsFirst([session('recent'), session('pinned-one', true), session('older'), session('pinned-two', true)])
-      .map(value => value.id)).toEqual(['pinned-one', 'pinned-two', 'recent', 'older'])
-  })
-
-  it('appends a page without duplicating sessions and promotes newly discovered pins', () => {
-    expect(appendSessionPage([session('recent')], [session('pinned', true), session('recent'), session('older')])
-      .map(value => value.id)).toEqual(['pinned', 'recent', 'older'])
-  })
-})

+ 0 - 51
tests/client/sessionOutline.test.ts

@@ -1,51 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { mount } from '@vue/test-utils'
-import { nextTick } from 'vue'
-import type { UiMessage } from '@/components/messages/types'
-import MarkdownContent from '@/components/messages/MarkdownContent.vue'
-import { buildSessionOutline } from '@/utils/sessionOutline'
-
-describe('session outline', () => {
-  it('keeps each user turn and all assistant H1-H3 headings before the next turn', () => {
-    const messages: UiMessage[] = [
-      { id: 'u1', role: 'user', content: '请给我一份完整方案' },
-      { id: 'a1', role: 'assistant', content: '# 结论\n正文\n## 实施步骤' },
-      { id: 'a2', role: 'assistant', content: '### 风险\n说明' },
-      { id: 'u2', role: 'user', content: '再补充测试' },
-      { id: 'a3', role: 'assistant', content: '## 测试计划' },
-    ]
-    expect(buildSessionOutline(messages).map(item => [item.type, item.level, item.content])).toEqual([
-      ['user', 0, '请给我一份完整方案'],
-      ['heading', 1, '结论'],
-      ['heading', 2, '实施步骤'],
-      ['heading', 3, '风险'],
-      ['user', 0, '再补充测试'],
-      ['heading', 2, '测试计划'],
-    ])
-  })
-
-  it('ignores reasoning, fenced-code headings, tools, and timeline system events', () => {
-    const messages: UiMessage[] = [
-      { id: 'system', role: 'user', content: '模型切换', timelineKind: 'system' },
-      { id: 'u1', role: 'user', content: '<think>内部</think>真实问题' },
-      { id: 'a1', role: 'assistant', content: '<think># 隐藏标题</think>\n```md\n# 代码标题\n```\n## 可见标题' },
-      { id: 'tool', role: 'tool', content: '# 工具标题' },
-    ]
-    expect(buildSessionOutline(messages).map(item => item.content)).toEqual(['真实问题', '可见标题'])
-  })
-
-  it('truncates long user questions to fifty characters', () => {
-    const content = '这是一条很长的用户问题'.repeat(8)
-    const [item] = buildSessionOutline([{ id: 'u1', role: 'user', content }])
-    expect(item?.content).toHaveLength(51)
-    expect(item?.content.endsWith('…')).toBe(true)
-  })
-
-  it('assigns stable DOM anchors to rendered Markdown headings', async () => {
-    const wrapper = mount(MarkdownContent, { props: { content: '# 结论\n## 步骤\n### 风险', outlinePrefix: 'outline-a1' } })
-    await nextTick()
-    expect(wrapper.find('h1').attributes('id')).toBe('outline-a1-heading-1')
-    expect(wrapper.find('h2').attributes('id')).toBe('outline-a1-heading-2')
-    expect(wrapper.find('h3').attributes('id')).toBe('outline-a1-heading-3')
-  })
-})

+ 0 - 40
tests/client/sessionPreferences.test.ts

@@ -1,40 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import {
-  moveSessionFastMode, readAgentShowThinking, readSessionFastMode, writeAgentShowThinking, writeSessionFastMode,
-} from '@/utils/sessionPreferences'
-
-beforeEach(() => {
-  const values = new Map<string, string>()
-  vi.stubGlobal('localStorage', {
-    getItem: (key: string) => values.get(key) ?? null,
-    setItem: (key: string, value: string) => void values.set(key, value),
-    removeItem: (key: string) => void values.delete(key),
-  })
-})
-afterEach(() => vi.unstubAllGlobals())
-
-describe('session and Agent display preferences', () => {
-  it('isolates fast mode by account, Agent, and session', () => {
-    writeSessionFastMode('u1', 'yaoer', 's1', true)
-    expect(readSessionFastMode('u1', 'yaoer', 's1')).toBe(true)
-    expect(readSessionFastMode('u1', 'default', 's1')).toBe(false)
-    expect(readSessionFastMode('u2', 'yaoer', 's1')).toBe(false)
-    expect(readSessionFastMode('u1', 'yaoer', 's2')).toBe(false)
-  })
-
-  it('moves a draft fast-mode selection to the stored session identity', () => {
-    writeSessionFastMode('u1', 'default', 'draft-1', true)
-    moveSessionFastMode('u1', 'default', 'draft-1', 'stored-1', true)
-    expect(readSessionFastMode('u1', 'default', 'draft-1')).toBe(false)
-    expect(readSessionFastMode('u1', 'default', 'stored-1')).toBe(true)
-  })
-
-  it('hides thinking by default and stores an explicit choice per account and Agent', () => {
-    expect(readAgentShowThinking('u1', 'yaoer')).toBe(false)
-    writeAgentShowThinking('u1', 'yaoer', false)
-    expect(readAgentShowThinking('u1', 'yaoer')).toBe(false)
-    expect(readAgentShowThinking('u1', 'default')).toBe(false)
-    writeAgentShowThinking('u1', 'yaoer', true)
-    expect(readAgentShowThinking('u1', 'yaoer')).toBe(true)
-  })
-})

+ 0 - 24
tests/client/sessionProtocol.test.ts

@@ -1,24 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { getMessages } from '@/api/sessions'
-
-afterEach(() => vi.unstubAllGlobals())
-
-describe('ordinary session history protocol', () => {
-  it('always uses Desktop-compatible latest compacted pagination', async () => {
-    const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(JSON.stringify({
-      messages: [{ id: 'm1', role: 'assistant', content: 'ok', timestamp: 1 }],
-      pagination: { total: 20, returned: 1, has_more: true, limit: 500 },
-    }), { status: 200, headers: { 'content-type': 'application/json' } }))
-    vi.stubGlobal('fetch', fetchMock)
-
-    const page = await getMessages('session/a', 12, 900, 'yao er')
-    const [input, init] = fetchMock.mock.calls[0]
-    const url = new URL(String(input), 'http://localhost')
-    expect(url.pathname).toBe('/api/app/sessions/session%2Fa/messages')
-    expect(Object.fromEntries(url.searchParams)).toMatchObject({
-      offset: '12', limit: '500', order: 'latest', include_compacted: 'true', profile: 'yao er',
-    })
-    expect(init).toMatchObject({ credentials: 'include', cache: 'no-store' })
-    expect(page).toMatchObject({ total: 20, returned: 1, hasMore: true })
-  })
-})

+ 0 - 13
tests/client/sessionUnread.test.ts

@@ -1,13 +0,0 @@
-import { afterEach, expect, it, vi } from 'vitest'
-import { getSessionUnread } from '@/api/sessions'
-
-afterEach(() => vi.unstubAllGlobals())
-
-it('uses final result counts for list badges, including an explicit zero', async () => {
-  vi.stubGlobal('fetch', vi.fn(async () => Response.json({ sessions: [
-    { session_id: 'result', unread_count: 12, final_unread_count: 1 },
-    { session_id: 'tools', unread_count: 8, final_unread_count: 0 },
-    { session_id: 'legacy', unread_count: 2 },
-  ] })))
-  expect(await getSessionUnread('default')).toEqual({ result: 1, tools: 0, legacy: 2 })
-})

+ 11 - 38
tests/client/settingsCenterDialog.test.ts

@@ -165,20 +165,16 @@ describe('Settings center dialog', () => {
     expect(wrapper.find('.bot-about').exists()).toBe(false)
     wrapper.unmount()
   })
-  it('groups administrator pages and routes Agent, voice, and system content to the right scope', async () => {
+  it('groups administrator pages and routes account, voice, and system content to the right scope', async () => {
     const wrapper = mountSettings()
 
+    // Bot mode only: base Profile identity and models live in each Bot's profile.
     expect(wrapper.findAll('.settings-sidebar nav h3').map(heading => heading.text())).toEqual([
       '个人',
       '管理',
-      '基础机器人',
     ])
-
-    await navigationButton(wrapper, '模型与 Provider').trigger('click')
-    expect(navigationButton(wrapper, '模型与 Provider').attributes('aria-current')).toBe('page')
-    const modelPanel = wrapper.get('[data-testid="model-services"]')
-    expect(modelPanel.attributes('data-profile')).toBe('ops:blue/team')
-    expect(wrapper.get('.settings-content__header').text()).toContain('正在设置:运维机器人 / ops:blue/team')
+    expect(wrapper.get('.settings-sidebar nav').text()).not.toContain('模型与 Provider')
+    expect(wrapper.get('.settings-sidebar nav').text()).not.toContain('身份与头像')
 
     await navigationButton(wrapper, '登录与安全').trigger('click')
     expect(wrapper.find('.settings-agent-selector').exists()).toBe(false)
@@ -198,7 +194,6 @@ describe('Settings center dialog', () => {
 
     expect(navigation.findAll('h3').map(heading => heading.text())).toEqual(['个人'])
     expect(navigation.text()).not.toContain('模型与 Provider')
-    expect(navigation.text()).not.toContain('管理')
     expect(navigation.text()).not.toContain('系统概览')
     expect(navigation.text()).not.toContain('双流语音')
     expect(navigation.text()).not.toContain('更新与回滚')
@@ -226,28 +221,19 @@ describe('Settings center dialog', () => {
 
   it('asks before discarding an edited page and keeps the current page when declined', async () => {
     const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
-    const wrapper = mountSettings()
-    wrapper.findComponent({ name: 'AgentIdentityPanel' }).vm.$emit('dirty-change', true)
-    await wrapper.vm.$nextTick()
+    const wrapper = mountSettings({ initialPage: 'system-voice' })
+    await wrapper.get('[data-testid="dirty-voice"]').trigger('click')
 
     await navigationButton(wrapper, '登录与安全').trigger('click')
     expect(confirm).toHaveBeenCalledWith('放弃当前页面未保存的更改?')
-    expect(wrapper.get('.settings-content__header').text()).toContain('身份与头像')
+    expect(wrapper.get('.settings-content__header').text()).toContain('双流语音')
 
     await navigationButton(wrapper, '登录与安全').trigger('click')
     expect(wrapper.find('[data-testid="account-security"]').exists()).toBe(true)
   })
 
-  it('protects Provider and global voice drafts from silent navigation or close', async () => {
+  it('protects global voice drafts from silent close', async () => {
     const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
-    const modelWrapper = mountSettings({ initialPage: 'agent-models' })
-    await modelWrapper.get('[data-testid="dirty-model"]').trigger('click')
-    await navigationButton(modelWrapper, '登录与安全').trigger('click')
-    expect(confirm).toHaveBeenCalledWith('放弃当前页面未保存的更改?')
-    expect(modelWrapper.find('[data-testid="model-services"]').exists()).toBe(true)
-    modelWrapper.unmount()
-
-    confirm.mockClear()
     const voiceWrapper = mountSettings({ initialPage: 'system-voice' })
     await voiceWrapper.get('[data-testid="dirty-voice"]').trigger('click')
     await voiceWrapper.get('.settings-center__close').trigger('click')
@@ -258,14 +244,14 @@ describe('Settings center dialog', () => {
   it('moves mobile focus into details and back to the active category', async () => {
     Object.defineProperty(window, 'innerWidth', { configurable: true, value: 390 })
     const wrapper = mountSettings()
-    const identity = navigationButton(wrapper, '身份与头像')
-    await identity.trigger('click')
+    const profile = navigationButton(wrapper, '账号资料')
+    await profile.trigger('click')
     await wrapper.vm.$nextTick()
     expect(document.activeElement).toBe(wrapper.get('.settings-content__header h3').element)
 
     await wrapper.get('.mobile-back').trigger('click')
     await wrapper.vm.$nextTick()
-    expect(document.activeElement).toBe(identity.element)
+    expect(document.activeElement).toBe(profile.element)
 
     const security = navigationButton(wrapper, '登录与安全')
     await security.trigger('click')
@@ -277,17 +263,4 @@ describe('Settings center dialog', () => {
     expect(document.activeElement).toBe(security.element)
   })
 
-  it('supports listbox keyboard navigation for the Agent selector', async () => {
-    const wrapper = mountSettings()
-    const trigger = wrapper.get('.settings-agent-selector > button')
-    expect(trigger.attributes('aria-haspopup')).toBe('listbox')
-    await trigger.trigger('click')
-    await wrapper.vm.$nextTick()
-    const menu = wrapper.get('.settings-agent-menu')
-    const options = menu.findAll<HTMLButtonElement>('[role="option"]')
-    expect(document.activeElement).toBe(options[0]!.element)
-
-    await menu.trigger('keydown', { key: 'ArrowDown' })
-    expect(document.activeElement).toBe(options[1]!.element)
-  })
 })

+ 1 - 2
tests/client/systemMessageNotice.test.ts

@@ -3,7 +3,6 @@ import { nextTick } from 'vue'
 import { mount } from '@vue/test-utils'
 import { systemMessageNotice } from '@/utils/systemMessageNotice'
 import WorkspaceMessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 import type { UiMessage } from '@/components/messages/types'
 
 const assignment: UiMessage = { id: 'assigned', role: 'system', content: '由管理员分派的子任务:终审文章\n\n- 核验来源\n- 检查配图' }
@@ -25,7 +24,7 @@ describe('system event disclosures', () => {
     expect(systemMessageNotice({ ...message, timelineMetadata: { exit_code: 143, signal: 'SIGTERM' } })?.title).toBe('后台子任务已终止')
   })
 
-  it.each([MessageTimeline, WorkspaceMessageTimeline])('keeps full requirements behind a short title in both timelines', async component => {
+  it.each([WorkspaceMessageTimeline])('keeps full requirements behind a short title in both timelines', async component => {
     vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} })
     Element.prototype.scrollTo = vi.fn()
     const wrapper = mount(component, { props: { identity: 'test', messages: [assignment] }, global: { stubs: { AgentAvatar: true, MarkdownContent: { props: ['content'], template: '<p>{{ content }}</p>' } } } })

+ 0 - 2
tests/client/typingIndicator.test.ts

@@ -2,7 +2,6 @@ import { mount } from '@vue/test-utils'
 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
 import { defineComponent, nextTick, type Component } from 'vue'
 import TypingIndicator from '@/components/common/TypingIndicator.vue'
-import MessageTimeline from '@/components/messages/MessageTimeline.vue'
 import WorkspaceMessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
 import type { UiMessage } from '@/components/messages/types'
 
@@ -75,7 +74,6 @@ describe('TypingIndicator', () => {
 
 describe('message timeline typing state', () => {
   const timelines: Array<{ name: string; component: Component }> = [
-    { name: 'ordinary', component: MessageTimeline },
     { name: 'workspace', component: WorkspaceMessageTimeline },
   ]
 

+ 8 - 82
tests/client/workspaceShell.test.ts

@@ -23,7 +23,7 @@ const SettingsCenterDialogStub = defineComponent({
   template: '<div v-if="open" data-testid="settings-center" :data-page="initialPage"><button data-testid="close-settings" type="button" @click="$emit(\'close\')">close</button></div>',
 })
 
-async function mountShell(start = '/chat') {
+async function mountShell(start = '/conversations') {
   const router = createRouter({
     history: createMemoryHistory(),
     routes: [
@@ -74,76 +74,8 @@ afterEach(() => {
   document.body.innerHTML = ''
 })
 
-describe('Workspace shell account controls', () => {
-  it('keeps Agent switching focused and opens settings from its independent button', async () => {
-    const wrapper = await mountShell()
-    const desktop = wrapper.get('.desktop-sidebar')
 
-    const agentTrigger = desktop.get('.sidebar-account-switcher__main')
-    expect(agentTrigger.attributes('aria-haspopup')).toBe('listbox')
-    expect(agentTrigger.attributes('aria-expanded')).toBe('false')
-    await agentTrigger.trigger('click')
-    expect(agentTrigger.attributes('aria-expanded')).toBe('true')
-    const menu = desktop.get('.profile-menu')
-    expect(menu.attributes('role')).toBe('listbox')
-    expect(menu.text()).toContain('切换机器人')
-    expect(menu.text()).toContain('丫头')
-    expect(menu.text()).toContain('运维机器人')
-    expect(menu.text()).not.toContain('机器人设置')
-    expect(menu.findAll('button')).toHaveLength(profiles.length)
-    expect(menu.findAll('[role="option"]').map(option => option.attributes('aria-selected'))).toEqual(['true', 'false'])
-    expect(menu.text()).not.toContain('账号安全')
-    expect(menu.text()).not.toContain('系统管理')
-    expect(menu.text()).not.toContain('系统更新')
-    expect(menu.text()).not.toContain('退出登录')
-
-    expect(document.activeElement).toBe(menu.find('[role="option"][aria-selected="true"]').element)
-    await menu.trigger('keydown', { key: 'ArrowDown' })
-    const targetProfile = menu.findAll<HTMLButtonElement>('button')
-      .find(button => button.text().includes('运维机器人'))!
-    expect(document.activeElement).toBe(targetProfile.element)
-    await targetProfile.trigger('click')
-    expect(wrapper.emitted('selectProfile')).toEqual([['ops:blue/team']])
-    expect(desktop.find('.profile-menu').exists()).toBe(false)
-
-    const settingsTrigger = desktop.get<HTMLButtonElement>('.sidebar-settings-trigger')
-    expect(settingsTrigger.text()).toBe('')
-    expect(settingsTrigger.attributes('aria-label')).toBe('设置与模式')
-    await settingsTrigger.trigger('click')
-    const actions = document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu [role="menuitem"]')
-    expect([...actions].map(button => button.textContent?.trim())).toEqual(['我的设置', '关于', '检测更新', '帮助', '进入 Bot 模式'])
-    actions[0]!.click()
-    await wrapper.vm.$nextTick()
-    const settings = wrapper.get('[data-testid="settings-center"]')
-    expect(settings.attributes('data-page')).toBe('agent-identity')
-    expect(desktop.find('.profile-menu').exists()).toBe(false)
-
-    await wrapper.get('[data-testid="close-settings"]').trigger('click')
-    await wrapper.vm.$nextTick()
-    expect(document.activeElement).toBe(settingsTrigger.element)
-
-    const mobileNavigation = wrapper.get<HTMLButtonElement>('.mobile-header button[aria-label="打开导航"]')
-    await mobileNavigation.trigger('click')
-    await wrapper.vm.$nextTick()
-    expect(wrapper.get('.mobile-header').attributes()).toHaveProperty('inert')
-    expect(document.activeElement).toBe(wrapper.get('.mobile-drawer button[aria-label="关闭导航"]').element)
-    await wrapper.get('.mobile-drawer .sidebar-settings-trigger').trigger('click')
-    document.querySelector<HTMLButtonElement>('.workspace-settings-menu [role="menuitem"]')!.click()
-    await wrapper.vm.$nextTick()
-    await wrapper.get('[data-testid="close-settings"]').trigger('click')
-    await wrapper.vm.$nextTick()
-    expect(document.activeElement).toBe(mobileNavigation.element)
-
-    expect(desktop.findAll('.sidebar-feature-nav button').map(button => button.text())).not.toContain('聊天')
-    await settingsTrigger.trigger('click')
-    document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu [role="menuitem"]')[4]!.click()
-    await vi.waitFor(() => expect(wrapper.classes()).toContain('workspace-shell--conversations'))
-    expect(document.querySelector('.workspace-settings-menu')).toBeNull()
-    wrapper.unmount()
-  })
-})
-
-it('uses the reference Bot list header and keeps mode changes in settings', async () => {
+it('uses the reference Bot list header and offers no interface mode switch', async () => {
   const wrapper = await mountShell('/conversations')
   const rail = wrapper.get('.desktop-sidebar')
   expect(wrapper.find('.sidebar-settings-trigger').exists()).toBe(false)
@@ -159,7 +91,7 @@ it('uses the reference Bot list header and keeps mode changes in settings', asyn
   expect(rail.find('.sidebar-context__heading').exists()).toBe(false)
   await rail.get('.sidebar-account-switcher__main').trigger('click')
   const accountItems = [...document.querySelectorAll<HTMLElement>('.workspace-settings-menu [role="menuitem"]')]
-  expect(accountItems.map(item => item.textContent?.trim())).toEqual(['我的设置', '关于', '检测更新', '帮助', '进入聊天模式'])
+  expect(accountItems.map(item => item.textContent?.trim())).toEqual(['我的设置', '关于', '检测更新', '帮助'])
   expect(document.querySelector<HTMLAnchorElement>('.workspace-settings-menu a')?.href).toBe('https://yaoyao.samien.cn/')
   accountItems[0]!.click(); await wrapper.vm.$nextTick()
   expect(wrapper.get('[data-testid="settings-center"]').attributes('data-page')).toBe('account-profile')
@@ -181,10 +113,7 @@ it('uses the reference Bot list header and keeps mode changes in settings', asyn
   wrapper.unmount()
 })
 
-it('shows Bot tools only in Bot mode and restores keyboard focus after closing', async () => {
-  const normal = await mountShell('/chat')
-  expect(normal.find('.sidebar-tools-trigger').exists()).toBe(false)
-  normal.unmount()
+it('shows Bot tools and restores keyboard focus after closing', async () => {
   const wrapper = await mountShell('/conversations')
   const trigger = wrapper.get<HTMLButtonElement>('.desktop-sidebar .sidebar-tools-trigger')
   await trigger.trigger('click')
@@ -221,9 +150,9 @@ it('opens dedicated Bot settings from tools and routes the existing VM shortcut
 })
 
 
-it.each(['/chat', '/history', '/conversations', '/files'])('opens an independent About dialog from the menu in %s', async path => {
-  const wrapper = await mountShell(path)
-  const trigger = wrapper.get<HTMLButtonElement>(path === '/conversations' ? '.desktop-sidebar .sidebar-account-switcher__main' : '.desktop-sidebar .sidebar-settings-trigger')
+it('opens an independent About dialog from the account menu', async () => {
+  const wrapper = await mountShell('/conversations')
+  const trigger = wrapper.get<HTMLButtonElement>('.desktop-sidebar .sidebar-account-switcher__main')
   await trigger.trigger('click')
   const item = [...document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu button')].find(b => b.textContent?.trim() === '关于')!
   item.click(); await flushPromises()
@@ -277,7 +206,7 @@ it('opens the native updater, prevents duplicate clicks and lets a failed openin
   wrapper.unmount()
 })
 
-it('keeps desktop downloads and restart beside the bell in both workspaces', async () => {
+it('keeps desktop downloads and restart beside the bell', async () => {
   vi.useFakeTimers()
   let state: DesktopUpdateState = { phase: 'checked', installMode: 'restart', currentVersion: '0.4.80', latestVersion: '0.4.81', available: true, received: 0, total: 100, message: '发现更新' }
   let finish!: (state: DesktopUpdateState) => void
@@ -318,9 +247,6 @@ it('keeps desktop downloads and restart beside the bell in both workspaces', asy
     expect(entry().text()).toBe('重新启动')
     expect(entry().classes()).toContain('desktop-update-entry--ready')
     expect(entry().get('button').attributes('title')).toContain('点击重新启动')
-    await wrapper.vm.$router.push('/chat'); await flushPromises()
-    expect(wrapper.find('.sidebar-status-actions .desktop-update-entry').exists()).toBe(true)
-    expect(entry().element.previousElementSibling?.classList.contains('unread-entry')).toBe(true)
     expect(updateAction).toHaveBeenCalledTimes(1)
     await entry().get('button').trigger('click'); await flushPromises()
     expect(updateAction).toHaveBeenLastCalledWith('install')

+ 1 - 1
tests/e2e/bot-panels.spec.ts

@@ -93,7 +93,7 @@ test('robot sidebar, source changes, requests, routines and group boundaries wor
  await create(page,'群聊成员')
  const all=(await(await page.request.get('/api/app/agents')).json()).agents
  const second=all.find((a:any)=>a.name==='群聊成员')
- const capabilities=await(await page.request.get('/api/realtime/capabilities')).json()
+ const capabilities=await(await page.request.get('/api/app/bootstrap')).json()
  const response=await page.request.post('/api/app/conversations',{headers:{'X-CSRF-Token':capabilities.csrfToken,Origin:'http://127.0.0.1:18832'},data:{name:'群聊侧栏验收',memberIds:[first.id,second.id],administratorId:first.id}})
  expect(response.ok(),await response.text()).toBe(true)
  const group=(await response.json()).conversation

+ 1 - 1
tests/e2e/credential-vault.spec.ts

@@ -93,7 +93,7 @@ test('UI approval survives port edits, closing settings and a full server proces
     await expect(page.locator('.desktop-sidebar .sidebar-account-switcher__main')).toBeVisible()
   }
   const settings=async()=>{await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click();await page.getByRole('menuitem',{name:'我的设置',exact:true}).click();await page.getByRole('button',{name:'密码管理',exact:true}).click()}
-  const headers=async()=>({Origin:base,'X-CSRF-Token':(await(await page.request.get(base+'/api/realtime/capabilities')).json()).csrfToken})
+  const headers=async()=>({Origin:base,'X-CSRF-Token':(await(await page.request.get(base+'/api/app/bootstrap')).json()).csrfToken})
   try{
     await start();await login()
     const agentResponse=await page.request.post(base+'/api/app/agents',{headers:await headers(),data:{name:'竹儿测试',profile:'default'}});expect(agentResponse.ok()).toBe(true)

+ 0 - 131
tests/e2e/hermesMedia.spec.ts

@@ -1,131 +0,0 @@
-import { expect, test, type APIRequestContext, type Locator } from '@playwright/test'
-
-const mediaPaths = [
-  '/Users/samien/.hermes/profiles/yaoer/cache/images/openai_codex_gpt-image-2-high_20260902_194820_1d225f08.png',
-  '/Users/samien/.hermes/profiles/yaoer/cache/images/国漫三视图.png',
-]
-const mediaNames = mediaPaths.map(path => path.split('/').at(-1)!)
-const mediaLabels = ['3D 半写实女性四视图', '国漫三视图']
-
-async function signIn(request: APIRequestContext, origin: string) {
-  const bootstrap = await (await request.get('/api/app/bootstrap')).json()
-  if (bootstrap.setupRequired) {
-    const setup = await request.post('/api/app/setup', {
-      headers: { Origin: origin, 'X-CSRF-Token': bootstrap.csrfToken },
-      data: { username: 'admin', password: 'e2e-password' },
-    })
-    expect(setup.ok()).toBe(true)
-    return
-  }
-  const login = await request.post('/api/app/login', {
-    headers: { Origin: origin, 'X-CSRF-Token': bootstrap.csrfToken },
-    data: { username: 'admin', password: 'e2e-password' },
-  })
-  expect(login.ok()).toBe(true)
-}
-
-async function expectDecodedImage(image: Locator) {
-  await expect(image).toBeVisible()
-  await expect.poll(() => image.evaluate(element => {
-    const img = element instanceof HTMLImageElement ? element : element.querySelector('img')
-    return img?.naturalWidth ?? 0
-  })).toBeGreaterThan(0)
-}
-
-test('loads Hermes profile cache images through the Web server and switches their full-size previews', async ({ page, baseURL }, testInfo) => {
-  await signIn(page.request, new URL(baseURL!).origin)
-  // No image interception: this exercises the real Web route, upstream account
-  // authentication, attachment-to-inline response handling, and browser decode.
-  const responses = mediaPaths.map(path => page.waitForResponse(response => (
-    new URL(response.url()).pathname === '/api/files/download' && new URL(response.url()).searchParams.get('path') === path
-  )))
-  await page.goto('/chat/session-media?profile=yaoer')
-  await expect(page).toHaveTitle('瑶儿生成图片验收 · 夭夭 AI')
-
-  for (const [index, name] of mediaLabels.entries()) {
-    const image = page.getByRole('button', { name: `预览图片 ${name}`, exact: true })
-    await image.scrollIntoViewIfNeeded()
-    await expectDecodedImage(image)
-    const response = await responses[index]!
-    expect(response.status()).toBe(200)
-    expect(response.headers()['content-type']).toContain('image/png')
-    expect(response.headers()['content-disposition'] ?? '').not.toMatch(/^attachment(?:;|$)/)
-    expect(new URL(response.url()).origin).toBe(new URL(baseURL!).origin)
-    expect(new URL(response.url()).searchParams.get('profile')).toBe('yaoer')
-  }
-
-  await page.getByRole('button', { name: `预览图片 ${mediaLabels[0]}`, exact: true }).click()
-  const preview = page.getByRole('dialog')
-  await expect(preview).toHaveAccessibleName(`预览 ${mediaNames[0]}`)
-  await expectDecodedImage(preview.getByRole('img', { name: mediaNames[0], exact: true }))
-  await expect(preview.getByRole('button', { name: '下一张媒体' })).toBeVisible()
-
-  await preview.getByRole('button', { name: '下一张媒体' }).click()
-  await expect(preview).toHaveAccessibleName(`预览 ${mediaNames[1]}`)
-  const secondPreview = preview.getByRole('img', { name: mediaNames[1], exact: true })
-  await expectDecodedImage(secondPreview)
-  expect(new URL(await secondPreview.getAttribute('src') || '', baseURL).searchParams.get('path')).toBe(mediaPaths[1])
-  await expect(preview.getByRole('button', { name: '上一张媒体' })).toBeVisible()
-  await expect(preview.getByRole('button', { name: '下一张媒体' })).toBeHidden()
-
-  await page.keyboard.press('ArrowLeft')
-  await expect(preview).toHaveAccessibleName(`预览 ${mediaNames[0]}`)
-  await expectDecodedImage(preview.getByRole('img', { name: mediaNames[0], exact: true }))
-  await expect(preview.getByRole('button', { name: '下一张媒体' })).toBeVisible()
-  await page.screenshot({ path: testInfo.outputPath('hermes-profile-cache-preview.png') })
-  await page.keyboard.press('Escape')
-  await expect(preview).toBeHidden()
-})
-
-test('restores nine user Profile uploads as images and opens the whole batch in the preview', async ({ page, baseURL }, testInfo) => {
-  await signIn(page.request, new URL(baseURL!).origin)
-  await page.goto('/chat/session-user-media?profile=yaoer')
-  const message = page.locator('.message--user')
-  await expect(message).toContainText('读取图片中的提示词')
-  await expect(message).not.toContainText('@image:')
-  await expect(message).not.toContainText('[用户附加图片')
-  await expect(message).not.toContainText('[screenshot]')
-  const images = message.locator('img')
-  await expect(images).toHaveCount(9)
-  for (const image of await images.all()) {
-    await image.scrollIntoViewIfNeeded()
-    await expectDecodedImage(image)
-    const url = new URL(await image.getAttribute('src') || '', baseURL)
-    expect(url.origin).toBe(new URL(baseURL!).origin)
-    expect(url.pathname).toBe('/api/files/download')
-    expect(url.searchParams.get('path')).toContain('/.hermes/profiles/yaoer/images/')
-    expect(url.searchParams.get('profile')).toBe('yaoer')
-  }
-  await page.screenshot({ path: testInfo.outputPath('user-profile-images.png') })
-  await images.first().click()
-  const preview = page.locator('.image-preview-overlay')
-  await expect(preview.locator('.image-preview-counter')).toHaveText('1 / 9')
-  await expectDecodedImage(preview.getByRole('img', { name: '照片-1.png', exact: true }))
-  await preview.getByRole('button', { name: '下一张媒体' }).click()
-  await expect(preview.locator('.image-preview-counter')).toHaveText('2 / 9')
-  await expectDecodedImage(preview.getByRole('img', { name: '照片-2.png', exact: true }))
-  await page.screenshot({ path: testInfo.outputPath('user-profile-image-preview.png') })
-})
-
-test('server permissions reject a previously readable image and retry succeeds after authorization', async ({page,baseURL}) => {
-  const origin=new URL(baseURL!).origin
-  await signIn(page.request,origin)
-  const capabilities=await(await page.request.get('/api/realtime/capabilities')).json()
-  const headers={Origin:origin,'X-CSRF-Token':capabilities.csrfToken}
-  const policy=async(mode:'folders'|'all')=>{
-    const response=await page.request.put('/api/app/settings/file-access',{headers,data:{mode,folders:[]}})
-    expect(response.ok(),await response.text()).toBe(true)
-  }
-  await policy('folders')
-  try {
-    await page.goto('/chat/session-media?profile=yaoer')
-    const failure=page.getByRole('button',{name:`${mediaLabels[0]} · 加载失败,点击重试`,exact:true})
-    await expect(failure).toBeVisible()
-    const denied=await page.request.get('/api/files/download',{params:{path:mediaPaths[0]!,profile:'yaoer',preview:'1'}})
-    expect(denied.status()).toBe(403)
-    await policy('all')
-    await failure.click()
-    await expectDecodedImage(page.getByRole('button',{name:`预览图片 ${mediaLabels[0]}`,exact:true}))
-    await expect(failure).toHaveCount(0)
-  } finally {await policy('all')}
-})

+ 0 - 63
tests/e2e/model-confirmation.spec.ts

@@ -1,63 +0,0 @@
-import { test, expect } from '@playwright/test'
-
-test('model confirmation survives reconnects and failed inputs retain their position after Allow, new replies and reload', async ({ page, browser }) => {
-  const modelCommands: Record<string, unknown>[] = []
-  let nativeApprovals = 0
-  await page.route('**/api/realtime/channels/*/commands', async route => {
-    const command = route.request().postDataJSON()
-    if (command.method === 'approval.respond') nativeApprovals++
-    if (command.method !== 'config.set' || command.params.key !== 'model') return route.continue()
-    modelCommands.push(command.params)
-    const result = command.params.confirm_expensive_model === true
-      ? { key: 'model', value: 'gpt-5.5', scope: 'session' }
-      : { confirm_required: true, confirm_message: '长上下文切换验收:请确认重新读取缓存。' }
-    await route.fulfill({ json: { state: 'confirmed', response: { result } } })
-  })
-  await page.goto('/chat/session-demo?profile=yaoyao')
-  await expect(page.getByRole('heading', { name: '登录夭夭' })).toBeVisible()
-  if (await page.getByRole('heading', { name: '登录夭夭' }).isVisible()) {
-    await page.getByLabel('账号').fill('admin')
-    await page.getByLabel('密码').fill('e2e-password')
-    await page.getByRole('button', { name: '登录', exact: true }).click()
-  }
-  await page.goto('/chat/session-demo?profile=yaoyao')
-  await expect(page.locator('.composer-tool--model')).toContainText('gpt-5.6')
-  await page.locator('.composer-tool--model').click()
-  await page.locator('.model-dialog__item').filter({ hasText: 'gpt-5.5' }).click()
-  // History can be opened without resuming Hermes; sending applies the pending pick.
-  await page.locator('.composer-textarea').fill('等待模型确认')
-  await page.getByRole('button', { name: '发送消息', exact: true }).click()
-  const confirmation = page.locator('.interaction-card--approval')
-  await expect(confirmation).toContainText('长上下文切换验收')
-  for (let i = 0; i < 2; i++) {
-    const resumed = page.waitForResponse(response => response.url().includes('/api/app/chat/sessions/session-demo/events'))
-    await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')))
-    await resumed
-    await expect(confirmation).toBeVisible()
-  }
-  await confirmation.getByRole('button', { name: '允许', exact: true }).click()
-  await expect(confirmation).toBeHidden()
-  expect(modelCommands).toHaveLength(2)
-  expect(modelCommands[1]).toMatchObject({ confirm_expensive_model: true, value: 'gpt-5.5 --provider openai --session' })
-  expect(nativeApprovals).toBe(0)
-  await page.locator('.composer-textarea').fill('模型确认后发送')
-  await page.getByRole('button', { name: '发送消息', exact: true }).click()
-  await expect(page.locator('.message__content').filter({ hasText: '这是来自假 Gateway 的流式回复。' })).toHaveCount(1)
-  expect(modelCommands).toHaveLength(2)
-  const relevantMessages = ['等待模型确认', '模型确认后发送', '这是来自假 Gateway 的流式回复。']
-  const visibleOrder = async () => (await page.locator('.message__content').allTextContents())
-    .map(text => text.trim()).filter(text => relevantMessages.includes(text))
-  await expect.poll(visibleOrder).toEqual(relevantMessages)
-  await page.reload()
-  await expect.poll(visibleOrder).toEqual(relevantMessages)
-  await expect(page.locator('.message--failed').filter({ hasText: '等待模型确认' })).toHaveCount(1)
-
-  // A fresh device gets the accepted transcript, not this browser's unsent outbox.
-  const other = await browser.newContext({ storageState: await page.context().storageState() })
-  try {
-    const otherPage = await other.newPage()
-    await otherPage.goto(page.url())
-    await expect(otherPage.locator('.message__content').filter({ hasText: '模型确认后发送' })).toHaveCount(1)
-    await expect(otherPage.locator('.message__content').filter({ hasText: '等待模型确认' })).toHaveCount(0)
-  } finally { await other.close() }
-})

+ 1 - 1
tests/e2e/npmUpdate.spec.ts

@@ -66,7 +66,7 @@ test('npm update downloads in place, survives reopening, and refreshes only afte
     const signedIn = await page.request.post(origin + '/api/app/setup', { headers: { Origin: origin, 'X-CSRF-Token': boot.csrfToken }, data: { username: 'admin', password: 'npm-e2e-password' } })
     expect(signedIn.ok()).toBe(true)
     page.on('dialog', dialog => { confirmations++; void dialog.dismiss() })
-    await page.goto(origin + '/chat')
+    await page.goto(origin + '/conversations')
     let dialog = await openUpdates()
     await expect(dialog).toContainText('不保留旧版本')
     await expect(dialog.getByRole('button', { name: '回滚上一版本', exact: true })).toHaveCount(0)

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است