@keyou007/agent-bot 0.1.27-alpha.0 → 0.1.27-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +63 -7
  3. package/README.zh.md +62 -6
  4. package/SECURITY.md +18 -4
  5. package/assets/workspace-sessions.js +648 -0
  6. package/assets/workspace.css +160 -0
  7. package/assets/workspace.js +1795 -0
  8. package/config.example.yaml +3 -2
  9. package/dist/codex/CodexEventMapper.js +35 -0
  10. package/dist/codex/CodexEventMapper.js.map +1 -1
  11. package/dist/codex/CodexRuntime.js +50 -4
  12. package/dist/codex/CodexRuntime.js.map +1 -1
  13. package/dist/codex/TraeTaskNotification.js +44 -0
  14. package/dist/codex/TraeTaskNotification.js.map +1 -0
  15. package/dist/config/SettingsStore.js +1 -1
  16. package/dist/config/SettingsStore.js.map +1 -1
  17. package/dist/config/loadConfig.js +3 -2
  18. package/dist/config/loadConfig.js.map +1 -1
  19. package/dist/config/paths.js +3 -0
  20. package/dist/config/paths.js.map +1 -1
  21. package/dist/feishu/CardRenderer.js +56 -12
  22. package/dist/feishu/CardRenderer.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +2 -2
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +103 -16
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/index.js +61 -17
  28. package/dist/index.js.map +1 -1
  29. package/dist/local-files/DiagramPreview.js +1 -1
  30. package/dist/local-files/GitDiffPreview.js +167 -0
  31. package/dist/local-files/GitDiffPreview.js.map +1 -0
  32. package/dist/local-files/LocalFileViewerServer.js +332 -30
  33. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  34. package/dist/local-files/MarkdownFileLinks.js +5 -4
  35. package/dist/local-files/MarkdownFileLinks.js.map +1 -1
  36. package/dist/local-files/TurnPreviewPage.js +138 -58
  37. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  38. package/dist/local-files/WebPageTitle.js +85 -0
  39. package/dist/local-files/WebPageTitle.js.map +1 -0
  40. package/dist/local-files/WorkspaceFiles.js +553 -0
  41. package/dist/local-files/WorkspaceFiles.js.map +1 -0
  42. package/dist/local-files/WorkspaceOrigin.js +38 -0
  43. package/dist/local-files/WorkspaceOrigin.js.map +1 -0
  44. package/dist/local-files/WorkspacePage.js +19 -0
  45. package/dist/local-files/WorkspacePage.js.map +1 -0
  46. package/dist/local-files/WorkspaceSessions.js +689 -0
  47. package/dist/local-files/WorkspaceSessions.js.map +1 -0
  48. package/dist/presentation/TurnStateReducer.js +74 -13
  49. package/dist/presentation/TurnStateReducer.js.map +1 -1
  50. package/dist/presentation/turnActivity.js +41 -0
  51. package/dist/presentation/turnActivity.js.map +1 -0
  52. package/dist/presentation/turnStatus.js +11 -0
  53. package/dist/presentation/turnStatus.js.map +1 -1
  54. package/dist/presentation/visibleTurnActivities.js +4 -2
  55. package/dist/presentation/visibleTurnActivities.js.map +1 -1
  56. package/dist/proxy/ProxySessionController.js +150 -14
  57. package/dist/proxy/ProxySessionController.js.map +1 -1
  58. package/dist/runtime/types.js +1 -1
  59. package/dist/runtime/types.js.map +1 -1
  60. package/dist/state/InboundMessageStore.js +54 -0
  61. package/dist/state/InboundMessageStore.js.map +1 -0
  62. package/dist/state/StateStore.js +71 -1
  63. package/dist/state/StateStore.js.map +1 -1
  64. package/dist/state/TurnPreviewJournal.js +4 -2
  65. package/dist/state/TurnPreviewJournal.js.map +1 -1
  66. package/dist/state/migrations.js +20 -0
  67. package/dist/state/migrations.js.map +1 -1
  68. package/dist/supervision/SafeRestartNotifier.js +1 -0
  69. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  70. package/dist/supervision/SafeRestartScheduler.js +33 -16
  71. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  72. package/dist/terminal/TerminalLinks.js +32 -0
  73. package/dist/terminal/TerminalLinks.js.map +1 -1
  74. package/dist/terminal/TerminalPage.js +75 -26
  75. package/dist/terminal/TerminalPage.js.map +1 -1
  76. package/dist/terminal/TerminalServer.js +125 -56
  77. package/dist/terminal/TerminalServer.js.map +1 -1
  78. package/docs/technical-reference.md +14 -4
  79. package/docs/technical-reference.zh.md +15 -5
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
  82. package/skills/agent-bot/SKILL.md +6 -2
  83. package/src/codex/CodexEventMapper.ts +39 -1
  84. package/src/codex/CodexRuntime.ts +54 -4
  85. package/src/codex/TraeTaskNotification.ts +49 -0
  86. package/src/config/SettingsStore.ts +1 -1
  87. package/src/config/loadConfig.ts +3 -2
  88. package/src/config/paths.ts +4 -0
  89. package/src/feishu/CardRenderer.ts +47 -13
  90. package/src/feishu/FeishuMessageClient.ts +2 -2
  91. package/src/feishu/FeishuTurnPresenter.ts +110 -20
  92. package/src/index.ts +62 -17
  93. package/src/local-files/DiagramPreview.ts +1 -1
  94. package/src/local-files/GitDiffPreview.ts +144 -0
  95. package/src/local-files/LocalFileViewerServer.ts +294 -31
  96. package/src/local-files/MarkdownFileLinks.ts +5 -3
  97. package/src/local-files/TurnPreviewPage.ts +159 -69
  98. package/src/local-files/WebPageTitle.ts +59 -0
  99. package/src/local-files/WorkspaceFiles.ts +468 -0
  100. package/src/local-files/WorkspaceOrigin.ts +31 -0
  101. package/src/local-files/WorkspacePage.ts +21 -0
  102. package/src/local-files/WorkspaceSessions.ts +587 -0
  103. package/src/presentation/TurnStateReducer.ts +76 -14
  104. package/src/presentation/turnActivity.ts +43 -0
  105. package/src/presentation/turnStatus.ts +14 -0
  106. package/src/presentation/turnViewTypes.ts +10 -1
  107. package/src/presentation/visibleTurnActivities.ts +4 -2
  108. package/src/proxy/ProxySessionController.ts +149 -13
  109. package/src/runtime/types.ts +17 -0
  110. package/src/state/InboundMessageStore.ts +72 -0
  111. package/src/state/StateStore.ts +80 -1
  112. package/src/state/TurnPreviewJournal.ts +4 -2
  113. package/src/state/migrations.ts +20 -0
  114. package/src/supervision/SafeRestartNotifier.ts +1 -0
  115. package/src/supervision/SafeRestartScheduler.ts +42 -18
  116. package/src/terminal/TerminalLinks.ts +26 -0
  117. package/src/terminal/TerminalPage.ts +76 -26
  118. package/src/terminal/TerminalServer.ts +119 -48
@@ -249,15 +249,25 @@ HTML 文本文件(`.html`、`.htm`,不区分大小写)支持预览与代
249
249
 
250
250
  多 Agent 时常用页提供默认 Agent,Agent 页提供模型/思考强度/权限下拉框。单 Agent 时常用页改为 Provider/模型,Agent 页保留思考强度和权限,不显示 Agent 选择器。只读模型发现使用已保存或运行时默认 Provider,不创建或恢复任务。切换默认 Provider 先读取目标目录,保留受支持的原模型,否则选择默认或首个候选(目录不可用时清除模型覆盖值);不兼容的思考强度在同一原子写入中恢复 Agent 默认。模型保留上游名称和 ID,思考强度去重;保存校验选项和模型/强度组合,保留未修改的环境变量引用和不可用当前值,异步发现后再次校验文件版本。目录错误仅显示通用提示,不透出原始上游错误;已有任务设置和历史保持不变。
251
251
 
252
+ ### 变更文件 Diff
253
+
254
+ Turn Preview 在 `history.state` 的独立命名空间中保存折叠块 ID 和展开/折叠标记,按 Turn 和历史记录隔离,不保存文件正文或工具输出。从文件页返回或刷新时,先恢复匹配节点的状态,再按需请求展开详情;折叠块不加载。其他 Turn 和新历史记录保持默认状态,History API 不可用不阻止预览。浏览器从往返缓存恢复页面时保留已有节点,重试中断的详情加载,并从最近已应用的 SSE 游标接续实时更新;终态 Turn 保持静态。
255
+
256
+ Turn Preview 的文件变更汇总和工具详情链接在已有路径签名 URL 中添加 `diff=1`,其他链接不变;该模式允许为已删除路径签发链接,以查看跟踪文件的删除差异。仅打开签名文件页时运行 Git,不在 Turn 渲染、列表懒加载或 SSE 更新时执行。页面显示打开时当前工作区与 `HEAD` 的差异,包含暂存和未暂存修改;首次提交前按新增文件展示。它不是持久化的历史 Turn 补丁,刷新会重新读取。Git 差异块合并到解码后的完整当前文件中,保留文件开头、末尾及差异块之间的所有未改动行,新增行绿色高亮,删除行在原位置以红色插入。每行显示新旧行号,当前文件保留 `L` 行号锚点。合并时校验差异坐标和正文,并核对读取前后的文件元数据;文件变化或补丁不匹配时回退,不显示错位高亮。“查看文件”返回普通实时预览;原始文件和下载始终返回原文。
257
+
258
+ Git 不经过 Shell,Windows 隐藏控制台,使用单文件 literal pathspec,禁用可选索引锁、external diff、textconv、clean/process filter 和 fsmonitor。共享四秒截止时间、1 MiB/10,000 行补丁、20,000 行合并视图和当前文件 2 MiB 大小限制约束开销。Git 不可用、非仓库、无改动/未跟踪、二进制或非 UTF-8 补丁、错误及超限时,文件存在则回退普通预览;删除文件无可用差异时返回 404。仍需通过路径签名及只读 HTTP 校验,不改写任务历史、Git 索引或提交。
259
+
252
260
  ## 交互式网页终端
253
261
 
254
- 飞书 `!` 命令卡片的 Open Terminal 打开密码表单。POST 先校验 `terminal.password`,未配置时默认 `123456`;通过后才读取命令任务、发送管理卡和签发浏览器凭证,不再需要飞书 Allow/Deny 审批。持有链接和密码的人可运行完整主机用户权限的 Shell,向其他设备开放前应更换默认密码。所有者可在 `/settings` → 高级 → 终端密码修改;密码保存在本机 Profile YAML,安全重启后生效,设置快照与卡片不回显已保存值,留空保留原值。其他凭证仍仅在本机管理。
262
+ 飞书 `!` 命令卡片的 Open Terminal 打开密码表单。POST 先校验 `terminal.password`,未配置时默认 `123456`;通过后才读取命令任务、发送管理卡和签发浏览器凭证,不再需要飞书 Allow/Deny 审批。持有链接和密码的人可运行完整主机用户权限的 Shell,向其他设备开放前应更换默认密码。所有者可在 `/settings` → 高级 → 工作台 / 终端密码修改;密码保存在本机 Profile YAML,安全重启后生效,设置快照与卡片不回显已保存值,留空保留原值。其他凭证仍仅在本机管理。
263
+
264
+ 密码通过固定长度摘要进行恒定时间比较。同一连接来源地址一分钟内五次错误尝试,或全局五十次错误尝试后,暂时拒绝登录;不信任转发 IP 请求头。正确登录仍受每十秒一次、每小时二十次和最多三个终端的限制。恢复运行中的 Shell 跳过密码及十秒创建间隔,仍受每小时请求上限限制。密码仅在登录 POST 请求体中传递,不放入 URL、日志或浏览器存储。随机浏览器密钥仅放在 sessionStorage 与 POST/WebSocket 请求体,不使用 Cookie。新标签页仅在创建或首次启动 Shell 时输入密码,同标签页刷新复用已签发凭证。五分钟未连接的授权自动过期,所有者或密码变更会撤销会话。
255
265
 
256
- 密码通过固定长度摘要进行恒定时间比较。同一连接来源地址一分钟内五次错误尝试,或全局五十次错误尝试后,暂时拒绝登录;不信任转发 IP 请求头。正确登录仍受每十秒一次、每小时二十次和最多三个终端的限制。密码仅在登录 POST 请求体中传递,不放入 URL、日志或浏览器存储。随机浏览器密钥仅放在 sessionStorage 与 POST/WebSocket 请求体,不使用 Cookie。新标签页重新输入密码,同标签页刷新复用已签发凭证。五分钟未连接的授权自动过期,所有者或密码变更会撤销会话。
266
+ 工作台内嵌终端复用工作台登录会话;未配置密码或使用默认密码时,工作台自动登录。终端链接只定位签名项目目录,不授予权限;终端页面、HTTP 请求及 WebSocket 均校验同一个工作台会话,会话撤销时关闭对应 Shell,不依赖或发送飞书管理卡。独立命令卡终端的密码页提示 `/setting` → 高级 → 工作台 / 终端密码。服务端只下发是否使用默认密码的标志,绝不下发自定义密码。实际密码为 `123456` 时回填公开默认值,倒计时五秒后走正常密码登录。编辑/自动填充、手动连接、切到后台/离开页面或离线取消这次倒计时,返回页面不自动重启倒计时。已有凭证与运行中 Shell 恢复跳过倒计时。后端密码校验、限流及重启保护仍生效,自动登录失败不重复提交密码。
257
267
 
258
268
  cwd、contextKey 和原命令卡片 ID 均取自服务端 Shell job,不接受浏览器指定。终端管理卡发往原会话,话题使用 reply_in_thread=true;任务移动后恢复仍保留原路由,投递失败不降级发往其他会话,也不启动 Shell。仅所有者可通过原始卡片 ID 和操作令牌关闭或刷新。管理卡展示稳定的八位终端 token 和打开/重开链接,不展示密码或浏览器密钥。
259
269
 
260
- 原命令链接用于创建独立 Shell,管理链接用于恢复同一个终端。新网页密码正确且管理卡投递成功后,撤销旧浏览器凭证并复用原 PTY;密码错误或投递失败不影响原 Shell 与访问权。页面加载和密码校验本身不创建进程,仅 WebSocket 鉴权成功后最多启动一个 Shell。安全重启阻止新建或首次启动 Shell,但允许重连或关闭已运行 Shell;已结束或上次进程的终端不能复活。
270
+ 原命令链接用于创建独立 Shell,管理链接用于恢复同一个终端。服务端仅对仍在运行的 Shell 标记自动恢复,新网页无需再次输入密码;签发恢复凭证且管理卡投递成功后,撤销旧浏览器凭证并复用原 PTY 与输出。尚未启动的 Shell 仍需密码;首次启动密码错误或投递失败不影响原 Shell 与访问权。页面加载和密码校验本身不创建进程,仅 WebSocket 鉴权成功后最多启动一个 Shell。安全重启阻止新建或首次启动 Shell,但允许重连或关闭已运行 Shell;已结束或上次进程的终端不能复活。
261
271
 
262
272
  WebSocket 就绪帧提供有界输出快照和回放标志。首次连接正常回应启动查询,重连只恢复画面;异步回放解析完成前禁用输入和自动响应。每次连接使用独立 xterm 实例,旧回调不能向新连接写入。Ctrl+C 复制选中文字,Ctrl+V 通过浏览器原生事件粘贴,工具栏保留显式中断按钮。
263
273
 
@@ -274,13 +284,13 @@ terminal:
274
284
  # password: "replace-with-a-strong-password" # 未配置时:123456
275
285
  ```
276
286
 
277
- 终端挂载于 Preview 路径前缀加 `/terminal`,共用 `fileViewer` 的协议、主机、端口和代理路径,无独立监听器或端口文件。命令和恢复链接统一使用 `/terminal/<8位token>`,区分大小写的 base64url token 只定位,不授权执行。持久化命令映射保存在 `<data>/terminal/open-links/<SHA256(token)>.json`;命令 token 使用密钥生成,冲突时重试而不覆盖。恢复 token 随机生成并在同一命名空间永久占位,只能定位当前进程内的终端。`<data>/terminal/secret` 用于生成命令引用;关闭 Preview 或 `terminal.enabled` 后隐藏终端入口。
287
+ 终端挂载于 Preview 路径前缀加 `/terminal`,共用 `fileViewer` 的协议、主机、端口和代理路径,无独立监听器或端口文件。命令和恢复链接统一使用 `/terminal/<8位token>`,区分大小写的 base64url 命令 token 只定位,仍需密码。恢复链接可直接重连运行中的 Shell,必须保密,但不能用于创建替代 Shell。持久化命令映射保存在 `<data>/terminal/open-links/<SHA256(token)>.json`;命令 token 使用密钥生成,冲突时重试而不覆盖。恢复 token 随机生成并在同一命名空间永久占位,只能定位当前进程内的终端。`<data>/terminal/secret` 用于生成命令引用;关闭 Preview 或 `terminal.enabled` 后隐藏终端入口。
278
288
 
279
289
  HTTP 仅适合可信网络,密码和终端流量均为明文。不可信网络使用 HTTPS,反向代理保留 Host/Origin 并支持 WebSocket。终端拒绝不透明的 `null` origin,校验请求来源和负载上限;Preview 路由保持只读,HTML/原始文件使用响应级沙箱,防止预览文档访问终端存储和同源 API。共用地址不等于共用授权。
280
290
 
281
291
  `node-pty` 是可选原生依赖,缺失时提示 Shell 启动失败而不阻止安装。Windows 使用 ConPTY(Windows 10 1903/Server 2022 或更新版本),按 pwsh、Windows PowerShell、cmd.exe 顺序选择并保留 profile;Unix 使用配置/登录/平台 Shell。语法高亮由 Shell 提供,xterm 只渲染。仅继承卡片 cwd,不继承原命令或进程状态;终端不受 Agent 沙箱限制。输出仅在内存保留最后 256 Ki 字符,不写入持久日志。
282
292
 
283
- 页面关闭开始独立三分钟断开计时,输出、状态查询和密码验证不延长时限。WebSocket 重连成功才取消计时并重置三十分钟输入/输出空闲时间。前台每三十秒上报可见性、有效九十秒,持续前台不因空闲关闭;后台空闲或断开超时任一满足均结束 Shell,累计寿命最多八小时。“关闭终端”立即结束 Shell,脱离终端的后台进程可能继续运行。活动终端仍阻止安全重启,重启卡展示活跃状态及当前命令,Worker 重启不保留 Shell。原后台 `!` 命令与终端相互独立。
293
+ 页面关闭开始独立三十分钟断开计时,输出、状态查询和恢复请求不延长时限。WebSocket 重连成功才取消计时并重置三十分钟输入/输出空闲时间。前台每三十秒上报可见性、有效九十秒,持续前台不因空闲关闭;后台空闲或断开超时任一满足均结束 Shell,累计寿命最多八小时。“关闭终端”立即结束 Shell,脱离终端的后台进程可能继续运行;生命周期说明放在按钮提示与关闭确认中,不再常驻页脚。活动终端仍阻止安全重启,重启卡展示活跃状态及当前命令,Worker 重启不保留 Shell。原后台 `!` 命令与终端相互独立。
284
294
 
285
295
  ## Agent Runtime
286
296
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@keyou007/agent-bot",
3
- "version": "0.1.27-alpha.0",
3
+ "version": "0.1.27-alpha.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@keyou007/agent-bot",
9
- "version": "0.1.27-alpha.0",
9
+ "version": "0.1.27-alpha.2",
10
10
  "license": "GPL-3.0-only",
11
11
  "dependencies": {
12
12
  "@agentclientprotocol/sdk": "1.2.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keyou007/agent-bot",
3
- "version": "0.1.27-alpha.0",
3
+ "version": "0.1.27-alpha.2",
4
4
  "type": "module",
5
5
  "description": "Use Codex, TraeX, and compatible coding agents from Lark/Feishu.",
6
6
  "license": "GPL-3.0-only",
@@ -209,11 +209,13 @@ For group mention-only mode (ordinary @ Prompts also receive bounded recent text
209
209
  agentbot task mute on|off
210
210
  ```
211
211
 
212
- Feishu `!` command cards offer **Open Terminal** for an independent full-host-user Shell in the card's cwd. The browser asks for the terminal password, not a Feishu verification-code approval. Default is `123456` when `terminal.password` is absent; the owner changes it through `/settings` > Advanced and safely restarts. Do not log, embed in URLs or persist the password in browser storage; use a strong password before exposing the service. Correct login issues browser credentials; only an authenticated WebSocket starts the Shell. Terminal links share Preview networking and use `/terminal/<8-character-token>`; tokens locate commands/sessions, never authorize execution. HTTPS is required on untrusted networks. Preview remains read-only/sandboxed. Opening the original command link creates a new Shell without replaying or taking over the original command.
212
+ Feishu `!` command cards offer **Open Terminal** for an independent full-host-user Shell in the card's cwd. The browser asks for the terminal password, not a Feishu verification-code approval. Default is `123456` when `terminal.password` is absent; the owner changes it through `/settings` > Advanced and safely restarts. Do not log, embed in URLs or persist the password in browser storage; use a strong password before exposing the service. Correct login issues browser credentials; only an authenticated WebSocket starts the Shell. Terminal links share Preview networking and use `/terminal/<8-character-token>`. Command tokens only locate jobs; recovery links authorize reattachment to running Shells and must remain private. HTTPS is required on untrusted networks. Preview remains read-only/sandboxed. Opening the original command link creates a new Shell without replaying or taking over the original command.
213
213
 
214
214
  ## Manage The Service
215
215
 
216
- If a terminal tab is lost, use its management card in the original Feishu conversation/topic. Open/Reopen identifies the same terminal; a new webpage verifies the password before revoking old browser access and reusing the Shell. Wrong passwords or failed management-card delivery leave the original Shell intact. Owner-only Close and Refresh work without the webpage. Reconnecting a running Shell is allowed during pending safe restart; first-start Shells are blocked. Closing the page starts a three-minute disconnect timer; successful WebSocket reattachment resets it and the thirty-minute idle clock. A foreground connection avoids idle closure; background idle or disconnect timeout independently ends the Shell. Terminals last at most eight hours and do not survive restart. Never close a user's terminal merely to unblock a restart.
216
+ Workspace and Terminal share `terminal.password`, set under `/setting` > Advanced > Workspace / Terminal Password. Workspace Tasks, Chat and the embedded terminal reuse one session. The public default allows anyone who can reach Workspace to enter and open a Shell if terminals are enabled; set a custom password or restrict network access. Logout ends the embedded Shells for that session. Feishu command-card terminals keep their separate connection flow: while the effective password is `123456`, the standalone page prefills that public default and auto-connects after five seconds. Editing, manual connection, hiding/leaving or going offline cancels the countdown. Custom passwords are never sent to the page; saved grants and running-Shell recovery skip the countdown. Default-password login still uses ordinary server authentication and restart safeguards.
217
+
218
+ If a terminal tab is lost, use its management card in the original Feishu conversation/topic. Reopen automatically restores the same running Shell/output without another password and revokes old browser access; an unstarted Shell still requires the password. Wrong first-start passwords or failed management-card delivery leave the original Shell intact. Owner-only Close and Refresh work without the webpage. Reconnecting a running Shell is allowed during pending safe restart; first-start Shells are blocked. Closing the page starts a thirty-minute disconnect timer; successful WebSocket reattachment resets it and the thirty-minute idle clock. A foreground connection avoids idle closure; background idle or disconnect timeout independently ends the Shell. Lifecycle help is in the Close button tooltip/confirmation, not a permanent footer. Terminals last at most eight hours and do not survive restart. Never close a user's terminal merely to unblock a restart.
217
219
 
218
220
  ```powershell
219
221
  agentbot server start
@@ -236,6 +238,8 @@ macOS LaunchAgents use `ProcessType=Standard`, never `Background`, because Agent
236
238
 
237
239
  Use safe restart by default. Prefer `agentbot task restart` when hosted so the current task is resolved automatically. Use `--immediate` or `task restart --force` only when the user explicitly accepts interruption.
238
240
 
241
+ Safe restart waits for incoming-message handlers and card actions as well as tasks and deliveries, and rechecks activity after notifications before pausing dispatch. Late handoff messages are persisted with their routing and attachments. Only recent, provably unprocessed ordinary messages with unchanged task/Stop boundaries and no newer conversation/shared-task message resume automatically within twenty minutes; the guards are rechecked after asynchronous preparation. A provably unprocessed Stop is honored before Turn recovery. Already handed-off work uses existing Turn/queue recovery. Ambiguous messages and commands are not blindly replayed. Do not delete deduplication records or resend old instructions to force recovery.
242
+
239
243
  The safe-restart card has matching `Cancel` and `ForceRestart` actions. Clicking `ForceRestart` explicitly accepts interruption and immediately executes the pending restart (including an already-prepared update), bypassing task, final-delivery, and quiet-window waits. Do not click it without the user's explicit request. Stale or already-triggered plans are rejected.
240
244
 
241
245
  Each displayed running task on that card has a `Stop` action targeting its exact task, even across conversations. It uses normal Agent interruption and leaves the restart scheduled; the card updates as tasks stop. Only stop a task when the user requests it.
@@ -1,5 +1,14 @@
1
1
  import { z } from "zod";
2
- import type { PlanStep, ToolState } from "../runtime/types.js";
2
+ import type { ModelQueueStatus, PlanStep, ToolState } from "../runtime/types.js";
3
+ import { readTaskNotification, readTaskNotifications, type TaskNotificationActivity } from "./TraeTaskNotification.js";
4
+
5
+ // Optional TraeX extension; ordinary Codex notifications need no queue fields.
6
+ const modelQueueStatus = z.object({
7
+ state: z.enum(["queued", "waiting", "ready"]),
8
+ position: z.number().int().min(0).max(4_294_967_295).nullish(),
9
+ message: z.string().nullish(),
10
+ operation: z.enum(["contextCompaction"]).nullish(),
11
+ });
3
12
 
4
13
  const modeChangeRequest = z.object({
5
14
  requestId: z.string().min(1),
@@ -16,6 +25,7 @@ const modeChangeResolution = z.object({
16
25
 
17
26
  export type MappedCodexNotification =
18
27
  | { kind: "turn_started"; threadId: string; turnId: string; startedAt?: number }
28
+ | { kind: "model_queue"; threadId: string; turnId: string; queue: ModelQueueStatus }
19
29
  | { kind: "runtime_error"; threadId: string; turnId: string; message: string; willRetry: boolean }
20
30
  | {
21
31
  kind: "token_usage";
@@ -68,6 +78,8 @@ export type MappedCodexNotification =
68
78
  status: "completed" | "cancelled" | "failed";
69
79
  durationMs?: number;
70
80
  error?: string;
81
+ taskNotifications?: TaskNotificationActivity[];
82
+ taskNotificationFinalResponse?: string;
71
83
  };
72
84
 
73
85
  export function mapCodexNotification(method: string, params: unknown): MappedCodexNotification | undefined {
@@ -76,6 +88,18 @@ export function mapCodexNotification(method: string, params: unknown): MappedCod
76
88
  const turnId = stringValue(params.turnId) ?? (isRecord(params.turn) ? stringValue(params.turn.id) : undefined);
77
89
  if (!threadId || !turnId) return undefined;
78
90
 
91
+ if (method === "queue/status") {
92
+ const parsed = modelQueueStatus.safeParse(params);
93
+ if (!parsed.success) return undefined;
94
+ const { state, position, message, operation } = parsed.data;
95
+ return { kind: "model_queue", threadId, turnId, queue: {
96
+ state,
97
+ ...(position == null ? {} : { position }),
98
+ ...(message == null ? {} : { message: message.slice(0, 1_000) }),
99
+ ...(operation == null ? {} : { operation }),
100
+ } };
101
+ }
102
+
79
103
  if (method === "error" && isRecord(params.error)) {
80
104
  const message = formatCodexError(params.error);
81
105
  if (!message || typeof params.willRetry !== "boolean") return undefined;
@@ -176,6 +200,10 @@ export function mapCodexNotification(method: string, params: unknown): MappedCod
176
200
  return { kind: "plan", threadId, turnId, steps };
177
201
  }
178
202
  if ((method === "item/started" || method === "item/completed") && isRecord(params.item)) {
203
+ if (params.item.type === "taskNotification") {
204
+ const activity = method === "item/completed" ? readTaskNotification(params.item) : undefined;
205
+ return activity && { kind: "progress", threadId, turnId, ...activity, append: false };
206
+ }
179
207
  if (params.item.type === "reasoning") {
180
208
  if (method !== "item/completed") return undefined;
181
209
  const itemId = stringValue(params.item.id);
@@ -221,6 +249,14 @@ export function mapCodexNotification(method: string, params: unknown): MappedCod
221
249
  const status = params.turn.status;
222
250
  const mappedStatus = status === "interrupted" ? "cancelled" : status === "failed" ? "failed" : "completed";
223
251
  const error = formatCodexError(params.turn.error);
252
+ const taskNotifications = readTaskNotifications(params.turn.items);
253
+ const taskNotificationFinalResponse = taskNotifications.length && Array.isArray(params.turn.items)
254
+ ? params.turn.items.flatMap((item) => {
255
+ if (!isRecord(item) || item.type !== "agentMessage" || item.phase !== "final_answer") return [];
256
+ const text = nonEmptyString(item.text);
257
+ return text ? [text] : [];
258
+ }).join("\n\n")
259
+ : undefined;
224
260
  return {
225
261
  kind: "terminal",
226
262
  threadId,
@@ -228,6 +264,8 @@ export function mapCodexNotification(method: string, params: unknown): MappedCod
228
264
  status: mappedStatus,
229
265
  durationMs: numberValue(params.turn.durationMs),
230
266
  error,
267
+ ...(taskNotifications.length ? { taskNotifications } : {}),
268
+ ...(taskNotificationFinalResponse ? { taskNotificationFinalResponse } : {}),
231
269
  };
232
270
  }
233
271
  return undefined;
@@ -12,6 +12,7 @@ import type {
12
12
  ModelOption,
13
13
  ModelListResult,
14
14
  ModelProviderOption,
15
+ ModelQueueStatus,
15
16
  PermissionMode,
16
17
  RemoteSessionActivity,
17
18
  RemoteSessionMetrics,
@@ -39,6 +40,8 @@ import { workspaceSandboxFromConfig, workspaceSandboxFromResponse, type TurnSand
39
40
  import { formatCodexError, mapCodexNotification } from "./CodexEventMapper.js";
40
41
  import { CodexLocalActivityDetector } from "./CodexLocalActivityDetector.js";
41
42
  import { hasCompletedTraePlanEntry } from "./TraePlanEntry.js";
43
+ import { readTaskNotifications } from "./TraeTaskNotification.js";
44
+ import { TASK_NOTIFICATION_ACTIVITY_PREFIX } from "../runtime/types.js";
42
45
  import { detectProjectlessWorkspace } from "./ProjectlessWorkspace.js";
43
46
  import { threadWriterLockPath } from "./ThreadWriterProcess.js";
44
47
  import { assertProviderSettingsApplied, PROVIDER_SWITCH_BUSY, PROVIDER_SWITCH_EMPTY, ProviderSwitchError, providerSwitchFailure } from "./ProviderSwitch.js";
@@ -88,6 +91,7 @@ export interface AppServerClientProvider {
88
91
 
89
92
  interface CodexSession extends RuntimeSession {
90
93
  activeTurnStartedAt?: number;
94
+ modelQueue?: ModelQueueStatus;
91
95
  terminalTurnIds: Set<string>;
92
96
  modeChangeRequestIds: Set<string>;
93
97
  planContinuationTurnId?: string;
@@ -1373,6 +1377,7 @@ export class CodexRuntime implements AgentRuntime {
1373
1377
  this.adoptTurn(session, mapped.turnId, mapped.startedAt ?? Date.now());
1374
1378
  return;
1375
1379
  }
1380
+ if (mapped.kind === "model_queue" && session.activeTurnId !== mapped.turnId) return;
1376
1381
  if (!session.activeTurnId || session.activeTurnId !== mapped.turnId) {
1377
1382
  this.logger.debug(
1378
1383
  { sessionId: session.localSessionId, activeTurnId: session.activeTurnId, notificationTurnId: mapped.turnId, method },
@@ -1384,7 +1389,9 @@ export class CodexRuntime implements AgentRuntime {
1384
1389
  return;
1385
1390
  }
1386
1391
  const sessionId = session.localSessionId;
1387
- if (mapped.kind === "mode_change_requested") {
1392
+ if (mapped.kind === "model_queue") {
1393
+ this.updateModelQueue(session, mapped.turnId, mapped.queue);
1394
+ } else if (mapped.kind === "mode_change_requested") {
1388
1395
  const requestId = `mode:${mapped.threadId}:${mapped.requestId}`;
1389
1396
  if (session.modeChangeRequestIds.has(requestId)) return;
1390
1397
  session.modeChangeRequestIds.add(requestId);
@@ -1537,6 +1544,9 @@ export class CodexRuntime implements AgentRuntime {
1537
1544
  delta: mapped.delta,
1538
1545
  });
1539
1546
  } else if (mapped.kind === "terminal") {
1547
+ for (const activity of mapped.taskNotifications ?? []) {
1548
+ this.emit({ type: "progress", sessionId, turnId: mapped.turnId, ...activity, append: false });
1549
+ }
1540
1550
  if (mapped.status === "completed" && !session.finalText && session.unphasedFinalMessageId) {
1541
1551
  this.promoteUnphasedMessage(session, mapped.turnId, session.unphasedFinalMessageId);
1542
1552
  }
@@ -1555,7 +1565,7 @@ export class CodexRuntime implements AgentRuntime {
1555
1565
  this.emit({ type: "turn_failed", sessionId, turnId: mapped.turnId, message: mapped.error ?? "App Server turn failed." });
1556
1566
  } else {
1557
1567
  const finalResponse = appendModelSwitchGuidance(
1558
- appendGeneratedImageMarkdown(session.finalText, session.generatedImagePaths),
1568
+ appendGeneratedImageMarkdown(session.finalText || mapped.taskNotificationFinalResponse || "", session.generatedImagePaths),
1559
1569
  session.model,
1560
1570
  );
1561
1571
  this.emit({
@@ -1727,6 +1737,7 @@ export class CodexRuntime implements AgentRuntime {
1727
1737
  if (session.turnCount !== undefined) session.turnCount += 1;
1728
1738
  }
1729
1739
  session.activeTurnId = turnId;
1740
+ session.modelQueue = undefined;
1730
1741
  session.responseFailureTurnId = undefined;
1731
1742
  session.activeTurnStartedAt = startedAt;
1732
1743
  session.planContinuationTurnId = undefined;
@@ -1751,6 +1762,9 @@ export class CodexRuntime implements AgentRuntime {
1751
1762
 
1752
1763
  private finishSnapshotTurn(session: CodexSession, turn: CodexTurnSnapshot): void {
1753
1764
  if (session.activeTurnId !== turn.id) return;
1765
+ for (const activity of readTaskNotifications(turn.items)) {
1766
+ this.emit({ type: "progress", sessionId: session.localSessionId, turnId: turn.id, ...activity, append: false });
1767
+ }
1754
1768
  if (turn.status === "completed") {
1755
1769
  for (const item of finalResponseMessages(turn)) {
1756
1770
  if (item.id) this.promoteUnphasedMessage(session, turn.id, item.id);
@@ -1880,7 +1894,40 @@ export class CodexRuntime implements AgentRuntime {
1880
1894
  && pending.targetMode === "default") session.planContinuationTurnId = pending.turnId;
1881
1895
  }
1882
1896
 
1897
+ private updateModelQueue(
1898
+ session: CodexSession, turnId: string, queue: ModelQueueStatus,
1899
+ source: RuntimeEvent["type"] | "queue/status" = "queue/status",
1900
+ ): void {
1901
+ const previous = session.modelQueue;
1902
+ const changed = previous?.state !== queue.state || previous?.position !== queue.position
1903
+ || previous?.operation !== queue.operation;
1904
+ if (!changed && previous?.message === queue.message) return;
1905
+ session.modelQueue = queue;
1906
+ if (changed) this.logger.info({
1907
+ sessionId: session.localSessionId, turnId, state: queue.state, source,
1908
+ position: queue.position, operation: queue.operation,
1909
+ }, "App Server model queue status changed.");
1910
+ const reason = source === "queue/status" ? undefined : source === "turn_status_unknown" ? "disconnected"
1911
+ : source === "turn_completed" || source === "turn_cancelled" || source === "turn_failed" ? "turn_ended" : "output";
1912
+ this.emit({ type: "model_queue_updated", sessionId: session.localSessionId, turnId, queue, timestampMs: Date.now(), reason });
1913
+ }
1914
+
1883
1915
  private emit(event: RuntimeEvent): void {
1916
+ const session = this.sessions.get(event.sessionId);
1917
+ if (session?.modelQueue && session.modelQueue.state !== "ready" && (
1918
+ event.type === "agent_text_delta" && event.text.trim().length > 0
1919
+ || event.type === "progress" && event.severity !== "warning"
1920
+ && !event.activityId?.startsWith(TASK_NOTIFICATION_ACTIVITY_PREFIX) && event.text.trim().length > 0
1921
+ || event.type === "reasoning_delta" && event.text.trim().length > 0
1922
+ || event.type === "tool_started"
1923
+ || event.type === "token_usage_updated"
1924
+ || event.type === "approval_requested"
1925
+ || event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed"
1926
+ || event.type === "turn_status_unknown"
1927
+ || event.type === "context_compaction" && event.phase === "completed"
1928
+ )) {
1929
+ this.updateModelQueue(session, event.turnId, { state: "ready", operation: session.modelQueue.operation }, event.type);
1930
+ }
1884
1931
  if (event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed") {
1885
1932
  for (const [requestId, pending] of this.modeChanges) {
1886
1933
  if (pending.sessionId !== event.sessionId || pending.turnId !== event.turnId) continue;
@@ -2089,8 +2136,11 @@ function remoteTurnDetails(remoteSessionId: string, turn: CodexTurnSnapshot): Re
2089
2136
  if (mapped?.kind === "tool") items.push({ kind: "tool", tool: mapped.tool });
2090
2137
  else if (mapped?.kind === "reasoning_completed") {
2091
2138
  items.push({ kind: "reasoning", id: mapped.itemId, summary: mapped.summary, content: mapped.content });
2092
- } else if (mapped?.kind === "progress") items.push({ kind: "message", id, role: "assistant", text: mapped.text });
2093
- else if (mapped?.kind === "plan") items.push({ kind: "plan", steps: mapped.steps });
2139
+ } else if (mapped?.kind === "progress") {
2140
+ const activityId = mapped.activityId.startsWith(TASK_NOTIFICATION_ACTIVITY_PREFIX)
2141
+ ? mapped.activityId.slice("commentary:".length) : id;
2142
+ items.push({ kind: "message", id: activityId, role: "assistant", text: mapped.text });
2143
+ } else if (mapped?.kind === "plan") items.push({ kind: "plan", steps: mapped.steps });
2094
2144
  }
2095
2145
  return {
2096
2146
  turnId: turn.id,
@@ -0,0 +1,49 @@
1
+ import { TASK_NOTIFICATION_ACTIVITY_PREFIX } from "../runtime/types.js";
2
+
3
+ export interface TaskNotificationActivity {
4
+ activityId: string;
5
+ text: string;
6
+ }
7
+
8
+ export function readTaskNotification(item: unknown): TaskNotificationActivity | undefined {
9
+ if (!isRecord(item) || item.type !== "taskNotification" || typeof item.id !== "string"
10
+ || !item.id.trim() || !Array.isArray(item.content)) return;
11
+
12
+ for (const block of item.content) {
13
+ if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string" || block.text.length > 16_384) continue;
14
+ const payload = /^<task-notification>\s*([\s\S]*?)\s*<\/task-notification>$/u.exec(block.text.trim())?.[1];
15
+ if (!payload) continue;
16
+ const status = field(payload, "status");
17
+ const summary = field(payload, "summary");
18
+ if (!status && !summary) continue;
19
+ const taskId = field(payload, "task-id");
20
+ const label = status === "completed" ? "后台任务已完成"
21
+ : status === "failed" ? "后台任务失败"
22
+ : status === "stopped" || status === "cancelled" || status === "canceled" || status === "interrupted" || status === "killed" ? "后台任务已停止"
23
+ : status === "timeout" || status === "timed_out" ? "后台任务超时" : "后台任务通知";
24
+ const title = label + (taskId && /^[a-z\d][a-z\d._-]{0,63}$/iu.test(taskId) ? ` · #${taskId}` : "");
25
+ const exitCode = /^Shell task (?:completed|failed) with exit code (-?\d{1,12})$/iu.exec(summary ?? "")?.[1];
26
+ // Keep the reported summary as text. Do not surface or read the output-file field.
27
+ const characters = Array.from(summary?.replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ").trim() ?? "");
28
+ const detail = characters.slice(0, 360).join("").replaceAll("```", "'''") + (characters.length > 360 ? "…" : "");
29
+ const text = exitCode !== undefined ? `${title} · Shell 退出码 ${exitCode}`
30
+ : detail ? `${title}\n\n\`\`\`\n${detail}\n\`\`\`` : title;
31
+ return { activityId: TASK_NOTIFICATION_ACTIVITY_PREFIX + item.id, text };
32
+ }
33
+ }
34
+
35
+ export function readTaskNotifications(items: unknown): TaskNotificationActivity[] {
36
+ return Array.isArray(items) ? items.flatMap((item) => {
37
+ const activity = readTaskNotification(item);
38
+ return activity ? [activity] : [];
39
+ }) : [];
40
+ }
41
+
42
+ function field(payload: string, name: "status" | "task-id" | "summary"): string | undefined {
43
+ const value = new RegExp(`(?:^|\\n)[ \\t]*<${name}>([\\s\\S]*?)</${name}>(?=[ \\t]*(?:\\r?\\n|$))`, "u").exec(payload)?.[1]?.trim();
44
+ return value || undefined;
45
+ }
46
+
47
+ function isRecord(value: unknown): value is Record<string, unknown> {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
@@ -240,7 +240,7 @@ function fieldsFor(
240
240
  return [
241
241
  bool("console", "本地控制台", ["console", "enabled"]),
242
242
  bool("terminal", "网页终端", ["terminal", "enabled"]),
243
- field("terminalPassword", "终端密码", ["terminal", "password"], "secret", DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema),
243
+ field("terminalPassword", "工作台 / 终端密码", ["terminal", "password"], "secret", DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema),
244
244
  bool("preview", "文件与 Turn 预览", ["fileViewer", "enabled"]),
245
245
  field(
246
246
  "host",
@@ -31,8 +31,9 @@ updates:
31
31
 
32
32
  terminal:
33
33
  enabled: true
34
- # Shares fileViewer networking. Set a strong password before exposing to other devices.
35
- # password: "123456" # Default when omitted; configurable in /settings > Advanced.
34
+ # Shared Workspace / Terminal password, configurable in /settings > Advanced.
35
+ # With the public default, Workspace (including its embedded terminal) is open to anyone who can reach it.
36
+ # password: "123456" # Default when omitted.
36
37
 
37
38
  fileViewer:
38
39
  enabled: true
@@ -24,6 +24,10 @@ export function defaultSqlitePath(env: NodeJS.ProcessEnv = process.env): string
24
24
  return path.join(agentBotHome(env), "data", "agent-bot.sqlite");
25
25
  }
26
26
 
27
+ export function inboundImageDirectory(sqlitePath: string): string {
28
+ return path.join(path.dirname(sqlitePath), "inbound-images");
29
+ }
30
+
27
31
  export function resolveUserPath(input: string, baseDirectory = process.cwd()): string {
28
32
  const expanded = expandHome(input);
29
33
  return path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDirectory, expanded);
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { approvalActivityId } from "../presentation/TurnStateReducer.js";
3
+ import { modelQueueLabel } from "../presentation/turnStatus.js";
3
4
  import path from "node:path";
4
5
  import type { JsonValue } from "../acp/acpTypes.js";
5
6
  import type { RuntimeSession } from "../acp/AcpSessionManager.js";
@@ -15,6 +16,7 @@ import type {
15
16
  import type { TurnActivity, TurnViewState, TurnViewStatus } from "../presentation/turnViewTypes.js";
16
17
  import type { ExecutionProvenance } from "../state/ExecutionProvenanceStore.js";
17
18
  import { visibleTurnActivities } from "../presentation/visibleTurnActivities.js";
19
+ import { formatModelQueueDuration, isCommentaryActivity, liveModelQueueActivity, systemActivityQuote, USER_ACTIVITY_ICON } from "../presentation/turnActivity.js";
18
20
  import { displayRuntimeError } from "../runtime/responseErrors.js";
19
21
  import { truncateMiddle, truncateText } from "../utils/markdown.js";
20
22
  import type { UpdateNotice } from "../updates/types.js";
@@ -64,6 +66,7 @@ export interface InitializationWelcomeView {
64
66
 
65
67
  export interface SafeRestartStatusView {
66
68
  activeTerminals?: number;
69
+ pendingInboundMessages?: number;
67
70
  terminalBlockers?: ActiveTerminal[];
68
71
  contextKey?: string;
69
72
  scheduleId: number;
@@ -1025,8 +1028,8 @@ export class CardRenderer {
1025
1028
  } else {
1026
1029
  const waiting = view.state === "approved";
1027
1030
  const label = waiting ? "打开终端" : "重新打开终端";
1028
- elements.push(markdown(`**状态**:${waiting ? "已授权,等待网页连接" : view.connected ? "已连接" : "网页已断开,Shell 仍在运行"}\n${waiting ? "请返回原网页连接;原网页已关闭时,点击下方“打开终端”。Shell 尚未启动。" : "点击下方“重新打开终端”恢复原 Shell。前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 3 分钟后会自动关闭 Shell,成功重连取消断开计时并重置空闲计时;“关闭终端”会中断其中的命令。"}`));
1029
- elements.push(markdown(`[${label}](${view.reopenUrl}) · 新网页输入终端密码${waiting ? ",连接成功后启动 Shell" : ",恢复原 Shell"}`));
1031
+ elements.push(markdown(`**状态**:${waiting ? "已授权,等待网页连接" : view.connected ? "已连接" : "网页已断开,Shell 仍在运行"}\n${waiting ? "请返回原网页连接;原网页已关闭时,点击下方“打开终端”。Shell 尚未启动。" : "点击下方“重新打开终端”直接恢复原 Shell,无需再次输入密码。前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 30 分钟后会自动关闭 Shell,成功重连取消断开计时并重置空闲计时;“关闭终端”会中断其中的命令。"}`));
1032
+ elements.push(markdown(`[${label}](${view.reopenUrl}) · ${waiting ? "新网页输入终端密码,连接成功后启动 Shell" : "直接恢复原 Shell"}`));
1030
1033
  elements.push(taskActionRow([{ text: "关闭终端", type: "danger", value: action("close") }, { text: "刷新", value: action("refresh") }]));
1031
1034
  }
1032
1035
  return sectionCard("网页终端管理", elements, view.state === "closed" ? "grey" : "blue");
@@ -1059,6 +1062,7 @@ export class CardRenderer {
1059
1062
  `**重启原因**:${inlineCode(view.reason)}`,
1060
1063
  `**重启倒计时**:${countdown}`,
1061
1064
  `**待投递结果**:${view.pendingFinalDeliveries} 条`,
1065
+ ...(view.pendingInboundMessages ? [`**正在处理收到的消息**:${view.pendingInboundMessages} 条`] : []),
1062
1066
  ...(view.activeTerminals ? [`**活动终端**:${view.activeTerminals} 个。结束终端会中断其中的命令;ForceRestart 会中断所有终端。`] : []),
1063
1067
  ];
1064
1068
  const elements: Record<string, unknown>[] = [markdown(lines.join("\n"))];
@@ -1321,18 +1325,42 @@ export class CardRenderer {
1321
1325
  );
1322
1326
  }
1323
1327
  return turnCard(
1324
- turnTitle(state.status, state.prompt ?? state.taskTitle),
1328
+ turnTitle(state.status, state.prompt ?? state.taskTitle, modelQueueLabel(state)),
1325
1329
  turnTemplate(state.status),
1326
1330
  elements,
1327
1331
  renderTurnSubtitle(state),
1328
1332
  );
1329
1333
  }
1330
1334
 
1335
+ renderTaskNotification(state: TurnViewState, previewUrl?: string, answer?: string, hasMore = false): Record<string, unknown> {
1336
+ const elements = (state.taskNotificationCard ?? []).map((notice) => markdown(notice.text));
1337
+ if (answer) {
1338
+ elements.push({ tag: "hr" }, markdown("**补充回答**"), markdown(answer));
1339
+ if (hasMore) elements.push(markdown(previewUrl ? "回答较长,完整内容可在 Preview 查看。" : "回答较长,剩余内容将另行发送。"));
1340
+ } else if (isTurnStoppable(state.status) || state.status === "starting") {
1341
+ elements.push(markdown(modelQueueLabel(state) ?? "正在处理后台任务结果…"));
1342
+ } else if (state.status === "cancelled" && !state.statusMessage) {
1343
+ elements.push(markdown("已停止处理后台任务结果。"));
1344
+ }
1345
+ if (state.approval) elements.push(...renderApprovalElements(state, state.approval));
1346
+ if (state.statusMessage) elements.push(markdown(codeBlock(state.statusMessage, 2_000)));
1347
+ if (state.error) elements.push(markdown(codeBlock(displayRuntimeError(state.error), 2_000)));
1348
+ const actions: TaskListCardAction[] = [];
1349
+ if (isTurnStoppable(state.status)) actions.push({
1350
+ text: "Stop", type: "danger", value: { action: "turn_cancel", sessionId: state.sessionId, turnId: state.turnId },
1351
+ });
1352
+ if (previewUrl) actions.push(turnPreviewAction(previewUrl));
1353
+ if (actions.length) elements.push({ tag: "hr" }, taskActionRow(actions));
1354
+ return turnCard("后台任务通知", state.error ? "red" : "blue", elements, truncateText(state.taskTitle ?? "", 80));
1355
+ }
1356
+
1331
1357
  renderTurnDetails(state: TurnViewState, previewUrl?: string, provenance?: ExecutionProvenance): Record<string, unknown> {
1332
1358
  const title = state.taskTitle
1333
1359
  ? `任务执行详情:${truncateText(state.taskTitle.replace(/\s+/g, " ").trim(), 60)}`
1334
1360
  : "任务执行详情";
1335
1361
  const elements = [markdown(`Turn: \`${state.turnId}\``)];
1362
+ const queueLabel = modelQueueLabel(state);
1363
+ if (queueLabel) elements.push(markdown(`**${queueLabel}**`));
1336
1364
  if (provenance) {
1337
1365
  const labels: Record<ExecutionProvenance["trigger"], string> = {
1338
1366
  user: "用户消息", queue: "排队消息", schedule: "定时任务", recovery: "未提交请求恢复",
@@ -1901,6 +1929,12 @@ function renderActivity(
1901
1929
  projectCwd?: string,
1902
1930
  fullAssistantText = false,
1903
1931
  ): Record<string, unknown>[] {
1932
+ if (activity.kind === "system") {
1933
+ const text = activity.text.trim();
1934
+ if (!text) return [];
1935
+ const chunks = fullAssistantText ? splitText(text, ACTIVITY_TEXT_CHUNK) : [truncateText(text, MAX_LIVE_ASSISTANT_TEXT)];
1936
+ return chunks.map((chunk) => markdown(systemActivityQuote(chunk)));
1937
+ }
1904
1938
  if (activity.kind === "user") {
1905
1939
  const text = activity.text.trim();
1906
1940
  if (!text) return [];
@@ -1931,7 +1965,7 @@ function boldUserActivity(text: string, showIcon: boolean): string {
1931
1965
  return text
1932
1966
  .split("\n")
1933
1967
  .map((line, index) => {
1934
- const content = showIcon && index === 0 ? `🙋 ${line}` : line;
1968
+ const content = showIcon && index === 0 ? `${USER_ACTIVITY_ICON} ${line}` : line;
1935
1969
  return content ? `**${content}**` : "";
1936
1970
  })
1937
1971
  .join("\n");
@@ -2004,7 +2038,7 @@ function groupTurnActivities(activities: TurnActivity[]): GroupedTurnActivity[]
2004
2038
  };
2005
2039
 
2006
2040
  for (const activity of activities) {
2007
- if (!isCommentaryActivity(activity)) {
2041
+ if (!isCommentaryActivity(activity) && activity.kind !== "system") {
2008
2042
  segment.push(activity);
2009
2043
  continue;
2010
2044
  }
@@ -2015,11 +2049,6 @@ function groupTurnActivities(activities: TurnActivity[]): GroupedTurnActivity[]
2015
2049
  return groups;
2016
2050
  }
2017
2051
 
2018
- function isCommentaryActivity(activity: TurnActivity): boolean {
2019
- return activity.kind === "assistant"
2020
- || (activity.kind === "reasoning" && activity.id.startsWith("commentary:"));
2021
- }
2022
-
2023
2052
  function executionActivityPanel(
2024
2053
  group: Extract<GroupedTurnActivity, { kind: "execution" }>,
2025
2054
  projectCwd: string | undefined,
@@ -2250,7 +2279,11 @@ function removeMarkdownBold(value: string): string {
2250
2279
 
2251
2280
  function turnActivities(state: TurnViewState): TurnActivity[] {
2252
2281
  if (state.activities?.length) {
2253
- const activities = visibleTurnActivities(state);
2282
+ const queue = liveModelQueueActivity(state);
2283
+ const activities = visibleTurnActivities(state).map((activity) => queue && activity.id === queue.id
2284
+ && activity.kind === "system" && activity.category === "model_queue"
2285
+ ? { ...activity, text: `${queue.label} · 已等待 ${formatModelQueueDuration(Date.now() - queue.startedAt)}。` }
2286
+ : activity);
2254
2287
  return state.approval ? activities.filter((a) => a.id !== approvalActivityId(state.turnId, state.approval!.id)) : activities;
2255
2288
  }
2256
2289
 
@@ -2765,7 +2798,7 @@ function persistedTaskStatus(sessionStatus: string, lastTurnStatus?: string): st
2765
2798
  return labels[lastTurnStatus ?? sessionStatus] ?? lastTurnStatus ?? sessionStatus;
2766
2799
  }
2767
2800
 
2768
- function turnTitle(status: TurnViewStatus, prompt?: string): string {
2801
+ function turnTitle(status: TurnViewStatus, prompt?: string, queueLabel?: string): string {
2769
2802
  if (status === "unknown") return `待核实${prompt ? `:${truncateTurnPrompt(prompt)}` : ""}`;
2770
2803
  const reactionEmoji = status === "completed"
2771
2804
  ? "✅"
@@ -2786,7 +2819,8 @@ function turnTitle(status: TurnViewStatus, prompt?: string): string {
2786
2819
  ? "等待确认"
2787
2820
  : "正在处理";
2788
2821
  const compactPrompt = truncateTurnPrompt(prompt);
2789
- const title = compactPrompt ? `${currentStatus}:${compactPrompt}` : currentStatus;
2822
+ const label = queueLabel ?? currentStatus;
2823
+ const title = compactPrompt ? `${label}:${compactPrompt}` : label;
2790
2824
  return `${reactionEmoji} ${title}`;
2791
2825
  }
2792
2826
 
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { Logger } from "pino";
5
- import { defaultSqlitePath } from "../config/paths.js";
5
+ import { defaultSqlitePath, inboundImageDirectory } from "../config/paths.js";
6
6
  import type { AppConfig } from "../config/schema.js";
7
7
  import { normalizeFeishuMarkdown } from "./FeishuMarkdown.js";
8
8
  import { LOCAL_CARD_IMAGE_PATH } from "./LocalCardImage.js";
@@ -835,7 +835,7 @@ export class FeishuMessageClient implements FeishuOutbound {
835
835
  if (bytes.byteLength > 20 * 1024 * 1024) throw new Error("Feishu image exceeds the 20 MiB input limit.");
836
836
 
837
837
  const sqlitePath = this.config.storage?.sqlitePath ?? defaultSqlitePath();
838
- const directory = path.join(path.dirname(sqlitePath), "inbound-images");
838
+ const directory = inboundImageDirectory(sqlitePath);
839
839
  await mkdir(directory, { recursive: true });
840
840
  const digest = createHash("sha256").update(`${messageId}:${imageKey}`).digest("hex");
841
841
  const filePath = path.join(directory, `${digest}${imageExtension(contentType)}`);