Просмотр исходного кода

迁移后旧 Bot 会话不存在时自动新建并补回近期记录

未导入旧 ~/.hermes 就升级时,Bot 绑定指向本机不存在的 Hermes 会话,
每次发送都失败「会话不存在」。恢复返回 session_not_found 时改为新建会话,
单聊与群聊都把夭夭保存的近期记录作为上下文补进新会话。
新增真实内核回归测试。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HvtCVdUBNe9gYx2xaCShcc
Claude 3 часов назад
Родитель
Сommit
d37121faa6

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

@@ -241,6 +241,7 @@ yaovi-agent 在内置 Hermes 的同时还做了很多产品层改动,本方案
 - 管理员与子账号使用同一套界面:「聊天」里的 Bot 单聊和群聊,以及工具菜单(电脑接管、自动化等)。设置中心默认打开「我的资料」,不再有模式切换。
 - 旧链接 `/`、`/chat/*`、`/history/*`、`/files`、`/artifacts` 及未知路径都跳转到 `/conversations`。
 - 未读只统计 Bot 会话;为兼容旧客户端,接口仍返回 `chat` 字段,固定为 0。
+- 升级时没有导入旧 `~/.hermes`(例如 Docker 未叠加 `compose.hermes-import.yaml`、旧数据不在默认目录或导入失败)时,已有 Bot 对话绑定的 Hermes 会话在本机不存在:Bot 会自动新建会话,并把夭夭保存的近期聊天记录作为上下文补给新会话,不再每次报「会话不存在」。
 - `/api/app/capabilities` 的 `features` 新增 `bot-only-v1`。yaoyao-mobile 看到该标记后强制进入 Bot 模式、隐藏「聊天模式」切换、不再加载普通聊天运行时,并拒绝打开普通聊天与旧群组通知;未带该标记的旧服务端保持原有行为。
 - 账号扫码登录保留;设备配对(`/api/app/pairings*`、`/api/app/paired-devices*`、`/api/pair/v1/*`)删除。远程 Bot 已在此前停用,因此已有节点记录只能查看和删除,新的子节点配对会因对端没有配对接口而失败。
 - 不再写入 `chat-cache.sqlite3` 和 `realtime-receipts.sqlite3`;已有文件保留在数据目录中,可手动删除。`HERMES_YAOYAO_CHAT_CACHE_MODE` 已停用。

+ 1 - 1
src/server/hermes/gateway.ts

@@ -271,7 +271,7 @@ export class EmbeddedGateway {
       const name = profile ?? 'default'
       if (!PROFILE.test(name)) throw new HttpError(400, 'Profile 名称无效', 'gateway_rejected')
       const detail = await this.options.pool.call<{ status: number }>(this.profileScope(name), 'dashboard.call', { method: 'GET', path: `/api/sessions/${id}` })
-      if (detail.status !== 200) throw new HttpError(404, '会话不存在', 'gateway_rejected')
+      if (detail.status !== 200) throw new HttpError(404, '会话不存在', 'session_not_found')
       const now = Date.now()
       session = this.options.sessions.put({ id, profile: name, source: 'web', createdAt: now, updatedAt: now })
     }

+ 11 - 4
src/server/workspaceRuntime.ts

@@ -406,6 +406,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
     // Rebuild old exclusive-environment sessions once: their Hermes Agent may
     // still retain restricted native context even after a new tool binding.
     const resetReason = (execution&&(binding?.executionRevision!==execution.revision||binding?.executionPolicyVersion!==2)?'execution_environment_changed':undefined) ?? memoryReset ?? (sourceReset ? 'source_changed' : movedRunner ? 'runner_changed' : undefined)
+    // Set when the stored Hermes session was missing and a new one replaced it; replays recent history.
+    let sessionRecreated = false
     if(resetReason) {
       if(recovering)throw new HttpError(409,'执行节点已变化,不能在另一节点重放原执行','runner_target_changed')
       this.inspector?.record(owner, c.id, { method: 'bot.session-reset', direction: 'event', agentId: agent.id, runId: run.runId, taskId: run.conversationTaskId,
@@ -804,8 +806,12 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
         } catch (error) {
           const code = error instanceof HttpError ? error.code : ''
           const message = error instanceof Error ? error.message : ''
-          if (recovering || (code !== 'computer_session_mode_changed' && !message.includes('执行方式已改变'))) throw error
+          // A Hermes session missing from this server (e.g. the legacy ~/.hermes was never imported)
+          // starts a fresh one; the Bot transcript itself lives in the workspace store.
+          const missing = error instanceof HttpError && error.status === 404 && (code === 'session_not_found' || message === '会话不存在')
+          if (recovering || (!missing && code !== 'computer_session_mode_changed' && !message.includes('执行方式已改变'))) throw error
           binding = undefined
+          sessionRecreated = missing
           opened = await createSession()
         }
       } else opened = await createSession()
@@ -1005,8 +1011,9 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
         }
         const members = run.turnConfiguration!.members
         const goal = run.conversationTaskId ? this.store.get<import('../shared/agentTasks.js').AgentGoal>(owner, 'goal', run.conversationTaskId) : undefined
-        const text = c.kind === 'group' ? this.contextText(owner, c, agent, run, binding.contextSeq ?? 0, !!resetReason)
-          : resetReason ? `${movedRunner ? '执行节点已切换' : '记忆或授权范围已变化,会话已重新建立'}。以下是原会话的近期记录,旧路径和执行状态需要在当前节点重新核实;不要重新执行已完成的操作。\n\n${this.contextText(owner,c,agent,run,0,true)}` : trigger.content
+        const replay = !!resetReason || sessionRecreated
+        const text = c.kind === 'group' ? this.contextText(owner, c, agent, run, binding.contextSeq ?? 0, replay)
+          : replay ? `${movedRunner ? '执行节点已切换' : resetReason ? '记忆或授权范围已变化,会话已重新建立' : '原 Hermes 会话已不存在,会话已重新建立'}。以下是原会话的近期记录,旧路径和执行状态需要在当前节点重新核实;不要重新执行已完成的操作。\n\n${this.contextText(owner,c,agent,run,0,true)}` : trigger.content
         const admission = this.getWork(owner, run.id)
         if (!this.store.taskMemberIds(owner,this.store.require<Conversation>(owner,'conversation',c.id),run.conversationTaskId).includes(agent.id)) {
           admission.status = 'interrupted'; admission.error = '执行前成员已移除'; this.saveWork(owner, admission)
@@ -1030,7 +1037,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
             knowledgeRules: knowledge ? BOT_KNOWLEDGE_RULES : undefined,
             memory: memoryDelta(memory, binding.memoryState), noReply: NO_REPLY,
             marker: `[yaoyao-run:${run.runId}:${resultMessage.id}]`,
-            content: text+(systemTurn?.description.length?'\n[本轮系统服务目录,仅含元数据]\n'+JSON.stringify(systemTurn.description):''), contentKind: c.kind === 'group' || !!resetReason ? 'history' : 'user', attachmentRefs,
+            content: text+(systemTurn?.description.length?'\n[本轮系统服务目录,仅含元数据]\n'+JSON.stringify(systemTurn.description):''), contentKind: c.kind === 'group' || replay ? 'history' : 'user', attachmentRefs,
           })
           this.inspector?.record(owner,c.id,{method:'bot.environment',direction:'request',agentId:agent.id,runId:run.runId,taskId:run.conversationTaskId,
             data:{snapshot:environment,computerToolIds:environmentCatalog.map(tool=>tool.id),pluginServices,pluginWarnings:resultMessage.serviceWarnings}})

+ 21 - 0
tests/server/embeddedWorkspace.test.ts

@@ -88,6 +88,27 @@ describe.skipIf(!kernel)('Bot turns on the embedded Hermes kernel', () => {
     expect(existsSync(join(home, 'bots', agent.id, 'runtime', 'state.db'))).toBe(true)
   }, 180_000)
 
+  it('starts a new Hermes session when a migrated Bot binding points at a session that was never imported', async () => {
+    const app = await setup(() => ({ content: '收到。' }))
+    const agent = app.workspace.createAgent('first', { name: '小夭', profile: 'default' })
+    const direct = app.workspace.list<WorkspaceConversation>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === agent.id)!
+    expect((await reply(app, direct, '记住暗号:青梅')).status).toBe('complete')
+    // An upgrade without importing ~/.hermes leaves bindings pointing at sessions this server never had.
+    const key = `${direct.id}:${agent.id}`
+    const binding = app.workspace.get<any>('first', 'binding', key)
+    expect(binding?.storedId).toBeTruthy()
+    app.workspace.put('first', 'binding', key, { ...binding, storedId: 'legacy0000missing', runtimeId: 'legacy0000missing', aliases: ['legacy0000missing'] })
+    requests.length = 0
+    const message = await reply(app, direct, '暗号是什么?')
+    expect(message.status, message.error).toBe('complete')
+    expect(message.content).toContain('收到。')
+    // Recent history from the workspace transcript is replayed into the new session.
+    const prompt = JSON.stringify(requests[0].messages)
+    expect(prompt).toContain('青梅')
+    expect(prompt).toContain('暗号是什么?')
+    expect(app.workspace.list<any>('first', 'binding').some(b => b.storedId === 'legacy0000missing')).toBe(false)
+  }, 240_000)
+
   it('lets a Bot use its granted workspace tools through the embedded lease', async () => {
     const app = await setup((messages, tools) => {
       if (messages.some(m => m.role === 'tool')) return { content: '已查看成员列表。' }