Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 将协同任务切换归一到主任务
DavidShen39afea78d6ce
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.tsindex 8d9a518b1d..d3ba5aac86 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts@@ -13,11 +13,14 @@ import {GhostTapPendingQueue,GhostTurnOriginTracker,GhostTurnTranslator,+ createGhostPrimarySessionFocusTracker,createGhostSessionFocusTracker,ghostActivityId,isGhostEligibleSessionRow,+ isGhostSessionSwitchEligibleRow,normalizeTurnUsage,readStatusIsRunning,+ resolveGhostPrimarySessionId,resolveGhostUserHookModel,withGhostAssistantHookModel,withGhostUserHookModel,@@ -31,6 +34,161 @@ import {type InstalledGhost,} from '../../../shared/ghost';+describe('did-session-switched primary session resolution', () => {+ it('allows ordinary sessions and Orca leads, but never workers or background sessions', () => {+ expect(isGhostSessionSwitchEligibleRow({ source: 'desktop', orcaRole: null })).toBe(true);+ expect(isGhostSessionSwitchEligibleRow({ source: 'shared', orcaRole: 'lead' })).toBe(true);+ expect(isGhostSessionSwitchEligibleRow({ source: 'plugin', orcaRole: 'lead' })).toBe(true);+ expect(isGhostSessionSwitchEligibleRow({ source: 'desktop', orcaRole: 'worker' })).toBe(false);+ expect(isGhostSessionSwitchEligibleRow({ source: 'desktop', orcaRole: 'unknown' })).toBe(false);+ expect(isGhostSessionSwitchEligibleRow({ source: 'scheduler', orcaRole: null })).toBe(false);+ });++ it('keeps ordinary and lead ids, and maps a worker to its lead', async () => {+ const roles = new Map<string, string | null>([+ ['ordinary', null],+ ['lead', 'lead'],+ ['worker', 'worker'],+ ]);+ const readSession = vi.fn(async (sessionId: string) =>+ roles.has(sessionId) ? { orcaRole: roles.get(sessionId) } : null,+ );+ const resolveWorkerLead = vi.fn(async () => 'lead');++ await expect(+ resolveGhostPrimarySessionId('ordinary', readSession, resolveWorkerLead),+ ).resolves.toBe('ordinary');+ await expect(resolveGhostPrimarySessionId('lead', readSession, resolveWorkerLead)).resolves.toBe(+ 'lead',+ );+ await expect(+ resolveGhostPrimarySessionId('worker', readSession, resolveWorkerLead),+ ).resolves.toBe('lead');+ expect(resolveWorkerLead).toHaveBeenCalledTimes(1);+ expect(resolveWorkerLead).toHaveBeenCalledWith('worker');+ });++ it('fails closed for missing rows, unknown roles, missing teams, and lookup failures', async () => {+ const noTeam = vi.fn(async () => null);+ await expect(+ resolveGhostPrimarySessionId('missing', async () => null, noTeam),+ ).resolves.toBeNull();+ await expect(+ resolveGhostPrimarySessionId('unknown', async () => ({ orcaRole: 'unknown' }), noTeam),+ ).resolves.toBeNull();+ await expect(+ resolveGhostPrimarySessionId('worker', async () => ({ orcaRole: 'worker' }), noTeam),+ ).resolves.toBeNull();+ await expect(+ resolveGhostPrimarySessionId(+ 'worker',+ async () => {+ throw new Error('db unavailable');+ },+ noTeam,+ ),+ ).resolves.toBeNull();+ });+});++describe('createGhostPrimarySessionFocusTracker', () => {+ it('deduplicates different workers that resolve to the same lead', async () => {+ const published: string[] = [];+ const notify = vi.fn(async (sessionId: string, claim: () => Promise<boolean>) => {+ if (await claim()) published.push(sessionId);+ });+ const tracker = createGhostPrimarySessionFocusTracker(async () => 'lead', notify);++ tracker.note('worker-1');+ await vi.waitFor(() => expect(published).toEqual(['lead']));+ tracker.note('worker-2');+ await Promise.resolve();++ expect(published).toEqual(['lead']);+ });++ it('ignores a stale async resolution after focus changes', async () => {+ let resolveFirst!: (sessionId: string | null) => void;+ let resolveSecond!: (sessionId: string | null) => void;+ const first = new Promise<string | null>((resolve) => {+ resolveFirst = resolve;+ });+ const second = new Promise<string | null>((resolve) => {+ resolveSecond = resolve;+ });+ const resolve = vi.fn((sessionId: string) => (sessionId === 'worker-1' ? first : second));+ const published: string[] = [];+ const notify = vi.fn(async (sessionId: string, claim: () => Promise<boolean>) => {+ if (await claim()) published.push(sessionId);+ });+ const tracker = createGhostPrimarySessionFocusTracker(resolve, notify);++ tracker.note('worker-1');+ tracker.note('worker-2');+ resolveSecond('lead-2');+ await vi.waitFor(() => expect(published).toEqual(['lead-2']));+ resolveFirst('lead-1');+ await Promise.resolve();++ expect(published).toEqual(['lead-2']);+ });++ it('claims publication at the final async boundary', async () => {+ const pending: Array<{ sessionId: string; claim: () => Promise<boolean> }> = [];+ const tracker = createGhostPrimarySessionFocusTracker(async () => 'lead', (sessionId, claim) => {+ pending.push({ sessionId, claim });+ });++ tracker.note('worker-1');+ await vi.waitFor(() => expect(pending).toHaveLength(1));+ tracker.note('worker-2');+ await vi.waitFor(() => expect(pending).toHaveLength(2));++ await expect(pending[0]?.claim()).resolves.toBe(false);+ await expect(pending[1]?.claim()).resolves.toBe(true);+ await expect(pending[1]?.claim()).resolves.toBe(false);+ });++ it('rejects a lead mapping that changes before publication', async () => {+ let currentLead = 'lead-1';+ const pending: Array<{ sessionId: string; claim: () => Promise<boolean> }> = [];+ const tracker = createGhostPrimarySessionFocusTracker(+ async () => currentLead,+ (sessionId, claim) => pending.push({ sessionId, claim }),+ );++ tracker.note('worker');+ await vi.waitFor(() => expect(pending).toHaveLength(1));+ currentLead = 'lead-2';++ expect(pending[0]?.sessionId).toBe('lead-1');+ await expect(pending[0]?.claim()).resolves.toBe(false);+ });++ it('clears deduplication when focus leaves the session or resolution fails', async () => {+ const published: string[] = [];+ const notify = vi.fn(async (sessionId: string, claim: () => Promise<boolean>) => {+ if (await claim()) published.push(sessionId);+ });+ const tracker = createGhostPrimarySessionFocusTracker(+ async (sessionId) => (sessionId === 'hidden-worker' ? null : 'lead'),+ notify,+ );++ tracker.note('worker');+ await vi.waitFor(() => expect(published).toHaveLength(1));+ tracker.note(null);+ tracker.note('lead');+ await vi.waitFor(() => expect(published).toHaveLength(2));+ tracker.note('hidden-worker');+ await Promise.resolve();+ tracker.note('lead');+ await vi.waitFor(() => expect(published).toHaveLength(3));++ expect(published).toEqual(['lead', 'lead', 'lead']);+ });+});+function ghost(id: string,subscribe: { topics?: string[]; hooks?: string[] } | undefined,diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex e407b7187c..af6f65a5ca 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -240,7 +240,8 @@ import {import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';-import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';+import { getSessionFsSnapshot, getSessionRowSnapshot } from '../localDb/ipc/sessions.js';+import { getTeamByWorkerSession } from '../localDb/orcaTeamStore.js';import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';import { readInstalledGhostManifest } from '../installedGhostManifest.js';import {@@ -252,10 +253,13 @@ import {GhostSubscriptionGateway,GhostActivityTracker,GhostTurnTranslator,+ createGhostPrimarySessionFocusTracker,createGhostSessionFocusTracker,GhostTapPendingQueue,GhostTurnOriginTracker,isGhostEligibleSessionRow,+ isGhostSessionSwitchEligibleRow,+ resolveGhostPrimarySessionId,type GhostInteractionActivityKind,type GhostScreenResult,type MinimalAgentEvent,@@ -1383,8 +1387,8 @@ export function getGhostSubscriptionGateway(): GhostSubscriptionGateway {}/**- * 会话是否在订阅事件的投递范围(用户主会话:desktop/shared 来源、非 orca;- * 行级判定见 subscriptionGateway.isGhostEligibleSessionRow)。+ * 会话是否在订阅事件的投递范围。默认只允许非 Orca 用户主任务;session-switch+ * 额外允许已归一后的 Orca Lead,行级判定见 subscriptionGateway。* outcome 三值:eligible / ineligible(查到行且明确不合格,可终身缓存)/* retry(DB 未就绪、查询抛错、行还没落库——都是暂时态,调用方稍后重试;* 2026-07-12 实测:启动期会话接线早于 DbClient 就绪,一次性判定会把@@ -1392,6 +1396,7 @@ export function getGhostSubscriptionGateway(): GhostSubscriptionGateway {*/async function isGhostEligibleSession(sessionId: string,+ scope: 'default' | 'session-switch' = 'default',): Promise<| { outcome: 'eligible'; agentKind?: string; workdir?: string }| { outcome: 'ineligible' }@@ -1412,7 +1417,11 @@ async function isGhostEligibleSession(.limit(1);const row = rows[0];if (!row) return { outcome: 'retry' }; // 行未落库(极早期)→ 暂时态- if (isGhostEligibleSessionRow(row)) {+ const isEligible =+ scope === 'session-switch'+ ? isGhostSessionSwitchEligibleRow(row)+ : isGhostEligibleSessionRow(row);+ if (isEligible) {return {outcome: 'eligible',agentKind: row.agentKind ?? undefined,@@ -1850,6 +1859,7 @@ export function runGhostAssistantReplyHook(export function notifyGhostSessionEvent(kind: 'created' | 'archived' | 'switched',data: { sessionId: string; workdir?: string },+ shouldPublish: () => boolean | Promise<boolean> = () => true,): void {void (async () => {try {@@ -1858,9 +1868,12 @@ export function notifyGhostSessionEvent((g) => g.enabled && g.manifest.subscribe?.topics?.includes('session'),);if (!hasSubscriber) return;- // 投递范围与 turn 事件同口径:只投用户主会话(retry 视为不投,- // 生命周期事件不值得重试机制)。- const info = await isGhostEligibleSession(data.sessionId);+ // created / archived 与 turn 事件同口径;switched 额外允许归一后的 Orca Lead。+ // retry 视为不投,生命周期事件不值得引入重试机制。+ const info = await isGhostEligibleSession(+ data.sessionId,+ kind === 'switched' ? 'session-switch' : 'default',+ );if (info.outcome !== 'eligible') return;// switched 的调用方(renderer 路由上报)只有 sessionId,workdir 从资格// 查询顺手补上,与 created/archived 的载荷形状对齐。@@ -1868,6 +1881,8 @@ export function notifyGhostSessionEvent(data.workdir === undefined && info.workdir !== undefined? { ...data, workdir: info.workdir }: data;+ // switched 在异步归一、资格查询完成后再确认一次焦点代次;确认与去重在同一步完成。+ if (!(await shouldPublish())) return;getGhostSubscriptionGateway().publish('session',kind === 'created'@@ -1885,13 +1900,24 @@ export function notifyGhostSessionEvent(/*** 会话切换上报入口(renderer MainLayout 路由 effect 经 'ghosts:session-focused'- * 调,平台无关):去重后发 did-session-switched。连续同 id / 非会话页(null)- * 不发;切走再切回算新切换(去重语义见 createGhostSessionFocusTracker)。+ * 调,平台无关):Worker 归一到 Lead 后发 did-session-switched。连续指向同一主任务 / 非会话页+ * (null)不发;切走再切回算新切换。原始焦点仍单独保留给旧 preview 缺省落点。*/+const ghostPrimarySessionFocusTracker = createGhostPrimarySessionFocusTracker(+ (sessionId) =>+ resolveGhostPrimarySessionId(+ sessionId,+ getSessionRowSnapshot,+ async (workerSessionId) =>+ (await getTeamByWorkerSession(workerSessionId))?.leadSessionId ?? null,+ ),+ (sessionId, claim) => notifyGhostSessionEvent('switched', { sessionId }, claim),+);const ghostSessionFocusTracker = createGhostSessionFocusTracker((sessionId) =>- notifyGhostSessionEvent('switched', { sessionId }),+ ghostPrimarySessionFocusTracker.note(sessionId),);export function noteGhostSessionFocused(sessionId: string | null): void {+ if (sessionId === null) ghostPrimarySessionFocusTracker.note(null);ghostSessionFocusTracker.note(sessionId);}diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex 5b7ff343fa..46f1231173 100644--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@ -564,6 +564,40 @@ export function isGhostEligibleSessionRow(row: {return (row.source === 'desktop' || row.source === 'shared' || row.source === 'plugin') && row.orcaRole == null;}+/** did-session-switched 可投递 Orca Lead,但绝不暴露 Worker。 */+export function isGhostSessionSwitchEligibleRow(row: {+ source: string | null | undefined;+ orcaRole: string | null | undefined;+}): boolean {+ return (+ (row.source === 'desktop' || row.source === 'shared' || row.source === 'plugin') &&+ (row.orcaRole == null || row.orcaRole === 'lead')+ );+}++/** 将焦点任务归一为用户可见的主任务;无法可靠归一时静默丢弃。 */+export async function resolveGhostPrimarySessionId(+ sessionId: string,+ readSession: (+ sessionId: string,+ ) => Promise<{ orcaRole?: string | null } | null>,+ resolveWorkerLead: (workerSessionId: string) => Promise<string | null>,+): Promise<string | null> {+ try {+ const row = await readSession(sessionId);+ if (!row) return null;+ if (row.orcaRole == null || row.orcaRole === 'lead') return sessionId;+ if (row.orcaRole !== 'worker') return null;++ const leadSessionId = await resolveWorkerLead(sessionId);+ return typeof leadSessionId === 'string' && leadSessionId.length > 0+ ? leadSessionId+ : null;+ } catch {+ return null;+ }+}+/*** 会话切换去重器(did-session-switched 的入口滤波,抽成工厂便于单测):* renderer 的路由 effect 每次路由变化都上报"当前台前会话"(路由重渲/非会话@@ -587,6 +621,53 @@ export function createGhostSessionFocusTracker(};}+/**+ * did-session-switched 的异步焦点归一器:只接受最新一次归一结果,并在+ * Worker -> Lead 归一之后去重。+ */+export function createGhostPrimarySessionFocusTracker(+ resolve: (sessionId: string) => Promise<string | null>,+ notify: (sessionId: string, claim: () => Promise<boolean>) => void,+): { note(sessionId: string | null): void } {+ let lastRawSessionId: string | null = null;+ let lastPrimarySessionId: string | null = null;+ let generation = 0;++ return {+ note(sessionId) {+ if (sessionId === lastRawSessionId) return;+ lastRawSessionId = sessionId;+ const currentGeneration = ++generation;++ if (sessionId === null) {+ lastPrimarySessionId = null;+ return;+ }++ void resolve(sessionId)+ .then((primarySessionId) => {+ if (currentGeneration !== generation) return;+ if (primarySessionId === null) {+ lastPrimarySessionId = null;+ return;+ }+ notify(primarySessionId, async () => {+ if (currentGeneration !== generation) return false;+ // Team 归属也可能在首次解析后变化;发布前重新解析,绝不投递过期 Lead。+ if ((await resolve(sessionId)) !== primarySessionId) return false;+ if (currentGeneration !== generation) return false;+ if (primarySessionId === lastPrimarySessionId) return false;+ lastPrimarySessionId = primarySessionId;+ return true;+ });+ })+ .catch(() => {+ if (currentGeneration === generation) lastPrimarySessionId = null;+ });+ },+ };+}+/* ── 会话事件翻译器(AgentEvent → did-turn-*)────────────────────────────* maker-core 没有独立的 turn_start/turn_end 事件:turn 生命周期由 status* (data.isRunning 翻转)+ done / terminal error 携带。本翻译器把它折叠成