Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat: 派活可转述 pick 亲选目录,errand 会话能建进项目里

Lizi669b2e12b7b6
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
index 0e8d12f9e3..579cea7036 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
@@ -95,6 +95,10 @@ describe('载荷校验', () => {
{ ...RUN, title: 'x'.repeat(101) },
{ ...RUN, mode: 'submit' },
{ ...RUN, callId: '' },
+ { ...RUN, workingDir: '' },
+ { ...RUN, workingDir: ' ' },
+ { ...RUN, workingDir: 42 },
+ { ...RUN, workingDir: 'x'.repeat(1025) },
];
for (const payload of cases) {
expect(await slot.handleRequest('helper', payload)).toMatchObject({
@@ -123,6 +127,18 @@ describe('载荷校验', () => {
const req = runner.mock.calls[0][0] as { message: string };
expect(req.message).toBe('总结 README\n\n[结构化上下文 JSON]\n{"a":1}');
});
+
+ it('workingDir 原样透传给 runner(是否亲选目录由 runner 对台账把关)', async () => {
+ const { slot, runner } = makeSlot();
+ await slot.handleRequest('helper', { ...RUN, workingDir: '/proj/repo' });
+ expect(runner.mock.calls[0][0]).toMatchObject({ workingDir: '/proj/repo' });
+ });
+
+ it('不带 workingDir 时 runner 请求里没有该字段', async () => {
+ const { slot, runner } = makeSlot();
+ await slot.handleRequest('helper', RUN);
+ expect('workingDir' in (runner.mock.calls[0][0] as object)).toBe(false);
+ });
});
describe('频控', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pickGrantsStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pickGrantsStore.test.ts
new file mode 100644
index 0000000000..7fffe5bf68
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pickGrantsStore.test.ts
@@ -0,0 +1,46 @@
+/**
+ * pickGrantsStore.test.ts — 亲选目录台账的 normalize 单测。
+ * 存储真身经 createOverrideSettingsFile 落 userData,依赖 electron;这里
+ * 只测纯函数(坏形态清洗/归一化/去重/条数上限),记账与对账链路由
+ * pickSlot 与 ghostErrandRunner 的测试覆盖。
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('electron', () => ({ app: { getPath: () => '/tmp/never-used-here' } }));
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },
+}));
+
+const { __testing, GRANTS_PER_GHOST } = await import('../pickGrantsStore');
+
+describe('normalize(台账清洗)', () => {
+ it('路径统一归一化存取:尾斜杠去掉,同目录不重复', () => {
+ expect(
+ __testing.normalize({
+ grants: { g1: ['/proj/demo/', '/proj/demo', '/proj/other'] },
+ }),
+ ).toEqual({ grants: { g1: ['/proj/demo', '/proj/other'] } });
+ });
+
+ it('坏形态逐项丢弃:非字符串/空串/超长/整列表非数组', () => {
+ expect(
+ __testing.normalize({
+ grants: {
+ g1: ['', 42, 'x'.repeat(1025), '/ok'],
+ g2: 'not-a-list',
+ g3: [],
+ },
+ }),
+ ).toEqual({ grants: { g1: ['/ok'] } });
+ expect(__testing.normalize(null)).toEqual({ grants: {} });
+ expect(__testing.normalize({ grants: 7 })).toEqual({ grants: {} });
+ });
+
+ it('每插件最多保留 GRANTS_PER_GHOST 条(读入时截断)', () => {
+ const many = Array.from({ length: GRANTS_PER_GHOST + 3 }, (_, i) => `/proj/p${i}`);
+ const out = __testing.normalize({ grants: { g1: many } });
+ expect(out.grants.g1).toHaveLength(GRANTS_PER_GHOST);
+ expect(out.grants.g1[0]).toBe('/proj/p0');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
index 3dce24f9ae..ef85ad22c5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
@@ -127,6 +127,31 @@ describe('pickSlot · 授权 = 用户亲选', () => {
await slot.handleRequest('pick-ghost', { mode: 'directory', deposit: true }),
).toMatchObject({ ok: false, errorCode: 'INTERNAL' });
});
+
+ it('亲选成功记台账(recordPickedDir);取消不记', async () => {
+ const recordPickedDir = vi.fn();
+ const { slot } = makeSlot({ recordPickedDir });
+ await slot.handleRequest('pick-ghost', { mode: 'directory' });
+ expect(recordPickedDir).toHaveBeenCalledWith('pick-ghost', '/Users/me/projects');
+
+ const cancelled = makeSlot({
+ showDirectoryDialog: vi.fn(async () => null),
+ recordPickedDir,
+ });
+ recordPickedDir.mockClear();
+ await cancelled.slot.handleRequest('pick-ghost', { mode: 'directory' });
+ expect(recordPickedDir).not.toHaveBeenCalled();
+ });
+
+ it('票据签发失败也已记台账(用户确实亲选过,授权事实不随票据丢)', async () => {
+ const recordPickedDir = vi.fn();
+ const { slot } = makeSlot({
+ depositDir: () => ({ ok: false as const, message: '超过收集上限' }),
+ recordPickedDir,
+ });
+ await slot.handleRequest('pick-ghost', { mode: 'directory', deposit: true });
+ expect(recordPickedDir).toHaveBeenCalledWith('pick-ghost', '/Users/me/projects');
+ });
});
describe('pickSlot · 骚扰钳制', () => {
diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.ts
index 18e0f257c2..691efe322e 100644
--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts
@@ -8,7 +8,9 @@
* - 插件必须声明 `agent` 槽 + `agent.errand: true`(装入确认高风险单列);
* - 任务文本只进普通 user 消息,绝不进 system prompt;
* - errand 会话的 agent/模型/权限档/工作目录由用户配置(runner 侧解析;
- * 权限档默认 plan 只读,协议层就没有 bypassPermissions);
+ * 权限档默认 plan 只读,协议层就没有 bypassPermissions)。唯一例外:
+ * 用户没配工作目录时,插件可在请求里**转述**一个目录,runner 只认
+ * pick 台账里用户亲手选过的(pickGrantsStore),台账没有即明拒;
* - 每插件同时最多 1 单在途 + 相邻提交最小间隔(防刷);
* - 任务表在内存:主进程重启即丢,query 对丢失单统一回「查无此任务」,
* 插件按可重新提交处理(与 cindy 槽异步代办同语义)。
@@ -45,6 +47,11 @@ export interface GhostErrandRunRequest {
message: string;
/** 首次创建 errand 会话时的标题提示。 */
title?: string;
+ /**
+ * 插件转述的期望工作目录(仅形状校验;是否真是用户亲选目录由 runner
+ * 对 pick 台账把关——授权对账需要归一化,归一化实现在 runner 侧)。
+ */
+ workingDir?: string;
}
export interface GhostErrandRunHooks {
@@ -56,7 +63,15 @@ export type GhostErrandRunOutcome =
| { ok: true; sessionId: string; text: string; agentKind?: string; model?: string }
| {
ok: false;
- errorCode: 'HOST_NOT_READY' | 'BUSY' | 'SESSION_UNAVAILABLE' | 'TURN_FAILED' | 'TIMEOUT' | 'INTERNAL';
+ errorCode:
+ | 'HOST_NOT_READY'
+ | 'BUSY'
+ | 'SESSION_UNAVAILABLE'
+ | 'TURN_FAILED'
+ | 'TIMEOUT'
+ | 'INTERNAL'
+ /** 目前仅一种来源:转述的 workingDir 不在用户亲选台账里。 */
+ | 'INVALID_REQUEST';
message: string;
};
@@ -165,6 +180,14 @@ export class GhostErrandSlot {
if (payload.mode !== undefined && payload.mode !== 'wait') {
return fail('INVALID_REQUEST', "mode 只支持 'wait'(同步等待)或不传(异步受理 + query 轮询)");
}
+ if (
+ payload.workingDir !== undefined &&
+ (typeof payload.workingDir !== 'string' ||
+ payload.workingDir.trim().length === 0 ||
+ payload.workingDir.length > 1024)
+ ) {
+ return fail('INVALID_REQUEST', 'workingDir 必须是 1–1024 字符的绝对路径字符串,或不传');
+ }
if (
payload.callId !== undefined &&
(typeof payload.callId !== 'string' || payload.callId.length === 0 || payload.callId.length > MAX_CALL_ID_LEN)
@@ -228,6 +251,7 @@ export class GhostErrandSlot {
ghostVersion: ghost.manifest.version,
message,
...(typeof payload.title === 'string' ? { title: payload.title.trim() } : {}),
+ ...(typeof payload.workingDir === 'string' ? { workingDir: payload.workingDir } : {}),
},
{
onSession: (sessionId) => {
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 8936bccfb1..dd83ae5e63 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2176,6 +2176,7 @@ const r = await cindy.agent.errand({
task: '阅读工作目录下的 README 并总结要点(200 字以内)',
// context: { anything: '结构化上下文,主机 JSON 化后附在任务消息尾部' },
// title: '我的插件 · 代办', // 仅首次创建 errand 会话时用作标题
+ // workingDir: repoDir, // 可选:请求建在某目录(只认用户亲选过的,见下)
// mode: 'wait', // 同步等到完成(30 分钟顶);默认不传 = 异步
callId: msg.callId,
});
@@ -2196,6 +2197,11 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });
**只读**(不能改任何文件),目录缺省是插件专属文件夹。别假设你能写文件——
只读档下让 Agent"分析/回答"没问题,"修改"类任务要在文案里引导用户先放开
权限档;
+- 目录有一个受控例外:run 请求可带 \`workingDir\`(绝对路径)**转述**一个目录,
+ 让 errand 会话建在项目里(Agent 能看到代码)。这不是授权——主机只认用户
+ 此前在 pick 槽(§4.14)系统选目录窗口里**亲手选过**的目录(主机自己记的
+ 台账),别的路径一律 \`INVALID_REQUEST\`,此时应引导用户去你的设置页重新
+ 选一次目录;用户在「AI 代办」卡里配置了目录时,以用户配置优先、本字段忽略;
- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带
标记);完成结果保留 30 分钟,应用重启后查无此单(按可重新提交处理);
- \`errorCode:'BUSY'\` = 你已有一单在途,或用户恰好正在 errand 会话里说话;
@@ -2480,7 +2486,10 @@ if (picked.ok) {
- 未声明 node 槽的插件必须 \`deposit: true\`(没有票据你什么都拿不到,请求会被拒);
票据收集有上限(500 文件/单文件 50MB/总 256MB),超限会签发失败;
- \`path\` 只发给声明了 node 槽的插件:Node 侧本就有用户级本机权限,给路径不扩权,
- 价值是把"用户选了哪个目录"这一事实可信地交过去。
+ 价值是把"用户选了哪个目录"这一事实可信地交过去;
+- 用户每次亲选成功,主机自己也会记一笔「亲选目录台账」(每插件最近 8 条)——
+ 派活(§4.11.1)的 \`workingDir\` 转述只对台账里的目录放行。台账建立在真实
+ 点选上,你存在 /kv 里的路径不算数。
## 4.15 面板预览(preview 槽)
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 4596e08893..ae7be1dc32 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -143,6 +143,7 @@ import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';
import { readGhostErrandConfig, writeGhostErrandConfig } from './errandPrefsStore.js';
import { GhostNodeRuntimeBroker } from './nodeRuntimeBroker.js';
import { GhostPickSlot } from './pickSlot.js';
+import { recordGhostPickedDir } from './pickGrantsStore.js';
import { GhostPreviewSlot } from './previewSlot.js';
import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';
import type { GhostTrustRegistry } from './ghostSignature.js';
@@ -1581,6 +1582,8 @@ export function getGhostPickSlot(): GhostPickSlot {
// (与确认卡点允许同强度;dirDeposit 注释的授权语义包含本通道)。
depositDir: (ghostId, dirAbs) =>
getDirDepositVault().deposit({ ghostId, dirAbs, workdirAbs: null, userGranted: true }),
+ // 亲选事实进台账:errand 的 workingDir 转述据此对账(pickGrantsStore)。
+ recordPickedDir: recordGhostPickedDir,
log,
});
}
diff --git a/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts b/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts
new file mode 100644
index 0000000000..860c651bb4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts
@@ -0,0 +1,92 @@
+/**
+ * pickGrantsStore —— pick 槽「用户亲选目录」台账的持久化。
+ *
+ * File: <userData>/ghost-pick-grants.json
+ *
+ * 形态:{ grants: { <ghostId>: [归一化绝对路径, ...] } }(新选的排前面)。
+ *
+ * 为什么要台账:pick 槽把绝对路径交给插件后,主机自己不再记得"用户亲手
+ * 选过哪个目录"。而 errand 等能力允许插件在请求里**转述**一个目录时,必须
+ * 有一个宿主侧的可信事实来对账——插件沙箱里的任何值都不构成授权。台账里
+ * 的每一条都对应一次用户在系统选目录窗口里的亲手点选(与确认卡点允许同
+ * 强度),所以"转述的目录 ∈ 台账"才放行。
+ *
+ * 语义边界:
+ * - 只记 pick 槽成功交付的目录(取消/失败不记);
+ * - 路径统一走 normalizeWorkingDirForStorage 归一化后存取,比对永不受
+ * 尾斜杠/分隔符差异干扰;
+ * - 每插件保留最近 GRANTS_PER_GHOST 条(重选同目录只提位,不重复);
+ * - 抽离插件**不**清台账——与 errand 配置、dirDeposit"同插件永久生效"
+ * 同一哲学:用户亲选的事实不因重装而消失。
+ */
+
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+
+const log = desktopMakerLogger.child('pick-grants-store');
+
+/** 每插件保留的亲选目录条数(超出淘汰最旧;够覆盖"换过几次项目目录")。 */
+export const GRANTS_PER_GHOST = 8;
+/** 单条路径长度上限(与 errand 配置 workingDir 同口径)。 */
+const MAX_DIR_LEN = 1024;
+
+interface GhostPickGrants {
+ grants: Record<string, string[]>;
+}
+
+const DEFAULTS: GhostPickGrants = { grants: {} };
+
+function normalize(raw: unknown): GhostPickGrants {
+ if (!raw || typeof raw !== 'object') return { grants: {} };
+ const grantsRaw = (raw as { grants?: unknown }).grants;
+ const grants: GhostPickGrants['grants'] = {};
+ if (grantsRaw && typeof grantsRaw === 'object') {
+ for (const [ghostId, listRaw] of Object.entries(grantsRaw as Record<string, unknown>)) {
+ if (!Array.isArray(listRaw)) continue;
+ const list: string[] = [];
+ for (const item of listRaw) {
+ if (typeof item !== 'string' || item.length === 0 || item.length > MAX_DIR_LEN) continue;
+ const dir = normalizeWorkingDirForStorage(item);
+ if (dir && !list.includes(dir)) list.push(dir);
+ if (list.length >= GRANTS_PER_GHOST) break;
+ }
+ if (list.length > 0) grants[ghostId] = list;
+ }
+ }
+ return { grants };
+}
+
+const store = createOverrideSettingsFile<GhostPickGrants>({
+ filePath: () => ownerScopedUserDataPath('ghost-pick-grants.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'ghost-pick-grants',
+});
+
+/** 记一笔亲选目录(pick 槽成功交付时调用;重选同目录提位到最前)。 */
+export function recordGhostPickedDir(ghostId: string, dirAbs: string): void {
+ const dir = normalizeWorkingDirForStorage(dirAbs);
+ if (!dir || dir.length > MAX_DIR_LEN) return;
+ store.invalidateIfChanged();
+ const grants = { ...store.read().grants };
+ const list = [dir, ...(grants[ghostId] ?? []).filter((d) => d !== dir)].slice(
+ 0,
+ GRANTS_PER_GHOST,
+ );
+ grants[ghostId] = list;
+ store.writePatch({ grants });
+ log.info('ghost picked dir recorded', { ghostId, dirs: list.length });
+}
+
+/** 这个目录是不是该插件的用户亲选过的(入参先归一化再比对)。 */
+export function isGhostPickedDir(ghostId: string, dirAbs: string): boolean {
+ const dir = normalizeWorkingDirForStorage(dirAbs);
+ if (!dir) return false;
+ store.invalidateIfChanged();
+ return (store.read().grants[ghostId] ?? []).includes(dir);
+}
+
+export const __testing = { normalize };
diff --git a/apps/desktop/src/main/cindy-brain/pickSlot.ts b/apps/desktop/src/main/cindy-brain/pickSlot.ts
index f3514fe363..6bead2e807 100644
--- a/apps/desktop/src/main/cindy-brain/pickSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/pickSlot.ts
@@ -45,6 +45,11 @@ export interface PickSlotDeps {
ghostId: string,
dirAbs: string,
): { ok: true; receipt: DirDepositReceiptShape } | { ok: false; message: string };
+ /**
+ * 亲选目录进台账(pickGrantsStore):errand 等能力据此对账"插件转述的
+ * 目录确实是用户亲手选过的"。只在成功交付(非取消)时调用。
+ */
+ recordPickedDir?(ghostId: string, dirAbs: string): void;
now?(): number;
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
@@ -129,6 +134,9 @@ export class GhostPickSlot {
if (picked === null) {
return fail('CANCELLED', '用户取消了选择');
}
+ // 用户已亲手选中:先记台账再分档发结果(票据签发失败也不该丢掉这次
+ // 授权事实——用户确实选了)。
+ this.deps.recordPickedDir?.(ghostId, picked);
const result: Extract<GhostPipePickResult, { ok: true }> = {
ok: true,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
index b6293569a4..4436acec0c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
@@ -71,6 +71,7 @@ function makeDeps(overrides: Partial<GhostErrandRunnerDeps> = {}): {
getGhostName: () => '帮手',
getDraftDefaults: () => ({}),
normalizeWorkingDir: (dir) => dir.replace(/\/+$/, ''),
+ isUserPickedDir: () => false,
isSessionBusy: () => false,
dispatch: vi.fn(async () => ({ ok: true as const, wakeKind: 'resumed' as const })),
getObservableSession: (id) => ensureEmitter(id).session,
@@ -166,6 +167,73 @@ describe('专属会话建/复用', () => {
});
});
+describe('插件转述目录(request.workingDir)', () => {
+ it('台账里的目录:建会话带上该目录;归一化后的同目录会话可复用', async () => {
+ const createSession = vi.fn(async () => 'sess-repo');
+ const { deps, emitters } = makeDeps({
+ createSession,
+ isUserPickedDir: (ghostId, dir) => ghostId === 'helper' && dir === '/proj/repo',
+ });
+ const runner = createGhostErrandRunner(deps);
+ const p = runner({ ...REQUEST, workingDir: '/proj/repo/' });
+ await vi.waitFor(() => expect(emitters.has('sess-repo')).toBe(true));
+ emitters.get('sess-repo')!.emit(doneEvent());
+ await p;
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ workingDir: '/proj/repo' }),
+ );
+
+ // 第二单同目录:命中已有 project 间,不再新建。
+ const createAgain = vi.fn(async () => 'should-not-happen');
+ const second = makeDeps({
+ createSession: createAgain,
+ isUserPickedDir: () => true,
+ readSessionId: () => 'sess-repo',
+ getSessionRow: async () => ({
+ ...ACTIVE_ROW,
+ workspaceKind: 'project',
+ workingDir: '/proj/repo',
+ }),
+ });
+ const runner2 = createGhostErrandRunner(second.deps);
+ const p2 = runner2({ ...REQUEST, workingDir: '/proj/repo' });
+ await vi.waitFor(() => expect(second.emitters.has('sess-repo')).toBe(true));
+ second.emitters.get('sess-repo')!.emit(doneEvent());
+ await p2;
+ expect(createAgain).not.toHaveBeenCalled();
+ });
+
+ it('台账里没有的目录 → INVALID_REQUEST,不建会话不投递', async () => {
+ const createSession = vi.fn(async () => 'should-not-happen');
+ const dispatch = vi.fn(async () => ({ ok: true as const, wakeKind: 'resumed' as const }));
+ const { deps } = makeDeps({ createSession, dispatch, isUserPickedDir: () => false });
+ const runner = createGhostErrandRunner(deps);
+ const r = await runner({ ...REQUEST, workingDir: '/anywhere/else' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });
+ expect(createSession).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('用户在「AI 代办」卡配置了目录 → 用户配置优先,转述字段忽略(不查台账)', async () => {
+ const createSession = vi.fn(async () => 'sess-cfg');
+ const isUserPickedDir = vi.fn(() => false);
+ const { deps, emitters } = makeDeps({
+ readConfig: () => ({ workingDir: '/user/configured' }),
+ createSession,
+ isUserPickedDir,
+ });
+ const runner = createGhostErrandRunner(deps);
+ const p = runner({ ...REQUEST, workingDir: '/ghost/says' });
+ await vi.waitFor(() => expect(emitters.has('sess-cfg')).toBe(true));
+ emitters.get('sess-cfg')!.emit(doneEvent());
+ await p;
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ workingDir: '/user/configured' }),
+ );
+ expect(isUserPickedDir).not.toHaveBeenCalled();
+ });
+});
+
describe('忙检与投递', () => {
it('会话正忙 → BUSY,不投递', async () => {
const dispatch = vi.fn();
diff --git a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
index abe6d3806e..8c401bafd3 100644
--- a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
+++ b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
@@ -12,7 +12,9 @@
*
* 安全不变量(与 errandSlot 头注释同一契约):任务文本只进普通 user 消息;
* 权限档只认 plan/acceptEdits/auto(存储层与本层双重钳制,bypassPermissions
- * 在协议上不存在);errand 会话侧边栏可见,用户可旁观可随时停。
+ * 在协议上不存在);errand 会话侧边栏可见,用户可旁观可随时停;工作目录
+ * 用户配置优先,插件转述的目录只认 pick 亲选台账(isUserPickedDir),
+ * 台账没有即明拒——插件不能凭空指路。
*
* 全部依赖注入(规则 14):register.ts 只做接线,本模块可单测。
*/
@@ -76,6 +78,11 @@ export interface GhostErrandRunnerDeps {
* 比对,否则"带尾斜杠 vs 不带"会让复用判定永远失败、每单都建新会话。
*/
normalizeWorkingDir(dir: string): string | null;
+ /**
+ * 插件转述的目录是不是这个插件的用户在 pick 槽里亲手选过的
+ * (pickGrantsStore 台账;入参已经过 normalizeWorkingDir)。
+ */
+ isUserPickedDir(ghostId: string, normalizedDir: string): boolean;
isSessionBusy(sessionId: string): boolean;
/** 统一投递通路(sendToSessionInternal 的窄化面)。 */
dispatch(params: { targetSessionId: string; message: string }): Promise<
@@ -122,15 +129,16 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
row: GhostErrandSessionRow,
cfg: GhostErrandConfig,
permissionMode: GhostErrandPermissionMode,
- configuredDir: string | undefined,
+ effectiveDir: string | undefined,
): boolean => {
if (row.status !== 'active') return false;
if (cfg.agentKind && row.agentKind !== cfg.agentKind) return false;
if (row.permissionMode !== permissionMode) return false;
- // 用户配置了项目目录:目录不同(或旧间还是 dialogue)就换新间;
- // 用户清掉目录配置:旧的 project 间不再复用,回到专属 dialogue 间。
- if (configuredDir) {
- if (row.workspaceKind !== 'project' || row.workingDir !== configuredDir) return false;
+ // 这单要目录(用户配置或已对账的插件转述):目录不同(或旧间还是
+ // dialogue)就换新间;这单不要目录:旧的 project 间不再复用,回到
+ // 专属 dialogue 间。
+ if (effectiveDir) {
+ if (row.workspaceKind !== 'project' || row.workingDir !== effectiveDir) return false;
} else if (row.workspaceKind !== 'dialogue') {
return false;
}
@@ -144,12 +152,27 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
const configuredDir = cfg.workingDir
? (deps.normalizeWorkingDir(cfg.workingDir) ?? undefined)
: undefined;
+ // 目录取值:用户在「AI 代办」卡里的配置永远优先;没配置时才看插件在
+ // 请求里转述的目录,且只认 pick 台账里用户亲手选过的——插件不能凭空
+ // 指路,否则等于让它借 Agent 的手读任意文件夹。查不到时明拒,不静默
+ // 落回专属对话间:静默降级会建出一间看不到代码的会话,插件还以为成了。
+ let effectiveDir = configuredDir;
+ if (!effectiveDir && request.workingDir) {
+ const requested = deps.normalizeWorkingDir(request.workingDir) ?? undefined;
+ if (!requested || !deps.isUserPickedDir(request.ghostId, requested)) {
+ return failure(
+ 'INVALID_REQUEST',
+ '这个目录不在用户亲选记录里,不能把 errand 会话建在那里;请引导用户在插件设置里重新选一次该目录(经系统选目录窗口),或在插件详情页「AI 代办」卡里配置工作目录',
+ );
+ }
+ effectiveDir = requested;
+ }
// ── 确保专属 errand 会话 ─────────────────────────────────────────────
let sessionId = deps.readSessionId(request.ghostId);
if (sessionId) {
const row = await deps.getSessionRow(sessionId);
- if (!row || !sessionMatchesConfig(row, cfg, permissionMode, configuredDir)) {
+ if (!row || !sessionMatchesConfig(row, cfg, permissionMode, effectiveDir)) {
// 旧间不可用/配置已变:解除映射换新间(旧会话留在侧边栏,历史可查)。
deps.writeSessionId(request.ghostId, null);
sessionId = null;
@@ -175,7 +198,7 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
? { providerId: cfg.providerId ?? draft.providerId }
: {}),
permissionMode,
- ...(configuredDir ? { workingDir: configuredDir } : {}),
+ ...(effectiveDir ? { workingDir: effectiveDir } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 117bb24da8..96ff1980e2 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -573,6 +573,7 @@ import {
readGhostErrandSessionId,
writeGhostErrandSessionId,
} from '../cindy-brain/errandPrefsStore.js';
+import { isGhostPickedDir } from '../cindy-brain/pickGrantsStore.js';
import { createGhostErrandRunner } from './ghostErrandRunner.js';
import {
createGhostErrandSession,
@@ -5906,6 +5907,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getGhostName: getInstalledGhostName,
getDraftDefaults: getWorkerDefaultsFromNewMaker,
normalizeWorkingDir: (dir) => normalizeWorkingDirForStorage(dir),
+ isUserPickedDir: isGhostPickedDir,
isSessionBusy: isSessionInTurn,
dispatch: async ({ targetSessionId, message }) => {
const r = await sendToSessionInternal({ targetSessionId, message });
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 490174c55d..f408c732c8 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -4269,6 +4269,13 @@ export type GhostPipeAgentErrandRequest =
context?: unknown;
/** errand 会话标题提示(仅首次创建该插件的 errand 会话时采用;1–100 字符)。 */
title?: string;
+ /**
+ * 可选:请求把 errand 会话建在这个目录(绝对路径,≤1024 字符)。
+ * 只是**转述**,不是授权——主机只认用户此前在 pick 槽系统窗口里
+ * 亲手选过的目录(pickGrantsStore 台账);台账里没有 → INVALID_REQUEST。
+ * 用户在「AI 代办」卡里配置了工作目录时以用户配置优先,本字段忽略。
+ */
+ workingDir?: string;
/**
* 'wait' = 同步吊着等完成(管子自动续命,30 分钟天花板);缺省异步:
* 受理后立即返回 jobId,用 kind:'query' 轮询取件。agent 干活是分钟级