Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): IM 对话被移动到其他项目后不再重开新对话 (#653)
Dash2de297c8adff
diff --git a/apps/desktop/src/main/hook-control/__tests__/bindings.test.ts b/apps/desktop/src/main/hook-control/__tests__/bindings.test.tsnew file mode 100644index 0000000000..87ba40b89c--- /dev/null+++ b/apps/desktop/src/main/hook-control/__tests__/bindings.test.ts@@ -0,0 +1,112 @@+/**+ * hook-control bindings 单测: os.tmpdir 临时文件(规则 23: 测试路径一律走系统+ * 临时目录, 收尾清理)。重点是工作目录快照的写入与老文件兼容 —— dispatcher 靠+ * 它区分「会话被用户移动」与「工作目录映射被改」。+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { createHookBindingStore } from '../bindings';++const noopLog = { warn: () => {} };++let dir: string;+const filePath = (): string => path.join(dir, 'hook-bindings.json');++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hook-bindings-'));+});++afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true });+});++const makeStore = () => createHookBindingStore({ filePath: filePath(), log: noopLog });++describe('hook binding store', () => {+ it('落绑定时记下工作目录快照与授权来源, get / getEntry 都能读回', () => {+ const store = makeStore();+ store.set('conn-1', 'slack:C1:1.1', 'sess-1', '/repos/demo', 'workspace');++ expect(store.get('conn-1', 'slack:C1:1.1')).toBe('sess-1');+ expect(store.getEntry('conn-1', 'slack:C1:1.1')).toEqual({+ sessionId: 'sess-1',+ workingDir: '/repos/demo',+ authority: 'workspace',+ });+ expect(store.getEntry('conn-1', 'missing')).toBeNull();+ });++ it('local-move 授权跨实例持久化(重启后跟随不能退回撤权)', () => {+ makeStore().set('conn-1', 'k', 'sess-1', '/repos/moved', 'local-move');++ expect(makeStore().getEntry('conn-1', 'k')).toEqual({+ sessionId: 'sess-1',+ workingDir: '/repos/moved',+ authority: 'local-move',+ });+ });++ it('未传目录 / 授权时不写这两个字段', () => {+ makeStore().set('conn-1', 'k', 'sess-2');+ const row = JSON.parse(fs.readFileSync(filePath(), 'utf-8')) as Record<+ string,+ Record<string, Record<string, unknown>>+ >;++ expect(row['conn-1']['k']).not.toHaveProperty('workingDir');+ expect(row['conn-1']['k']).not.toHaveProperty('authority');+ expect(makeStore().getEntry('conn-1', 'k')).toEqual({+ sessionId: 'sess-2',+ workingDir: null,+ authority: null,+ });+ });++ it('老文件(无 workingDir / authority)读成 null, 不当成"目录变过"或"已授权"', () => {+ fs.writeFileSync(+ filePath(),+ JSON.stringify({ 'conn-1': { 'slack:C1:1.1': { sessionId: 'legacy', updatedAt: 1 } } }),+ 'utf-8',+ );+ const store = makeStore();++ expect(store.get('conn-1', 'slack:C1:1.1')).toBe('legacy');+ expect(store.getEntry('conn-1', 'slack:C1:1.1')).toEqual({+ sessionId: 'legacy',+ workingDir: null,+ authority: null,+ });+ });++ it('authority 是未知字面量时按"没有授权记录"读(fail closed)', () => {+ fs.writeFileSync(+ filePath(),+ JSON.stringify({+ 'conn-1': {+ k: {+ sessionId: 'sess-1',+ workingDir: '/repos/demo',+ authority: 'anything',+ updatedAt: 1,+ },+ },+ }),+ 'utf-8',+ );++ expect(makeStore().getEntry('conn-1', 'k')?.authority).toBeNull();+ });++ it('remove 清掉整条绑定(含快照与授权)', () => {+ const store = makeStore();+ store.set('conn-1', 'k', 'sess-1', '/repos/demo', 'local-move');+ store.remove('conn-1', 'k');++ expect(store.getEntry('conn-1', 'k')).toBeNull();+ });+});diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.tsindex 140f5513ea..ec451e9411 100644--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts@@ -14,13 +14,14 @@ import {buildHookSessionTitle,createHookDispatcher,isPathWithin,+ isSamePath,normalizeTaskSource,type HookDispatcherDeps,type HookRunOutcome,type HookRunRequest,type HookSessionRunner,} from '../dispatcher';-import type { HookBindingStore } from '../bindings';+import type { HookBindingEntry, HookBindingStore } from '../bindings';import type { HookConnectionConfig } from '../store';const noopLog = { info: () => {}, warn: () => {} };@@ -36,13 +37,22 @@ const CONFIG: HookConnectionConfig = {createdAt: 0,};-/** 内存 binding。 */+/** 内存 binding(含工作目录快照与授权来源, 与文件实现同语义)。 */function memoryBindings(): HookBindingStore {- const map = new Map<string, string>();+ const map = new Map<string, HookBindingEntry>();const k = (c: string, e: string): string => `${c}|${e}`;return {- get: (c, e) => map.get(k(c, e)) ?? null,- set: (c, e, s) => void map.set(k(c, e), s),+ get: (c, e) => map.get(k(c, e))?.sessionId ?? null,+ getEntry: (c, e) => {+ const row = map.get(k(c, e));+ return row ? { ...row } : null;+ },+ set: (c, e, s, workingDir, authority) =>+ void map.set(k(c, e), {+ sessionId: s,+ workingDir: workingDir ?? null,+ authority: authority ?? null,+ }),remove: (c, e) => void map.delete(k(c, e)),};}@@ -151,6 +161,16 @@ describe('isPathWithin', () => {});});+describe('isSamePath', () => {+ it('同一目录的不同写法算相同, 子目录不算', () => {+ expect(isSamePath(WS_DIR, WS_DIR)).toBe(true);+ expect(isSamePath(WS_DIR, path.join(WS_DIR, 'sub', '..'))).toBe(true);+ expect(isSamePath(WS_DIR, `${WS_DIR}${path.sep}`)).toBe(true);+ expect(isSamePath(WS_DIR, path.join(WS_DIR, 'sub'))).toBe(false);+ expect(isSamePath(WS_DIR, path.resolve('/repos/other'))).toBe(false);+ });+});+describe('buildHookSessionTitle', () => {it('短消息原样进标题, 换行/连续空白压平成单空格', () => {expect(buildHookSessionTitle('slack', '修一下登录页', 'C1:1.1')).toBe('[Slack] 修一下登录页');@@ -408,6 +428,212 @@ describe('dispatcher 核心语义', () => {fr.finish();});+ it('会话被移出工作目录映射: 目录变过 -> 跟随复用并说明, 不重开新会话', async () => {+ const bindings = memoryBindings();+ const sessions: Record<string, { workingDir: string; usable: boolean }> = {};+ const fr = fakeRunner({ sessions });+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();+ const first = c.last('task.ack')!.payload.sessionId!;+ sessions[first] = { workingDir: WS_DIR, usable: true };+ fr.finish();+ await tick();++ // 用户在桌面端把这条会话「移动到项目」, 目标目录不在工作目录映射里+ const MOVED_DIR = path.resolve('/repos/another-project');+ sessions[first] = { workingDir: MOVED_DIR, usable: true };++ d.handleDispatch('conn-1', dispatch({ requestId: 'req-2' }), c.send);+ await tick();+ expect(c.last('task.ack')!.payload).toMatchObject({ result: 'accepted', sessionId: first });+ expect(fr.calls[1]).toMatchObject({ isNew: false, sessionId: first, workingDir: MOVED_DIR });+ // 快照跟随移动, 并记下"这份授权来自本地移动"+ expect(bindings.getEntry('conn-1', 'team-slack:C1:1.1')).toEqual({+ sessionId: first,+ workingDir: MOVED_DIR,+ authority: 'local-move',+ });++ fr.finish({ finalText: '在新目录里跑完了' });+ await tick();+ const finalText = c.last('turn.end')!.payload.finalText;+ expect(finalText).toContain('已被移动到新的工作目录');+ expect(finalText).toContain('在新目录里跑完了');+ });++ it('移动后的后续消息持续复用同一 session, 且不再重复提示(跟随不能只生效一次)', async () => {+ const bindings = memoryBindings();+ const sessions: Record<string, { workingDir: string; usable: boolean }> = {};+ const fr = fakeRunner({ sessions });+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();+ const MOVED_DIR = path.resolve('/repos/another-project');++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();+ const first = c.last('task.ack')!.payload.sessionId!;+ sessions[first] = { workingDir: WS_DIR, usable: true };+ fr.finish();+ await tick();++ // 移动后连发两条: 第二条时快照已等于新目录, 只有持久化的授权来源能保住复用+ sessions[first] = { workingDir: MOVED_DIR, usable: true };+ d.handleDispatch('conn-1', dispatch({ requestId: 'req-2' }), c.send);+ await tick();+ fr.finish({ finalText: '第一次' });+ await tick();++ d.handleDispatch('conn-1', dispatch({ requestId: 'req-3' }), c.send);+ await tick();+ expect(c.last('task.ack')!.payload).toMatchObject({ result: 'accepted', sessionId: first });+ expect(fr.calls[2]).toMatchObject({ isNew: false, sessionId: first, workingDir: MOVED_DIR });++ fr.finish({ finalText: '第二次' });+ await tick();+ // 说明只在"这次刚发现被移动"时出现一次+ expect(c.last('turn.end')!.payload.finalText).toBe('第二次');+ });++ it('对话移回工作目录映射内: 授权来源复位, 此后映射被改仍按撤权重建', async () => {+ const bindings = memoryBindings();+ const sessions: Record<string, { workingDir: string; usable: boolean }> = {};+ const fr = fakeRunner({ sessions });+ const config: HookConnectionConfig = { ...CONFIG, workspaces: { xdmaker: WS_DIR } };+ const { d } = makeDispatcher({ runner: fr.runner, bindings, config });+ const c = collector();+ const MOVED_DIR = path.resolve('/repos/another-project');++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();+ const first = c.last('task.ack')!.payload.sessionId!;+ sessions[first] = { workingDir: MOVED_DIR, usable: true };+ fr.finish();+ await tick();++ // 移出去一次(拿到 local-move 授权), 再移回映射内+ d.handleDispatch('conn-1', dispatch({ requestId: 'req-2' }), c.send);+ await tick();+ fr.finish();+ await tick();+ sessions[first] = { workingDir: WS_DIR, usable: true };+ d.handleDispatch('conn-1', dispatch({ requestId: 'req-3' }), c.send);+ await tick();+ expect(bindings.getEntry('conn-1', 'team-slack:C1:1.1')).toEqual({+ sessionId: first,+ workingDir: WS_DIR,+ authority: 'workspace',+ });+ fr.finish();+ await tick();++ // 授权已复位: 映射改指别处时按撤权重建, 不再吃老的 local-move+ config.workspaces = { xdmaker: path.resolve('/repos/elsewhere') };+ d.handleDispatch('conn-1', dispatch({ requestId: 'req-4' }), c.send);+ await tick();+ expect(c.last('task.ack')!.payload.sessionId).not.toBe(first);+ fr.finish();+ });++ it('工作目录映射被改(会话目录没变) -> 仍丢绑定重建, 并说明原因', async () => {+ const bindings = memoryBindings();+ const sessions: Record<string, { workingDir: string; usable: boolean }> = {};+ const fr = fakeRunner({ sessions });+ const config: HookConnectionConfig = { ...CONFIG, workspaces: { xdmaker: WS_DIR } };+ const { d } = makeDispatcher({ runner: fr.runner, bindings, config });+ const c = collector();++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();+ const first = c.last('task.ack')!.payload.sessionId!;+ sessions[first] = { workingDir: WS_DIR, usable: true };+ fr.finish();+ await tick();++ // 用户把别名改指到别的目录 = 撤销旧目录的 IM 访问, 旧会话不得继续被驱动+ config.workspaces = { xdmaker: path.resolve('/repos/elsewhere') };++ d.handleDispatch('conn-1', dispatch({ requestId: 'req-2' }), c.send);+ await tick();+ const second = c.last('task.ack')!.payload.sessionId!;+ expect(second).not.toBe(first);+ expect(fr.calls[1]).toMatchObject({+ isNew: true,+ workingDir: path.resolve('/repos/elsewhere'),+ });++ fr.finish({ finalText: '新会话的回答' });+ await tick();+ const finalText = c.last('turn.end')!.payload.finalText;+ expect(finalText).toContain('原对话已不在可用的工作目录里');+ expect(finalText).toContain('新会话的回答');+ });++ it('老绑定没有目录快照时按保守侧处理: 越界即重建', async () => {+ const bindings = memoryBindings();+ const OUTSIDE = path.resolve('/repos/another-project');+ const fr = fakeRunner({+ sessions: { 'legacy-session': { workingDir: OUTSIDE, usable: true } },+ });+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();+ // v1 形态: 只有 sessionId, 无从判断目录是被用户移动还是映射被改+ bindings.set('conn-1', 'team-slack:C1:1.1', 'legacy-session');++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();++ const sessionId = c.last('task.ack')!.payload.sessionId!;+ expect(sessionId).not.toBe('legacy-session');+ expect(fr.calls[0]).toMatchObject({ isNew: true, workingDir: WS_DIR });+ expect(bindings.getEntry('conn-1', 'team-slack:C1:1.1')).toEqual({+ sessionId,+ workingDir: WS_DIR,+ authority: 'workspace',+ });+ fr.finish();+ });++ it('正常复用顺手回填目录快照(存量绑定升级路径)', async () => {+ const bindings = memoryBindings();+ const fr = fakeRunner({ sessions: { 'legacy-session': { workingDir: WS_DIR, usable: true } } });+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();+ bindings.set('conn-1', 'team-slack:C1:1.1', 'legacy-session');++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();++ expect(c.last('task.ack')!.payload.sessionId).toBe('legacy-session');+ expect(bindings.getEntry('conn-1', 'team-slack:C1:1.1')).toEqual({+ sessionId: 'legacy-session',+ workingDir: WS_DIR,+ authority: 'workspace',+ });+ fr.finish({ finalText: '继续' });+ await tick();+ // 正常复用不打扰用户+ expect(c.last('turn.end')!.payload.finalText).toBe('继续');+ });++ it('绑定的会话已归档/删除 -> 重建并说明是原对话没了', async () => {+ const bindings = memoryBindings();+ const fr = fakeRunner({ sessions: { 'gone-session': { workingDir: WS_DIR, usable: false } } });+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();+ bindings.set('conn-1', 'team-slack:C1:1.1', 'gone-session', WS_DIR, 'workspace');++ d.handleDispatch('conn-1', dispatch(), c.send);+ await tick();+ expect(c.last('task.ack')!.payload.sessionId).not.toBe('gone-session');++ fr.finish({ finalText: '新的回答' });+ await tick();+ expect(c.last('turn.end')!.payload.finalText).toContain('原对话已被归档或删除');+ });+it('切账号期间异步定位失败也不回写旧代 rejected ack', async () => {let rejectInspect: ((reason: Error) => void) | undefined;const runner: HookSessionRunner = {diff --git a/apps/desktop/src/main/hook-control/bindings.ts b/apps/desktop/src/main/hook-control/bindings.tsindex 890804bbcb..3f4a376530 100644--- a/apps/desktop/src/main/hook-control/bindings.ts+++ b/apps/desktop/src/main/hook-control/bindings.ts@@ -3,25 +3,65 @@* ---------------------------------------------------------------------------* externalKey -> sessionId 映射存储(协议铁律「同 key 同 session」的落地)。*- * 结构: { [connectionId]: { [externalKey]: { sessionId, updatedAt } } } ——- * 以 connectionId 为命名空间隔离, 两个 hook server 的同名 key 不会串台。+ * 结构:+ * { [connectionId]: { [externalKey]: { sessionId, workingDir, authority, updatedAt } } }+ * —— 以 connectionId 为命名空间隔离, 两个 hook server 的同名 key 不会串台。* 持久化为 <userData>/hook-bindings.json(原子写), 跨 app 重启保持会话连续性。* 体量: 每 thread/issue 一条, 实际规模远小于消息量, JSON 文件足够;* 若未来需要清理策略再升级 localDb 表。+ *+ * workingDir + authority 记录**上次确认这条绑定可用时**的工作目录, 以及那次+ * 是凭什么放行的。dispatcher 靠这两个字段区分三件本来看起来一样的事:+ * 「用户在桌面端把对话移出了工作目录映射」(目录相对快照变了 -> 跟随, 并把+ * authority 记为 local-move)、「上一条消息已按本地移动放行过」(目录没再变且+ * authority=local-move -> 继续跟随, 否则跟随只生效一次)、「用户改动了工作+ * 目录映射」(目录没变且 authority=workspace -> 撤权, 丢绑定重建)。+ * 老文件没有这两个字段 = null/undefined, 判定按保守侧(见 resolveTarget)。*/import fs from 'node:fs';import path from 'node:path';+/**+ * 上次放行这条绑定的依据:+ * - 'workspace': 目录当时落在工作目录映射(或内置对话根)内, 授权随映射走 ——+ * 映射被改/删且目录没动时即失效(撤权)。+ * - 'local-move': 用户在桌面端把对话移出了映射, 由这次**本地**移动授权 ——+ * 目录不在映射内也继续复用, 直到它再被移动(重新判定)或移回映射内。+ */+export type HookBindingAuthority = 'workspace' | 'local-move';++/** 一条绑定的完整视图(get 只要 sessionId 时用 get, 需要目录快照时用 getEntry)。 */+export interface HookBindingEntry {+ sessionId: string;+ /** 上次确认时会话的工作目录; null = 老数据未记录快照。 */+ workingDir: string | null;+ /** 上次放行的依据; null = 老数据未记录。 */+ authority: HookBindingAuthority | null;+}+export interface HookBindingStore {get(connectionId: string, externalKey: string): string | null;- set(connectionId: string, externalKey: string, sessionId: string): void;+ /** 含工作目录快照与授权来源的绑定视图; 不存在时 null。 */+ getEntry(connectionId: string, externalKey: string): HookBindingEntry | null;+ /** 整行覆盖写: 省略 workingDir / authority 等于把它们清空, 调用方应显式传。 */+ set(+ connectionId: string,+ externalKey: string,+ sessionId: string,+ workingDir?: string | null,+ authority?: HookBindingAuthority | null,+ ): void;/** 删除单条绑定(session 失效重建前清理)。 */remove(connectionId: string, externalKey: string): void;}interface BindingRow {sessionId: string;+ /** 见文件头: 上次确认时的工作目录快照; 缺省 = 老数据。 */+ workingDir?: string | null;+ /** 见文件头: 上次放行的依据; 缺省 = 老数据。 */+ authority?: HookBindingAuthority | null;updatedAt: number;}@@ -57,9 +97,25 @@ export function createHookBindingStore(deps: {const row = readAll()[connectionId]?.[externalKey];return typeof row?.sessionId === 'string' ? row.sessionId : null;},- set(connectionId, externalKey, sessionId) {+ getEntry(connectionId, externalKey) {+ const row = readAll()[connectionId]?.[externalKey];+ if (typeof row?.sessionId !== 'string') return null;+ return {+ sessionId: row.sessionId,+ workingDir: typeof row.workingDir === 'string' ? row.workingDir : null,+ // 未知字面量(手改文件 / 更早的实验值)按"没有授权记录"处理, fail closed+ authority:+ row.authority === 'workspace' || row.authority === 'local-move' ? row.authority : null,+ };+ },+ set(connectionId, externalKey, sessionId, workingDir, authority) {const data = readAll();- (data[connectionId] ??= {})[externalKey] = { sessionId, updatedAt: Date.now() };+ (data[connectionId] ??= {})[externalKey] = {+ sessionId,+ ...(typeof workingDir === 'string' && workingDir.length > 0 ? { workingDir } : {}),+ ...(authority === 'workspace' || authority === 'local-move' ? { authority } : {}),+ updatedAt: Date.now(),+ };writeAll(data);},remove(connectionId, externalKey) {diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex f21b1eb2be..4744010aad 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -11,7 +11,11 @@* - 带 sessionId(接管): session 必须存在且其工作目录落在本连接注册的* 别名路径内(白名单不因接管放松), 通过后把 externalKey 重绑到它;* - 不带(默认): 别名解析(映射即白名单)-> binding 查 externalKey ->- * 复用(且重校验白名单)或新建并落绑定;+ * 复用(且重校验白名单)或新建并落绑定; 白名单重校验失败时看绑定上的+ * 目录快照与授权来源: 目录相对快照变过 = 用户在桌面端把对话移出了+ * 映射(目录是本地用户亲手选的, 不是远端指定的)-> 跟随并记 local-move;+ * 目录没再变但已记过 local-move -> 继续认这份授权(否则跟随只生效一+ * 次); 两者都不满足 = 映射被改/删的撤权语义 -> 丢绑定重建;* 3. 排队: 目标 session 正在跑 turn 时 FIFO 排队, ack 回 queued + 位置;* turn 收口后自动 drain;* 4. 回推: turn.end 经当前连接发送; 连接不在线时缓存, 重连(onConnected)@@ -46,7 +50,7 @@ import {import { HOOK_CHAT_WORKSPACE_ALIAS } from '../../shared/hookControlIpc.js';import type { HookConnectionConfig } from './store.js';-import type { HookBindingStore } from './bindings.js';+import type { HookBindingAuthority, HookBindingStore } from './bindings.js';/** 会话执行器抽象 —— 生产实现 session-runner.ts(包 maker), 测试注入假的。 */export interface HookSessionRunner {@@ -213,16 +217,39 @@ const MAX_QUEUE_PER_SESSION = 20;/** 单连接离线 turn.end 缓存上限(FIFO 丢最老)。 */const MAX_PENDING_TURN_ENDS = 100;+/** 路径比较前的规范化。Windows 大小写不敏感(规则 15)。 */+function normalizePathForCompare(p: string): string {+ const resolved = path.resolve(p);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+}+/** target 是否落在 base 目录内(含相等)。Windows 大小写不敏感(规则 15)。 */export function isPathWithin(base: string, target: string): boolean {- const norm = (p: string): string => {- const resolved = path.resolve(p);- return process.platform === 'win32' ? resolved.toLowerCase() : resolved;- };- const rel = path.relative(norm(base), norm(target));+ const rel = path.relative(normalizePathForCompare(base), normalizePathForCompare(target));return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));}+/** 两个路径是否指向同一目录(同 isPathWithin 的规范化口径)。 */+export function isSamePath(a: string, b: string): boolean {+ return normalizePathForCompare(a) === normalizePathForCompare(b);+}++/**+ * 会话被用户移出工作目录映射后, 回给渠道的一次性说明(Slack / Telegram 侧文案+ * 不进 locale, 与 interactions.ts 的卡片按钮同规硬编码中文)。+ */+const NOTICE_SESSION_MOVED = 'ℹ️ 这个对话已被移动到新的工作目录,后续消息都在新目录里执行。';+/**+ * 重建说明必须如实: 旧绑定被丢弃后同一个 externalKey 立刻指向新会话, 光把+ * 老目录加回映射**不会**自动接回原对话(那条 thread 已经绑到新的了), 只有先+ * 恢复目录、再用会话选择重新指定原对话才接得回来 —— 两步缺一不可。+ */+const NOTICE_SESSION_RECREATED =+ 'ℹ️ 原对话已不在可用的工作目录里,这条消息起换用了新对话,原对话的上下文不会带过来。' ++ '想接回原对话:先到 Cindy 的 设置 → 远程连接 → 工作目录映射 把它所在的目录加回来,' ++ '再在这里用对话选择重新指定它。';+const NOTICE_SESSION_GONE = 'ℹ️ 原对话已被归档或删除,这条消息起换用了新对话。';+/** 标题里消息摘要的最大长度(字符), 超出截断加省略号。 */const TITLE_SNIPPET_MAX = 24;/** Server-controlled source metadata is persisted and rendered, so keep it bounded locally too. */@@ -307,6 +334,8 @@ interface PendingTask {externalKey: string;run: HookRunRequest;accountGeneration: number;+ /** 会话定位阶段产生的一次性说明, 前置到本次 turn.end 的 finalText。 */+ notice?: string;}export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {@@ -480,6 +509,13 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {const status: 'ok' | 'error' | 'cancelled' = wasCancelled ? 'cancelled' : outcome.status;// 协议约束: error 必须带非空 errorMessage, ok / cancelled 必须为 nullconst isError = status === 'error';+ // 会话定位说明前置到正文: 协议没有系统消息通道, 而"为什么换了个会话 /+ // 目录变了"必须让渠道里的人看见, 否则只能观察到会话莫名重开。+ const finalText = task.notice+ ? outcome.finalText+ ? `${task.notice}\n\n${outcome.finalText}`+ : task.notice+ : outcome.finalText;sendOrBuffer(task.connectionId,makeTurnEnd({@@ -487,7 +523,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {externalKey: task.externalKey,sessionId,status,- finalText: outcome.finalText,+ finalText,errorMessage: isError ? outcome.errorMessage || 'unknown error' : null,usage: { durationMs: outcome.durationMs },...(outcome.attachments !== undefined && outcome.attachments.length > 0@@ -511,13 +547,17 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {void promise.finally(() => executing.delete(promise));}- /** 会话定位(接管 / 绑定复用 / 新建), 返回 run 参数或拒绝原因。 */+ /**+ * 会话定位(接管 / 绑定复用 / 新建), 返回 run 参数或拒绝原因。+ * notice: 需要随本次 turn.end 一并告知渠道用户的一次性说明(会话被移动 /+ * 旧绑定失效换了新会话) —— 协议没有系统消息通道, 由 execute 前置到 finalText。+ */async function resolveTarget(connectionId: string,config: HookConnectionConfig,payload: TaskDispatchPayload,generation: number,- ): Promise<{ run: HookRunRequest } | { reject: TaskRejectReason }> {+ ): Promise<{ run: HookRunRequest; notice?: string } | { reject: TaskRejectReason }> {// options 四元组原样透传给 runner —— 空值由 runner 按桌面端草稿默认落值// (取值链: Slack 按目录偏好 > 草稿默认, 权限缺省 bypass; 见// hook-control/defaults.ts)。复用/接管路径也照传, 消费与否由 runner 决定@@ -539,6 +579,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {dir !== null && dialogue !== undefined && isPathWithin(dialogue.rootDir(), dir);// 保留别名「对话」: 不查 config.workspaces, 解析成 app 托管对话目录const isChat = payload.workspace === HOOK_CHAT_WORKSPACE_ALIAS && dialogue !== undefined;+ /** 旧绑定作废、本次不得不新建会话时, 随 turn.end 回给渠道的说明。 */+ let recreatedNotice: string | null = null;// 接管路径: server 显式指定已有 session(对话会话同样可接管)if (payload.sessionId !== null) {@@ -548,7 +590,15 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {if (!inWhitelist(info.workingDir) && !inDialogueRoot(info.workingDir)) {return { reject: 'workspace_not_allowed' };}- bindings.set(connectionId, payload.externalKey, payload.sessionId);+ // 接管路径刚校验过白名单, 授权来源恒为 workspace(远端不能凭接管把会话+ // 带出映射 —— 越界的 sessionId 在上面就被 workspace_not_allowed 打回)+ bindings.set(+ connectionId,+ payload.externalKey,+ payload.sessionId,+ info.workingDir,+ 'workspace',+ );return {run: {sessionId: payload.sessionId,@@ -580,15 +630,21 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// account/provider namespace may read it only as a candidate; it is moved// after current-account DB existence + workspace allowlist checks pass.const legacyNamespace = connectionId.endsWith(':slack') ? 'slack' : null;- const namespacedBound = bindings.get(connectionId, payload.externalKey);- const legacyBound =- namespacedBound === null && legacyNamespace !== null- ? bindings.get(legacyNamespace, payload.externalKey)+ const namespacedEntry = bindings.getEntry(connectionId, payload.externalKey);+ const legacyEntry =+ namespacedEntry === null && legacyNamespace !== null+ ? bindings.getEntry(legacyNamespace, payload.externalKey): null;- const bound = namespacedBound ?? legacyBound;- const migrateLegacyBinding = (): void => {+ const namespacedBound = namespacedEntry?.sessionId ?? null;+ const legacyBound = legacyEntry?.sessionId ?? null;+ const boundEntry = namespacedEntry ?? legacyEntry;+ const bound = boundEntry?.sessionId ?? null;+ const migrateLegacyBinding = (+ workingDir: string | null,+ authority: HookBindingAuthority | null,+ ): void => {if (!legacyBound || !legacyNamespace) return;- bindings.set(connectionId, payload.externalKey, legacyBound);+ bindings.set(connectionId, payload.externalKey, legacyBound, workingDir, authority);bindings.remove(legacyNamespace, payload.externalKey);};if (bound) {@@ -624,16 +680,54 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {if (!isCurrentGeneration(generation)) return { reject: 'disabled' };// 复用条件: 仍存在、可用、且仍在白名单内(别名映射可能已被用户改过);// chat 伪目录的会话住在 dialogues 根下, 按对话根校验- if (- info?.usable &&- (isChat ? inDialogueRoot(info.workingDir) : inWhitelist(info.workingDir))- ) {- migrateLegacyBinding();+ const inAllowedRoot =+ info !== null && (isChat ? inDialogueRoot(info.workingDir) : inWhitelist(info.workingDir));+ const usable = info?.usable === true && info.workingDir !== null;+ /** 会话目录与绑定快照一致 = 自上次确认以来它没被动过。 */+ const sameAsSnapshot =+ usable &&+ boundEntry?.workingDir != null &&+ isSamePath(boundEntry.workingDir, info!.workingDir!);+ /**+ * 白名单外但**目录相对快照变过** = 用户在桌面端把这条会话「移动到项目」了。+ * 目录是本地用户亲手选的(不是远端指定的 —— 远端只能在接管路径里选白名单+ * 内的会话), 属本地授权, 跟随即可; 否则同一个 thread 每条消息都会重开新+ * 会话, 破坏「同 key 同 session」。+ */+ const movedNow =+ !inAllowedRoot && usable && boundEntry?.workingDir != null && !sameAsSnapshot;+ /**+ * 上一条消息已按本地移动放行过, 且此后目录没再变 —— 必须继续认这份授权。+ * 少了这一条, 跟随只在移动后的第一条消息生效: 那次会把快照更新成新目录,+ * 下一条消息 movedNow 就变回 false, 绑定又被丢掉(PR #653 review 实测)。+ */+ const stillLocallyAuthorized =+ !inAllowedRoot && usable && boundEntry?.authority === 'local-move' && sameAsSnapshot;+ // 目录没变、也没有本地移动授权而校验失败, 才是「工作目录映射被改/删」的+ // 撤权语义, 仍丢绑定重建。老绑定没有快照时同样走保守侧(正常复用会回填)。+ if (usable && (inAllowedRoot || movedNow || stillLocallyAuthorized)) {+ const workingDir = info!.workingDir!;+ const authority: HookBindingAuthority = inAllowedRoot ? 'workspace' : 'local-move';+ migrateLegacyBinding(workingDir, authority);+ // 快照回填 / 跟随: 只在目录或授权来源变化时落盘, 常规复用不产生写。+ if (+ namespacedEntry !== null &&+ (namespacedEntry.workingDir === null ||+ !isSamePath(namespacedEntry.workingDir, workingDir) ||+ namespacedEntry.authority !== authority)+ ) {+ bindings.set(connectionId, payload.externalKey, bound, workingDir, authority);+ }+ if (movedNow) {+ log.info(+ `hook session ${bound} followed a desktop-side move to ${workingDir} (outside the workspace map)`,+ );+ }return {run: {sessionId: bound,isNew: false,- workingDir: info.workingDir as string,+ workingDir,agentKind,model,effort,@@ -643,10 +737,20 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {attachments: payload.attachments,origin,},+ // 只在"这次刚发现被移动"时说明一次; 之后的消息静默沿用该授权+ ...(movedNow ? { notice: NOTICE_SESSION_MOVED } : {}),};}bindings.remove(connectionId, payload.externalKey);if (legacyNamespace) bindings.remove(legacyNamespace, payload.externalKey);+ // 旧绑定作废后下面会新建会话 —— 渠道侧只会看到"换了个会话"却无从得知+ // 原因, 因此带一条说明随本次 turn.end 回去(见 execute)。+ recreatedNotice = info?.usable ? NOTICE_SESSION_RECREATED : NOTICE_SESSION_GONE;+ log.info(+ `hook binding for ${payload.externalKey} dropped: session ${bound} ${+ info?.usable ? 'left the workspace map' : 'is gone or archived'+ }`,+ );}// 新建会话: 默认为它预建独立 git worktree —— 每个 thread/会话一个隔离@@ -686,7 +790,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {if (prep.ok) void prep.cleanup().catch(() => undefined);}}- bindings.set(connectionId, payload.externalKey, sessionId);+ // 新建会话跑在别名目录(或对话根)里, 授权随映射走+ bindings.set(connectionId, payload.externalKey, sessionId, runDir, 'workspace');// 标题带 provider 名: externalKey 约定为 `<providerId>:<渠道内标识>`,// 取前缀作 provider 名(如 team-slack), 比连接名(desktop 侧命名)更能// 说明"这条会话是谁驱动的"; 无前缀(非常规 key)时回退连接名@@ -716,6 +821,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {attachments: payload.attachments,origin,},+ ...(recreatedNotice ? { notice: recreatedNotice } : {}),};}@@ -773,6 +879,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {externalKey: payload.externalKey,run: { ...resolved.run, ...(source ? { source } : {}) },accountGeneration: admittedGeneration,+ ...(resolved.notice ? { notice: resolved.notice } : {}),};const sessionId = resolved.run.sessionId;const queue = queues.get(sessionId) ?? [];