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(desktop): 插件派活(errand)支持 sessionKey 分会话

Lizi3b058644120d
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts
index 07e3941daa..a5c9107a66 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts
@@ -80,8 +80,28 @@ describe('normalize(整文件清洗)', () => {
});
});
+ it('带钥匙的 sessions 条目(ghostId#key)原样保留', () => {
+ expect(
+ __testing.normalize({
+ errand: {},
+ sessions: { helper: 'sess-1', 'helper#pr-123': 'sess-2' },
+ }),
+ ).toEqual({
+ errand: {},
+ sessions: { helper: 'sess-1', 'helper#pr-123': 'sess-2' },
+ });
+ });
+
it('非对象/缺区 → 全空', () => {
expect(__testing.normalize(null)).toEqual({ errand: {}, sessions: {} });
expect(__testing.normalize({})).toEqual({ errand: {}, sessions: {} });
});
});
+
+describe('sessionMapKey(会话映射键)', () => {
+ it('缺省 = ghostId 本身;带钥匙 = ghostId#key(两侧字符集都不含 #,无歧义)', () => {
+ expect(__testing.sessionMapKey('helper')).toBe('helper');
+ expect(__testing.sessionMapKey('helper', undefined)).toBe('helper');
+ expect(__testing.sessionMapKey('helper', 'pr-123')).toBe('helper#pr-123');
+ });
+});
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 579cea7036..19459825c6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
@@ -99,6 +99,10 @@ describe('载荷校验', () => {
{ ...RUN, workingDir: ' ' },
{ ...RUN, workingDir: 42 },
{ ...RUN, workingDir: 'x'.repeat(1025) },
+ { ...RUN, sessionKey: '' },
+ { ...RUN, sessionKey: 'pr#1' },
+ { ...RUN, sessionKey: 'x'.repeat(65) },
+ { ...RUN, sessionKey: 42 },
];
for (const payload of cases) {
expect(await slot.handleRequest('helper', payload)).toMatchObject({
@@ -128,6 +132,15 @@ describe('载荷校验', () => {
expect(req.message).toBe('总结 README\n\n[结构化上下文 JSON]\n{"a":1}');
});
+ it('sessionKey 合法时原样透传 runner;不传则请求里不带该字段', async () => {
+ const { slot, runner, clock } = makeSlot();
+ await slot.handleRequest('helper', { ...RUN, sessionKey: 'pr-123' });
+ expect((runner.mock.calls[0][0] as { sessionKey?: string }).sessionKey).toBe('pr-123');
+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS;
+ await slot.handleRequest('helper', RUN);
+ expect('sessionKey' in (runner.mock.calls[1][0] as object)).toBe(false);
+ });
+
it('workingDir 原样透传给 runner(是否亲选目录由 runner 对台账把关)', async () => {
const { slot, runner } = makeSlot();
await slot.handleRequest('helper', { ...RUN, workingDir: '/proj/repo' });
diff --git a/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts b/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts
index ecaf530046..62474dba56 100644
--- a/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts
@@ -48,13 +48,20 @@ export interface GhostErrandConfig {
interface GhostErrandPrefs {
errand: Record<string, GhostErrandConfig>;
/**
- * ghostId → 专属 errand 会话 id(runner 复用映射)。放在偏好文件里而非
- * DB:这是"哪间是它的干活间"的宿主侧记忆,丢了(手删/损坏)的后果只是
- * 下一单重建一间,不值得动 sessions schema(migration 风险不对等)。
+ * 映射键 → 专属 errand 会话 id(runner 复用映射)。键形态两种:
+ * `ghostId` = 该插件的缺省共用间;`ghostId#sessionKey` = 按钥匙分的间
+ * (ghostId 与 sessionKey 的合法字符集都不含 `#`,拼接无歧义)。放在偏好
+ * 文件里而非 DB:这是"哪间是它的干活间"的宿主侧记忆,丢了(手删/损坏)
+ * 的后果只是下一单重建一间,不值得动 sessions schema(migration 风险不对等)。
*/
sessions: Record<string, string>;
}
+/** sessions 表的映射键(见 GhostErrandPrefs.sessions 注释)。 */
+function sessionMapKey(ghostId: string, sessionKey?: string): string {
+ return sessionKey ? `${ghostId}#${sessionKey}` : ghostId;
+}
+
const DEFAULTS: GhostErrandPrefs = { errand: {}, sessions: {} };
/** 单字段清洗:类型/值域不合法一律丢弃(= 回到跟随默认),不迁就脏数据。 */
@@ -144,20 +151,25 @@ export function writeGhostErrandConfig(ghostId: string, config: unknown): GhostE
return cfg;
}
-/** 读某插件的专属 errand 会话 id;null = 还没建过(或映射被清)。 */
-export function readGhostErrandSessionId(ghostId: string): string | null {
+/** 读某插件的专属 errand 会话 id(可带分会话钥匙);null = 还没建过(或映射被清)。 */
+export function readGhostErrandSessionId(ghostId: string, sessionKey?: string): string | null {
store.invalidateIfChanged();
- return store.read().sessions[ghostId] ?? null;
+ return store.read().sessions[sessionMapKey(ghostId, sessionKey)] ?? null;
}
-/** 写/清某插件的专属 errand 会话映射(null 即清除;会话失效重建时更新)。 */
-export function writeGhostErrandSessionId(ghostId: string, sessionId: string | null): void {
+/** 写/清某插件的专属 errand 会话映射(可带分会话钥匙;null 即清除;会话失效重建时更新)。 */
+export function writeGhostErrandSessionId(
+ ghostId: string,
+ sessionId: string | null,
+ sessionKey?: string,
+): void {
store.invalidateIfChanged();
+ const key = sessionMapKey(ghostId, sessionKey);
const sessions = { ...store.read().sessions };
- if (sessionId === null) delete sessions[ghostId];
- else sessions[ghostId] = sessionId;
+ if (sessionId === null) delete sessions[key];
+ else sessions[key] = sessionId;
store.writePatch({ sessions });
- log.info('ghost errand session mapping written', { ghostId, sessionId });
+ log.info('ghost errand session mapping written', { ghostId, sessionKey: sessionKey ?? null, sessionId });
}
-export const __testing = { normalize, normalizeConfig };
+export const __testing = { normalize, normalizeConfig, sessionMapKey };
diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.ts
index 691efe322e..cc3ebdb416 100644
--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts
@@ -27,6 +27,7 @@ import {
GHOST_ERRAND_MAX_RESULT_CHARS,
GHOST_ERRAND_MAX_TASK_CHARS,
GHOST_ERRAND_MIN_INTERVAL_MS,
+ GHOST_ERRAND_SESSION_KEY_RE,
GHOST_PIPE_CALL_MAX_TOTAL_MS,
type GhostAgentErrandErrorCode,
type GhostPipeAgentErrandResult,
@@ -45,8 +46,13 @@ export interface GhostErrandRunRequest {
ghostVersion: string;
/** 已组装的最终任务消息(task + 结构化上下文;本层组装,runner 原样投递)。 */
message: string;
- /** 首次创建 errand 会话时的标题提示。 */
+ /** 首次创建对应 errand 会话时的标题提示。 */
title?: string;
+ /**
+ * 分会话钥匙(形状已由本层按 GHOST_ERRAND_SESSION_KEY_RE 校验)。缺省 =
+ * 插件共用一间;传了 = 同钥匙同间、异钥匙各间(映射按 ghostId+key 存取)。
+ */
+ sessionKey?: string;
/**
* 插件转述的期望工作目录(仅形状校验;是否真是用户亲选目录由 runner
* 对 pick 台账把关——授权对账需要归一化,归一化实现在 runner 侧)。
@@ -180,6 +186,15 @@ export class GhostErrandSlot {
if (payload.mode !== undefined && payload.mode !== 'wait') {
return fail('INVALID_REQUEST', "mode 只支持 'wait'(同步等待)或不传(异步受理 + query 轮询)");
}
+ if (
+ payload.sessionKey !== undefined &&
+ (typeof payload.sessionKey !== 'string' || !GHOST_ERRAND_SESSION_KEY_RE.test(payload.sessionKey))
+ ) {
+ return fail(
+ 'INVALID_REQUEST',
+ 'sessionKey 只能是 1–64 位的字母/数字/./_/-(不传 = 插件共用一间 errand 会话)',
+ );
+ }
if (
payload.workingDir !== undefined &&
(typeof payload.workingDir !== 'string' ||
@@ -252,6 +267,7 @@ export class GhostErrandSlot {
message,
...(typeof payload.title === 'string' ? { title: payload.title.trim() } : {}),
...(typeof payload.workingDir === 'string' ? { workingDir: payload.workingDir } : {}),
+ ...(typeof payload.sessionKey === 'string' ? { sessionKey: payload.sessionKey } : {}),
},
{
onSession: (sessionId) => {
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index dd83ae5e63..249644bddb 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2175,8 +2175,12 @@ await cindy.agent.run({
const r = await cindy.agent.errand({
task: '阅读工作目录下的 README 并总结要点(200 字以内)',
// context: { anything: '结构化上下文,主机 JSON 化后附在任务消息尾部' },
- // title: '我的插件 · 代办', // 仅首次创建 errand 会话时用作标题
+ // title: '我的插件 · 代办', // 仅首次创建对应 errand 会话时用作标题
// workingDir: repoDir, // 可选:请求建在某目录(只认用户亲选过的,见下)
+ // sessionKey: 'pr-123', // 可选:分会话钥匙(1–64 位字母/数字/._-)。
+ // // 不传 = 插件共用一间;同钥匙同间、异钥匙各间,
+ // // 适合按业务对象各聊各的(如每条 PR 一间,标题
+ // // 在该间首次创建时用 title 定,正好带上对象编号)
// mode: 'wait', // 同步等到完成(30 分钟顶);默认不传 = 异步
callId: msg.callId,
});
@@ -2204,6 +2208,7 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });
选一次目录;用户在「AI 代办」卡里配置了目录时,以用户配置优先、本字段忽略;
- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带
标记);完成结果保留 30 分钟,应用重启后查无此单(按可重新提交处理);
+ \`sessionKey\` 只是分间,**不放大并发**——不同钥匙的两单同样要排队;
- \`errorCode:'BUSY'\` = 你已有一单在途,或用户恰好正在 errand 会话里说话;
\`'NO_CANDIDATE'\` 不存在于此——但会话创建/派发失败有 \`'SESSION_UNAVAILABLE'\`,
超时有 \`'TIMEOUT'\`(任务可能仍在会话里继续,提示用户打开会话查看)。
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 4436acec0c..a21fdb6a03 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
@@ -234,6 +234,60 @@ describe('插件转述目录(request.workingDir)', () => {
});
});
+describe('分会话钥匙(sessionKey)', () => {
+ it('带钥匙:按 ghostId+key 读映射,新建后按同一把钥匙写映射', async () => {
+ const readSessionId = vi.fn(() => null);
+ const keyedWrites: Array<[string, string | null, string | undefined]> = [];
+ const { deps, emitters } = makeDeps({
+ readSessionId,
+ writeSessionId: (ghostId, sessionId, sessionKey) => {
+ keyedWrites.push([ghostId, sessionId, sessionKey]);
+ },
+ });
+ const runner = createGhostErrandRunner(deps);
+ const p = runner({ ...REQUEST, sessionKey: 'pr-123' });
+ await vi.waitFor(() => expect(emitters.has('sess-new')).toBe(true));
+ const e = emitters.get('sess-new')!;
+ e.emit(textEvent('ok'));
+ e.emit(doneEvent());
+ await p;
+ expect(readSessionId).toHaveBeenCalledWith('helper', 'pr-123');
+ expect(keyedWrites).toContainEqual(['helper', 'sess-new', 'pr-123']);
+ });
+
+ it('钥匙间投递失败解除映射时同样带钥匙(不误伤共用间映射)', async () => {
+ const keyedWrites: Array<[string, string | null, string | undefined]> = [];
+ const { deps } = makeDeps({
+ readSessionId: () => 'sess-1',
+ writeSessionId: (ghostId, sessionId, sessionKey) => {
+ keyedWrites.push([ghostId, sessionId, sessionKey]);
+ },
+ dispatch: async () => ({ ok: false as const, errorCode: 'ARCHIVED', message: '归档了' }),
+ });
+ const r = await createGhostErrandRunner(deps)({ ...REQUEST, sessionKey: 'pr-9' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'SESSION_UNAVAILABLE' });
+ expect(keyedWrites).toContainEqual(['helper', null, 'pr-9']);
+ });
+
+ it('不带钥匙:读写映射的 sessionKey 一律是 undefined(旧行为不变)', async () => {
+ const readSessionId = vi.fn(() => null);
+ const keyedWrites: Array<[string, string | null, string | undefined]> = [];
+ const { deps, emitters } = makeDeps({
+ readSessionId,
+ writeSessionId: (ghostId, sessionId, sessionKey) => {
+ keyedWrites.push([ghostId, sessionId, sessionKey]);
+ },
+ });
+ const runner = createGhostErrandRunner(deps);
+ const p = runner(REQUEST);
+ await vi.waitFor(() => expect(emitters.has('sess-new')).toBe(true));
+ emitters.get('sess-new')!.emit(doneEvent());
+ await p;
+ expect(readSessionId).toHaveBeenCalledWith('helper', undefined);
+ expect(keyedWrites).toContainEqual(['helper', 'sess-new', undefined]);
+ });
+});
+
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 8c401bafd3..b5d48b32c7 100644
--- a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
+++ b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
@@ -4,7 +4,8 @@
* errandSlot(cindy-brain)只负责资格审/频控/任务表;真正的干活链在这里:
*
* 解析用户配置(errandPrefsStore,缺省跟随 New Maker 草稿偏好)
- * → 确保专属 errand 会话(映射存 prefs;失效/配置关键项变更则重建)
+ * → 确保专属 errand 会话(映射存 prefs;失效/配置关键项变更则重建;
+ * 请求带 sessionKey 时按 ghostId+key 分间——同钥匙同间、异钥匙各间)
* → 忙检(errand 会话正被占用即 BUSY,不排队——排队会让结果对不上单)
* → sendToSessionInternal 统一通路投递(消息落库/进程拉起与用户亲发一致)
* → observeHookTurn 收口(与飞书 bot / scheduler 同一套 turn 观察语义)
@@ -49,8 +50,9 @@ export interface GhostErrandSessionRow {
export interface GhostErrandRunnerDeps {
readConfig(ghostId: string): GhostErrandConfig;
- readSessionId(ghostId: string): string | null;
- writeSessionId(ghostId: string, sessionId: string | null): void;
+ /** sessionKey 缺省 = 插件共用间;带钥匙 = 该钥匙专属间(映射按 ghostId+key)。 */
+ readSessionId(ghostId: string, sessionKey?: string): string | null;
+ writeSessionId(ghostId: string, sessionId: string | null, sessionKey?: string): void;
getSessionRow(sessionId: string): Promise<GhostErrandSessionRow | null>;
/** 建 errand 会话 DB 行(不拉 agent);config 已由本层解析合并完毕。 */
createSession(params: {
@@ -168,13 +170,14 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
effectiveDir = requested;
}
- // ── 确保专属 errand 会话 ─────────────────────────────────────────────
- let sessionId = deps.readSessionId(request.ghostId);
+ // ── 确保专属 errand 会话(sessionKey 缺省共用间,带钥匙各开各间) ────
+ const sessionKey = request.sessionKey;
+ let sessionId = deps.readSessionId(request.ghostId, sessionKey);
if (sessionId) {
const row = await deps.getSessionRow(sessionId);
if (!row || !sessionMatchesConfig(row, cfg, permissionMode, effectiveDir)) {
// 旧间不可用/配置已变:解除映射换新间(旧会话留在侧边栏,历史可查)。
- deps.writeSessionId(request.ghostId, null);
+ deps.writeSessionId(request.ghostId, null, sessionKey);
sessionId = null;
}
}
@@ -205,7 +208,7 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
deps.log.warn('ghost errand session create failed', { ghostId: request.ghostId, error: message });
return failure('SESSION_UNAVAILABLE', `errand 会话创建失败:${message}`);
}
- deps.writeSessionId(request.ghostId, sessionId);
+ deps.writeSessionId(request.ghostId, sessionId, sessionKey);
}
hooks?.onSession?.(sessionId);
@@ -225,7 +228,7 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
dispatched.errorCode === 'DELETED'
) {
// 会话在忙检与投递之间被删/归档:解除映射,让下一单重建。
- deps.writeSessionId(request.ghostId, null);
+ deps.writeSessionId(request.ghostId, null, sessionKey);
return failure('SESSION_UNAVAILABLE', dispatched.message);
}
return failure('INTERNAL', dispatched.message);
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index f408c732c8..89d0274fce 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -4249,6 +4249,9 @@ export const GHOST_ERRAND_JOB_TTL_MS = 30 * 60_000;
/** 每插件相邻两次提交的最小间隔(毫秒;与 agent-request 后台档同口径)。
* 同步等待(mode:'wait')的绝对上限直接复用 GHOST_PIPE_CALL_MAX_TOTAL_MS。 */
export const GHOST_ERRAND_MIN_INTERVAL_MS = 10_000;
+/** sessionKey 的合法形状(1–64 位字母/数字/._-;字符集刻意排除 `#`,
+ * 存储层用 `ghostId#sessionKey` 做映射键,ghostId 字符集同样无 `#`,不会歧义)。 */
+export const GHOST_ERRAND_SESSION_KEY_RE = /^[A-Za-z0-9._-]{1,64}$/;
/**
* errand 会话允许的权限档。plan = 只读默认档;acceptEdits / auto 由用户在
@@ -4267,8 +4270,15 @@ export type GhostPipeAgentErrandRequest =
task: string;
/** 可选结构化上下文:主机 JSON.stringify 后附在任务消息尾部(≤64KB)。 */
context?: unknown;
- /** errand 会话标题提示(仅首次创建该插件的 errand 会话时采用;1–100 字符)。 */
+ /** errand 会话标题提示(仅首次创建对应 errand 会话时采用;1–100 字符)。 */
title?: string;
+ /**
+ * 可选的分会话钥匙(1–64 位字母/数字/._-)。不传 = 插件共用一间专属
+ * errand 会话(旧行为);传了 = 同一把钥匙复用同一间、不同钥匙各开各
+ * 的间(每单仍受"每插件同时 1 单在途"约束,分会话不放大并发)。适合
+ * 「按业务对象各聊各的」场景,如每条 PR 一间:sessionKey:'pr-123'。
+ */
+ sessionKey?: string;
/**
* 可选:请求把 errand 会话建在这个目录(绝对路径,≤1024 字符)。
* 只是**转述**,不是授权——主机只认用户此前在 pick 槽系统窗口里