Procházet zdrojové kódy

发布 v0.4.18:修复聊天同步与令牌续期并增加检测更新入口

Samien před 2 měsíci
rodič
revize
02a5caef4c
48 změnil soubory, kde provedl 1815 přidání a 136 odebrání
  1. 6 6
      README.md
  2. 11 2
      desktop/main.mjs
  3. 1 0
      desktop/preload.cjs
  4. 53 0
      desktop/update-entry.test.mjs
  5. 1 0
      desktop/update-window.test.mjs
  6. 1 1
      docker.env.example
  7. 7 7
      docs/docker-install.md
  8. 43 0
      docs/releases/v0.4.18.md
  9. 30 0
      docs/verification/2026-09-14-desktop-csrf/README.md
  10. 10 0
      docs/verification/2026-09-14-desktop-csrf/results.txt
  11. 6 0
      docs/verification/2026-09-14-desktop-csrf/verify.sh
  12. 37 0
      docs/verification/2026-09-14-ordinary-chat-consistency/README.md
  13. 117 0
      docs/verification/2026-09-14-ordinary-chat-consistency/baseline.txt
  14. 32 0
      docs/verification/2026-09-14-ordinary-chat-consistency/results.txt
  15. 10 0
      docs/verification/2026-09-14-ordinary-chat-consistency/verify.sh
  16. 2 2
      package-lock.json
  17. 1 1
      package.json
  18. 3 3
      release.json
  19. 1 1
      src/client/api/auth.ts
  20. 98 0
      src/client/api/chatTranscript.ts
  21. 121 35
      src/client/api/client.ts
  22. 3 2
      src/client/api/httpRealtime.ts
  23. 2 1
      src/client/api/realtime.ts
  24. 61 0
      src/client/components/app/UpdateCheckDialog.vue
  25. 38 5
      src/client/components/app/WorkspaceShell.vue
  26. 1 0
      src/client/env.d.ts
  27. 124 35
      src/client/stores/chat.ts
  28. 5 2
      src/server/app.ts
  29. 34 7
      src/server/chatCache.ts
  30. 13 4
      src/server/chatEventProjection.ts
  31. 73 0
      src/server/chatTranscriptApi.ts
  32. 146 0
      src/server/chatTranscriptStore.ts
  33. 2 0
      src/server/realtimeApi.ts
  34. 3 3
      src/server/realtimeBroker.ts
  35. 8 0
      src/server/routes.ts
  36. 60 0
      src/shared/chatTranscript.ts
  37. 2 0
      src/shared/types.ts
  38. 95 0
      tests/client/chatCrossClientSync.test.ts
  39. 261 0
      tests/client/csrfRecovery.test.ts
  40. 56 0
      tests/client/updateCheckDialog.test.ts
  41. 48 4
      tests/client/workspaceShell.test.ts
  42. 2 2
      tests/e2e/serverIdentity.spec.ts
  43. 3 3
      tests/e2e/team-tools.spec.ts
  44. 55 6
      tests/e2e/workspace-chat.spec.ts
  45. 1 1
      tests/live/dockerPlatform.live.test.ts
  46. 2 2
      tests/live/localVm.live.test.ts
  47. 22 1
      tests/server/app.test.ts
  48. 104 0
      tests/server/chatTranscript.test.ts

+ 6 - 6
README.md

@@ -1,6 +1,6 @@
 # 夭夭 AI
 
-当前 Web 与 macOS 桌面发布版本:**v0.4.17**。桌面版提供 Apple Silicon(arm64)DMG,详见 [发布说明](docs/releases/v0.4.17.md)。
+当前 Web 与 macOS 桌面发布版本:**v0.4.18**。桌面版提供 Apple Silicon(arm64)DMG,详见 [发布说明](docs/releases/v0.4.18.md)。
 
 夭夭 AI 为网页、iOS 和安卓提供统一的 Agent、群聊、文件库及语音配置服务。Hermes 通过标准 9119 HTTP/WebSocket 接口执行任务。
 
@@ -38,7 +38,7 @@ Web 数据默认保存在 `~/.yaoyao`,可用 `YAOYAO_HOME` 指定(兼容 `HE
 
 ## macOS 桌面版
 
-在 [v0.4.17 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.17) 下载 `Yaoyao-0.4.17-arm64.dmg`,将“夭夭”拖到应用程序后打开。首次启动会核对并同步配套本机 Web 服务;普通退出保留后台运行,“停止后台服务并退出”可完整停止本应用管理的后台。详细说明见 [macOS App](docs/macos-app.md)。
+在 [v0.4.18 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.18) 下载 `Yaoyao-0.4.18-arm64.dmg`,将“夭夭”拖到应用程序后打开。首次启动会核对并同步配套本机 Web 服务;普通退出保留后台运行,“停止后台服务并退出”可完整停止本应用管理的后台。详细说明见 [macOS App](docs/macos-app.md)。
 
 此 DMG 使用 Apple Development 开发签名,未做 Apple 公证。
 
@@ -48,11 +48,11 @@ Web 数据默认保存在 `~/.yaoyao`,可用 `YAOYAO_HOME` 指定(兼容 `HE
 
 | 镜像 | 架构 |
 | --- | --- |
-| `samienluo/yaoyao:v0.4.17-amd` | AMD64 |
-| `samienluo/yaoyao:v0.4.17` | 自动匹配 AMD64 / ARM64 |
-| `samienluo/yaoyao:latest` | 最新稳定版通用镜像,当前与 `v0.4.17` 相同 |
+| `samienluo/yaoyao:v0.4.18-amd` | AMD64 |
+| `samienluo/yaoyao:v0.4.18` | 自动匹配 AMD64 / ARM64 |
+| `samienluo/yaoyao:latest` | 最新稳定版通用镜像,当前与 `v0.4.18` 相同 |
 
-准备好 Docker Engine/Compose 和容器可访问的 Hermes 9119 服务,在仓库目录将 `docker.env.example` 复制为 `docker.env`。配置上游地址,并设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.17`(或 `samienluo/yaoyao:latest`),即可使用远程镜像:
+准备好 Docker Engine/Compose 和容器可访问的 Hermes 9119 服务,在仓库目录将 `docker.env.example` 复制为 `docker.env`。配置上游地址,并设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.18`(或 `samienluo/yaoyao:latest`),即可使用远程镜像:
 
 ```sh
 docker compose --env-file docker.env pull web

+ 11 - 2
desktop/main.mjs

@@ -54,6 +54,15 @@ else {
   })
   const trustedUpdate = event => event.sender === updateWindow?.webContents
     && event.senderFrame === updateWindow.webContents.mainFrame && event.senderFrame.url === updateURL
+  ipcMain.handle('desktop:updates', async event => {
+    let trusted = false
+    try {
+      trusted = event.sender === window?.webContents && event.senderFrame === window.webContents.mainFrame
+        && manager?.state.phase === 'ready' && new URL(event.senderFrame.url).origin === manager.state.url
+    } catch { /* Only the main local application page may open the updater. */ }
+    if (!trusted || closing || quitting || !updater) throw new Error('不允许此页面打开 App 更新')
+    await showUpdates()
+  })
   for (const action of ['state', 'check', 'download', 'cancel', 'open', 'folder', 'release']) {
     ipcMain.handle(`desktop-update:${action}`, async event => {
       if (!trustedUpdate(event) || closing || quitting) throw new Error('不允许此页面操作 App 更新')
@@ -68,7 +77,7 @@ else {
       else { const error = await shell.openPath(path); if (error) throw new Error(error) }
     })
   }
-  function showUpdates() {
+  async function showUpdates() {
     if (closing || quitting) return
     if (updateWindow && !updateWindow.isDestroyed()) { updateWindow.show(); updateWindow.focus(); return }
     updateWindow = new BrowserWindow({ title: 'App 更新 · 夭夭', width: 640, height: 620, minWidth: 360, minHeight: 440, show: false,
@@ -80,7 +89,7 @@ else {
     updateWindow.webContents.on('will-attach-webview', event => event.preventDefault())
     updateWindow.on('closed', () => { updater.cancel(); updateWindow = undefined })
     updateWindow.once('ready-to-show', () => updateWindow?.show())
-    void updateWindow.loadURL(updateURL)
+    await updateWindow.loadURL(updateURL)
   }
 
   function show() {

+ 1 - 0
desktop/preload.cjs

@@ -3,6 +3,7 @@ contextBridge.exposeInMainWorld('yaoyaoDesktop', Object.freeze({
   status: () => ipcRenderer.invoke('desktop:status'),
   retry: () => ipcRenderer.invoke('desktop:retry'),
   logs: () => ipcRenderer.invoke('desktop:logs'),
+  openUpdates: () => ipcRenderer.invoke('desktop:updates'),
   openComputer: id => ipcRenderer.invoke('desktop-computer:open', id),
   computerClosed: () => ipcRenderer.invoke('desktop-computer:closed'),
   onComputerClose: callback => {

+ 53 - 0
desktop/update-entry.test.mjs

@@ -0,0 +1,53 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, readFile, writeFile, realpath, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { createServer } from 'node:http'
+import { _electron as electron, expect } from '@playwright/test'
+import { dataKey } from './service-manager.mjs'
+
+test('only the main local app can open the native updater and repeated requests reuse its window', { timeout: 60000 }, async () => {
+  const root = resolve(import.meta.dirname, '..')
+  const home = await realpath(await mkdtemp(join(tmpdir(), 'yaoyao-update-entry-')))
+  const version = JSON.parse(await readFile(join(root, '.desktop-build/release.json'), 'utf8')).webVersion
+  const identity = { protocol: 1, instanceId: 'update-entry', pid: process.pid, dataKey: dataKey(home), version }
+  // Let Playwright attach to the boot renderer before the fixture changes its URL.
+  let releaseIdentity
+  const identityReady = new Promise(resolve => { releaseIdentity = resolve })
+  const server = createServer(async (req, res) => {
+    if (req.url === '/desktop/service') { await identityReady; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(identity)) }
+    else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('<title>Update entry fixture</title><button onclick="window.yaoyaoDesktop.openUpdates()">检测更新</button>') }
+  })
+  await new Promise(done => server.listen(0, '127.0.0.1', done))
+  const origin = `http://127.0.0.1:${server.address().port}`
+  await writeFile(join(home, 'service-instance.json'), JSON.stringify({ ...identity, url: origin, token: 'fixture' }))
+  let app
+  try {
+    app = await electron.launch({ args: [root], cwd: root, env: { ...process.env, HERMES_YAOYAO_DESKTOP_TEST_HOME: home, HERMES_YAOYAO_DESKTOP_PORT: String(server.address().port), HERMES_YAOYAO_DESKTOP_TEST_SYNC: '0' } })
+    const page = await app.firstWindow()
+    releaseIdentity()
+    await page.waitForURL(origin + '/**')
+    await app.evaluate(({ net }) => { net.fetch = async () => new Response('', { status: 403 }) })
+    const opened = app.waitForEvent('window')
+    await page.getByRole('button', { name: '检测更新', exact: true }).click()
+    const updates = await opened
+    await expect(updates.getByRole('alert')).toContainText('GitHub 请求受限')
+    await page.evaluate(() => window.yaoyaoDesktop.openUpdates())
+    assert.equal(app.windows().length, 2)
+    const denied = await app.evaluate(async ({ BrowserWindow }, { origin, preload }) => {
+      const outsider = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload } })
+      try {
+        await outsider.loadURL(origin)
+        return await outsider.webContents.executeJavaScript('window.yaoyaoDesktop.openUpdates().then(() => false, () => true)')
+      } finally { outsider.destroy() }
+    }, { origin, preload: join(root, 'desktop/preload.cjs') })
+    assert.equal(denied, true)
+    assert.equal(server.listening, true)
+  } finally {
+    releaseIdentity()
+    await app?.close().catch(() => {})
+    await new Promise(done => server.close(done))
+    await rm(home, { recursive: true, force: true })
+  }
+})

+ 1 - 0
desktop/update-window.test.mjs

@@ -29,6 +29,7 @@ test('native update window works without a Web service, verifies a real DMG and
     const boot = await app.firstWindow()
     await boot.locator('#status[role="alert"]').waitFor()
     assert.equal(await boot.evaluate(() => typeof window.yaoyaoUpdate), 'undefined')
+    assert.equal(await boot.evaluate(() => window.yaoyaoDesktop.openUpdates().then(() => false, () => true)), true)
     // Even another renderer carrying the real bridge cannot acquire update privileges.
     const denied = await app.evaluate(async ({ BrowserWindow }, preload) => {
       const outsider = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload } })

+ 1 - 1
docker.env.example

@@ -3,7 +3,7 @@ HERMES_YAOYAO_BIND_ADDRESS=127.0.0.1
 HERMES_YAOYAO_PUBLISHED_PORT=15300
 # 远程通用镜像支持 AMD64 / ARM64;每次发布更新 latest 并保留旧版本标签。
 # HERMES_YAOYAO_IMAGE=samienluo/yaoyao:latest
-# 固定版本:samienluo/yaoyao:v0.4.17;仅 AMD64:samienluo/yaoyao:v0.4.17-amd。
+# 固定版本:samienluo/yaoyao:v0.4.18;仅 AMD64:samienluo/yaoyao:v0.4.18-amd。
 # 留空时使用本地构建名称 yaoyao:local。
 # YAOYAO_DESKTOP_IMAGE=hermes-yaoyao-desktop:0.4.0
 # Cursor Universal 兼容桌面的本地构建名称;基础镜像在 deploy/computer/Dockerfile.cursor 中固定。

+ 7 - 7
docs/docker-install.md

@@ -12,14 +12,14 @@
 
 | 标签 | 架构 |
 | --- | --- |
-| `v0.4.17-amd` | `linux/amd64` |
-| `v0.4.17` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
-| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.17` 相同的镜像 |
+| `v0.4.18-amd` | `linux/amd64` |
+| `v0.4.18` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
+| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.18` 相同的镜像 |
 
 ```sh
-docker pull samienluo/yaoyao:v0.4.17
+docker pull samienluo/yaoyao:v0.4.18
 # 需要固定 AMD64 时:
-docker pull samienluo/yaoyao:v0.4.17-amd
+docker pull samienluo/yaoyao:v0.4.18-amd
 ```
 
 每次新版本发布都会更新 `latest`,旧版本标签继续保留。需要固定部署版本时使用具体版本标签。
@@ -34,7 +34,7 @@ cp docker.env.example docker.env
 
 | 配置 | 用途 |
 | --- | --- |
-| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.17` 或 `samienluo/yaoyao:latest`;未设置时使用本地构建名称 |
+| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.18` 或 `samienluo/yaoyao:latest`;未设置时使用本地构建名称 |
 | `HERMES_YAOYAO_UPSTREAM` | Hermes 上游地址,默认 `http://host.docker.internal:9119` |
 | `HERMES_YAOYAO_BIND_ADDRESS` | Web 的宿主机发布地址,默认 `127.0.0.1`;局域网访问可设为 `0.0.0.0` |
 | `HERMES_YAOYAO_PUBLISHED_PORT` | 宿主机 Web 端口,默认 `15300` |
@@ -152,7 +152,7 @@ curl --fail http://127.0.0.1:15300/healthz
 使用 Docker Hub 发布镜像时,在 `docker.env` 设置:
 
 ```dotenv
-HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.17
+HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.18
 YAOYAO_CURSOR_DESKTOP_IMAGE=samienluo/yaoyao-desktop:v0.4.12-cursor-amd
 ```
 

+ 43 - 0
docs/releases/v0.4.18.md

@@ -0,0 +1,43 @@
+# 夭夭 AI v0.4.18
+
+本次发布 Web、macOS Apple Silicon 桌面版、Android 1.3(170)及 Docker Web 双架构镜像。
+
+## 更新内容
+
+- 修复普通聊天后台历史补齐后,切回会话仍显示旧内容的问题。历史请求、分页与流式更新交错时,保留当前回复和已加载的旧消息,避免迟到响应覆盖新状态。
+- 修复桌面长期打开后安全令牌过期导致发送消息或保存设置失败的问题。明确收到令牌失效拒绝时自动续领并重试一次,同窗口请求合并续领,多窗口协调签发;取消、超时或切换账号后不重放旧操作。
+- 账号菜单新增“检测更新”。桌面版可直接打开原生更新窗口,网页版管理员可查看当前版本、最新版本及更新说明,并进入更新设置。重复点击复用已有更新窗口。
+- 精简 Bot 模式的账号与设置入口,减少重复按钮,并完善桌面和窄屏菜单的键盘操作与焦点恢复。
+- 增加普通聊天统一消息记录、可重放事件流和恢复检查点的试验实现。Android 1.3(170)加入对应能力识别与本地检查点存储,默认继续使用现有同步协议。
+
+## 升级说明
+
+- 普通聊天新同步协议默认关闭,仅设置 `HERMES_YAOYAO_ORDINARY_TRANSCRIPTS=1` 后启用。该试验功能尚未完成全部跨端联调、特殊过程事件与断线分页边界验收,本次稳定使用路径保持原有协议。
+- Android 本地数据库增加恢复检查点表,沿用正式发布密钥,可覆盖升级已有安装。
+- 数据目录继续使用 `.yaoyao`。升级前备份数据与密钥,保留已有数据卷、执行节点及独立电脑配置。
+- 主项目采用 Apache-2.0,第三方组件保留各自许可与署名。
+
+## 下载
+
+- `Yaoyao-0.4.18-arm64.dmg`:macOS Apple Silicon,Apple Development 开发签名,未公证。
+- `Yaoyao-1.3-170-android.apk`:Android 12 及以上,正式签名。源码提交 `9c0f1d3`。
+- `Yaoyao-0.4.18-source.tar.gz`:Web/桌面源码及部署配置。
+- `SHA256SUMS.txt`:以上附件的 SHA-256 校验值。
+
+## Docker Hub
+
+| 镜像 | 架构 |
+| --- | --- |
+| `samienluo/yaoyao:v0.4.18-amd` | `linux/amd64` |
+| `samienluo/yaoyao:v0.4.18` | `linux/amd64`、`linux/arm64` |
+| `samienluo/yaoyao:latest` | 版本镜像验证后指向同一通用镜像 |
+
+```sh
+docker pull samienluo/yaoyao:v0.4.18
+docker compose --env-file docker.env pull web
+docker compose --env-file docker.env up -d --no-build web
+```
+
+Compose 中设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.18`。独立电脑镜像沿用现有配置,保留旧版本标签与附件。Docker 镜像发布到 Docker Hub,GitHub 不上传镜像归档。
+
+最终附件摘要、镜像摘要和运行验证记录发布在 [GitHub 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.18)。

+ 30 - 0
docs/verification/2026-09-14-desktop-csrf/README.md

@@ -0,0 +1,30 @@
+# 桌面长期打开后的 CSRF 自动恢复
+
+基线:主分支 `a23f030`(v0.4.17)。按用户要求直接在主分支开发。
+
+## 原因与修改
+
+本地登录 Cookie 有效期为 30 天,CSRF Cookie 为 8 小时。页面一直保留旧的内存令牌;Cookie 到期后,后续写入请求收到 `403 invalid_csrf`,此前没有自动恢复路径。
+
+统一 API 客户端现在会在缺少令牌时准备令牌,或在收到明确的 `403 invalid_csrf` 后续领,再重试原请求一次。续领使用 `GET /api/app/bootstrap?csrfOnly=1`,新服务端仅返回 CSRF 令牌与当前账号 ID,不访问 9119、不加载机器人列表;旧服务端忽略参数后返回的完整 bootstrap 仍可读取。响应禁止缓存。
+
+同一窗口的请求共用一次续领。支持 Web Locks 的同源窗口还会串行签发,避免同时收到两个新 Cookie 相互覆盖;跨窗口令牌通知触发身份核验,而不是直接拿另一窗口的令牌重放操作。
+
+原 Cookie 有效期、签名校验、Origin 校验和登录权限保持原规则。只有业务执行前的明确 CSRF 拒绝才允许重试;网络失败、超时、权限拒绝和一般服务端错误不会自动重试。原请求 ID、请求体和附件保持一致。取消、超时或切换账号后不会重放旧操作。
+
+## 验证
+
+运行:
+
+```sh
+bash docs/verification/2026-09-14-desktop-csrf/verify.sh
+```
+
+- 使用真实 `CsrfProtection` 签名逻辑及模拟浏览器 Cookie 时钟,将时间推进到 8 小时之后;第一次请求被 CSRF 拦截,自动续领后成功,业务执行计数为 1。
+- 普通聊天、Bot 消息和设置并发时只续领一次;晚到的旧令牌拒绝复用已经更新的令牌。
+- 覆盖旧服务端完整 bootstrap、缺失令牌、续领失败、重复拒绝、网络失败、原请求超时、取消、附件快照和账号切换。
+- 覆盖多窗口 Cookie 签发串行和跨账号令牌通知。
+- 实际 HTTP 路由验证匿名、管理员、普通账号均能续领,且不访问上游;保留既有 Origin、CSRF 和服务重启校验测试。
+- 全部客户端测试及相关服务端测试 **66 个文件、378 项通过**;类型检查通过。
+
+此次为自动化时钟和协议测试,没有让真实桌面程序等待 8 小时,也没有重启用户服务或更新安装包。结果见 `results.txt`。

+ 10 - 0
docs/verification/2026-09-14-desktop-csrf/results.txt

@@ -0,0 +1,10 @@
+Command: NODE_OPTIONS=--no-experimental-webstorage npm test -- tests/client tests/server/app.test.ts tests/server/security.test.ts tests/server/realtimeApi.test.ts
+
+Test Files  66 passed (66)
+      Tests  378 passed (378)
+   Start at  08:04:13
+   Duration  4.53s (transform 5.72s, setup 496ms, collect 20.41s, tests 5.13s, environment 20.59s, prepare 2.59s)
+
+> yaoyao@0.4.17 typecheck
+> vue-tsc -b && tsc --noEmit -p tsconfig.server.json
+Typecheck exit code: 0

+ 6 - 0
docs/verification/2026-09-14-desktop-csrf/verify.sh

@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
+export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--no-experimental-webstorage"
+npm test -- tests/client tests/server/app.test.ts tests/server/security.test.ts tests/server/realtimeApi.test.ts
+npm run typecheck

+ 37 - 0
docs/verification/2026-09-14-ordinary-chat-consistency/README.md

@@ -0,0 +1,37 @@
+# 普通聊天跨端历史一致性排查
+
+基线:主分支 `29e60b5`(v0.4.17)。修复分支:`codex/ordinary-chat-consistency`。
+
+## 已复现的问题
+
+Web 收到 `sessions.changed / cache.synced` 时只刷新当前打开的会话。后台会话保留 `historySynced=true`,切回后跳过历史读取,继续展示已过时的中间结果。该判断来自 `c17b5f1`(2026-09-10),早于本次十路并发改动。
+
+此外,SSE 会替换 Web 的会话状态对象。历史读取若仍持有请求前的对象,就会把结果写到旧对象中,页面内容和加载状态无法正确更新。历史请求或分页进行中收到的新补齐通知也可能被忽略。
+
+## 修复
+
+- 按 Profile 和 session ID 标记对应缓存失效;后台会话保留可读内容,在再次选择时读取最新历史。
+- 补齐通知使用本地递增版本;请求期间的新通知合并为一次后续读取,不接受早于新通知的快照。
+- 历史读取和分页在异步返回后重新定位当前状态,合并现有流式尾部及已加载旧消息。
+- 历史请求采用单调递增编号,离开账号或被较新请求替代的结果不能修改新状态。
+- 不修改 Bot 调度、发送幂等规则或服务端数据库。
+
+## 验证结果
+
+`tests/client/chatCrossClientSync.test.ts` 的 4 个新增场景在原主线代码上全部失败(另外 12 项原测试通过),修复后通过。对照期间仅临时替换独立 worktree 的 Web store 文件,并在 `finally` 恢复修复版本。
+
+新增场景:后台会话补齐后重新进入;补齐通知与迟到快照交错;SSE 替换状态期间合并历史并保留流式回复;分页期间补齐且保留旧消息。
+
+相关 10 个测试文件共 **125 项全部通过**,`npm run typecheck` 通过。执行:
+
+```sh
+bash docs/verification/2026-09-14-ordinary-chat-consistency/verify.sh
+```
+
+原主线失败记录见 `baseline.txt`,修复后结果见 `results.txt`。
+
+## 线上对照范围
+
+沿用用户先前提供的服务与账号,只读抽查最近两条普通聊天。分别包含 68 条和 2 条记录;Web 本地历史接口与原始历史接口的角色和正文逐条一致。部分投影消息的 ID 与原始数据库 ID 不同,但此次对照中正文相同。登录会话已退出,原始业务数据仅保存在权限受限的临时目录,没有提交到仓库。
+
+用户尚未指定实际出现差异的会话,因此以上抽查不能证明所有会话均无差异,也未在用户 iPhone 上核对其缓存。本次仅修改已复现的 Web 问题,iOS 代码未修改;未合并或部署此修复。

+ 117 - 0
docs/verification/2026-09-14-ordinary-chat-consistency/baseline.txt

@@ -0,0 +1,117 @@
+
+> yaoyao@0.4.17 test
+> vitest run tests/client/chatCrossClientSync.test.ts
+
+
+ RUN  v3.2.7 /Users/samien/git/ordinary-chat-consistency/yaoyao
+
+ ❯ tests/client/chatCrossClientSync.test.ts (16 tests | 4 failed) 4256ms
+   ✓ cross-client chat subscriptions > subscribes a viewer before another device starts, then shows thinking, tools, text and completion 6ms
+   ✓ cross-client chat subscriptions > restores a run opened before its first text, so tool events are not dropped 1ms
+   ✓ cross-client chat subscriptions > restores a partial answer and appends later deltas without an extra row 1ms
+   ✓ cross-client chat subscriptions > resubscribes an idle viewer after disconnection and discovers a remote run 1ms
+   ✓ cross-client chat subscriptions > does not repeatedly resume a subscribed session when revisiting it 0ms
+   × cross-client chat subscriptions > reconciles a background session after cache synchronization before reusing it 1012ms
+     → expected [ '第一个问题', '旧的中间结果' ] to deeply equal [ '第一个问题', '后台完成的完整结果' ]
+   × cross-client chat subscriptions > coalesces history invalidations that arrive while an older snapshot is loading 1056ms
+     → expected [ '已过时快照' ] to deeply equal [ '较新完整历史' ]
+   × cross-client chat subscriptions > merges synchronized history into the current route when SSE replaces its state during the read 1061ms
+     → expected '旧正文' to be '之前的完整正文' // Object.is equality
+   × cross-client chat subscriptions > keeps loaded older messages and follows up a synchronization received during pagination 1007ms
+     → expected [ '旧的最新页' ] to deeply equal [ '之前加载的老消息', '补齐后的最新页' ]
+   ✓ cross-client chat subscriptions > reconciles synchronized history before a delayed submit receipt without duplicating or demoting the user row 107ms
+   ✓ cross-client chat subscriptions > settles a run and clears an interaction completed while the viewer was offline 2ms
+   ✓ cross-client chat subscriptions > does not duplicate completed history from a retained inactive snapshot 0ms
+   ✓ cross-client chat subscriptions > keeps history-only sessions unattached with owned=false 0ms
+   ✓ cross-client chat subscriptions > keeps history-only sessions unattached with owned=undefined 0ms
+   ✓ cross-client chat subscriptions > never creates a runtime for an unsent draft on ready 0ms
+   ✓ cross-client chat subscriptions > retains readable history when subscribing fails and can retry on selection 0ms
+
+⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
+
+ FAIL  tests/client/chatCrossClientSync.test.ts > cross-client chat subscriptions > reconciles a background session after cache synchronization before reusing it
+AssertionError: expected [ '第一个问题', '旧的中间结果' ] to deeply equal [ '第一个问题', '后台完成的完整结果' ]
+
+- Expected
++ Received
+
+  [
+    "第一个问题",
+-   "后台完成的完整结果",
++   "旧的中间结果",
+  ]
+
+ ❯ tests/client/chatCrossClientSync.test.ts:136:82
+    134|     expect(chat.messages).toEqual([])
+    135|     await chat.selectSession(first, 'alpha')
+    136|     await vi.waitFor(() => expect(chat.messages.map(message => message…
+       |                                                                                  ^
+    137|     expect(realtime.request.mock.calls.filter(([method]) => method ===…
+    138|   })
+
+⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯
+
+ FAIL  tests/client/chatCrossClientSync.test.ts > cross-client chat subscriptions > coalesces history invalidations that arrive while an older snapshot is loading
+AssertionError: expected [ '已过时快照' ] to deeply equal [ '较新完整历史' ]
+
+- Expected
++ Received
+
+  [
+-   "较新完整历史",
++   "已过时快照",
+  ]
+
+ ❯ tests/client/chatCrossClientSync.test.ts:156:82
+    154|     emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha…
+    155|     release(page('已过时快照'))
+    156|     await vi.waitFor(() => expect(chat.messages.map(message => message…
+       |                                                                                  ^
+    157|     expect(api.getMessages).toHaveBeenCalledTimes(3)
+    158|     expect(chat.activeRouteState?.isLoadingHistory).toBe(false)
+
+⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/4]⎯
+
+ FAIL  tests/client/chatCrossClientSync.test.ts > cross-client chat subscriptions > merges synchronized history into the current route when SSE replaces its state during the read
+AssertionError: expected '旧正文' to be '之前的完整正文' // Object.is equality
+
+Expected: "之前的完整正文"
+Received: "旧正文"
+
+ ❯ tests/client/chatCrossClientSync.test.ts:180:106
+    178|     emit('message.delta', { text: '新回复正在继续' })
+    179|     release(page('之前的完整正文'))
+    180|     await vi.waitFor(() => expect(chat.messages.find(message => messag…
+       |                                                                                                          ^
+    181|     expect(chat.messages.at(-1)?.content).toBe('新回复正在继续')
+    182|     expect(chat.isStreaming).toBe(true)
+
+⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/4]⎯
+
+ FAIL  tests/client/chatCrossClientSync.test.ts > cross-client chat subscriptions > keeps loaded older messages and follows up a synchronization received during pagination
+AssertionError: expected [ '旧的最新页' ] to deeply equal [ '之前加载的老消息', '补齐后的最新页' ]
+
+- Expected
++ Received
+
+  [
+-   "之前加载的老消息",
+-   "补齐后的最新页",
++   "旧的最新页",
+  ]
+
+ ❯ tests/client/chatCrossClientSync.test.ts:204:82
+    202|       role: 'user', content: '之前加载的老消息', timestamp: 1, stage: 'settled…
+    203|     await older
+    204|     await vi.waitFor(() => expect(chat.messages.map(message => message…
+       |                                                                                  ^
+    205|     expect(api.getMessages).toHaveBeenCalledTimes(3)
+    206|     expect(chat.activeRouteState?.isLoadingHistory).toBe(false)
+
+⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/4]⎯
+
+
+ Test Files  1 failed (1)
+      Tests  4 failed | 12 passed (16)
+   Start at  07:06:49
+   Duration  4.66s (transform 70ms, setup 10ms, collect 101ms, tests 4.26s, environment 148ms, prepare 28ms)

+ 32 - 0
docs/verification/2026-09-14-ordinary-chat-consistency/results.txt

@@ -0,0 +1,32 @@
+
+> yaoyao@0.4.17 test
+> vitest run tests/client/chatCrossClientSync.test.ts tests/client/chatLifecycle.test.ts tests/client/chatStore.test.ts tests/client/chatModelSync.test.ts tests/client/chatProtocol.test.ts tests/client/sessionProtocol.test.ts tests/server/ordinaryChatLocal.test.ts tests/server/chatCache.test.ts tests/server/chatCachePagination.test.ts tests/server/realtimeBroker.test.ts
+
+
+ RUN  v3.2.7 /Users/samien/git/ordinary-chat-consistency/yaoyao
+
+ ✓ tests/server/chatCachePagination.test.ts (4 tests) 59ms
+ ✓ tests/client/sessionProtocol.test.ts (1 test) 5ms
+ ✓ tests/client/chatStore.test.ts (20 tests) 6ms
+ ✓ tests/client/chatProtocol.test.ts (6 tests) 10ms
+ ✓ tests/client/chatModelSync.test.ts (8 tests) 11ms
+ ✓ tests/client/chatLifecycle.test.ts (8 tests) 6ms
+ ✓ tests/server/ordinaryChatLocal.test.ts (9 tests) 310ms
+ ✓ tests/server/chatCache.test.ts (29 tests) 442ms
+ ✓ tests/client/chatCrossClientSync.test.ts (16 tests) 383ms
+ ✓ tests/server/realtimeBroker.test.ts (24 tests) 1682ms
+   ✓ realtime broker > recovers the upstream replay ring without losing offline deltas  569ms
+   ✓ realtime broker > reports reset when upstream history was truncated  522ms
+
+ Test Files  10 passed (10)
+      Tests  125 passed (125)
+   Start at  07:08:17
+   Duration  2.15s (transform 379ms, setup 71ms, collect 825ms, tests 2.92s, environment 1.50s, prepare 378ms)
+
+
+
+> yaoyao@0.4.17 typecheck
+> vue-tsc -b && tsc --noEmit -p tsconfig.server.json
+
+
+Typecheck exit code: 0

+ 10 - 0
docs/verification/2026-09-14-ordinary-chat-consistency/verify.sh

@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
+export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--no-experimental-webstorage"
+npm test -- tests/client/chatCrossClientSync.test.ts tests/client/chatLifecycle.test.ts \
+  tests/client/chatStore.test.ts tests/client/chatModelSync.test.ts \
+  tests/client/chatProtocol.test.ts tests/client/sessionProtocol.test.ts \
+  tests/server/ordinaryChatLocal.test.ts tests/server/chatCache.test.ts \
+  tests/server/chatCachePagination.test.ts tests/server/realtimeBroker.test.ts
+npm run typecheck

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "yaoyao",
-  "version": "0.4.17",
+  "version": "0.4.18",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "yaoyao",
-      "version": "0.4.17",
+      "version": "0.4.18",
       "license": "Apache-2.0",
       "dependencies": {
         "@koa/bodyparser": "^5.0.0",

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "yaoyao",
-  "version": "0.4.17",
+  "version": "0.4.18",
   "private": true,
   "license": "Apache-2.0",
   "description": "夭夭 AI:聊天、多 Agent 团队、文件库与电脑工作空间",

+ 3 - 3
release.json

@@ -1,6 +1,6 @@
 {
   "schemaVersion": 1,
-  "releaseVersion": "0.4.17",
-  "webVersion": "0.4.17",
-  "gitTag": "v0.4.17"
+  "releaseVersion": "0.4.18",
+  "webVersion": "0.4.18",
+  "gitTag": "v0.4.18"
 }

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

@@ -25,7 +25,7 @@ function normalizeBootstrap(payload: unknown): BootstrapResponse {
     serverIdentity: serverIdentityValue(root.serverIdentity),
   }
   if (rawUser) response.user = normalizeUser(rawUser)
-  setApiCsrfToken(csrfToken)
+  setApiCsrfToken(csrfToken, response.user?.id ?? (authRequired ? null : 'local'))
   return response
 }
 

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

@@ -0,0 +1,98 @@
+import { apiRequest } from './client'
+import { SSEParser } from '@shared/sse'
+import { applyTranscriptEvent, CHAT_TRANSCRIPT_FEATURE, TranscriptGap,
+  type TranscriptEvent, type TranscriptMessage, type TranscriptSnapshot } from '@shared/chatTranscript'
+
+export class ChatTranscriptClient {
+  private abort = new AbortController()
+  private messages: TranscriptMessage[] = []
+  private cursor = 0
+  private epoch = ''
+  private snapshot?: TranscriptSnapshot
+  private fetchingOlder = false
+  constructor(readonly profile:string,readonly sessionId:string,
+    readonly changed:(snapshot:TranscriptSnapshot)=>Promise<void>,readonly failed:(error:Error)=>void,
+    readonly initialCount=150){}
+  static async supported():Promise<boolean>{
+    try{return (await apiRequest<{features:string[]}>('/api/app/chat/capabilities')).features.includes(CHAT_TRANSCRIPT_FEATURE)}catch{return false}
+  }
+  close(){this.abort.abort()}
+  restore(value:TranscriptSnapshot){if(value.profile===this.profile&&value.sessionId===this.sessionId){this.snapshot=value;this.messages=value.messages;this.cursor=value.cursor;this.epoch=value.epoch}}
+  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 publish(){if(this.snapshot&&!this.abort.signal.aborted)await this.changed({...this.snapshot,messages:this.messages,cursor:this.cursor,epoch:this.epoch})}
+  private async hydrate(){
+    const page=await this.page()
+    if(this.abort.signal.aborted)return
+    const first=page.messages[0]?.seq??Infinity,deleted=new Set(page.deletedIds??[])
+    const old=this.epoch===page.epoch?this.messages.filter(m=>m.seq<first&&!deleted.has(m.id)):[]
+    this.messages=[...old,...page.messages];this.epoch=page.epoch;this.cursor=page.cursor;this.snapshot=page
+    // Upgrade already loaded legacy pages before replacing the visible cache.
+    while(this.messages.length<this.initialCount&&this.snapshot.hasOlder&&this.messages.length){
+      const older=await this.page(this.messages[0]!.seq)
+      if(older.epoch!==this.epoch)throw new TranscriptGap()
+      const ids=new Set(this.messages.map(m=>m.id))
+      const added=older.messages.filter(m=>!ids.has(m.id))
+      this.messages=[...added,...this.messages];this.snapshot.hasOlder=older.hasOlder
+      if(!added.length)break
+    }
+    await this.publish()
+  }
+  async loadOlder(){
+    if(this.fetchingOlder||!this.snapshot?.hasOlder||!this.messages.length)return
+    this.fetchingOlder=true
+    try{
+      const page=await this.page(this.messages[0]!.seq)
+      if(page.epoch!==this.epoch)throw new TranscriptGap()
+      const current=new Map(this.messages.map(m=>[m.id,m]))
+      for(const message of page.messages)if((current.get(message.id)?.revision??0)<message.revision)current.set(message.id,message)
+      this.messages=[...current.values()].sort((a,b)=>a.seq-b.seq||a.id.localeCompare(b.id));this.snapshot.hasOlder=page.hasOlder
+      // A history page is not an event acknowledgement; never move cursor here.
+      await this.publish()
+    }finally{this.fetchingOlder=false}
+  }
+  async run(){
+    let needsSnapshot=!this.snapshot
+    while(!this.abort.signal.aborted){
+      let reader:ReadableStreamDefaultReader<Uint8Array>|undefined
+      try{
+        if(needsSnapshot){await this.hydrate();needsSnapshot=false}
+        const response=await fetch(this.path('events'),{headers:{Accept:'text/event-stream','Last-Event-ID':`${this.epoch}:${this.cursor}`},credentials:'include',cache:'no-store',signal:this.abort.signal})
+        if(response.status===409){needsSnapshot=true;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){
+          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!=='transcript')continue
+            const event=JSON.parse(frame.data) as TranscriptEvent
+            if(event.profile!==this.profile||event.sessionId!==this.sessionId||!Number.isSafeInteger(event.cursor))throw new TranscriptGap()
+            if(event.cursor<=this.cursor)continue
+            if(event.type==='session.deleted'||event.type==='session.migrated')throw new TranscriptGap()
+            const data=event.data as {seq?:number}
+            // Older, unloaded pages are read from their current snapshot later.
+            if(!(event.type==='message.patch'&&data.seq!==undefined&&this.messages[0]&&data.seq<this.messages[0].seq))
+              this.messages=applyTranscriptEvent(this.messages,event)
+            if(this.snapshot&&event.type==='session.changed'){
+              const detail=event.data as {eventType?:string;payload?:Record<string,unknown>;running?:boolean;queued?:boolean}
+              this.snapshot.running=detail.running;this.snapshot.queued=detail.queued
+              if(detail.eventType==='session.info'&&detail.payload)this.snapshot.session={...this.snapshot.session,...detail.payload}
+            }
+            const previous=this.cursor;this.cursor=event.cursor
+            try{await this.publish()}catch(error){this.cursor=previous;throw error}
+          }
+        }
+      }catch(error){
+        if(this.abort.signal.aborted)return
+        if(error instanceof TranscriptGap)needsSnapshot=true
+        this.failed(error instanceof Error?error:new Error('聊天消息需要同步'))
+      }finally{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()})
+    }
+  }
+}

+ 121 - 35
src/client/api/client.ts

@@ -1,4 +1,5 @@
 import type { JsonValue } from '@shared/types'
+import { bool, normalizeUser, record, string } from '@/utils/normalize'
 
 export class ApiError extends Error {
   readonly status: number
@@ -15,21 +16,84 @@ export class ApiError extends Error {
 }
 
 let csrfToken = ''
+let csrfAccountId: string | null | undefined
+let securityGeneration = 0
+let csrfRefresh: { generation: number; promise: Promise<void> } | undefined
 const unauthorizedListeners = new Set<() => void>()
 const securityChannel = typeof window !== 'undefined' && typeof window.BroadcastChannel !== 'undefined'
   ? new window.BroadcastChannel('hermes-yaoyao-security')
   : undefined
 securityChannel?.addEventListener('message', event => {
-  if (typeof event.data === 'string') csrfToken = event.data
+  // Another window shares cookies, but may now belong to another account.
+  // Revalidate that identity before using its token for a pending action.
+  if (typeof event.data === 'string' && event.data !== csrfToken) csrfToken = ''
 })
 
-export function setApiCsrfToken(token?: string | null): void {
+export function setApiCsrfToken(token?: string | null, accountId?: string | null): void {
+  if (accountId !== undefined) {
+    if (csrfAccountId !== undefined && csrfAccountId !== accountId) securityGeneration += 1
+    csrfAccountId = accountId
+  }
   csrfToken = token?.trim() ?? ''
   securityChannel?.postMessage(csrfToken)
 }
 
 export function clearApiSecurityContext(): void {
+  securityGeneration += 1
   csrfToken = ''
+  csrfAccountId = undefined
+  csrfRefresh = undefined
+}
+
+function requireSecurityGeneration(generation: number): void {
+  if (generation !== securityGeneration) throw new ApiError('登录状态已变化,请重新操作', 0, 'SECURITY_CONTEXT_CHANGED')
+}
+
+function refreshCsrfToken(rejectedToken: string): Promise<void> {
+  if (csrfToken && csrfToken !== rejectedToken) return Promise.resolve()
+  const generation = securityGeneration, accountId = csrfAccountId
+  if (csrfRefresh?.generation === generation) return csrfRefresh.promise
+  const renew = async () => {
+    requireSecurityGeneration(generation)
+    const payload = await apiRequest<unknown>('/api/app/bootstrap?csrfOnly=1', {
+      csrf: false, notifyUnauthorized: false, timeoutMs: 10_000,
+    })
+    requireSecurityGeneration(generation)
+    const root = record(unwrapData(payload)), status = record(root.status)
+    const user = root.user ?? root.identity
+    const token = string(root.csrfToken ?? root.csrf_token ?? root.csrf).trim()
+    const authRequired = root.authRequired ?? root.auth_required ?? status.authRequired ?? status.auth_required
+    if (!token || (!('userId' in root) && !user && authRequired === undefined)
+      || ('userId' in root && root.userId !== null && typeof root.userId !== 'string'))
+      throw new ApiError('无法更新安全令牌,请稍后重试', 0, 'CSRF_REFRESH_FAILED')
+    // Older servers ignore csrfOnly and return a complete bootstrap response.
+    const currentAccount = 'userId' in root ? (typeof root.userId === 'string' ? root.userId : null)
+      : user ? normalizeUser(user).id
+        : bool(authRequired) ? null : 'local'
+    if (accountId !== undefined && currentAccount !== accountId) {
+      clearApiSecurityContext()
+      for (const listener of unauthorizedListeners) listener()
+      throw new ApiError('登录账号已变化,请重新登录后操作', 401, 'SECURITY_CONTEXT_CHANGED')
+    }
+    setApiCsrfToken(token, currentAccount)
+  }
+  // Cookie issuance must also be serialized across windows when supported;
+  // otherwise two expired-cookie responses can replace one another's token.
+  const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined
+  const promise = (locks ? locks.request('hermes-yaoyao-csrf-refresh', renew) : renew())
+    .finally(() => { if (csrfRefresh?.promise === promise) csrfRefresh = undefined })
+  csrfRefresh = { generation, promise }
+  return promise
+}
+
+function waitForCsrfRefresh(promise: Promise<void>, signal: AbortSignal): Promise<void> {
+  return new Promise((resolve, reject) => {
+    const abort = () => { cleanup(); reject(new DOMException('Request aborted', 'AbortError')) }
+    const cleanup = () => signal.removeEventListener('abort', abort)
+    signal.addEventListener('abort', abort, { once: true })
+    promise.then(() => { cleanup(); resolve() }, error => { cleanup(); reject(error) })
+    if (signal.aborted) abort()
+  })
 }
 
 export function onApiUnauthorized(listener: () => void): () => void {
@@ -76,17 +140,19 @@ export async function apiRequest<T>(path: string, options: ApiRequestOptions = {
   if (!path.startsWith('/api/app/') && !path.startsWith('/api/realtime/')) throw new ApiError('客户端仅允许访问应用接口', 0, 'INVALID_PATH')
 
   const method = (options.method ?? 'GET').toUpperCase()
+  const requiresCsrf = options.csrf !== false && !['GET', 'HEAD', 'OPTIONS'].includes(method)
+  const generation = securityGeneration
   const headers = new Headers(options.headers)
   headers.set('Accept', 'application/json')
-  if (options.csrf !== false && !['GET', 'HEAD', 'OPTIONS'].includes(method)) {
-    if (!csrfToken) throw new ApiError('安全令牌尚未就绪,请刷新后重试', 0, 'CSRF_MISSING')
-    headers.set('X-CSRF-Token', csrfToken)
-  }
 
   let body: BodyInit | undefined
   if (options.body !== undefined) {
     if (isBodyInit(options.body)) {
-      body = options.body
+      if (typeof FormData !== 'undefined' && options.body instanceof FormData) {
+        const snapshot = new FormData()
+        options.body.forEach((value, key) => snapshot.append(key, value))
+        body = snapshot
+      } else body = options.body
     } else {
       headers.set('Content-Type', 'application/json')
       body = JSON.stringify(options.body)
@@ -97,37 +163,57 @@ export async function apiRequest<T>(path: string, options: ApiRequestOptions = {
   const timeout = window.setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)
   const abort = () => controller.abort(options.signal?.reason)
   options.signal?.addEventListener('abort', abort, { once: true })
+  if (options.signal?.aborted) abort()
   try {
-    const response = await fetch(path, {
-      ...options,
-      method,
-      headers,
-      body,
-      credentials: 'include',
-      cache: 'no-store',
-      signal: controller.signal,
-    })
-    const contentType = response.headers.get('content-type') ?? ''
-    const payload = response.status === 204
-      ? undefined
-      : contentType.includes('application/json')
-        ? await response.json().catch(() => undefined)
-        : await response.text().catch(() => undefined)
-    if (!response.ok) {
-      const record = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined
-      const code = typeof record?.code === 'string' ? record.code : undefined
-      if (response.status === 401
-        && options.notifyUnauthorized !== false) {
-        for (const listener of unauthorizedListeners) listener()
+    if (controller.signal.aborted) throw new DOMException('Request aborted', 'AbortError')
+    if (requiresCsrf && !csrfToken) await waitForCsrfRefresh(refreshCsrfToken(''), controller.signal)
+    for (let attempt = 0; attempt < 2; attempt += 1) {
+      const requestHeaders = new Headers(headers)
+      if (controller.signal.aborted) throw new DOMException('Request aborted', 'AbortError')
+      if (requiresCsrf) {
+        requireSecurityGeneration(generation)
+        requestHeaders.set('X-CSRF-Token', csrfToken)
+      }
+      const sentToken = requestHeaders.get('X-CSRF-Token') ?? ''
+      const response = await fetch(path, {
+        ...options,
+        method,
+        headers: requestHeaders,
+        body,
+        credentials: 'include',
+        cache: 'no-store',
+        signal: controller.signal,
+      })
+      const contentType = response.headers.get('content-type') ?? ''
+      const payload = response.status === 204
+        ? undefined
+        : contentType.includes('application/json')
+          ? await response.json().catch(() => undefined)
+          : await response.text().catch(() => undefined)
+      if (!response.ok) {
+        const record = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined
+        const code = typeof record?.code === 'string' ? record.code : undefined
+        if (requiresCsrf && attempt === 0 && response.status === 403 && code === 'invalid_csrf') {
+          requireSecurityGeneration(generation)
+          // This explicit rejection occurs before the server executes the action.
+          // Preserve the original body and idempotency key; never retry timeouts.
+          await waitForCsrfRefresh(refreshCsrfToken(sentToken), controller.signal)
+          continue
+        }
+        if (response.status === 401
+          && options.notifyUnauthorized !== false) {
+          for (const listener of unauthorizedListeners) listener()
+        }
+        throw new ApiError(
+          errorMessage(payload, `请求失败(${response.status})`),
+          response.status,
+          code,
+          payload as JsonValue,
+        )
       }
-      throw new ApiError(
-        errorMessage(payload, `请求失败(${response.status})`),
-        response.status,
-        code,
-        payload as JsonValue,
-      )
+      return payload as T
     }
-    return payload as T
+    throw new ApiError('安全令牌校验失败,请稍后重试', 403, 'invalid_csrf')
   } catch (error) {
     if (error instanceof ApiError) throw error
     if (controller.signal.aborted) throw new ApiError('请求已取消或超时', 0, 'REQUEST_ABORTED')

+ 3 - 2
src/client/api/httpRealtime.ts

@@ -14,8 +14,8 @@ export class HTTPRealtimeChannel {
   private abort?: AbortController
   private ready = false
   constructor(readonly onFrame: (frame: string) => Promise<unknown>, readonly onFailure: (error: Error) => void) {}
-  static async requireSupport(): Promise<void> {
-    let value: { protocolVersion: number; csrfToken?: string }
+  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')
@@ -23,6 +23,7 @@ export class HTTPRealtimeChannel {
     }
     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, ...anchor } })

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

@@ -22,6 +22,7 @@ export class ChatRpcSocket {
   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) }
@@ -29,7 +30,7 @@ export class ChatRpcSocket {
     this.close()
     const generation = ++this.generation
     this.publishState('connecting')
-    await HTTPRealtimeChannel.requireSupport()
+    this.transcriptSupported = (await HTTPRealtimeChannel.requireSupport()).includes('ordinary-chat-transcript-v1')
     if (generation !== this.generation) return
     this.http = new HTTPRealtimeChannel(frame => this.handleMessage(frame, generation), error => {
       if (generation === this.generation) this.publishState('failed', error.message)

+ 61 - 0
src/client/components/app/UpdateCheckDialog.vue

@@ -0,0 +1,61 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
+import { checkSystemUpdate, systemUpdateStatus, type SystemUpdateStatus } from '@/api/systemUpdate'
+import AppIcon from '@/components/common/AppIcon.vue'
+import StandaloneDialog from '@/components/common/StandaloneDialog.vue'
+
+const emit = defineEmits<{ close: []; manage: [] }>()
+const status = ref<SystemUpdateStatus>()
+const checking = ref(true)
+const checked = ref(false)
+const error = ref('')
+let disposed = false
+const message = computed(() => checking.value ? '正在检测更新…'
+  : error.value ? '检测失败,请重试'
+    : status.value?.updateAvailable ? `发现新版本 ${status.value.latest?.webVersion}` : '当前已是最新版本')
+const releasePage = computed(() => {
+  try {
+    const url = new URL(status.value?.releasePageUrl || '')
+    return url.protocol === 'https:' ? url.href : undefined
+  } catch { return undefined }
+})
+
+async function check() {
+  checking.value = true
+  checked.value = false
+  error.value = ''
+  try {
+    const next = await checkSystemUpdate()
+    if (disposed) return
+    status.value = next
+    checked.value = true
+  } catch (cause) {
+    if (!disposed) error.value = cause instanceof Error ? cause.message : '无法连接更新服务'
+  } finally { if (!disposed) checking.value = false }
+}
+onMounted(async () => {
+  // Keep the installed version visible even when the remote check fails.
+  try { const current = await systemUpdateStatus(); if (!disposed) status.value = current } catch { /* The check below reports actionable errors. */ }
+  if (!disposed) await check()
+})
+onBeforeUnmount(() => { disposed = true })
+</script>
+<template>
+  <StandaloneDialog title="检测更新" compact @close="emit('close')">
+    <section class="update-check" :aria-busy="checking">
+      <div class="update-check__icon" :class="{ spinning: checking }"><AppIcon :name="checking ? 'refresh' : error ? 'alert' : status?.updateAvailable ? 'download' : 'check'" :size="28" /></div>
+      <p class="update-check__status" role="status" aria-live="polite">{{ message }}</p>
+      <dl aria-label="Web 版本信息"><div><dt>当前 Web 版本</dt><dd>{{ status?.current.webVersion || '—' }}</dd></div><div><dt>最新版本</dt><dd>{{ checking ? '检测中…' : !checked ? '未获取' : status?.latest?.webVersion || status?.current.webVersion }}</dd></div></dl>
+      <p v-if="error" class="update-check__error" role="alert">{{ error }}</p>
+      <p v-if="checked && status?.updateAvailable && !status.supported" class="update-check__note">{{ status.unsupportedReason || '请通过部署环境更新 Web。' }}</p>
+      <a v-if="checked && releasePage" :href="releasePage" target="_blank" rel="noopener noreferrer">查看发布说明<AppIcon name="external" :size="14" /></a>
+      <div class="update-check__actions">
+        <button type="button" :disabled="checking" @click="check">{{ checking ? '正在检测…' : error ? '重试' : '重新检测' }}</button>
+        <button v-if="checked && status?.updateAvailable && status.supported" class="primary" type="button" @click="emit('manage')">前往更新</button>
+      </div>
+    </section>
+  </StandaloneDialog>
+</template>
+<style scoped>
+.update-check{display:grid;gap:18px;text-align:center}.update-check__icon{display:grid;place-items:center;color:var(--accent)}.update-check__status{margin:0;font-size:16px;font-weight:600;line-height:1.5}dl{display:grid;gap:12px;margin:0;padding:16px 0;border-block:1px solid var(--line);font-size:13px}dl div{display:flex;justify-content:space-between;gap:12px}dt{color:var(--text-secondary)}dd{margin:0;font-variant-numeric:tabular-nums}.update-check__error,.update-check__note{margin:0;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.update-check__error{color:var(--danger)}.update-check__note{color:var(--text-secondary)}a{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:44px;color:var(--accent);font-size:13px;text-decoration:none}a:hover{text-decoration:underline}.update-check__actions{display:flex;gap:10px;flex-wrap:wrap}button{flex:1;min-height:44px;padding:8px 14px;border:1px solid var(--line);border-radius:9px;background:var(--surface-raised);color:var(--text-primary);font:500 13px var(--font-ui);cursor:pointer}button:hover{background:var(--surface-hover)}button.primary{background:var(--accent);border-color:var(--accent);color:var(--text-on-solid)}button:disabled{opacity:.6;cursor:wait}button:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.spinning{animation:update-spin 1s linear infinite}@keyframes update-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.spinning{animation:none}}
+</style>

+ 38 - 5
src/client/components/app/WorkspaceShell.vue

@@ -11,6 +11,7 @@ import SettingsCenterDialog from '@/components/app/SettingsCenterDialog.vue'
 import { rememberInterfacePath } from '@/utils/interfaceMode'
 import YaoYaoSidebarIcon from '@/components/common/YaoYaoSidebarIcon.vue'
 const AboutDialog = defineAsyncComponent(() => import('./AboutDialog.vue'))
+const UpdateCheckDialog = defineAsyncComponent(() => import('./UpdateCheckDialog.vue'))
 const BotPluginsDialog = defineAsyncComponent(() => import('@/components/workspace/BotPluginsDialog.vue'))
 
 type NavItem = {
@@ -102,7 +103,7 @@ const router = useRouter()
 const mobileDrawerOpen = ref(false)
 const profileMenuOpen = ref(false)
 const settingsOpen = ref(false)
-const standalone = ref<'plugins' | 'about' | null>(null)
+const standalone = ref<'plugins' | 'about' | 'update' | null>(null)
 const standaloneReturnFocus = ref<HTMLElement>()
 const settingsPage = ref<SettingsPage>('agent-identity')
 const settingsReturnFocus = ref<HTMLButtonElement>()
@@ -116,6 +117,9 @@ const createMenu = ref<HTMLElement | null>(null)
 let createTrigger: HTMLElement | null = null
 const createPosition = ref({ left: '8px', top: '58px' })
 const settingsMenuOpen = ref(false)
+const canCheckUpdates = computed(() => Boolean(window.yaoyaoDesktop?.openUpdates) || props.isAdmin)
+const openingUpdate = ref(false)
+const updateError = ref('')
 const settingsMenu = ref<HTMLElement | null>(null)
 let settingsTrigger: HTMLButtonElement | null = null
 const settingsMenuPosition = ref({ left: '8px', top: '8px' })
@@ -205,7 +209,7 @@ function chooseCreate(kind: 'agent' | 'group' | 'remote-agent') {
 function actionMenuKeydown(event: KeyboardEvent) {
   if (!['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return
   event.preventDefault()
-  const buttons = [...(event.currentTarget as HTMLElement).querySelectorAll<HTMLElement>('[role="menuitem"]')]
+  const buttons = [...(event.currentTarget as HTMLElement).querySelectorAll<HTMLElement>('[role="menuitem"]:not(:disabled)')]
   const index = buttons.indexOf(document.activeElement as HTMLElement)
   buttons[event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1 : (index + (event.key === 'ArrowUp' ? -1 : 1) + buttons.length) % buttons.length]?.focus()
 }
@@ -218,15 +222,40 @@ async function openSettingsMenu(event: MouseEvent) {
   if (settingsMenuOpen.value) { closeSettingsMenu(); return }
   settingsTrigger = event.currentTarget as HTMLButtonElement
   const rect = settingsTrigger.getBoundingClientRect()
-  const height = (props.isAdmin ? 4 : 3) * (window.innerWidth < 768 ? 44 : 36) + 18
+  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 = ''
   settingsMenuOpen.value = true
   await nextTick()
   settingsMenu.value?.querySelector<HTMLButtonElement>('[role="menuitem"]')?.focus()
 }
+async function checkForUpdates() {
+  if (openingUpdate.value || !canCheckUpdates.value) return
+  updateError.value = ''
+  if (window.yaoyaoDesktop?.openUpdates) {
+    openingUpdate.value = true
+    try {
+      await window.yaoyaoDesktop.openUpdates()
+      closeSettingsMenu()
+    } catch (cause) {
+      updateError.value = cause instanceof Error ? cause.message : '无法打开更新窗口,请重试'
+    } finally { openingUpdate.value = false }
+    return
+  }
+  standaloneReturnFocus.value = settingsTrigger?.closest('.mobile-drawer')
+    ? mobileNavigationTrigger.value : settingsTrigger ?? undefined
+  settingsMenuOpen.value = false
+  mobileDrawerOpen.value = false
+  standalone.value = 'update'
+}
+function openUpdateSettings() {
+  settingsReturnFocus.value = standaloneReturnFocus.value as HTMLButtonElement | undefined
+  standalone.value = null
+  openSettings('system-update')
+}
 function chooseSettingsAction(action: 'settings' | 'bots' | 'about') {
   settingsMenuOpen.value = false
   if (action === 'bots') { switchInterfaceMode(); return }
@@ -515,7 +544,7 @@ defineExpose({openLocalVm:()=>{if(props.isAdmin)openSettings('system-local-vm')}
             </span>
             <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
           </button>
-          <button class="sidebar-settings-trigger" type="button" title="设置与模式" aria-label="设置与模式" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu">
+          <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">
@@ -623,7 +652,7 @@ defineExpose({openLocalVm:()=>{if(props.isAdmin)openSettings('system-local-vm')}
             </span>
             <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
           </button>
-          <button class="sidebar-settings-trigger" type="button" title="设置与模式" aria-label="设置与模式" aria-haspopup="menu" :aria-expanded="settingsMenuOpen" @click="openSettingsMenu">
+          <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">
@@ -664,6 +693,7 @@ defineExpose({openLocalVm:()=>{if(props.isAdmin)openSettings('system-local-vm')}
     </Transition>
 
     <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" />
     <SettingsCenterDialog
       :open="settingsOpen"
@@ -695,6 +725,8 @@ defineExpose({openLocalVm:()=>{if(props.isAdmin)openSettings('system-local-vm')}
         <div ref="settingsMenu" class="workspace-create-menu workspace-settings-menu" :style="settingsMenuPosition" role="menu" aria-label="账号菜单" @keydown="actionMenuKeydown">
           <button type="button" role="menuitem" @click="chooseSettingsAction('settings')"><AppIcon name="settings" :size="17" />设置</button>
           <button type="button" role="menuitem" @click="chooseSettingsAction('about')"><AppIcon name="info" :size="17" />关于</button>
+          <button v-if="canCheckUpdates" type="button" role="menuitem" :disabled="openingUpdate" :aria-busy="openingUpdate" @click="checkForUpdates"><AppIcon name="refresh" :size="17" />{{ openingUpdate ? '正在打开…' : '检测更新' }}</button>
+          <p v-if="updateError" class="update-menu-error" role="alert">{{ updateError }}</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>
@@ -712,6 +744,7 @@ defineExpose({openLocalVm:()=>{if(props.isAdmin)openSettings('system-local-vm')}
 </template>
 
 <style scoped>
+.update-menu-error{margin:4px 10px;color:var(--danger);font-size:12px;line-height:1.5;overflow-wrap:anywhere}.workspace-settings-menu button:disabled{opacity:.6;cursor:wait}
 .sidebar-tools-trigger{display:flex;width:100%;min-height:44px;align-items:center;gap:10px;padding:8px 12px;margin:0 0 8px;border:0;border-radius:9px;background:transparent;color:var(--text-primary);font:500 13px var(--font-ui);cursor:pointer}.sidebar-tools-trigger span{flex:1;text-align:left}.sidebar-tools-trigger:hover,.sidebar-tools-trigger[aria-expanded=true]{background:var(--surface-hover)}.sidebar-tools-trigger:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.workspace-settings-menu a{display:flex;align-items:center;gap:8px;min-height:36px;padding:8px 10px;box-sizing:border-box;border-radius:7px;color:var(--text-primary);text-decoration:none;font-size:13px}.workspace-settings-menu a:hover{background:var(--surface-hover)}.workspace-settings-menu a:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
 .workspace-shell {
   display: grid;

+ 1 - 0
src/client/env.d.ts

@@ -11,6 +11,7 @@ interface ImportMeta {
 
 interface Window {
   yaoyaoDesktop?: {
+    openUpdates?(): Promise<void>
     openComputer(id: string): Promise<boolean>
     computerClosed(): Promise<void>
     onComputerClose(callback: () => void): () => void

+ 124 - 35
src/client/stores/chat.ts

@@ -8,6 +8,8 @@ import {
 } 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 } from '@/utils/attachments'
 import { ScopedCache } from '@/utils/cache'
@@ -20,7 +22,7 @@ import { modelForSession, modelSelectionFromSessionInfo } from '@/utils/sessionM
 import { moveSessionFastMode, readSessionFastMode, writeSessionFastMode } from '@/utils/sessionPreferences'
 import { useAuthStore } from './auth'
 
-interface CachedHistory { messages: ChatMessage[]; total: number; savedAt: number }
+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
@@ -111,9 +113,52 @@ export const useChatStore = defineStore('chat', () => {
   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)
+  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')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=await historyCache.get(scope,id)
+      if(!current())return
+      if(!state.messages.length&&cached?.messages.length)state.messages=cached.messages
+      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)
+          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))
+        const messages=[...canonical,...pending]
+        const {messages:_,...checkpoint}=value
+        await historyCache.set(scope,id,{messages,total:value.total,savedAt:Date.now(),transcript:checkpoint})
+        const latest=current();if(!latest)return
+        latest.messages=messages;latest.messageTotal=value.total;latest.loadedMessageCount=canonical.length
+        latest.hasMoreBefore=value.hasOlder;latest.historySynced=true;latest.isLoadingHistory=false;latest.error=undefined
+        latest.isStreaming=value.running??canonical.some(m=>m.isStreaming);latest.isQueued=value.queued??false
+        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){
+        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
@@ -304,9 +349,13 @@ export const useChatStore = defineStore('chat', () => {
     if (event.type === 'gateway.ready') return
     const payload = record(event.payload)
     if (event.type === 'sessions.changed') {
-      if(payload.reason==='cache.synced'){
-        const state=activeRouteState.value
-        if(state && state.route.profile===payload.profile && state.route.sessionId===payload.session_id && !state.isLoadingHistory)
+      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()
@@ -328,6 +377,18 @@ export const useChatStore = defineStore('chat', () => {
     }
     if (!key) return
     let state = routes[key]
+    if(transcriptSupported.value&&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))){
+      // Message bodies come exclusively from the persisted transcript stream.
+      // Legacy control events may only wake/settle the execution indicator.
+      if(['message.start','run.started'].includes(event.type))state.isStreaming=true
+      if(['message.complete','run.completed','run.failed'].includes(event.type)){
+        state.isQueued=number(payload.queue_remaining)>0;state.isStreaming=state.isQueued||number(payload.background_pending)>0
+        if(!state.isStreaming){state.liveStatus=undefined;state.pendingApproval=undefined;state.pendingClarification=undefined}
+      }
+      updateInflightMarker(state);return
+    }
     if (event.type === 'session.info') {
       const storedId = string(payload.stored_session_id ?? payload.storedSessionId ?? payload.session_key)
       if (storedId && storedId !== state.route.sessionId) {
@@ -364,7 +425,7 @@ export const useChatStore = defineStore('chat', () => {
       window.clearTimeout(reconnectTimer)
       reconnectTimer = undefined
     }
-    connectPromise = socket.connect().catch(cause => {
+    connectPromise = socket.connect().then(()=>{if(auth.isAuthenticated)transcriptSupported.value=socket.transcriptSupported===true}).catch(cause => {
       connectionState.value = 'failed'
       error.value = errorMessage(cause)
       throw cause
@@ -373,6 +434,7 @@ export const useChatStore = defineStore('chat', () => {
   }
 
   function disconnect(): void {
+    transcriptGeneration++;transcript?.close();transcript=undefined;transcriptSupported.value=false
     if (reconnectTimer !== undefined) window.clearTimeout(reconnectTimer)
     reconnectTimer = undefined
     socket.close()
@@ -486,40 +548,55 @@ export const useChatStore = defineStore('chat', () => {
   }
 
   async function loadHistory(state: ChatRouteState, forceRefresh = false): Promise<void> {
-    const generation = ++state.generation
+    if(transcriptSupported.value&&sessionView==='chat'){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)
-    if (generation !== state.generation) return
+    let latest = current()
+    if (!latest) return
     if (cached?.messages.length) {
-      state.messages = mergeChatMessages(state.messages, cached.messages, 'snapshot')
-      state.messageTotal = cached.total
-      state.loadedMessageCount = 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)
-      if (generation !== state.generation) return
-      if (forceRefresh && routes[routeKey(state.route.profile, state.route.sessionId)]?.isStreaming) {
+      latest = current()
+      if (!latest || (latest.historySyncRevision ?? 0) !== syncRevision) return
+      if (forceRefresh && latest.isStreaming) {
         throw new Error('正在回复,请结束后再刷新历史')
       }
-      const retained = forceRefresh ? state.messages.filter(message => message.role === 'user' && message.stage !== 'settled') : state.messages
-      state.messages = reconcileChatHistory(retained, page.messages, state.isStreaming)
-      state.messageTotal = page.total
-      state.loadedMessageCount = page.returned
-      state.hasMoreBefore = page.hasMore
-      state.historySynced = true
+      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: state.messages, total: page.total, savedAt: Date.now() })
+      await historyCache.set(scope, state.route.sessionId, { messages: latest.messages, total: page.total, savedAt: Date.now() })
     } catch (cause) {
-      if (generation === state.generation) state.error = errorMessage(cause)
+      latest = current()
+      if (latest) latest.error = errorMessage(cause)
       if(cause instanceof ApiError && cause.code==='CHAT_HISTORY_SYNC_PENDING')return
       throw cause
     } finally {
-      if (generation === state.generation) state.isLoadingHistory = false
+      latest = current()
+      if (latest) {
+        latest.isLoadingHistory = false
+        if ((latest.historySyncRevision ?? 0) !== syncRevision && latest === activeRouteState.value)
+          void loadHistory(latest).catch(() => {})
+      }
     }
   }
 
@@ -538,7 +615,7 @@ export const useChatStore = defineStore('chat', () => {
     syncSelectedModel(refreshed?.model, refreshed?.provider)
     if (refreshed?.owned === true && !sessionId.startsWith('draft-')
       && activeSessionId.value === sessionId && activeProfileName.value === selectedProfile) {
-      await ensureRuntime(state).catch(cause => {
+      await ensureRuntime(routes[routeKey(selectedProfile, sessionId)] ?? state).catch(cause => {
         const current = routes[routeKey(selectedProfile, sessionId)]
         if (current) current.error = errorMessage(cause)
       })
@@ -554,22 +631,34 @@ export const useChatStore = defineStore('chat', () => {
   }
 
   async function loadOlder(): Promise<void> {
+    if(transcriptSupported.value&&transcript){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)
-      if (generation !== state.generation) return
-      state.messages = mergeChatMessages(state.messages, page.messages, 'prepend')
-      state.loadedMessageCount += page.returned
-      state.messageTotal = Math.max(state.messageTotal, page.total)
-      state.hasMoreBefore = page.hasMore
+      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: state.messages, total: state.messageTotal, savedAt: Date.now(),
+        messages: latest.messages, total: latest.messageTotal, savedAt: Date.now(),
       })
-    } catch (cause) { state.error = errorMessage(cause) }
-    finally { if (generation === state.generation) state.isLoadingHistory = false }
+    } 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 {
@@ -630,7 +719,7 @@ export const useChatStore = defineStore('chat', () => {
     persistFastMode(migrated)
     const resumedMessages = values(result.messages)
       .map(value => normalizeChatMessage(value, storedId, migrated.route.profile))
-    if (resumedMessages.length) migrated.messages = mergeChatMessages(migrated.messages, resumedMessages, 'snapshot')
+    if (!transcriptSupported.value&&resumedMessages.length) migrated.messages = mergeChatMessages(migrated.messages, resumedMessages, 'snapshot')
     const inflight = record(result.inflight ?? result.active_run)
     const assistant = string(inflight.assistant)
     const inflightError = string(inflight.error)
@@ -641,7 +730,7 @@ export const useChatStore = defineStore('chat', () => {
     // A turn can be thinking or calling tools before producing any text.
     // Create its live row now so subsequent tool events have a visible target.
     const existing = [...migrated.messages].reverse().find(message => message.role === 'assistant' && message.isStreaming)
-    if (migrated.isStreaming || inflightError || (existing && assistant)) {
+    if (!transcriptSupported.value&&(migrated.isStreaming || inflightError || (existing && assistant))) {
       migrated.messages = mergeChatMessages(migrated.messages, [{
         ...existing,
         id: existing?.id ?? `resume:${runtimeId}`,
@@ -657,11 +746,11 @@ export const useChatStore = defineStore('chat', () => {
     }
     if (!migrated.isStreaming) {
       migrated.liveStatus = undefined
-      migrated.messages = settleChatMessages(migrated.messages)
+      if(!transcriptSupported.value)migrated.messages = settleChatMessages(migrated.messages)
     }
     migrated.pendingApproval = undefined
     migrated.pendingClarification = undefined
-    values(inflight.corrections).forEach((correction, index) => {
+    values(transcriptSupported.value?[]:inflight.corrections).forEach((correction, index) => {
       const content = string(correction)
       if (!content) return
       migrated.messages = mergeChatMessages(migrated.messages, [{
@@ -674,7 +763,7 @@ export const useChatStore = defineStore('chat', () => {
         stage: 'accepted',
       }])
     })
-    if (queuedUser) {
+    if (!transcriptSupported.value&&queuedUser) {
       migrated.messages = mergeChatMessages(migrated.messages, [{
         id: `resume-queued:${runtimeId}`,
         sessionId: storedId,

+ 5 - 2
src/server/app.ts

@@ -1,3 +1,4 @@
+import { chatTranscriptRouter } from './chatTranscriptApi.js'
 import {DesktopEnvironments} from './desktopEnvironments.js'
 import type {GrokAuth} from './grokAuth.js'
 import {GrokCloud} from './grokCloud.js'
@@ -261,6 +262,7 @@ export function createApplication(options: ApplicationOptions = {}): Application
   }, (owner, profile, sessionID) =>
     chatCache?.store.ownsSession(owner, profile, sessionID) ?? false)
   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(/^(message\.(start|delta|interim|complete)|reasoning\.|tool\.|run\.(completed|failed))/.test(frame.type)){
@@ -290,8 +292,8 @@ export function createApplication(options: ApplicationOptions = {}): Application
   realtime.broker.onNativeCommand = (owner, profile, storedId, method, params) => {
     chatCache?.command(owner, profile, storedId, method, params)
   }
-  realtime.broker.onNativeRoute = (owner, profile, storedId, runtimeId) => {
-    chatCache?.route(owner, profile, storedId, runtimeId)
+  realtime.broker.onNativeRoute = (owner, profile, storedId, runtimeId, running) => {
+    chatCache?.route(owner, profile, storedId, runtimeId, running)
   }
   chatPushJobs.setTransportFactory(realtime.recoveryTransport, job => realtime.ownsPushJob(job.id))
   try {
@@ -447,6 +449,7 @@ export function createApplication(options: ApplicationOptions = {}): Application
       } 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),

+ 34 - 7
src/server/chatCache.ts

@@ -1,4 +1,5 @@
 import { projectChatEvent } from './chatEventProjection.js'
+import { ChatTranscriptStore } from './chatTranscriptStore.js'
 import { isFinalChatResult } from './chatUnread.js'
 import { HttpError } from './errors.js'
 import { createHash, randomUUID } from 'node:crypto'
@@ -139,6 +140,7 @@ function referencedPaths(value: unknown, output = new Set<string>()): Set<string
 export class ChatCacheStore {
   readonly db: DatabaseSync
   readonly assetsRoot: string
+  readonly transcripts: ChatTranscriptStore
   private closed = false
   get isClosed(): boolean { return this.closed }
 
@@ -316,9 +318,10 @@ export class ChatCacheStore {
       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.db.close() }
+  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)
@@ -429,6 +432,7 @@ export class ChatCacheStore {
       }
       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}
   }
@@ -447,6 +451,7 @@ export class ChatCacheStore {
     if (typeof message.content==='string' && message.content.trim()) summary.preview=message.content.slice(0,160)
     this.db.prepare('UPDATE chat_sessions SET data=?,message_total=?,last_synced_at=? WHERE owner=? AND profile=? AND session_id=?').run(JSON.stringify(summary),total,now,owner,profile,id)
     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,now)
+    this.transcripts.upsert(owner,profile,id,message,position)
   }
 
   projectedMessageID(owner:string,profile:string,id:string):string|undefined {
@@ -478,7 +483,7 @@ export class ChatCacheStore {
     if(message){
       if(previous && previous.id !== message.id && !startsNew){
         const exists=this.db.prepare('SELECT 1 FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').get(owner,profile,id,message.id)
-        if(!exists)this.db.prepare('UPDATE chat_messages SET message_id=? WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(message.id,owner,profile,id,previous.id)
+        if(!exists){this.transcripts.promote(owner,profile,id,String(previous.id),String(message.id));this.db.prepare('UPDATE chat_messages SET message_id=? WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(message.id,owner,profile,id,previous.id)}
         else {this.db.prepare("UPDATE chat_sessions SET sync_state='gap' WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id);return}
       }
       this.writeLiveMessage(owner,profile,id,message)
@@ -560,10 +565,14 @@ export class ChatCacheStore {
           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 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}[]
+          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')
@@ -583,6 +592,8 @@ export class ChatCacheStore {
       }))
       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.transcripts.sessionChanged(owner,profile,sessionID,{eventType:'history.synced'})
       this.db.exec('RELEASE history_sync')
       return true
     } catch (error) {
@@ -745,6 +756,7 @@ export class ChatCacheStore {
       sync_state=excluded.sync_state,last_synced_at=excluded.last_synced_at`)
       .run(owner, profile, rawSeq > 0 ? rawSeq : lastSeen, state, now)
     this.projectEvent(owner,profile,sessionID,type,object(frame.payload)??{},eventID)
+    if (!['message.delta','reasoning.delta','thinking.delta'].includes(type)&&!type.startsWith('tool.')) this.transcripts.sessionChanged(owner,profile,sessionID,{eventType:type,payload:object(frame.payload)??{}})
     this.db.exec('RELEASE live_event')
     return true
     }catch(e){this.db.exec('ROLLBACK TO live_event; RELEASE live_event');throw e}
@@ -771,11 +783,14 @@ export class ChatCacheStore {
       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): void {
+  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 }
@@ -785,10 +800,15 @@ export class ChatCacheStore {
       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'
@@ -806,7 +826,10 @@ export class ChatCacheStore {
     if((method==='prompt.submit'||method==='session.steer') && params._delivery_id){
       const userID=`user:${params._delivery_id}`
       this.writeLiveMessage(owner,profile,sessionID,{id:userID,role:'user',content:params.text??params.input??'',timestamp:now/1000,status:'pending',client_message_id:String(params._delivery_id).replace(/^(web|ios):prompt:/,'')})
-      this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,assistant_id) VALUES(?,?,?,NULL) ON CONFLICT(owner,profile,session_id) DO UPDATE SET assistant_id=NULL`).run(owner,profile,sessionID)
+      const streaming=this.db.prepare(`SELECT 1 FROM chat_local_state l JOIN chat_messages m ON m.owner=l.owner AND m.profile=l.profile AND m.session_id=l.session_id AND m.message_id=l.assistant_id
+        WHERE l.owner=? AND l.profile=? AND l.session_id=? AND json_extract(m.data,'$.status')='streaming'`).get(owner,profile,sessionID)
+      if(!streaming)this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,assistant_id) VALUES(?,?,?,NULL) ON CONFLICT(owner,profile,session_id) DO UPDATE SET assistant_id=NULL`).run(owner,profile,sessionID)
+      this.transcripts.sessionChanged(owner,profile,sessionID,{eventType:'command.submitted',payload:{delivery_id:params._delivery_id}})
     }
     const payload = JSON.stringify(params)
     const seq = Number.parseInt(createHash('sha256').update(`${method}:${payload}`).digest('hex').slice(0, 12), 16)
@@ -814,6 +837,8 @@ export class ChatCacheStore {
       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 {
@@ -869,6 +894,7 @@ export class ChatCacheStore {
       }
       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)
@@ -1220,6 +1246,7 @@ export class ChatCacheStore {
         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'))
+      this.transcripts.upsert(owner,profile,sessionID,{...message,id:messageID(message,String(start+index))},start+index)
       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`)
@@ -1438,8 +1465,8 @@ export class ChatCacheCoordinator {
     this.store.recordCommand(owner, profile, sessionID, method, params)
   }
 
-  route(owner: string, profile: string, sessionID: string, runtimeID: string): void {
-    this.store.recordRoute(owner, profile, sessionID, runtimeID)
+  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> {

+ 13 - 4
src/server/chatEventProjection.ts

@@ -4,7 +4,7 @@ export type ChatRecord = Record<string, any>
 const text = (p: ChatRecord) => String(p.delta ?? p.text_delta ?? p.content_delta ?? p.text ?? '')
 export function projectChatEvent(type: string, payload: ChatRecord, previous: ChatRecord | undefined,
   fallbackID: string, now: number): ChatRecord | undefined {
-  const supported = /^(message\.(start|delta|interim|complete)|reasoning\.(delta|complete)|tool\.|run\.(completed|failed)|error$)/.test(type)
+  const supported = /^(message\.(start|delta|interim|complete)|(?:reasoning|thinking)\.(delta|complete)|tool\.|run\.(completed|failed)|error$)/.test(type)
   if (!supported) return undefined
   // Parameter-generation notifications have no invocation identity. They are
   // progress text, not an additional tool call which can later complete.
@@ -14,8 +14,16 @@ export function projectChatEvent(type: string, payload: ChatRecord, previous: Ch
   const message: ChatRecord = { role: 'assistant', content: '', reasoning: '', timestamp: now / 1000,
     ...previous, ...supplied, id }
   if (type === 'message.delta') message.content = String(message.content ?? '') + text(payload)
-  if (type === 'message.interim') message.status = 'complete'
-  if (type === 'reasoning.delta') message.reasoning = String(message.reasoning ?? '') + text(payload)
+  if (type === 'message.interim') {
+    if (typeof payload.text === 'string') message.content = payload.text
+    else if (typeof payload.content === 'string') message.content = payload.content
+    message.status = 'complete'
+  }
+  if (type === 'reasoning.delta' || type === 'thinking.delta') message.reasoning = String(message.reasoning ?? '') + text(payload)
+  if (type === 'reasoning.complete' || type === 'thinking.complete') {
+    const reasoning = payload.reasoning ?? payload.text ?? payload.content
+    if (typeof reasoning === 'string') message.reasoning = reasoning
+  }
   if (type.startsWith('tool.')) {
     const tools: ChatRecord[] = Array.isArray(message.tool_calls) ? [...message.tool_calls] : []
     const toolID = String(payload.tool_id ?? payload.tool_call_id ?? payload.id ?? '')
@@ -29,7 +37,8 @@ export function projectChatEvent(type: string, payload: ChatRecord, previous: Ch
     if (typeof payload.output === 'string') message.content = payload.output
     else if (typeof payload.content === 'string') message.content = payload.content
     else if (typeof payload.text === 'string') message.content = payload.text
-    message.status = payload.error || ['error','failed'].includes(payload.status) ? 'failed' : 'complete'
+    message.status = ['interrupted','cancelled','canceled'].includes(payload.status) ? 'interrupted'
+      : payload.error || ['error','failed'].includes(payload.status) ? 'failed' : 'complete'
     if(payload.error)message.error=payload.error
   } else if (type === 'error' || type === 'run.failed') {
     message.status = 'failed'; message.error = String(payload.error ?? payload.message ?? '运行失败')

+ 73 - 0
src/server/chatTranscriptApi.ts

@@ -0,0 +1,73 @@
+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'
+
+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 total=Number(JSON.parse(store.localDetail(owner,profile,id)!.response.body.toString()).message_count??0)
+    const offset=before===Number.MAX_SAFE_INTEGER?0:Math.max(0,total-(before-1))
+    if(!store.messagePage(owner,profile,id,offset,before===Number.MAX_SAFE_INTEGER?limit:Math.min(limit,before-1))){cache.schedule(owner,profile,id,true);throw new HttpError(409,'历史正在后台补齐','CHAT_HISTORY_SYNC_PENDING')}
+    cache.readLocal(owner,'messages',profile,id,{limit:1})
+    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,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)
+    const raw=ctx.get('last-event-id')||String(ctx.query.after??''),parts=raw.split(':')
+    let cursor=Number(parts.at(-1)),closed=false,lastFlush=0
+    if(parts.length!==2||parts[0]!==transcripts.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.current(ctx)?.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 flush=()=>{
+      clearTimeout(timer);timer=undefined
+      if(!valid()){close();return}
+      const events=transcripts.events(owner,profile,id,cursor)
+      for(const event of events){if(!write(`id: ${transcripts.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)
+    }
+    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();write(`event: ready\ndata: ${JSON.stringify({epoch:transcripts.epoch,cursor})}\n\n`)
+    heartbeat=setInterval(()=>{if(valid())write(': heartbeat\n\n');else close()},15_000);heartbeat.unref()
+  })
+  return router
+}

+ 146 - 0
src/server/chatTranscriptStore.ts

@@ -0,0 +1,146 @@
+import { randomUUID } from 'node:crypto'
+import type { DatabaseSync } from 'node:sqlite'
+import { CHAT_TRANSCRIPT_FEATURE, type TranscriptEvent, type TranscriptMessage, type TranscriptSnapshot } from '../shared/chatTranscript.js'
+
+/** A versioned display projection and replay log in the chat cache transaction. */
+export class ChatTranscriptStore {
+  // Opt in until the three clients finish end-to-end transcript validation.
+  readonly enabled = process.env.HERMES_YAOYAO_ORDINARY_TRANSCRIPTS === '1'
+  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.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) {
+    this.db.prepare('INSERT INTO chat_transcript_events(owner,profile,session_id,type,data,created_at) VALUES(?,?,?,?,?,?)')
+      .run(owner,profile,sessionId,type,JSON.stringify(data),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) {
+    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.tool_call_id}`)
+    const 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:sourceID,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
+    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)
+  }
+  reconcile(owner:string,profile:string,sessionId:string) {
+    const rows=this.db.prepare('SELECT data,position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? ORDER BY position').all(owner,profile,sessionId) as {data:string;position:number}[]
+    const live=new Set<string>()
+    const enriched=this.enrich(owner,profile,sessionId,rows.map(row=>JSON.parse(row.data)))
+    for(const [index,row] of rows.entries()){const source=enriched[index]!;this.upsert(owner,profile,sessionId,source,row.position);const id=this.alias(owner,profile,sessionId,`source:${source.id??source.message_id}`);if(id)live.add(id)}
+    for(const row of this.db.prepare('SELECT id,revision FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0').all(owner,profile,sessionId) as {id:string;revision:number}[]){
+      if(live.has(row.id))continue
+      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,row.id)
+      this.event(owner,profile,sessionId,'message.deleted',{id:row.id,revision:row.revision+1})
+    }
+  }
+  seed(owner:string,profile:string,sessionId:string) {
+    if(this.db.prepare('SELECT 1 FROM chat_transcript_scopes WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionId))return
+    this.reconcile(owner,profile,sessionId)
+    this.db.prepare('INSERT INTO chat_transcript_scopes VALUES(?,?,?)').run(owner,profile,sessionId)
+  }
+  sessionChanged(owner:string,profile:string,sessionId:string,data:Record<string,unknown>) {
+    const row=this.db.prepare('SELECT data FROM chat_transcript_execution WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionId) as {data:string}|undefined
+    const state=row?JSON.parse(row.data):{running:false,queued:false,pending:{}}
+    const p=(data.payload??{}) as Record<string,any>,type=String(data.eventType)
+    state.pending??={}
+    if(type==='command.submitted'){state.pending[p.delivery_id]=state.running;state.queued=state.running;state.running=true}
+    if(type==='command.confirmed'||type==='command.rejected'){
+      if(type==='command.rejected')state.running=state.pending[p.delivery_id]??state.running
+      else{state.running=true;state.queued=p.status==='queued'}
+      delete state.pending[p.delivery_id]
+    }
+    if(['message.start','run.started','approval.request','clarify.request'].includes(type))state.running=true
+    if(type==='route.resumed'&&typeof p.running==='boolean')state.running=p.running
+    if(['message.complete','run.completed','run.failed','error'].includes(type)){
+      state.queued=Number(p.queue_remaining??p.queueRemaining??0)>0
+      state.running=state.queued||Number(p.background_pending??p.backgroundPending??0)>0
+    }
+    this.db.prepare('INSERT INTO chat_transcript_execution VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET data=excluded.data').run(owner,profile,sessionId,JSON.stringify(state))
+    this.event(owner,profile,sessionId,'session.changed',{...data,running:state.running,queued:state.queued})
+  }
+  migrate(owner:string,profile:string,oldID:string,newID:string) {
+    for(const table of ['chat_transcript_messages','chat_transcript_aliases','chat_transcript_scopes','chat_transcript_execution'])this.db.prepare(`UPDATE ${table} SET session_id=? WHERE owner=? AND profile=? AND session_id=?`).run(newID,owner,profile,oldID)
+    this.event(owner,profile,oldID,'session.migrated',{sessionId:newID})
+  }
+  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'])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,data: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 execution=this.db.prepare('SELECT data FROM chat_transcript_execution WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionId) as {data:string}|undefined
+    const run=execution?JSON.parse(execution.data):{}
+    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.epoch,cursor:this.cursor(owner,profile,sessionId),profile,sessionId,running:run.running,queued:run.queued,
+      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||(rows.length>0&&Number(JSON.parse(rows[Math.min(limit,rows.length)-1]!.data).seq)>1),
+      total:Number(this.db.prepare('SELECT COUNT(*) n FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0').get(owner,profile,sessionId)!.n)}
+  }
+}

+ 2 - 0
src/server/realtimeApi.ts

@@ -16,6 +16,7 @@ import { CHAT_MAX_PAYLOAD } from './realtimeProtocol.js'
 import { ChatPushRelayObserver, type ChatNotificationResolver, type PushEventCoordinator, type ChatPushTransportFactory } from './pushEvents.js'
 
 export class RealtimeAPI {
+  transcriptsAvailable = false
   readonly broker: RealtimeBroker
   private observers = new Map<string, ChatPushRelayObserver>()
   constructor(readonly config: ServerConfig, readonly auth: LocalAuthStore, readonly csrf: CsrfProtection,
@@ -169,6 +170,7 @@ export class RealtimeAPI {
       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 ? ['ordinary-chat-transcript-v1'] : [],
           ...(device ? {} : { csrfToken: this.csrf.issue(ctx) }) }
         return
       }

+ 3 - 3
src/server/realtimeBroker.ts

@@ -50,7 +50,7 @@ export class RealtimeBroker {
   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) => void = () => {}
+  onNativeRoute: (owner: string, profile: string, storedId: string, runtimeId: string, running?: boolean) => void = () => {}
   readonly epoch = randomUUID()
   readonly channels = new Map<string, RealtimeChannel>()
   private upstreams = new Map<string, Upstream>()
@@ -283,7 +283,7 @@ export class RealtimeBroker {
         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) this.onNativeRoute(nativeOwner, profile, stored, runtime)
+        if (nativeOwner) this.onNativeRoute(nativeOwner, profile, stored, runtime, r.active)
         if (nativeOwner && (method === 'session.create' || method === 'session.branch')) {
           this.onNativeCommand(nativeOwner, profile, stored, method, {...p,_delivery_id:deliveryID})
         }
@@ -419,7 +419,7 @@ export class RealtimeBroker {
             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)
+              if(owner&&principal.valid())this.onNativeRoute(owner,r.profile,r.stored,r.runtime,r.active)
             }
           }
         }

+ 8 - 0
src/server/routes.ts

@@ -1677,6 +1677,14 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
   })
 
   router.get('/api/app/bootstrap', async (ctx) => {
+    ctx.set('Cache-Control', 'no-store')
+    if (ctx.query.csrfOnly === '1') {
+      json(ctx, 200, {
+        csrfToken: dependencies.csrf.issue(ctx),
+        userId: dependencies.auth.current(ctx)?.id ?? null,
+      })
+      return
+    }
     await bootstrap(ctx, dependencies)
   })
   router.post('/api/app/setup', async (ctx) => {

+ 60 - 0
src/shared/chatTranscript.ts

@@ -0,0 +1,60 @@
+/** Ordinary-chat display protocol. Upstream identities remain server metadata. */
+export const CHAT_TRANSCRIPT_FEATURE = 'ordinary-chat-transcript-v1'
+export interface TranscriptMessage {
+  id: string
+  seq: number
+  revision: number
+  source_message_id: string
+  client_message_id?: string
+  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
+  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
+}
+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
+}

+ 2 - 0
src/shared/types.ts

@@ -201,6 +201,8 @@ export interface ChatRouteState {
   messages: ChatMessage[]
   runtimeSessionId?: string
   historySynced: boolean
+  /** Server history invalidations received since this route was opened. */
+  historySyncRevision?: number
   hasMoreBefore: boolean
   loadedMessageCount: number
   messageTotal: number

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

@@ -111,6 +111,101 @@ describe('cross-client chat subscriptions', () => {
     expect(api.getMessages).toHaveBeenCalledTimes(1)
   })
 
+  it('reconciles a background session after cache synchronization before reusing it', async () => {
+    const first = 'background-sync-first', second = 'background-sync-second'
+    chat.sessions = [session(first), session(second)]
+    realtime.request.mockImplementation((_method: string, params: Record<string, string>) => Promise.resolve({
+      session_id: `runtime-${params.session_id}`, stored_session_id: params.session_id, running: false,
+    }))
+    const user = { id: 'user-background', serverMessageId: 'user-background', sessionId: first,
+      role: 'user', content: '第一个问题', timestamp: 1, stage: 'settled' }
+    let synchronized = false
+    api.getMessages.mockImplementation((id: string) => Promise.resolve({
+      messages: id === first ? [user, { id: synchronized ? 'server-final' : 'event:interim',
+        serverMessageId: synchronized ? 'server-final' : undefined, sessionId: first,
+        role: 'assistant', content: synchronized ? '后台完成的完整结果' : '旧的中间结果', timestamp: 2, stage: 'settled' }] : [],
+      total: id === first ? 2 : 0, returned: id === first ? 2 : 0, hasMore: false,
+    }))
+    await chat.selectSession(first, 'alpha')
+    await chat.selectSession(second, 'alpha')
+    synchronized = true
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: first })
+    expect(chat.activeSessionId).toBe(second)
+    expect(chat.messages).toEqual([])
+    await chat.selectSession(first, 'alpha')
+    await vi.waitFor(() => expect(chat.messages.map(message => message.content)).toEqual(['第一个问题', '后台完成的完整结果']))
+    expect(realtime.request.mock.calls.filter(([method]) => method === 'prompt.submit')).toHaveLength(0)
+  })
+
+  it('coalesces history invalidations that arrive while an older snapshot is loading', async () => {
+    const id = 'sync-during-history-load'
+    chat.sessions = [session(id)]
+    realtime.request.mockResolvedValue({ session_id: 'runtime-1', stored_session_id: id, running: false })
+    const page = (text: string) => ({ messages: [{ id: 'answer-sync', serverMessageId: 'answer-sync',
+      sessionId: id, role: 'assistant', content: text, timestamp: 1, stage: 'settled' }], total: 1, returned: 1, hasMore: false })
+    api.getMessages.mockResolvedValue(page('原缓存'))
+    await chat.selectSession(id, 'alpha')
+    let release!: (value: unknown) => void
+    api.getMessages.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: id })
+    await vi.waitFor(() => expect(api.getMessages).toHaveBeenCalledTimes(2))
+    api.getMessages.mockResolvedValue(page('较新完整历史'))
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: id })
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: id })
+    release(page('已过时快照'))
+    await vi.waitFor(() => expect(chat.messages.map(message => message.content)).toEqual(['较新完整历史']))
+    expect(api.getMessages).toHaveBeenCalledTimes(3)
+    await vi.waitFor(() => expect(chat.activeRouteState?.isLoadingHistory).toBe(false))
+    expect(chat.historySynced).toBe(true)
+  })
+
+  it('merges synchronized history into the current route when SSE replaces its state during the read', async () => {
+    const id = 'stream-during-history-load'
+    chat.sessions = [session(id)]
+    realtime.request.mockResolvedValue({ session_id: 'runtime-1', stored_session_id: id, running: false })
+    const page = (text: string) => ({ messages: [
+      { id: 'prior-user', serverMessageId: 'prior-user', sessionId: id, role: 'user', content: '之前的问题', timestamp: 1, stage: 'settled' },
+      { id: 'prior-answer', serverMessageId: 'prior-answer', sessionId: id, role: 'assistant', content: text, timestamp: 2, stage: 'settled' },
+    ], total: 2, returned: 2, hasMore: false })
+    api.getMessages.mockResolvedValue(page('旧正文'))
+    await chat.selectSession(id, 'alpha')
+    let release!: (value: unknown) => void
+    api.getMessages.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: id })
+    await vi.waitFor(() => expect(api.getMessages).toHaveBeenCalledTimes(2))
+    emit('run.peer_user_message', { message_id: 'live-user', client_message_id: 'live-client', text: '新问题', timestamp: 3, status: 'accepted' })
+    emit('message.start')
+    emit('message.delta', { text: '新回复正在继续' })
+    release(page('之前的完整正文'))
+    await vi.waitFor(() => expect(chat.messages.find(message => message.id === 'prior-answer')?.content).toBe('之前的完整正文'))
+    expect(chat.messages.at(-1)?.content).toBe('新回复正在继续')
+    expect(chat.isStreaming).toBe(true)
+    await vi.waitFor(() => expect(chat.activeRouteState?.isLoadingHistory).toBe(false))
+  })
+
+  it('keeps loaded older messages and follows up a synchronization received during pagination', async () => {
+    const id = 'sync-during-older-page'
+    chat.sessions = [session(id)]
+    realtime.request.mockResolvedValue({ session_id: 'runtime-1', stored_session_id: id, running: false })
+    const recent = (text: string) => ({ messages: [{ id: 'recent-answer', serverMessageId: 'recent-answer',
+      sessionId: id, role: 'assistant', content: text, timestamp: 2, stage: 'settled' }], total: 2, returned: 1, hasMore: true })
+    api.getMessages.mockResolvedValue(recent('旧的最新页'))
+    await chat.selectSession(id, 'alpha')
+    let release!: (value: unknown) => void
+    api.getMessages.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    const older = chat.loadOlder()
+    await vi.waitFor(() => expect(api.getMessages).toHaveBeenCalledTimes(2))
+    emit('session.info', { model: 'new-model' })
+    api.getMessages.mockResolvedValue(recent('补齐后的最新页'))
+    emit('sessions.changed', { reason: 'cache.synced', profile: 'alpha', session_id: id })
+    release({ messages: [{ id: 'older-user', serverMessageId: 'older-user', sessionId: id,
+      role: 'user', content: '之前加载的老消息', timestamp: 1, stage: 'settled' }], total: 2, returned: 1, hasMore: false })
+    await older
+    await vi.waitFor(() => expect(chat.messages.map(message => message.content)).toEqual(['之前加载的老消息', '补齐后的最新页']))
+    expect(api.getMessages).toHaveBeenCalledTimes(3)
+    await vi.waitFor(() => expect(chat.activeRouteState?.isLoadingHistory).toBe(false))
+  })
+
   it('reconciles synchronized history before a delayed submit receipt without duplicating or demoting the user row', async () => {
     chat.sessions = [session('identity-session')]
     realtime.request.mockResolvedValue({ session_id: 'runtime-1', stored_session_id: 'identity-session', running: false })

+ 261 - 0
tests/client/csrfRecovery.test.ts

@@ -0,0 +1,261 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type Koa from 'koa'
+import { CsrfProtection } from '../../src/server/security'
+import { apiRequest, clearApiSecurityContext, onApiUnauthorized, setApiCsrfToken } from '@/api/client'
+
+const refreshPath = '/api/app/bootstrap?csrfOnly=1'
+const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
+  status, headers: { 'content-type': 'application/json' },
+})
+const invalid = () => response({ code: 'invalid_csrf', message: 'CSRF token is invalid or missing' }, 403)
+afterEach(() => { clearApiSecurityContext(); vi.useRealTimers(); vi.unstubAllGlobals() })
+
+describe('long-lived desktop CSRF recovery', () => {
+  it('renews an expired eight-hour signed cookie and executes the original action exactly once', async () => {
+    const csrf = new CsrfProtection()
+    let clock = 1000, cookie = '', expiresAt = 0, executed = 0
+    const renew = () => {
+      const headers: Record<string, unknown> = {}
+      const ctx = { response: { headers }, get: () => clock < expiresAt ? cookie : '',
+        set: (key: string, value: unknown) => { headers[key.toLowerCase()] = value } } as unknown as Koa.Context
+      const token = csrf.issue(ctx)
+      if (headers['set-cookie']) {
+        const value = (headers['set-cookie'] as string[])[0]!
+        expect(value).toContain('Max-Age=28800')
+        cookie = value.split(';')[0]!; expiresAt = clock + 28_800_000
+      }
+      return token
+    }
+    const old = renew()
+    setApiCsrfToken(old, 'account-a')
+    clock += 28_800_001
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+      if (path === refreshPath) return response({ csrfToken: renew(), userId: 'account-a' })
+      if (!csrf.verify(clock < expiresAt ? cookie : '', new Headers(init?.headers).get('X-CSRF-Token') ?? undefined)) return invalid()
+      executed += 1
+      return response({ accepted: true })
+    })
+    vi.stubGlobal('fetch', fetchMock)
+    const body = { requestId: 'original-send-id', content: '只发送一次' }
+    await expect(apiRequest('/api/app/conversations/session/messages', {
+      method: 'POST', body, headers: { 'Idempotency-Key': 'original-send-id' },
+    })).resolves.toEqual({ accepted: true })
+    expect(executed).toBe(1)
+    const mutations = fetchMock.mock.calls.filter(([path]) => path !== refreshPath)
+    expect(mutations).toHaveLength(2)
+    expect(mutations.map(([, init]) => init?.body)).toEqual([JSON.stringify(body), JSON.stringify(body)])
+    expect(mutations.map(([, init]) => new Headers(init?.headers).get('Idempotency-Key'))).toEqual(['original-send-id', 'original-send-id'])
+    expect(new Headers(mutations[0]![1]?.headers).get('X-CSRF-Token')).toBe(old)
+    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 () => {
+    setApiCsrfToken('expired', 'account-a')
+    let release!: (value: Response) => void
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+      if (path === refreshPath) return new Promise<Response>(resolve => { release = resolve })
+      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 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' }))
+    await Promise.all(jobs)
+    expect(fetchMock.mock.calls.filter(([path]) => path === refreshPath)).toHaveLength(1)
+    for (const path of paths) expect(fetchMock.mock.calls.filter(([value]) => value === path)).toHaveLength(2)
+  })
+
+  it('prepares a missing token and accepts a full bootstrap from an older server', async () => {
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath
+      ? response({ csrfToken: 'legacy-token', user: { id: 'account-a' }, authRequired: true, profiles: [] })
+      : response({ ok: true }))
+    vi.stubGlobal('fetch', fetchMock)
+    await apiRequest('/api/app/account/avatar', { method: 'PUT', body: {} })
+    expect(fetchMock.mock.calls.map(([path]) => path)).toEqual([refreshPath, '/api/app/account/avatar'])
+  })
+
+  it.each([['invalid_origin', 403], ['permission_denied', 403], ['upstream_failure', 500]])(
+    'does not retry %s failures', async (code, status) => {
+      setApiCsrfToken('valid', 'account-a')
+      const fetchMock = vi.fn(async () => response({ code }, Number(status)))
+      vi.stubGlobal('fetch', fetchMock)
+      await expect(apiRequest('/api/app/action', { method: 'POST', body: {} })).rejects.toMatchObject({ code })
+      expect(fetchMock).toHaveBeenCalledTimes(1)
+    },
+  )
+
+  it('does not retry network failures with an unknown submission result', async () => {
+    setApiCsrfToken('valid', 'account-a')
+    const fetchMock = vi.fn(async () => { throw new TypeError('Connection lost') })
+    vi.stubGlobal('fetch', fetchMock)
+    await expect(apiRequest('/api/app/action', { method: 'POST', body: {} })).rejects.toMatchObject({ code: 'NETWORK_ERROR' })
+    expect(fetchMock).toHaveBeenCalledTimes(1)
+  })
+
+  it('stops after one retry when the refreshed token is still rejected', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath
+      ? response({ csrfToken: 'new-token', userId: 'account-a' }) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    await expect(apiRequest('/api/app/action', { method: 'POST', body: {} })).rejects.toMatchObject({ code: 'invalid_csrf' })
+    expect(fetchMock.mock.calls.map(([path]) => path)).toEqual(['/api/app/action', refreshPath, '/api/app/action'])
+  })
+
+  it('does not replay an old account action after a cookie account change', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    const expired = vi.fn(), unsubscribe = onApiUnauthorized(expired)
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath
+      ? response({ csrfToken: 'account-b-token', userId: 'account-b' }) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    try {
+      await expect(apiRequest('/api/app/action', { method: 'POST', body: {} })).rejects.toMatchObject({ code: 'SECURITY_CONTEXT_CHANGED' })
+      expect(fetchMock.mock.calls.filter(([path]) => path !== refreshPath)).toHaveLength(1)
+      expect(expired).toHaveBeenCalledTimes(1)
+    } finally { unsubscribe() }
+  })
+
+  it('discards a refresh completed after local logout', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    let release!: (value: Response) => void
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath
+      ? new Promise<Response>(resolve => { release = resolve }) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    const sending = apiRequest('/api/app/action', { method: 'POST', body: {} }).catch(error => error)
+    await vi.waitFor(() => expect(release).toBeTypeOf('function'))
+    clearApiSecurityContext(); setApiCsrfToken('account-b-token', 'account-b')
+    release(response({ csrfToken: 'late-a-token', userId: 'account-a' }))
+    expect(await sending).toMatchObject({ code: 'SECURITY_CONTEXT_CHANGED' })
+    expect(fetchMock.mock.calls.filter(([path]) => path !== refreshPath)).toHaveLength(1)
+  })
+
+  it('cancels one waiting request without cancelling another request sharing the refresh', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    let release!: (value: Response) => void
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => path === refreshPath
+      ? new Promise<Response>(resolve => { release = resolve })
+      : new Headers(init?.headers).get('X-CSRF-Token') === 'renewed' ? response({ ok: true }) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    const abort = new AbortController()
+    const cancelled = apiRequest('/api/app/cancelled', { method: 'POST', signal: abort.signal }).catch(error => error)
+    const retained = apiRequest('/api/app/retained', { method: 'POST' })
+    await vi.waitFor(() => expect(release).toBeTypeOf('function'))
+    abort.abort()
+    expect(await cancelled).toMatchObject({ code: 'REQUEST_ABORTED' })
+    release(response({ csrfToken: 'renewed', userId: 'account-a' }))
+    await expect(retained).resolves.toEqual({ ok: true })
+    expect(fetchMock.mock.calls.filter(([path]) => path === '/api/app/cancelled')).toHaveLength(1)
+    expect(fetchMock.mock.calls.filter(([path]) => path === '/api/app/retained')).toHaveLength(2)
+  })
+
+  it('does not send an already cancelled action', async () => {
+    const fetchMock = vi.fn(), abort = new AbortController(); abort.abort()
+    vi.stubGlobal('fetch', fetchMock)
+    await expect(apiRequest('/api/app/action', { method: 'POST', signal: abort.signal })).rejects.toMatchObject({ code: 'REQUEST_ABORTED' })
+    expect(fetchMock).not.toHaveBeenCalled()
+  })
+
+  it('honors the original request deadline while renewal is pending', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    let release!: (value: Response) => void
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath
+      ? new Promise<Response>(resolve => { release = resolve }) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    await expect(apiRequest('/api/app/action', { method: 'POST', timeoutMs: 20 })).rejects.toMatchObject({ code: 'REQUEST_ABORTED' })
+    release(response({ csrfToken: 'renewed', userId: 'account-a' }))
+    await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
+    expect(fetchMock.mock.calls.filter(([path]) => path !== refreshPath)).toHaveLength(1)
+  })
+
+  it('uses an already renewed token for a late CSRF rejection without renewing twice', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    let rejectLate!: (value: Response) => void
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+      if (path === refreshPath) return response({ csrfToken: 'renewed', userId: 'account-a' })
+      if (new Headers(init?.headers).get('X-CSRF-Token') === 'renewed') return response({ ok: true })
+      return path.endsWith('/late') ? new Promise<Response>(resolve => { rejectLate = resolve }) : invalid()
+    })
+    vi.stubGlobal('fetch', fetchMock)
+    const late = apiRequest('/api/app/late', { method: 'POST' })
+    await apiRequest('/api/app/first', { method: 'POST' })
+    rejectLate(invalid())
+    await late
+    expect(fetchMock.mock.calls.filter(([path]) => path === refreshPath)).toHaveLength(1)
+  })
+
+  it('keeps the login context when renewal returns malformed data and allows a later retry', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    const expired = vi.fn(), unsubscribe = onApiUnauthorized(expired)
+    const fetchMock = vi.fn(async (path: string) => path === refreshPath ? response({}) : invalid())
+    vi.stubGlobal('fetch', fetchMock)
+    try {
+      await expect(apiRequest('/api/app/action', { method: 'POST' })).rejects.toMatchObject({ code: 'CSRF_REFRESH_FAILED' })
+      expect(expired).not.toHaveBeenCalled()
+      fetchMock.mockImplementation(async (path: string, init?: RequestInit) => path === refreshPath
+        ? response({ csrfToken: 'valid-again', userId: 'account-a' })
+        : new Headers(init?.headers).get('X-CSRF-Token') === 'valid-again' ? response({ ok: true }) : invalid())
+      await expect(apiRequest('/api/app/action', { method: 'POST' })).resolves.toEqual({ ok: true })
+    } finally { unsubscribe() }
+  })
+
+  it('preserves the original upload body while renewing its token', async () => {
+    setApiCsrfToken('expired', 'account-a')
+    const body = new FormData(); body.set('caption', '原始内容'); body.set('file', new Blob(['original']), 'original.txt')
+    const snapshots: Array<[string | null, string]> = []
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+      if (path === refreshPath) {
+        body.set('caption', '后续编辑'); body.set('file', new Blob(['new']), 'new.txt')
+        return response({ csrfToken: 'new-token', userId: 'account-a' })
+      }
+      const sent = init?.body as FormData
+      snapshots.push([sent.get('caption') as string | null, (sent.get('file') as File).name])
+      return snapshots.length === 1 ? invalid() : response({ ok: true })
+    })
+    vi.stubGlobal('fetch', fetchMock)
+    await apiRequest('/api/app/uploads', { method: 'POST', body })
+    expect(snapshots).toEqual([['原始内容', 'original.txt'], ['原始内容', 'original.txt']])
+  })
+
+  it('revalidates another window token instead of silently executing under its account', async () => {
+    let receive!: (event: { data: unknown }) => void
+    vi.stubGlobal('BroadcastChannel', class {
+      addEventListener(_type: string, handler: typeof receive) { receive = handler }
+      postMessage() {}
+    })
+    vi.resetModules()
+    const client = await import('@/api/client')
+    client.setApiCsrfToken('account-a-token', 'account-a')
+    receive({ data: 'account-b-token' })
+    const fetchMock = vi.fn(async () => response({ csrfToken: 'account-b-token', userId: 'account-b' }))
+    vi.stubGlobal('fetch', fetchMock)
+    try {
+      await expect(client.apiRequest('/api/app/action', { method: 'POST' })).rejects.toMatchObject({ code: 'SECURITY_CONTEXT_CHANGED' })
+      expect(fetchMock).toHaveBeenCalledExactlyOnceWith(refreshPath, expect.objectContaining({ credentials: 'include' }))
+    } finally { client.clearApiSecurityContext() }
+  })
+
+  it('serializes expired-cookie renewal across windows using the origin lock', async () => {
+    let tail = Promise.resolve(), cookie = '', issued = 0
+    const lock = vi.fn((_name: string, action: () => Promise<void>) => {
+      const job = tail.then(action); tail = job.catch(() => {}); return job
+    })
+    vi.stubGlobal('navigator', { locks: { request: lock } })
+    vi.resetModules()
+    const otherWindow = await import('@/api/client')
+    setApiCsrfToken('expired', 'account-a'); otherWindow.setApiCsrfToken('expired', 'account-a')
+    const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+      if (path === refreshPath) {
+        const token = cookie || `renewed-${++issued}`
+        await Promise.resolve(); cookie = token
+        return response({ csrfToken: token, userId: 'account-a' })
+      }
+      return new Headers(init?.headers).get('X-CSRF-Token') === cookie ? response({ ok: true }) : invalid()
+    })
+    vi.stubGlobal('fetch', fetchMock)
+    try {
+      await Promise.all([apiRequest('/api/app/first-window', { method: 'POST' }), otherWindow.apiRequest('/api/app/second-window', { method: 'POST' })])
+      expect(issued).toBe(1)
+      expect(lock).toHaveBeenCalledTimes(2)
+    } finally { otherWindow.clearApiSecurityContext() }
+  })
+})

+ 56 - 0
tests/client/updateCheckDialog.test.ts

@@ -0,0 +1,56 @@
+import { mount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import UpdateCheckDialog from '@/components/app/UpdateCheckDialog.vue'
+import { checkSystemUpdate, systemUpdateStatus, type SystemUpdateStatus } from '@/api/systemUpdate'
+
+vi.mock('@/api/systemUpdate', () => ({ checkSystemUpdate: vi.fn(), systemUpdateStatus: vi.fn() }))
+const current = { schemaVersion: 1 as const, webVersion: '0.4.17', releaseVersion: '0.4.17', gitTag: 'v0.4.17' }
+const status: SystemUpdateStatus = { current, latest: current, updateAvailable: false, installationMode: 'source', supported: true, canRollback: false }
+const render = () => mount(UpdateCheckDialog, { global: { stubs: { StandaloneDialog: { template: '<div><slot /></div>' }, AppIcon: true } } })
+beforeEach(() => { vi.mocked(systemUpdateStatus).mockResolvedValue(status); vi.mocked(checkSystemUpdate).mockResolvedValue(status) })
+afterEach(() => vi.resetAllMocks())
+
+it('checks immediately, keeps the installed version visible and disables repeat checks until finished', async () => {
+  let finish!: (value: SystemUpdateStatus) => void
+  vi.mocked(checkSystemUpdate).mockReturnValue(new Promise(resolve => { finish = resolve }))
+  const wrapper = render()
+  await flushPromises()
+  expect(wrapper.text()).toContain('正在检测更新')
+  expect(wrapper.text()).toContain('0.4.17')
+  expect(wrapper.get('button').attributes()).toHaveProperty('disabled')
+  finish(status); await flushPromises()
+  expect(wrapper.get('[role="status"]').text()).toBe('当前已是最新版本')
+  expect(checkSystemUpdate).toHaveBeenCalledTimes(1)
+  wrapper.unmount()
+})
+
+it('shows a new version and opens update management only on request', async () => {
+  vi.mocked(checkSystemUpdate).mockResolvedValue({ ...status, latest: { ...current, webVersion: '0.4.18' }, updateAvailable: true, releasePageUrl: 'https://github.com/Lsamien/yaoyao/releases/tag/v0.4.18' })
+  const wrapper = render(); await flushPromises()
+  expect(wrapper.text()).toContain('发现新版本 0.4.18')
+  expect(wrapper.get('a').attributes('href')).toContain('/releases/tag/v0.4.18')
+  expect(wrapper.emitted('manage')).toBeUndefined()
+  await wrapper.findAll('button')[1]!.trigger('click')
+  expect(wrapper.emitted('manage')).toHaveLength(1)
+  wrapper.unmount()
+})
+
+it('reports failed checks without claiming the cached version is latest and supports retry', async () => {
+  vi.mocked(checkSystemUpdate).mockRejectedValueOnce(new Error('无法连接 GitHub'))
+  const wrapper = render(); await flushPromises()
+  expect(wrapper.get('[role="alert"]').text()).toBe('无法连接 GitHub')
+  expect(wrapper.text()).not.toContain('已是最新')
+  expect(wrapper.text()).toContain('未获取')
+  await wrapper.get('button').trigger('click'); await flushPromises()
+  expect(wrapper.text()).toContain('当前已是最新版本')
+  wrapper.unmount()
+})
+
+it('explains externally managed installations without offering an unsupported update', async () => {
+  vi.mocked(checkSystemUpdate).mockResolvedValue({ ...status, latest: { ...current, webVersion: '0.4.18' }, updateAvailable: true, supported: false, unsupportedReason: '请使用 Docker Compose 更新', releasePageUrl: 'javascript:alert(1)' })
+  const wrapper = render(); await flushPromises()
+  expect(wrapper.text()).toContain('请使用 Docker Compose 更新')
+  expect(wrapper.text()).not.toContain('前往更新')
+  expect(wrapper.find('a').exists()).toBe(false)
+  wrapper.unmount()
+})

+ 48 - 4
tests/client/workspaceShell.test.ts

@@ -50,6 +50,7 @@ async function mountShell(start = '/chat') {
       stubs: {
         SettingsCenterDialog: SettingsCenterDialogStub,
         BotPluginsDialog: defineComponent({emits:['close'],template:'<div data-testid="plugins-dialog"><button @click="$emit(\'close\')">关闭已连接应用</button></div>'}),
+        UpdateCheckDialog: defineComponent({emits:['close', 'manage'],template:'<div data-testid="update-dialog"><button @click="$emit(\'close\')">关闭检测更新</button><button @click="$emit(\'manage\')">前往更新</button></div>'}),
         AboutDialog: defineComponent({emits:['close'],template:'<div data-testid="about-dialog"><button @click="$emit(\'close\')">关闭关于</button></div>'}),
         AgentAvatar: true,
         AppIcon: true,
@@ -62,6 +63,7 @@ async function mountShell(start = '/chat') {
 
 beforeEach(() => {
   localStorage.clear()
+  delete window.yaoyaoDesktop
 })
 
 afterEach(() => {
@@ -117,7 +119,7 @@ describe('Workspace shell account controls', () => {
     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 模式'])
+    expect([...actions].map(button => button.textContent?.trim())).toEqual(['设置', '关于', '检测更新', '帮助', '进入 Bot 模式'])
     actions[0]!.click()
     await wrapper.vm.$nextTick()
     const settings = wrapper.get('[data-testid="settings-center"]')
@@ -142,7 +144,7 @@ describe('Workspace shell account controls', () => {
 
     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"]')[3]!.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()
@@ -152,6 +154,7 @@ describe('Workspace shell account controls', () => {
 it('uses the reference Bot list header and keeps mode changes in settings', async () => {
   const wrapper = await mountShell('/conversations')
   const rail = wrapper.get('.desktop-sidebar')
+  expect(wrapper.find('.sidebar-settings-trigger').exists()).toBe(false)
   expect(rail.find('.sidebar-feature-nav').exists()).toBe(false)
   expect(rail.find('.sidebar-primary-action').exists()).toBe(false)
   expect(rail.find('.sidebar-footer').exists()).toBe(true)
@@ -164,7 +167,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-security')
@@ -210,7 +213,7 @@ it('shows Bot tools only in Bot mode and restores keyboard focus after closing',
 
 it.each(['/chat', '/history', '/conversations', '/kanban', '/files'])('opens an independent About dialog from the menu in %s', async path => {
   const wrapper = await mountShell(path)
-  const trigger = wrapper.get<HTMLButtonElement>('.desktop-sidebar .sidebar-settings-trigger')
+  const trigger = wrapper.get<HTMLButtonElement>(path === '/conversations' ? '.desktop-sidebar .sidebar-account-switcher__main' : '.desktop-sidebar .sidebar-settings-trigger')
   await trigger.trigger('click')
   const item = [...document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu button')].find(b => b.textContent?.trim() === '关于')!
   item.click(); await flushPromises()
@@ -230,3 +233,44 @@ it('navigates to the independent automation route without opening settings', asy
   expect(wrapper.find('[data-testid="settings-center"]').exists()).toBe(false)
   wrapper.unmount()
 })
+
+
+it('checks Web updates from the Bot account menu and preserves focus through update settings', async () => {
+  const wrapper = await mountShell('/conversations')
+  const trigger = wrapper.get<HTMLButtonElement>('.desktop-sidebar .sidebar-account-switcher__main')
+  await trigger.trigger('click')
+  ;[...document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu button')].find(b => b.textContent?.trim() === '检测更新')!.click()
+  await flushPromises()
+  expect(wrapper.find('[data-testid="update-dialog"]').exists()).toBe(true)
+  await wrapper.get('[data-testid="update-dialog"] button:nth-child(2)').trigger('click')
+  expect(wrapper.get('[data-testid="settings-center"]').attributes('data-page')).toBe('system-update')
+  await wrapper.get('[data-testid="close-settings"]').trigger('click')
+  await flushPromises()
+  expect(document.activeElement).toBe(trigger.element)
+  wrapper.unmount()
+})
+
+it('opens the native updater, prevents duplicate clicks and lets a failed opening retry', async () => {
+  const openUpdates = vi.fn().mockRejectedValueOnce(new Error('窗口打开失败')).mockResolvedValueOnce(undefined)
+  window.yaoyaoDesktop = { openUpdates, openComputer: vi.fn(), computerClosed: vi.fn(), onComputerClose: vi.fn() }
+  const wrapper = await mountShell('/conversations')
+  await wrapper.get('.desktop-sidebar .sidebar-account-switcher__main').trigger('click')
+  const item = [...document.querySelectorAll<HTMLButtonElement>('.workspace-settings-menu button')].find(b => b.textContent?.trim() === '检测更新')!
+  item.click(); item.click()
+  await flushPromises()
+  expect(openUpdates).toHaveBeenCalledTimes(1)
+  expect(document.querySelector('[role="alert"]')?.textContent).toContain('窗口打开失败')
+  item.click(); await flushPromises()
+  expect(openUpdates).toHaveBeenCalledTimes(2)
+  expect(document.querySelector('.workspace-settings-menu')).toBeNull()
+  expect(wrapper.find('[data-testid="update-dialog"]').exists()).toBe(false)
+  wrapper.unmount()
+})
+
+it('does not expose server update controls to a non-admin browser account', async () => {
+  const wrapper = await mountShell('/conversations')
+  await wrapper.setProps({ isAdmin: false })
+  await wrapper.get('.desktop-sidebar .sidebar-account-switcher__main').trigger('click')
+  expect(document.querySelector('.workspace-settings-menu')?.textContent).not.toContain('检测更新')
+  wrapper.unmount()
+})

+ 2 - 2
tests/e2e/serverIdentity.spec.ts

@@ -1,6 +1,6 @@
 import {expect,test,type Page} from '@playwright/test'
-async function login(page:Page){await page.goto('/conversations');await page.getByRole('textbox',{name:'账号',exact:true}).fill('fixture');await page.getByRole('textbox',{name:'密码',exact:true}).fill('fixture-pass');await page.getByRole('button',{name:'登录',exact:true}).click();await expect(page.getByRole('button',{name:'设置与模式'}).first()).toBeVisible()}
-async function settings(page:Page){await page.getByRole('button',{name:'设置与模式'}).first().click();await page.getByRole('menuitem',{name:'进入设置',exact:true}).click();await expect(page.locator('input[name=server-display-name]')).toBeVisible();await expect(page.locator('.settings-center-layer')).toHaveCSS('opacity','1')}
+async function login(page:Page){await page.goto('/conversations');await page.getByRole('textbox',{name:'账号',exact:true}).fill('fixture');await page.getByRole('textbox',{name:'密码',exact:true}).fill('fixture-pass');await page.getByRole('button',{name:'登录',exact:true}).click();await expect(page.locator('.desktop-sidebar .sidebar-account-switcher__main')).toBeVisible()}
+async function settings(page:Page){await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click();await page.getByRole('menuitem',{name:'进入设置',exact:true}).click();await expect(page.locator('input[name=server-display-name]')).toBeVisible();await expect(page.locator('.settings-center-layer')).toHaveCSS('opacity','1')}
 test('shares a server name across two clients without reloading',async({page,browser},testInfo)=>{
   await login(page);await settings(page)
   const observerContext=await browser.newContext({baseURL:'http://127.0.0.1:18804',viewport:{width:1100,height:850}})

+ 3 - 3
tests/e2e/team-tools.spec.ts

@@ -147,7 +147,7 @@ test('registers an execution node, downloads its private config and disables it'
   await page.getByRole('textbox',{name:'账号',exact:true}).fill('fixture')
   await page.getByRole('textbox',{name:'密码',exact:true}).fill('fixture-pass')
   await page.getByRole('button',{name:'登录',exact:true}).click()
-  await page.getByRole('button',{name:/^(打开设置中心|设置与模式)$/}).first().click()
+  await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
   await page.getByRole('menuitem',{name:'设置',exact:true}).click()
   const dialog=page.getByRole('dialog',{name:'设置中心'})
   await dialog.getByRole('button',{name:'Hermes 连接',exact:true}).click()
@@ -207,7 +207,7 @@ async function login(page:any,ready=false){
 }
 test('persists idle-stop settings and the host environment checkbox on desktop and mobile',async({page},testInfo)=>{
  await login(page,true)
- await page.getByRole('button',{name:'设置与模式',exact:true}).first().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click()
+ await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click();await page.getByRole('menuitem',{name:'设置',exact:true}).click()
  const settings=page.getByRole('dialog',{name:'设置中心'});await settings.getByRole('button',{name:'本地虚拟机',exact:true}).click()
  const timeout=settings.getByRole('combobox',{name:'虚拟机空闲停止时间',exact:true})
  await timeout.selectOption('30');await expect(timeout).toHaveValue('30')
@@ -249,7 +249,7 @@ test('cloud VM keeps its own selection while the host option can be checked and
 test('Local VM settings replace the image catalog and prepare the managed desktop',async({page},testInfo)=>{
  await login(page)
  await expect(page.getByRole('button',{name:'电脑与环境',exact:true})).toHaveCount(0)
- await page.getByRole('button',{name:'设置与模式',exact:true}).first().click()
+ await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
  await page.getByRole('menuitem',{name:'设置',exact:true}).click()
  const settings=page.getByRole('dialog',{name:'设置中心'})
  await settings.getByRole('button',{name:'本地虚拟机',exact:true}).click()

+ 55 - 6
tests/e2e/workspace-chat.spec.ts

@@ -222,8 +222,8 @@ test('created roles and editable teams share a durable chat list without plugin
   await expect(rail.locator('.sidebar-footer')).toBeVisible()
   await expect(rail.locator('.sidebar-account-switcher__main')).toContainText('fixture')
   await expect(rail.locator('.sidebar-account-switcher__main .account-initial-avatar')).toHaveText('F')
-  await rail.getByRole('button', { name: '设置与模式', exact: true }).click()
-  await expect(page.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['设置', '关于', '帮助', '进入聊天模式'])
+  await rail.locator('.sidebar-account-switcher__main').click()
+  await expect(page.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['设置', '关于', '检测更新', '帮助', '进入聊天模式'])
   await page.getByRole('menuitem', { name: '关于', exact: true }).click()
   const about = page.getByRole('dialog', { name: '关于夭夭 AI', exact: true })
   await expect(about).toBeVisible()
@@ -249,7 +249,7 @@ test('created roles and editable teams share a durable chat list without plugin
   await page.screenshot({ path: testInfo.outputPath('independent-automations.png') })
   await page.getByRole('button', { name: '返回聊天', exact: true }).click()
   await expect(page).toHaveURL(/\/conversations$/)
-  await rail.getByRole('button', { name: '设置与模式', exact: true }).click()
+  await rail.locator('.sidebar-account-switcher__main').click()
   await page.getByRole('menuitem', { name: '设置', exact: true }).click()
   const settings = page.getByRole('dialog', { name: '设置中心', exact: true })
   await expect(settings.locator('.settings-account-summary')).toContainText('fixture')
@@ -287,7 +287,7 @@ test('created roles and editable teams share a durable chat list without plugin
   await expect(rail.getByRole('button', { name: '聊天', exact: true })).toHaveCount(0)
   await rail.getByRole('button', { name: '设置与模式', exact: true }).click()
   const settingsMenu = page.getByRole('menu', { name: '账号菜单', exact: true })
-  await expect(settingsMenu.getByRole('menuitem')).toHaveText(['设置', '关于', '帮助', '进入 Bot 模式'])
+  await expect(settingsMenu.getByRole('menuitem')).toHaveText(['设置', '关于', '检测更新', '帮助', '进入 Bot 模式'])
   await page.screenshot({ path: testInfo.outputPath('chat-settings-mode-menu.png') })
   await settingsMenu.getByRole('menuitem', { name: '设置', exact: true }).click()
   await expect(page.getByRole('dialog', { name: '设置中心', exact: true })).toBeVisible()
@@ -542,7 +542,7 @@ test('created roles and editable teams share a durable chat list without plugin
 
 test('subaccount allocation and Bot-only navigation work through the browser', async ({ page, browser }, testInfo) => {
   await login(page)
-  await page.locator('.desktop-sidebar').getByRole('button', { name: '设置与模式', exact: true }).click()
+  await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
   await page.getByRole('menuitem', { name: '设置', exact: true }).click()
   const settings = page.getByRole('dialog', { name: '设置中心', exact: true })
   await settings.getByRole('button', { name: '用户与权限', exact: true }).click()
@@ -566,7 +566,7 @@ test('subaccount allocation and Bot-only navigation work through the browser', a
   await child.getByRole('button', { name: '保存并进入夭夭', exact: true }).click()
   await expect(child).toHaveURL(/\/conversations$/)
   await expect(child.getByRole('heading', { name: '还没有聊天' })).toBeVisible()
-  await child.locator('.desktop-sidebar').getByRole('button', { name: '设置与模式', exact: true }).click()
+  await child.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
   await expect(child.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['设置', '关于', '帮助'])
   await child.keyboard.press('Escape')
   await openCreate(child, '新建 Bot')
@@ -703,3 +703,52 @@ test('Bot transcript switches from cache and preserves the viewport during histo
     await page.request.delete(`/api/app/agents/${seed.agentId}`, { headers })
   }
 })
+
+test('account update checks show loading, available versions and retry on desktop and phone', async ({ page }, testInfo) => {
+  await login(page)
+  const current = { schemaVersion: 1, releaseVersion: '0.4.17', webVersion: '0.4.17', gitTag: 'v0.4.17' }
+  const status = { current, latest: { ...current, webVersion: '0.4.18', releaseVersion: '0.4.18', gitTag: 'v0.4.18' }, supported: true, installationMode: 'source', updateAvailable: true, canRollback: false, releasePageUrl: 'https://github.com/Lsamien/yaoyao/releases/tag/v0.4.18' }
+  await page.route('**/api/app/system/update/status', route => route.fulfill({ json: status }))
+  let failed = false
+  let releaseCheck: (() => void) | undefined
+  await page.route('**/api/app/system/update/check', async route => {
+    await new Promise<void>(resolve => { releaseCheck = resolve })
+    await route.fulfill(failed ? { status: 502, json: { error: '暂时无法连接更新服务' } } : { json: status })
+  })
+  for (const width of [1280, 390]) {
+    await page.setViewportSize({ width, height: 866 })
+    await page.emulateMedia({ colorScheme: width === 390 ? 'dark' : 'light', reducedMotion: 'reduce' })
+    const account = page.locator('.desktop-sidebar .sidebar-account-switcher__main')
+    await expect(page.locator('.sidebar-settings-trigger')).toHaveCount(0)
+    await account.click()
+    // The menu's dismiss layer receives the second pointer click over the account.
+    const accountRect = (await account.boundingBox())!
+    await page.mouse.click(accountRect.x + accountRect.width / 2, accountRect.y + accountRect.height / 2)
+    await expect(page.getByRole('menu', { name: '账号菜单' })).toHaveCount(0)
+    await account.click()
+    await page.screenshot({ path: testInfo.outputPath(`update-menu-${width}.png`) })
+    await page.getByRole('menuitem', { name: '检测更新', exact: true }).click()
+    const dialog = page.getByRole('dialog', { name: '检测更新', exact: true })
+    await expect(dialog.getByRole('status')).toHaveText('正在检测更新…')
+    await expect(dialog.getByRole('button', { name: '正在检测…', exact: true })).toBeDisabled()
+    await expect.poll(() => Boolean(releaseCheck)).toBe(true)
+    releaseCheck!(); releaseCheck = undefined
+    await expect(dialog.getByRole('status')).toHaveText('发现新版本 0.4.18')
+    await page.screenshot({ path: testInfo.outputPath(`update-available-${width}.png`) })
+    expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
+    failed = true
+    await dialog.getByRole('button', { name: '重新检测', exact: true }).click()
+    await expect.poll(() => Boolean(releaseCheck)).toBe(true)
+    releaseCheck!(); releaseCheck = undefined
+    await expect(dialog.getByRole('alert')).toContainText('暂时无法连接更新服务')
+    await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toHaveCount(0)
+    failed = false
+    await dialog.getByRole('button', { name: '重试', exact: true }).click()
+    await expect.poll(() => Boolean(releaseCheck)).toBe(true)
+    releaseCheck!(); releaseCheck = undefined
+    await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toBeVisible()
+    await page.keyboard.press('Escape')
+    await expect(dialog).toHaveCount(0)
+    await expect(account).toBeFocused()
+  }
+})

+ 1 - 1
tests/live/dockerPlatform.live.test.ts

@@ -69,7 +69,7 @@ it.skipIf(!process.env.YAOYAO_PLATFORM_IMAGE||!process.env.YAOYAO_COMPUTER_IMAGE
     await page.getByRole('textbox',{name:'账号',exact:true}).fill('docker-fixture')
     await page.getByRole('textbox',{name:'密码',exact:true}).fill('docker-fixture-password')
     await page.getByRole('button',{name:'登录',exact:true}).click()
-    await page.getByRole('button',{name:'设置与模式',exact:true}).first().click()
+    await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
     await page.getByRole('menuitem',{name:'进入设置',exact:true}).click()
     const settings=page.getByRole('dialog',{name:'设置中心'})
     await settings.getByRole('button',{name:'本地虚拟机',exact:true}).click()

+ 2 - 2
tests/live/localVm.live.test.ts

@@ -51,7 +51,7 @@ it.skipIf(!process.env.YAOYAO_HERMES_PYTHON||!process.env.YAOYAO_COMPUTER_IMAGE)
   await page.getByRole('textbox',{name:'账号',exact:true}).fill('vm-ui-fixture')
   await page.getByRole('textbox',{name:'密码',exact:true}).fill('vm-ui-fixture-password')
   await page.getByRole('button',{name:'登录',exact:true}).click()
-  await page.getByRole('button',{name:'设置与模式',exact:true}).first().click()
+  await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
   await page.getByRole('menuitem',{name:'进入设置',exact:true}).click()
   const settings=page.getByRole('dialog',{name:'设置中心'})
   await settings.getByRole('button',{name:'本地虚拟机',exact:true}).click()
@@ -121,7 +121,7 @@ it.skipIf(!process.env.YAOYAO_HERMES_PYTHON||!process.env.YAOYAO_COMPUTER_IMAGE)
   const ordinaryWorkId='sharing-policy-ordinary-chat'
   app.workspace.put(owner,'turn',ordinaryWorkId,{agentId:chatting.id,status:'running'})
   try{
-    await page.getByRole('button',{name:'设置与模式',exact:true}).first().click()
+    await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
     await page.getByRole('menuitem',{name:'进入设置',exact:true}).click()
     await settings.getByRole('button',{name:'本地虚拟机',exact:true}).click()
     page.once('dialog',dialog=>{void dialog.accept()})

+ 22 - 1
tests/server/app.test.ts

@@ -5,7 +5,7 @@ import request from 'supertest'
 import { afterEach, describe, expect, it } from 'vitest'
 import { createApplication as createUnauthenticatedApplication, type ApplicationRuntime } from '../../src/server/app.js'
 import type { ServerConfig } from '../../src/server/config.js'
-import { createAuthenticatedApplication as createApplication } from './authenticatedApplication.js'
+import { createAuthenticatedApplication as createApplication, createUserAuthenticatedApplication } from './authenticatedApplication.js'
 import { saveFileAccess } from '../../src/server/fileAccess.js'
 
 interface RecordedRequest {
@@ -106,6 +106,27 @@ function cookieHeader(response: request.Response): string {
 }
 
 describe('15300 BFF', () => {
+  it.each([
+    { create: createUnauthenticatedApplication, userId: null },
+    { create: createApplication, userId: 'test-admin' },
+    { create: createUserAuthenticatedApplication, userId: 'test-user' },
+  ])('renews CSRF for $userId without requesting upstream profiles or status', async ({ create, userId }) => {
+    const records: RecordedRequest[] = []
+    const runtime = create({ config: makeConfig(), fetchImpl: fakeGateway(records) })
+    runtimes.push(runtime)
+    const result = await request(runtime.app.callback()).get('/api/app/bootstrap?csrfOnly=1')
+      .set('Host', '127.0.0.1:15300').expect(200)
+    expect(result.body).toEqual({ csrfToken: expect.any(String), userId })
+    expect(runtime.csrf.verify(cookieHeader(result), result.body.csrfToken)).toBe(true)
+    expect(result.headers['set-cookie'][0]).toContain('Max-Age=28800')
+    expect(result.headers['cache-control']).toContain('no-store')
+    expect(records).toEqual([])
+    const again = await request(runtime.app.callback()).get('/api/app/bootstrap?csrfOnly=1')
+      .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(result)).expect(200)
+    expect(again.body.csrfToken).toBe(result.body.csrfToken)
+    expect(records).toEqual([])
+  })
+
   it('keeps existing CSRF tokens valid across an 15300 restart', async () => {
     const config = makeConfig()
     const first = createApplication({ config, fetchImpl: fakeGateway([]) })

+ 104 - 0
tests/server/chatTranscript.test.ts

@@ -0,0 +1,104 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { ChatCacheStore, ChatCacheCoordinator } from '../../src/server/chatCache'
+import { applyTranscriptEvent, type TranscriptSnapshot } from '../../src/shared/chatTranscript'
+import type { UpstreamServiceSession } from '../../src/server/localAuth'
+
+const fixtures:Array<{home:string;store:ChatCacheStore;cache:ChatCacheCoordinator}>=[]
+function fixture(){const home=mkdtempSync(join(tmpdir(),'ordinary-transcript-')),store=new ChatCacheStore(home),cache=new ChatCacheCoordinator(store,{request:vi.fn()} as unknown as UpstreamServiceSession);fixtures.push({home,store,cache});return {home,store,cache}}
+afterEach(()=>{for(const f of fixtures.splice(0)){f.cache.close();if(!f.store.isClosed)f.store.close();rmSync(f.home,{recursive:true,force:true})}})
+function snapshot(store:ChatCacheStore,id='s',owner='owner'):TranscriptSnapshot {
+  store.transcripts.seed(owner,'p',id)
+  const detail=store.localDetail(owner,'p',id)!
+  return store.transcripts.snapshot(owner,'p',id,JSON.parse(detail.response.body.toString()),detail.state)
+}
+describe('ordinary server-owned transcript',()=>{
+  it('preserves interim text, reasoning, tool results and final text as separate records',()=>{
+    const {store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    store.recordCommand('owner','p','s','prompt.submit',{text:'问题',_delivery_id:'ios:prompt:user-one'})
+    let n=0
+    const send=(type:string,payload:object)=>cache.observe('owner','p','s',{type,payload,delivery_id:`event-${++n}`})
+    send('message.start',{})
+    send('reasoning.delta',{text:'先思考'})
+    send('message.interim',{text:'先检查文件'})
+    send('tool.start',{tool_id:'tool-one',name:'read_file'})
+    send('tool.complete',{tool_id:'tool-one',result:'完整工具输出'})
+    send('message.delta',{text:'最终答案'})
+    send('message.complete',{text:'最终答案'})
+    const value=snapshot(store)
+    expect(value.messages.map(m=>m.content)).toEqual(['问题','先检查文件','最终答案'])
+    expect(value.messages[1]!.reasoning).toBe('先思考')
+    expect(value.messages[2]!.tool_calls).toMatchObject([{id:'tool-one',result:'完整工具输出'}])
+    expect(new Set(value.messages.map(m=>m.id)).size).toBe(3)
+    expect(value.messages.map(m=>m.seq)).toEqual([1,2,3])
+  })
+  it('keeps a queued prompt from detaching the currently streaming assistant',()=>{
+    const {store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    store.recordCommand('owner','p','s','prompt.submit',{text:'第一问',_delivery_id:'ios:prompt:first'})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'前半'},delivery_id:'one'})
+    const assistant=snapshot(store).messages.find(m=>m.role==='assistant')!
+    store.recordCommand('owner','p','s','prompt.submit',{text:'排队的第二问',_delivery_id:'ios:prompt:second'})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'后半'},delivery_id:'two'})
+    expect(snapshot(store).messages.find(m=>m.id===assistant.id)?.content).toBe('前半后半')
+    expect(snapshot(store).messages.filter(m=>m.role==='assistant')).toHaveLength(1)
+  })
+  it('commits replayable append patches and ignores duplicate deliveries',()=>{
+    const {store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'中文'},delivery_id:'one'})
+    const base=snapshot(store),id=base.messages[0]!.id
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'🙂'},delivery_id:'two'})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'🙂'},delivery_id:'two'})
+    const events=store.transcripts.events('owner','p','s',base.cursor)
+    expect(events).toHaveLength(1);expect(events[0]!.type).toBe('message.patch')
+    const replay=events.reduce(applyTranscriptEvent,base.messages)
+    expect(replay).toEqual(snapshot(store).messages)
+    expect(replay[0]).toMatchObject({id,content:'中文🙂',revision:2})
+    expect(applyTranscriptEvent(replay,events[0]!)).toEqual(replay)
+  })
+  it('retains stable message identity when an upstream row ID becomes known',()=>{
+    const {store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'回复'},delivery_id:'one'})
+    const before=snapshot(store).messages[0]!
+    cache.observe('owner','p','s',{type:'message.complete',payload:{message_id:'upstream-42',text:'完整回复'},delivery_id:'two'})
+    expect(snapshot(store).messages).toHaveLength(1)
+    expect(snapshot(store).messages[0]).toMatchObject({id:before.id,seq:before.seq,source_message_id:'upstream-42',content:'完整回复',status:'complete'})
+  })
+  it('rolls back content and event log together when durable event storage fails',async()=>{
+    const {store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    const listener=vi.fn();store.transcripts.subscribe(listener)
+    store.db.exec("CREATE TRIGGER fail_transcript_event BEFORE INSERT ON chat_transcript_events BEGIN SELECT RAISE(ABORT,'disk full'); END")
+    expect(()=>cache.observe('owner','p','s',{type:'message.delta',payload:{text:'不能发布'},delivery_id:'fail'})).toThrow('disk full')
+    await Promise.resolve()
+    expect(store.db.prepare('SELECT COUNT(*) n FROM chat_messages').get()!.n).toBe(0)
+    expect(store.db.prepare('SELECT COUNT(*) n FROM chat_transcript_messages').get()!.n).toBe(0)
+    expect(store.transcripts.events('owner','p','s',0)).toEqual([])
+    expect(listener).not.toHaveBeenCalled()
+  })
+  it('replays committed events after server restart without resubmitting prompts',()=>{
+    const {home,store,cache}=fixture();store.recordCommand('owner','p','s','session.create',{})
+    cache.observe('owner','p','s',{type:'message.delta',payload:{text:'开始'},delivery_id:'one'})
+    const before=snapshot(store)
+    cache.observe('owner','p','s',{type:'message.complete',payload:{text:'结束'},delivery_id:'two'})
+    const after=snapshot(store);cache.close();store.close()
+    const reopened=new ChatCacheStore(home)
+    try{expect(reopened.transcripts.epoch).toBe(before.epoch);expect(reopened.transcripts.events('owner','p','s',before.cursor).reduce(applyTranscriptEvent,before.messages)).toEqual(after.messages)}finally{reopened.close()}
+  })
+  it('keeps owner/session scopes and history pagination independent',()=>{
+    const {store,cache}=fixture()
+    for(const owner of ['owner','other'])for(const id of ['s','t']){
+      store.recordCommand(owner,'p',id,'session.create',{})
+      for(let i=0;i<5;i++)store.recordCommand(owner,'p',id,'prompt.submit',{text:`${owner}:${id}:${i}`,_delivery_id:`${owner}:${id}:${i}`})
+    }
+    snapshot(store)
+    const detail=store.localDetail('owner','p','s')!
+    const tail=store.transcripts.snapshot('owner','p','s',{},detail.state,Number.MAX_SAFE_INTEGER,2)
+    const old=store.transcripts.snapshot('owner','p','s',{},detail.state,tail.messages[0]!.seq,2)
+    expect(tail.messages.map(m=>m.content)).toEqual(['owner:s:3','owner:s:4'])
+    expect(old.messages.map(m=>m.content)).toEqual(['owner:s:1','owner:s:2'])
+    expect(store.transcripts.events('unknown','p','s',0)).toEqual([])
+    cache.close()
+  })
+})