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。

fix(desktop): 插件执行落到可见任务时切到该任务 (#3227)

Chris Zhang61e7d15190b6
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts
index 11baf2c3dd..04ac88af3a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts
@@ -59,6 +59,7 @@ function makeSlot(options: {
ghosts?: InstalledGhost[];
runner?: GhostAgentTurnRunner | null;
now?: () => number;
+ onRevealSession?: (sessionId: string) => void;
} = {}) {
const ghosts = options.ghosts ?? [fakeGhost('alpha')];
let tokenIndex = 0;
@@ -67,6 +68,7 @@ function makeSlot(options: {
runner: options.runner,
now: options.now ?? (() => 20_000),
createToken: () => `token-${++tokenIndex}`,
+ ...(options.onRevealSession ? { onRevealSession: options.onRevealSession } : {}),
};
return new GhostAgentSlot(deps);
}
@@ -276,3 +278,92 @@ describe('agentSlot · 后台权限', () => {
expect(runner).toHaveBeenCalledTimes(2);
});
});
+
+describe('agentSlot · 可见任务自动切过去', () => {
+ it('user-action continue 切到原会话', async () => {
+ const reveal = vi.fn();
+ const slot = makeSlot({ runner: acceptedRunner(), onRevealSession: reveal });
+ const token = slot.issueUserActionToken('alpha', 'session-source')!;
+ await slot.handleRequest('alpha', userRequest(token));
+ expect(reveal).toHaveBeenCalledOnce();
+ expect(reveal).toHaveBeenCalledWith('session-source');
+ });
+
+ it('user-action new / fork 切到新任务', async () => {
+ const reveal = vi.fn();
+ const slot = makeSlot({ runner: acceptedRunner(), onRevealSession: reveal });
+ for (const mode of ['new', 'fork'] as const) {
+ const token = slot.issueUserActionToken('alpha', 'session-source')!;
+ await slot.handleRequest(
+ 'alpha',
+ userRequest(token, { mode, title: mode === 'new' ? '新任务' : undefined }),
+ );
+ }
+ expect(reveal.mock.calls.map(([sessionId]) => sessionId)).toEqual([
+ 'target-new',
+ 'target-fork',
+ ]);
+ });
+
+ it('后台 continue 不切任务', async () => {
+ const reveal = vi.fn();
+ const slot = makeSlot({
+ ghosts: [fakeGhost('alpha', { background: true })],
+ runner: acceptedRunner(),
+ onRevealSession: reveal,
+ });
+ slot.issueUserActionToken('alpha', 'session-1');
+ await slot.handleRequest('alpha', {
+ ...userRequest('unused'),
+ trigger: 'background',
+ sessionId: 'session-1',
+ });
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('后台 new / fork 也不切任务', async () => {
+ let now = 20_000;
+ const reveal = vi.fn();
+ const slot = makeSlot({
+ ghosts: [fakeGhost('alpha', { background: true })],
+ runner: acceptedRunner(),
+ onRevealSession: reveal,
+ now: () => now,
+ });
+ slot.issueUserActionToken('alpha', 'session-1');
+ for (const mode of ['new', 'fork'] as const) {
+ const result = await slot.handleRequest('alpha', {
+ ...userRequest('unused'),
+ trigger: 'background',
+ mode,
+ title: mode === 'new' ? '插件新任务' : undefined,
+ sessionId: 'session-1',
+ });
+ expect(result.ok).toBe(true);
+ now += 10_000;
+ }
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('runner 失败不切', async () => {
+ const reveal = vi.fn();
+ const runner = vi.fn<GhostAgentTurnRunner>(async () => ({
+ ok: false as const,
+ errorCode: 'NOT_FOUND',
+ message: 'gone',
+ }));
+ const slot = makeSlot({ runner, onRevealSession: reveal });
+ const token = slot.issueUserActionToken('alpha', 'session-source')!;
+ await slot.handleRequest('alpha', userRequest(token));
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('setRevealSession 可以后接线', async () => {
+ const reveal = vi.fn();
+ const slot = makeSlot({ runner: acceptedRunner() });
+ slot.setRevealSession(reveal);
+ const token = slot.issueUserActionToken('alpha', 'session-source')!;
+ await slot.handleRequest('alpha', userRequest(token));
+ expect(reveal).toHaveBeenCalledWith('session-source');
+ });
+});
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 dcda32382c..00fb4e9e2f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts
@@ -389,3 +389,186 @@ describe('clearGhost', () => {
expect(await slot.handleRequest('helper', RUN)).toMatchObject({ ok: true, status: 'running' });
});
});
+
+describe('可见任务自动切过去', () => {
+ it('onSession 只回填 id,投递成功后再切;收口不再切第二次', async () => {
+ const reveal = vi.fn();
+ let hooks: {
+ onSession?: (sid: string) => void;
+ onDispatched?: (sid: string) => void;
+ } | undefined;
+ let finish: (() => void) | null = null;
+ const runner = vi.fn(
+ (_req: unknown, h?: { onSession?: (sid: string) => void; onDispatched?: (sid: string) => void }) => {
+ hooks = h;
+ return new Promise((resolve) => {
+ finish = () => resolve({ ok: true, sessionId: 'sess-9', text: 'done' });
+ });
+ },
+ );
+ const { slot } = makeSlot({
+ runner: runner as unknown as GhostErrandRunner,
+ onRevealSession: reveal,
+ });
+ slot.noteUserGesture('helper');
+ await slot.handleRequest('helper', RUN);
+ hooks?.onSession?.('sess-9');
+ expect(reveal).not.toHaveBeenCalled();
+ hooks?.onDispatched?.('sess-9');
+ expect(reveal).toHaveBeenCalledOnce();
+ expect(reveal).toHaveBeenCalledWith('sess-9');
+ finish!();
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('runner 没回调 onSession、只在收口给 sessionId 也切一次', async () => {
+ const reveal = vi.fn();
+ const { slot } = makeSlot({ onRevealSession: reveal });
+ slot.noteUserGesture('helper');
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledOnce();
+ expect(reveal).toHaveBeenCalledWith('sess-1');
+ });
+
+ it('只回填了 onSession、随后失败不切', async () => {
+ const reveal = vi.fn();
+ const runner = vi.fn(
+ async (_req: unknown, h?: { onSession?: (sid: string) => void }) => {
+ h?.onSession?.('sess-busy');
+ return {
+ ok: false as const,
+ errorCode: 'BUSY' as const,
+ message: '正忙',
+ };
+ },
+ );
+ const { slot } = makeSlot({
+ runner: runner as unknown as GhostErrandRunner,
+ onRevealSession: reveal,
+ });
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('runner 失败且从未给出 sessionId 不切', async () => {
+ const reveal = vi.fn();
+ const { slot } = makeSlot({
+ onRevealSession: reveal,
+ runner: vi.fn(async () => ({
+ ok: false as const,
+ errorCode: 'TIMEOUT' as const,
+ message: '超时了',
+ })) as unknown as GhostErrandRunner,
+ });
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('setRevealSession 可以后接线', async () => {
+ const reveal = vi.fn();
+ const { slot } = makeSlot();
+ slot.setRevealSession(reveal);
+ slot.noteUserGesture('helper');
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledWith('sess-1');
+ });
+
+ it('没有主机点击凭据的派活不切任务', async () => {
+ const reveal = vi.fn();
+ const runner = vi.fn(async (_req: { origin?: string }, h?: { onDispatched?: (sid: string) => void }) => {
+ h?.onDispatched?.('sess-bg');
+ return { ok: true as const, sessionId: 'sess-bg', text: 'done' };
+ });
+ const { slot } = makeSlot({
+ runner: runner as unknown as GhostErrandRunner,
+ onRevealSession: reveal,
+ });
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(runner.mock.calls[0][0].origin).toBe('background');
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('Host 铸造的卡片点击票可以把派活标成 user-action,且一次作废', async () => {
+ const reveal = vi.fn();
+ const live = new Set(['click-1']);
+ const { slot, runner, clock } = makeSlot({
+ onRevealSession: reveal,
+ consumeUserActionToken: (token, ghostId) => {
+ if (ghostId !== 'helper' || !live.has(token)) return false;
+ live.delete(token);
+ return true;
+ },
+ });
+ await slot.handleRequest('helper', { ...RUN, userActionToken: 'click-1' });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(runner.mock.calls[0][0]).toMatchObject({ origin: 'user-action' });
+ expect(reveal).toHaveBeenCalledOnce();
+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS + 1;
+ await slot.handleRequest('helper', { ...RUN, userActionToken: 'click-1' });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(runner.mock.calls[1][0].origin).toBe('background');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('假票或过期票不能切任务', async () => {
+ const reveal = vi.fn();
+ const { slot, runner } = makeSlot({
+ onRevealSession: reveal,
+ consumeUserActionToken: () => false,
+ });
+ await slot.handleRequest('helper', { ...RUN, userActionToken: 'forged' });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(runner.mock.calls[0][0].origin).toBe('background');
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('面板点击手势只够切一次', async () => {
+ const reveal = vi.fn();
+ const { slot, clock } = makeSlot({ onRevealSession: reveal });
+ slot.noteUserGesture('helper');
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledOnce();
+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS + 1;
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('消费卡片票时顺手清掉同一次点击留下的面板手势', async () => {
+ const reveal = vi.fn();
+ const live = new Set(['click-1']);
+ const { slot, clock } = makeSlot({
+ onRevealSession: reveal,
+ consumeUserActionToken: (token) => {
+ if (!live.has(token)) return false;
+ live.delete(token);
+ return true;
+ },
+ });
+ slot.noteUserGesture('helper');
+ await slot.handleRequest('helper', { ...RUN, userActionToken: 'click-1' });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledOnce();
+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS + 1;
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('过期的面板手势不能再切任务', async () => {
+ const reveal = vi.fn();
+ const { slot, clock } = makeSlot({ onRevealSession: reveal });
+ slot.noteUserGesture('helper');
+ clock.now += 3_001;
+ await slot.handleRequest('helper', RUN);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(reveal).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index fb811166fb..6b7abb2be9 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1559,6 +1559,7 @@ describe('FORGE_GUIDE', () => {
'cindy.agent.errand',
'queryErrand',
'"errand": true',
+ 'userActionToken',
'node 槽',
'cindy.node.request',
'json-rpc-stdio',
diff --git a/apps/desktop/src/main/cindy-brain/agentSlot.ts b/apps/desktop/src/main/cindy-brain/agentSlot.ts
index cc548551fe..1d3d5d9011 100644
--- a/apps/desktop/src/main/cindy-brain/agentSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/agentSlot.ts
@@ -73,6 +73,11 @@ export interface GhostAgentSlotDeps {
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
};
+ /**
+ * 执行落到一条可见任务时,由主机把左侧切过去。
+ * 只对 user-action 调用 — 后台 continue/new/fork 不能抢当前任务。
+ */
+ onRevealSession?: (sessionId: string) => void;
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
@@ -90,9 +95,11 @@ export class GhostAgentSlot {
private readonly inFlightGhosts = new Set<string>();
private readonly lastBackgroundAt = new Map<string, number>();
private runner: GhostAgentTurnRunner | null;
+ private onRevealSession: ((sessionId: string) => void) | null;
constructor(private readonly deps: GhostAgentSlotDeps) {
this.runner = deps.runner ?? null;
+ this.onRevealSession = deps.onRevealSession ?? null;
}
/** maker-ipc 初始化完成后注入真实 session runner;传 null 用于退出清理。 */
@@ -100,6 +107,11 @@ export class GhostAgentSlot {
this.runner = runner;
}
+ /** maker-ipc 初始化完成后注入任务聚焦;传 null 用于退出清理。 */
+ setRevealSession(reveal: ((sessionId: string) => void) | null): void {
+ this.onRevealSession = reveal;
+ }
+
/** 插件停用/卸载时清除该 ghost 的所有会话关联和节流状态,防止权限残留。 */
clearGhost(ghostId: string): void {
this.associatedSessions.delete(ghostId);
@@ -146,6 +158,14 @@ export class GhostAgentSlot {
return token;
}
+ /** 消费卡片点击票。派活切任务与 agent.run 共用,一次作废。 */
+ consumeUserActionToken(token: string, ghostId: string): boolean {
+ const peeked = this.peekGrant(token, ghostId);
+ if (!peeked.ok) return false;
+ this.grants.delete(token);
+ return true;
+ }
+
/** 处理电子脑的 agent-request;所有失败都折叠成结构化返回。 */
async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeAgentResult> {
const ghost = this.deps.getGhost(ghostId);
@@ -312,6 +332,7 @@ export class GhostAgentSlot {
trigger,
disposition: result.disposition,
});
+ this.maybeRevealSession(trigger, mode as GhostAgentRunMode, result.sessionId);
return {
ok: true,
sessionId: result.sessionId,
@@ -329,6 +350,20 @@ export class GhostAgentSlot {
}
}
+ private maybeRevealSession(
+ trigger: string,
+ _mode: GhostAgentRunMode,
+ sessionId: string,
+ ): void {
+ // 只认用户当次点击。后台 new/fork 也会开可见任务,但不能抢前台。
+ if (trigger !== 'user-action') return;
+ try {
+ this.onRevealSession?.(sessionId);
+ } catch {
+ // 聚焦失败不能让已经成功的回合对插件变失败。
+ }
+ }
+
private now(): number {
return this.deps.now?.() ?? Date.now();
}
diff --git a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
index f7c922d4f7..b408a92b02 100644
--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
@@ -161,6 +161,7 @@ export class GhostCardActionDispatcher {
await this.deps.wake(ghost);
if (!ownerUsable()) return rejectStaleOwner(ghostId);
}
+ // 卡片路径只发这一张一次性票;不另记面板手势,避免一次点击两份凭据。
const userActionToken = this.deps.issueUserActionToken?.(ghostId, sessionId) ?? null;
if (!ownerUsable()) return rejectStaleOwner(ghostId);
this.deps.sendToGhost(ghostId, {
diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.ts
index 8f0336102d..b091c7d76d 100644
--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts
@@ -41,9 +41,14 @@ const MAX_JOB_ID_LEN = 64;
/** 每插件完成态任务记录保留上限(同 cindySlot 的第二道闸)。 */
const MAX_SETTLED_JOBS_PER_GHOST = 16;
+/** 派活来源:面板/卡片点击 vs MCP/调度器静默回合。由主机归因,插件不能自报。 */
+export type GhostErrandOrigin = 'user-action' | 'background';
+
export interface GhostErrandRunRequest {
ghostId: string;
ghostVersion: string;
+ /** 主机归因的来源;切任务只认 user-action。 */
+ origin: GhostErrandOrigin;
/** 已组装的最终任务消息(task + 结构化上下文;本层组装,runner 原样投递)。 */
message: string;
/** 首次创建对应 errand 会话时的标题提示。 */
@@ -63,6 +68,8 @@ export interface GhostErrandRunRequest {
export interface GhostErrandRunHooks {
/** errand 会话 id 一旦确定即回报(异步单据此让 query 尽早可见 sessionId)。 */
onSession?(sessionId: string): void;
+ /** 忙检通过且消息已投进会话后再回报;切任务只认这一下。 */
+ onDispatched?(sessionId: string): void;
}
export type GhostErrandRunOutcome =
@@ -94,10 +101,17 @@ export interface GhostErrandSlotDeps {
releasePipeCall?(ghostId: string, callId: string): void;
now?: () => number;
createJobId?: () => string;
+ /** 消费卡片点击票(与 agent.run 同一套 Host 铸造票,一次作废)。 */
+ consumeUserActionToken?(token: string, ghostId: string): boolean;
log?: {
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
};
+ /**
+ * 派活落到专属可见任务时,由主机把左侧切过去。
+ * 签字门「执行」走这条:插件自己开一间 errand 会话干活。
+ */
+ onRevealSession?: (sessionId: string) => void;
}
/** 在途/完成的派活任务记录(内存表;语义同 cindySlot 的 CindyAsyncJob)。 */
@@ -107,6 +121,10 @@ interface ErrandJob {
status: 'running' | 'done' | 'failed';
/** runner 一旦确定 errand 会话即回填(running 期即可见)。 */
sessionId?: string;
+ /** 本单已经切过左侧,onSession + 收口只切一次。 */
+ revealed?: boolean;
+ /** 主机归因:只有 user-action 才切任务。 */
+ origin: GhostErrandOrigin;
result?: { sessionId: string; text: string; agentKind?: string; model?: string };
errorCode?: GhostAgentErrandErrorCode;
error?: string;
@@ -130,14 +148,21 @@ export function clampErrandResultText(text: string): string {
return `${text.slice(0, GHOST_ERRAND_MAX_RESULT_CHARS)}\n…[结果超长,已截断]`;
}
+/** 面板点击到派活必须紧挨着;订阅/定时器不能吃到几分钟前的一次乱点。 */
+const USER_GESTURE_TTL_MS = 3_000;
+
export class GhostErrandSlot {
private readonly jobs = new Map<string, ErrandJob>();
private readonly inFlightGhosts = new Set<string>();
private readonly lastRunAt = new Map<string, number>();
+ /** ghostId → 主机观察到的当次点击过期时刻。 */
+ private readonly userGestures = new Map<string, number>();
private runner: GhostErrandRunner | null;
+ private onRevealSession: ((sessionId: string) => void) | null;
constructor(private readonly deps: GhostErrandSlotDeps) {
this.runner = deps.runner ?? null;
+ this.onRevealSession = deps.onRevealSession ?? null;
}
/** maker-ipc 初始化完成后注入真实 runner;传 null 用于退出清理。 */
@@ -145,6 +170,11 @@ export class GhostErrandSlot {
this.runner = runner;
}
+ /** maker-ipc 初始化完成后注入任务聚焦;传 null 用于退出清理。 */
+ setRevealSession(reveal: ((sessionId: string) => void) | null): void {
+ this.onRevealSession = reveal;
+ }
+
/** clearGhost 只删 jobs,不删 inFlightGhosts;收口前两者可能短暂不一致。 */
hasActiveErrandFor(ghostId: string): boolean {
return this.inFlightGhosts.has(ghostId) || [...this.jobs.values()].some(
@@ -152,9 +182,16 @@ export class GhostErrandSlot {
);
}
+ /** 宿主确认的真实点击(卡片按钮 / 面板 mouseDown / keyDown)。 */
+ noteUserGesture(ghostId: string): void {
+ this.sweepUserGestures();
+ this.userGestures.set(ghostId, this.now() + USER_GESTURE_TTL_MS);
+ }
+
/** 插件停用/卸载时清除节流状态与任务记录,防止权限/信息残留。 */
clearGhost(ghostId: string): void {
this.lastRunAt.delete(ghostId);
+ this.userGestures.delete(ghostId);
for (const [jobId, job] of [...this.jobs]) {
if (job.ghostId === ghostId) this.jobs.delete(jobId);
}
@@ -217,6 +254,16 @@ export class GhostErrandSlot {
return fail('INVALID_REQUEST', 'callId 不合法(1–128 字符的字符串,或不传)');
}
const callId = (payload.callId as string | undefined) ?? 'unattributed';
+ if (
+ payload.userActionToken !== undefined &&
+ (typeof payload.userActionToken !== 'string' ||
+ payload.userActionToken.length === 0 ||
+ payload.userActionToken.length > MAX_CALL_ID_LEN)
+ ) {
+ return fail('INVALID_REQUEST', 'userActionToken 不合法');
+ }
+ const userActionToken =
+ typeof payload.userActionToken === 'string' ? payload.userActionToken : undefined;
// 结构化上下文:JSON 化由主机做(确定性代码),超限明拒。
let contextJson: string | null = null;
@@ -248,7 +295,8 @@ export class GhostErrandSlot {
this.lastRunAt.set(ghostId, now);
this.evictSettledJobs(ghostId);
const jobId = (this.deps.createJobId ?? randomUUID)();
- const job: ErrandJob = { ghostId, startedAt: now, status: 'running' };
+ const origin = this.resolveOrigin(ghostId, userActionToken);
+ const job: ErrandJob = { ghostId, startedAt: now, status: 'running', origin };
this.jobs.set(jobId, job);
this.inFlightGhosts.add(ghostId);
@@ -262,6 +310,7 @@ export class GhostErrandSlot {
ghostId,
jobId,
callId,
+ origin,
mode: payload.mode === 'wait' ? 'wait' : 'submit',
});
@@ -271,6 +320,7 @@ export class GhostErrandSlot {
{
ghostId,
ghostVersion: ghost.manifest.version,
+ origin,
message,
...(typeof payload.title === 'string' ? { title: payload.title.trim() } : {}),
...(typeof payload.workingDir === 'string' ? { workingDir: payload.workingDir } : {}),
@@ -280,11 +330,16 @@ export class GhostErrandSlot {
onSession: (sessionId) => {
job.sessionId = sessionId;
},
+ onDispatched: (sessionId) => {
+ job.sessionId = sessionId;
+ this.revealSessionOnce(job, sessionId);
+ },
},
);
if (outcome.ok) {
job.status = 'done';
job.sessionId = outcome.sessionId;
+ this.revealSessionOnce(job, outcome.sessionId);
job.result = {
sessionId: outcome.sessionId,
text: clampErrandResultText(outcome.text),
@@ -387,6 +442,44 @@ export class GhostErrandSlot {
return fail(job.errorCode ?? 'TURN_FAILED', job.error ?? '派活失败');
}
+ private resolveOrigin(ghostId: string, userActionToken?: string): GhostErrandOrigin {
+ // 只认 Host 铸造的当次点击:卡片票,或面板 webview 上真实的 mouse/key。
+ if (
+ userActionToken &&
+ this.deps.consumeUserActionToken?.(userActionToken, ghostId) === true
+ ) {
+ this.userGestures.delete(ghostId);
+ return 'user-action';
+ }
+ if (this.consumeUserGesture(ghostId)) return 'user-action';
+ return 'background';
+ }
+
+ private consumeUserGesture(ghostId: string): boolean {
+ const expiresAt = this.userGestures.get(ghostId);
+ if (expiresAt === undefined) return false;
+ this.userGestures.delete(ghostId);
+ return expiresAt > this.now();
+ }
+
+ private sweepUserGestures(): void {
+ const now = this.now();
+ for (const [ghostId, expiresAt] of [...this.userGestures]) {
+ if (expiresAt <= now) this.userGestures.delete(ghostId);
+ }
+ }
+
+ private revealSessionOnce(job: ErrandJob, sessionId: string): void {
+ if (job.origin !== 'user-action') return;
+ if (job.revealed) return;
+ job.revealed = true;
+ try {
+ this.onRevealSession?.(sessionId);
+ } catch {
+ // 聚焦失败不能让已经受理的派活对插件变失败。
+ }
+ }
+
private now(): number {
return this.deps.now?.() ?? Date.now();
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 942963f9ba..9faa8e62f2 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3405,6 +3405,7 @@ const r = await cindy.agent.errand({
// // 适合按业务对象各聊各的(如每条 PR 一间,标题
// // 在该间首次创建时用 title 定,正好带上对象编号)
// mode: 'wait', // 同步等到完成(30 分钟顶);默认不传 = 异步
+ // userActionToken: msg.userActionToken, // 卡片点击票;校验后切到 errand 任务,一次性
callId: msg.callId,
});
// 受理:{ ok:true, jobId, status:'running', sessionId }
@@ -3432,6 +3433,10 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });
- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带
标记);完成结果保留 30 分钟,应用重启后查无此单(按可重新提交处理);
\`sessionKey\` 只是分间,**不放大并发**——不同钥匙的两单同样要排队;
+- 可选 \`userActionToken\`:把 \`card-action\` 里主机签发的点击票原样带上。
+ 主机校验通过才把这次派活当成用户发起并切到 errand 任务;票一次性消费,
+ 不能再拿去 \`agent.run\` 或再派一次。面板上的真实点击由主机自己记账,
+ 必须紧挨着这次派活,不能靠几分钟前点过输入框来顶替;
- \`errorCode:'BUSY'\` = 你已有一单在途,或用户恰好正在 errand 会话里说话;
\`'NO_CANDIDATE'\` 不存在于此——但会话创建/派发失败有 \`'SESSION_UNAVAILABLE'\`,
超时有 \`'TIMEOUT'\`(任务可能仍在会话里继续,提示用户打开会话查看)。
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 0bf45ef77d..1e9ae1de58 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1594,6 +1594,12 @@ export function setGhostAgentTurnRunner(runner: GhostAgentTurnRunner | null): vo
getGhostAgentSlot().setRunner(runner);
}
+/** maker-ipc 完成初始化后注入「切到这条可见任务」;保持 cindy-brain 不反向依赖 deepLink。 */
+export function setGhostSessionRevealer(reveal: ((sessionId: string) => void) | null): void {
+ getGhostAgentSlot().setRevealSession(reveal);
+ getGhostErrandSlot().setRevealSession(reveal);
+}
+
let errandSlotSingleton: GhostErrandSlot | null = null;
/** 派活取件槽单例(agent 槽 errand 加档):资格审/频控/任务表的统一守门点。 */
@@ -1605,6 +1611,8 @@ export function getGhostErrandSlot(): GhostErrandSlot {
holdPipeCall: (ghostId, callId, budgetMs) =>
getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),
releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),
+ consumeUserActionToken: (token, ghostId) =>
+ getGhostAgentSlot().consumeUserActionToken(token, ghostId),
log,
});
}
@@ -1624,6 +1632,11 @@ export function setGhostErrandRunner(runner: GhostErrandRunner | null): void {
getGhostErrandSlot().setRunner(runner);
}
+/** 宿主确认的面板/卡片点击。派活只在这之后才切任务。 */
+export function noteGhostUserGesture(ghostId: string): void {
+ getGhostErrandSlot().noteUserGesture(ghostId);
+}
+
/** 插件展示名(errand 会话默认标题等宿主侧使用;未装返回 null)。 */
export function getInstalledGhostName(id: string): string | null {
return findAvailableGhost(id)?.manifest.name ?? null;
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 b4c46e5de5..6d70a710a0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts
@@ -97,7 +97,12 @@ function makeDeps(overrides: Partial<GhostErrandRunnerDeps> = {}): {
return { deps, emitters, writes };
}
-const REQUEST = { ghostId: 'helper', ghostVersion: '1.0.0', message: '干活' };
+const REQUEST = {
+ ghostId: 'helper',
+ ghostVersion: '1.0.0',
+ origin: 'user-action' as const,
+ message: '干活',
+};
describe('权限档钳制', () => {
it('白名单外/缺省一律收敛到 plan;bypassPermissions 不存在', () => {
@@ -132,20 +137,25 @@ describe('Pi 代办路由', () => {
});
describe('专属会话建/复用', () => {
- it('无映射时创建会话并写映射,onSession 尽早回报', async () => {
+ it('无映射时创建会话并写映射,onSession 尽早回报,投递成功才 onDispatched', async () => {
const { deps, emitters, writes } = makeDeps();
const runner = createGhostErrandRunner(deps);
const seen: string[] = [];
- const p = runner(REQUEST, { onSession: (sid) => seen.push(sid) });
+ const dispatched: string[] = [];
+ const p = runner(REQUEST, {
+ onSession: (sid) => seen.push(sid),
+ onDispatched: (sid) => dispatched.push(sid),
+ });
await vi.waitFor(() => {
expect(emitters.has('sess-new')).toBe(true);
});
+ expect(seen).toEqual(['sess-new']);
+ expect(dispatched).toEqual(['sess-new']);
const e = emitters.get('sess-new')!;
e.emit(textEvent('答案'));
e.emit(doneEvent());
const r = await p;
expect(r).toMatchObject({ ok: true, sessionId: 'sess-new', text: '答案', agentKind: 'cc' });
- expect(seen).toEqual(['sess-new']);
expect(writes).toContainEqual(['helper', 'sess-new']);
});
@@ -331,11 +341,20 @@ describe('忙检与投递', () => {
isSessionBusy: () => true,
dispatch: dispatch as unknown as GhostErrandRunnerDeps['dispatch'],
});
- expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({
+ const seen: string[] = [];
+ const dispatched: string[] = [];
+ expect(
+ await createGhostErrandRunner(deps)(REQUEST, {
+ onSession: (sid) => seen.push(sid),
+ onDispatched: (sid) => dispatched.push(sid),
+ }),
+ ).toMatchObject({
ok: false,
errorCode: 'BUSY',
});
expect(dispatch).not.toHaveBeenCalled();
+ expect(seen).toEqual(['sess-1']);
+ expect(dispatched).toEqual([]);
});
it('投递返回 queued(竞态窗口)→ 如实报 BUSY', async () => {
@@ -343,10 +362,33 @@ describe('忙检与投递', () => {
readSessionId: () => 'sess-1',
dispatch: async () => ({ ok: true as const, wakeKind: 'queued' as const }),
});
- expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({
+ const dispatched: string[] = [];
+ expect(
+ await createGhostErrandRunner(deps)(REQUEST, {
+ onDispatched: (sid) => dispatched.push(sid),
+ }),
+ ).toMatchObject({
ok: false,
errorCode: 'BUSY',
});
+ expect(dispatched).toEqual([]);
+ });
+
+ it('投递成功但会话进程不可观察 → SESSION_UNAVAILABLE,不 onDispatched', async () => {
+ const { deps } = makeDeps({
+ readSessionId: () => 'sess-1',
+ getObservableSession: () => null,
+ });
+ const dispatched: string[] = [];
+ expect(
+ await createGhostErrandRunner(deps)(REQUEST, {
+ onDispatched: (sid) => dispatched.push(sid),
+ }),
+ ).toMatchObject({
+ ok: false,
+ errorCode: 'SESSION_UNAVAILABLE',
+ });
+ expect(dispatched).toEqual([]);
});
it('投递失败映射:NOT_FOUND/ARCHIVED → SESSION_UNAVAILABLE 并解除映射', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
index 74b9be94eb..0fd6f8e1c7 100644
--- a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
+++ b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts
@@ -245,12 +245,12 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran
'errand 会话恰好正忙,本单任务已排队进该会话但结果不再取回;请稍后查看会话或重新提交',
);
}
-
// ── 收口:观察这一轮直到 done / 终态错误 / 超时 ─────────────────────
const session = deps.getObservableSession(sessionId);
if (!session) {
return failure('SESSION_UNAVAILABLE', 'errand 会话进程不可用,请稍后再试');
}
+ hooks?.onDispatched?.(sessionId);
const observer = observeHookTurn(session, {
// 不传 onProgress: errand 只取终态结果, 不向任何渠道发过程快照。
onSilentStopSettled: deps.onSilentStopSettled,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d198ba185a..21dadf9d99 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -942,6 +942,7 @@ import {
hasEnabledUserMessageHookGhost,
screenGhostUserMessage,
setGhostAgentTurnRunner,
+ setGhostSessionRevealer,
setGhostErrandRunner,
setGhostWorkspaceSessionService,
notifyGhostSessionEvent,
@@ -9382,6 +9383,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
disposition: 'forked',
};
});
+ setGhostSessionRevealer((sessionId) => openMainWindowSession(sessionId));
// Ghost 的派活取件(agent 槽 errand 加档):守门在 cindy-brain/errandSlot,
// 这里注入真实执行链——专属会话确保/统一投递/turn 收口。投递仍走
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index aca4e57ea0..1d4c141651 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -42,6 +42,7 @@ import { getAppShortcutStore } from './app-shortcuts/index.js';
import {
handleGhostExternalLinkNavigation,
handleGhostPreviewNavigation,
+ noteGhostUserGesture,
resolveGhostWebviewAttach,
} from './cindy-brain/index.js';
import { classifyGhostPanelNavigation } from './cindy-brain/previewGate.js';
@@ -794,6 +795,13 @@ export function installGhostGuestNavigationHandlers(
},
): void {
guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ const noteGesture = () => noteGhostUserGesture(ghostId);
+ guestContents.on('before-mouse-event', (_event, mouse) => {
+ if (mouse.type === 'mouseDown') noteGesture();
+ });
+ guestContents.on('before-input-event', (_event, input) => {
+ if (input.type === 'keyDown') noteGesture();
+ });
guestContents.on('will-navigate', (event, url) => {
const nav = classifyGhostPanelNavigation(url, ghostId);
if (nav === 'allow') return;
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 84acb2fdbe..f2bd4b90d3 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -5601,6 +5601,12 @@ export type GhostPipeAgentErrandRequest =
mode?: 'wait';
/** 归因号(tool-call 触发时把 callId 原样带上;同 cindy-request 语义)。 */
callId?: string;
+ /**
+ * 可选:把 `card-action` 事件里主机签发的点击票原样带上。
+ * 主机校验通过才把这次派活当成用户发起并切到 errand 任务;
+ * 票一次性消费,不能再拿去 agent.run 或再派一次。
+ */
+ userActionToken?: string;
}
| {
type: 'agent-errand-request';