Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 失效 hook 任务自动创建新任务 (#1863)
Dash580f127bb646
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.tsindex a6c5e54603..3d6b230c12 100644--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts@@ -34,6 +34,7 @@ import type { HookConnectionConfig } from '../store';const noopLog = { info: () => {}, warn: () => {} };const WS_DIR = path.resolve('/repos/xdmaker');+const DIALOGUE_ROOT = path.resolve('/userdata/dialogues');const CONFIG: HookConnectionConfig = {id: 'conn-1',@@ -44,6 +45,21 @@ const CONFIG: HookConnectionConfig = {createdAt: 0,};+function dialogueDep() {+ const allocated: string[] = [];+ return {+ allocated,+ dep: {+ rootDir: () => DIALOGUE_ROOT,+ allocateDir: async (sessionId: string) => {+ const dir = path.join(DIALOGUE_ROOT, '2026-07-07', sessionId);+ allocated.push(dir);+ return dir;+ },+ },+ };+}+/** 内存 binding(与文件实现同语义: 只存 externalKey -> sessionId)。 */function memoryBindings(): HookBindingStore {const map = new Map<string, string>();@@ -83,8 +99,7 @@ function memoryTerminalLedger(): HookRequestLedger & { records: HookTerminalReco},markSent(connectionId, requestId) {const record = records.findLast(- (candidate) =>- candidate.connectionId === connectionId && candidate.requestId === requestId,+ (candidate) => candidate.connectionId === connectionId && candidate.requestId === requestId,);if (!record) return false;record.delivery = 'sent';@@ -163,6 +178,7 @@ async function tick(times = 10): Promise<void> {}function makeDispatcher(overrides?: {+ getConnection?: HookDispatcherDeps['getConnection'];runner?: HookSessionRunner;bindings?: HookBindingStore;terminalLedger?: HookRequestLedger;@@ -181,7 +197,9 @@ function makeDispatcher(overrides?: {const fr = fakeRunner();const runner = overrides?.runner ?? fr.runner;const d = createHookDispatcher({- getConnection: () => (overrides?.config === undefined ? CONFIG : overrides.config),+ getConnection:+ overrides?.getConnection ??+ (() => (overrides?.config === undefined ? CONFIG : overrides.config)),bindings,terminalLedger: overrides?.terminalLedger,runner,@@ -1109,12 +1127,11 @@ describe('dispatcher 核心语义', () => {});});- it('接管: session 存在且在白名单内 -> 复用并重绑; 不存在/越界分别拒绝', async () => {+ it('接管: 可用 session 在白名单内则复用并重绑, 越界仍拒绝', async () => {const fr = fakeRunner({sessions: {'sess-in': { workingDir: path.join(WS_DIR, 'sub'), usable: true },'sess-out': { workingDir: path.resolve('/private/dir'), usable: true },- 'sess-dead': { workingDir: WS_DIR, usable: false },},});const bindings = memoryBindings();@@ -1137,21 +1154,461 @@ describe('dispatcher 核心语义', () => {result: 'rejected',reason: 'workspace_not_allowed',});+ });++ it('接管白名单按 inspect 完成后的当前映射判定', async () => {+ let currentConfig: HookConnectionConfig = CONFIG;+ const fr = fakeRunner({+ sessions: {+ 'sess-in': { workingDir: path.join(WS_DIR, 'sub'), usable: true },+ },+ });+ const runner: HookSessionRunner = {+ ...fr.runner,+ inspect: async (id) => {+ const info = await fr.runner.inspect(id);+ currentConfig = {+ ...CONFIG,+ workspaces: { moved: path.resolve('/repos/moved') },+ };+ return info;+ },+ };+ const { d } = makeDispatcher({ runner, getConnection: () => currentConfig });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'sess-in', workspace: null }), c.send);+ await tick();+ expect(c.last('task.ack')?.payload).toMatchObject({+ result: 'rejected',+ reason: 'workspace_not_allowed',+ });+ });++ it('连续携带同一失效 sessionId 时复用第一次替换出的 session 并排队', async () => {+ const dd = dialogueDep();+ const fr = fakeRunner();+ const externalKey = 'team-slack:C1:repeat-stale';+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'stale-1', externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();+ const firstSessionId = fr.calls[0]?.sessionId;+ expect(firstSessionId).toBeTruthy();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'stale-2', externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();++ expect(fr.calls).toHaveLength(1);+ expect(c.ofType('task.ack').map((message) => message.payload)).toEqual([+ expect.objectContaining({+ requestId: 'stale-1',+ result: 'accepted',+ sessionId: firstSessionId,+ }),+ expect.objectContaining({+ requestId: 'stale-2',+ result: 'queued',+ sessionId: firstSessionId,+ }),+ ]);++ fr.finish();+ await tick();+ expect(fr.calls).toHaveLength(2);+ expect(fr.calls[1]?.sessionId).toBe(firstSessionId);+ fr.finish();+ });++ it('首轮 replacement 未落库时显式带回 ACK sessionId: 复用同一任务并排队', async () => {+ const dd = dialogueDep();+ const fr = fakeRunner();+ const externalKey = 'team-slack:C1:ack-replacement';+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'stale-first', externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();+ const replacementSessionId = c.last('task.ack')?.payload.sessionId;+ expect(replacementSessionId).toEqual(expect.any(String));+ expect(fr.calls).toHaveLength(1);++ // server 已接受首条 ACK,随后把 replacement id 当作显式目标带回;首轮仍在+ // agent.startSession、尚未落库,所以 inspect 会返回 null。+ d.handleDispatch(+ 'conn-1',+ dispatch({+ requestId: 'replacement-follow-up',+ externalKey,+ sessionId: replacementSessionId,+ workspace: null,+ }),+ c.send,+ );+ await tick();++ expect(fr.calls).toHaveLength(1);+ expect(c.last('task.ack')?.payload).toMatchObject({+ requestId: 'replacement-follow-up',+ result: 'queued',+ sessionId: replacementSessionId,+ });++ fr.finish({ finalText: 'first done' });+ await tick();+ expect(fr.calls).toHaveLength(2);+ expect(fr.calls[1]?.sessionId).toBe(replacementSessionId);+ fr.finish({ finalText: 'follow-up done' });+ });++ it('首轮 replacement 未落库但目录已撤权: 显式带回 ACK sessionId 仍拒绝', async () => {+ const config: HookConnectionConfig = { ...CONFIG, workspaces: { xdmaker: WS_DIR } };+ const bindings = memoryBindings();+ const fr = fakeRunner();+ const externalKey = 'team-slack:C1:ack-replacement-revoked';+ const { d } = makeDispatcher({ runner: fr.runner, bindings, config });+ const c = collector();d.handleDispatch('conn-1',- dispatch({ requestId: 'r3', sessionId: 'ghost', workspace: null }),+ dispatch({ requestId: 'stale-first', externalKey, sessionId: 'ghost' }),c.send,);await tick();+ const replacementSessionId = c.last('task.ack')?.payload.sessionId;+ expect(replacementSessionId).toEqual(expect.any(String));+ expect(fr.calls).toHaveLength(1);++ config.workspaces = {};+ d.handleDispatch(+ 'conn-1',+ dispatch({+ requestId: 'replacement-revoked',+ externalKey,+ sessionId: replacementSessionId,+ workspace: null,+ }),+ c.send,+ );+ await tick();+expect(c.last('task.ack')?.payload).toMatchObject({+ requestId: 'replacement-revoked',result: 'rejected',- reason: 'session_not_found',+ reason: 'workspace_not_allowed',+ });+ expect(fr.calls).toHaveLength(1);+ expect(bindings.get('conn-1', externalKey)).toBe(replacementSessionId);+ fr.finish();+ });++ it('首轮 replacement 已落库且不可投递: 显式带回 ACK sessionId 时重新创建任务', async () => {+ const dd = dialogueDep();+ const sessions: Record<string, { workingDir: string; usable: boolean }> = {};+ const fr = fakeRunner({ sessions });+ const externalKey = 'team-slack:C1:ack-replacement-unusable';+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'stale-first', externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();+ const replacementSessionId = c.last('task.ack')?.payload.sessionId;+ expect(replacementSessionId).toEqual(expect.any(String));+ sessions[replacementSessionId!] = {+ workingDir: path.join(DIALOGUE_ROOT, '2026-07-07', replacementSessionId!),+ usable: false,+ };++ d.handleDispatch(+ 'conn-1',+ dispatch({+ requestId: 'replacement-unusable',+ externalKey,+ sessionId: replacementSessionId,+ workspace: null,+ }),+ c.send,+ );+ await tick();++ expect(fr.calls).toHaveLength(2);+ expect(fr.calls[1]?.sessionId).not.toBe(replacementSessionId);+ expect(fr.calls[1]).toMatchObject({ isNew: true });+ expect(c.last('task.ack')?.payload).toMatchObject({+ requestId: 'replacement-unusable',+ result: 'accepted',+ sessionId: fr.calls[1]?.sessionId,+ });++ fr.finish();+ fr.finish();+ });++ it('显式接管检查失败时拒绝且保留原 binding, 不静默创建替代任务', async () => {+ const dd = dialogueDep();+ const bindings = memoryBindings();+ const externalKey = 'team-slack:C1:inspect-error';+ bindings.set('conn-1', externalKey, 'existing-binding');+ const fr = fakeRunner();+ const runner: HookSessionRunner = {+ ...fr.runner,+ inspect: async () => {+ throw new Error('database unavailable');+ },+ };+ const { d } = makeDispatcher({ runner, bindings, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'inspect-error', externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();++ expect(c.last('task.ack')?.payload).toMatchObject({+ requestId: 'inspect-error',+ result: 'rejected',+ reason: 'invalid',});+ expect(bindings.get('conn-1', externalKey)).toBe('existing-binding');+ expect(fr.calls).toHaveLength(0);+ });++ it('同一消息线切换到另一个失效 sessionId 时创建新的替代 session', async () => {+ const dd = dialogueDep();+ const fr = fakeRunner();+ const externalKey = 'team-slack:C1:different-stale';+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'conn-1',+ dispatch({ requestId: 'stale-a', externalKey, sessionId: 'ghost-a', workspace: null }),+ c.send,+ );+ await tick();+ const firstSessionId = fr.calls[0]?.sessionId;+ expect(firstSessionId).toBeTruthy();d.handleDispatch('conn-1',- dispatch({ requestId: 'r4', sessionId: 'sess-dead', workspace: null }),+ dispatch({ requestId: 'stale-b', externalKey, sessionId: 'ghost-b', workspace: null }),+ c.send,+ );+ await tick();++ expect(fr.calls).toHaveLength(2);+ const secondSessionId = fr.calls[1]?.sessionId;+ expect(secondSessionId).toBeTruthy();+ expect(secondSessionId).not.toBe(firstSessionId);+ expect(c.ofType('task.ack').map((message) => message.payload)).toEqual([+ expect.objectContaining({+ requestId: 'stale-a',+ result: 'accepted',+ sessionId: firstSessionId,+ }),+ expect.objectContaining({+ requestId: 'stale-b',+ result: 'accepted',+ sessionId: secondSessionId,+ }),+ ]);++ fr.finish();+ fr.finish();+ });++ it('显式目标不存在且无可用提示时静默新建 chat,并替换当前及旧版 binding', async () => {+ const dd = dialogueDep();+ const bindings = memoryBindings();+ const externalKey = 'team-slack:C1:fresh';+ bindings.set('slack:account-one:slack', externalKey, 'unrelated-current');+ bindings.set('slack', externalKey, 'unrelated-legacy');+ const fr = fakeRunner();+ const { d } = makeDispatcher({ runner: fr.runner, bindings, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch(+ 'slack:account-one:slack',+ dispatch({ externalKey, sessionId: 'ghost', workspace: null }),+ c.send,+ );+ await tick();+ const ack = c.last('task.ack')!.payload;+ expect(ack.result).toBe('accepted');+ expect(ack.sessionId).not.toBe('ghost');+ expect(ack.sessionId).not.toBe('unrelated-current');+ expect(bindings.get('slack:account-one:slack', externalKey)).toBe(ack.sessionId);+ expect(bindings.get('slack', externalKey)).toBeNull();+ expect(fr.calls[0]).toMatchObject({+ sessionId: ack.sessionId,+ isNew: true,+ workspaceKind: 'dialogue',+ workspaceAlias: 'chat',+ });+ expect(dd.allocated).toEqual([fr.calls[0].workingDir]);++ fr.finish({ finalText: 'fresh result' });+ await tick();+ expect(c.last('turn.end')?.payload.finalText).toBe('fresh result');+ });++ it('已归档项目任务只沿旧路径推断工作区,并从映射根创建新 worktree', async () => {+ const nestedRoot = path.join(WS_DIR, 'nested-project');+ const staleWorktree = path.join(nestedRoot, '.xdt-worktrees', 'archived-session');+ const freshWorktree = path.join(nestedRoot, '.xdt-worktrees', 'fresh-session');+ const config = {+ ...CONFIG,+ workspaces: { broad: WS_DIR, nested: nestedRoot },+ };+ const fr = fakeRunner({+ sessions: {+ 'sess-dead': { workingDir: staleWorktree, usable: false },+ },+ });+ const prepareWorktree = vi.fn(async (dir: string): Promise<PrepareWorktreeResult> => ({+ ok: true,+ sessionId: 'fresh-session',+ path: path.join(dir, '.xdt-worktrees', 'fresh-session'),+ cleanup: async () => {},+ }));+ const { d } = makeDispatcher({ runner: fr.runner, config, prepareWorktree });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'sess-dead', workspace: null }), c.send);+ await tick();+ expect(prepareWorktree).toHaveBeenCalledWith(nestedRoot);+ expect(c.last('task.ack')?.payload).toMatchObject({+ result: 'accepted',+ sessionId: 'fresh-session',+ });+ expect(fr.calls[0]).toMatchObject({+ isNew: true,+ workingDir: freshWorktree,+ workspaceAlias: 'nested',+ });+ expect(fr.calls[0].workingDir).not.toBe(staleWorktree);+ fr.finish();+ });++ it('已归档 dialogue 任务分配新的对话目录', async () => {+ const dd = dialogueDep();+ const staleDir = path.join(DIALOGUE_ROOT, '2026-07-01', 'sess-dead');+ const fr = fakeRunner({+ sessions: {+ 'sess-dead': { workingDir: staleDir, usable: false },+ },+ });+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'sess-dead', workspace: 'xdmaker' }), c.send);+ await tick();+ expect(c.last('task.ack')?.payload.result).toBe('accepted');+ expect(fr.calls[0]).toMatchObject({+ isNew: true,+ workspaceKind: 'dialogue',+ workspaceAlias: 'chat',+ });+ expect(fr.calls[0].workingDir).not.toBe(staleDir);+ expect(dd.allocated).toEqual([fr.calls[0].workingDir]);+ fr.finish();+ });++ it('显式目标不存在时可使用仍有效的 workspace 提示新建任务', async () => {+ const fr = fakeRunner();+ const { d } = makeDispatcher({ runner: fr.runner });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'ghost', workspace: 'xdmaker' }), c.send);+ await tick();+ expect(c.last('task.ack')?.payload.result).toBe('accepted');+ expect(fr.calls[0]).toMatchObject({+ isNew: true,+ workingDir: WS_DIR,+ workspaceAlias: 'xdmaker',+ });+ fr.finish();+ });++ it('显式目标不存在且 workspace 提示无效时安全回退 chat', async () => {+ const dd = dialogueDep();+ const fr = fakeRunner();+ const { d } = makeDispatcher({ runner: fr.runner, dialogue: dd.dep });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'ghost', workspace: 'nope' }), c.send);+ await tick();+ expect(c.last('task.ack')?.payload.result).toBe('accepted');+ expect(fr.calls[0]).toMatchObject({+ isNew: true,+ workspaceKind: 'dialogue',+ workspaceAlias: 'chat',+ });+ expect(isPathWithin(DIALOGUE_ROOT, fr.calls[0].workingDir)).toBe(true);+ fr.finish();+ });++ it('不可用目标在映射外时只回退受管 chat,绝不运行旧路径', async () => {+ const dd = dialogueDep();+ const staleDir = path.resolve('/private/archived-worktree');+ const fr = fakeRunner({+ sessions: {+ 'sess-dead': { workingDir: staleDir, usable: false },+ },+ });+ const prepareWorktree = vi.fn();+ const { d } = makeDispatcher({+ runner: fr.runner,+ dialogue: dd.dep,+ prepareWorktree,+ });+ const c = collector();++ d.handleDispatch('conn-1', dispatch({ sessionId: 'sess-dead', workspace: 'nope' }), c.send);+ await tick();+ expect(c.last('task.ack')?.payload.result).toBe('accepted');+ expect(fr.calls[0]).toMatchObject({+ isNew: true,+ workspaceKind: 'dialogue',+ workspaceAlias: 'chat',+ });+ expect(fr.calls[0].workingDir).not.toBe(staleDir);+ expect(isPathWithin(DIALOGUE_ROOT, fr.calls[0].workingDir)).toBe(true);+ expect(prepareWorktree).not.toHaveBeenCalled();+ fr.finish();+ });++ it('旧宿主没有 dialogue 且无安全落点时保留 session_not_found 与原 binding', async () => {+ const bindings = memoryBindings();+ const externalKey = 'team-slack:C1:legacy-host';+ bindings.set('slack:account-one:slack', externalKey, 'unrelated-current');+ bindings.set('slack', externalKey, 'unrelated-legacy');+ const fr = fakeRunner();+ const { d } = makeDispatcher({ runner: fr.runner, bindings });+ const c = collector();++ d.handleDispatch(+ 'slack:account-one:slack',+ dispatch({ externalKey, sessionId: 'ghost', workspace: null }),c.send,);await tick();@@ -1159,6 +1616,8 @@ describe('dispatcher 核心语义', () => {result: 'rejected',reason: 'session_not_found',});+ expect(bindings.get('slack:account-one:slack', externalKey)).toBe('unrelated-current');+ expect(bindings.get('slack', externalKey)).toBe('unrelated-legacy');});it('busy 排队: 第二条 queued(位置0), 第一条收口后自动 drain, FIFO', async () => {@@ -1348,11 +1807,7 @@ describe('dispatcher 核心语义', () => {const { d } = makeDispatcher({ runner: fr.runner, terminalLedger });const c = collector();- d.handleDispatch(- 'conn-1',- dispatch({ requestId: 'pending-replay-fallback' }),- c.send,- );+ d.handleDispatch('conn-1', dispatch({ requestId: 'pending-replay-fallback' }), c.send);await tick();expect(fr.calls).toHaveLength(0);@@ -2546,22 +3001,6 @@ describe('interaction.decision 路由', () => {});describe('内置「对话」伪目录(chat 保留别名)', () => {- const DIALOGUE_ROOT = path.resolve('/userdata/dialogues');- function dialogueDep() {- const allocated: string[] = [];- return {- allocated,- dep: {- rootDir: () => DIALOGUE_ROOT,- allocateDir: async (sessionId: string) => {- const dir = path.join(DIALOGUE_ROOT, '2026-07-07', sessionId);- allocated.push(dir);- return dir;- },- },- };- }-it('chat 新建: 分配对话目录、不做 worktree、workspaceKind=dialogue、ack accepted', async () => {const dd = dialogueDep();const prepareWorktree = vi.fn();diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex 670ecb2c96..9278fdb7ae 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -110,6 +110,7 @@ vi.mock('../../localDb/ipc/messages.js', () => ({}));vi.mock('../../localDb/ipc/sessions.js', () => ({getSessionRowSnapshot: vi.fn(async () => null),+ getSessionRowSnapshotStrict: vi.fn(async () => null),setSessionProviderIdInDb: h.setSessionProviderIdInDb,setSessionSourceInDb: h.setSessionSourceInDb,setWorktreePathInDb: vi.fn(async () => undefined),@@ -373,6 +374,21 @@ beforeEach(() => {});describe('hook session 精确接管边界', () => {+ it('inspect 的数据库读取失败向上抛出, 不伪装成不存在', async () => {+ const { getSessionRowSnapshotStrict } = await import('../../localDb/ipc/sessions.js');+ vi.mocked(getSessionRowSnapshotStrict).mockRejectedValueOnce(new Error('database unavailable'));+ const runner = createMakerHookSessionRunner({ log });++ await expect(runner.inspect('session-under-test')).rejects.toThrow('database unavailable');+ });++ it('inspect 的 maker metadata 读取失败向上抛出, 不伪装成不存在', async () => {+ fakeMaker.getSessionMeta.mockRejectedValueOnce(new Error('metadata unavailable'));+ const runner = createMakerHookSessionRunner({ log });++ await expect(runner.inspect('session-under-test')).rejects.toThrow('metadata unavailable');+ });+it('拒绝接管 SSH 远程会话和内部 worker 会话', async () => {const { getSessionRowSnapshot } = await import('../../localDb/ipc/sessions.js');vi.mocked(getSessionRowSnapshot)diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex af7f8e77f6..e6c3b78204 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -8,8 +8,9 @@* 职责链(对应协议语义):* 1. 幂等: (connectionId, requestId) 去重 —— 重投只回放上次 ack, 不重跑;* 2. 会话定位:- * - 带 sessionId(接管): session 必须存在且其工作目录落在本连接注册的+ * - 带 sessionId(接管): 可用 session 的工作目录必须落在本连接注册的* 别名路径内(白名单不因接管放松), 通过后把 externalKey 重绑到它;+ * session 已失效时从受管目录静默新建任务并重绑;* - 不带(默认): 别名解析(映射即白名单)-> binding 查 externalKey ->* 复用或新建并落绑定。复用与否**每条消息现场重算**, 唯一依据是会话* 当前的工作目录是否仍落在工作目录映射(或内置对话根)内 —— 映射是@@ -68,8 +69,10 @@ export interface HookSessionRunner {/** 目标 session 是否正在跑 turn。 */isBusy(sessionId: string): boolean;/**- * 会话现状: null = 不存在; usable=false = 已归档/删除(不可投递);- * workingDir 用于接管/复用时的白名单校验。+ * 会话现状: null = 不存在; usable=false = 不可投递(已归档/删除、SSH remote、+ * Orca worker 等);+ * workingDir 用于接管/复用时的白名单校验。检查失败会 reject, 上层必须+ * fail closed 并保留既有 binding, 不能把暂时读不到当成失效任务。*/inspect(sessionId: string): Promise<{ workingDir: string | null; usable: boolean } | null>;/** 跑一个完整 turn, 收口(done / terminal error)后返回。 */@@ -646,6 +649,16 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {* 收口(run 返回时 session 必已建好)。因此表的规模 ≤ 并发新建数, 不会泄漏。*/const awaitingPersist = new Map<string, string>();+ /**+ * 当前 externalKey 最近一次失效显式接管的目标与 replacement。显式 stale 请求+ * 必须跳过进场时的无关旧 binding, 但同一消息线随后再次携带同一个 stale id+ * 时要认出刚创建的 replacement;换了 stale id 则必须重新创建任务。+ * 关联随 binding 被替换或归档而删除,生命周期不超过当前 binding。+ */+ const staleTakeoverReplacements = new Map<+ string,+ { staleSessionId: string; replacementSessionId: string }+ >();/** 每 session 的 FIFO 等待队列。 */const queues = new Map<string, PendingTask[]>();/** connectionId + requestId -> 正在执行它的 session(cancel 定位与归属校验用, 收口即清)。 */@@ -804,6 +817,10 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {return `${connectionId} ${requestId}`;}+ function bindingKey(connectionId: string, externalKey: string): string {+ return `${connectionId}\u0000${externalKey}`;+ }+function persistTerminalRecord(record: HookTerminalRecord): boolean {if (!terminalLedger) return false;try {@@ -1461,9 +1478,6 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {connectionName: config.name,externalKey: payload.externalKey,};- const whitelistDirs = Object.values(config.workspaces);- const inWhitelist = (dir: string | null): boolean =>- dir !== null && whitelistDirs.some((base) => isPathWithin(base, dir));/*** 同上, 但每次都重读连接配置 —— 撤权判定必须用**此刻**的映射: `config` 是* 消息进来那一刻的快照, 而下面要 await `runner.inspect()`。用快照判定的话,@@ -1478,68 +1492,161 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {/** app 托管对话目录(dialogues 根)内的路径 —— chat 伪目录会话的白名单等价物。 */const inDialogueRoot = (dir: string | null): boolean =>dir !== null && dialogue !== undefined && isPathWithin(dialogue.rootDir(), dir);- // 保留别名「对话」: 不查 config.workspaces, 解析成 app 托管对话目录- const isChat = payload.workspace === HOOK_CHAT_WORKSPACE_ALIAS && dialogue !== undefined;+ // 显式接管的目标失效时会从旧目录 / 本次别名提示里挑一个安全落点, 然后+ // 复用下方的新建路径。普通派发仍原样使用 payload.workspace。+ let effectiveWorkspace = payload.workspace;+ let effectiveWorkspaces = config.workspaces;+ let forceNew = false;/** 旧绑定作废、本次不得不新建会话时, 随 turn.end 回给渠道的说明。 */let recreatedNotice: string | null = null;const laneKind = deriveLaneKind(payload.externalKey);+ const laneKey = bindingKey(connectionId, payload.externalKey);+ const namespacedBound = bindings.get(connectionId, payload.externalKey);+ // v1 stored every mapping under the literal "slack" namespace. A new+ // 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;// 接管路径: server 显式指定已有 session(对话会话同样可接管)if (payload.sessionId !== null) {const info = await runner.inspect(payload.sessionId);if (!isCurrentGeneration(generation)) return { reject: 'disabled' };- if (!info || !info.usable) return { reject: 'session_not_found' };- if (!inWhitelist(info.workingDir) && !inDialogueRoot(info.workingDir)) {- return { reject: 'workspace_not_allowed' };+ if (info !== null) awaitingPersist.delete(payload.sessionId);+ /**+ * 首次失效接管的 ACK 会把 replacement sessionId 回给 server。若 server 在+ * 首轮落库前就把这个新 id 显式带回来, inspect 仍会查不到;它不是第二个+ * stale 目标, 而是当前消息线刚创建、正在执行的 replacement。只在当前+ * namespaced binding + awaitingPersist + running/queued 三者同时命中、且+ * inspect 确实还查不到时复用,并仍用当前映射重验目录,避免把落库窗口+ * 变成撤权或 usable=false 的旁路。+ */+ const pendingDir = awaitingPersist.get(payload.sessionId) ?? null;+ if (+ info === null &&+ payload.sessionId === namespacedBound &&+ pendingDir !== null &&+ (running.has(payload.sessionId) || (queues.get(payload.sessionId)?.length ?? 0) > 0)+ ) {+ if (!inWhitelistNow(pendingDir) && !inDialogueRoot(pendingDir)) {+ return { reject: 'workspace_not_allowed' };+ }+ return {+ run: {+ sessionId: payload.sessionId,+ isNew: false,+ laneKind,+ workingDir: pendingDir,+ agentKind,+ model,+ effort,+ permissionMode,+ title: null,+ prompt: payload.prompt,+ attachments: payload.attachments,+ origin,+ },+ };}- // 接管路径刚校验过白名单, 授权来源恒为 workspace(远端不能凭接管把会话- // 带出映射 —— 越界的 sessionId 在上面就被 workspace_not_allowed 打回)- bindings.set(connectionId, payload.externalKey, payload.sessionId);- return {- run: {- sessionId: payload.sessionId,- isNew: false,- laneKind,- workingDir: info.workingDir as string,- agentKind,- model,- effort,- permissionMode,- title: null,- prompt: payload.prompt,- attachments: payload.attachments,- origin,- },- };+ if (info?.usable) {+ if (!inWhitelistNow(info.workingDir) && !inDialogueRoot(info.workingDir)) {+ return { reject: 'workspace_not_allowed' };+ }+ // 接管路径刚校验过白名单, 授权来源恒为 workspace(远端不能凭接管把会话+ // 带出映射 —— 越界的 sessionId 在上面就被 workspace_not_allowed 打回)+ staleTakeoverReplacements.delete(laneKey);+ bindings.set(connectionId, payload.externalKey, payload.sessionId);+ return {+ run: {+ sessionId: payload.sessionId,+ isNew: false,+ laneKind,+ workingDir: info.workingDir as string,+ agentKind,+ model,+ effort,+ permissionMode,+ title: null,+ prompt: payload.prompt,+ attachments: payload.attachments,+ origin,+ },+ };+ }++ // 目标不存在、被归档或不可投递: 用户已经明确发来一条新消息, 因而静默+ // 新建任务并重绑这条外部消息线。旧 workingDir 只能帮助找回逻辑工作区,+ // 绝不能直接拿来运行 —— 归档任务的专属 worktree 可能早已被删除。+ effectiveWorkspaces = getConnection(connectionId)?.workspaces ?? config.workspaces;+ const oldWorkingDir = info?.workingDir ?? null;+ const inferredWorkspace =+ oldWorkingDir === null+ ? null+ : (Object.entries(effectiveWorkspaces)+ .filter(([, root]) => isPathWithin(root, oldWorkingDir))+ .sort(+ ([, left], [, right]) => path.resolve(right).length - path.resolve(left).length,+ )[0]?.[0] ?? null);+ if (inDialogueRoot(oldWorkingDir)) {+ effectiveWorkspace = HOOK_CHAT_WORKSPACE_ALIAS;+ } else if (inferredWorkspace !== null) {+ effectiveWorkspace = inferredWorkspace;+ } else if (payload.workspace === HOOK_CHAT_WORKSPACE_ALIAS && dialogue !== undefined) {+ effectiveWorkspace = HOOK_CHAT_WORKSPACE_ALIAS;+ } else if (+ payload.workspace !== null &&+ Object.hasOwn(effectiveWorkspaces, payload.workspace)+ ) {+ effectiveWorkspace = payload.workspace;+ } else if (dialogue !== undefined) {+ effectiveWorkspace = HOOK_CHAT_WORKSPACE_ALIAS;+ } else {+ // 兼容未注入内置对话目录的旧宿主 / 单测: 没有任何可验证的安全落点时+ // 仍保留旧拒绝语义, 避免凭空选择一个工作目录。+ return { reject: 'session_not_found' };+ }+ forceNew = true;+ log.info(+ `hook takeover target ${payload.sessionId} is gone or archived; creating a fresh session in ${effectiveWorkspace}`,+ );}// 默认路径: 别名解析(映射即白名单); chat 伪目录不走映射, 目录建会话时分配+ // 保留别名「对话」: 不查 workspaces, 解析成 app 托管对话目录+ const isChat = effectiveWorkspace === HOOK_CHAT_WORKSPACE_ALIAS && dialogue !== undefined;const dir = isChat? undefined- : payload.workspace- ? Object.hasOwn(config.workspaces, payload.workspace)- ? config.workspaces[payload.workspace]+ : effectiveWorkspace+ ? Object.hasOwn(effectiveWorkspaces, effectiveWorkspace)+ ? effectiveWorkspaces[effectiveWorkspace]: undefined: undefined;if (!dir && !isChat) return { reject: 'unknown_workspace' };- // v1 stored every mapping under the literal "slack" namespace. A new- // 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): null;const bound = namespacedBound ?? legacyBound;+ const trackedReplacement = staleTakeoverReplacements.get(laneKey);+ const reusesTrackedReplacement =+ forceNew &&+ payload.sessionId !== null &&+ trackedReplacement?.staleSessionId === payload.sessionId &&+ trackedReplacement.replacementSessionId === bound;+ if (+ trackedReplacement !== undefined &&+ (trackedReplacement.replacementSessionId !== bound ||+ (forceNew && trackedReplacement.staleSessionId !== payload.sessionId))+ ) {+ staleTakeoverReplacements.delete(laneKey);+ }const migrateLegacyBinding = (): void => {if (!legacyBound || !legacyNamespace) return;bindings.set(connectionId, payload.externalKey, legacyBound);bindings.remove(legacyNamespace, payload.externalKey);};- if (bound) {+ if ((!forceNew || reusesTrackedReplacement) && bound) {const info = await runner.inspect(bound);if (!isCurrentGeneration(generation)) return { reject: 'disabled' };// 查得到 = 已落库, 此后一律走映射校验@@ -1637,7 +1744,9 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {if (legacyNamespace) bindings.remove(legacyNamespace, payload.externalKey);// 旧绑定作废后下面会新建会话 —— 渠道侧只会看到"换了个会话"却无从得知// 原因, 因此带一条说明随本次 turn.end 回去(见 execute)。- recreatedNotice = info?.usable ? NOTICE_SESSION_RECREATED : NOTICE_SESSION_GONE;+ if (!forceNew) {+ 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'@@ -1687,6 +1796,17 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {}// 新建会话跑在别名目录(或对话根)里, 是否还能复用每次现场按映射判定bindings.set(connectionId, payload.externalKey, sessionId);+ if (forceNew && payload.sessionId !== null) {+ staleTakeoverReplacements.set(laneKey, {+ staleSessionId: payload.sessionId,+ replacementSessionId: sessionId,+ });+ } else {+ staleTakeoverReplacements.delete(laneKey);+ }+ // 显式接管失效时 forceNew 已跳过旧 binding 复用;等新目录准备成功后才覆盖+ // 当前 binding 并清理旧版 namespace,避免分配失败 / 账号切换时无谓解绑。+ if (forceNew && legacyNamespace) bindings.remove(legacyNamespace, payload.externalKey);// 落库前的免检窗口从这里开始(见 awaitingPersist 声明处): 此刻这个 session// 必定建在映射内, inspect 还查不到它, 同 key 的后续消息要能认出它。记下它// 建在哪 —— 免检时要拿这个目录跟当时的映射再比一次。@@ -1714,7 +1834,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {effort,permissionMode,...(isChat ? { workspaceKind: 'dialogue' as const } : {}),- ...(payload.workspace ? { workspaceAlias: payload.workspace } : {}),+ ...(effectiveWorkspace ? { workspaceAlias: effectiveWorkspace } : {}),title: buildHookSessionTitle(providerName,titleText,@@ -1987,6 +2107,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// 不在这里清的话, 每次切账号都永久留下一条 sessionId + 完整工作目录路径// (PR #733 review 指出)。这些会话属于上一个账号, 新账号下本就不该免检。awaitingPersist.clear();+ staleTakeoverReplacements.clear();keyChains.clear();})();accountDeactivation = drain.finally(() => {@@ -2001,6 +2122,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {// 归档并发穿插 —— 归档排在其后, 能看到刚落下的绑定。serializeByKey(`${connectionId} ${externalKey}`, async () => {if (!isCurrentGeneration(admittedGeneration)) return;+ staleTakeoverReplacements.delete(bindingKey(connectionId, externalKey));/*** 这个会话此刻还归远端管吗 —— 归档同样要过工作目录映射这道边界。* 会话已被移出映射(或映射被改/删)时, 远端的 `/new` 不该还能归档它并@@ -2191,6 +2313,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {dropContinuation(sessionId, { silent: true, remember: false });}pendingReopens.clear();+ staleTakeoverReplacements.clear();serverFeatures.clear();sendFns.clear();pendingTurnEnds.clear();diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 8b8fb508c6..a8d39b7dd9 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -68,6 +68,7 @@ import { toDesktopSessionDispatchOutcome } from '../maker-host/send-outcome.js';import { createMessage } from '../localDb/ipc/messages.js';import {getSessionRowSnapshot,+ getSessionRowSnapshotStrict,setSessionProviderIdInDb,setSessionSourceInDb,setWorktreePathInDb,@@ -431,10 +432,8 @@ export function createMakerHookSessionRunner(deps: {async inspect(sessionId) {const [meta, row] = await Promise.all([- getMaker()- .getSessionMeta(sessionId)- .catch(() => null),- getSessionRowSnapshot(sessionId),+ getMaker().getSessionMeta(sessionId),+ getSessionRowSnapshotStrict(sessionId),]);if (!meta && !row) return null;const usable =