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(bots): 伙伴工作台——把本机项目交给伙伴,伙伴随时知道项目事务并按主人的意思跟进 (#5292)

Chris Zhangeac952c9605d
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionImportDirFacts.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionImportDirFacts.test.ts
new file mode 100644
index 0000000000..eb86beb018
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionImportDirFacts.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createGitRepoProbe } from '../sessionImportDirFacts.js';
+
+describe('createGitRepoProbe', () => {
+ it('stats each unique directory once and reports only git repositories', async () => {
+ const statExists = vi.fn(async (target: string) => target.startsWith('/w/repo'));
+ const probe = createGitRepoProbe(statExists);
+ expect(await probe(['/w/repo', '/w/plain', '/w/repo', ''])).toEqual(['/w/repo']);
+ expect(await probe(['/w/plain', '/w/repo'])).toEqual(['/w/repo']);
+ expect(statExists).toHaveBeenCalledTimes(2);
+ expect(statExists.mock.calls.map(([target]) => target.replace(/\\/g, '/'))).toEqual(['/w/repo/.git', '/w/plain/.git']);
+ });
+
+ it('checks a directory again after five minutes, so a newly created or removed repo is noticed', async () => {
+ let now = 0;
+ let isRepo = false;
+ const statExists = vi.fn(async () => isRepo);
+ const probe = createGitRepoProbe(statExists, () => now);
+ expect(await probe(['/w/app'])).toEqual([]);
+ isRepo = true;
+ now = 4 * 60_000;
+ expect(await probe(['/w/app'])).toEqual([]);
+ now = 5 * 60_000;
+ expect(await probe(['/w/app'])).toEqual(['/w/app']);
+ expect(statExists).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 1082736720..a7d78b4664 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -60,6 +60,16 @@ import {
import { syncBotProfileFromFolder } from '../../maker-ipc/botProfileFolderSync.js';
import { requestBotRuntimeEpochRefresh } from '../../maker-ipc/botRuntimeEpochRefreshSignal.js';
import { createLogger } from '../../logger.js';
+import {
+ addBotWorkbenchDirectory,
+ broadcastBotWorkbenchChanged,
+ readBotWorkbench,
+ removeBotWorkbenchDirectory,
+} from '../../maker-ipc/botWorkbenchService.js';
+import {
+ listBotWorkbenchCandidatesForOwner,
+ readBotWorkbenchTaskForOwner,
+} from '../../maker-ipc/botWorkbenchTools.js';
import {
NEW_BOT_DEFAULT_PI_EFFORT,
NEW_BOT_DEFAULT_PI_MODEL,
@@ -2086,6 +2096,53 @@ export function registerBotIpc(): void {
owner.assertCurrent();
return result;
};
+ ipcMain.handle('local-db:bots:workbench:get', async (event, rawBotId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const botId = readText(rawBotId, 'botId', 128, true);
+ const owner = captureBotOperationOwner();
+ const workbench = await readBotWorkbench(owner.userDataDir, botId);
+ owner.assertCurrent();
+ return workbench;
+ });
+ ipcMain.handle('local-db:bots:workbench:add-directory', async (event, rawBotId: unknown, rawPath: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const botId = readText(rawBotId, 'botId', 128, true);
+ const dirPath = readText(rawPath, 'path', 4096, true);
+ const owner = captureBotOperationOwner();
+ const result = await addBotWorkbenchDirectory(owner.userDataDir, botId, dirPath);
+ owner.assertCurrent();
+ if (result.ok) broadcastBotWorkbenchChanged(botId);
+ return result;
+ });
+ // 工作台详情视图:只读一件任务的最近内容(有界)。范围限于该伙伴已接手的项目,
+ // 外部会话只读转录尾部,不写库、不导入。
+ ipcMain.handle('local-db:bots:workbench:read-task', async (event, rawBotId: unknown, rawTaskId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const botId = readText(rawBotId, 'botId', 128, true);
+ const taskId = readText(rawTaskId, 'taskId', 256, true);
+ const owner = captureBotOperationOwner();
+ const result = await readBotWorkbenchTaskForOwner(botId, taskId);
+ owner.assertCurrent();
+ return result;
+ });
+ // 工作台:已接手项目里近期本机会话的 id 与最近活动(只读、按项目过滤、只看近期)。
+ ipcMain.handle('local-db:bots:workbench:candidates', async (event, rawBotId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const botId = readText(rawBotId, 'botId', 128, true);
+ const owner = captureBotOperationOwner();
+ const result = await listBotWorkbenchCandidatesForOwner(botId);
+ owner.assertCurrent();
+ return result;
+ });
+ ipcMain.handle('local-db:bots:workbench:remove-directory', async (event, rawBotId: unknown, rawPath: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const botId = readText(rawBotId, 'botId', 128, true);
+ const dirPath = readText(rawPath, 'path', 4096, true);
+ const owner = captureBotOperationOwner();
+ await removeBotWorkbenchDirectory(owner.userDataDir, botId, dirPath);
+ owner.assertCurrent();
+ broadcastBotWorkbenchChanged(botId);
+ });
// Local settings read; remote clients already use settings:<botId>/skills.
ipcMain.handle('local-db:bots:skills:list', async (event, rawBotId: unknown) => {
assertTrustedAppRendererEvent(event);
diff --git a/apps/desktop/src/main/localDb/ipc/session-import.ts b/apps/desktop/src/main/localDb/ipc/session-import.ts
index 3a70c3fbbb..4882a056bb 100644
--- a/apps/desktop/src/main/localDb/ipc/session-import.ts
+++ b/apps/desktop/src/main/localDb/ipc/session-import.ts
@@ -5,7 +5,7 @@
* explicitly selects sessions and confirms import in Settings.
*/
-import { ipcMain } from 'electron';
+import { app, ipcMain } from 'electron';
import { getCurrentDbClientUserId, getDbClient } from '../client/current.js';
import { createLogger } from '../../logger.js';
@@ -19,6 +19,11 @@ import {
scanExternalClaudeCodeSessions,
} from '../../maker-host/claude-local-sessions.js';
import { dialogueWorkspaceRoots } from '../dialogueWorkspace.js';
+import {
+ createGitRepoProbe,
+ readSessionImportPathHints,
+ type SessionImportPathHints,
+} from './sessionImportDirFacts.js';
import {
normalizeWorkingDirForGrouping,
normalizeWorkingDirForStorage,
@@ -54,6 +59,10 @@ interface SessionImportScanResult {
existing: number;
};
currentProjectDirs: string[];
+ /** 候选与本机已有项目里是 git 仓库的目录(只 stat `.git`,按目录缓存)。 */
+ gitRepoDirs: string[];
+ /** 主目录、应用数据目录、系统临时目录:伙伴工作台不把它们当成用户项目。 */
+ pathHints: SessionImportPathHints;
}
interface SessionImportRequest {
@@ -69,6 +78,7 @@ interface CodexProjectLinkRequest {
}
const SESSION_IMPORT_SCAN_CACHE_TTL_MS = 30_000;
+const probeGitRepoDirs = createGitRepoProbe();
let cachedSessionImportScan: { scope: string; result: SessionImportScanResult; expiresAt: number } | null = null;
let inFlightSessionImportScan: {
@@ -248,6 +258,12 @@ async function runSessionImportScan(): Promise<SessionImportScanResult> {
}),
].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
+ const gitRepoDirs = await probeGitRepoDirs([
+ ...currentProjectDirs,
+ ...candidates.flatMap((item) => (item.projectDir ? [item.projectDir] : [])),
+ ]);
+ const pathHints = await readSessionImportPathHints(safeUserDataDir());
+
log.info('session import scan complete', {
codexHomes: codex.homes.length,
claudeRoots: claude.roots.length,
@@ -270,10 +286,20 @@ async function runSessionImportScan(): Promise<SessionImportScanResult> {
existing: existingCount,
},
currentProjectDirs: [...currentProjectDirs].sort(),
+ gitRepoDirs,
+ pathHints,
};
}
-function invalidateSessionImportScanCache(): void {
+function safeUserDataDir(): string | null {
+ try {
+ return normalizeWorkingDirForStorage(app.getPath('userData'));
+ } catch {
+ return null;
+ }
+}
+
+export function invalidateSessionImportScanCache(): void {
sessionImportScanCacheVersion += 1;
cachedSessionImportScan = null;
inFlightSessionImportScan = null;
diff --git a/apps/desktop/src/main/localDb/ipc/sessionImportDirFacts.ts b/apps/desktop/src/main/localDb/ipc/sessionImportDirFacts.ts
new file mode 100644
index 0000000000..773b864889
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/sessionImportDirFacts.ts
@@ -0,0 +1,60 @@
+/**
+ * 本机项目目录的轻量事实,给伙伴工作台的项目清单分档用。
+ *
+ * 只 stat `<dir>/.git` 是否存在(文件或目录都算:worktree / submodule 的 .git 是文件),
+ * 不读任何文件内容;结果按目录缓存 5 分钟,之后重新 stat(用户可能刚 init 或删了仓库)。
+ */
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+const MAX_CACHED_DIRS = 4_096;
+const PROBE_TTL_MS = 5 * 60_000;
+
+export type StatExists = (target: string) => Promise<boolean>;
+
+const defaultStatExists: StatExists = async (target) => {
+ try {
+ await fs.stat(target);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+export function createGitRepoProbe(statExists: StatExists = defaultStatExists, now: () => number = Date.now) {
+ const cache = new Map<string, { isRepo: boolean; at: number }>();
+ return async function gitRepoDirs(dirs: Iterable<string>): Promise<string[]> {
+ const unique = [...new Set([...dirs].filter(Boolean))];
+ const results = await Promise.all(
+ unique.map(async (dir) => {
+ const cached = cache.get(dir);
+ if (cached && now() - cached.at < PROBE_TTL_MS) return [dir, cached.isRepo] as const;
+ const isRepo = await statExists(path.join(dir, '.git'));
+ if (cache.size >= MAX_CACHED_DIRS) cache.clear();
+ cache.set(dir, { isRepo, at: now() });
+ return [dir, isRepo] as const;
+ }),
+ );
+ return results.filter(([, isRepo]) => isRepo).map(([dir]) => dir).sort();
+ };
+}
+
+/** 渲染层过滤「不像用户项目」的目录要用到的本机路径;只给路径,不给内容。 */
+export interface SessionImportPathHints {
+ homeDir: string | null;
+ userDataDir: string | null;
+ tempDirs: string[];
+}
+
+export async function readSessionImportPathHints(userDataDir: string | null): Promise<SessionImportPathHints> {
+ const tempDirs = new Set<string>();
+ const tmp = os.tmpdir();
+ tempDirs.add(tmp);
+ try {
+ tempDirs.add(await fs.realpath(tmp));
+ } catch {
+ // realpath 失败时保留原值即可。
+ }
+ return { homeDir: os.homedir() || null, userDataDir, tempDirs: [...tempDirs] };
+}
diff --git a/apps/desktop/src/main/maker-host/codex-account-auth.ts b/apps/desktop/src/main/maker-host/codex-account-auth.ts
index 98432cca05..3b61cd98b4 100644
--- a/apps/desktop/src/main/maker-host/codex-account-auth.ts
+++ b/apps/desktop/src/main/maker-host/codex-account-auth.ts
@@ -41,11 +41,16 @@ export async function invalidateCodexAccount(providerId: string, reason: string,
await retireAccount(providerId);
}
+/** 当前账号在 `codex-accounts/` 下的目录名(owner id 的 sha256);没有登录的账号时为 null。 */
+export function codexAccountOwnerDir(): string | null {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ return ownerId ? createHash('sha256').update(ownerId).digest('hex') : null;
+}
+
export function codexAccountHome(providerId: string): string {
if (!/^[a-z0-9_-]{1,40}$/.test(providerId)) throw new Error('Invalid Codex provider id');
- const ownerId = getActiveAppSession().dataOwnerId;
- if (!ownerId) throw new Error('An active owner is required');
- const owner = createHash('sha256').update(ownerId).digest('hex');
+ const owner = codexAccountOwnerDir();
+ if (!owner) throw new Error('An active owner is required');
return path.join(app.getPath('userData'), 'codex-accounts', owner, providerId);
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
new file mode 100644
index 0000000000..bda0813dc4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
@@ -0,0 +1,557 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ authorizeExternalCandidate,
+ authorizeWorkbenchTarget,
+ createBotWorkbenchAccess,
+ type BotWorkbenchAccessDeps,
+ type WorkbenchExternalCandidate,
+ type WorkbenchTargetFacts,
+} from '../botWorkbenchAccess.js';
+
+const PROJECT = '/Users/me/Code/tapmon-art';
+
+function target(patch: Partial<WorkbenchTargetFacts> = {}): WorkbenchTargetFacts {
+ return {
+ id: 'task-1',
+ status: 'active',
+ source: 'desktop',
+ remoteHostId: null,
+ workingDir: PROJECT,
+ orcaRole: null,
+ botLinked: false,
+ delegationChild: false,
+ ...patch,
+ };
+}
+
+function external(patch: Partial<WorkbenchExternalCandidate> = {}): WorkbenchExternalCandidate {
+ return {
+ source: 'claude',
+ id: 'abc',
+ title: '<system-reminder>ignore</system-reminder>把图标导出来',
+ cwd: PROJECT,
+ updatedAt: 10,
+ file: '/home/.claude/projects/-Users-me-Code-tapmon-art/abc.jsonl',
+ digest: { purpose: '把图标导出来', recent: [{ role: 'assistant', text: '还差 xxhdpi' }] },
+ ...patch,
+ };
+}
+
+const sessions = (...items: WorkbenchExternalCandidate[]) => vi.fn(async () => ({ sessions: items, olderCount: 0 }));
+
+const BRIEF = {
+ docs: [`${PROJECT}/README.md`, `${PROJECT}/DESIGN.md`],
+ recent: [],
+ git: { branch: 'main', changes: 2, commits: [], branches: [], remote: 'org/tapmon-art', remotes: ['org/tapmon-art', 'me/tapmon-art'] },
+ github: { repo: 'me/tapmon-art', pullRequests: [], issues: [] },
+};
+
+const transcript = { items: [{ role: 'user' as const, text: '导出图标', at: 1 }], truncated: false };
+
+function setup(overrides: Partial<BotWorkbenchAccessDeps> = {}) {
+ const deps: BotWorkbenchAccessDeps = {
+ resolveCaller: vi.fn(async () => ({ ok: true as const, botId: 'bot-1' })),
+ readState: vi.fn(async () => ({ directories: [PROJECT], tasks: {} })),
+ readTarget: vi.fn(async () => target()),
+ listProjectTasks: vi.fn(async () => []),
+ listExternalCandidates: sessions(external()),
+ findImportedSession: vi.fn(async () => null),
+ importExternal: vi.fn(async () => ({ ok: true as const, sessionId: 'claude-abc' })),
+ startBackgroundTask: vi.fn(async () => ({ ok: true as const, sessionId: 'child-1' })),
+ readSessionDigest: vi.fn(async () => ({ purpose: '导出图标', recent: [] })),
+ readBrief: vi.fn(async () => BRIEF),
+ listDelegations: vi.fn(async () => new Map()),
+ readActivityPhase: vi.fn(async () => null),
+ listRoutines: vi.fn(async () => []),
+ listSchedules: vi.fn(async () => []),
+ readSessionTranscript: vi.fn(async () => transcript),
+ readExternalTranscript: vi.fn(async () => transcript),
+ saveJudgment: vi.fn(async (_botId, _taskId, judgment) => ({ ...judgment, updatedAt: '2026-10-01T00:00:00.000Z' })),
+ rekeyJudgment: vi.fn(async () => undefined),
+ deleteJudgment: vi.fn(async () => undefined),
+ notifyChanged: vi.fn(),
+ sendToSession: vi.fn(async () => ({ ok: true as const, wakeKind: 'queued', queuedMessageId: 'q-1' })),
+ stopSessionTurn: vi.fn(async () => ({ ok: true as const, status: 'requested' as const })),
+ caseInsensitive: false,
+ ...overrides,
+ };
+ return { deps, access: createBotWorkbenchAccess(deps) };
+}
+
+describe('authorizeWorkbenchTarget', () => {
+ it('allows an ordinary local task inside a handed-over project, including its worktrees', () => {
+ expect(authorizeWorkbenchTarget(target(), [PROJECT], false)).toEqual({ ok: true, projectDir: PROJECT });
+ expect(
+ authorizeWorkbenchTarget(target({ workingDir: `${PROJECT}/.cindy-worktrees/fix-icons` }), [PROJECT], false),
+ ).toEqual({ ok: true, projectDir: PROJECT });
+ });
+
+ it.each([
+ ['missing', null, 'TASK_NOT_FOUND'],
+ ['deleted', target({ status: 'deleted' }), 'TASK_NOT_FOUND'],
+ ['a Bot hidden session (link row)', target({ botLinked: true }), 'TASK_NOT_ACCESSIBLE'],
+ ['a Bot hidden session (source)', target({ source: 'bot' }), 'TASK_NOT_ACCESSIBLE'],
+ ['remote', target({ remoteHostId: 'ssh-1' }), 'TASK_REMOTE'],
+ ['archived', target({ status: 'archived' }), 'TASK_ARCHIVED'],
+ ['a background task', target({ delegationChild: true }), 'TASK_IS_BACKGROUND_TASK'],
+ ['an automation run', target({ source: 'scheduler' }), 'TASK_NOT_SUPPORTED'],
+ ['an IM channel task', target({ source: 'telegram' }), 'TASK_NOT_SUPPORTED'],
+ ['an Orca worker', target({ orcaRole: 'worker' }), 'TASK_NOT_SUPPORTED'],
+ ['outside the project', target({ workingDir: '/Users/me/Code/other' }), 'TASK_OUTSIDE_WORKBENCH'],
+ ['a sibling folder sharing the prefix', target({ workingDir: `${PROJECT}-old` }), 'TASK_OUTSIDE_WORKBENCH'],
+ ['a dialogue task without a directory', target({ workingDir: null }), 'TASK_OUTSIDE_WORKBENCH'],
+ ])('rejects %s', (_label, facts, errorCode) => {
+ expect(authorizeWorkbenchTarget(facts, [PROJECT], false)).toMatchObject({ ok: false, errorCode });
+ });
+
+ it('folds case only on case-insensitive platforms', () => {
+ const upper = target({ workingDir: 'C:/Code/Tapmon' });
+ expect(authorizeWorkbenchTarget(upper, ['C:/code/tapmon'], true)).toMatchObject({ ok: true });
+ expect(authorizeWorkbenchTarget(upper, ['C:/code/tapmon'], false)).toMatchObject({ ok: false });
+ });
+});
+
+describe('authorizeExternalCandidate', () => {
+ it('only accepts sessions whose cwd is inside a handed-over project', () => {
+ expect(authorizeExternalCandidate(external(), [PROJECT], false)).toEqual({ ok: true, projectDir: PROJECT });
+ expect(authorizeExternalCandidate(null, [PROJECT], false)).toMatchObject({ errorCode: 'TASK_NOT_FOUND' });
+ expect(authorizeExternalCandidate(external({ cwd: '/Users/me/Code/other' }), [PROJECT], false)).toMatchObject({
+ errorCode: 'TASK_OUTSIDE_WORKBENCH',
+ });
+ });
+});
+
+describe('workbench read / set', () => {
+ it('reads an external session tail without importing it', async () => {
+ const { deps, access } = setup();
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'claude:abc' }))
+ .resolves.toEqual({ ok: true, taskId: 'claude:abc', transcript });
+ expect(deps.readExternalTranscript).toHaveBeenCalledWith(expect.objectContaining({ source: 'claude', id: 'abc' }));
+ expect(deps.importExternal).not.toHaveBeenCalled();
+ });
+
+ it('refuses to read an external session whose cwd is outside the handed-over projects', async () => {
+ const { deps, access } = setup({ listExternalCandidates: sessions(external({ cwd: '/elsewhere' })) });
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'claude:abc' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ expect(deps.readExternalTranscript).not.toHaveBeenCalled();
+ });
+
+ it('treats an already imported external id as the Cindy task it became', async () => {
+ const { deps, access } = setup({
+ listExternalCandidates: sessions(),
+ findImportedSession: vi.fn(async () => 'claude-abc'),
+ });
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'claude:abc' }))
+ .resolves.toMatchObject({ ok: true, taskId: 'claude-abc' });
+ expect(deps.readTarget).toHaveBeenCalledWith('claude-abc');
+ });
+
+ it('saves a judgment with the project it belongs to and notifies the workbench', async () => {
+ const { deps, access } = setup();
+ await expect(
+ access.set({
+ callerSessionId: 'bot-main',
+ taskId: 'claude:abc',
+ title: ' 导出 Android 图标 ',
+ verdict: 'unfinished',
+ next: '把 xxhdpi 补完',
+ }),
+ ).resolves.toMatchObject({ ok: true, taskId: 'claude:abc', judgment: { verdict: 'unfinished' } });
+ expect(deps.saveJudgment).toHaveBeenCalledWith('bot-1', 'claude:abc', {
+ title: '导出 Android 图标',
+ verdict: 'unfinished',
+ next: '把 xxhdpi 补完',
+ project: PROJECT,
+ ref: null,
+ });
+ expect(deps.notifyChanged).toHaveBeenCalledWith('bot-1');
+ });
+
+ it('records PR, issue and idea entries against the project they belong to', async () => {
+ const { deps, access } = setup({ readState: vi.fn(async () => ({ directories: [PROJECT, '/Users/me/Code/other'], tasks: {} })) });
+ await expect(access.set({
+ callerSessionId: 'bot-main',
+ taskId: 'pr:me/tapmon-art#12',
+ title: '图标 PR',
+ verdict: 'unfinished',
+ next: '处理 review',
+ ref: 'https://github.com/me/tapmon-art/pull/12',
+ })).resolves.toMatchObject({ ok: true, taskId: 'pr:me/tapmon-art#12' });
+ expect(deps.saveJudgment).toHaveBeenLastCalledWith('bot-1', 'pr:me/tapmon-art#12', expect.objectContaining({
+ project: PROJECT,
+ ref: 'https://github.com/me/tapmon-art/pull/12',
+ }));
+ await expect(access.set({
+ callerSessionId: 'bot-main',
+ taskId: 'idea:dark-icons',
+ title: '暗色图标',
+ verdict: 'idea',
+ next: '按 DESIGN.md 补一套',
+ ref: `${PROJECT}/DESIGN.md`,
+ project: 'tapmon-art',
+ })).resolves.toMatchObject({ ok: true, taskId: 'idea:dark-icons' });
+ expect(deps.saveJudgment).toHaveBeenLastCalledWith('bot-1', 'idea:dark-icons', expect.objectContaining({
+ project: PROJECT,
+ ref: `${PROJECT}/DESIGN.md`,
+ }));
+ });
+
+ it.each([
+ ['a repo that is not a handed-over project', { taskId: 'pr:someone/else#1' }, 'TASK_OUTSIDE_WORKBENCH'],
+ ['a malformed idea slug', { taskId: 'idea:X' }, 'TASK_NOT_FOUND'],
+ ['an http link', { taskId: 'idea:dark-icons', ref: 'http://example.com' }, 'INVALID_REF'],
+ ['a path outside the project', { taskId: 'idea:dark-icons', ref: '/etc/passwd' }, 'INVALID_REF'],
+ ['a path escaping the project', { taskId: 'idea:dark-icons', ref: `${PROJECT}/../secret` }, 'INVALID_REF'],
+ ['a link with credentials', { taskId: 'idea:dark-icons', ref: 'https://u:[email protected]' }, 'INVALID_REF'],
+ ])('rejects %s', async (_label, patch, errorCode) => {
+ const { deps, access } = setup();
+ await expect(access.set({ callerSessionId: 'bot-main', title: 't', verdict: 'idea', next: 'n', ...patch }))
+ .resolves.toMatchObject({ ok: false, errorCode });
+ expect(deps.saveJudgment).not.toHaveBeenCalled();
+ });
+
+ it('asks which project an idea belongs to when several are handed over', async () => {
+ const { access } = setup({ readState: vi.fn(async () => ({ directories: [PROJECT, '/Users/me/Code/other'], tasks: {} })) });
+ await expect(access.set({ callerSessionId: 'bot-main', taskId: 'idea:dark-icons', title: 't', verdict: 'idea', next: 'n' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'PROJECT_REQUIRED' });
+ });
+
+ it('writes a batch item by item, reports each result and notifies once', async () => {
+ const { deps, access } = setup();
+ const result = await access.setMany({
+ callerSessionId: 'bot-main',
+ items: [
+ { taskId: 'claude:abc', title: '导出图标', verdict: 'unfinished', next: '补 xxhdpi' },
+ { taskId: 'idea:x', title: '坏 slug', verdict: 'idea', next: 'n' },
+ { taskId: 'task-1', title: '整理意见', verdict: 'done' },
+ ],
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ saved: 2,
+ results: [
+ { taskId: 'claude:abc', ok: true },
+ { taskId: 'idea:x', ok: false, errorCode: 'TASK_NOT_FOUND' },
+ { taskId: 'task-1', ok: true },
+ ],
+ });
+ expect(deps.notifyChanged).toHaveBeenCalledTimes(1);
+ expect(deps.listExternalCandidates).toHaveBeenCalledTimes(1);
+ });
+
+ it('caps a batch at 30 items', async () => {
+ const { deps, access } = setup();
+ const items = Array.from({ length: 31 }, (_, index) => ({ taskId: `t-${index}`, title: 't', verdict: 'done' }));
+ await expect(access.setMany({ callerSessionId: 'bot-main', items })).resolves.toMatchObject({ errorCode: 'INVALID_ARGS' });
+ expect(deps.saveJudgment).not.toHaveBeenCalled();
+ });
+
+ it.each<[Record<string, string>, string]>([
+ [{ title: '', verdict: 'done' }, 'empty title'],
+ [{ title: 'x'.repeat(41), verdict: 'done' }, 'long title'],
+ [{ title: '标题', verdict: 'maybe' }, 'unknown verdict'],
+ [{ title: '标题', verdict: 'idea', next: '' }, 'idea without next'],
+ [{ title: '标题', verdict: 'unfinished', next: 'x'.repeat(121) }, 'long next'],
+ ])('rejects invalid judgments (%j, %s)', async (patch) => {
+ const { deps, access } = setup();
+ await expect(access.set({ callerSessionId: 'bot-main', taskId: 'task-1', ...patch } as never))
+ .resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ expect(deps.saveJudgment).not.toHaveBeenCalled();
+ });
+
+ it('allows done without a next step', async () => {
+ const { deps, access } = setup();
+ await expect(access.set({ callerSessionId: 'bot-main', taskId: 'task-1', title: '整理意见', verdict: 'done' }))
+ .resolves.toMatchObject({ ok: true });
+ expect(deps.saveJudgment).toHaveBeenCalledWith('bot-1', 'task-1', expect.objectContaining({ next: null }));
+ });
+});
+
+describe('workbench continue / stop', () => {
+ it('continues a Cindy task through the existing send path, as the calling Bot', async () => {
+ const { deps, access } = setup();
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: ' 把导出做完 ' }))
+ .resolves.toEqual({ ok: true, taskId: 'task-1', delivery: 'queued', queuedMessageId: 'q-1' });
+ expect(deps.sendToSession).toHaveBeenCalledWith({
+ targetSessionId: 'task-1',
+ message: '把导出做完',
+ dispatcherSessionId: 'bot-main',
+ });
+ expect(deps.importExternal).not.toHaveBeenCalled();
+ });
+
+ it('imports only the one external session it continues and moves the judgment onto it', async () => {
+ const { deps, access } = setup({ readTarget: vi.fn(async () => target({ id: 'claude-abc' })) });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'claude:abc', message: '接着导出' }))
+ .resolves.toMatchObject({ ok: true, taskId: 'claude-abc', importedFrom: 'claude:abc' });
+ expect(deps.importExternal).toHaveBeenCalledWith('claude', 'abc');
+ expect(deps.rekeyJudgment).toHaveBeenCalledWith('bot-1', 'claude:abc', 'claude-abc');
+ expect(deps.sendToSession).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: 'claude-abc' }));
+ });
+
+ it('falls back to a background task with the session digest when the import fails', async () => {
+ const { deps, access } = setup({
+ listExternalCandidates: sessions(external({ source: 'codex' })),
+ importExternal: vi.fn(async () => ({ ok: false as const, errorCode: 'IMPORT_FAILED', message: 'nope' })),
+ });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'codex:abc', message: 'go' }))
+ .resolves.toMatchObject({ ok: true, taskId: 'child-1', startedFrom: 'codex:abc' });
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ expect(deps.rekeyJudgment).not.toHaveBeenCalled();
+ const call = vi.mocked(deps.startBackgroundTask).mock.calls[0]![0];
+ expect(call).toMatchObject({ callerSessionId: 'bot-main', workingDir: PROJECT });
+ expect(call.objective).toContain('go');
+ expect(call.objective).toContain('起始目的:把图标导出来');
+ expect(call.objective).toContain('还差 xxhdpi');
+ });
+
+ it('continues a Pi session as a background task, never importing it', async () => {
+ const { deps, access } = setup({ listExternalCandidates: sessions(external({ source: 'pi', id: 'p1' })) });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'pi:p1', message: '接着做' }))
+ .resolves.toMatchObject({ ok: true, taskId: 'child-1', startedFrom: 'pi:p1' });
+ expect(deps.importExternal).not.toHaveBeenCalled();
+ });
+
+ it('continues a PR or idea entry as a project background task and drops the entry', async () => {
+ const judgment = {
+ title: '暗色图标',
+ verdict: 'idea' as const,
+ next: '按 DESIGN.md 补一套',
+ project: PROJECT,
+ ref: `${PROJECT}/DESIGN.md`,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ };
+ const { deps, access } = setup({
+ readState: vi.fn(async () => ({ directories: [PROJECT], tasks: { 'idea:dark-icons': judgment } })),
+ });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'idea:dark-icons', message: '开始做' }))
+ .resolves.toEqual({ ok: true, taskId: 'child-1', delivery: 'started', startedFrom: 'idea:dark-icons' });
+ const call = vi.mocked(deps.startBackgroundTask).mock.calls[0]![0];
+ expect(call).toMatchObject({ workingDir: PROJECT, title: '暗色图标' });
+ expect(call.objective).toContain(`参考:${PROJECT}/DESIGN.md`);
+ expect(deps.deleteJudgment).toHaveBeenCalledWith('bot-1', 'idea:dark-icons');
+ expect(deps.notifyChanged).toHaveBeenCalledWith('bot-1');
+ });
+
+ it('refuses to continue an entry that was never written down', async () => {
+ const { deps, access } = setup();
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'pr:me/tapmon-art#3', message: 'go' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_FOUND' });
+ expect(deps.startBackgroundTask).not.toHaveBeenCalled();
+ });
+
+ it('does not read a transcript for PR, issue or idea entries', async () => {
+ const { access } = setup();
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'issue:me/tapmon-art#4' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_READABLE' });
+ });
+
+ it('stops the current turn through the existing graceful stop path, but not an un-imported session', async () => {
+ const { deps, access } = setup();
+ await expect(access.stopTask({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toEqual({ ok: true, taskId: 'task-1', status: 'requested' });
+ expect(deps.stopSessionTurn).toHaveBeenCalledWith({ targetSessionId: 'task-1' });
+ await expect(access.stopTask({ callerSessionId: 'bot-main', taskId: 'claude:abc' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_RUNNING' });
+ });
+
+ it('refuses a caller that is not a Bot main task and never touches the target', async () => {
+ const { deps, access } = setup({
+ resolveCaller: vi.fn(async () => ({
+ ok: false as const,
+ errorCode: 'BOT_MAIN_TASK_REQUIRED',
+ message: 'only the main task',
+ })),
+ });
+ for (const call of [
+ () => access.continueTask({ callerSessionId: 'group-lane', taskId: 'task-1', message: 'hi' }),
+ () => access.stopTask({ callerSessionId: 'group-lane', taskId: 'task-1' }),
+ () => access.read({ callerSessionId: 'group-lane', taskId: 'task-1' }),
+ () => access.set({ callerSessionId: 'group-lane', taskId: 'task-1', title: 't', verdict: 'done' }),
+ ]) {
+ await expect(call()).resolves.toMatchObject({ ok: false, errorCode: 'BOT_MAIN_TASK_REQUIRED' });
+ }
+ expect(deps.readTarget).not.toHaveBeenCalled();
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ expect(deps.saveJudgment).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['outside the handed-over project', target({ workingDir: '/elsewhere' }), 'TASK_OUTSIDE_WORKBENCH'],
+ ['a Bot hidden session', target({ botLinked: true }), 'TASK_NOT_ACCESSIBLE'],
+ ['a remote task', target({ remoteHostId: 'ssh-1' }), 'TASK_REMOTE'],
+ ['an archived task', target({ status: 'archived' }), 'TASK_ARCHIVED'],
+ ])('denies %s without reading, sending or stopping', async (_label, facts, errorCode) => {
+ const { deps, access } = setup({ readTarget: vi.fn(async () => facts) });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: 'hi' }))
+ .resolves.toMatchObject({ ok: false, errorCode });
+ await expect(access.stopTask({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode });
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode });
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ expect(deps.stopSessionTurn).not.toHaveBeenCalled();
+ expect(deps.readSessionTranscript).not.toHaveBeenCalled();
+ });
+
+ it('stops before delivery when the account changes mid-call', async () => {
+ const { deps, access } = setup({ isOwnerScopeCurrent: () => false });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: 'hi' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'OWNER_SCOPE_CHANGED' });
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ });
+
+ it('re-checks the grant right before acting, so a project removed mid-call is not touched', async () => {
+ const { deps, access } = setup();
+ vi.mocked(deps.readState)
+ .mockResolvedValueOnce({ directories: [PROJECT], tasks: {} })
+ .mockResolvedValue({ directories: [], tasks: {} });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: 'hi' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+
+ vi.mocked(deps.readState)
+ .mockResolvedValueOnce({ directories: [PROJECT], tasks: {} })
+ .mockResolvedValue({ directories: [], tasks: {} });
+ await expect(access.stopTask({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ expect(deps.stopSessionTurn).not.toHaveBeenCalled();
+
+ vi.mocked(deps.readState)
+ .mockResolvedValueOnce({ directories: [PROJECT], tasks: {} })
+ .mockResolvedValue({ directories: [], tasks: {} });
+ await expect(access.read({ callerSessionId: 'bot-main', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ });
+
+ it('rejects empty or oversized messages', async () => {
+ const { deps, access } = setup();
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: ' ' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ await expect(access.continueTask({ callerSessionId: 'bot-main', taskId: 'task-1', message: 'x'.repeat(4_001) }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ expect(deps.resolveCaller).not.toHaveBeenCalled();
+ });
+});
+
+describe('workbench detail reads for the owner', () => {
+ it('reads through the same project boundary as the tools', async () => {
+ const { access } = setup();
+ await expect(access.readForOwner({ botId: 'bot-1', taskId: 'claude:abc' })).resolves.toMatchObject({ ok: true });
+ const outside = setup({ listExternalCandidates: sessions(external({ cwd: '/elsewhere' })) });
+ await expect(outside.access.readForOwner({ botId: 'bot-1', taskId: 'claude:abc' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ expect(outside.deps.readExternalTranscript).not.toHaveBeenCalled();
+ const hidden = setup({ readTarget: vi.fn(async () => target({ botLinked: true })) });
+ await expect(hidden.access.readForOwner({ botId: 'bot-1', taskId: 'task-1' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_ACCESSIBLE' });
+ });
+});
+
+describe('workbench snapshot', () => {
+ it('merges Cindy tasks and local sessions as candidates, newest first, with judgments, digests and briefs', async () => {
+ const DAY = 24 * 60 * 60 * 1000;
+ const NOW = 100 * DAY;
+ const { access } = setup({
+ now: () => NOW,
+ readState: vi.fn(async () => ({
+ directories: [PROJECT],
+ tasks: {
+ 'claude:abc': {
+ title: '导出图标',
+ verdict: 'unfinished' as const,
+ next: '补 xxhdpi',
+ project: PROJECT,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ },
+ },
+ })),
+ listDelegations: vi.fn(async () => new Map([['delegated-1', 'queued' as const]])),
+ listProjectTasks: vi.fn(async () => [
+ { id: 'running', title: '**导出** 图标', workingDir: PROJECT, agentKind: 'cc', summary: null, lastActiveAt: NOW - 1, messageCount: 12 },
+ { id: 'delegated-1', title: '过一遍导出目录', workingDir: PROJECT, agentKind: 'pi', summary: null, lastActiveAt: NOW - 40 * DAY },
+ { id: 'stale', title: '很久以前', workingDir: PROJECT, agentKind: 'cc', summary: null, lastActiveAt: NOW - 31 * DAY },
+ { id: 'elsewhere', title: '别的项目', workingDir: '/other', agentKind: 'cc', summary: null, lastActiveAt: NOW },
+ ]),
+ listExternalCandidates: vi.fn(async () => ({
+ sessions: [
+ external({ updatedAt: NOW - 2 }),
+ external({ source: 'codex', id: 'far', cwd: '/other', updatedAt: NOW }),
+ ],
+ olderCount: 4,
+ })),
+ readActivityPhase: vi.fn(async (id: string) => (id === 'running' ? 'running' : null)),
+ listSchedules: vi.fn(async () => [
+ { id: 's-1', name: '检查 PR', status: 'active', workspaceKind: 'project', workingDir: PROJECT, nextFireAt: 0 },
+ ]),
+ });
+ const result = await access.get({ callerSessionId: 'bot-main' });
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.workbench.tasks.map((task) => [task.taskId, task.source, task.state, task.kind])).toEqual([
+ ['running', 'cindy', 'running', 'existing'],
+ ['claude:abc', 'claude-code', null, 'existing'],
+ ['delegated-1', 'cindy', 'queued', 'delegated'],
+ ]);
+ expect(result.workbench.tasks[0]).toMatchObject({ title: '导出 图标', messageCount: 12, imported: true });
+ expect(result.workbench.tasks[1]).toMatchObject({
+ title: '把图标导出来',
+ imported: false,
+ judgment: { verdict: 'unfinished', next: '补 xxhdpi' },
+ });
+ expect(result.workbench.tasks[1]!.digest).toMatchObject({ purpose: '把图标导出来' });
+ expect(result.workbench.tasks[0]!.digest).toMatchObject({ purpose: '导出图标' });
+ expect(result.workbench.counts).toEqual({ unfinished: 1, idea: 0, done: 0, unjudged: 1 });
+ expect(result.workbench.automations.map((item) => item.id)).toEqual(['s-1']);
+ expect(result.workbench.totalTasks).toBe(3);
+ // 30 天前的 Cindy 任务只计数(伙伴自己的后台任务除外),加上外部来源报来的 4 条。
+ expect(result.workbench.olderCount).toBe(5);
+ expect(result.workbench.projects[0]).toMatchObject({ path: PROJECT, brief: { docs: [`${PROJECT}/README.md`, `${PROJECT}/DESIGN.md`] } });
+ });
+
+ it('always carries the project Cindy tasks (owner-opened, unjudged) ahead of local sessions', async () => {
+ const NOW = 100 * 24 * 60 * 60 * 1000;
+ const { access } = setup({
+ now: () => NOW,
+ listProjectTasks: vi.fn(async () =>
+ Array.from({ length: 35 }, (_, index) => ({
+ id: `own-${index}`,
+ title: `主人的任务 ${index}`,
+ workingDir: PROJECT,
+ agentKind: 'cc',
+ summary: null,
+ lastActiveAt: NOW - 1_000 - index,
+ })),
+ ),
+ listExternalCandidates: vi.fn(async () => ({
+ sessions: Array.from({ length: 20 }, (_, index) => external({ id: `ext-${index}`, updatedAt: NOW - index })),
+ olderCount: 0,
+ })),
+ });
+ const result = await access.get({ callerSessionId: 'bot-main' });
+ if (!result.ok) throw new Error('expected ok');
+ const ids = result.workbench.tasks.map((task) => task.taskId);
+ expect(ids.filter((id) => id.startsWith('own-'))).toHaveLength(30);
+ expect(ids.filter((id) => id.startsWith('claude:'))).toHaveLength(10);
+ expect(result.workbench.tasks.find((task) => task.taskId === 'own-0')).toMatchObject({ judgment: null, imported: true });
+ expect(result.workbench).toMatchObject({ truncated: true, totalTasks: 55 });
+ });
+
+ it('keeps going without a brief when building it fails', async () => {
+ const { access } = setup({ readBrief: vi.fn(async () => { throw new Error('git missing'); }) });
+ const result = await access.get({ callerSessionId: 'bot-main' });
+ expect(result).toMatchObject({ ok: true, workbench: { projects: [{ path: PROJECT, brief: null }] } });
+ });
+
+ it('still lists the Bot own routines before any project is handed over', async () => {
+ const { deps, access } = setup({
+ readState: vi.fn(async () => ({ directories: [], tasks: {} })),
+ listRoutines: vi.fn(async () => [{ id: 'r-1', name: '每日提醒', enabled: true, activity: 'running' as const, lastResult: null }]),
+ });
+ const result = await access.get({ callerSessionId: 'bot-main' });
+ expect(result).toMatchObject({ ok: true, workbench: { projects: [], tasks: [], automations: [{ id: 'r-1', state: 'running' }] } });
+ expect(deps.listProjectTasks).not.toHaveBeenCalled();
+ expect(deps.listExternalCandidates).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchBrief.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchBrief.test.ts
new file mode 100644
index 0000000000..8b366d2daa
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchBrief.test.ts
@@ -0,0 +1,136 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { buildProjectBrief, createBriefCache, parseGithubRemote, type WorkbenchBriefDeps } from '../botWorkbenchBrief.js';
+
+let root: string | null = null;
+afterEach(async () => {
+ if (root) await rm(root, { recursive: true, force: true });
+ root = null;
+});
+
+async function project() {
+ root = await mkdtemp(path.join(os.tmpdir(), 'wb-brief-'));
+ await mkdir(path.join(root, 'node_modules', 'pkg'), { recursive: true });
+ await writeFile(path.join(root, 'node_modules', 'pkg', 'index.js'), '');
+ await mkdir(path.join(root, 'docs', 'deep'), { recursive: true });
+ await writeFile(path.join(root, 'notes.md'), '');
+ await writeFile(path.join(root, 'DESIGN.md'), '');
+ await writeFile(path.join(root, 'README.md'), '');
+ await writeFile(path.join(root, 'docs', 'guide.md'), '');
+ await mkdir(path.join(root, 'docs', 'product-rules'), { recursive: true });
+ await mkdir(path.join(root, 'docs', 'dev-rules', 'deep'), { recursive: true });
+ await writeFile(path.join(root, 'docs', 'product-rules', 'core.md'), '');
+ await writeFile(path.join(root, 'docs', 'dev-rules', 'deep', 'setup.md'), '');
+ await writeFile(path.join(root, 'docs', 'design-rules-DESIGN.md'), '');
+ await mkdir(path.join(root, 'src'), { recursive: true });
+ await writeFile(path.join(root, 'src', 'ignored.md'), '');
+ return root;
+}
+
+function gitDeps(overrides: Partial<WorkbenchBriefDeps> = {}): WorkbenchBriefDeps {
+ // 「最近」以真实时间为准:临时文件的 mtime 就是现在。
+ const outputs: Record<string, string> = {
+ 'rev-parse --is-inside-work-tree': 'true\n',
+ 'rev-parse --abbrev-ref HEAD': 'main\n',
+ 'status --porcelain': ' M a.ts\n?? b.ts\n',
+ 'remote get-url upstream': 'https://github.com/org/app.git\n',
+ 'remote get-url origin': '[email protected]:me/app.git\n',
+ };
+ return {
+ git: vi.fn(async (_cwd: string, args: string[]) => {
+ const key = args.join(' ');
+ if (args[0] === 'log') return 'abc123\u00002026-09-30T10:00:00+08:00\u0000Me\u0000fix icons\n';
+ if (args[0] === 'for-each-ref') return 'main\u00002026-09-30T10:00:00+08:00\nfeat\u00002026-09-29T10:00:00+08:00\n';
+ return outputs[key] ?? null;
+ }),
+ searchGithub: vi.fn(async (query: string) => [{
+ number: query.includes('is:pr') ? 12 : 7,
+ title: query.includes('is:pr') ? 'Icons PR' : 'Icon bug',
+ state: 'open',
+ updatedAt: '2026-09-30T00:00:00Z',
+ url: 'https://github.com/me/app/x',
+ }]),
+ now: () => Date.now(),
+ ...overrides,
+ };
+}
+
+describe('parseGithubRemote', () => {
+ it('reads owner/repo from ssh and https remotes only', () => {
+ expect(parseGithubRemote('[email protected]:me/app.git')).toBe('me/app');
+ expect(parseGithubRemote('https://github.com/me/app')).toBe('me/app');
+ expect(parseGithubRemote('https://gitlab.com/me/app.git')).toBeNull();
+ expect(parseGithubRemote(null)).toBeNull();
+ });
+});
+
+describe('buildProjectBrief', () => {
+ it('lists top-level and docs Markdown paths with key docs first, plus recent git and GitHub items', async () => {
+ const dir = await project();
+ const deps = gitDeps({ now: () => Date.parse('2026-10-01T00:00:00Z') });
+ const brief = await buildProjectBrief(dir, deps);
+ expect(brief.docs.map((file) => path.relative(dir, file))).toEqual([
+ 'DESIGN.md',
+ 'README.md',
+ path.join('docs', 'product-rules', 'core.md'),
+ path.join('docs', 'dev-rules', 'deep', 'setup.md'),
+ 'notes.md',
+ path.join('docs', 'design-rules-DESIGN.md'),
+ path.join('docs', 'guide.md'),
+ ]);
+ expect(brief.recent).toEqual([]);
+ expect(brief.git).toMatchObject({
+ branch: 'main',
+ changes: 2,
+ remote: 'org/app',
+ remotes: ['org/app', 'me/app'],
+ commits: [{ sha: 'abc123', author: 'Me', subject: 'fix icons' }],
+ branches: [{ name: 'main' }, { name: 'feat' }],
+ });
+ // fork 工作流:PR / issue 查 upstream。
+ expect(brief.github).toMatchObject({ repo: 'org/app', pullRequests: [{ number: 12 }], issues: [{ number: 7 }] });
+ expect(vi.mocked(deps.searchGithub).mock.calls[0]![0]).toContain('repo:org/app');
+ const log = vi.mocked(deps.git).mock.calls.find(([, args]) => args[0] === 'log')![1];
+ expect(log).toContain('--since=2026-09-17T00:00:00.000Z');
+ expect(log).toContain('--max-count=30');
+ });
+
+ it('reports missing pieces instead of guessing', async () => {
+ const dir = await project();
+ expect((await buildProjectBrief(dir, gitDeps({ searchGithub: vi.fn(async () => null) }))).github)
+ .toEqual({ unavailable: 'no-credential' });
+ expect((await buildProjectBrief(dir, gitDeps({ searchGithub: vi.fn(async () => { throw new Error('rate'); }) }))).github)
+ .toEqual({ unavailable: 'error' });
+ const plain = await buildProjectBrief(dir, gitDeps({ git: vi.fn(async () => null) }));
+ expect(plain).toMatchObject({ git: null, github: { unavailable: 'not-github' } });
+ expect(plain.docs.length).toBe(7);
+ // 不是 git 仓库:给最近 14 天改过的文件,跳过 node_modules 与隐藏目录。
+ expect(plain.recent.map((file) => path.relative(dir, file.path)).sort()).toContain(path.join('src', 'ignored.md'));
+ expect(plain.recent.length).toBeLessThanOrEqual(20);
+ const missing = await buildProjectBrief(path.join(dir, 'nope'), gitDeps({ git: vi.fn(async () => null) }));
+ expect(missing).toEqual({ docs: [], recent: [], git: null, github: { unavailable: 'not-github' } });
+ });
+});
+
+describe('createBriefCache', () => {
+ it('reuses a brief for 60 seconds unless the fingerprint changes', async () => {
+ const dir = await project();
+ let now = 0;
+ let print = 'a';
+ const deps = gitDeps({ now: () => now });
+ const readBrief = createBriefCache({ ...deps, fingerprint: async () => print });
+ await readBrief(dir);
+ await readBrief(dir);
+ expect(vi.mocked(deps.searchGithub)).toHaveBeenCalledTimes(3);
+ print = 'b';
+ await readBrief(dir);
+ expect(vi.mocked(deps.searchGithub)).toHaveBeenCalledTimes(6);
+ now = 61_000;
+ await readBrief(dir);
+ expect(vi.mocked(deps.searchGithub)).toHaveBeenCalledTimes(9);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts
new file mode 100644
index 0000000000..80d1a26ea1
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchService.test.ts
@@ -0,0 +1,185 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));
+
+import { botProfileDir } from '../botProfileFolder.js';
+import {
+ addBotWorkbenchDirectory,
+ boundJudgments,
+ normalizeWorkbench,
+ readBotWorkbench,
+ readBotWorkbenchDirectoryPaths,
+ readBotWorkbenchState,
+ rekeyBotWorkbenchJudgment,
+ removeBotWorkbenchDirectory,
+ setBotWorkbenchJudgment,
+} from '../botWorkbenchService.js';
+
+let root: string | null = null;
+afterEach(async () => {
+ if (root) await rm(root, { recursive: true, force: true });
+ root = null;
+});
+
+describe('bot workbench storage', () => {
+ it('records handed-over projects in the Bot home, newest first, and removes them', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const filo = path.join(root, 'Filo');
+ const art = path.join(root, 'tapmon-art');
+ await mkdir(filo);
+ await mkdir(art);
+
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', filo, new Date('2026-10-01T01:00:00.000Z'))).toEqual({ ok: true });
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', art, new Date('2026-10-01T02:00:00.000Z'))).toEqual({ ok: true });
+ // Handing the same project over again only moves it to the front.
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', filo, new Date('2026-10-01T03:00:00.000Z'))).toEqual({ ok: true });
+
+ expect((await readBotWorkbench(root, 'bot-1')).directories).toEqual([
+ { path: filo, name: 'Filo', addedAt: '2026-10-01T03:00:00.000Z', exists: true },
+ { path: art, name: 'tapmon-art', addedAt: '2026-10-01T02:00:00.000Z', exists: true },
+ ]);
+ expect(await readBotWorkbenchDirectoryPaths(root, 'bot-1')).toEqual([filo, art]);
+
+ await removeBotWorkbenchDirectory(root, 'bot-1', filo);
+ expect(await readBotWorkbenchDirectoryPaths(root, 'bot-1')).toEqual([art]);
+ // Other Bots never see this Bot's projects.
+ expect(await readBotWorkbenchDirectoryPaths(root, 'bot-2')).toEqual([]);
+ });
+
+ it('rejects missing folders and more than six projects', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', path.join(root, 'missing'))).toEqual({
+ ok: false,
+ errorCode: 'NOT_A_DIRECTORY',
+ });
+ for (let index = 0; index < 6; index += 1) {
+ const dir = path.join(root, `p${index}`);
+ await mkdir(dir);
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', dir)).toEqual({ ok: true });
+ }
+ const extra = path.join(root, 'extra');
+ await mkdir(extra);
+ expect(await addBotWorkbenchDirectory(root, 'bot-1', extra)).toEqual({ ok: false, errorCode: 'TOO_MANY' });
+ });
+
+ it('reads an empty workbench when a Bot has none yet or the file is corrupt', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ expect(await readBotWorkbench(root, 'bot-1')).toEqual({ directories: [], tasks: {} });
+ await mkdir(botProfileDir(root, 'bot-1'), { recursive: true });
+ await writeFile(path.join(botProfileDir(root, 'bot-1'), 'workbench.json'), '{not json', 'utf8');
+ expect(await readBotWorkbench(root, 'bot-1')).toEqual({ directories: [], tasks: {} });
+ });
+
+ it('ignores cards written by the earlier draft and drops them on the next write', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const project = path.join(root, 'Filo');
+ await mkdir(project);
+ const file = path.join(botProfileDir(root, 'bot-1'), 'workbench.json');
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({
+ cards: [{ title: '进度', rows: [{ title: '#4100', status: 'review' }] }],
+ updatedAt: '2026-09-30T00:00:00.000Z',
+ directories: [{ path: project, addedAt: '2026-09-30T00:00:00.000Z' }],
+ }), 'utf8');
+
+ expect(await readBotWorkbench(root, 'bot-1')).toEqual({
+ directories: [{ path: project, name: 'Filo', addedAt: '2026-09-30T00:00:00.000Z', exists: true }],
+ tasks: {},
+ });
+ await removeBotWorkbenchDirectory(root, 'bot-1', path.join(root, 'nothing'));
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
+ directories: [{ path: project, addedAt: '2026-09-30T00:00:00.000Z' }],
+ tasks: {},
+ });
+ });
+
+ it('bounds and drops malformed directory entries instead of trusting the file', () => {
+ const normalized = normalizeWorkbench({
+ directories: [
+ null,
+ { path: 'relative/path' },
+ { path: '/a', addedAt: 7 },
+ { path: '/a' },
+ ...Array.from({ length: 8 }, (_, index) => ({ path: `/p${index}`, addedAt: 'x' })),
+ ],
+ });
+ expect(normalized?.directories).toHaveLength(6);
+ expect(normalized?.directories[0]).toEqual({ path: '/a', addedAt: new Date(0).toISOString() });
+ });
+});
+
+describe('bot workbench judgments', () => {
+ const judgment = (verdict: 'unfinished' | 'idea' | 'done', updatedAt: string) => ({
+ title: '导出图标',
+ verdict,
+ next: verdict === 'done' ? null : '补 xxhdpi',
+ project: '/w/art',
+ updatedAt,
+ });
+
+ it('stores, replaces and re-keys a judgment next to the handed-over projects', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'bot-workbench-'));
+ const project = path.join(root, 'art');
+ await mkdir(project);
+ await addBotWorkbenchDirectory(root, 'bot-1', project);
+ await setBotWorkbenchJudgment(root, 'bot-1', 'claude:abc', {
+ title: '导出图标',
+ verdict: 'unfinished',
+ next: '补 xxhdpi',
+ project,
+ }, new Date('2026-10-01T01:00:00.000Z'));
+ await setBotWorkbenchJudgment(root, 'bot-1', 'claude:abc', {
+ title: '导出 Android 图标',
+ verdict: 'idea',
+ next: '先问要不要做 xxxhdpi',
+ project,
+ }, new Date('2026-10-01T02:00:00.000Z'));
+ expect((await readBotWorkbenchState(root, 'bot-1')).tasks).toEqual({
+ 'claude:abc': {
+ title: '导出 Android 图标',
+ verdict: 'idea',
+ next: '先问要不要做 xxxhdpi',
+ project,
+ updatedAt: '2026-10-01T02:00:00.000Z',
+ },
+ });
+ await rekeyBotWorkbenchJudgment(root, 'bot-1', 'claude:abc', 'claude-abc');
+ const state = await readBotWorkbenchState(root, 'bot-1');
+ expect(Object.keys(state.tasks)).toEqual(['claude-abc']);
+ expect(state.directories).toEqual([project]);
+ // Removing a project keeps the judgments; the projection hides them by project.
+ await removeBotWorkbenchDirectory(root, 'bot-1', project);
+ expect(Object.keys((await readBotWorkbenchState(root, 'bot-1')).tasks)).toEqual(['claude-abc']);
+ });
+
+ it('keeps at most the limit, evicting the oldest done judgments first', () => {
+ const tasks = {
+ a: judgment('done', '2026-10-01T00:00:01.000Z'),
+ b: judgment('unfinished', '2026-10-01T00:00:00.000Z'),
+ c: judgment('done', '2026-10-01T00:00:02.000Z'),
+ d: judgment('idea', '2026-10-01T00:00:03.000Z'),
+ };
+ expect(Object.keys(boundJudgments(tasks, 3)).sort()).toEqual(['b', 'c', 'd']);
+ expect(Object.keys(boundJudgments(tasks, 2)).sort()).toEqual(['b', 'd']);
+ expect(Object.keys(boundJudgments(tasks, 1))).toEqual(['d']);
+ });
+
+ it('drops malformed judgments when reading', () => {
+ const normalized = normalizeWorkbench({
+ tasks: {
+ ok: judgment('idea', '2026-10-01T00:00:00.000Z'),
+ badVerdict: { ...judgment('idea', 'x'), verdict: 'maybe' },
+ noTitle: { ...judgment('idea', 'x'), title: '' },
+ relativeProject: { ...judgment('idea', 'x'), project: 'art' },
+ long: { ...judgment('unfinished', 'x'), title: 'x'.repeat(80), next: 'y'.repeat(300) },
+ },
+ });
+ expect(Object.keys(normalized?.tasks ?? {})).toEqual(['ok', 'long']);
+ expect(normalized?.tasks.long.title).toHaveLength(40);
+ expect(normalized?.tasks.long.next).toHaveLength(120);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchSessionRoots.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchSessionRoots.test.ts
new file mode 100644
index 0000000000..c9cfca1662
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchSessionRoots.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import { workbenchSessionRoots } from '../botWorkbenchSessionRoots.js';
+
+const SUPPORT = '/Users/me/Library/Application Support';
+
+describe('workbenchSessionRoots', () => {
+ it('lists native Claude Code, Codex and Pi transcript dirs including every Cindy profile on macOS', () => {
+ const roots = workbenchSessionRoots({
+ homeDir: '/Users/me',
+ appDataDir: SUPPORT,
+ userDataDir: `${SUPPORT}/CindyGlobal-dev2-bot-workbench`,
+ platform: 'darwin',
+ env: {},
+ });
+ expect(roots.claude).toEqual(['/Users/me/.claude/projects']);
+ for (const home of [
+ '/Users/me/.codex',
+ `${SUPPORT}/Codex/codex-home`,
+ `${SUPPORT}/Codex`,
+ `${SUPPORT}/CindyGlobal-dev2-bot-workbench/codex-home`,
+ `${SUPPORT}/Cindy/codex-home`,
+ `${SUPPORT}/CindyGlobal/codex-home`,
+ `${SUPPORT}/CindyDev/codex-home`,
+ `${SUPPORT}/xdt-maker/codex-home`,
+ ]) {
+ expect(roots.codex).toContain(`${home}/sessions`);
+ expect(roots.codex).toContain(`${home}/archived_sessions`);
+ }
+ expect(roots.pi).toEqual([
+ `${SUPPORT}/CindyGlobal-dev2-bot-workbench/pi-agent-home/sessions`,
+ `${SUPPORT}/Cindy/pi-agent-home/sessions`,
+ `${SUPPORT}/CindyGlobal/pi-agent-home/sessions`,
+ `${SUPPORT}/CindyDev/pi-agent-home/sessions`,
+ `${SUPPORT}/xdt-maker/pi-agent-home/sessions`,
+ ]);
+ });
+
+ it('honours CODEX_HOME / CLAUDE_CONFIG_DIR and does not repeat the current profile', () => {
+ const roots = workbenchSessionRoots({
+ homeDir: '/home/me',
+ appDataDir: '/home/me/.config',
+ userDataDir: '/home/me/.config/Cindy',
+ platform: 'linux',
+ env: { CODEX_HOME: '/opt/codex', CLAUDE_CONFIG_DIR: '/opt/claude' },
+ });
+ expect(roots.claude).toEqual(['/opt/claude/projects', '/home/me/.claude/projects']);
+ expect(roots.codex[0]).toBe('/opt/codex/sessions');
+ expect(roots.codex).toContain('/home/me/.config/codex/sessions');
+ expect(roots.codex.filter((dir) => dir === '/home/me/.config/Cindy/codex-home/sessions')).toHaveLength(1);
+ expect(roots.pi.filter((dir) => dir === '/home/me/.config/Cindy/pi-agent-home/sessions')).toHaveLength(1);
+ });
+
+ it('uses APPDATA for the Codex app on Windows and skips it when unknown', () => {
+ const win = workbenchSessionRoots({
+ homeDir: 'C:/Users/me',
+ appDataDir: null,
+ userDataDir: null,
+ platform: 'win32',
+ env: { APPDATA: 'C:/Users/me/AppData/Roaming' },
+ });
+ expect(win.codex.some((dir) => dir.includes('Roaming') && dir.endsWith('sessions'))).toBe(true);
+ expect(win.pi).toEqual([]);
+ const bare = workbenchSessionRoots({ homeDir: 'C:/Users/me', appDataDir: null, userDataDir: null, platform: 'win32', env: {} });
+ expect(bare.codex).toHaveLength(2);
+ });
+
+ it('adds the current account codex-accounts folder of every profile, and nothing for other or missing owners', () => {
+ const owner = 'a'.repeat(64);
+ const roots = workbenchSessionRoots({
+ homeDir: '/Users/me',
+ appDataDir: SUPPORT,
+ userDataDir: `${SUPPORT}/CindyGlobal-dev2-bot-workbench`,
+ platform: 'darwin',
+ env: {},
+ codexAccountOwner: owner,
+ });
+ expect(roots.codexAccounts).toEqual([
+ `${SUPPORT}/CindyGlobal-dev2-bot-workbench/codex-accounts/${owner}`,
+ `${SUPPORT}/Cindy/codex-accounts/${owner}`,
+ `${SUPPORT}/CindyGlobal/codex-accounts/${owner}`,
+ `${SUPPORT}/CindyDev/codex-accounts/${owner}`,
+ `${SUPPORT}/xdt-maker/codex-accounts/${owner}`,
+ ]);
+ const base = { homeDir: '/Users/me', appDataDir: SUPPORT, userDataDir: null, platform: 'darwin', env: {} };
+ expect(workbenchSessionRoots(base).codexAccounts).toEqual([]);
+ expect(workbenchSessionRoots({ ...base, codexAccountOwner: '../../etc' }).codexAccounts).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts
new file mode 100644
index 0000000000..b79f0475c9
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts
@@ -0,0 +1,189 @@
+import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({
+ drizzle: { select: () => ({ from: () => ({ where: async () => inCindyRows }) }) },
+ }),
+}));
+vi.mock('../../maker-host/claude-local-sessions.js', () => ({
+ parseClaudeCodeMessageLine: vi.fn((line: string) => {
+ const row = JSON.parse(line) as { type?: string; message?: { content?: unknown } };
+ if ((row.type !== 'user' && row.type !== 'assistant') || typeof row.message?.content !== 'string') return [];
+ return [{ role: row.type, content: row.message.content, createdAt: 0 }];
+ }),
+}));
+vi.mock('../../maker-host/codex-local-sessions.js', () => ({
+ parseCodexRolloutMessageLine: vi.fn((line: string) => {
+ const row = JSON.parse(line) as { type?: string; payload?: { role?: string; text?: string } };
+ return row.type === 'msg' && row.payload?.text ? { role: row.payload.role, text: row.payload.text, createdAt: 0 } : null;
+ }),
+}));
+
+let inCindyRows: Array<{ sdkSessionId: string; agentKind: string }> = [];
+
+import {
+ boundTranscript,
+ claudeStorageNames,
+ findCwdInHead,
+ listExternalSessionsForProjects,
+ parsePiTranscriptLine,
+ readHeadTailLines,
+ recentCodexDayDirs,
+} from '../botWorkbenchTranscripts.js';
+
+let root: string | null = null;
+afterEach(async () => {
+ if (root) await rm(root, { recursive: true, force: true });
+ root = null;
+});
+
+describe('boundTranscript', () => {
+ it('strips instruction blocks, drops empty messages and keeps the most recent within the budget', () => {
+ const items = [
+ { role: 'user' as const, text: 'old '.repeat(400), at: 1 },
+ { role: 'assistant' as const, text: '<system-reminder>internal</system-reminder>', at: 2 },
+ { role: 'user' as const, text: '把图标导出来', at: 3 },
+ { role: 'assistant' as const, text: '导好了 mdpi,还差 xxhdpi', at: 4 },
+ ];
+ const bounded = boundTranscript(items, 200);
+ expect(bounded.items.map((item) => item.at)).toEqual([1, 3, 4]);
+ expect(bounded.items[0].text.startsWith('…')).toBe(true);
+ expect(bounded.items.reduce((sum, item) => sum + item.text.length, 0)).toBeLessThanOrEqual(200);
+ expect(bounded.truncated).toBe(true);
+ expect(boundTranscript(items.slice(2)).truncated).toBe(false);
+ });
+});
+
+describe('readHeadTailLines', () => {
+ it('reads a small file once and only the head and tail of a large one', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'wb-ht-'));
+ const small = path.join(root, 's.jsonl');
+ await writeFile(small, ['a', 'b', 'c', ''].join('\n'), 'utf8');
+ expect(await readHeadTailLines(small, 64)).toMatchObject({ head: ['a', 'b', 'c'], tail: ['a', 'b', 'c'], whole: true });
+ const big = path.join(root, 'b.jsonl');
+ const lines = Array.from({ length: 200 }, (_, index) => `line-${String(index).padStart(3, '0')}`);
+ await writeFile(big, `${lines.join('\n')}\n`, 'utf8');
+ const parts = await readHeadTailLines(big, 64);
+ expect(parts.whole).toBe(false);
+ expect(parts.head[0]).toBe('line-000');
+ expect(parts.tail.at(-1)).toBe('line-199');
+ // 被截断的半行丢掉:每段都只剩完整行,远少于全文。
+ for (const line of [...parts.head, ...parts.tail]) expect(line).toMatch(/^line-\d{3}$/);
+ expect(parts.head.length + parts.tail.length).toBeLessThan(20);
+ });
+});
+
+describe('transcript helpers', () => {
+ it('parses Pi message lines and skips anything uncertain', () => {
+ expect(parsePiTranscriptLine(JSON.stringify({
+ type: 'message',
+ timestamp: '2026-10-01T00:00:00.000Z',
+ message: { role: 'user', content: [{ type: 'text', text: '修图标' }, { type: 'image', data: 'x' }] },
+ }))).toEqual({ role: 'user', text: '修图标', at: Date.parse('2026-10-01T00:00:00.000Z') });
+ expect(parsePiTranscriptLine(JSON.stringify({ type: 'session', id: 'p1', cwd: '/w' }))).toBeNull();
+ expect(parsePiTranscriptLine(JSON.stringify({ type: 'message', message: { role: 'toolResult', content: 'x' } }))).toBeNull();
+ expect(parsePiTranscriptLine('{not json')).toBeNull();
+ });
+
+ it('finds cwd in a truncated head', () => {
+ expect(findCwdInHead('{"type":"session_meta","payload":{"id":"x","cwd":"/Users/me/Code/app","instructions":"lo')).toBe('/Users/me/Code/app');
+ expect(findCwdInHead('{"cwd":"C:\\\\Code\\\\app"}')).toBe('C:\\Code\\app');
+ expect(findCwdInHead('{"type":"x"}')).toBeNull();
+ });
+
+ it('derives Claude storage names and recent Codex day folders', () => {
+ expect(claudeStorageNames('/Users/me/Code/my.app')).toEqual(['-Users-me-Code-my.app', '-Users-me-Code-my-app']);
+ expect(claudeStorageNames('C:\\Users\\me\\app')).toEqual(['C--Users-me-app']);
+ const days = recentCodexDayDirs('/c/sessions', new Date(2026, 9, 1, 12).getTime(), 2);
+ expect(days).toEqual([
+ path.join('/c/sessions', '2026', '10', '01'),
+ path.join('/c/sessions', '2026', '09', '30'),
+ path.join('/c/sessions', '2026', '09', '29'),
+ ]);
+ });
+});
+
+describe('listExternalSessionsForProjects', () => {
+ const DAY = 24 * 60 * 60 * 1000;
+
+ it('finds recent sessions of all three sources inside the project, with bounded digests, counting older ones', async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'wb-ext-'));
+ const project = path.join(root, 'Code', 'app');
+ const now = Date.now();
+ const claudeRoot = path.join(root, 'claude');
+ const codexRoot = path.join(root, 'codex', 'sessions');
+ const piRoot = path.join(root, 'pi');
+ const claudeFolder = path.join(claudeRoot, claudeStorageNames(project)[0]!);
+ await mkdir(claudeFolder, { recursive: true });
+ const claudeLine = (type: string, content: string) => JSON.stringify({ type, cwd: project, message: { content } });
+ await writeFile(path.join(claudeFolder, 'c-new.jsonl'), [
+ claudeLine('user', '把图标导出来'),
+ ...Array.from({ length: 50 }, (_, index) => claudeLine('assistant', `step ${index} ${'x'.repeat(4000)}`)),
+ claudeLine('assistant', '还差 xxhdpi'),
+ ].join('\n'));
+ await writeFile(path.join(claudeFolder, 'c-old.jsonl'), claudeLine('user', '很久以前'));
+ await utimes(path.join(claudeFolder, 'c-old.jsonl'), new Date(now - 40 * DAY), new Date(now - 40 * DAY));
+ await writeFile(path.join(claudeFolder, 'c-imported.jsonl'), claudeLine('user', '已在 Cindy 里'));
+
+ const today = recentCodexDayDirs(codexRoot, now, 0)[0]!;
+ await mkdir(today, { recursive: true });
+ const uuid = '01a0f587-e669-7900-a224-363dcb19f570';
+ const other = '01a0f587-e669-7900-a224-363dcb19f571';
+ const meta = (cwd: string) => JSON.stringify({ type: 'session_meta', payload: { id: 'x', cwd, instructions: 'i'.repeat(200_000) } });
+ await writeFile(path.join(today, `rollout-2026-10-01T11-35-19-${uuid}.jsonl`), [
+ meta(path.join(project, '.cindy-worktrees', 'fix')),
+ JSON.stringify({ type: 'msg', payload: { role: 'user', text: '修 CI' } }),
+ ].join('\n'));
+ await writeFile(path.join(today, `rollout-2026-10-01T11-35-19-${other}.jsonl`), meta(path.join(root, 'elsewhere')));
+
+ // 多账号登录的 Codex home:codex-accounts/<账号>/<供应商>/sessions/YYYY/MM/DD。
+ const accountsRoot = path.join(root, 'codex-accounts', 'a'.repeat(64));
+ const accountDay = recentCodexDayDirs(path.join(accountsRoot, 'openai-1', 'sessions'), now, 0)[0]!;
+ await mkdir(accountDay, { recursive: true });
+ const accountId = '01a0f587-e669-7900-a224-363dcb19f572';
+ await writeFile(path.join(accountDay, `rollout-2026-10-01T11-35-19-${accountId}.jsonl`), [
+ meta(project),
+ JSON.stringify({ type: 'msg', payload: { role: 'user', text: '账号会话' } }),
+ ].join('\n'));
+
+ await mkdir(piRoot, { recursive: true });
+ await writeFile(path.join(piRoot, '2026-10-01T00-00-00_p1.jsonl'), [
+ JSON.stringify({ type: 'session', id: 'p1', cwd: project }),
+ JSON.stringify({ type: 'message', message: { role: 'user', content: [{ type: 'text', text: '写文档' }] } }),
+ ].join('\n'));
+
+ inCindyRows = [{ sdkSessionId: 'c-imported', agentKind: 'cc' }];
+ const result = await listExternalSessionsForProjects({
+ roots: { claude: [claudeRoot], codex: [codexRoot, path.join(root, 'missing')], codexAccounts: [accountsRoot], pi: [piRoot] },
+ projectDirs: [project],
+ caseInsensitive: false,
+ since: now - 30 * DAY,
+ now,
+ });
+ const byKey = new Map(result.sessions.map((item) => [`${item.source}:${item.id}`, item]));
+ expect([...byKey.keys()].sort()).toEqual(['claude:c-new', `codex:${uuid}`, `codex:${accountId}`, 'pi:p1']);
+ expect(byKey.get(`codex:${accountId}`)!.digest).toMatchObject({ purpose: '账号会话' });
+ expect(result.olderCount).toBe(1);
+ expect(result.overflowCount).toBe(0);
+ expect(byKey.get('claude:c-new')!.digest).toMatchObject({ purpose: '把图标导出来' });
+ expect(byKey.get('claude:c-new')!.digest!.recent.at(-1)).toEqual({ role: 'assistant', text: '还差 xxhdpi' });
+ expect(byKey.get(`codex:${uuid}`)!.digest).toMatchObject({ purpose: '修 CI' });
+ expect(byKey.get('pi:p1')).toMatchObject({ title: '写文档', cwd: project });
+
+ const capped = await listExternalSessionsForProjects({
+ roots: { claude: [claudeRoot], codex: [codexRoot], codexAccounts: [accountsRoot], pi: [piRoot] },
+ projectDirs: [project],
+ caseInsensitive: false,
+ since: now - 30 * DAY,
+ now,
+ max: 1,
+ });
+ expect(capped.sessions).toHaveLength(1);
+ expect(capped.overflowCount).toBe(3);
+ inCindyRows = [];
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
new file mode 100644
index 0000000000..542042dfa0
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
@@ -0,0 +1,773 @@
+/**
+ * 伙伴工作台的权限边界与工具服务(纯逻辑,依赖全部注入,便于单测)。
+ *
+ * 产品裁决(2026-10-01):伙伴可以查看、继续、停止「主人明确交给它的项目」里的任务。
+ * 授权来自主人在工作台里点「交给伙伴」的那一次,范围只限记在该伙伴
+ * `workbench.json` 里的项目,主人随时可以移除;其它任务仍不可触达。
+ *
+ * 接手 = 理解,不是搬运:项目是目录。宿主先给每个项目一份有界的素材(文档清单、近期提交与
+ * 分支、我的 PR / issue)和近期会话的摘要(起始目的 + 最后几条),伙伴凭这些一次性写下判断
+ * (没做完 / 聊过没下文 / 做完),只对拿不准的再读;条目可以是会话,也可以是 PR、issue
+ * 或伙伴从素材里摸出来的建议。项目里的 Cindy 任务(含主人自己开的)不论有无判断都带回,
+ * 是伙伴随时知道的项目事务。主人点头(或在工作台点「跟进」)的那件才继续。
+ *
+ * 每次调用都在 main 里确定性校验:
+ * 1. 调用方 session → 伙伴:只认本机、在用的伙伴主任务(canonical);
+ * 2. Cindy 任务:存在、未删除未归档、本机、不是任何伙伴的隐藏任务、不是后台任务、
+ * 是普通来源的任务,并且工作目录属于该伙伴已接手的某个项目;
+ * 3. 本机会话(Claude Code / Codex / Pi):这次发现里确有这条,且它的 cwd 落在已接手项目内;
+ * 4. PR / issue:仓库必须是某个已接手项目的 GitHub 远端;建议:必须挂在某个已接手项目上;
+ * 5. 参考(ref):只接受 https 链接,或已接手项目内的路径。
+ * 任一条不满足就返回明确的错误码,不读、不写、不投递。
+ */
+import {
+ boundWorkbenchSummary,
+ canonicalWorkbenchTaskId,
+ cleanWorkbenchTitle,
+ deriveWorkbenchAutomationState,
+ deriveWorkbenchSessionState,
+ findWorkbenchProject,
+ importedSessionOrigin,
+ isWorkbenchTaskSource,
+ parseWorkbenchTaskId,
+ validateWorkbenchRef,
+ WORKBENCH_JUDGMENT_NEXT_MAX,
+ WORKBENCH_JUDGMENT_TITLE_MAX,
+ WORKBENCH_RECENT_WINDOW_MS,
+ type WorkbenchDelegationStatus,
+ type WorkbenchDigest,
+ type WorkbenchTaskJudgment,
+ type WorkbenchTaskRef,
+ type WorkbenchTaskState,
+ type WorkbenchTranscript,
+ type WorkbenchVerdict,
+} from '../../shared/botWorkbench.js';
+import type { WorkbenchProjectBrief } from './botWorkbenchBrief.js';
+
+type Failure = { ok: false; errorCode: string; message: string };
+
+/** 工具一次最多带回的会话候选数;多出来的只报总数。 */
+export const WORKBENCH_TOOL_MAX_TASKS = 40;
+/**
+ * 其中项目里的 Cindy 任务(含主人自己开的)优先占的条数:它们属于伙伴随时知道的项目事务,
+ * 不受判断影响;剩下的名额给本机外部会话。
+ */
+export const WORKBENCH_TOOL_MAX_CINDY_TASKS = 30;
+export const WORKBENCH_TOOL_MAX_MESSAGE_CHARS = 4_000;
+export const WORKBENCH_TOOL_MAX_BATCH = 30;
+const UNTITLED = '未命名任务';
+
+export type WorkbenchCallerResult = { ok: true; botId: string } | Failure;
+
+/** 授权判定所需的目标任务事实,由宿主从数据库读出。 */
+export interface WorkbenchTargetFacts {
+ id: string;
+ status: string;
+ source: string | null;
+ remoteHostId: string | null;
+ workingDir: string | null;
+ orcaRole: string | null;
+ /** 该 session 在 bot_session_links 里有记录(伙伴主任务、群专线、历史等)。 */
+ botLinked: boolean;
+ /** 该 session 是某个伙伴后台任务(bot_delegations.child_session_id)的执行任务。 */
+ delegationChild: boolean;
+}
+
+export type WorkbenchTargetDecision = { ok: true; projectDir: string } | Failure;
+
+export function authorizeWorkbenchTarget(
+ target: WorkbenchTargetFacts | null,
+ projectDirs: readonly string[],
+ caseInsensitive: boolean,
+): WorkbenchTargetDecision {
+ if (!target || target.status === 'deleted') {
+ return { ok: false, errorCode: 'TASK_NOT_FOUND', message: '找不到这件任务,它可能已被删除' };
+ }
+ if (target.botLinked || target.source === 'bot') {
+ return { ok: false, errorCode: 'TASK_NOT_ACCESSIBLE', message: '这是伙伴自己的任务,不能通过工作台操作' };
+ }
+ if (target.remoteHostId) {
+ return { ok: false, errorCode: 'TASK_REMOTE', message: '远端任务不在工作台的范围内' };
+ }
+ if (target.status !== 'active') {
+ return { ok: false, errorCode: 'TASK_ARCHIVED', message: '这件任务已归档,请让主人先恢复它' };
+ }
+ if (target.delegationChild) {
+ return {
+ ok: false,
+ errorCode: 'TASK_IS_BACKGROUND_TASK',
+ message: '这是伙伴开的后台任务,请用 message_session_task / stop_session_task',
+ };
+ }
+ if (!isWorkbenchTaskSource(target.source) || target.orcaRole === 'worker') {
+ return { ok: false, errorCode: 'TASK_NOT_SUPPORTED', message: '这类任务不在工作台的范围内' };
+ }
+ const projectDir = findWorkbenchProject(target.workingDir, projectDirs, caseInsensitive);
+ if (!projectDir) {
+ return { ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH', message: '这件任务不在主人交给你的项目里' };
+ }
+ return { ok: true, projectDir };
+}
+
+/** 本机外部会话候选(按项目目录发现,只读)。 */
+export interface WorkbenchExternalCandidate {
+ source: 'claude' | 'codex' | 'pi';
+ id: string;
+ title: string;
+ cwd: string;
+ updatedAt: number;
+ file: string;
+ digest: WorkbenchDigest | null;
+}
+
+export function authorizeExternalCandidate(
+ candidate: Pick<WorkbenchExternalCandidate, 'cwd'> | null,
+ projectDirs: readonly string[],
+ caseInsensitive: boolean,
+): WorkbenchTargetDecision {
+ if (!candidate) {
+ return { ok: false, errorCode: 'TASK_NOT_FOUND', message: '找不到这条本机会话(只看最近 30 天)' };
+ }
+ const projectDir = findWorkbenchProject(candidate.cwd, projectDirs, caseInsensitive);
+ if (!projectDir) {
+ return { ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH', message: '这条本机会话不在主人交给你的项目里' };
+ }
+ return { ok: true, projectDir };
+}
+
+/** 项目里一件 Cindy 候选任务的原始事实(未推导状态)。 */
+export interface WorkbenchTaskRow {
+ id: string;
+ title: string;
+ workingDir: string | null;
+ agentKind: string | null;
+ summary: string | null;
+ lastActiveAt: number | null;
+ messageCount?: number | null;
+}
+
+export interface WorkbenchRoutineRow {
+ id: string;
+ name: string;
+ enabled: boolean;
+ activity?: 'queued' | 'running';
+ lastResult: string | null;
+}
+
+export interface WorkbenchScheduleRow {
+ id: string;
+ name: string;
+ status: string;
+ source?: string;
+ workspaceKind?: string;
+ workingDir?: string | null;
+ nextFireAt?: number | null;
+}
+
+export interface BotWorkbenchAccessDeps {
+ resolveCaller(callerSessionId: string): Promise<WorkbenchCallerResult>;
+ readState(botId: string): Promise<{ directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> }>;
+ projectExists?(dir: string): Promise<boolean>;
+ readTarget(sessionId: string): Promise<WorkbenchTargetFacts | null>;
+ /**
+ * 已接手项目里的 Cindy 候选任务,按最近活动倒序;不含伙伴隐藏任务与从未发过消息的草稿。
+ * `alwaysInclude` 里的任务(伙伴刚开、还在排队的后台任务)即使还没有消息也要列出。
+ */
+ listProjectTasks(projectDirs: readonly string[], alwaysInclude: ReadonlySet<string>): Promise<WorkbenchTaskRow[]>;
+ /** 已接手项目里近期的本机 Claude Code / Codex / Pi 会话(当前库里已有的除外),带摘要。 */
+ listExternalCandidates(
+ projectDirs: readonly string[],
+ ): Promise<{ sessions: WorkbenchExternalCandidate[]; olderCount: number; overflowCount?: number }>;
+ /** 本机会话已经是当前 Cindy 库里的任务时,对应的 Cindy session id。 */
+ findImportedSession(source: 'claude' | 'codex' | 'pi', externalId: string): Promise<string | null>;
+ /** 只导入这一条外部会话(仅 Claude Code / Codex 支持),返回它的 Cindy session id。 */
+ importExternal(source: 'claude' | 'codex', externalId: string): Promise<{ ok: true; sessionId: string } | Failure>;
+ /** 在项目目录里开一条伙伴后台任务(start_session_task 的服务端路径)。 */
+ startBackgroundTask(params: {
+ callerSessionId: string;
+ workingDir: string;
+ title: string;
+ objective: string;
+ }): Promise<{ ok: true; sessionId: string } | Failure>;
+ readSessionDigest(sessionId: string, updatedAt: number): Promise<WorkbenchDigest>;
+ readBrief(projectDir: string): Promise<WorkbenchProjectBrief>;
+ /** 该伙伴自己的后台任务:执行任务 id → 状态。 */
+ listDelegations(botId: string): Promise<Map<string, WorkbenchDelegationStatus>>;
+ readActivityPhase(sessionId: string): Promise<string | null>;
+ listRoutines(botId: string): Promise<WorkbenchRoutineRow[]>;
+ listSchedules(): Promise<WorkbenchScheduleRow[]>;
+ readSessionTranscript(sessionId: string): Promise<WorkbenchTranscript>;
+ readExternalTranscript(candidate: WorkbenchExternalCandidate): Promise<WorkbenchTranscript | null>;
+ saveJudgment(
+ botId: string,
+ taskId: string,
+ judgment: Omit<WorkbenchTaskJudgment, 'updatedAt'>,
+ ): Promise<WorkbenchTaskJudgment>;
+ rekeyJudgment(botId: string, fromTaskId: string, toTaskId: string): Promise<void>;
+ deleteJudgment(botId: string, taskId: string): Promise<void>;
+ notifyChanged(botId: string): void;
+ sendToSession(params: {
+ targetSessionId: string;
+ message: string;
+ dispatcherSessionId: string;
+ }): Promise<{ ok: true; wakeKind: string; queuedMessageId?: string } | Failure>;
+ stopSessionTurn(params: {
+ targetSessionId: string;
+ }): Promise<
+ | { ok: true; status: 'no-active-turn' | 'waiting-for-safe-point' | 'requested' | 'unconfirmed' }
+ | Failure
+ >;
+ caseInsensitive: boolean;
+ now?(): number;
+ /** 账号切换守卫:返回 false 时中止,不做任何写入或投递。 */
+ isOwnerScopeCurrent?(): boolean;
+}
+
+function projectName(dir: string): string {
+ return dir.split(/[\\/]/).filter(Boolean).pop() ?? dir;
+}
+
+const scopeChanged: Failure = { ok: false, errorCode: 'OWNER_SCOPE_CHANGED', message: '账号已切换,请重试' };
+
+type ResolvedTarget =
+ | { ok: true; kind: 'session'; taskId: string; sessionId: string; projectDir: string }
+ | {
+ ok: true;
+ kind: 'external';
+ taskId: string;
+ candidate: WorkbenchExternalCandidate;
+ projectDir: string;
+ }
+ | { ok: true; kind: 'item'; taskId: string; ref: WorkbenchTaskRef; projectDir: string };
+
+const VERDICTS: readonly WorkbenchVerdict[] = ['unfinished', 'idea', 'done'];
+const SOURCE_LABEL = { claude: 'Claude Code', codex: 'Codex', pi: 'Pi' } as const;
+
+export interface WorkbenchJudgmentInput {
+ taskId: string;
+ title: string;
+ verdict: string;
+ next?: string | null;
+ ref?: string | null;
+ /** 建议(idea:)挂在哪个项目;只交了一个项目时可省略。项目路径或项目名。 */
+ project?: string | null;
+}
+
+export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
+ const scopeCurrent = () => deps.isOwnerScopeCurrent?.() ?? true;
+ const now = () => deps.now?.() ?? Date.now();
+
+ const resolveSession = async (
+ sessionId: string,
+ projectDirs: readonly string[],
+ ): Promise<ResolvedTarget | Failure> => {
+ const decision = authorizeWorkbenchTarget(await deps.readTarget(sessionId), projectDirs, deps.caseInsensitive);
+ if (!decision.ok) return decision;
+ return { ok: true, kind: 'session', taskId: sessionId, sessionId, projectDir: decision.projectDir };
+ };
+
+ // 同一次调用(尤其批量写)里多次解析外部会话时,只扫一次目录。
+ let externalsMemo: { key: string; at: number; value: ReturnType<BotWorkbenchAccessDeps['listExternalCandidates']> } | null = null;
+ const listExternals = (projectDirs: readonly string[]) => {
+ const key = projectDirs.join('\n');
+ if (!externalsMemo || externalsMemo.key !== key || now() - externalsMemo.at > 5_000) {
+ externalsMemo = { key, at: now(), value: deps.listExternalCandidates(projectDirs) };
+ }
+ return externalsMemo.value;
+ };
+
+ const projectForRepo = async (owner: string, repo: string, projectDirs: readonly string[]) => {
+ const wanted = `${owner}/${repo}`.toLowerCase();
+ for (const dir of projectDirs) {
+ const brief = await deps.readBrief(dir).catch(() => null);
+ if (brief?.git?.remotes.some((remote) => remote.toLowerCase() === wanted)) return dir;
+ }
+ return null;
+ };
+
+ const projectByHint = (hint: string | null | undefined, projectDirs: readonly string[]) => {
+ if (!hint) return projectDirs.length === 1 ? projectDirs[0] : null;
+ return (
+ findWorkbenchProject(hint, projectDirs, deps.caseInsensitive)
+ ?? projectDirs.find((dir) => projectName(dir).toLowerCase() === hint.trim().toLowerCase())
+ ?? null
+ );
+ };
+
+ const resolveTarget = async (
+ taskId: string,
+ workbench: { directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> },
+ projectHint?: string | null,
+ ): Promise<ResolvedTarget | Failure> => {
+ const projectDirs = workbench.directories;
+ const ref = parseWorkbenchTaskId(taskId);
+ if (!ref) return { ok: false, errorCode: 'TASK_NOT_FOUND', message: '任务 id 格式不对' };
+ if (ref.kind === 'session') return resolveSession(ref.sessionId, projectDirs);
+ const canonical = canonicalWorkbenchTaskId(ref);
+ if (ref.kind === 'github') {
+ const projectDir = await projectForRepo(ref.owner, ref.repo, projectDirs);
+ if (!projectDir) {
+ return { ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH', message: '这个仓库不是主人交给你的项目的 GitHub 远端' };
+ }
+ return { ok: true, kind: 'item', taskId: canonical, ref, projectDir };
+ }
+ if (ref.kind === 'idea') {
+ const existing = workbench.tasks[canonical]?.project;
+ const projectDir = projectByHint(projectHint ?? existing, projectDirs)
+ ?? (existing ? findWorkbenchProject(existing, projectDirs, deps.caseInsensitive) : null);
+ if (!projectDir) {
+ return {
+ ok: false,
+ errorCode: projectDirs.length > 1 ? 'PROJECT_REQUIRED' : 'TASK_OUTSIDE_WORKBENCH',
+ message: projectDirs.length > 1 ? '交了不止一个项目,请用 project 指明这条建议属于哪个项目' : '这条建议不在主人交给你的项目里',
+ };
+ }
+ return { ok: true, kind: 'item', taskId: canonical, ref, projectDir };
+ }
+ const imported = await deps.findImportedSession(ref.source, ref.externalId);
+ if (imported) return resolveSession(imported, projectDirs);
+ const { sessions } = await listExternals(projectDirs);
+ const candidate = sessions.find((item) => item.source === ref.source && item.id === ref.externalId) ?? null;
+ const decision = authorizeExternalCandidate(candidate, projectDirs, deps.caseInsensitive);
+ if (!decision.ok) return decision;
+ return { ok: true, kind: 'external', taskId: canonical, candidate: candidate!, projectDir: decision.projectDir };
+ };
+
+ const authorize = async (callerSessionId: string, taskId: string, projectHint?: string | null) => {
+ const caller = await deps.resolveCaller(callerSessionId);
+ if (!caller.ok) return caller;
+ const workbench = await deps.readState(caller.botId);
+ const target = await resolveTarget(taskId, workbench, projectHint);
+ if (!target.ok) return target;
+ if (!scopeCurrent()) return scopeChanged;
+ return { ok: true as const, botId: caller.botId, workbench, target };
+ };
+
+ /**
+ * 主人可能在这次调用进行中收回了项目:在返回内容或做任何投递 / 停止之前再读一次
+ * 已接手的项目,确认目标所在项目仍在。
+ */
+ const stillGranted = async (botId: string, projectDir: string): Promise<Failure | null> => {
+ const { directories } = await deps.readState(botId);
+ if (!directories.includes(projectDir)) {
+ return { ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH', message: '主人已收回这个项目' };
+ }
+ return scopeCurrent() ? null : scopeChanged;
+ };
+
+ const readTranscript = async (target: ResolvedTarget): Promise<WorkbenchTranscript | Failure | null> => {
+ if (target.kind === 'session') return deps.readSessionTranscript(target.sessionId);
+ if (target.kind === 'external') return deps.readExternalTranscript(target.candidate);
+ return { ok: false, errorCode: 'TASK_NOT_READABLE', message: 'PR、issue 与建议没有对话记录,请直接看链接或项目文件' };
+ };
+
+ const validateJudgment = (
+ input: WorkbenchJudgmentInput,
+ ): { ok: true; title: string; verdict: WorkbenchVerdict; next: string } | Failure => {
+ const title = input.title.replace(/\s+/g, ' ').trim();
+ const next = (input.next ?? '').replace(/\s+/g, ' ').trim();
+ if (!title || title.length > WORKBENCH_JUDGMENT_TITLE_MAX) {
+ return { ok: false, errorCode: 'INVALID_ARGS', message: `title 不能为空,且不超过 ${WORKBENCH_JUDGMENT_TITLE_MAX} 字` };
+ }
+ if (!VERDICTS.includes(input.verdict as WorkbenchVerdict)) {
+ return { ok: false, errorCode: 'INVALID_ARGS', message: 'verdict 只能是 unfinished / idea / done' };
+ }
+ if (next.length > WORKBENCH_JUDGMENT_NEXT_MAX) {
+ return { ok: false, errorCode: 'INVALID_ARGS', message: `next 不超过 ${WORKBENCH_JUDGMENT_NEXT_MAX} 字` };
+ }
+ if (input.verdict !== 'done' && !next) {
+ return { ok: false, errorCode: 'INVALID_ARGS', message: '没做完或聊过没下文的任务需要写一句 next' };
+ }
+ return { ok: true, title, verdict: input.verdict as WorkbenchVerdict, next };
+ };
+
+ const saveOne = async (
+ botId: string,
+ workbench: { directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> },
+ input: WorkbenchJudgmentInput,
+ ) => {
+ const valid = validateJudgment(input);
+ if (!valid.ok) return { taskId: input.taskId, ...valid };
+ const target = await resolveTarget(input.taskId, workbench, input.project);
+ if (!target.ok) return { taskId: input.taskId, ...target };
+ let ref: string | null = null;
+ if (input.ref) {
+ const checked = validateWorkbenchRef(input.ref, workbench.directories, deps.caseInsensitive);
+ if (!checked.ok) {
+ return {
+ taskId: input.taskId,
+ ok: false as const,
+ errorCode: 'INVALID_REF',
+ message: 'ref 只能是 https 链接,或主人交给你的项目里的路径',
+ };
+ }
+ ref = checked.ref;
+ }
+ const saved = await deps.saveJudgment(botId, target.taskId, {
+ title: valid.title,
+ verdict: valid.verdict,
+ next: valid.next || null,
+ project: target.projectDir,
+ ref,
+ });
+ return { taskId: target.taskId, ok: true as const, judgment: saved };
+ };
+
+ /** 在项目目录里开一条伙伴后台任务承接这件事,工作台上的条目随之变成「你交代的」。 */
+ const continueAsBackgroundTask = async (
+ callerSessionId: string,
+ botId: string,
+ target: ResolvedTarget,
+ judgment: WorkbenchTaskJudgment | undefined,
+ message: string,
+ ) => {
+ const title = judgment?.title
+ ?? (target.kind === 'external' ? cleanWorkbenchTitle(target.candidate.title, UNTITLED) : UNTITLED);
+ const background: string[] = [];
+ if (judgment?.next) background.push(`下一步:${judgment.next}`);
+ if (judgment?.ref) background.push(`参考:${judgment.ref}`);
+ if (target.kind === 'item' && target.ref.kind === 'github') {
+ background.push(`GitHub ${target.ref.type === 'pr' ? 'PR' : 'issue'}:${target.ref.owner}/${target.ref.repo}#${target.ref.number}`);
+ }
+ if (target.kind === 'external') {
+ const digest = target.candidate.digest;
+ background.push(`这件事之前在本机 ${SOURCE_LABEL[target.candidate.source]} 会话里做过(转录:${target.candidate.file})。`);
+ if (digest?.purpose) background.push(`起始目的:${digest.purpose}`);
+ for (const item of digest?.recent ?? []) background.push(`${item.role === 'user' ? '用户' : '助手'}:${item.text}`);
+ }
+ const objective = [title, message, ...background].join('\n\n').slice(0, 8_000);
+ const revoked = await stillGranted(botId, target.projectDir);
+ if (revoked) return revoked;
+ const started = await deps.startBackgroundTask({ callerSessionId, workingDir: target.projectDir, title, objective });
+ if (!started.ok) return started;
+ if (judgment) await deps.deleteJudgment(botId, target.taskId);
+ deps.notifyChanged(botId);
+ return { ok: true as const, taskId: started.sessionId, delivery: 'started' as const, startedFrom: target.taskId };
+ };
+
+ return {
+ async get(params: { callerSessionId: string }) {
+ const caller = await deps.resolveCaller(params.callerSessionId);
+ if (!caller.ok) return caller;
+ const workbench = await deps.readState(caller.botId);
+ const projectDirs = workbench.directories;
+ const since = now() - WORKBENCH_RECENT_WINDOW_MS;
+ const delegations = await deps.listDelegations(caller.botId);
+ const [rows, externals, routines, schedules, exists, briefs] = await Promise.all([
+ projectDirs.length
+ ? deps.listProjectTasks(projectDirs, new Set(delegations.keys()))
+ : Promise.resolve([]),
+ projectDirs.length ? listExternals(projectDirs) : Promise.resolve({ sessions: [], olderCount: 0, overflowCount: 0 }),
+ deps.listRoutines(caller.botId),
+ projectDirs.length ? deps.listSchedules() : Promise.resolve([]),
+ Promise.all(projectDirs.map((dir) => deps.projectExists?.(dir) ?? Promise.resolve(true))),
+ Promise.all(projectDirs.map((dir) => deps.readBrief(dir).catch(() => null))),
+ ]);
+ type Candidate = {
+ taskId: string;
+ source: 'cindy' | 'claude-code' | 'codex' | 'pi';
+ title: string;
+ project: string;
+ lastActiveMs: number;
+ messageCount: number | null;
+ row?: WorkbenchTaskRow;
+ digest: WorkbenchDigest | null;
+ };
+ const all: Candidate[] = [];
+ let olderCount = externals.olderCount;
+ for (const row of rows) {
+ const project = findWorkbenchProject(row.workingDir, projectDirs, deps.caseInsensitive);
+ if (!project) continue;
+ const lastActiveMs = row.lastActiveAt ?? 0;
+ // 只看近期;伙伴自己的后台任务不管多久都列出。
+ if (lastActiveMs < since && !delegations.has(row.id)) {
+ olderCount += 1;
+ continue;
+ }
+ all.push({
+ taskId: row.id,
+ source: importedSessionOrigin(row.id, row.agentKind) ?? 'cindy',
+ title: cleanWorkbenchTitle(row.title, UNTITLED),
+ project: projectName(project),
+ lastActiveMs,
+ messageCount: row.messageCount ?? null,
+ row,
+ digest: null,
+ });
+ }
+ for (const external of externals.sessions) {
+ const project = findWorkbenchProject(external.cwd, projectDirs, deps.caseInsensitive);
+ if (!project) continue;
+ all.push({
+ taskId: `${external.source}:${external.id}`,
+ source: external.source === 'claude' ? 'claude-code' : external.source,
+ title: cleanWorkbenchTitle(external.title, UNTITLED),
+ project: projectName(project),
+ lastActiveMs: external.updatedAt,
+ messageCount: null,
+ digest: external.digest,
+ });
+ }
+ all.sort((a, b) => b.lastActiveMs - a.lastActiveMs);
+ const cindy = all.filter((candidate) => candidate.row).slice(0, WORKBENCH_TOOL_MAX_CINDY_TASKS);
+ const external = all
+ .filter((candidate) => !candidate.row)
+ .slice(0, WORKBENCH_TOOL_MAX_TASKS - cindy.length);
+ const shown = [...cindy, ...external].sort((a, b) => b.lastActiveMs - a.lastActiveMs);
+ const tasks = await Promise.all(
+ shown.map(async (candidate) => {
+ const delegationStatus = candidate.row ? (delegations.get(candidate.row.id) ?? null) : null;
+ const state: WorkbenchTaskState | null = candidate.row
+ ? deriveWorkbenchSessionState({
+ activityPhase: await deps.readActivityPhase(candidate.row.id),
+ delegationStatus,
+ })
+ : null;
+ const digest = candidate.row
+ ? await deps.readSessionDigest(candidate.row.id, candidate.lastActiveMs).catch(() => null)
+ : candidate.digest;
+ const judgment = workbench.tasks[candidate.taskId] ?? null;
+ return {
+ taskId: candidate.taskId,
+ source: candidate.source,
+ imported: Boolean(candidate.row),
+ title: candidate.title,
+ project: candidate.project,
+ state,
+ kind: delegationStatus ? ('delegated' as const) : ('existing' as const),
+ lastActiveAt: candidate.lastActiveMs ? new Date(candidate.lastActiveMs).toISOString() : null,
+ messageCount: candidate.messageCount,
+ digest,
+ judgment: judgment
+ ? { title: judgment.title, verdict: judgment.verdict, next: judgment.next, updatedAt: judgment.updatedAt }
+ : null,
+ };
+ }),
+ );
+ // PR / issue / 建议:伙伴之前写过的判断原样带回,便于它整理。
+ const items = Object.entries(workbench.tasks).flatMap(([taskId, judgment]) => {
+ const ref = parseWorkbenchTaskId(taskId);
+ if (!ref || (ref.kind !== 'github' && ref.kind !== 'idea')) return [];
+ const project = findWorkbenchProject(judgment.project, projectDirs, deps.caseInsensitive);
+ if (!project) return [];
+ return [{
+ taskId,
+ project: projectName(project),
+ judgment: {
+ title: judgment.title,
+ verdict: judgment.verdict,
+ next: judgment.next,
+ ref: judgment.ref ?? null,
+ updatedAt: judgment.updatedAt,
+ },
+ }];
+ });
+ const automations = [
+ ...routines.map((routine) => ({
+ id: routine.id,
+ name: routine.name,
+ kind: 'routine' as const,
+ state: deriveWorkbenchAutomationState({
+ enabled: routine.enabled,
+ running: routine.activity === 'running',
+ queued: routine.activity === 'queued',
+ }),
+ project: null,
+ nextRunAt: null,
+ lastResult: boundWorkbenchSummary(routine.lastResult),
+ })),
+ ...schedules.flatMap((schedule) => {
+ if (schedule.source === 'bot' || schedule.workspaceKind === 'dialogue') return [];
+ const project = findWorkbenchProject(schedule.workingDir, projectDirs, deps.caseInsensitive);
+ if (!project) return [];
+ return [{
+ id: schedule.id,
+ name: schedule.name,
+ kind: 'automation' as const,
+ state: deriveWorkbenchAutomationState({ enabled: schedule.status === 'active' }),
+ project: projectName(project),
+ nextRunAt: schedule.nextFireAt ? new Date(schedule.nextFireAt).toISOString() : null,
+ lastResult: null,
+ }];
+ }),
+ ];
+ const counts = { unfinished: 0, idea: 0, done: 0, unjudged: 0 };
+ for (const task of tasks) {
+ if (task.judgment) counts[task.judgment.verdict] += 1;
+ else if (task.kind !== 'delegated') counts.unjudged += 1;
+ }
+ if (!scopeCurrent()) return scopeChanged;
+ return {
+ ok: true as const,
+ workbench: {
+ projects: projectDirs.map((dir, index) => ({
+ name: projectName(dir),
+ path: dir,
+ exists: exists[index] ?? true,
+ brief: briefs[index],
+ })),
+ tasks,
+ items,
+ automations,
+ counts,
+ truncated: all.length > shown.length || (externals.overflowCount ?? 0) > 0,
+ totalTasks: all.length + (externals.overflowCount ?? 0),
+ olderCount,
+ },
+ };
+ },
+
+ async read(params: { callerSessionId: string; taskId: string }) {
+ const allowed = await authorize(params.callerSessionId, params.taskId);
+ if (!allowed.ok) return allowed;
+ const transcript = await readTranscript(allowed.target);
+ if (!transcript) return { ok: false as const, errorCode: 'TRANSCRIPT_UNAVAILABLE', message: '读不到这条会话的记录' };
+ if ('ok' in transcript) return transcript;
+ const revoked = await stillGranted(allowed.botId, allowed.target.projectDir);
+ if (revoked) return revoked;
+ return { ok: true as const, taskId: allowed.target.taskId, transcript };
+ },
+
+ async set(params: { callerSessionId: string } & WorkbenchJudgmentInput) {
+ const caller = await deps.resolveCaller(params.callerSessionId);
+ if (!caller.ok) return caller;
+ const valid = validateJudgment(params);
+ if (!valid.ok) return valid;
+ const workbench = await deps.readState(caller.botId);
+ if (!scopeCurrent()) return scopeChanged;
+ const result = await saveOne(caller.botId, workbench, params);
+ if (!result.ok) return { ok: false as const, errorCode: result.errorCode, message: result.message };
+ deps.notifyChanged(caller.botId);
+ return { ok: true as const, taskId: result.taskId, judgment: result.judgment };
+ },
+
+ /** 批量写判断:逐条校验,一条失败不影响其它条;最后只广播一次。 */
+ async setMany(params: { callerSessionId: string; items: WorkbenchJudgmentInput[] }) {
+ if (params.items.length === 0 || params.items.length > WORKBENCH_TOOL_MAX_BATCH) {
+ return { ok: false as const, errorCode: 'INVALID_ARGS', message: `一次写 1–${WORKBENCH_TOOL_MAX_BATCH} 条` };
+ }
+ const caller = await deps.resolveCaller(params.callerSessionId);
+ if (!caller.ok) return caller;
+ if (!scopeCurrent()) return scopeChanged;
+ const results = [];
+ for (const item of params.items) {
+ const workbench = await deps.readState(caller.botId);
+ results.push(await saveOne(caller.botId, workbench, item));
+ }
+ if (results.some((result) => result.ok)) deps.notifyChanged(caller.botId);
+ return {
+ ok: true as const,
+ saved: results.filter((result) => result.ok).length,
+ results: results.map((result) =>
+ result.ok
+ ? { taskId: result.taskId, ok: true as const }
+ : { taskId: result.taskId, ok: false as const, errorCode: result.errorCode, message: result.message },
+ ),
+ };
+ },
+
+ async continueTask(params: { callerSessionId: string; taskId: string; message: string }) {
+ const message = params.message.trim();
+ if (!message || message.length > WORKBENCH_TOOL_MAX_MESSAGE_CHARS) {
+ return { ok: false as const, errorCode: 'INVALID_ARGS', message: `消息不能为空,且不超过 ${WORKBENCH_TOOL_MAX_MESSAGE_CHARS} 字` };
+ }
+ const allowed = await authorize(params.callerSessionId, params.taskId);
+ if (!allowed.ok) return allowed;
+ const target = allowed.target;
+ const judgment = allowed.workbench.tasks[target.taskId];
+ if (target.kind === 'item') {
+ if (!judgment) {
+ return { ok: false as const, errorCode: 'TASK_NOT_FOUND', message: '先用 set_workbench_task 写下这件事,再继续' };
+ }
+ return continueAsBackgroundTask(params.callerSessionId, allowed.botId, target, judgment, message);
+ }
+ let sessionId: string;
+ let imported = false;
+ const revokedBefore = await stillGranted(allowed.botId, target.projectDir);
+ if (revokedBefore) return revokedBefore;
+ if (target.kind === 'external') {
+ // 主人点头的这一件才导入:只导入这一条,判断改挂到新的任务上。Pi 会话没有导入路径,
+ // Claude Code / Codex 导入不了时(例如转录在另一个 Cindy profile 里),改为在项目里开一条
+ // 伙伴后台任务承接,并带上原会话的摘要。
+ const result = target.candidate.source === 'pi'
+ ? null
+ : await deps.importExternal(target.candidate.source, target.candidate.id);
+ if (!result || !result.ok) {
+ return continueAsBackgroundTask(params.callerSessionId, allowed.botId, target, judgment, message);
+ }
+ if (!scopeCurrent()) return scopeChanged;
+ await deps.rekeyJudgment(allowed.botId, target.taskId, result.sessionId);
+ imported = true;
+ deps.notifyChanged(allowed.botId);
+ const recheck = await resolveSession(result.sessionId, allowed.workbench.directories);
+ if (!recheck.ok) return recheck;
+ sessionId = result.sessionId;
+ } else {
+ sessionId = target.sessionId;
+ }
+ const revoked = await stillGranted(allowed.botId, target.projectDir);
+ if (revoked) return revoked;
+ const sent = await deps.sendToSession({
+ targetSessionId: sessionId,
+ message,
+ dispatcherSessionId: params.callerSessionId,
+ });
+ if (!sent.ok) return sent;
+ return {
+ ok: true as const,
+ taskId: sessionId,
+ delivery: sent.wakeKind === 'queued' ? ('queued' as const) : ('started' as const),
+ ...(sent.queuedMessageId ? { queuedMessageId: sent.queuedMessageId } : {}),
+ ...(imported ? { importedFrom: target.taskId } : {}),
+ };
+ },
+
+ async stopTask(params: { callerSessionId: string; taskId: string }) {
+ const allowed = await authorize(params.callerSessionId, params.taskId);
+ if (!allowed.ok) return allowed;
+ if (allowed.target.kind !== 'session') {
+ return { ok: false as const, errorCode: 'TASK_NOT_RUNNING', message: '这件事还没在 Cindy 里跑,没有可停的' };
+ }
+ const revoked = await stillGranted(allowed.botId, allowed.target.projectDir);
+ if (revoked) return revoked;
+ const stopped = await deps.stopSessionTurn({ targetSessionId: allowed.target.sessionId });
+ if (!stopped.ok) return stopped;
+ return { ok: true as const, taskId: allowed.target.sessionId, status: stopped.status };
+ },
+
+ /**
+ * 渲染层详情视图读取同一份有界摘录。调用方是主人自己的界面(受信 renderer),
+ * 仍按该伙伴已接手的项目判定范围,不让详情视图成为读任意会话的入口。
+ */
+ async readForOwner(params: { botId: string; taskId: string }) {
+ const workbench = await deps.readState(params.botId);
+ const target = await resolveTarget(params.taskId, workbench);
+ if (!target.ok) return target;
+ const transcript = await readTranscript(target);
+ if (!transcript) return { ok: false as const, errorCode: 'TRANSCRIPT_UNAVAILABLE', message: '读不到这条会话的记录' };
+ if ('ok' in transcript) return transcript;
+ if (!scopeCurrent()) return scopeChanged;
+ return { ok: true as const, taskId: target.taskId, transcript };
+ },
+
+ /** 工作台用:已接手项目里近期本机会话的 id 与最近活动(判断「正在了解」与排序)。 */
+ async listCandidatesForOwner(params: { botId: string }) {
+ const workbench = await deps.readState(params.botId);
+ if (workbench.directories.length === 0) return { ok: true as const, candidates: [] };
+ const { sessions } = await listExternals(workbench.directories);
+ if (!scopeCurrent()) return scopeChanged;
+ return {
+ ok: true as const,
+ candidates: sessions.map((item) => ({
+ source: item.source,
+ id: item.id,
+ projectDir: item.cwd,
+ updatedAt: new Date(item.updatedAt).toISOString(),
+ archived: false,
+ })),
+ };
+ },
+ };
+}
+
+export type BotWorkbenchAccess = ReturnType<typeof createBotWorkbenchAccess>;
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchBrief.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchBrief.ts
new file mode 100644
index 0000000000..0776457b0c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchBrief.ts
@@ -0,0 +1,252 @@
+/**
+ * 伙伴工作台的项目素材(brief):宿主现算、有界、只看近期、带缓存,不经过模型。
+ *
+ * - docs:顶层与 `docs/` 下两级以内的 Markdown 文件路径(最多 30 个),只给路径不给正文;顺序为
+ * 顶层 README / DESIGN / AGENTS / CLAUDE → docs 里同名的 → `docs/product-rules` → `docs/dev-rules`
+ * → 其余顶层 → 其余 docs;
+ * - recent:不是 git 仓库时,最近 14 天改过的文件(最多 20 个,跳过隐藏目录与 node_modules 等),
+ * 让伙伴在没有提交记录时也知道最近动了什么;
+ * - git:当前分支、未提交改动数、最近 14 天的提交(最多 30 条)、最近有提交的本地分支(最多 10 个);
+ * 每条命令限时,拿不到就缺项;
+ * - github:远端是 GitHub 且本机已有 gh 登录时,我打开的 PR 与指派给我 / 我开的 issue(各最多 10 条);
+ * 没有凭证返回 `unavailable: 'no-credential'`,不猜、不弹登录。
+ * 按项目缓存 60 秒,目录 mtime 或 git HEAD / index 变化即失效。
+ */
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+export interface WorkbenchBriefCommit {
+ sha: string;
+ date: string;
+ author: string;
+ subject: string;
+}
+
+export interface WorkbenchBriefGithubItem {
+ number: number;
+ title: string;
+ state: string;
+ updatedAt: string;
+ url: string;
+}
+
+export interface WorkbenchProjectBrief {
+ docs: string[];
+ /** 不是 git 仓库时最近 14 天改过的文件;git 仓库为空(看 git.commits)。 */
+ recent: Array<{ path: string; modifiedAt: string }>;
+ git: {
+ branch: string | null;
+ changes: number | null;
+ commits: WorkbenchBriefCommit[];
+ branches: Array<{ name: string; date: string }>;
+ /** 查 PR / issue 用的 GitHub `owner/repo`:fork 工作流优先 `upstream`,否则 `origin`;都不是 GitHub 为 null。 */
+ remote: string | null;
+ /** `upstream` 与 `origin` 里所有 GitHub `owner/repo`(条目归属项目时都认)。 */
+ remotes: string[];
+ } | null;
+ github:
+ | { repo: string; pullRequests: WorkbenchBriefGithubItem[]; issues: WorkbenchBriefGithubItem[] }
+ | { unavailable: 'no-credential' | 'not-github' | 'error' };
+}
+
+export interface WorkbenchBriefDeps {
+ /** 在 cwd 里跑 git,失败返回 null(限时由实现保证)。 */
+ git(cwd: string, args: string[]): Promise<string | null>;
+ /** 以 GitHub 搜索语法查 issue / PR;没有凭证返回 null。 */
+ searchGithub(query: string, limit: number): Promise<WorkbenchBriefGithubItem[] | null>;
+ now(): number;
+}
+
+export const BRIEF_MAX_DOCS = 30;
+export const BRIEF_MAX_COMMITS = 30;
+export const BRIEF_MAX_BRANCHES = 10;
+export const BRIEF_MAX_GITHUB = 10;
+export const BRIEF_MAX_RECENT_FILES = 20;
+const BRIEF_RECENT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
+/** 找最近改过的文件时最多看这么多目录项,大目录也有界。 */
+const RECENT_SCAN_BUDGET = 3_000;
+const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'out', 'target', 'vendor', 'Pods', 'DerivedData', '__pycache__']);
+export const BRIEF_TTL_MS = 60_000;
+const DOC_PRIORITY = /^(readme|design|agents|claude)(\.|$)/i;
+
+/** 从 git 远端地址解析 GitHub 的 `owner/repo`。 */
+export function parseGithubRemote(url: string | null | undefined): string | null {
+ if (!url) return null;
+ const match = /github\.com[:/]([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(url.trim());
+ return match ? `${match[1]}/${match[2]}` : null;
+}
+
+async function listMarkdown(projectDir: string): Promise<string[]> {
+ const out: string[] = [];
+ const visit = async (dir: string, depth: number) => {
+ if (out.length >= 200) return;
+ let entries: import('node:fs').Dirent[];
+ try {
+ entries = await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isFile() && /\.mdx?$/i.test(entry.name)) out.push(full);
+ // docs/ 本身算第一层,再往下两级:docs/<a>/<b>/*.md。
+ else if (entry.isDirectory() && depth < 3 && (depth > 0 || entry.name === 'docs')) await visit(full, depth + 1);
+ }
+ };
+ await visit(projectDir, 0);
+ const rank = (file: string) => {
+ const relative = path.relative(projectDir, file).split(path.sep).join('/');
+ const top = !relative.includes('/');
+ const key = DOC_PRIORITY.test(path.basename(file));
+ if (top && key) return 0;
+ if (key) return 1;
+ if (relative.startsWith('docs/product-rules/')) return 2;
+ if (relative.startsWith('docs/dev-rules/')) return 3;
+ return top ? 4 : 5;
+ };
+ return out
+ .sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
+ .slice(0, BRIEF_MAX_DOCS);
+}
+
+async function listRecentFiles(projectDir: string, since: number): Promise<WorkbenchProjectBrief['recent']> {
+ const found: Array<{ path: string; mtimeMs: number }> = [];
+ let budget = RECENT_SCAN_BUDGET;
+ const visit = async (dir: string, depth: number) => {
+ if (budget <= 0) return;
+ let entries: import('node:fs').Dirent[];
+ try {
+ entries = await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (--budget <= 0) return;
+ if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (depth < 4) await visit(full, depth + 1);
+ } else if (entry.isFile()) {
+ const stat = await fs.stat(full).catch(() => null);
+ if (stat && stat.mtimeMs >= since) found.push({ path: full, mtimeMs: stat.mtimeMs });
+ }
+ }
+ };
+ await visit(projectDir, 0);
+ return found
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
+ .slice(0, BRIEF_MAX_RECENT_FILES)
+ .map((file) => ({ path: file.path, modifiedAt: new Date(file.mtimeMs).toISOString() }));
+}
+
+function parseCommits(raw: string | null): WorkbenchBriefCommit[] {
+ if (!raw) return [];
+ return raw
+ .split('\n')
+ .filter(Boolean)
+ .slice(0, BRIEF_MAX_COMMITS)
+ .map((line) => {
+ const [sha = '', date = '', author = '', subject = ''] = line.split('\u0000');
+ return { sha, date, author: author.slice(0, 80), subject: subject.slice(0, 200) };
+ })
+ .filter((commit) => commit.sha);
+}
+
+export async function buildProjectBrief(projectDir: string, deps: WorkbenchBriefDeps): Promise<WorkbenchProjectBrief> {
+ const sinceIso = new Date(deps.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
+ const [docs, inside] = await Promise.all([
+ listMarkdown(projectDir),
+ deps.git(projectDir, ['rev-parse', '--is-inside-work-tree']),
+ ]);
+ if (inside?.trim() !== 'true') {
+ const recent = await listRecentFiles(projectDir, deps.now() - BRIEF_RECENT_WINDOW_MS);
+ return { docs, recent, git: null, github: { unavailable: 'not-github' } };
+ }
+ const [branch, status, log, refs, upstreamUrl, originUrl] = await Promise.all([
+ deps.git(projectDir, ['rev-parse', '--abbrev-ref', 'HEAD']),
+ deps.git(projectDir, ['status', '--porcelain']),
+ deps.git(projectDir, [
+ 'log',
+ `--since=${sinceIso}`,
+ `--max-count=${BRIEF_MAX_COMMITS}`,
+ '--format=%h%x00%cI%x00%an%x00%s',
+ ]),
+ deps.git(projectDir, [
+ 'for-each-ref',
+ '--sort=-committerdate',
+ `--count=${BRIEF_MAX_BRANCHES}`,
+ '--format=%(refname:short)%00%(committerdate:iso-strict)',
+ 'refs/heads',
+ ]),
+ deps.git(projectDir, ['remote', 'get-url', 'upstream']),
+ deps.git(projectDir, ['remote', 'get-url', 'origin']),
+ ]);
+ const remotes = [...new Set([parseGithubRemote(upstreamUrl), parseGithubRemote(originUrl)].filter((item): item is string => Boolean(item)))];
+ const remote = remotes[0] ?? null;
+ const git = {
+ branch: branch?.trim() && branch.trim() !== 'HEAD' ? branch.trim() : null,
+ changes: status === null ? null : status.split('\n').filter(Boolean).length,
+ commits: parseCommits(log),
+ branches: (refs ?? '')
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => {
+ const [name = '', date = ''] = line.split('\u0000');
+ return { name, date };
+ })
+ .filter((item) => item.name)
+ .slice(0, BRIEF_MAX_BRANCHES),
+ remote,
+ remotes,
+ };
+ if (!remote) return { docs, recent: [], git, github: { unavailable: 'not-github' } };
+ try {
+ const [pullRequests, authored, assigned] = await Promise.all([
+ deps.searchGithub(`repo:${remote} is:pr is:open author:@me`, BRIEF_MAX_GITHUB),
+ deps.searchGithub(`repo:${remote} is:issue is:open author:@me`, BRIEF_MAX_GITHUB),
+ deps.searchGithub(`repo:${remote} is:issue is:open assignee:@me`, BRIEF_MAX_GITHUB),
+ ]);
+ if (pullRequests === null || authored === null || assigned === null) {
+ return { docs, recent: [], git, github: { unavailable: 'no-credential' } };
+ }
+ const issues = new Map<number, WorkbenchBriefGithubItem>();
+ for (const item of [...assigned, ...authored]) if (!issues.has(item.number)) issues.set(item.number, item);
+ return {
+ docs,
+ recent: [],
+ git,
+ github: {
+ repo: remote,
+ pullRequests: pullRequests.slice(0, BRIEF_MAX_GITHUB),
+ issues: [...issues.values()]
+ .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))
+ .slice(0, BRIEF_MAX_GITHUB),
+ },
+ };
+ } catch {
+ return { docs, recent: [], git, github: { unavailable: 'error' } };
+ }
+}
+
+/** 缓存指纹:目录 mtime + `.git/HEAD` 内容 + `.git/index` mtime;读不到的部分记空。 */
+export async function briefFingerprint(projectDir: string): Promise<string> {
+ const stat = async (file: string) => (await fs.stat(file).catch(() => null))?.mtimeMs ?? 0;
+ const head = await fs.readFile(path.join(projectDir, '.git', 'HEAD'), 'utf8').catch(() => '');
+ return [await stat(projectDir), head.trim(), await stat(path.join(projectDir, '.git', 'index'))].join('|');
+}
+
+export function createBriefCache(deps: WorkbenchBriefDeps & { fingerprint?: (dir: string) => Promise<string> }) {
+ const cache = new Map<string, { at: number; fingerprint: string; brief: WorkbenchProjectBrief }>();
+ const fingerprint = deps.fingerprint ?? briefFingerprint;
+ return async function readBrief(projectDir: string): Promise<WorkbenchProjectBrief> {
+ const now = deps.now();
+ const print = await fingerprint(projectDir);
+ const cached = cache.get(projectDir);
+ if (cached && cached.fingerprint === print && now - cached.at < BRIEF_TTL_MS) return cached.brief;
+ const brief = await buildProjectBrief(projectDir, deps);
+ if (cache.size > 64) cache.clear();
+ cache.set(projectDir, { at: now, fingerprint: print, brief });
+ return brief;
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
new file mode 100644
index 0000000000..a70d6fb2db
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
@@ -0,0 +1,284 @@
+/**
+ * 伙伴工作台的存储,记在伙伴自己的家 `<ownerRoot>/bots/<botId>/workbench.json`:
+ * - `directories`:主人交给伙伴的项目目录(授权范围);
+ * - `tasks`:伙伴读过候选任务后写下的判断(人话标题、没做完 / 聊过没下文 / 做完、下一步)。
+ *
+ * 条目的运行状态不落盘:它们是宿主从已有任务、后台任务和自动化现算出来的投影
+ * (见 `shared/botWorkbench.ts`)。旧版本在同一个文件里存过伙伴写的卡片
+ * (`cards` / `updatedAt`),读取时直接忽略,下次写入时不再带上,不报错。
+ */
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import { BrowserWindow } from 'electron';
+
+import {
+ BOT_WORKBENCH_MAX_DIRECTORIES,
+ WORKBENCH_JUDGMENT_NEXT_MAX,
+ WORKBENCH_JUDGMENT_TITLE_MAX,
+ WORKBENCH_MAX_JUDGMENTS,
+ WORKBENCH_REF_MAX,
+ type BotWorkbench,
+ type BotWorkbenchDirectory,
+ type WorkbenchTaskJudgment,
+} from '../../shared/botWorkbench.js';
+import { botProfileDir } from './botProfileFolder.js';
+import { MAKER_PUSH } from './channels.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('bot-workbench');
+const WORKBENCH_FILE = 'workbench.json';
+
+interface StoredDirectory {
+ path: string;
+ addedAt: string;
+}
+
+interface StoredWorkbench {
+ directories: StoredDirectory[];
+ tasks: Record<string, WorkbenchTaskJudgment>;
+}
+
+const VERDICTS = new Set(['unfinished', 'idea', 'done']);
+
+function boundedText(value: unknown, max: number): string | null {
+ if (typeof value !== 'string') return null;
+ const text = value.replace(/\s+/g, ' ').trim();
+ return text ? text.slice(0, max) : null;
+}
+
+function normalizeJudgment(raw: unknown): WorkbenchTaskJudgment | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const entry = raw as Record<string, unknown>;
+ const title = boundedText(entry.title, WORKBENCH_JUDGMENT_TITLE_MAX);
+ if (!title || typeof entry.verdict !== 'string' || !VERDICTS.has(entry.verdict)) return null;
+ if (typeof entry.project !== 'string' || !path.isAbsolute(entry.project)) return null;
+ return {
+ title,
+ verdict: entry.verdict as WorkbenchTaskJudgment['verdict'],
+ next: boundedText(entry.next, WORKBENCH_JUDGMENT_NEXT_MAX),
+ project: entry.project,
+ ...(typeof entry.ref === 'string' && entry.ref.trim() ? { ref: entry.ref.trim().slice(0, WORKBENCH_REF_MAX) } : {}),
+ updatedAt: typeof entry.updatedAt === 'string' ? entry.updatedAt : new Date(0).toISOString(),
+ };
+}
+
+/**
+ * 判断上限 200 条:超出时先淘汰最旧的 done,再淘汰最旧的其它判断。
+ */
+export function boundJudgments(
+ tasks: Record<string, WorkbenchTaskJudgment>,
+ max = WORKBENCH_MAX_JUDGMENTS,
+): Record<string, WorkbenchTaskJudgment> {
+ const entries = Object.entries(tasks);
+ if (entries.length <= max) return tasks;
+ const byAge = (a: [string, WorkbenchTaskJudgment], b: [string, WorkbenchTaskJudgment]) =>
+ Date.parse(a[1].updatedAt) - Date.parse(b[1].updatedAt) || a[0].localeCompare(b[0]);
+ const evictOrder = [
+ ...entries.filter(([, value]) => value.verdict === 'done').sort(byAge),
+ ...entries.filter(([, value]) => value.verdict !== 'done').sort(byAge),
+ ];
+ const drop = new Set(evictOrder.slice(0, entries.length - max).map(([key]) => key));
+ return Object.fromEntries(entries.filter(([key]) => !drop.has(key)));
+}
+
+function normalizeTasks(raw: unknown): Record<string, WorkbenchTaskJudgment> {
+ const out: Record<string, WorkbenchTaskJudgment> = {};
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (!key || key.length > 256) continue;
+ const judgment = normalizeJudgment(value);
+ if (judgment) out[key] = judgment;
+ }
+ return boundJudgments(out);
+}
+
+function normalizeDirectories(raw: unknown): StoredDirectory[] {
+ const out: StoredDirectory[] = [];
+ const seen = new Set<string>();
+ for (const entry of Array.isArray(raw) ? raw : []) {
+ if (out.length >= BOT_WORKBENCH_MAX_DIRECTORIES) break;
+ if (!entry || typeof entry !== 'object') continue;
+ const dir = entry as { path?: unknown; addedAt?: unknown };
+ if (typeof dir.path !== 'string' || !path.isAbsolute(dir.path) || seen.has(dir.path)) continue;
+ seen.add(dir.path);
+ out.push({ path: dir.path, addedAt: typeof dir.addedAt === 'string' ? dir.addedAt : new Date(0).toISOString() });
+ }
+ return out;
+}
+
+/** 读盘后的有界规整:丢掉畸形条目与旧版卡片字段,不信任磁盘上的任何字段。 */
+export function normalizeWorkbench(raw: unknown): StoredWorkbench | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const record = raw as { directories?: unknown; tasks?: unknown };
+ return { directories: normalizeDirectories(record.directories), tasks: normalizeTasks(record.tasks) };
+}
+
+function workbenchPath(userDataDir: string, botId: string): string {
+ return path.join(botProfileDir(userDataDir, botId), WORKBENCH_FILE);
+}
+
+async function readStored(userDataDir: string, botId: string): Promise<StoredWorkbench> {
+ const empty: StoredWorkbench = { directories: [], tasks: {} };
+ try {
+ const raw = await fs.readFile(workbenchPath(userDataDir, botId), 'utf8');
+ return normalizeWorkbench(JSON.parse(raw)) ?? empty;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn('Bot workbench read failed', { botId, error: String(error) });
+ }
+ return empty;
+ }
+}
+
+async function writeStored(userDataDir: string, botId: string, stored: StoredWorkbench): Promise<void> {
+ const target = workbenchPath(userDataDir, botId);
+ await fs.mkdir(path.dirname(target), { recursive: true });
+ const temp = `${target}.${process.pid}.${Date.now()}.tmp`;
+ await fs.writeFile(
+ temp,
+ `${JSON.stringify({ directories: stored.directories, tasks: stored.tasks }, null, 2)}\n`,
+ 'utf8',
+ );
+ await fs.rename(temp, target);
+}
+
+/** 同一伙伴的读改写串行,并发的添加 / 移除互不覆盖。 */
+const writeChains = new Map<string, Promise<unknown>>();
+function mutate<T>(
+ userDataDir: string,
+ botId: string,
+ change: (stored: StoredWorkbench) => { next: StoredWorkbench; result: T },
+): Promise<T> {
+ const key = `${userDataDir}\0${botId}`;
+ const run = (writeChains.get(key) ?? Promise.resolve())
+ .catch(() => undefined)
+ .then(async () => {
+ const { next, result } = change(await readStored(userDataDir, botId));
+ await writeStored(userDataDir, botId, next);
+ return result;
+ });
+ writeChains.set(key, run);
+ void run.finally(() => {
+ if (writeChains.get(key) === run) writeChains.delete(key);
+ });
+ return run;
+}
+
+async function describeDirectory(dir: StoredDirectory): Promise<BotWorkbenchDirectory> {
+ let exists = false;
+ try {
+ exists = (await fs.stat(dir.path)).isDirectory();
+ } catch {
+ exists = false;
+ }
+ return { path: dir.path, name: path.basename(dir.path) || dir.path, addedAt: dir.addedAt, exists };
+}
+
+export async function readBotWorkbench(userDataDir: string, botId: string): Promise<BotWorkbench> {
+ const stored = await readStored(userDataDir, botId);
+ return {
+ directories: await Promise.all(stored.directories.map(describeDirectory)),
+ tasks: stored.tasks,
+ };
+}
+
+/** 工具读取用:已接手项目与判断,不做文件系统探测。 */
+export async function readBotWorkbenchState(
+ userDataDir: string,
+ botId: string,
+): Promise<{ directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> }> {
+ const stored = await readStored(userDataDir, botId);
+ return { directories: stored.directories.map((dir) => dir.path), tasks: stored.tasks };
+}
+
+/** 整条替换一件任务的判断(上限与淘汰见 `boundJudgments`)。 */
+export async function setBotWorkbenchJudgment(
+ userDataDir: string,
+ botId: string,
+ taskId: string,
+ judgment: Omit<WorkbenchTaskJudgment, 'updatedAt'>,
+ now: Date = new Date(),
+): Promise<WorkbenchTaskJudgment> {
+ const saved: WorkbenchTaskJudgment = { ...judgment, updatedAt: now.toISOString() };
+ const normalized = normalizeJudgment(saved);
+ if (!normalized) throw new Error('Invalid workbench judgment');
+ return mutate(userDataDir, botId, (stored) => ({
+ next: { ...stored, tasks: boundJudgments({ ...stored.tasks, [taskId]: normalized }) },
+ result: normalized,
+ }));
+}
+
+/** 条目转成伙伴的后台任务后删掉它的判断(之后它就是普通的「你交代的」格子)。 */
+export async function deleteBotWorkbenchJudgment(userDataDir: string, botId: string, taskId: string): Promise<void> {
+ await mutate(userDataDir, botId, (stored) => {
+ if (!stored.tasks[taskId]) return { next: stored, result: undefined };
+ const rest = { ...stored.tasks };
+ delete rest[taskId];
+ return { next: { ...stored, tasks: rest }, result: undefined };
+ });
+}
+
+/** 外部会话导入成 Cindy 任务后,把判断改挂到新的 session id。 */
+export async function rekeyBotWorkbenchJudgment(
+ userDataDir: string,
+ botId: string,
+ fromTaskId: string,
+ toTaskId: string,
+): Promise<void> {
+ await mutate(userDataDir, botId, (stored) => {
+ const judgment = stored.tasks[fromTaskId];
+ if (!judgment || fromTaskId === toTaskId) return { next: stored, result: undefined };
+ const rest = { ...stored.tasks };
+ delete rest[fromTaskId];
+ return { next: { ...stored, tasks: { ...rest, [toTaskId]: judgment } }, result: undefined };
+ });
+}
+
+/** 只要路径的已接手项目列表(授权校验用,不做文件系统探测)。 */
+export async function readBotWorkbenchDirectoryPaths(userDataDir: string, botId: string): Promise<string[]> {
+ return (await readStored(userDataDir, botId)).directories.map((dir) => dir.path);
+}
+
+export type DirectoryChangeResult = { ok: true } | { ok: false; errorCode: 'NOT_A_DIRECTORY' | 'TOO_MANY' };
+
+export async function addBotWorkbenchDirectory(
+ userDataDir: string,
+ botId: string,
+ dirPath: string,
+ now: Date = new Date(),
+): Promise<DirectoryChangeResult> {
+ const resolved = path.resolve(dirPath);
+ try {
+ if (!(await fs.stat(resolved)).isDirectory()) return { ok: false, errorCode: 'NOT_A_DIRECTORY' };
+ } catch {
+ return { ok: false, errorCode: 'NOT_A_DIRECTORY' };
+ }
+ return mutate<DirectoryChangeResult>(userDataDir, botId, (stored) => {
+ const rest = stored.directories.filter((dir) => dir.path !== resolved);
+ if (rest.length >= BOT_WORKBENCH_MAX_DIRECTORIES) {
+ return { next: stored, result: { ok: false, errorCode: 'TOO_MANY' } };
+ }
+ // 最近交代的项目排最前。
+ const next = { ...stored, directories: [{ path: resolved, addedAt: now.toISOString() }, ...rest] };
+ return { next, result: { ok: true } };
+ });
+}
+
+export async function removeBotWorkbenchDirectory(userDataDir: string, botId: string, dirPath: string): Promise<void> {
+ await mutate(userDataDir, botId, (stored) => ({
+ next: { ...stored, directories: stored.directories.filter((dir) => dir.path !== dirPath) },
+ result: undefined,
+ }));
+}
+
+export function broadcastBotWorkbenchChanged(botId: string): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (win.isDestroyed()) continue;
+ try {
+ win.webContents.send(MAKER_PUSH.BOT_WORKBENCH_CHANGED, { botId });
+ } catch (error) {
+ log.warn('Bot workbench broadcast failed', { error: String(error) });
+ }
+ }
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchSessionRoots.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchSessionRoots.ts
new file mode 100644
index 0000000000..949386d33f
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchSessionRoots.ts
@@ -0,0 +1,88 @@
+/**
+ * 伙伴工作台读本机会话转录的根目录(纯函数,集中在一处)。
+ *
+ * 转录是固定目录下的文件,与哪个数据库无关:
+ * - Claude Code:Cindy 不隔离配置目录,用户自己与 Cindy 跑的都在 `~/.claude/projects`;
+ * - Codex:用户的 `~/.codex`、`$CODEX_HOME`、Codex.app,以及 Cindy 各正式 profile
+ * (CN `Cindy`、Global `CindyGlobal`、`CindyDev`、历史 `xdt-maker`)与当前运行
+ * (含 dev 沙盒)的 `<userData>/codex-home`,以及多账号登录的 `<userData>/codex-accounts/<当前账号>/<供应商>`
+ * (只取当前 Cindy 账号那一层,别的账号不碰);每个 home 取 `sessions/` 与 `archived_sessions/`;
+ * - Pi:Cindy 各 profile 与当前运行的 `<userData>/pi-agent-home/sessions`。
+ * dev 沙盒因此也能看到正式版 Cindy 跑过的任务。所有根只是候选,不存在的目录由调用方跳过。
+ */
+import path from 'node:path';
+
+/** Cindy 各正式 profile 的 userData 目录名(与 maker-shared brandIdentity 一致)。 */
+export const CINDY_PROFILE_DIR_NAMES = ['Cindy', 'CindyGlobal', 'CindyDev', 'xdt-maker'] as const;
+
+export interface WorkbenchSessionRootsInput {
+ homeDir: string;
+ /** 系统应用数据目录(macOS 为 ~/Library/Application Support)。 */
+ appDataDir: string | null;
+ /** 当前运行的 userData(dev 沙盒时就是沙盒目录)。 */
+ userDataDir: string | null;
+ platform: string;
+ env: { CODEX_HOME?: string; CLAUDE_CONFIG_DIR?: string; APPDATA?: string };
+ /** 当前 Cindy 账号在 `codex-accounts/` 下的目录名(owner id 的 sha256);没有登录时为 null。 */
+ codexAccountOwner?: string | null;
+}
+
+export interface WorkbenchSessionRoots {
+ claude: string[];
+ codex: string[];
+ /** `codex-accounts/<当前账号>` 目录;下面每个供应商子目录是一个 Codex home,读取时展开。 */
+ codexAccounts: string[];
+ pi: string[];
+}
+
+type PathApi = typeof path.posix;
+
+function unique(p: PathApi, paths: Array<string | null | undefined>): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const raw of paths) {
+ if (!raw) continue;
+ const resolved = p.resolve(raw);
+ if (seen.has(resolved)) continue;
+ seen.add(resolved);
+ out.push(resolved);
+ }
+ return out;
+}
+
+export function workbenchSessionRoots(input: WorkbenchSessionRootsInput): WorkbenchSessionRoots {
+ // 按目标平台拼路径,而不是按运行测试的宿主:同一份输入在任何机器上得到同样的结果。
+ const p = input.platform === 'win32' ? path.win32 : path.posix;
+ const profileDirs = unique(p, [
+ input.userDataDir,
+ ...(input.appDataDir ? CINDY_PROFILE_DIR_NAMES.map((name) => p.join(input.appDataDir!, name)) : []),
+ ]);
+
+ const claude = unique(p, [
+ input.env.CLAUDE_CONFIG_DIR ? p.join(input.env.CLAUDE_CONFIG_DIR, 'projects') : null,
+ p.join(input.homeDir, '.claude', 'projects'),
+ ]);
+
+ const codexHomes = unique(p, [
+ input.env.CODEX_HOME,
+ p.join(input.homeDir, '.codex'),
+ ...(input.platform === 'darwin'
+ ? [
+ p.join(input.homeDir, 'Library', 'Application Support', 'Codex', 'codex-home'),
+ p.join(input.homeDir, 'Library', 'Application Support', 'Codex'),
+ ]
+ : input.platform === 'win32'
+ ? input.env.APPDATA
+ ? [p.join(input.env.APPDATA, 'Codex', 'codex-home'), p.join(input.env.APPDATA, 'Codex')]
+ : []
+ : [p.join(input.homeDir, '.config', 'codex')]),
+ ...profileDirs.map((dir) => p.join(dir, 'codex-home')),
+ ]);
+ const codex = unique(p, codexHomes.flatMap((home) => [p.join(home, 'sessions'), p.join(home, 'archived_sessions')]));
+
+ const owner = input.codexAccountOwner && /^[0-9a-f]{64}$/.test(input.codexAccountOwner) ? input.codexAccountOwner : null;
+ const codexAccounts = owner ? unique(p, profileDirs.map((dir) => p.join(dir, 'codex-accounts', owner))) : [];
+
+ const pi = unique(p, profileDirs.map((dir) => p.join(dir, 'pi-agent-home', 'sessions')));
+ return { claude, codex, codexAccounts, pi };
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
new file mode 100644
index 0000000000..1aec1437a3
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -0,0 +1,438 @@
+/**
+ * 伙伴工作台工具的宿主实现:把 `botWorkbenchAccess.ts` 的纯逻辑接到真实数据源上。
+ *
+ * - 伙伴身份从调用方 session 反查(只认本机、在用的伙伴主任务);
+ * - 已接手项目与伙伴的判断读写伙伴家的 `workbench.json`;
+ * - 任务、后台任务、活动快照、例行任务与自动化都读宿主已有的权威来源,不另存状态;
+ * - 本机 Claude Code / Codex / Pi 会话按固定的转录目录发现(`botWorkbenchSessionRoots.ts`),只看近期、
+ * 只读头尾;只有伙伴继续某一件时才经设置页同一条单条导入路径导入它(Pi 与导入不了的改开后台任务);
+ * - 项目素材 brief(文档路径、git、GitHub PR / issue)宿主现算、有界、带缓存;
+ * - 继续 / 停止复用宿主已有的发消息与优雅停止路径(与 send_to_session、
+ * stop_session_turn 同一条链路),由调用方注入。
+ */
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+
+import { app } from 'electron';
+
+import { and, count, desc, eq, inArray, isNotNull, isNull, like, ne, or } from 'drizzle-orm';
+
+import { getDbClient } from '../localDb/client/current.js';
+import { botDelegations, botProfiles, botSessionLinks, messages, sessions } from '../localDb/schema.js';
+import { invalidateSessionImportScanCache } from '../localDb/ipc/session-import.js';
+import { importExternalClaudeCodeSessions } from '../maker-host/claude-local-sessions.js';
+import { importExternalCodexSessions } from '../maker-host/codex-local-sessions.js';
+import {
+ activeOwnerScopeKey,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+} from '../appSessionState.js';
+import { routineTools } from '../routines/service.js';
+import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';
+import {
+ isCaseInsensitivePlatform,
+ WORKBENCH_RECENT_WINDOW_MS,
+ type WorkbenchDelegationStatus,
+} from '../../shared/botWorkbench.js';
+import {
+ broadcastBotWorkbenchChanged,
+ deleteBotWorkbenchJudgment,
+ readBotWorkbenchState,
+ rekeyBotWorkbenchJudgment,
+ setBotWorkbenchJudgment,
+} from './botWorkbenchService.js';
+import {
+ listExternalSessionsForProjects,
+ readExternalTranscriptFile,
+ readSessionDigest,
+ readSessionTranscript,
+} from './botWorkbenchTranscripts.js';
+import { workbenchSessionRoots } from './botWorkbenchSessionRoots.js';
+import { createBriefCache, type WorkbenchBriefGithubItem } from './botWorkbenchBrief.js';
+import { readCanonicalSessionActivity } from './sessionActivityProjection.js';
+import {
+ createBotWorkbenchAccess,
+ type BotWorkbenchAccess,
+ type BotWorkbenchAccessDeps,
+ type WorkbenchCallerResult,
+ type WorkbenchTargetFacts,
+} from './botWorkbenchAccess.js';
+
+/** 伙伴主任务才能用工作台;远端、归档、非主任务一律拒绝。 */
+async function resolveWorkbenchCaller(callerSessionId: string): Promise<WorkbenchCallerResult> {
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({
+ botId: botSessionLinks.botId,
+ role: botSessionLinks.role,
+ sessionStatus: sessions.status,
+ remoteHostId: sessions.remoteHostId,
+ profileStatus: botProfiles.status,
+ linkArchivedAt: botSessionLinks.archivedAt,
+ })
+ .from(botSessionLinks)
+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
+ .innerJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
+ .where(and(eq(botSessionLinks.sessionId, callerSessionId), eq(sessions.source, 'bot')))
+ .limit(1);
+ if (!row) return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };
+ if (row.sessionStatus !== 'active' || row.profileStatus !== 'active' || row.linkArchivedAt !== null) {
+ return { ok: false, errorCode: 'BOT_SESSION_INACTIVE', message: '伙伴或它的主任务已停用' };
+ }
+ if (row.role !== 'canonical') {
+ return { ok: false, errorCode: 'BOT_MAIN_TASK_REQUIRED', message: '只有伙伴的主任务可以使用工作台' };
+ }
+ if (row.remoteHostId) {
+ return { ok: false, errorCode: 'REMOTE_WORKBENCH_UNAVAILABLE', message: '远端伙伴暂不支持工作台' };
+ }
+ return { ok: true, botId: row.botId };
+}
+
+async function readWorkbenchTarget(taskId: string): Promise<WorkbenchTargetFacts | null> {
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({
+ id: sessions.id,
+ status: sessions.status,
+ source: sessions.source,
+ remoteHostId: sessions.remoteHostId,
+ workingDir: sessions.workingDir,
+ orcaRole: sessions.orcaRole,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, taskId))
+ .limit(1);
+ if (!row) return null;
+ const [[link], [delegation]] = await Promise.all([
+ db.select({ id: botSessionLinks.id }).from(botSessionLinks).where(eq(botSessionLinks.sessionId, taskId)).limit(1),
+ db.select({ id: botDelegations.id }).from(botDelegations).where(eq(botDelegations.childSessionId, taskId)).limit(1),
+ ]);
+ return {
+ id: row.id,
+ status: row.status,
+ source: row.source ?? null,
+ remoteHostId: row.remoteHostId ?? null,
+ workingDir: row.workingDir ?? null,
+ orcaRole: row.orcaRole ?? null,
+ botLinked: Boolean(link),
+ delegationChild: Boolean(delegation),
+ };
+}
+
+/**
+ * 已接手项目里的候选任务。先用前缀 LIKE 缩小范围(托管 worktree 都在主仓库目录下;SQLite 的
+ * LIKE 对 ASCII 不区分大小写,路径里的 `_` / `%` 只会让范围变宽),精确的项目归属由调用方
+ * 用共享的归一规则再判一次,所以这里不需要转义。
+ */
+async function listWorkbenchProjectTasks(
+ projectDirs: readonly string[],
+ alwaysInclude: ReadonlySet<string>,
+) {
+ const prefixes = projectDirs
+ .map((dir) => normalizeWorkingDirForGrouping(dir))
+ .filter((dir): dir is string => Boolean(dir));
+ if (prefixes.length === 0) return [];
+ const db = getDbClient().drizzle;
+ const hiddenIds = db.select({ id: botSessionLinks.sessionId }).from(botSessionLinks);
+ const rows = await db
+ .select({
+ id: sessions.id,
+ title: sessions.title,
+ workingDir: sessions.workingDir,
+ agentKind: sessions.agentKind,
+ source: sessions.source,
+ orcaRole: sessions.orcaRole,
+ userSendAt: sessions.userSendAt,
+ updatedAt: sessions.updatedAt,
+ listPreview: sessions.listPreview,
+ })
+ .from(sessions)
+ .where(
+ and(
+ eq(sessions.status, 'active'),
+ isNull(sessions.remoteHostId),
+ isNotNull(sessions.workingDir),
+ or(isNull(sessions.source), inArray(sessions.source, ['desktop', 'plugin'])),
+ or(isNull(sessions.orcaRole), eq(sessions.orcaRole, 'lead')),
+ or(...prefixes.map((prefix) => like(sessions.workingDir, `${prefix}%`))),
+ ),
+ )
+ .orderBy(desc(sessions.updatedAt))
+ .limit(500);
+ const hidden = new Set((await hiddenIds).map((row) => row.id));
+ const kept = rows
+ .filter((row) => !hidden.has(row.id))
+ .filter((row) => row.userSendAt != null || row.listPreview != null || alwaysInclude.has(row.id));
+ const messageCounts = new Map<string, number>();
+ if (kept.length > 0) {
+ const counted = await db
+ .select({ sessionId: messages.sessionId, total: count() })
+ .from(messages)
+ .where(and(
+ inArray(messages.sessionId, kept.slice(0, 200).map((row) => row.id)),
+ isNull(messages.rewindAt),
+ inArray(messages.role, ['user', 'assistant']),
+ ))
+ .groupBy(messages.sessionId);
+ for (const row of counted) messageCounts.set(row.sessionId, Number(row.total));
+ }
+ return kept
+ .map((row) => ({
+ id: row.id,
+ title: row.title,
+ workingDir: row.workingDir ?? null,
+ agentKind: row.agentKind ?? null,
+ summary: row.listPreview ?? null,
+ // 与渲染层同一口径:主人发消息与任务本身的最近更新取较晚的那个。
+ lastActiveAt: Math.max(row.userSendAt ?? 0, row.updatedAt ?? 0) || null,
+ messageCount: messageCounts.get(row.id) ?? null,
+ }))
+ .sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0));
+}
+
+async function listBotDelegationChildren(botId: string): Promise<Map<string, WorkbenchDelegationStatus>> {
+ const rows = await getDbClient()
+ .drizzle.select({
+ childSessionId: botDelegations.childSessionId,
+ status: botDelegations.status,
+ lastError: botDelegations.lastError,
+ })
+ .from(botDelegations)
+ .where(and(eq(botDelegations.requestingBotId, botId), isNotNull(botDelegations.childSessionId)))
+ .orderBy(desc(botDelegations.createdAt));
+ const out = new Map<string, WorkbenchDelegationStatus>();
+ for (const row of rows) {
+ if (!row.childSessionId || out.has(row.childSessionId)) continue;
+ // 与后台任务卡同一口径:超时收尾在库里是 failed + TIMEOUT 前缀。
+ const status = row.status === 'failed' && /^TIMEOUT(?:_|:)/i.test(row.lastError ?? '')
+ ? 'timed-out'
+ : (row.status as WorkbenchDelegationStatus);
+ out.set(row.childSessionId, status);
+ }
+ return out;
+}
+
+async function listBotRoutines(botId: string) {
+ const routines = await routineTools.list(botId);
+ return Promise.all(
+ routines.map(async (routine) => {
+ const latest = (await routineTools.history(botId, routine.id).catch(() => []))[0];
+ const lastResult = latest
+ ? [latest.status, latest.resultText ?? latest.error].filter(Boolean).join(': ')
+ : null;
+ return {
+ id: routine.id,
+ name: routine.name,
+ enabled: routine.enabled,
+ ...(routine.activity ? { activity: routine.activity } : {}),
+ lastResult,
+ };
+ }),
+ );
+}
+
+async function listProjectSchedules() {
+ // 调度器入口牵连通知等主进程模块,按需加载,避免任务 IPC 一引用本模块就把它们带进来。
+ const { getSchedulerIfInitialized } = await import('../scheduler-host/index.js');
+ const scheduler = getSchedulerIfInitialized();
+ if (!scheduler) return [];
+ const schedules = await scheduler.list();
+ return schedules.map((schedule) => ({
+ id: schedule.id,
+ name: schedule.name,
+ status: schedule.status,
+ ...(schedule.source ? { source: schedule.source } : {}),
+ workspaceKind: schedule.workspaceKind,
+ workingDir: schedule.workingDir ?? null,
+ nextFireAt: schedule.nextFireAt ?? null,
+ }));
+}
+
+function appPath(name: 'appData' | 'userData'): string | null {
+ try {
+ return app.getPath(name);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * 已接手项目里近期的本机 Claude Code / Codex / Pi 会话。根目录见 `workbenchSessionRoots`
+ * (含其它 Cindy profile 的 codex-home 与 pi-agent-home),按 cwd 过滤,只读近期转录的头尾。
+ */
+async function listExternalCandidates(projectDirs: readonly string[]) {
+ const now = Date.now();
+ // 与 `codexAccountHome` 同一个派生;按需加载,不把账号登录模块带进任务 IPC。
+ const { codexAccountOwnerDir } = await import('../maker-host/codex-account-auth.js');
+ return listExternalSessionsForProjects({
+ roots: workbenchSessionRoots({
+ homeDir: os.homedir(),
+ appDataDir: appPath('appData'),
+ userDataDir: appPath('userData'),
+ platform: process.platform,
+ env: { CODEX_HOME: process.env.CODEX_HOME, CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR, APPDATA: process.env.APPDATA },
+ codexAccountOwner: codexAccountOwnerDir(),
+ }),
+ projectDirs,
+ caseInsensitive: isCaseInsensitivePlatform(process.platform),
+ since: now - WORKBENCH_RECENT_WINDOW_MS,
+ now,
+ });
+}
+
+const GIT_TIMEOUT_MS = 3_000;
+const GITHUB_TIMEOUT_MS = 8_000;
+
+/** 项目素材:git 命令限时、gh 登录 token 复用,拿不到就缺项。按项目缓存 60 秒。 */
+// git / GitHub 依赖按需加载:只有伙伴真的读工作台时才用到,不拖累引用本模块的其它入口。
+const readBrief = createBriefCache({
+ git: async (cwd, args) => {
+ try {
+ const { runGit } = await import('../git-review/gitRunner.js');
+ return (await runGit(args, { cwd, timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 512 * 1024 })).stdout;
+ } catch {
+ return null;
+ }
+ },
+ searchGithub: async (query, limit) => {
+ const [{ getSharedGhCliTokenSource }, { GithubClient }, { outboundFetch }] = await Promise.all([
+ import('../git-context/ghCliTokenSource.js'),
+ import('@cindy/github-client'),
+ import('../maker-host/outbound-fetch.js'),
+ ]);
+ const token = await getSharedGhCliTokenSource().readToken();
+ if (!token) return null;
+ const client = new GithubClient({ token, fetchImpl: outboundFetch });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const result = await Promise.race([
+ client.searchIssuesAndPRs({ q: query, sort: 'updated', order: 'desc', per_page: limit }),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('github timeout')), GITHUB_TIMEOUT_MS);
+ }),
+ ]).finally(() => clearTimeout(timer));
+ return result.items.slice(0, limit).map((item): WorkbenchBriefGithubItem => ({
+ number: item.number,
+ title: item.title.slice(0, 200),
+ state: item.state,
+ updatedAt: item.updated_at,
+ url: item.html_url,
+ }));
+ },
+ now: () => Date.now(),
+});
+
+const AGENT_KIND = { claude: 'cc', codex: 'codex', pi: 'pi' } as const;
+
+async function findImportedSession(source: 'claude' | 'codex' | 'pi', externalId: string): Promise<string | null> {
+ const [row] = await getDbClient()
+ .drizzle.select({ id: sessions.id })
+ .from(sessions)
+ .where(and(
+ eq(sessions.sdkSessionId, externalId),
+ eq(sessions.agentKind, AGENT_KIND[source]),
+ ne(sessions.status, 'deleted'),
+ ))
+ .orderBy(desc(sessions.updatedAt))
+ .limit(1);
+ return row?.id ?? null;
+}
+
+/** 只导入这一条外部会话(设置页同一条导入路径),返回它在 Cindy 里的任务 id。 */
+async function importExternalSession(
+ source: 'claude' | 'codex',
+ externalId: string,
+): Promise<{ ok: true; sessionId: string } | { ok: false; errorCode: string; message: string }> {
+ try {
+ if (source === 'claude') await importExternalClaudeCodeSessions([externalId]);
+ else await importExternalCodexSessions([externalId]);
+ } catch (error) {
+ return {
+ ok: false,
+ errorCode: 'IMPORT_FAILED',
+ message: `没能把这条本机会话接过来:${error instanceof Error ? error.message : String(error)}`,
+ };
+ } finally {
+ invalidateSessionImportScanCache();
+ }
+ const sessionId = await findImportedSession(source, externalId);
+ return sessionId
+ ? { ok: true, sessionId }
+ : { ok: false, errorCode: 'IMPORT_FAILED', message: '没能把这条本机会话接过来,请让主人稍后重试' };
+}
+
+/** 投递、停止与开后台任务由调用方注入(与 send_to_session、stop_session_turn、start_session_task 同一条宿主路径)。 */
+export type BotWorkbenchSendDeps = Pick<BotWorkbenchAccessDeps, 'sendToSession' | 'stopSessionTurn' | 'startBackgroundTask'>;
+
+/**
+ * 按调用时的账号作用域组装一次工具服务:作用域在调用期间切换则中止,不做投递。
+ */
+function createDesktopBotWorkbenchAccess(send: BotWorkbenchSendDeps): BotWorkbenchAccess {
+ const scopeKey = activeOwnerScopeKey();
+ const userDataDir = ownerScopedUserDataPath();
+ return createBotWorkbenchAccess({
+ resolveCaller: resolveWorkbenchCaller,
+ readState: (botId) => readBotWorkbenchState(userDataDir, botId),
+ projectExists: async (dir) => {
+ try {
+ return (await fs.stat(dir)).isDirectory();
+ } catch {
+ return false;
+ }
+ },
+ readTarget: readWorkbenchTarget,
+ listProjectTasks: listWorkbenchProjectTasks,
+ listExternalCandidates,
+ findImportedSession,
+ importExternal: importExternalSession,
+ startBackgroundTask: send.startBackgroundTask,
+ readSessionDigest,
+ readBrief,
+ readSessionTranscript,
+ readExternalTranscript: (candidate) => readExternalTranscriptFile(candidate.source, candidate.id, candidate.file),
+ deleteJudgment: (botId, taskId) => deleteBotWorkbenchJudgment(userDataDir, botId, taskId),
+ saveJudgment: (botId, taskId, judgment) => setBotWorkbenchJudgment(userDataDir, botId, taskId, judgment),
+ rekeyJudgment: (botId, from, to) => rekeyBotWorkbenchJudgment(userDataDir, botId, from, to),
+ notifyChanged: broadcastBotWorkbenchChanged,
+ listDelegations: listBotDelegationChildren,
+ readActivityPhase: async (sessionId) => (await readCanonicalSessionActivity(sessionId)).phase,
+ listRoutines: listBotRoutines,
+ listSchedules: listProjectSchedules,
+ sendToSession: send.sendToSession,
+ stopSessionTurn: send.stopSessionTurn,
+ caseInsensitive: isCaseInsensitivePlatform(process.platform),
+ isOwnerScopeCurrent: () => !isAppSessionBoundaryPending() && activeOwnerScopeKey() === scopeKey,
+ });
+}
+
+type ToolFailure = { ok: false; errorCode: string; message: string };
+
+/** 工具入口的统一兜底:账号切换中直接拒绝,未预期异常转成 INTERNAL,不向模型抛栈。 */
+export async function runBotWorkbenchTool<T>(
+ send: BotWorkbenchSendDeps,
+ run: (access: BotWorkbenchAccess) => Promise<T | ToolFailure>,
+): Promise<T | ToolFailure> {
+ if (isAppSessionBoundaryPending()) {
+ return { ok: false, errorCode: 'OWNER_SCOPE_CHANGED', message: '账号正在切换,请稍后重试' };
+ }
+ try {
+ return await run(createDesktopBotWorkbenchAccess(send));
+ } catch (error) {
+ return { ok: false, errorCode: 'INTERNAL', message: error instanceof Error ? error.message : String(error) };
+ }
+}
+
+const NO_SEND: BotWorkbenchSendDeps = {
+ sendToSession: async () => ({ ok: false, errorCode: 'UNSUPPORTED', message: 'read only' }),
+ stopSessionTurn: async () => ({ ok: false, errorCode: 'UNSUPPORTED', message: 'read only' }),
+ startBackgroundTask: async () => ({ ok: false, errorCode: 'UNSUPPORTED', message: 'read only' }),
+};
+
+/** 工作台详情视图(主人自己的界面)读取一件任务的最近内容;范围同样限于已接手项目。 */
+export async function readBotWorkbenchTaskForOwner(botId: string, taskId: string) {
+ return runBotWorkbenchTool(NO_SEND, (access) => access.readForOwner({ botId, taskId }));
+}
+
+/** 工作台用:已接手项目里近期本机会话的 id 与最近活动。 */
+export async function listBotWorkbenchCandidatesForOwner(botId: string) {
+ return runBotWorkbenchTool(NO_SEND, (access) => access.listCandidatesForOwner({ botId }));
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts
new file mode 100644
index 0000000000..c046966b26
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts
@@ -0,0 +1,501 @@
+/**
+ * 伙伴工作台的只读会话读取:候选发现、摘要(起始目的 + 最后几条)与有界摘录。
+ *
+ * 成本约束(用户 2026-10-01 实机反馈:扫描慢、不该全文读,只看近期):
+ * - 转录是固定目录下的文件(见 `botWorkbenchSessionRoots.ts`,含多账号的 Codex home),按项目目录(cwd)过滤;
+ * - 只看近期:最近 30 天内活动过的才读内容。Codex 只进最近 31 天的日期子目录,
+ * 归档目录按文件名里的日期预筛;Claude Code 只进项目存储目录;
+ * - 近期文件先只读开头 16KB 找 cwd;项目里最新的至多 30 条才读头部 64KB + 尾部 64KB
+ * (小文件整读一次;首行超长时跳过它再取头部,至多往后找 1MB),绝不全文;
+ * - Cindy 任务用两条有界查询(第一条用户消息、最后 3 条);
+ * - 摘要按 (文件 mtime, size) / (任务 updatedAt) 缓存。
+ * 输出统一去掉 `<system-reminder>` 之类的指令块。不写库、不导入。
+ */
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import { and, asc, desc, eq, gt, inArray, isNull, ne } from 'drizzle-orm';
+
+import { getDbClient } from '../localDb/client/current.js';
+import { messages, sessions } from '../localDb/schema.js';
+import { parseClaudeCodeMessageLine } from '../maker-host/claude-local-sessions.js';
+import { parseCodexRolloutMessageLine } from '../maker-host/codex-local-sessions.js';
+import {
+ buildWorkbenchDigest,
+ findWorkbenchProject,
+ stripInstructionBlocks,
+ type WorkbenchDigest,
+ type WorkbenchTranscript,
+ type WorkbenchTranscriptItem,
+} from '../../shared/botWorkbench.js';
+import type { WorkbenchSessionRoots } from './botWorkbenchSessionRoots.js';
+
+export type WorkbenchExternalSource = 'claude' | 'codex' | 'pi';
+
+export const WORKBENCH_TRANSCRIPT_MAX_CHARS = 4_000;
+const PER_MESSAGE_MAX_CHARS = 1_200;
+/** 每条转录头尾各最多读这么多字节。 */
+export const WORKBENCH_HEAD_TAIL_BYTES = 64 * 1024;
+const HEAD_SKIP_MAX_BYTES = 1024 * 1024;
+const SESSION_MESSAGE_ROWS = 60;
+const CACHE_MAX = 4_000;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function cleanText(raw: string): string {
+ return stripInstructionBlocks(raw)
+ .replace(/[ \t]+\n/g, '\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+/** 保留最近的消息,单条与总量都有界;顺序仍按时间正序。 */
+export function boundTranscript(
+ items: readonly WorkbenchTranscriptItem[],
+ maxChars = WORKBENCH_TRANSCRIPT_MAX_CHARS,
+): WorkbenchTranscript {
+ const out: WorkbenchTranscriptItem[] = [];
+ let used = 0;
+ let truncated = false;
+ for (let index = items.length - 1; index >= 0; index -= 1) {
+ const cleaned = cleanText(items[index].text);
+ if (!cleaned) continue;
+ let text = cleaned.length > PER_MESSAGE_MAX_CHARS ? `${cleaned.slice(0, PER_MESSAGE_MAX_CHARS - 1)}…` : cleaned;
+ if (used + text.length > maxChars) {
+ const room = maxChars - used;
+ truncated = true;
+ if (room < 80) break;
+ text = `…${text.slice(text.length - room + 1)}`;
+ }
+ out.push({ ...items[index], text });
+ used += text.length;
+ if (used >= maxChars) {
+ truncated = truncated || index > 0;
+ break;
+ }
+ }
+ return { items: out.reverse(), truncated };
+}
+
+/**
+ * 读文件头部与尾部各至多 `bytes` 字节,丢掉被截断的半行。文件不大于两段之和时整读一次,
+ * head 与 tail 是同一份。`headText` 保留头部原文(半行也在),用于在超长首行里找 cwd。
+ */
+export async function readHeadTailLines(
+ file: string,
+ bytes = WORKBENCH_HEAD_TAIL_BYTES,
+): Promise<{ head: string[]; tail: string[]; whole: boolean; headText: string }> {
+ const handle = await fs.open(file, 'r');
+ try {
+ const { size } = await handle.stat();
+ const read = async (start: number, length: number) => {
+ const buffer = Buffer.alloc(length);
+ await handle.read(buffer, 0, length, start);
+ return buffer.toString('utf8');
+ };
+ if (size <= bytes * 2) {
+ const text = await read(0, size);
+ const lines = text.split(/\r?\n/).filter(Boolean);
+ return { head: lines, tail: lines, whole: true, headText: text.slice(0, bytes) };
+ }
+ const headText = await read(0, bytes);
+ let headStart = 0;
+ let headChunk = headText;
+ // 首行超长(如 Codex 的 session_meta 带整份 instructions):跳过它再取头部,
+ // 至多往后找 1MB,找不到就只用尾部。
+ if (!headText.includes('\n')) {
+ headChunk = '';
+ for (let offset = bytes; offset < Math.min(size, HEAD_SKIP_MAX_BYTES); offset += bytes) {
+ const chunk = Buffer.alloc(Math.min(bytes, size - offset));
+ await handle.read(chunk, 0, chunk.length, offset);
+ const newline = chunk.indexOf(0x0a);
+ if (newline >= 0) {
+ headStart = offset + newline + 1;
+ headChunk = await read(headStart, Math.min(bytes, size - headStart));
+ break;
+ }
+ }
+ }
+ const head = headChunk.split(/\r?\n/);
+ if (headStart + bytes < size) head.pop();
+ const tail = (await read(size - bytes, bytes)).split(/\r?\n/);
+ tail.shift();
+ return { head: head.filter(Boolean), tail: tail.filter(Boolean), whole: false, headText };
+ } finally {
+ await handle.close();
+ }
+}
+
+/** Pi 转录的最小解析:只取 `type: message` 行里 user / assistant 的文字块,拿不准的行跳过。 */
+export function parsePiTranscriptLine(line: string): WorkbenchTranscriptItem | null {
+ let obj: unknown;
+ try {
+ obj = JSON.parse(line);
+ } catch {
+ return null;
+ }
+ if (!obj || typeof obj !== 'object') return null;
+ const record = obj as { type?: unknown; timestamp?: unknown; message?: unknown };
+ if (record.type !== 'message' || !record.message || typeof record.message !== 'object') return null;
+ const message = record.message as { role?: unknown; content?: unknown };
+ if (message.role !== 'user' && message.role !== 'assistant') return null;
+ const blocks = Array.isArray(message.content) ? message.content : [];
+ const text = typeof message.content === 'string'
+ ? message.content
+ : blocks
+ .map((block) =>
+ block && typeof block === 'object' && (block as { type?: unknown }).type === 'text'
+ ? String((block as { text?: unknown }).text ?? '')
+ : '',
+ )
+ .filter(Boolean)
+ .join('\n');
+ if (!text.trim()) return null;
+ const at = typeof record.timestamp === 'string' ? Date.parse(record.timestamp) : NaN;
+ return { role: message.role, text, at: Number.isFinite(at) ? at : 0 };
+}
+
+function parseLines(source: WorkbenchExternalSource, lines: readonly string[], externalId: string): WorkbenchTranscriptItem[] {
+ const items: WorkbenchTranscriptItem[] = [];
+ lines.forEach((line, index) => {
+ if (source === 'claude') {
+ for (const row of parseClaudeCodeMessageLine(line, index + 1, externalId, '')) {
+ if ((row.role === 'user' || row.role === 'assistant') && typeof row.content === 'string') {
+ items.push({ role: row.role, text: row.content, at: row.createdAt });
+ }
+ }
+ } else if (source === 'codex') {
+ const row = parseCodexRolloutMessageLine(line, index + 1);
+ if (row) items.push({ role: row.role, text: row.text, at: row.createdAt });
+ } else {
+ const row = parsePiTranscriptLine(line);
+ if (row) items.push(row);
+ }
+ });
+ return items;
+}
+
+/** 在头部原文里找第一个 `"cwd":"…"`(Codex 的首行可能超长被截断,不能整行解析)。 */
+export function findCwdInHead(headText: string): string | null {
+ const match = /"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(headText);
+ if (!match) return null;
+ try {
+ const cwd = JSON.parse(match[1]) as unknown;
+ return typeof cwd === 'string' && cwd ? cwd : null;
+ } catch {
+ return null;
+ }
+}
+
+/** 找 cwd 只读文件开头这么多字节(Codex 的 session_meta 里 cwd 在 instructions 之前)。 */
+const CWD_PROBE_BYTES = 16 * 1024;
+
+const fileCwdCache = new Map<string, { mtimeMs: number; size: number; cwd: string | null }>();
+const fileDigestCache = new Map<string, { mtimeMs: number; size: number; digest: WorkbenchDigest }>();
+
+async function readFileCwd(file: string, stat: { mtimeMs: number; size: number }): Promise<string | null> {
+ const cached = fileCwdCache.get(file);
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.cwd;
+ const handle = await fs.open(file, 'r');
+ let cwd: string | null;
+ try {
+ const length = Math.min(stat.size, CWD_PROBE_BYTES);
+ const buffer = Buffer.alloc(length);
+ await handle.read(buffer, 0, length, 0);
+ cwd = findCwdInHead(buffer.toString('utf8'));
+ } finally {
+ await handle.close();
+ }
+ if (fileCwdCache.size >= CACHE_MAX) fileCwdCache.clear();
+ fileCwdCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, cwd });
+ return cwd;
+}
+
+async function readFileDigest(
+ source: WorkbenchExternalSource,
+ externalId: string,
+ file: string,
+ stat: { mtimeMs: number; size: number },
+): Promise<WorkbenchDigest> {
+ const cached = fileDigestCache.get(file);
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.digest;
+ const { head, tail } = await readHeadTailLines(file);
+ const digest = buildWorkbenchDigest(parseLines(source, head, externalId), parseLines(source, tail, externalId));
+ if (fileDigestCache.size >= CACHE_MAX) fileDigestCache.clear();
+ fileDigestCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, digest });
+ return digest;
+}
+
+/** 一件外部会话的有界摘录:头部 + 尾部,不全文。 */
+export async function readExternalTranscriptFile(
+ source: WorkbenchExternalSource,
+ externalId: string,
+ file: string,
+): Promise<WorkbenchTranscript | null> {
+ const parts = await readHeadTailLines(file).catch(() => null);
+ if (!parts) return null;
+ const items = parts.whole
+ ? parseLines(source, parts.head, externalId)
+ : [...parseLines(source, parts.head, externalId).slice(0, 2), ...parseLines(source, parts.tail, externalId)];
+ return boundTranscript(items);
+}
+
+function messageText(raw: string): string {
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ if (typeof parsed === 'string') return parsed;
+ if (parsed && typeof parsed === 'object') {
+ const text = (parsed as { text?: unknown; content?: unknown }).text
+ ?? (parsed as { content?: unknown }).content;
+ if (typeof text === 'string') return text;
+ }
+ return '';
+ } catch {
+ return raw;
+ }
+}
+
+async function sessionMessageWhere(sessionId: string) {
+ const db = getDbClient().drizzle;
+ const [session] = await db
+ .select({ clearedAt: sessions.clearedAt })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const clearedAt = typeof session?.clearedAt === 'number' ? session.clearedAt : NaN;
+ const where = [
+ eq(messages.sessionId, sessionId),
+ isNull(messages.rewindAt),
+ inArray(messages.role, ['user', 'assistant']),
+ ];
+ if (Number.isFinite(clearedAt)) where.push(gt(messages.createdAt, clearedAt));
+ return { db, where: and(...where) };
+}
+
+export async function readSessionTranscript(sessionId: string): Promise<WorkbenchTranscript> {
+ const { db, where } = await sessionMessageWhere(sessionId);
+ const rows = await db
+ .select({ role: messages.role, content: messages.content, createdAt: messages.createdAt })
+ .from(messages)
+ .where(where)
+ .orderBy(desc(messages.createdAt))
+ .limit(SESSION_MESSAGE_ROWS);
+ const items = rows
+ .reverse()
+ .map((row) => ({ role: row.role as 'user' | 'assistant', text: messageText(row.content), at: row.createdAt }));
+ return boundTranscript(items);
+}
+
+const sessionDigestCache = new Map<string, { updatedAt: number; digest: WorkbenchDigest }>();
+
+/** Cindy 任务的摘要:第一条用户消息 + 最后 3 条,两条有界查询;按 updatedAt 缓存。 */
+export async function readSessionDigest(sessionId: string, updatedAt: number): Promise<WorkbenchDigest> {
+ const cached = sessionDigestCache.get(sessionId);
+ if (cached && cached.updatedAt === updatedAt) return cached.digest;
+ const { db, where } = await sessionMessageWhere(sessionId);
+ const [first, last] = await Promise.all([
+ db
+ .select({ role: messages.role, content: messages.content, createdAt: messages.createdAt })
+ .from(messages)
+ .where(and(where, eq(messages.role, 'user')))
+ .orderBy(asc(messages.createdAt))
+ .limit(1),
+ db
+ .select({ role: messages.role, content: messages.content, createdAt: messages.createdAt })
+ .from(messages)
+ .where(where)
+ .orderBy(desc(messages.createdAt))
+ .limit(3),
+ ]);
+ const toItem = (row: { role: string; content: string; createdAt: number }): WorkbenchTranscriptItem => ({
+ role: row.role as 'user' | 'assistant',
+ text: messageText(row.content),
+ at: row.createdAt,
+ });
+ const digest = buildWorkbenchDigest(first.map(toItem), last.reverse().map(toItem));
+ if (sessionDigestCache.size >= CACHE_MAX) sessionDigestCache.clear();
+ sessionDigestCache.set(sessionId, { updatedAt, digest });
+ return digest;
+}
+
+// ─── 发现:按项目目录找近期的本机转录 ───────────────────────────────
+
+interface TranscriptFile {
+ source: WorkbenchExternalSource;
+ file: string;
+ /** 文件名能看出来的 id;Pi 以首行 session id 为准时在读取后覆盖。 */
+ id: string;
+ mtimeMs: number;
+ size: number;
+}
+
+async function readdirSafe(dir: string) {
+ try {
+ return await fs.readdir(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+}
+
+async function statFile(source: WorkbenchExternalSource, file: string, id: string): Promise<TranscriptFile | null> {
+ const stat = await fs.stat(file).catch(() => null);
+ return stat?.isFile() ? { source, file, id, mtimeMs: stat.mtimeMs, size: stat.size } : null;
+}
+
+/**
+ * Claude Code 的项目存储名:路径分隔符(含 Windows 的 `\\`)与盘符冒号换成 `-`,另一种写法把所有
+ * 非字母数字都换成 `-`(与 CLI 的转码一致),两种都试。
+ */
+export function claudeStorageNames(projectDir: string): string[] {
+ return [...new Set([projectDir.replace(/[\\/:]/g, '-'), projectDir.replace(/[^A-Za-z0-9]/g, '-')])];
+}
+
+const CODEX_ROLLOUT_ID = /rollout-.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
+const CODEX_ROLLOUT_DATE = /^rollout-(\d{4})-(\d{2})-(\d{2})T/;
+
+/** Codex sessions/ 下最近 `days` 天的 `YYYY/MM/DD` 子目录。 */
+export function recentCodexDayDirs(root: string, now: number, days: number): string[] {
+ const out: string[] = [];
+ for (let offset = 0; offset <= days; offset += 1) {
+ const date = new Date(now - offset * DAY_MS);
+ const yyyy = String(date.getFullYear());
+ const mm = String(date.getMonth() + 1).padStart(2, '0');
+ const dd = String(date.getDate()).padStart(2, '0');
+ out.push(path.join(root, yyyy, mm, dd));
+ }
+ return [...new Set(out)];
+}
+
+async function collectTranscriptFiles(
+ roots: WorkbenchSessionRoots,
+ projectDirs: readonly string[],
+ since: number,
+ now: number,
+): Promise<{ recent: TranscriptFile[]; olderCount: number }> {
+ const recent: TranscriptFile[] = [];
+ let olderCount = 0;
+ const windowDays = Math.ceil((now - since) / DAY_MS) + 1;
+
+ // Claude Code:只进与项目存储名相同或以它为前缀(worktree 等)的文件夹。
+ const prefixes = projectDirs.flatMap(claudeStorageNames);
+ for (const root of roots.claude) {
+ for (const entry of await readdirSafe(root)) {
+ if (!entry.isDirectory()) continue;
+ if (!prefixes.some((prefix) => entry.name === prefix || entry.name.startsWith(`${prefix}-`))) continue;
+ const folder = path.join(root, entry.name);
+ for (const file of await readdirSafe(folder)) {
+ if (!file.isFile() || !file.name.endsWith('.jsonl')) continue;
+ const found = await statFile('claude', path.join(folder, file.name), path.basename(file.name, '.jsonl'));
+ if (!found) continue;
+ if (found.mtimeMs >= since) recent.push(found);
+ else olderCount += 1;
+ }
+ }
+ }
+
+ // Codex:多账号目录下每个供应商子目录是一个 home,先展开。
+ const accountRoots: string[] = [];
+ for (const accounts of roots.codexAccounts) {
+ for (const provider of await readdirSafe(accounts)) {
+ if (!provider.isDirectory()) continue;
+ accountRoots.push(path.join(accounts, provider.name, 'sessions'), path.join(accounts, provider.name, 'archived_sessions'));
+ }
+ }
+ // Codex:sessions/ 只进最近的日期子目录;archived_sessions/ 按文件名日期预筛。
+ for (const root of [...roots.codex, ...accountRoots]) {
+ const isArchive = path.basename(root) === 'archived_sessions';
+ const dirs = isArchive ? [root] : recentCodexDayDirs(root, now, windowDays);
+ for (const dir of dirs) {
+ for (const file of await readdirSafe(dir)) {
+ if (!file.isFile() || !file.name.endsWith('.jsonl')) continue;
+ const id = CODEX_ROLLOUT_ID.exec(file.name)?.[1];
+ if (!id) continue;
+ const date = CODEX_ROLLOUT_DATE.exec(file.name);
+ // 文件名日期是创建日;归档目录里明显早于窗口一个月以上的直接跳过,不 stat。
+ if (isArchive && date && Date.UTC(+date[1], +date[2] - 1, +date[3]) < since - windowDays * DAY_MS) continue;
+ const found = await statFile('codex', path.join(dir, file.name), id);
+ if (found && found.mtimeMs >= since) recent.push(found);
+ }
+ }
+ }
+
+ // Pi:平铺的 `<时间>_<id>.jsonl`,按 mtime 取近期。
+ for (const root of roots.pi) {
+ for (const file of await readdirSafe(root)) {
+ if (!file.isFile() || !file.name.endsWith('.jsonl')) continue;
+ const id = /_([^_]+)\.jsonl$/.exec(file.name)?.[1] ?? path.basename(file.name, '.jsonl');
+ const found = await statFile('pi', path.join(root, file.name), id);
+ if (found && found.mtimeMs >= since) recent.push(found);
+ }
+ }
+ return { recent, olderCount };
+}
+
+/** 本机外部会话候选(当前 Cindy 库里已有同一条的除外,避免重复显示),近期的带摘要。 */
+export interface WorkbenchExternalSession {
+ source: WorkbenchExternalSource;
+ id: string;
+ title: string;
+ cwd: string;
+ updatedAt: number;
+ file: string;
+ digest: WorkbenchDigest | null;
+}
+
+const AGENT_KIND: Record<WorkbenchExternalSource, string> = { claude: 'cc', codex: 'codex', pi: 'pi' };
+
+async function sessionsAlreadyInCindy(files: readonly TranscriptFile[]): Promise<Set<string>> {
+ const ids = [...new Set(files.map((file) => file.id))];
+ if (ids.length === 0) return new Set();
+ const rows = await getDbClient()
+ .drizzle.select({ sdkSessionId: sessions.sdkSessionId, agentKind: sessions.agentKind })
+ .from(sessions)
+ .where(and(inArray(sessions.sdkSessionId, ids), ne(sessions.status, 'deleted')));
+ return new Set(rows.flatMap((row) => (row.sdkSessionId ? [`${row.agentKind}:${row.sdkSessionId}`] : [])));
+}
+
+export const WORKBENCH_EXTERNAL_MAX = 30;
+
+/**
+ * 按已接手项目找本机 Claude Code / Codex / Pi 会话。两步都有界:
+ * 1. 近期文件只读开头 16KB 找 cwd,不在项目里的直接丢掉;
+ * 2. 项目里最新的至多 30 条才读头尾 64KB 算摘要。
+ * 更早的只计数,不读。当前 Cindy 库里已有的同一条只在任务里显示一次,不再当外部候选。
+ * `overflowCount` 是近期、在项目里但排在 30 条之外的条数。
+ */
+export async function listExternalSessionsForProjects(input: {
+ roots: WorkbenchSessionRoots;
+ projectDirs: readonly string[];
+ caseInsensitive: boolean;
+ since: number;
+ now: number;
+ max?: number;
+}): Promise<{ sessions: WorkbenchExternalSession[]; olderCount: number; overflowCount: number }> {
+ if (input.projectDirs.length === 0) return { sessions: [], olderCount: 0, overflowCount: 0 };
+ const { recent, olderCount } = await collectTranscriptFiles(input.roots, input.projectDirs, input.since, input.now);
+ const inCindy = await sessionsAlreadyInCindy(recent);
+ const byKey = new Map<string, TranscriptFile & { cwd: string }>();
+ for (const file of recent.sort((a, b) => b.mtimeMs - a.mtimeMs)) {
+ const key = `${file.source}:${file.id}`;
+ if (byKey.has(key) || inCindy.has(`${AGENT_KIND[file.source]}:${file.id}`)) continue;
+ const cwd = await readFileCwd(file.file, file).catch(() => null);
+ if (!cwd || !findWorkbenchProject(cwd, input.projectDirs, input.caseInsensitive)) continue;
+ byKey.set(key, { ...file, cwd });
+ }
+ const matched = [...byKey.values()];
+ const max = input.max ?? WORKBENCH_EXTERNAL_MAX;
+ const sessions = await Promise.all(
+ matched.slice(0, max).map(async (file): Promise<WorkbenchExternalSession> => {
+ const digest = await readFileDigest(file.source, file.id, file.file, file).catch(() => null);
+ return {
+ source: file.source,
+ id: file.id,
+ title: digest?.purpose ?? '',
+ cwd: file.cwd,
+ updatedAt: file.mtimeMs,
+ file: file.file,
+ digest,
+ };
+ }),
+ );
+ return { sessions, olderCount, overflowCount: Math.max(0, matched.length - max) };
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index c635ce3aaf..3cf138de08 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -961,6 +961,8 @@ export const MAKER_PUSH = {
BOT_GROUP_CHANGED: 'maker:bot-group:changed',
/** Bot 档案经主进程创建或更新后变化;renderer 收到后重拉伙伴列表。 */
BOT_PROFILE_CHANGED: 'maker:bot-profile:changed',
+ /** 伙伴工作台已接手的项目变化(payload: { botId });renderer 收到后重读项目列表。 */
+ BOT_WORKBENCH_CHANGED: 'maker:bot-workbench:changed',
BOT_LIFECYCLE_CHANGED: 'maker:bot-lifecycle:changed',
/**
* 被控端「当前 New Maker 草稿」全量变更广播。SYNC_NEW_MAKER_DRAFT 落 main 缓存后随即发,
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index c7451d2e28..d58d7c1761 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -71,6 +71,7 @@ import {
listBotSkillsForSession,
saveBotSkillForSession,
} from '../maker-ipc/botSkillService.js';
+import { runBotWorkbenchTool, type BotWorkbenchSendDeps } from '../maker-ipc/botWorkbenchTools.js';
import {
patchSessionMetaInDb,
renameSessionTitlesInDb,
@@ -167,6 +168,33 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
};
}
+ const workbenchSend: BotWorkbenchSendDeps = {
+ sendToSession: wrap(async (svc, { targetSessionId, message, dispatcherSessionId }) => {
+ const result = await svc.sendToSession({ targetSessionId, message, dispatcherSessionId });
+ return result.ok
+ ? {
+ ok: true as const,
+ wakeKind: result.wakeKind,
+ ...(result.queuedMessageId ? { queuedMessageId: result.queuedMessageId } : {}),
+ }
+ : { ok: false as const, errorCode: result.errorCode, message: result.message };
+ }),
+ stopSessionTurn: wrap(async (svc, params) => {
+ const result = await svc.stopSessionTurn(params);
+ return result.ok
+ ? { ok: true as const, status: result.status }
+ : { ok: false as const, errorCode: result.errorCode, message: result.message };
+ }),
+ startBackgroundTask: async ({ callerSessionId, workingDir, title, objective }) => {
+ const svc = tryGetBotDelegationService();
+ if (!svc) return { ok: false, errorCode: 'HOST_NOT_READY', message: 'Session task service not initialized' };
+ const result = await svc.startSessionTask({ callerSessionId, objective, title, workingDir });
+ return result.ok
+ ? { ok: true as const, sessionId: result.childSessionId }
+ : { ok: false as const, errorCode: result.errorCode, message: result.message };
+ },
+ };
+
const withAccountDataAccess = async <T>(sessionId: string | undefined, operation: (assertCurrent: () => Promise<void>) => Promise<T>): Promise<T> => {
const dbClient = tryGetDbClient();
if (!dbClient || !sessionId) throw new Error('Account data caller unavailable');
@@ -847,6 +875,16 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
},
list: (params) => listBotSkillsForSession(params),
},
+ // 工作台:伙伴继续 / 停止主人交给它的项目里的任务。授权在 botWorkbenchAccess 里逐次
+ // 确定性校验;投递与停止复用 send_to_session / stop_session_turn 的同一条宿主路径。
+ botWorkbench: {
+ get: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.get(params)),
+ read: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.read(params)),
+ set: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.set(params)),
+ setMany: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.setMany(params)),
+ continueTask: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.continueTask(params)),
+ stopTask: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.stopTask(params)),
+ },
skillhub: createSkillhubAgentTools({
isCurrentSession: (context) => !!context.sessionId
&& deps.isCurrentLocalSessionInstance?.(context.sessionId, context.sessionInstanceId) === true,
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index 0dfc9e5001..0ffc093ee4 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -139,6 +139,10 @@ function parseCommand(raw: unknown): RsbWindowCommand {
if (typeof r.botId !== 'string' || !r.botId || r.botId.length > 128) throwIpcError('INVALID_PARAMS', 'Invalid teammate');
return { type: 'open-routines-tab', sessionId: r.sessionId, botId: r.botId };
}
+ if (r.type === 'open-bot-workbench-tab') {
+ if (typeof r.botId !== 'string' || !r.botId || r.botId.length > 128) throwIpcError('INVALID_PARAMS', 'Invalid teammate');
+ return { type: 'open-bot-workbench-tab', sessionId: r.sessionId, botId: r.botId };
+ }
if (r.type === 'open-background-tasks-tab') {
const hasFocusTaskId =
Object.prototype.hasOwnProperty.call(r, 'focusTaskId') && r.focusTaskId !== undefined;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 2fb764b265..849472e2dc 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -804,6 +804,7 @@ const fanOutBotDelegationChanged = createIpcFanOut('maker:bot-delegation:changed
const fanOutBotDirectMessageChanged = createIpcFanOut('maker:bot-direct-message:changed');
const fanOutBotGroupChanged = createIpcFanOut('maker:bot-group:changed');
const fanOutBotProfileChanged = createIpcFanOut('maker:bot-profile:changed');
+const fanOutBotWorkbenchChanged = createIpcFanOut('maker:bot-workbench:changed');
const fanOutBotLifecycleChanged = createIpcFanOut('maker:bot-lifecycle:changed');
const fanOutMakerPiPackagesChanged = createIpcFanOut('maker:pi-packages:changed');
const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USD
@@ -5504,6 +5505,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('local-db:bots:create-canonical-session', body),
history: (botId: string): Promise<unknown[]> =>
ipcRenderer.invoke('local-db:bots:history', botId),
+ workbench: {
+ get: (botId: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:bots:workbench:get', botId),
+ addDirectory: (botId: string, path: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:bots:workbench:add-directory', botId, path),
+ removeDirectory: (botId: string, path: string): Promise<void> =>
+ ipcRenderer.invoke('local-db:bots:workbench:remove-directory', botId, path),
+ readTask: (botId: string, taskId: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:bots:workbench:read-task', botId, taskId),
+ candidates: (botId: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:bots:workbench:candidates', botId),
+ },
listSkills: (botId: string): Promise<import('../shared/botSkill').BotSkillSummary[]> =>
ipcRenderer.invoke('local-db:bots:skills:list', botId),
memory: {
@@ -5937,6 +5950,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:bot-group:plan-edit', input),
onBotGroupChanged: fanOutBotGroupChanged,
onBotProfileChanged: fanOutBotProfileChanged,
+ onBotWorkbenchChanged: fanOutBotWorkbenchChanged,
runBotLifecycleAction: (
request: import('../shared/botLifecycle').BotLifecycleActionRequest,
): Promise<import('../shared/botLifecycle').BotLifecycleActionResult> =>
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx b/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
index e264818ef3..9258fe494c 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx
@@ -6,15 +6,18 @@
* you are talking to, and the way into their settings. Two entrances, both
* leading to the same place — the name/avatar lockup itself, and the gear at the
* right end of the bar — because "click the name" is the discoverable one and
- * "the gear is on the right" is the learned one.
+ * "the gear is on the right" is the learned one. Local teammates also get a
+ * permanent way into their workbench here: the sidebar tab can be closed, and
+ * nothing else reopens it.
*/
import { useMemo } from 'react';
-import { Settings2 } from 'lucide-react';
+import { LayoutGrid, Settings2 } from 'lucide-react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useRegisterContentHeader } from '../feature-context';
+import { openBotWorkbenchTab } from '@/features/right-sidebar/lib/openBotWorkbenchTab';
import { BotAvatar } from './BotAvatar';
import { isCindyDeviceBot } from './cindyDeviceRoster';
import { CindyHeaderDevicePicker } from './CindyDevicePicker';
@@ -24,6 +27,8 @@ export interface BotChatIdentity {
templateId?: string;
deviceId?: string;
deviceName?: string;
+ /** 本机伙伴主任务的 session id;有它才有工作台入口。远程名册里为 null。 */
+ sessionId?: string | null;
name: string;
avatar?: string | null;
avatarColor?: string | null;
@@ -62,6 +67,18 @@ export function BotSessionContentHeader({ bot }: { bot: BotChatIdentity }) {
{bot.deviceName}
</span>
) : null}
+ {!bot.deviceId && bot.sessionId ? (
+ <button
+ type="button"
+ onClick={() => void openBotWorkbenchTab(bot.sessionId!, bot.id).catch(() => undefined)}
+ aria-label={t('bots.workbench.open')}
+ title={t('bots.workbench.open')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <LayoutGrid size={15} />
+ </button>
+ ) : null}
<button
type="button"
onClick={openSettings}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
index f1e214dbc9..427843e796 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
@@ -10,6 +10,7 @@ import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
import type { ComposerBotMention } from '@/lib/fileTypes';
import { getBotLastReadAt, markBotRead } from './botReadState';
import { useBotProfiles } from './botStore';
+import { ensureBotWorkbenchTab } from '@/features/right-sidebar/lib/openBotWorkbenchTab';
import type { BotChatIdentity } from './BotSessionContentHeader';
import type { BotChatBinding } from './botChatPresentation';
import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
@@ -185,6 +186,14 @@ function BotSessionGateView() {
};
}, [botId, reloadVersion, sessionId]);
+ // 本机伙伴主任务:右侧栏默认带上「工作台」标签(首次进入时创建并展开)。
+ // 远程伙伴走 RemoteBotSessionView,不经过这里;渠道任务、历史任务不提供工作台。
+ const workbenchSessionId = gate.kind === 'ready' && gate.isCanonical ? sessionId : undefined;
+ useEffect(() => {
+ if (!botId || !workbenchSessionId) return;
+ void ensureBotWorkbenchTab(workbenchSessionId, botId).catch(() => undefined);
+ }, [botId, workbenchSessionId]);
+
const onReadThrough = useCallback((at: number) => {
if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
}, [botId, gate, sessionId]);
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
new file mode 100644
index 0000000000..8a1d3eb388
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -0,0 +1,1552 @@
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+import {
+ ArrowLeft,
+ ArrowUp,
+ ChevronRight,
+ CircleCheck,
+ CircleDot,
+ CirclePause,
+ Clock3,
+ FileText,
+ Folder,
+ FolderOpen,
+ GitPullRequest,
+ Lightbulb,
+ Link2,
+ Plus,
+ Square,
+ SquareArrowOutUpRight,
+ X,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { prStatusKey, sessionPrUrl } from '@cindy/maker-shared';
+import { useNavigate } from 'react-router-dom';
+import type { Routine, RoutineRun } from '@cindy/maker-scheduler';
+
+import { Button } from '@/components/ui/button';
+import { FileTypeTile } from '@/components/ui/file-type-tile';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { Tip } from '@/components/ui/tooltip';
+import { collectCachedGeneratedFiles } from '@/components/chat/generatedFilesProjection';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';
+import { useElementVisible } from '@/cindy-brain/ghostUnreadStore';
+import type { PrStatusKind } from '@/lib/gitContext.types';
+import { PR_STATUS_COLOR, PR_STATUS_ICON } from '@/features/cc-agent/gitContextPrVisuals';
+import { useCCSessions } from '@/hooks/useCCSessions';
+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { useSessionAttentionKinds } from '@/lib/sessionAttentionStore';
+import * as sessionService from '@/lib/sessionService';
+import { emitRefresh } from '@/lib/sessionsBus';
+import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import { cronToHuman } from '@/features/scheduler/lib/cronToHuman';
+import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';
+import { formatNextRun } from '@/features/scheduler/lib/formatters';
+import { schedulesStore, useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';
+import { openRoutinesTab } from '@/features/right-sidebar/lib/openRoutinesTab';
+import { useAgentIslandActivityMap } from '@/state/agentIslandActivity';
+import {
+ BOT_WORKBENCH_MAX_DIRECTORIES,
+ isCaseInsensitivePlatform,
+ parseWorkbenchTaskId,
+ validateWorkbenchRef,
+ type BotWorkbench as BotWorkbenchData,
+ type WorkbenchTaskState,
+ type WorkbenchTranscript,
+} from '../../../shared/botWorkbench';
+import { useBotDelegations } from './botDelegationLive';
+import { isBotPrimaryGeneratedFile } from './botGeneratedArtifacts';
+import { useBotProfiles } from './botStore';
+import {
+ buildWorkbenchProjectOptions,
+ buildWorkbenchTiles,
+ collectBotHiddenSessionIds,
+ countUnjudgedCandidates,
+ groupWorkbenchTiles,
+ workbenchGroupHasFollowUp,
+ tierWorkbenchProjectOptions,
+ type ExternalSessionCandidate,
+ type WorkbenchPathHints,
+ type WorkbenchGroupKey,
+ type WorkbenchProjectOption,
+ type WorkbenchRoutineInput,
+ type WorkbenchTile,
+} from './botWorkbenchProjection';
+
+/**
+ * 伙伴工作台(右侧栏的一个标签,只对本机伙伴主任务提供)。
+ *
+ * - 没接手项目时:从已有项目里选一个 →「交给<伙伴>」,两次点击完成接手。接手 = 理解:
+ * 只记下目录、告诉伙伴一声,不批量导入;伙伴随后读候选、写判断,条目随之出现。
+ * - 接手后:项目胶囊、伙伴还在读时一行「正在了解…」、单列任务列表、最近产出。项目里最近
+ * 30 天的 Cindy 任务(含主人自己开的)都在,随任务列表实时更新。列表按 等你 / 在做 / 待做 /
+ * 做完 分组(做完默认折叠),每条两层:完整标题 + 伙伴的意见(末尾可带 PR 状态标)。
+ * - 推进:待做 / 等你 两组的「跟进」以主人身份让伙伴在左边接着干;点一条在本标签内打开详情:
+ * 伙伴的判断、PR、最近内容、补一句让伙伴接着做。
+ */
+
+/** 默认展示几格;「全部 N」展开其余。 */
+const MAX_OUTPUTS = 4;
+
+type ChatStore = typeof import('@/lib/makerChatStore').makerChatStore;
+type ChatSnapshot = ReturnType<ChatStore['getSnapshot']>;
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
+/** 发送链路初始化较重;工作台挂载后再加载,不拖慢伙伴页首屏。 */
+function useChatStore(): ChatStore | null {
+ const [store, setStore] = useState<ChatStore | null>(null);
+ useEffect(() => {
+ let alive = true;
+ import('@/lib/makerChatStore')
+ .then((module) => {
+ if (alive) setStore(module.makerChatStore);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, []);
+ return store;
+}
+
+function useChatSnapshot(store: ChatStore | null, sessionId: string): ChatSnapshot | null {
+ const subscribe = useCallback(
+ (onChange: () => void) => (store ? store.subscribe(sessionId, onChange) : () => {}),
+ [sessionId, store],
+ );
+ const read = useCallback(() => (store ? store.getSnapshot(sessionId) : null), [sessionId, store]);
+ return useSyncExternalStore(subscribe, read, read);
+}
+
+function useNow(active: boolean): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!active) return;
+ const timer = setInterval(() => setNow(Date.now()), 1_000);
+ return () => clearInterval(timer);
+ }, [active]);
+ return now;
+}
+
+function relativeTime(ms: number, language: string, now: number): string | null {
+ if (!Number.isFinite(ms) || ms <= 0) return null;
+ const minutes = Math.round((ms - now) / 60_000);
+ const format = new Intl.RelativeTimeFormat(language, { numeric: 'auto', style: 'short' });
+ if (Math.abs(minutes) < 60) return format.format(minutes, 'minute');
+ const hours = Math.round(minutes / 60);
+ if (Math.abs(hours) < 24) return format.format(hours, 'hour');
+ return format.format(Math.round(hours / 24), 'day');
+}
+
+function elapsed(startedAtMs: number, now: number): string {
+ const seconds = Math.max(0, Math.floor((now - startedAtMs) / 1_000));
+ const minutes = Math.floor(seconds / 60);
+ const pad = (value: number) => String(value).padStart(2, '0');
+ return minutes >= 60
+ ? `${Math.floor(minutes / 60)}:${pad(minutes % 60)}:${pad(seconds % 60)}`
+ : `${minutes}:${pad(seconds % 60)}`;
+}
+
+function listFormat(items: string[], language: string): string {
+ try {
+ return new Intl.ListFormat(language, { style: 'long', type: 'conjunction' }).format(items);
+ } catch {
+ return items.join(', ');
+ }
+}
+
+/** 伙伴自己的例行任务(含导入来的自动化)及最近一次运行。 */
+function useBotRoutines(botId: string): WorkbenchRoutineInput[] {
+ const [routines, setRoutines] = useState<WorkbenchRoutineInput[]>([]);
+ useEffect(() => {
+ const api = window.electronAPI?.routines;
+ if (!api) return;
+ let alive = true;
+ let request = 0;
+ const owner = getDataOwnerGeneration();
+ const load = () => {
+ const current = ++request;
+ void api
+ .list(botId)
+ .then((items: Routine[]) =>
+ Promise.all(
+ items.map(async (routine): Promise<WorkbenchRoutineInput> => {
+ const history: RoutineRun[] = await api.history(botId, routine.id).catch(() => []);
+ const last = history[0];
+ return {
+ id: routine.id,
+ name: routine.name,
+ enabled: routine.enabled,
+ ...(routine.activity ? { activity: routine.activity } : {}),
+ triggers: routine.triggers,
+ updatedAt: routine.updatedAt,
+ lastRun: last
+ ? {
+ status: last.status,
+ createdAt: last.createdAt,
+ ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}),
+ ...(last.resultText ? { resultText: last.resultText } : {}),
+ ...(last.error ? { error: last.error } : {}),
+ }
+ : null,
+ };
+ }),
+ ),
+ )
+ .then((rows) => {
+ if (alive && current === request && isDataOwnerGenerationCurrent(owner)) setRoutines(rows);
+ })
+ .catch(() => {});
+ };
+ load();
+ const off = api.onChanged(load);
+ return () => {
+ alive = false;
+ off();
+ };
+ }, [botId]);
+ return routines;
+}
+
+const EMPTY_WORKBENCH: BotWorkbenchData = { directories: [], tasks: {} };
+
+function useWorkbenchData(botId: string): BotWorkbenchData | null {
+ const [data, setData] = useState<BotWorkbenchData | null>(null);
+ useEffect(() => {
+ const api = window.electronAPI?.localDb?.bots?.workbench;
+ if (!api) {
+ setData(EMPTY_WORKBENCH);
+ return;
+ }
+ let alive = true;
+ const load = () => {
+ const owner = getDataOwnerGeneration();
+ void api
+ .get(botId)
+ .then((next) => {
+ if (alive && isDataOwnerGenerationCurrent(owner)) {
+ setData(next ? { directories: next.directories ?? [], tasks: next.tasks ?? {} } : EMPTY_WORKBENCH);
+ }
+ })
+ .catch(() => {
+ if (alive) setData((previous) => previous ?? EMPTY_WORKBENCH);
+ });
+ };
+ setData(null);
+ load();
+ const off = window.electronAPI?.maker?.onBotWorkbenchChanged?.((payload) => {
+ if (payload.botId !== botId) return;
+ load();
+ // 伙伴继续一条本机会话时会先把它导入;刷新任务列表,让新任务出现在格子里。
+ emitRefresh();
+ });
+ return () => {
+ alive = false;
+ off?.();
+ };
+ }, [botId]);
+ return data;
+}
+
+/**
+ * 已接手项目里近期的本机 Claude Code / Codex / Pi 会话(与伙伴工具同一份发现:按项目过滤、只看
+ * 最近 30 天、只读头部找目录)。项目变化时读一次,不轮询,不导入。
+ */
+function useExternalCandidates(botId: string, projectKey: string): ExternalSessionCandidate[] {
+ const [candidates, setCandidates] = useState<ExternalSessionCandidate[]>([]);
+ useEffect(() => {
+ const api = window.electronAPI?.localDb?.bots?.workbench;
+ if (!projectKey || !api?.candidates) {
+ setCandidates([]);
+ return;
+ }
+ let alive = true;
+ const owner = getDataOwnerGeneration();
+ void api
+ .candidates(botId)
+ .then((result) => {
+ if (alive && isDataOwnerGenerationCurrent(owner) && result.ok) setCandidates(result.candidates);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [botId, projectKey]);
+ return candidates;
+}
+
+/** 以主人身份往伙伴主任务发一句话(交接、详情里的「补一句」都走这里)。 */
+async function sendAsOwner(sessionId: string, text: string): Promise<boolean> {
+ const owner = getDataOwnerGeneration();
+ const [chatStore, row] = await Promise.all([
+ import('@/lib/makerChatStore').then((module) => module.makerChatStore),
+ sessionService.get(sessionId),
+ ]);
+ if (!isDataOwnerGenerationCurrent(owner) || !row.workingDir) return false;
+ return chatStore.sendMessage(sessionId, text, row.model, row.effort, row.permissionMode, row.workingDir);
+}
+
+export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: string }) {
+ const { t, i18n } = useTranslation();
+ const navigate = useNavigate();
+ const profiles = useBotProfiles();
+ const botName = profiles.find((profile) => profile.id === botId)?.name ?? '';
+ const workbench = useWorkbenchData(botId);
+ const { sessions } = useCCSessions({ includeArchived: 'active' });
+ const delegations = useBotDelegations(sessionId);
+ const activityMap = useAgentIslandActivityMap();
+ const attentionKinds = useSessionAttentionKinds();
+ const schedules = useSchedulesSnapshot();
+ const routines = useBotRoutines(botId);
+ const chatStore = useChatStore();
+ const chat = useChatSnapshot(chatStore, sessionId);
+ const caseInsensitive = isCaseInsensitivePlatform(window.electronAPI?.platform);
+ const inSidebarWindow = isSidebarWindow();
+
+ useEffect(() => {
+ void schedulesStore.ensure().catch(() => {});
+ }, []);
+
+ const directories = useMemo(() => workbench?.directories ?? [], [workbench]);
+ const judgments = useMemo(() => workbench?.tasks ?? {}, [workbench]);
+ const projectDirs = useMemo(() => directories.map((dir) => dir.path), [directories]);
+ const candidates = useExternalCandidates(botId, projectDirs.join('\n'));
+ const hiddenIds = useMemo(() => collectBotHiddenSessionIds(profiles), [profiles]);
+ const erroredIds = useMemo(
+ () => new Set([...attentionKinds].filter(([, kind]) => kind === 'error').map(([id]) => id)),
+ [attentionKinds],
+ );
+
+ const tiles = useMemo(
+ () =>
+ buildWorkbenchTiles({
+ sessions,
+ hiddenIds,
+ projectDirs,
+ caseInsensitive,
+ delegations,
+ activity: activityMap,
+ erroredIds,
+ schedules: schedules ?? [],
+ routines,
+ judgments,
+ candidates,
+ }),
+ [
+ sessions,
+ hiddenIds,
+ projectDirs,
+ caseInsensitive,
+ delegations,
+ activityMap,
+ erroredIds,
+ schedules,
+ routines,
+ judgments,
+ candidates,
+ ],
+ );
+
+ // 伙伴正在读这些项目:还有本机外部会话没写判断,且伙伴主任务正在跑。
+ const unjudged = useMemo(
+ () => countUnjudgedCandidates({ projectDirs, caseInsensitive, candidates, judgments }),
+ [projectDirs, caseInsensitive, candidates, judgments],
+ );
+ const understanding = unjudged > 0 && activityMap.get(sessionId)?.phase === 'running';
+ // 打开详情时记下那一格;之后格子状态变了(甚至因为做完而不再上工作台)详情仍留在原处。
+ const [detailOpened, setDetailOpened] = useState<WorkbenchTile | null>(null);
+ const detailTile = detailOpened ? (tiles.find((tile) => tile.key === detailOpened.key) ?? detailOpened) : null;
+
+ const [adding, setAdding] = useState(false);
+ const picking = workbench !== null && (directories.length === 0 || adding);
+ const now = useNow(tiles.some((tile) => tile.state === 'running' && tile.startedAtMs !== null));
+
+ const openTile = useCallback(
+ (tile: WorkbenchTile) => {
+ if (tile.type === 'session' || tile.type === 'external' || tile.type === 'item') {
+ // 任务在本标签内打开详情,不换路由、不跳任务页。
+ setDetailOpened(tile);
+ } else if (tile.type === 'schedule') {
+ if (!inSidebarWindow) navigate(scheduleFocusPath(tile.id));
+ } else {
+ void openRoutinesTab(sessionId, botId);
+ }
+ },
+ [botId, inSidebarWindow, navigate, sessionId],
+ );
+
+ // 跟进:以主人身份往伙伴聊天发「跟进「<标题>」」,由伙伴在左边接着干。按钮转圈直到伙伴主任务
+ // 开始运行(或已在运行、消息排进队列);条目怎么移动交给真实状态,不做乐观更新。
+ const botPhase = activityMap.get(sessionId)?.phase ?? null;
+ const [following, setFollowing] = useState<{ key: string; sentWhileRunning: boolean } | null>(null);
+ const followingKey = following?.key ?? null;
+ useEffect(() => {
+ if (!following) return;
+ if (botPhase === 'running' && !following.sentWhileRunning) setFollowing(null);
+ if (botPhase !== 'running' && following.sentWhileRunning) setFollowing((value) => value && { ...value, sentWhileRunning: false });
+ }, [botPhase, following]);
+ useEffect(() => {
+ if (!following) return;
+ const timer = setTimeout(() => setFollowing(null), 30_000);
+ return () => clearTimeout(timer);
+ }, [following?.key]);
+ const followUp = useCallback(
+ (tile: WorkbenchTile) => {
+ if (following) return;
+ const title = tile.title || t('bots.workbench.untitled');
+ setFollowing({ key: tile.key, sentWhileRunning: botPhase === 'running' });
+ void sendAsOwner(sessionId, t('bots.workbench.followUp.message', { title }))
+ .then((sent) => {
+ if (sent) return;
+ setFollowing(null);
+ toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ })
+ .catch(() => {
+ setFollowing(null);
+ toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ });
+ },
+ [botName, botPhase, following, sessionId, t],
+ );
+
+ const [chatWorkingDir, setChatWorkingDir] = useState<string | null>(null);
+ useEffect(() => {
+ let alive = true;
+ void sessionService
+ .get(sessionId)
+ .then((row) => {
+ if (alive) setChatWorkingDir(row.workingDir ?? null);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [sessionId]);
+
+ // 产出:后台任务交回的文件在前(明确交付的成果),再补主任务对话里伙伴新建的文件。
+ const outputs = useMemo(() => {
+ const out: Array<{ path: string; name: string }> = [];
+ const seen = new Set<string>();
+ const push = (file: { path: string; name: string }) => {
+ if (out.length >= MAX_OUTPUTS || seen.has(file.path)) return;
+ seen.add(file.path);
+ out.push(file);
+ };
+ for (const task of [...delegations].sort((a, b) => b.createdAt - a.createdAt)) {
+ for (const artifact of task.artifacts) {
+ if (!artifact.absolutePath || artifact.status === 'deleted') continue;
+ const name = artifact.absolutePath.split(/[\\/]/).pop() ?? artifact.path;
+ if (isBotPrimaryGeneratedFile({ path: artifact.absolutePath, name, source: 'tool' })) {
+ push({ path: artifact.absolutePath, name });
+ }
+ }
+ }
+ if (chat && chatWorkingDir && chat.messages.length > 0) {
+ const files = collectCachedGeneratedFiles(chat.messages, chatWorkingDir);
+ for (let index = files.length - 1; index >= 0; index -= 1) {
+ const file = files[index];
+ if (file.source !== 'tool' || file.ready === false) continue;
+ if (isBotPrimaryGeneratedFile(file, chatWorkingDir)) push({ path: file.path, name: file.name });
+ }
+ }
+ return out;
+ }, [chat, chatWorkingDir, delegations]);
+
+ if (workbench === null) {
+ return (
+ <div className="flex h-full items-center justify-center bg-[var(--surface)]">
+ <Spinner size={16} className="text-[var(--text-tertiary)]" role="status" aria-label={t('ccAgent.common.loading')} />
+ </div>
+ );
+ }
+
+ const routineTiles = tiles.filter((tile) => tile.type === 'routine');
+
+ if (detailTile && (detailTile.type === 'session' || detailTile.type === 'external' || detailTile.type === 'item')) {
+ return (
+ <TaskDetail
+ botId={botId}
+ botName={botName}
+ botSessionId={sessionId}
+ tile={detailTile}
+ now={now}
+ canNavigate={!inSidebarWindow}
+ projectDirs={projectDirs}
+ caseInsensitive={caseInsensitive}
+ onBack={() => setDetailOpened(null)}
+ />
+ );
+ }
+
+ // 最近交给伙伴的项目排在最前,正在了解的通常就是它。
+ const understandingProject = understanding ? (directories[0]?.name ?? '') : '';
+
+ return (
+ <div className="h-full min-h-0 overflow-y-auto overflow-x-hidden bg-[var(--surface)]">
+ {picking ? (
+ <ProjectPicker
+ botId={botId}
+ botName={botName}
+ sessionId={sessionId}
+ sessions={sessions}
+ hiddenIds={hiddenIds}
+ schedules={schedules ?? []}
+ excludeDirs={projectDirs}
+ onCancel={directories.length > 0 ? () => setAdding(false) : undefined}
+ onHandedOver={() => setAdding(false)}
+ />
+ ) : (
+ <>
+ <ProjectCapsules
+ botId={botId}
+ botName={botName}
+ directories={directories}
+ onAdd={directories.length < BOT_WORKBENCH_MAX_DIRECTORIES ? () => setAdding(true) : undefined}
+ />
+ {understanding ? (
+ <p className="flex items-center gap-1.5 px-5 pb-3 pt-1 text-13 leading-5 text-[var(--text-secondary)]">
+ <Spinner size={12} aria-hidden className="shrink-0" />
+ <span className="min-w-0 truncate">
+ {t('bots.workbench.understanding', { name: botName, project: understandingProject })}
+ </span>
+ </p>
+ ) : null}
+ </>
+ )}
+
+ {/* 还没接手项目时,伙伴已有的自动化(例行任务、导入来的自动化)照常列在下面。 */}
+ {!picking || routineTiles.length > 0 ? (
+ <TaskGroups
+ tiles={picking ? routineTiles : tiles}
+ now={now}
+ language={i18n.language}
+ showEmpty={!picking && !understanding}
+ followingKey={followingKey}
+ onOpen={openTile}
+ onFollowUp={followUp}
+ />
+ ) : null}
+
+ {!picking ? (
+ <section className="border-t border-[var(--border-default)] px-5 pb-5">
+ <h3 className="flex h-11 items-center text-16 font-medium leading-6 text-[var(--text-primary)]">
+ {t('bots.workbench.outputs')}
+ </h3>
+ {outputs.length === 0 ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('bots.workbench.outputsEmpty', { name: botName })}
+ </p>
+ ) : (
+ <div className="grid grid-cols-4 gap-2.5">
+ {outputs.map((file) => (
+ <button
+ key={file.path}
+ type="button"
+ title={file.path}
+ onClick={() => void window.electronAPI.openPath?.(file.path)}
+ className="group flex min-w-0 flex-col items-center gap-1.5 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <span className="flex h-[52px] w-full items-center justify-center rounded-xl border border-[var(--border-default)] transition-colors group-hover:bg-[var(--surface-hover)]">
+ <FileTypeTile name={file.name} />
+ </span>
+ <span className="w-full truncate text-center text-12 leading-4 text-[var(--text-secondary)]">
+ {file.name}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </section>
+ ) : null}
+ </div>
+ );
+}
+
+// ─── 空状态:把一个项目交给伙伴 ─────────────────────────────────────
+
+type ScanState =
+ | { kind: 'loading' }
+ | {
+ kind: 'ready';
+ candidates: ExternalSessionCandidate[];
+ gitRepoDirs: string[];
+ pathHints: WorkbenchPathHints | null;
+ }
+ | { kind: 'failed' };
+
+type ProjectOptionsInput = Parameters<typeof buildWorkbenchProjectOptions>[0];
+
+function ProjectPicker({
+ botId,
+ botName,
+ sessionId,
+ sessions,
+ hiddenIds,
+ schedules,
+ excludeDirs,
+ onCancel,
+ onHandedOver,
+}: {
+ botId: string;
+ botName: string;
+ sessionId: string;
+ sessions: ProjectOptionsInput['sessions'];
+ hiddenIds: ReadonlySet<string>;
+ schedules: ProjectOptionsInput['schedules'];
+ excludeDirs: readonly string[];
+ onCancel?: () => void;
+ onHandedOver: () => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const platform = window.electronAPI?.platform ?? '';
+ const caseInsensitive = isCaseInsensitivePlatform(platform);
+ const [scan, setScan] = useState<ScanState>({ kind: 'loading' });
+ const [selected, setSelected] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [showFolded, setShowFolded] = useState(false);
+ const [now] = useState(() => Date.now());
+
+ // 本机 Claude Code / Codex 的候选只在打开空状态时扫描一次(主进程带缓存与并发去重),不轮询。
+ useEffect(() => {
+ const api = window.electronAPI?.localDb?.sessionImport;
+ if (!api) {
+ setScan({ kind: 'ready', candidates: [], gitRepoDirs: [], pathHints: null });
+ return;
+ }
+ let alive = true;
+ const owner = getDataOwnerGeneration();
+ void api
+ .scan()
+ .then((result) => {
+ if (!alive || !isDataOwnerGenerationCurrent(owner)) return;
+ setScan({
+ kind: 'ready',
+ candidates: result.candidates
+ .filter((item) => item.workspaceKind === 'project')
+ .map((item) => ({
+ source: item.source,
+ id: item.id,
+ projectDir: item.projectDir,
+ updatedAt: item.updatedAt,
+ archived: item.archived,
+ })),
+ gitRepoDirs: result.gitRepoDirs ?? [],
+ pathHints: result.pathHints ?? null,
+ });
+ })
+ .catch(() => {
+ if (alive) setScan({ kind: 'failed' });
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ const candidates = useMemo(() => (scan.kind === 'ready' ? scan.candidates : []), [scan]);
+ const gitRepoDirs = useMemo(() => (scan.kind === 'ready' ? scan.gitRepoDirs : []), [scan]);
+ const pathHints = scan.kind === 'ready' ? scan.pathHints : null;
+ const options = useMemo(
+ () =>
+ buildWorkbenchProjectOptions({
+ sessions,
+ hiddenIds,
+ schedules,
+ candidates,
+ gitRepoDirs,
+ localPlatform: platform,
+ caseInsensitive,
+ excludeDirs,
+ }),
+ [sessions, hiddenIds, schedules, candidates, gitRepoDirs, platform, caseInsensitive, excludeDirs],
+ );
+ // 不像用户项目的目录直接不列;像临时目录、只有零星会话的折叠到「还有 N 个」里。
+ const tiers = useMemo(
+ () => tierWorkbenchProjectOptions(options, { hints: pathHints, caseInsensitive, now }),
+ [options, pathHints, caseInsensitive, now],
+ );
+ const visible = showFolded ? [...tiers.primary, ...tiers.folded] : tiers.primary;
+ const listed = tiers.primary.length + tiers.folded.length;
+ const chosen = options.find((option) => option.dir === selected) ?? null;
+
+ const handOver = useCallback(
+ async (dir: string, name: string) => {
+ const api = window.electronAPI?.localDb?.bots?.workbench;
+ if (busy || !api) return;
+ setBusy(true);
+ const owner = getDataOwnerGeneration();
+ try {
+ // 1. 记下这个项目:这一次点击就是主人对该项目任务的授权。不导入任何会话。
+ const added = await api.addDirectory(botId, dir).catch(() => null);
+ if (!added?.ok) {
+ toast.error(
+ added?.errorCode === 'TOO_MANY'
+ ? t('bots.workbench.tooManyDirs', { name: botName, count: BOT_WORKBENCH_MAX_DIRECTORIES })
+ : t('bots.workbench.dirUnavailable'),
+ );
+ return;
+ }
+ onHandedOver();
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ // 2. 以主人身份告诉伙伴一声;怎么接手写在伙伴的工具说明里,用户可见的消息只说人话。
+ const sent = await sendAsOwner(sessionId, t('bots.workbench.handoverMessage', { project: name }));
+ if (!sent) toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ } catch {
+ toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ } finally {
+ setBusy(false);
+ }
+ },
+ [botId, botName, busy, onHandedOver, sessionId, t],
+ );
+
+ const pickFolder = useCallback(async () => {
+ const picked = await window.electronAPI.dialog?.showOpenDirectory();
+ const dirPath = picked?.success ? picked.path : null;
+ if (!dirPath) return;
+ const name = dirPath.split(/[\\/]/).filter(Boolean).pop() ?? dirPath;
+ await handOver(dirPath, name);
+ }, [handOver]);
+
+ const grant = chosen ? grantText(chosen, botName, i18n.language, t) : null;
+
+ return (
+ <section className="px-5 pb-5 pt-3">
+ <div className="flex items-start gap-2">
+ <h2 className="min-w-0 flex-1 text-18 font-medium leading-[1.44] text-[var(--text-primary)]">
+ {t('bots.workbench.emptyTitle', { name: botName })}
+ </h2>
+ {onCancel ? (
+ <Button variant="secondary" size="sm" tone="quiet" compact onClick={onCancel}>
+ {t('bots.workbench.cancelAdd')}
+ </Button>
+ ) : null}
+ </div>
+ <p className="mt-1 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('bots.workbench.emptyDescription', { name: botName })}
+ </p>
+ <div
+ className="mt-4 flex flex-col gap-2"
+ role="radiogroup"
+ aria-label={t('bots.workbench.emptyTitle', { name: botName })}
+ >
+ {visible.map((option) => (
+ <button
+ key={option.dir}
+ type="button"
+ role="radio"
+ aria-checked={selected === option.dir}
+ disabled={busy}
+ title={option.dir}
+ onClick={() => setSelected(option.dir)}
+ className={cn(
+ 'flex h-[68px] w-full items-center gap-3 rounded-xl border px-3.5 text-left outline-none transition-colors',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-60',
+ selected === option.dir
+ ? 'border-[var(--text-tertiary)] bg-[var(--surface-hover)]'
+ : 'border-[var(--border-default)] enabled:hover:bg-[var(--surface-hover)]',
+ )}
+ >
+ <Folder size={18} strokeWidth={1.8} className="shrink-0 text-[var(--text-secondary)]" aria-hidden />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-14 font-medium leading-[1.57] text-[var(--text-primary)]">{option.name}</span>
+ <span className="truncate text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {projectCounts(option, t)}
+ </span>
+ </span>
+ <span className="shrink-0 text-12 text-[var(--text-tertiary)]">
+ {relativeTime(option.latestActivityMs, i18n.language, now)}
+ </span>
+ </button>
+ ))}
+ {tiers.folded.length > 0 ? (
+ <Button
+ variant="secondary"
+ size="sm"
+ tone="quiet"
+ compact
+ className="-ml-3 self-start"
+ aria-expanded={showFolded}
+ onClick={() => setShowFolded((value) => !value)}
+ >
+ {showFolded
+ ? t('bots.workbench.hideMoreProjects')
+ : t('bots.workbench.moreProjects', { count: tiers.folded.length })}
+ </Button>
+ ) : null}
+ {scan.kind === 'loading' && listed === 0 ? (
+ <div className="flex items-center gap-2 py-2 text-12 text-[var(--text-tertiary)]">
+ <Spinner size={14} aria-hidden />
+ {t('bots.workbench.scanning')}
+ </div>
+ ) : null}
+ {scan.kind !== 'loading' && listed === 0 ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('bots.workbench.noProjects', { name: botName })}
+ </p>
+ ) : null}
+ </div>
+ {chosen && grant ? (
+ <div className="mt-4">
+ <p className="text-13 leading-5 text-[var(--text-secondary)]">{grant}</p>
+ <Button
+ variant="cta"
+ size="lg"
+ className="mt-3"
+ loading={busy}
+ disabled={busy}
+ onClick={() => void handOver(chosen.dir, chosen.name)}
+ >
+ {t('bots.workbench.handOver', { name: botName })}
+ </Button>
+ </div>
+ ) : null}
+ <Button
+ variant="secondary"
+ size="sm"
+ tone="quiet"
+ compact
+ className="-ml-3 mt-2.5"
+ disabled={busy}
+ onClick={() => void pickFolder()}
+ >
+ <FolderOpen size={14} aria-hidden />
+ {t('bots.workbench.pickFolder')}
+ </Button>
+ </section>
+ );
+}
+
+function projectCounts(option: WorkbenchProjectOption, t: Translate): string {
+ const external = option.claudeCount + option.codexCount > 0;
+ const parts: string[] = external
+ ? [
+ option.taskCount > 0 ? t('bots.workbench.sourceCindy', { count: option.taskCount }) : '',
+ option.claudeCount > 0 ? t('bots.workbench.sourceClaude', { count: option.claudeCount }) : '',
+ option.codexCount > 0 ? t('bots.workbench.sourceCodex', { count: option.codexCount }) : '',
+ ]
+ : [t('bots.workbench.projectTasks', { count: option.taskCount })];
+ if (option.automationCount > 0) parts.push(t('bots.workbench.projectAutomations', { count: option.automationCount }));
+ return parts.filter(Boolean).join(' · ');
+}
+
+function grantText(option: WorkbenchProjectOption, botName: string, language: string, t: Translate): string {
+ const claude = option.claudeCount;
+ const codex = option.codexCount;
+ const items = [
+ option.taskCount > 0
+ ? t(claude + codex > 0 ? 'bots.workbench.grantCindy' : 'bots.workbench.grantTasks', { count: option.taskCount })
+ : '',
+ claude > 0 ? t('bots.workbench.grantClaude', { count: claude }) : '',
+ codex > 0 ? t('bots.workbench.grantCodex', { count: codex }) : '',
+ option.automationCount > 0 ? t('bots.workbench.grantAutomations', { count: option.automationCount }) : '',
+ ].filter(Boolean);
+ const scope = items.length > 0 ? listFormat(items, language) : t('bots.workbench.grantEverything');
+ return t('bots.workbench.grant', { name: botName, project: option.name, scope });
+}
+
+// ─── 已接手:项目胶囊 + 汇总 ─────────────────────────────────────────
+
+const ICON_BUTTON_CLASS =
+ 'flex shrink-0 items-center justify-center rounded-full outline-none transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';
+
+function ProjectCapsules({
+ botId,
+ botName,
+ directories,
+ onAdd,
+}: {
+ botId: string;
+ botName: string;
+ directories: BotWorkbenchData['directories'];
+ onAdd?: () => void;
+}) {
+ const { t } = useTranslation();
+ const remove = useCallback(
+ (dirPath: string) => {
+ void window.electronAPI?.localDb?.bots?.workbench?.removeDirectory(botId, dirPath).catch(() => {});
+ },
+ [botId],
+ );
+ return (
+ <div className="flex flex-wrap items-center gap-2 px-5 pt-3">
+ {directories.map((dir) => (
+ <span
+ key={dir.path}
+ title={dir.exists ? dir.path : t('bots.workbench.dirMissing')}
+ className={cn(
+ 'inline-flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full bg-[var(--surface-chip)] pl-3 pr-1 text-13',
+ dir.exists ? 'text-[var(--text-primary)]' : 'text-[var(--text-danger)]',
+ )}
+ >
+ <Folder size={14} strokeWidth={1.8} aria-hidden className="shrink-0" />
+ <span className="min-w-0 truncate">{dir.name}</span>
+ <Tip text={t('bots.workbench.removeProject', { name: botName, project: dir.name })}>
+ <button
+ type="button"
+ onClick={() => remove(dir.path)}
+ aria-label={t('bots.workbench.removeProject', { name: botName, project: dir.name })}
+ className={cn(ICON_BUTTON_CLASS, 'size-6 text-[var(--text-tertiary)]')}
+ >
+ <X size={12} aria-hidden />
+ </button>
+ </Tip>
+ </span>
+ ))}
+ {onAdd ? (
+ <Tip text={t('bots.workbench.addProject', { name: botName })}>
+ <button
+ type="button"
+ onClick={onAdd}
+ aria-label={t('bots.workbench.addProject', { name: botName })}
+ className={cn(ICON_BUTTON_CLASS, 'size-8 border border-dashed border-[var(--text-tertiary)] text-[var(--text-tertiary)]')}
+ >
+ <Plus size={14} aria-hidden />
+ </button>
+ </Tip>
+ ) : null}
+ </div>
+ );
+}
+
+// ─── 任务列表:单列、按四组、每条两层 ─────────────────────────────────
+
+/** 「等你」组第二层写等的是什么;其它组不写状态词。 */
+function waitingText(tile: WorkbenchTile, t: Translate): string {
+ if (tile.state === 'waiting') return t('bots.workbench.line.waiting');
+ const kind = tile.line.kind;
+ if (kind === 'interrupted' || kind === 'errored' || kind === 'failed') return t(`bots.workbench.line.${kind}`);
+ return t('bots.workbench.line.errored');
+}
+
+/** 自动化的第二层:周期 + 下次运行(或已暂停 / 已停用)。 */
+function automationLine(tile: WorkbenchTile, t: Translate, language: string, now: number): string | null {
+ if (tile.type !== 'schedule' && tile.type !== 'routine') return null;
+ const cycle =
+ (tile.type === 'schedule' ? scheduleCycle(tile.schedule, t, language) : routineCycle(tile.triggers, t, language))
+ ?? t('bots.workbench.kind.automationPlain');
+ const line = tile.line;
+ const extra =
+ line.kind === 'next'
+ ? formatNextRun(line.at, now, t as Parameters<typeof formatNextRun>[2])
+ : line.kind === 'paused' || line.kind === 'disabled'
+ ? t(`bots.workbench.line.${line.kind}`)
+ : null;
+ return extra ? `${cycle} · ${extra}` : cycle;
+}
+
+/**
+ * 第二层只写「伙伴的意见」:伙伴写的下一步;没有时在做的写「在做 · 用时」,自动化写周期与下次运行,
+ * 排队的写「排队中」,做完的不写。来源与相对时间都不显示(在详情里)。
+ */
+function tileNote(tile: WorkbenchTile, group: WorkbenchGroupKey, t: Translate, language: string, now: number): string | null {
+ if ('next' in tile && tile.next) return tile.next;
+ const automation = automationLine(tile, t, language, now);
+ if (automation) return automation;
+ if (group === 'running') {
+ return tile.startedAtMs
+ ? `${t('bots.workbench.state.running')} · ${elapsed(tile.startedAtMs, now)}`
+ : t('bots.workbench.state.running');
+ }
+ if (tile.state === 'queued') return t('bots.workbench.line.queued');
+ return null;
+}
+
+type TilePr = { number: number; kind: PrStatusKind | null; url: string };
+
+/**
+ * 条目关联的 PR 与状态:
+ * - Cindy 任务:任务里出现过的 PR 引用(取最近一条),状态与刷新复用 PrRefsContext——条目可见时
+ * `registerPrConsumer`,跟侧栏 / 顶栏同一套周期与聚焦刷新,不另起轮询;
+ * - `pr:` 条目:可见时用同一个 `gitContext.getPrStatuses` 查一次(main 侧 60 秒缓存与去重);
+ * 拿不到(没有 gh 登录等)就只显示编号。
+ */
+function useTilePr(tile: WorkbenchTile, visible: boolean): TilePr | null {
+ const sessionId = tile.type === 'session' ? tile.id : '';
+ const { registerPrConsumer } = usePrActions();
+ const refs = usePrRefsForSession(sessionId);
+ const { statuses, successfulStatuses } = usePrStatuses(sessionId);
+ useEffect(() => {
+ if (!visible || !sessionId) return;
+ return registerPrConsumer(sessionId);
+ }, [visible, sessionId, registerPrConsumer]);
+
+ const github = tile.type === 'item' && tile.itemKind === 'pr' ? parseWorkbenchTaskId(tile.id) : null;
+ const itemRef = github?.kind === 'github' ? github : null;
+ const [itemKind, setItemKind] = useState<PrStatusKind | null>(null);
+ useEffect(() => {
+ if (!visible || !itemRef) return;
+ let alive = true;
+ void window.electronAPI?.gitContext
+ ?.getPrStatuses([{ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }])
+ .then((results) => {
+ const result = results?.[0];
+ if (alive && result?.ok) setItemKind(result.status);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ // itemRef 由 tile.id 决定。
+ }, [visible, tile.id]);
+
+ if (itemRef) {
+ return { number: itemRef.number, kind: itemKind, url: sessionPrUrl({ owner: itemRef.owner, repo: itemRef.repo, prNumber: itemRef.number }) };
+ }
+ if (refs.length === 0) return null;
+ const latest = refs.reduce((best, ref) => (ref.lastSeenAt > best.lastSeenAt ? ref : best));
+ const key = prStatusKey(latest);
+ const result = statuses.get(key);
+ const confirmed = result?.ok ? result : successfulStatuses.get(key);
+ return { number: latest.prNumber, kind: confirmed?.ok ? confirmed.status : null, url: sessionPrUrl(latest) };
+}
+
+/** 小的 PR 状态标:图标 + 「#5292 · 已合并」,颜色与侧栏 / 顶栏同一套 PR_STATUS_*。 */
+function PrTag({ pr }: { pr: TilePr }) {
+ const { t } = useTranslation();
+ const Icon = pr.kind ? PR_STATUS_ICON[pr.kind] : GitPullRequest;
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1 text-12 leading-5 text-[var(--text-tertiary)]">
+ <Icon size={12} aria-hidden style={{ color: pr.kind ? PR_STATUS_COLOR[pr.kind] : 'var(--text-tertiary)' }} />
+ <span className="tabular-nums">
+ #{pr.number}
+ {pr.kind ? ` · ${t(`ccAgent.gitContext.pr.status.${pr.kind}`)}` : ''}
+ </span>
+ </span>
+ );
+}
+
+function TaskRow({
+ tile,
+ group,
+ now,
+ language,
+ following,
+ onOpen,
+ onFollowUp,
+}: {
+ tile: WorkbenchTile;
+ group: WorkbenchGroupKey;
+ now: number;
+ language: string;
+ /** 这一条刚点了「跟进」,在等伙伴开始干活。 */
+ following: boolean;
+ onOpen: (tile: WorkbenchTile) => void;
+ onFollowUp?: (tile: WorkbenchTile) => void;
+}) {
+ const { t } = useTranslation();
+ const title = tile.title || t('bots.workbench.untitled');
+ const waiting = group === 'waiting' ? waitingText(tile, t) : null;
+ const note = tileNote(tile, group, t, language, now);
+ const second = waiting ? (note ? `${waiting} · ${note}` : waiting) : note;
+ const { ref: observe, visible } = useElementVisible();
+ const pr = useTilePr(tile, visible);
+ return (
+ <li
+ ref={observe}
+ className="group flex min-w-0 items-start rounded-xl bg-[var(--surface-elevated)] transition-colors hover:bg-[var(--surface-hover)]">
+ <button
+ type="button"
+ onClick={() => onOpen(tile)}
+ aria-label={t('bots.workbench.openTask', { title, state: t(`bots.workbench.group.${group}`) })}
+ className={cn(
+ 'flex min-w-0 flex-1 flex-col rounded-xl py-3 pl-3.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ onFollowUp ? 'pr-2' : 'pr-3.5',
+ )}
+ >
+ <span className="line-clamp-3 text-14 font-medium leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]">
+ {title}
+ </span>
+ {second || pr ? (
+ <span className="mt-1.5 flex min-w-0 items-start gap-1.5 text-13 leading-5 text-[var(--text-secondary)]">
+ {waiting ? (
+ <span aria-hidden className="mt-[7px] size-1.5 shrink-0 rounded-full bg-[var(--card-status-awaiting)]" />
+ ) : null}
+ {second ? <span className="line-clamp-2 min-w-0 flex-1 [overflow-wrap:anywhere]">{second}</span> : null}
+ {pr ? <PrTag pr={pr} /> : null}
+ </span>
+ ) : null}
+ </button>
+ {onFollowUp ? (
+ <button
+ type="button"
+ onClick={() => onFollowUp(tile)}
+ disabled={following}
+ aria-label={t('bots.workbench.followUp.aria', { title })}
+ className="mr-2.5 mt-2.5 flex h-7 shrink-0 items-center gap-1 rounded-[8px] px-2.5 text-12 font-medium leading-4 text-[var(--text-tertiary)] outline-none transition-colors hover:bg-[var(--surface-chip)] hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] group-hover:text-[var(--text-secondary)] disabled:cursor-default"
+ >
+ {following ? <Spinner size={12} aria-hidden /> : null}
+ {t('bots.workbench.followUp.label')}
+ </button>
+ ) : null}
+ </li>
+ );
+}
+
+function TaskGroups({
+ tiles,
+ now,
+ language,
+ showEmpty,
+ followingKey,
+ onOpen,
+ onFollowUp,
+}: {
+ tiles: readonly WorkbenchTile[];
+ now: number;
+ language: string;
+ showEmpty: boolean;
+ followingKey: string | null;
+ onOpen: (tile: WorkbenchTile) => void;
+ onFollowUp?: (tile: WorkbenchTile) => void;
+}) {
+ const { t } = useTranslation();
+ const groups = useMemo(() => groupWorkbenchTiles(tiles), [tiles]);
+ const [openDone, setOpenDone] = useState(false);
+ if (groups.length === 0) {
+ return showEmpty ? (
+ <p className="px-5 pb-5 pt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.tasksEmpty')}</p>
+ ) : null;
+ }
+ return (
+ <div className="flex flex-col gap-5 px-5 pb-5 pt-1">
+ {groups.map((group) => {
+ const open = !group.defaultCollapsed || openDone;
+ const label = t(`bots.workbench.group.${group.key}`);
+ const heading = (
+ <>
+ <span>{label}</span>
+ <span className="font-normal tabular-nums text-[var(--text-tertiary)]">{group.total}</span>
+ </>
+ );
+ const followUp = onFollowUp && workbenchGroupHasFollowUp(group.key) ? onFollowUp : undefined;
+ return (
+ <section key={group.key} aria-label={label}>
+ {group.defaultCollapsed ? (
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpenDone((value) => !value)}
+ className="-mx-1 flex h-6 items-center gap-1.5 rounded-[8px] px-1 text-13 font-medium leading-5 text-[var(--text-secondary)] outline-none transition-colors hover:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {heading}
+ <ChevronRight
+ size={14}
+ aria-hidden
+ className={cn('text-[var(--text-tertiary)] transition-transform', open && 'rotate-90')}
+ />
+ </button>
+ ) : (
+ <h3 className="flex h-6 items-center gap-1.5 text-13 font-medium leading-5 text-[var(--text-secondary)]">
+ {heading}
+ </h3>
+ )}
+ {open ? (
+ <ul className="mt-2 flex flex-col gap-2">
+ {group.tiles.map((tile) => (
+ <TaskRow
+ key={tile.key}
+ tile={tile}
+ group={group.key}
+ now={now}
+ language={language}
+ following={followingKey === tile.key}
+ onOpen={onOpen}
+ onFollowUp={followUp}
+ />
+ ))}
+ {group.hiddenCount > 0 ? (
+ <li className="px-3.5 pt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('bots.workbench.olderCount', { count: group.hiddenCount })}
+ </li>
+ ) : null}
+ </ul>
+ ) : null}
+ </section>
+ );
+ })}
+ </div>
+ );
+}
+
+function StateIcon({ state, verdict }: { state: WorkbenchTaskState; verdict?: 'unfinished' | 'idea' | null }) {
+ const { t } = useTranslation();
+ const live = state === 'running' || state === 'waiting' || state === 'queued';
+ if (!live && verdict) {
+ // 没做完沿用「停着」的图标;聊过没下文用小灯泡。
+ const VerdictIcon = verdict === 'idea' ? Lightbulb : CirclePause;
+ return (
+ <span role="img" aria-label={t(`bots.workbench.verdict.${verdict}`)} className="flex size-3 shrink-0 items-center justify-center">
+ <VerdictIcon size={13} strokeWidth={1.8} aria-hidden className="text-[var(--text-tertiary)]" />
+ </span>
+ );
+ }
+ const label = t(`bots.workbench.state.${state}`);
+ if (state === 'running') {
+ return (
+ <Spinner size={12} strokeWidth={2} role="img" aria-label={label} className="shrink-0 text-[var(--text-secondary)]" />
+ );
+ }
+ if (state === 'waiting' || state === 'queued') {
+ return (
+ <span role="img" aria-label={label} className="flex size-3 shrink-0 items-center justify-center">
+ <span
+ aria-hidden
+ className={
+ state === 'waiting'
+ ? 'size-2 rounded-full bg-[var(--card-status-awaiting)]'
+ : 'size-2.5 rounded-full border border-dashed border-[var(--text-tertiary)]'
+ }
+ />
+ </span>
+ );
+ }
+ const Icon = state === 'stopped' ? CirclePause : state === 'automation' ? Clock3 : CircleCheck;
+ return (
+ <span role="img" aria-label={label} className="flex size-3 shrink-0 items-center justify-center">
+ <Icon
+ size={13}
+ strokeWidth={1.8}
+ aria-hidden
+ className={state === 'done' ? 'text-[var(--card-status-done)]' : 'text-[var(--text-tertiary)]'}
+ />
+ </span>
+ );
+}
+
+function scheduleCycle(
+ schedule: { manual?: boolean; cronExpr?: string; intervalMs?: number },
+ t: Translate,
+ language: string,
+): string | null {
+ if (schedule.manual) return t('bots.workbench.cycle.manual');
+ if (schedule.intervalMs) return t('routines.everyMinutes', { count: Math.round(schedule.intervalMs / 60_000) });
+ if (schedule.cronExpr) {
+ return schedule.cronExpr === '0 * * * *' ? t('routines.hourly') : cronToHuman(schedule.cronExpr, t, language);
+ }
+ return null;
+}
+
+function routineCycle(triggers: WorkbenchRoutineInput['triggers'], t: Translate, language: string): string | null {
+ const first = triggers[0];
+ if (!first) return null;
+ if (first.kind === 'interval' && first.intervalMs) {
+ return t('routines.everyMinutes', { count: Math.round(first.intervalMs / 60_000) });
+ }
+ if (first.kind === 'cron' && first.expression) {
+ return first.expression === '0 * * * *' ? t('routines.hourly') : cronToHuman(first.expression, t, language);
+ }
+ if (first.kind === 'once') return t('bots.workbench.cycle.once');
+ if (first.kind === 'event') return t('bots.workbench.cycle.event');
+ return null;
+}
+
+function originLabel(origin: string, t: Translate): string {
+ const key =
+ origin === 'delegated'
+ ? 'delegated'
+ : origin === 'claude-code'
+ ? 'claudeCode'
+ : origin === 'codex' || origin === 'pi'
+ ? origin
+ : 'existing';
+ return t(`bots.workbench.kind.${key}`);
+}
+
+type ItemTile = Extract<WorkbenchTile, { type: 'item' }>;
+
+/** 「PR #5292」「Issue #5026」「建议」。 */
+function itemLabel(tile: ItemTile, t: Translate): string {
+ if (tile.itemKind === 'idea') return t('bots.workbench.kind.idea');
+ return t(`bots.workbench.kind.${tile.itemKind}`, { number: tile.number });
+}
+
+function ItemIcon({ tile }: { tile: ItemTile }) {
+ const Icon = tile.itemKind === 'pr' ? GitPullRequest : tile.itemKind === 'issue' ? CircleDot : Lightbulb;
+ return (
+ <span aria-hidden className="flex size-3 shrink-0 items-center justify-center">
+ <Icon size={13} strokeWidth={1.8} className="text-[var(--text-tertiary)]" />
+ </span>
+ );
+}
+
+// ─── 详情:在工作台标签内看一件任务 ───────────────────────────────────
+
+type DetailTile = Extract<WorkbenchTile, { type: 'session' | 'external' | 'item' }>;
+
+type TranscriptState =
+ | { kind: 'loading' }
+ | { kind: 'ready'; transcript: WorkbenchTranscript }
+ | { kind: 'failed' };
+
+/**
+ * 详情视图:不换路由、不跳任务页。伙伴的判断在上,最近内容(同一份有界只读摘录)在中,
+ * 底部「补一句」以主人身份发给伙伴,由伙伴决定怎么继续——不绕过伙伴直接投给任务。
+ */
+function TaskDetail({
+ botId,
+ botName,
+ botSessionId,
+ tile,
+ now,
+ canNavigate,
+ projectDirs,
+ caseInsensitive,
+ onBack,
+}: {
+ botId: string;
+ botName: string;
+ botSessionId: string;
+ tile: DetailTile;
+ now: number;
+ canNavigate: boolean;
+ projectDirs: readonly string[];
+ caseInsensitive: boolean;
+ onBack: () => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const navigate = useNavigate();
+ const [transcript, setTranscript] = useState<TranscriptState>({ kind: 'loading' });
+ const [draft, setDraft] = useState('');
+ const [sending, setSending] = useState(false);
+ const title = tile.title || t('bots.workbench.untitled');
+ const live = tile.state === 'running' || tile.state === 'waiting' || tile.state === 'queued';
+ const statusText = live || !tile.verdict ? t(`bots.workbench.state.${tile.state}`) : t(`bots.workbench.verdict.${tile.verdict}`);
+ // 运行中的任务内容在变:状态变化时重读一次,不轮询。
+ const reloadKey = `${tile.type}:${tile.id}:${tile.state}:${tile.lastActiveMs}`;
+
+ useEffect(() => {
+ // PR / issue / 建议没有对话记录,只显示判断与参考。
+ if (tile.type === 'item') return;
+ const api = window.electronAPI?.localDb?.bots?.workbench;
+ if (!api?.readTask) {
+ setTranscript({ kind: 'failed' });
+ return;
+ }
+ let alive = true;
+ const owner = getDataOwnerGeneration();
+ setTranscript((previous) => (previous.kind === 'ready' ? previous : { kind: 'loading' }));
+ void api
+ .readTask(botId, tile.id)
+ .then((result) => {
+ if (!alive || !isDataOwnerGenerationCurrent(owner)) return;
+ setTranscript(result.ok ? { kind: 'ready', transcript: result.transcript } : { kind: 'failed' });
+ })
+ .catch(() => {
+ if (alive) setTranscript({ kind: 'failed' });
+ });
+ return () => {
+ alive = false;
+ };
+ // reloadKey 已涵盖 tile.id 与 tile.type。
+ }, [botId, reloadKey]);
+
+ const send = useCallback(async () => {
+ const text = draft.trim();
+ if (!text || sending) return;
+ setSending(true);
+ try {
+ const sent = await sendAsOwner(botSessionId, t('bots.workbench.continueMessage', { title, text }));
+ if (sent) {
+ setDraft('');
+ toast.success(t('bots.workbench.detail.sent', { name: botName }));
+ } else {
+ toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ }
+ } catch {
+ toast.error(t('bots.workbench.sendFailed', { name: botName }));
+ } finally {
+ setSending(false);
+ }
+ }, [botName, botSessionId, draft, sending, t, title]);
+
+ const stop = useCallback(() => {
+ if (tile.type !== 'session') return;
+ void import('@/lib/makerChatStore').then((module) => module.makerChatStore.stopSession(tile.id));
+ }, [tile]);
+
+ // 参考只在点击时打开:https 交给系统浏览器,路径必须仍落在已接手的项目里。
+ // 详情打开期间同样登记为 PR 消费者(可见即刷新)。参考就是这个 PR 链接时不重复列。
+ const pr = useTilePr(tile, true);
+ const reference = tile.type === 'item' && tile.ref && tile.ref !== pr?.url ? tile.ref : null;
+ const openReference = useCallback(() => {
+ if (!reference) return;
+ if (/^https:\/\//i.test(reference)) {
+ void window.electronAPI.openExternal?.(reference);
+ return;
+ }
+ const checked = validateWorkbenchRef(reference, projectDirs, caseInsensitive);
+ if (checked.ok) void window.electronAPI.openPath?.(checked.ref);
+ else toast.error(t('bots.workbench.detail.refBlocked'));
+ }, [caseInsensitive, projectDirs, reference, t]);
+
+ const openInTasks = useCallback(() => {
+ if (tile.type !== 'session') return;
+ void resolveSessionRoute(tile.id).then((target) => navigate(target));
+ }, [navigate, tile]);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col bg-[var(--surface)]">
+ <div className="flex h-[52px] shrink-0 items-center gap-1 pl-2 pr-2.5">
+ <Tip text={t('bots.workbench.detail.back')}>
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label={t('bots.workbench.detail.back')}
+ className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
+ >
+ <ArrowLeft size={16} aria-hidden />
+ </button>
+ </Tip>
+ <h3 className="min-w-0 flex-1 truncate text-15 font-medium leading-[1.47] text-[var(--text-primary)]">{title}</h3>
+ {tile.type === 'session' && tile.state === 'running' ? (
+ <Tip text={t('bots.workbench.detail.stop')}>
+ <button
+ type="button"
+ onClick={stop}
+ aria-label={t('bots.workbench.detail.stop')}
+ className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
+ >
+ <Square size={12} fill="currentColor" aria-hidden />
+ </button>
+ </Tip>
+ ) : null}
+ {tile.type === 'session' && canNavigate ? (
+ <Tip text={t('bots.workbench.detail.openInTasks')}>
+ <button
+ type="button"
+ onClick={openInTasks}
+ aria-label={t('bots.workbench.detail.openInTasks')}
+ className={cn(ICON_BUTTON_CLASS, 'size-8 text-[var(--text-secondary)]')}
+ >
+ <SquareArrowOutUpRight size={14} aria-hidden />
+ </button>
+ </Tip>
+ ) : null}
+ </div>
+ <div className="flex shrink-0 items-center gap-2 px-5 pb-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {tile.type === 'item' ? <ItemIcon tile={tile} /> : <StateIcon state={tile.state} verdict={tile.verdict} />}
+ <span className="text-[var(--text-secondary)]">
+ {statusText}
+ {tile.state === 'running' && tile.startedAtMs ? ` ${elapsed(tile.startedAtMs, now)}` : ''}
+ </span>
+ <span aria-hidden>·</span>
+ <span className="min-w-0 truncate">{tile.type === 'item' ? itemLabel(tile, t) : originLabel(tile.origin, t)}</span>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-5 py-4">
+ {tile.verdict && tile.next ? (
+ <section className="mb-4 rounded-xl border border-[var(--border-default)] px-3.5 py-3">
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('bots.workbench.detail.judgment', { name: botName })}
+ </p>
+ <p className="mt-1 text-13 leading-5 text-[var(--text-primary)]">{tile.next}</p>
+ </section>
+ ) : null}
+ {pr ? (
+ <button
+ type="button"
+ onClick={() => void window.electronAPI.openExternal?.(pr.url)}
+ aria-label={t('bots.workbench.detail.openPr', { number: pr.number })}
+ className="mb-3 flex w-full min-w-0 items-center gap-2 rounded-xl border border-[var(--border-default)] px-3.5 py-2.5 text-left outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <span className="min-w-0 flex-1">
+ <PrTag pr={pr} />
+ </span>
+ <SquareArrowOutUpRight size={13} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ </button>
+ ) : null}
+ {tile.type === 'item' ? (
+ reference || pr ? (reference ? (
+ <button
+ type="button"
+ onClick={openReference}
+ className="flex w-full min-w-0 items-center gap-2 rounded-xl border border-[var(--border-default)] px-3.5 py-2.5 text-left outline-none transition-colors hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {/^https:\/\//i.test(reference) ? (
+ <Link2 size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ ) : (
+ <FileText size={14} aria-hidden className="shrink-0 text-[var(--text-tertiary)]" />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.ref')}</span>
+ <span className="block truncate text-13 leading-5 text-[var(--text-primary)]">{reference}</span>
+ </span>
+ </button>
+ ) : null) : (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.noRef')}</p>
+ )
+ ) : transcript.kind === 'loading' ? (
+ <div className="flex justify-center py-6">
+ <Spinner size={16} className="text-[var(--text-tertiary)]" role="status" aria-label={t('ccAgent.common.loading')} />
+ </div>
+ ) : transcript.kind === 'failed' ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.loadFailed')}</p>
+ ) : transcript.transcript.items.length === 0 ? (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.workbench.detail.empty')}</p>
+ ) : (
+ <div className="flex flex-col gap-3">
+ {transcript.transcript.truncated ? (
+ <p className="text-center text-11 text-[var(--text-tertiary)]">{t('bots.workbench.detail.truncated')}</p>
+ ) : null}
+ {transcript.transcript.items.map((item, index) =>
+ item.role === 'user' ? (
+ <div
+ key={`${item.at}-${index}`}
+ className="max-w-[90%] self-end whitespace-pre-wrap break-words rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3.5 py-2.5 text-13 leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]"
+ >
+ {item.text}
+ </div>
+ ) : (
+ <div
+ key={`${item.at}-${index}`}
+ className="whitespace-pre-wrap break-words text-13 leading-[1.69] text-[var(--text-primary)] [overflow-wrap:anywhere]"
+ >
+ {item.text}
+ </div>
+ ),
+ )}
+ <p className="text-11 text-[var(--text-tertiary)]">
+ {relativeTime(transcript.transcript.items.at(-1)?.at ?? 0, i18n.language, now)}
+ </p>
+ </div>
+ )}
+ </div>
+ <form
+ className="flex shrink-0 items-center gap-2 px-3 pb-3 pt-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void send();
+ }}
+ >
+ <Input
+ value={draft}
+ onChange={setDraft}
+ size="md"
+ className="min-w-0 flex-1"
+ placeholder={t('bots.workbench.detail.placeholder', { name: botName })}
+ ariaLabel={t('bots.workbench.detail.placeholder', { name: botName })}
+ disabled={sending}
+ onKeyDown={(event) => {
+ // 输入法组字时回车只确认候选,不发送。
+ if (event.key === 'Enter' && (event.nativeEvent.isComposing || event.keyCode === 229)) event.preventDefault();
+ }}
+ />
+ <Tip text={t('bots.workbench.detail.send')}>
+ <button
+ type="submit"
+ disabled={sending || !draft.trim()}
+ aria-label={t('bots.workbench.detail.send')}
+ className={cn(
+ ICON_BUTTON_CLASS,
+ 'size-8 border border-[var(--border-default)] text-[var(--text-secondary)] disabled:opacity-50',
+ )}
+ >
+ {sending ? <Spinner size={12} aria-hidden /> : <ArrowUp size={14} aria-hidden />}
+ </button>
+ </Tip>
+ </form>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
index a8bb1dcc5c..b1b0b6453a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
@@ -9,6 +9,8 @@ const h = vi.hoisted(() => ({
profiles: [] as Array<{ id: string; name: string; avatar: string; avatarColor: string }>,
profileListeners: new Set<() => void>(),
}));
+// 工作台在右侧栏里有自己的数据订阅,这里只验证伙伴对话的挂载与读位。
+vi.mock('@/features/right-sidebar/lib/openBotWorkbenchTab', () => ({ ensureBotWorkbenchTab: vi.fn(async () => {}) }));
vi.mock('../botStore', async () => {
const { useSyncExternalStore } = await import('react');
return {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
index 792c2400db..27638eda71 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
@@ -3,6 +3,8 @@
import { act, cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+// 工作台在右侧栏里有自己的数据订阅,这里只验证伙伴对话的挂载与读位。
+vi.mock('@/features/right-sidebar/lib/openBotWorkbenchTab', () => ({ ensureBotWorkbenchTab: vi.fn(async () => {}) }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
new file mode 100644
index 0000000000..8b5f54096e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
@@ -0,0 +1,572 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Session } from '@/lib/ccAgent.types';
+import {
+ buildWorkbenchProjectOptions,
+ buildWorkbenchTiles,
+ collectBotHiddenSessionIds,
+ isNonProjectDir,
+ looksGeneratedDirName,
+ countUnjudgedCandidates,
+ groupWorkbenchTiles,
+ tierWorkbenchProjectOptions,
+ workbenchGroupHasFollowUp,
+ workbenchTileGroup,
+ type WorkbenchProjectOption,
+ type WorkbenchDelegationInput,
+} from '../botWorkbenchProjection';
+
+const ART = '/Users/me/Code/tapmon-art';
+const CINDY = '/Users/me/Code/cindy';
+
+function session(id: string, patch: Partial<Session> = {}): Session {
+ return {
+ id,
+ userId: 'u',
+ title: id,
+ workingDir: ART,
+ workspaceKind: 'project',
+ model: 'm',
+ effort: 'high',
+ permissionMode: 'ask',
+ sdkSessionId: null,
+ totalTokenUsage: 0,
+ totalCostUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ fastMode: false,
+ clearedAt: null,
+ pinnedAt: null,
+ userSendAt: '2026-10-01T01:00:00.000Z',
+ status: 'active',
+ agentKind: 'cc',
+ source: 'desktop',
+ extraDirs: [],
+ createdAt: '2026-09-30T00:00:00.000Z',
+ updatedAt: '2026-10-01T01:00:00.000Z',
+ ...patch,
+ } as Session;
+}
+
+function delegation(childSessionId: string, status: WorkbenchDelegationInput['status']): WorkbenchDelegationInput {
+ return {
+ childSessionId,
+ status,
+ resultSummary: null,
+ lastError: null,
+ createdAt: 1,
+ acceptedAt: status === 'running' ? 1_000 : null,
+ completedAt: null,
+ updatedAt: 2,
+ };
+}
+
+const base = {
+ hiddenIds: new Set<string>(),
+ projectDirs: [ART],
+ caseInsensitive: false,
+ delegations: [] as WorkbenchDelegationInput[],
+ activity: new Map(),
+ erroredIds: new Set<string>(),
+ schedules: [],
+ routines: [],
+ now: Date.parse('2026-10-02T00:00:00.000Z'),
+};
+
+describe('buildWorkbenchTiles', () => {
+ it('derives each tile state from host signals only', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ sessions: [
+ session('running'),
+ session('asking'),
+ session('bg-queued', { userSendAt: null }),
+ ],
+ delegations: [delegation('bg-queued', 'queued')],
+ activity: new Map([
+ ['running', { phase: 'running', startedAtMs: 500, currentActionSummary: '导出 xhdpi 尺寸' }],
+ ['asking', { phase: 'needs-interaction' }],
+ ]),
+ });
+ const byId = new Map(tiles.map((tile) => [tile.id, tile]));
+ expect(byId.get('running')).toMatchObject({
+ state: 'running',
+ startedAtMs: 500,
+ line: { kind: 'action', text: '导出 xhdpi 尺寸' },
+ });
+ expect(byId.get('asking')).toMatchObject({ state: 'waiting', line: { kind: 'waiting' } });
+ expect(byId.get('bg-queued')).toMatchObject({ state: 'queued', origin: 'delegated' });
+ });
+
+ it('lists every recent Cindy task, but external sessions only when judged worth continuing', () => {
+ const judgment = (verdict: 'unfinished' | 'idea' | 'done', title: string, project = ART) => ({
+ title,
+ verdict,
+ next: verdict === 'done' ? null : `${title}的下一步`,
+ project,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ });
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ sessions: [
+ session('running', { title: '<system-reminder>x</system-reminder>导出图标' }),
+ session('unjudged-idle', { preview: '12 条意见' }),
+ session('unjudged-errored'),
+ session('judged-unfinished', { title: '原始标题' }),
+ session('judged-done'),
+ session('claude-imported', { agentKind: 'cc' }),
+ ],
+ activity: new Map([['running', { phase: 'running' }]]),
+ erroredIds: new Set(['unjudged-errored']),
+ judgments: {
+ 'judged-unfinished': judgment('unfinished', '补描边'),
+ 'judged-done': judgment('done', '整理意见'),
+ 'claude-imported': judgment('idea', '换图标风格'),
+ 'claude:ext-1': judgment('unfinished', '压缩原画'),
+ 'codex:ext-2': judgment('idea', '加自动导出'),
+ 'codex:ext-done': judgment('done', '问答'),
+ 'codex:ext-elsewhere': judgment('unfinished', '别的项目', CINDY),
+ },
+ candidates: [{ source: 'claude', id: 'ext-1', projectDir: ART, updatedAt: '2026-10-01T05:00:00.000Z', archived: false }],
+ });
+ const byId = new Map(tiles.map((tile) => [tile.id, tile]));
+ // Cindy 任务(含主人自己开的空闲任务、判为 done 的)都在;外部会话只留判为值得继续的。
+ expect([...byId.keys()].sort()).toEqual(
+ [
+ 'claude-imported',
+ 'claude:ext-1',
+ 'codex:ext-2',
+ 'judged-done',
+ 'judged-unfinished',
+ 'running',
+ 'unjudged-errored',
+ 'unjudged-idle',
+ ].sort(),
+ );
+ expect(byId.has('codex:ext-done')).toBe(false);
+ expect(byId.has('codex:ext-elsewhere')).toBe(false);
+ expect(byId.get('running')).toMatchObject({ title: '导出图标', verdict: null });
+ expect(byId.get('judged-unfinished')).toMatchObject({ title: '补描边', verdict: 'unfinished', next: '补描边的下一步' });
+ expect(byId.get('claude-imported')).toMatchObject({ verdict: 'idea', origin: 'claude-code' });
+ expect(byId.get('claude:ext-1')).toMatchObject({
+ type: 'external',
+ origin: 'claude-code',
+ verdict: 'unfinished',
+ lastActiveMs: Date.parse('2026-10-01T05:00:00.000Z'),
+ });
+ expect(byId.get('codex:ext-2')).toMatchObject({ type: 'external', origin: 'codex', verdict: 'idea' });
+ // Live first, then unfinished, then ideas, then the rest.
+ expect(tiles.slice(0, 5).map((tile) => ('verdict' in tile ? tile.verdict : null))).toEqual([
+ null,
+ 'unfinished',
+ 'unfinished',
+ 'idea',
+ 'idea',
+ ]);
+ expect(groupWorkbenchTiles(tiles).map((group) => [group.key, group.tiles.map((tile) => tile.id).sort()])).toEqual([
+ ['waiting', ['unjudged-errored']],
+ ['running', ['running']],
+ ['todo', ['claude-imported', 'claude:ext-1', 'codex:ext-2', 'judged-unfinished'].sort()],
+ ['done', ['judged-done', 'unjudged-idle']],
+ ]);
+ });
+
+ it('shows Pi sessions and PR / issue / idea entries the Bot wrote down, labelled by kind', () => {
+ const judgment = (verdict: 'unfinished' | 'idea' | 'done', title: string, extra: Record<string, unknown> = {}) => ({
+ title,
+ verdict,
+ next: verdict === 'done' ? null : `${title}的下一步`,
+ project: ART,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ ...extra,
+ });
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ sessions: [],
+ judgments: {
+ 'pi:p1': judgment('unfinished', '写文档'),
+ 'pr:me/art#12': judgment('unfinished', '图标 PR', { ref: 'https://github.com/me/art/pull/12' }),
+ 'issue:me/art#7': judgment('idea', '暗色图标'),
+ 'idea:dark-icons': judgment('idea', '补一套暗色', { ref: `${ART}/DESIGN.md` }),
+ 'idea:done-one': judgment('done', '已做完'),
+ 'idea:elsewhere': judgment('idea', '别的项目', { project: CINDY }),
+ },
+ });
+ const byId = new Map(tiles.map((tile) => [tile.id, tile]));
+ expect([...byId.keys()].sort()).toEqual(['idea:dark-icons', 'issue:me/art#7', 'pi:p1', 'pr:me/art#12']);
+ expect(byId.get('pi:p1')).toMatchObject({ type: 'external', origin: 'pi', verdict: 'unfinished' });
+ expect(byId.get('pr:me/art#12')).toMatchObject({
+ type: 'item',
+ itemKind: 'pr',
+ number: 12,
+ ref: 'https://github.com/me/art/pull/12',
+ project: ART,
+ });
+ expect(byId.get('issue:me/art#7')).toMatchObject({ type: 'item', itemKind: 'issue', number: 7, ref: null });
+ expect(byId.get('idea:dark-icons')).toMatchObject({ type: 'item', itemKind: 'idea', number: null, ref: `${ART}/DESIGN.md` });
+ });
+
+ it('shows a task the owner just opened in the project, and drops ones idle for over 30 days', () => {
+ const now = Date.parse('2026-10-02T00:00:00.000Z');
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ now,
+ sessions: [
+ session('just-opened', { userSendAt: '2026-10-01T23:59:00.000Z', updatedAt: '2026-10-01T23:59:00.000Z' }),
+ session('stale', { userSendAt: '2026-08-20T00:00:00.000Z', updatedAt: '2026-08-20T00:00:00.000Z' }),
+ session('stale-bg', { userSendAt: '2026-08-20T00:00:00.000Z', updatedAt: '2026-08-20T00:00:00.000Z' }),
+ ],
+ delegations: [{ ...delegation('stale-bg', 'completed'), updatedAt: 1 }],
+ candidates: [{ source: 'codex', id: 'unjudged', projectDir: ART, updatedAt: '2026-10-01T00:00:00.000Z', archived: false }],
+ });
+ expect(tiles.map((tile) => tile.id).sort()).toEqual(['just-opened', 'stale-bg']);
+ expect(workbenchTileGroup(tiles.find((tile) => tile.id === 'just-opened')!)).toBe('done');
+ });
+
+ it('keeps Bot hidden sessions, other projects, drafts, remote, archived and non-task sources out', () => {
+ const live = (id: string) => [id, { phase: 'running' }] as const;
+ const ids = ['kept', 'bot-main', 'bot-source', 'elsewhere', 'draft', 'remote', 'device', 'archived', 'automation-run', 'worker'];
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ hiddenIds: new Set(['bot-main']),
+ activity: new Map(ids.map(live)),
+ sessions: [
+ session('kept'),
+ session('bot-main'),
+ session('bot-source', { source: 'bot' }),
+ session('elsewhere', { workingDir: CINDY }),
+ session('draft', { userSendAt: null, _count: { messages: 0 } }),
+ session('remote', { remoteHostId: 'ssh-1' }),
+ session('device', { deviceLinkDeviceId: 'mac-2' }),
+ session('archived', { status: 'archived' }),
+ session('automation-run', { source: 'scheduler' }),
+ session('worker', { orcaRole: 'worker' }),
+ ],
+ });
+ expect(tiles.map((tile) => tile.id)).toEqual(['kept']);
+ });
+
+ it('counts only external candidates the Bot has not judged yet, never Cindy tasks', () => {
+ expect(
+ countUnjudgedCandidates({
+ projectDirs: [ART],
+ caseInsensitive: false,
+ candidates: [
+ { source: 'claude', id: 'x', projectDir: ART, updatedAt: '2026-10-01T00:00:00.000Z', archived: false },
+ { source: 'codex', id: 'y', projectDir: ART, updatedAt: '2026-10-01T00:00:00.000Z', archived: false },
+ { source: 'codex', id: 'z', projectDir: ART, updatedAt: '2026-10-01T00:00:00.000Z', archived: true },
+ ],
+ judgments: {
+ a: { title: 'a', verdict: 'done', next: null, project: ART, updatedAt: 'x' },
+ 'claude:x': { title: 'x', verdict: 'idea', next: 'n', project: ART, updatedAt: 'x' },
+ },
+ }),
+ ).toBe(1);
+ });
+
+ it('includes project automations and the Bot own routines, disabled ones as stopped', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ sessions: [],
+ schedules: [
+ { id: 's-1', name: '检查 PR', status: 'active', workspaceKind: 'project', workingDir: ART, cronExpr: '0 * * * *', nextFireAt: 99 },
+ { id: 's-2', name: '暂停的', status: 'paused', workspaceKind: 'project', workingDir: ART },
+ { id: 's-3', name: '别的项目', status: 'active', workspaceKind: 'project', workingDir: CINDY },
+ { id: 's-4', name: '伙伴内部', status: 'active', source: 'bot', workspaceKind: 'project', workingDir: ART },
+ ],
+ routines: [
+ { id: 'r-1', name: '巡检', enabled: true, triggers: [], updatedAt: 1, lastRun: { status: 'success', createdAt: 1, resultText: '没有异常' } },
+ { id: 'r-2', name: '导入的提醒', enabled: false, triggers: [], updatedAt: 1 },
+ { id: 'r-3', name: '正在跑', enabled: true, activity: 'running', triggers: [], updatedAt: 1 },
+ ],
+ });
+ const byId = new Map(tiles.map((tile) => [tile.id, tile]));
+ expect(byId.get('s-1')).toMatchObject({ type: 'schedule', state: 'automation', line: { kind: 'next', at: 99 } });
+ expect(byId.get('s-2')).toMatchObject({ state: 'stopped', line: { kind: 'paused' } });
+ expect(byId.has('s-3')).toBe(false);
+ expect(byId.has('s-4')).toBe(false);
+ expect(byId.get('r-1')).toMatchObject({ type: 'routine', state: 'automation', line: { kind: 'last-run', ok: true, text: '没有异常' } });
+ expect(byId.get('r-2')).toMatchObject({ state: 'stopped', line: { kind: 'disabled' } });
+ expect(byId.get('r-3')).toMatchObject({ state: 'running' });
+ });
+
+ it('shows nothing from projects when none was handed over, but still lists routines', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ projectDirs: [],
+ sessions: [session('kept')],
+ routines: [{ id: 'r-1', name: '每日提醒', enabled: true, triggers: [], updatedAt: 1 }],
+ });
+ expect(tiles.map((tile) => tile.id)).toEqual(['r-1']);
+ });
+});
+
+describe('groupWorkbenchTiles', () => {
+ const judgment = (verdict: 'unfinished' | 'idea', title: string) => ({
+ title,
+ verdict,
+ next: `${title}的下一步`,
+ project: ART,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ });
+
+ function fixture() {
+ return buildWorkbenchTiles({
+ ...base,
+ sessions: [
+ session('waiting'),
+ session('errored'),
+ session('running'),
+ session('queued-bg'),
+ session('judged', { updatedAt: '2026-10-01T03:00:00.000Z' }),
+ session('finished-bg', { updatedAt: '2026-10-01T02:00:00.000Z' }),
+ session('failed-bg'),
+ ],
+ activity: new Map([
+ ['waiting', { phase: 'needs-interaction' }],
+ ['running', { phase: 'running', startedAtMs: 5 }],
+ ]),
+ erroredIds: new Set(['errored']),
+ delegations: [
+ delegation('queued-bg', 'queued'),
+ delegation('finished-bg', 'completed'),
+ delegation('failed-bg', 'failed'),
+ ],
+ judgments: {
+ judged: judgment('unfinished', '补描边'),
+ // 出错停下的任务即使伙伴判为没做完,也先放「等你」。
+ errored: judgment('unfinished', '导出报错'),
+ 'idea:dark-icons': judgment('idea', '暗色图标'),
+ 'pr:me/art#12': judgment('unfinished', '图标 PR'),
+ },
+ schedules: [
+ { id: 's-idle', name: '检查 PR', status: 'active', workspaceKind: 'project', workingDir: ART, nextFireAt: 99 },
+ { id: 's-off', name: '暂停的', status: 'paused', workspaceKind: 'project', workingDir: ART },
+ ],
+ routines: [{ id: 'r-run', name: '每日整理', enabled: true, activity: 'running', triggers: [], updatedAt: 1 }],
+ });
+ }
+
+ it('sorts every tile into waiting / running / to do / done', () => {
+ const groupOf = new Map(fixture().map((tile) => [tile.id, workbenchTileGroup(tile)]));
+ expect(Object.fromEntries(groupOf)).toEqual({
+ waiting: 'waiting',
+ errored: 'waiting',
+ 'failed-bg': 'waiting',
+ running: 'running',
+ 'r-run': 'running',
+ 'queued-bg': 'todo',
+ judged: 'todo',
+ 'idea:dark-icons': 'todo',
+ 'pr:me/art#12': 'todo',
+ 'finished-bg': 'done',
+ 's-idle': 'done',
+ 's-off': 'done',
+ });
+ });
+
+ it('keeps the fixed group order, collapses only done and reports its count', () => {
+ const groups = groupWorkbenchTiles(fixture());
+ expect(groups.map((group) => [group.key, group.defaultCollapsed])).toEqual([
+ ['waiting', false],
+ ['running', false],
+ ['todo', false],
+ ['done', true],
+ ]);
+ expect(groups.find((group) => group.key === 'done')!.tiles).toHaveLength(3);
+ });
+
+ it('lists at most 30 done entries and reports the older ones as a count', () => {
+ const now = Date.parse('2026-10-02T00:00:00.000Z');
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ now,
+ sessions: Array.from({ length: 33 }, (_, index) =>
+ session(`t-${index}`, {
+ updatedAt: new Date(now - (index + 1) * 60_000).toISOString(),
+ userSendAt: new Date(now - (index + 1) * 60_000).toISOString(),
+ }),
+ ),
+ });
+ const done = groupWorkbenchTiles(tiles).find((group) => group.key === 'done')!;
+ expect(done).toMatchObject({ total: 33, hiddenCount: 3, defaultCollapsed: true });
+ expect(done.tiles).toHaveLength(30);
+ expect(done.tiles[0]!.id).toBe('t-0');
+ });
+
+ it('offers 跟进 only on to-do and waiting entries', () => {
+ const withFollowUp = groupWorkbenchTiles(fixture())
+ .filter((group) => workbenchGroupHasFollowUp(group.key))
+ .map((group) => group.key);
+ expect(withFollowUp).toEqual(['waiting', 'todo']);
+ expect(workbenchGroupHasFollowUp('running')).toBe(false);
+ expect(workbenchGroupHasFollowUp('done')).toBe(false);
+ });
+
+ it('keeps the Bot own background tasks in the groups by their real state', () => {
+ const groupOf = new Map(fixture().map((tile) => [tile.id, workbenchTileGroup(tile)]));
+ expect([groupOf.get('queued-bg'), groupOf.get('failed-bg'), groupOf.get('finished-bg')]).toEqual(['todo', 'waiting', 'done']);
+ });
+
+ it('leaves empty groups out', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ sessions: [],
+ judgments: { 'idea:dark-icons': judgment('idea', '暗色图标') },
+ });
+ expect(groupWorkbenchTiles(tiles).map((group) => group.key)).toEqual(['todo']);
+ expect(groupWorkbenchTiles([])).toEqual([]);
+ });
+});
+
+describe('buildWorkbenchProjectOptions', () => {
+ it('merges local projects with Claude Code / Codex candidates and counts automations', () => {
+ const options = buildWorkbenchProjectOptions({
+ sessions: [
+ session('a1', { userSendAt: '2026-10-01T05:00:00.000Z' }),
+ session('a2'),
+ session('c1', { workingDir: CINDY, userSendAt: '2026-09-01T00:00:00.000Z' }),
+ session('hidden', { workingDir: '/Users/me/Code/secret' }),
+ session('dialogue', { workingDir: '/tmp/dialogue', workspaceKind: 'dialogue' }),
+ ],
+ hiddenIds: new Set(['hidden']),
+ schedules: [{ id: 's-1', name: 'PR', status: 'active', workspaceKind: 'project', workingDir: ART }],
+ candidates: [
+ { source: 'claude', id: 'x1', projectDir: ART, updatedAt: '2026-09-30T00:00:00.000Z', archived: false },
+ { source: 'codex', id: 'x2', projectDir: '/Users/me/Code/only-codex', updatedAt: '2026-10-01T09:00:00.000Z', archived: false },
+ { source: 'claude', id: 'x3', projectDir: CINDY, updatedAt: '2026-09-30T00:00:00.000Z', archived: true },
+ ],
+ localPlatform: 'darwin',
+ caseInsensitive: false,
+ });
+ expect(options.map((option) => [option.name, option.taskCount, option.automationCount, option.claudeCount, option.codexCount]))
+ .toEqual([
+ ['only-codex', 0, 0, 0, 1],
+ ['tapmon-art', 2, 1, 1, 0],
+ ['cindy', 1, 0, 0, 0],
+ ]);
+ });
+
+ it('leaves out projects already handed over', () => {
+ const options = buildWorkbenchProjectOptions({
+ sessions: [session('a1'), session('c1', { workingDir: CINDY })],
+ hiddenIds: new Set(),
+ schedules: [],
+ candidates: [],
+ localPlatform: 'darwin',
+ caseInsensitive: false,
+ excludeDirs: [ART],
+ });
+ expect(options.map((option) => option.name)).toEqual(['cindy']);
+ });
+});
+
+describe('hidden sessions', () => {
+ it('collects every Bot-linked session from the profile projection', () => {
+ expect(collectBotHiddenSessionIds([{ sessions: [{ id: 'a' }, { id: 'b' }] }, { sessions: [{ id: 'c' }] }]))
+ .toEqual(new Set(['a', 'b', 'c']));
+ });
+});
+
+describe('project picker filtering and tiers', () => {
+ const NOW = Date.UTC(2026, 9, 1);
+ const DAY = 24 * 60 * 60 * 1000;
+ const hints = {
+ homeDir: '/Users/me',
+ userDataDir: '/Users/me/Library/Application Support/Cindy Dev',
+ tempDirs: ['/var/folders/ab/T'],
+ };
+ const option = (dir: string, patch: Partial<WorkbenchProjectOption> = {}): WorkbenchProjectOption => ({
+ dir,
+ name: dir.split('/').pop() ?? dir,
+ taskCount: 0,
+ automationCount: 0,
+ claudeCount: 0,
+ codexCount: 0,
+ latestActivityMs: NOW - DAY,
+ isGitRepo: false,
+ ...patch,
+ });
+
+ it('drops the home folder, Cindy data, Bot workspaces and temp / tool caches', () => {
+ for (const dir of [
+ '/Users/me',
+ '/Users/me/Library/Application Support/Cindy Dev/owner/bots/b1/workspace',
+ '/tmp/scratch',
+ '/private/tmp/x',
+ '/var/folders/ab/T/cli_aae4',
+ '/Users/me/Library/Caches/foo',
+ '/Users/me/.cache/x',
+ '/Users/me/.codex/sessions',
+ '/Users/me/.claude/projects/x',
+ '/Users/me/.cindy',
+ '/Users/me/.cursor/worktrees/a',
+ ]) {
+ expect(isNonProjectDir(dir, hints, false), dir).toBe(true);
+ }
+ expect(isNonProjectDir('/Users/me/Code/cindy', hints, false)).toBe(false);
+ // Without host hints the common home shapes are still recognized.
+ expect(isNonProjectDir('/Users/someone', null, false)).toBe(true);
+ expect(isNonProjectDir('/Users/someone/.codex/x', null, false)).toBe(true);
+ expect(isNonProjectDir('C:/Users/me', null, true)).toBe(true);
+ });
+
+ it('recognizes generated directory names but not ordinary ones', () => {
+ for (const name of [
+ '6a7a8ec7-7e91-440b-9c1d-2f3e4a5b6c7d',
+ '1a34b5b6-0000-4000-8000-000000000000',
+ 'cli_aae4722842785d27',
+ 'telegram-8678037594',
+ 'a1b2c3d4e5f60718',
+ ]) {
+ expect(looksGeneratedDirName(name), name).toBe(true);
+ }
+ for (const name of ['cindy', 'filoai-frontend', 'photos-gps', '3-codex', 'sprint-12', 'tapmon-art']) {
+ expect(looksGeneratedDirName(name), name).toBe(false);
+ }
+ });
+
+ it('puts git repos, Cindy projects and busy folders first, folds the rest', () => {
+ const { primary, folded } = tierWorkbenchProjectOptions(
+ [
+ option('/Users/me/Code/cindy', { isGitRepo: true, latestActivityMs: NOW - 1 }),
+ option('/Users/me/Code/filoai-frontend', { codexCount: 3, latestActivityMs: NOW - 2 }),
+ option('/Users/me/Code/notes', { taskCount: 1 }),
+ option('/Users/me', { taskCount: 9 }),
+ option('/Users/me/Library/Application Support/Cindy Dev/o/bots/b/workspace', { taskCount: 4 }),
+ option('/Users/me/tmp/6a7a8ec7-7e91-440b-9c1d-2f3e4a5b6c7d', { taskCount: 5, isGitRepo: true }),
+ option('/Users/me/Code/photos-gps', { claudeCount: 1, latestActivityMs: NOW - 30 * DAY }),
+ option('/Users/me/Code/3-codex', { codexCount: 1 }),
+ ],
+ { hints, caseInsensitive: false, now: NOW },
+ );
+ expect(primary.map((item) => item.name)).toEqual(['cindy', 'filoai-frontend', 'notes']);
+ expect(folded.map((item) => item.name)).toEqual([
+ '3-codex',
+ '6a7a8ec7-7e91-440b-9c1d-2f3e4a5b6c7d',
+ 'photos-gps',
+ ]);
+ });
+
+ it('shows at most five first-tier rows and folds the overflow by recency', () => {
+ const options = Array.from({ length: 7 }, (_, index) =>
+ option(`/Users/me/Code/p${index}`, { isGitRepo: true, latestActivityMs: NOW - index * DAY }),
+ );
+ const { primary, folded } = tierWorkbenchProjectOptions(options, { hints, caseInsensitive: false, now: NOW });
+ expect(primary.map((item) => item.name)).toEqual(['p0', 'p1', 'p2', 'p3', 'p4']);
+ expect(folded.map((item) => item.name)).toEqual(['p5', 'p6']);
+ });
+
+ it('marks git repositories reported by the host scan', () => {
+ const [cindy] = buildWorkbenchProjectOptions({
+ sessions: [session('c1', { workingDir: CINDY })],
+ hiddenIds: new Set(),
+ schedules: [],
+ candidates: [],
+ gitRepoDirs: [CINDY],
+ localPlatform: 'darwin',
+ caseInsensitive: false,
+ });
+ expect(cindy).toMatchObject({ name: 'cindy', isGitRepo: true });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/botDelegationLive.ts b/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
index 35e4337c94..41faad564a 100644
--- a/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
+++ b/apps/desktop/src/renderer/features/bots/botDelegationLive.ts
@@ -172,6 +172,21 @@ export function useBotDelegation(
return live;
}
+/** 本会话发起的全部委派(伙伴工作台的进度卡用),与协作卡共用同一份订阅。 */
+export function useBotDelegations(sessionId: string | null): readonly BotDelegationView[] {
+ const [rows, setRows] = useState<readonly BotDelegationView[]>([]);
+ useEffect(() => {
+ if (!sessionId) {
+ setRows([]);
+ return;
+ }
+ const read = () => setRows(sessions.get(sessionId)?.rows ?? []);
+ read();
+ return subscribe(sessionId, read);
+ }, [sessionId]);
+ return rows;
+}
+
/** 测试用:清掉进程内缓存,避免用例之间互相看到对方的订阅。 */
export function __resetBotDelegationLiveForTest(): void {
for (const entry of sessions.values()) entry.unsubscribe?.();
diff --git a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
new file mode 100644
index 0000000000..4259af3436
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
@@ -0,0 +1,730 @@
+/**
+ * 伙伴工作台的渲染层投影(纯函数)。
+ *
+ * 输入全是渲染层已经有的数据:任务列表缓存、伙伴档案(用来排除伙伴自己的隐藏任务)、
+ * 伙伴的后台任务、灵动岛同源的活动快照、侧栏同源的待关注标记、自动化与例行任务。
+ * 输出两样东西:
+ * - 空状态的项目清单:复用任务列表的项目分组(`groupSessions`),合并本机 Claude Code /
+ * Codex 的可导入候选与项目里的自动化;
+ * - 已接手项目的任务列表:项目里最近 30 天的 Cindy 任务一律列出(含主人自己开的,不管伙伴判断过没有);
+ * 本机外部会话与伙伴从项目素材里写下的 PR / issue / 建议只在伙伴判为「没做完 / 聊过没下文」时列出;
+ * 另有伙伴自己开的后台任务与自动化;状态用 `shared/botWorkbench.ts` 与主进程同一套规则推导,
+ * 再由 `groupWorkbenchTiles` 分成 等你 / 在做 / 待做 / 做完 四组。
+ */
+import { hasPendingSessionInterruption } from '@cindy/maker-shared/session-activity';
+
+import type { Session } from '@/lib/ccAgent.types';
+import { groupSessions } from '@/features/cc-agent/lib/projectGrouping';
+import {
+ boundWorkbenchSummary,
+ cleanWorkbenchTitle,
+ deriveWorkbenchAutomationState,
+ deriveWorkbenchSessionState,
+ findWorkbenchProject,
+ importedSessionOrigin,
+ WORKBENCH_RECENT_WINDOW_MS,
+ externalWorkbenchTaskId,
+ isWorkbenchTaskSource,
+ parseWorkbenchTaskId,
+ workbenchProjectKey,
+ type WorkbenchDelegationStatus,
+ type WorkbenchTaskJudgment,
+ type WorkbenchTaskOrigin,
+ type WorkbenchTaskState,
+} from '../../../shared/botWorkbench';
+
+/** 活动快照里工作台用得到的字段(灵动岛 / 侧栏同源)。 */
+export interface WorkbenchActivity {
+ phase: string;
+ startedAtMs?: number | null;
+ currentActionSummary?: string | null;
+ compactDetail?: string | null;
+}
+
+export interface WorkbenchDelegationInput {
+ childSessionId: string | null;
+ status: WorkbenchDelegationStatus;
+ resultSummary: string | null;
+ lastError: string | null;
+ createdAt: number;
+ acceptedAt: number | null;
+ completedAt: number | null;
+ updatedAt: number;
+}
+
+export interface WorkbenchScheduleInput {
+ id: string;
+ name: string;
+ status: string;
+ source?: string;
+ workspaceKind?: string;
+ workingDir?: string;
+ manual?: boolean;
+ cronExpr?: string;
+ intervalMs?: number;
+ nextFireAt?: number;
+ lastFinishedAt?: number;
+ updatedAt?: number;
+}
+
+export interface WorkbenchRoutineInput {
+ id: string;
+ name: string;
+ enabled: boolean;
+ activity?: 'queued' | 'running';
+ triggers: Array<{ kind: string; expression?: string; intervalMs?: number; at?: number }>;
+ updatedAt: number;
+ lastRun?: { status: string; finishedAt?: number; createdAt: number; resultText?: string; error?: string } | null;
+}
+
+export interface ExternalSessionCandidate {
+ source: 'claude' | 'codex' | 'pi';
+ id: string;
+ projectDir: string | null;
+ updatedAt: string;
+ archived: boolean;
+}
+
+/** 格子底部那一行说的是什么;具体文案由界面按语言拼。 */
+export type WorkbenchTileLine =
+ | { kind: 'action'; text: string }
+ | { kind: 'waiting' }
+ | { kind: 'queued' }
+ | { kind: 'interrupted' }
+ | { kind: 'errored' }
+ | { kind: 'failed'; text: string | null }
+ | { kind: 'summary'; text: string }
+ | { kind: 'next'; at: number }
+ | { kind: 'manual' }
+ | { kind: 'paused' }
+ | { kind: 'disabled' }
+ | { kind: 'last-run'; ok: boolean; text: string | null }
+ | { kind: 'never-run' }
+ | { kind: 'none' };
+
+/** 伙伴判为值得接着做的两类;done 不上工作台。 */
+export type WorkbenchShownVerdict = 'unfinished' | 'idea';
+
+export type WorkbenchTile =
+ | {
+ type: 'session';
+ key: string;
+ /** Cindy 任务 id(也是工作台 task_id)。 */
+ id: string;
+ /** 伙伴写的人话标题;没有时为清洗过的原始标题(可能为空,界面用「未命名任务」)。 */
+ title: string;
+ state: WorkbenchTaskState;
+ origin: WorkbenchTaskOrigin;
+ verdict: WorkbenchShownVerdict | null;
+ /** 伙伴写的下一步。 */
+ next: string | null;
+ /** 在做时用来显示用时。 */
+ startedAtMs: number | null;
+ lastActiveMs: number;
+ line: WorkbenchTileLine;
+ }
+ | {
+ /** 还没接过来的本机 Claude Code / Codex / Pi 会话,只因伙伴的判断而出现。 */
+ type: 'external';
+ key: string;
+ /** 工作台 task_id:`claude:<id>` / `codex:<id>` / `pi:<id>`。 */
+ id: string;
+ title: string;
+ state: WorkbenchTaskState;
+ origin: 'claude-code' | 'codex' | 'pi';
+ verdict: WorkbenchShownVerdict;
+ next: string | null;
+ startedAtMs: null;
+ lastActiveMs: number;
+ line: WorkbenchTileLine;
+ }
+ | {
+ /** 伙伴从项目素材里写下的 PR / issue / 建议,只因伙伴的判断而出现。 */
+ type: 'item';
+ key: string;
+ /** 工作台 task_id:`pr:<owner>/<repo>#<n>` / `issue:…` / `idea:<slug>`。 */
+ id: string;
+ itemKind: 'pr' | 'issue' | 'idea';
+ /** PR / issue 编号;建议为 null。 */
+ number: number | null;
+ title: string;
+ state: WorkbenchTaskState;
+ verdict: WorkbenchShownVerdict;
+ next: string | null;
+ /** 伙伴给的参考:https 链接或项目内路径。 */
+ ref: string | null;
+ /** 条目所属的项目目录(用来限定打开路径)。 */
+ project: string;
+ startedAtMs: null;
+ lastActiveMs: number;
+ line: WorkbenchTileLine;
+ }
+ | {
+ type: 'schedule';
+ key: string;
+ id: string;
+ title: string;
+ state: WorkbenchTaskState;
+ schedule: Pick<WorkbenchScheduleInput, 'manual' | 'cronExpr' | 'intervalMs'>;
+ startedAtMs: null;
+ lastActiveMs: number;
+ line: WorkbenchTileLine;
+ }
+ | {
+ type: 'routine';
+ key: string;
+ id: string;
+ title: string;
+ state: WorkbenchTaskState;
+ triggers: WorkbenchRoutineInput['triggers'];
+ startedAtMs: null;
+ lastActiveMs: number;
+ line: WorkbenchTileLine;
+ };
+
+function toMs(value: string | number | null | undefined): number {
+ if (typeof value === 'number') return Number.isFinite(value) ? value : 0;
+ if (!value) return 0;
+ const ms = Date.parse(value);
+ return Number.isFinite(ms) ? ms : 0;
+}
+
+/** 伙伴档案里投影出的全部伙伴 session(主任务、群专线、历史、伙伴间委派)。 */
+export function collectBotHiddenSessionIds(
+ profiles: ReadonlyArray<{ sessions: ReadonlyArray<{ id: string }> }>,
+): Set<string> {
+ const out = new Set<string>();
+ for (const profile of profiles) for (const session of profile.sessions) if (session.id) out.add(session.id);
+ return out;
+}
+
+/**
+ * 能进工作台的本机任务:未归档删除、本机、普通来源、不是 Orca worker、不是伙伴的
+ * 隐藏任务。草稿(从没发过消息)不算,伙伴刚开、还在排队的后台任务例外。
+ */
+export function isWorkbenchCandidateSession(
+ session: Session,
+ hiddenIds: ReadonlySet<string>,
+ delegationChildIds: ReadonlySet<string> = new Set(),
+): boolean {
+ if (session.status !== 'active') return false;
+ if (session.remoteHostId || session.deviceLinkDeviceId) return false;
+ if (hiddenIds.has(session.id) || session.source === 'bot') return false;
+ if (!isWorkbenchTaskSource(session.source) || session.orcaRole === 'worker') return false;
+ if (!session.workingDir) return false;
+ if (delegationChildIds.has(session.id)) return true;
+ return session.userSendAt != null || (session._count?.messages ?? 0) > 0;
+}
+
+export interface WorkbenchProjectOption {
+ /** 项目目录(用于记录与比较)。 */
+ dir: string;
+ name: string;
+ taskCount: number;
+ automationCount: number;
+ /** 还没导入的本机 Claude Code / Codex 任务。 */
+ claudeCount: number;
+ codexCount: number;
+ latestActivityMs: number;
+ /** 目录下有 `.git`(主进程扫描时 stat 得出;未知时为 false)。 */
+ isGitRepo: boolean;
+}
+
+/**
+ * 空状态的项目清单:本机已有项目(任务列表同一套项目分组)+ 只在 Claude Code / Codex 里
+ * 出现过的目录;每行给出任务数、自动化数与待导入数。已导入的外部任务由扫描方去重。
+ */
+export function buildWorkbenchProjectOptions(input: {
+ sessions: readonly Session[];
+ hiddenIds: ReadonlySet<string>;
+ schedules: readonly WorkbenchScheduleInput[];
+ candidates: readonly ExternalSessionCandidate[];
+ /** 主进程扫描给出的 git 仓库目录。 */
+ gitRepoDirs?: readonly string[];
+ localPlatform: string;
+ caseInsensitive: boolean;
+ excludeDirs?: readonly string[];
+}): WorkbenchProjectOption[] {
+ const eligible = input.sessions.filter(
+ (session) => session.workspaceKind !== 'dialogue' && isWorkbenchCandidateSession(session, input.hiddenIds),
+ );
+ const grouped = groupSessions(eligible, {
+ includePinnedInProjects: true,
+ localPlatform: input.localPlatform,
+ });
+ const byKey = new Map<string, WorkbenchProjectOption>();
+ for (const project of grouped.projects) {
+ if (project.scope !== 'local') continue;
+ const key = workbenchProjectKey(project.workingDir, input.caseInsensitive);
+ if (!key) continue;
+ byKey.set(key, {
+ dir: project.workingDir,
+ name: project.displayName,
+ taskCount: project.sessions.length,
+ automationCount: 0,
+ claudeCount: 0,
+ codexCount: 0,
+ latestActivityMs: toMs(project.latestActivityAt),
+ isGitRepo: false,
+ });
+ }
+ const ensure = (dir: string, key: string) => {
+ let option = byKey.get(key);
+ if (!option) {
+ option = {
+ dir,
+ name: dir.split(/[\\/]/).filter(Boolean).pop() ?? dir,
+ taskCount: 0,
+ automationCount: 0,
+ claudeCount: 0,
+ codexCount: 0,
+ latestActivityMs: 0,
+ isGitRepo: false,
+ };
+ byKey.set(key, option);
+ }
+ return option;
+ };
+ for (const schedule of input.schedules) {
+ if (schedule.source === 'bot' || schedule.workspaceKind === 'dialogue' || !schedule.workingDir) continue;
+ const key = workbenchProjectKey(schedule.workingDir, input.caseInsensitive);
+ if (!key) continue;
+ const option = byKey.get(key);
+ // 只有自动化、没有任何任务的目录不单独成行:自动化挂在已有项目上才有意义。
+ if (option) option.automationCount += 1;
+ }
+ for (const candidate of input.candidates) {
+ if (candidate.archived || !candidate.projectDir) continue;
+ const key = workbenchProjectKey(candidate.projectDir, input.caseInsensitive);
+ if (!key) continue;
+ const option = ensure(candidate.projectDir, key);
+ if (candidate.source === 'claude') option.claudeCount += 1;
+ else if (candidate.source === 'codex') option.codexCount += 1;
+ else continue;
+ option.latestActivityMs = Math.max(option.latestActivityMs, toMs(candidate.updatedAt));
+ }
+ for (const dir of input.gitRepoDirs ?? []) {
+ const key = workbenchProjectKey(dir, input.caseInsensitive);
+ const option = key ? byKey.get(key) : undefined;
+ if (option) option.isGitRepo = true;
+ }
+ const excluded = new Set(
+ (input.excludeDirs ?? [])
+ .map((dir) => workbenchProjectKey(dir, input.caseInsensitive))
+ .filter((key): key is string => Boolean(key)),
+ );
+ return [...byKey.entries()]
+ .filter(([key, option]) => !excluded.has(key) && option.taskCount + option.claudeCount + option.codexCount > 0)
+ .map(([, option]) => option)
+ .sort((a, b) => b.latestActivityMs - a.latestActivityMs || a.name.localeCompare(b.name));
+}
+
+function shownVerdict(judgment: WorkbenchTaskJudgment | undefined): WorkbenchShownVerdict | null {
+ return judgment && judgment.verdict !== 'done' ? judgment.verdict : null;
+}
+
+/**
+ * 任务格排列:在做 / 等你 / 排队在前,其次没做完、聊过没下文,再是自动化,
+ * 最后是伙伴自己开的、已收尾的后台任务;同一档按最近活动倒序。
+ */
+export function workbenchTileRank(tile: Pick<WorkbenchTile, 'state' | 'type'> & { verdict?: WorkbenchShownVerdict | null }): number {
+ if (tile.state === 'running' || tile.state === 'waiting' || tile.state === 'queued') return 0;
+ if (tile.verdict === 'unfinished') return 1;
+ if (tile.verdict === 'idea') return 2;
+ if (tile.type === 'schedule' || tile.type === 'routine') return 3;
+ return 4;
+}
+
+/**
+ * 项目里还没被伙伴判断过的本机外部会话数(还没接过来的 Claude Code / Codex / Pi)。
+ * 汇总行据此显示「正在了解…」。Cindy 自己的任务不计:它们本来就在工作台上,
+ * 主人新开一件任务不等于伙伴"还在读"。
+ */
+export function countUnjudgedCandidates(input: {
+ projectDirs: readonly string[];
+ caseInsensitive: boolean;
+ candidates: readonly ExternalSessionCandidate[];
+ judgments: Readonly<Record<string, WorkbenchTaskJudgment>>;
+}): number {
+ let unjudged = 0;
+ for (const candidate of input.candidates) {
+ if (candidate.archived || !candidate.projectDir) continue;
+ if (!findWorkbenchProject(candidate.projectDir, input.projectDirs, input.caseInsensitive)) continue;
+ if (!input.judgments[externalWorkbenchTaskId(candidate.source, candidate.id)]) unjudged += 1;
+ }
+ return unjudged;
+}
+
+function sessionLine(
+ state: WorkbenchTaskState,
+ session: Session,
+ activity: WorkbenchActivity | null,
+ delegation: WorkbenchDelegationInput | null,
+ interrupted: boolean,
+): WorkbenchTileLine {
+ if (state === 'running') {
+ const text = boundWorkbenchSummary(activity?.currentActionSummary ?? activity?.compactDetail);
+ return text ? { kind: 'action', text } : { kind: 'none' };
+ }
+ if (state === 'waiting') return { kind: 'waiting' };
+ if (state === 'queued') return { kind: 'queued' };
+ if (state === 'stopped') {
+ if (delegation && ['failed', 'timed-out', 'cancelled'].includes(delegation.status)) {
+ return { kind: 'failed', text: boundWorkbenchSummary(delegation.resultSummary) };
+ }
+ return interrupted ? { kind: 'interrupted' } : { kind: 'errored' };
+ }
+ const text = boundWorkbenchSummary(delegation?.resultSummary ?? session.summary ?? session.preview);
+ return text ? { kind: 'summary', text } : { kind: 'none' };
+}
+
+/**
+ * 已接手项目的条目:项目里最近 30 天的 Cindy 任务(含主人自己开的,不论有无判断)、伙伴开的后台任务、
+ * 伙伴判为没做完 / 聊过没下文的本机外部会话与 PR / issue / 建议、项目里的自动化、伙伴自己的例行任务
+ * (含导入来的自动化)。排列见 `workbenchTileRank`,分组见 `groupWorkbenchTiles`。
+ */
+export function buildWorkbenchTiles(input: {
+ sessions: readonly Session[];
+ hiddenIds: ReadonlySet<string>;
+ projectDirs: readonly string[];
+ caseInsensitive: boolean;
+ delegations: readonly WorkbenchDelegationInput[];
+ activity: ReadonlyMap<string, WorkbenchActivity>;
+ erroredIds: ReadonlySet<string>;
+ schedules: readonly WorkbenchScheduleInput[];
+ routines: readonly WorkbenchRoutineInput[];
+ judgments?: Readonly<Record<string, WorkbenchTaskJudgment>>;
+ /** 渲染层扫描到的本机会话,只用来补最近活动时间。 */
+ candidates?: readonly ExternalSessionCandidate[];
+ /** 当前时间;只列最近 30 天活动过的 Cindy 任务(伙伴的后台任务不限)。 */
+ now?: number;
+}): WorkbenchTile[] {
+ const since = (input.now ?? Date.now()) - WORKBENCH_RECENT_WINDOW_MS;
+ const judgments = input.judgments ?? {};
+ const delegationByChild = new Map<string, WorkbenchDelegationInput>();
+ for (const delegation of [...input.delegations].sort((a, b) => b.createdAt - a.createdAt)) {
+ if (delegation.childSessionId && !delegationByChild.has(delegation.childSessionId)) {
+ delegationByChild.set(delegation.childSessionId, delegation);
+ }
+ }
+ const delegationChildIds = new Set(delegationByChild.keys());
+ const tiles: WorkbenchTile[] = [];
+
+ for (const session of input.sessions) {
+ if (!isWorkbenchCandidateSession(session, input.hiddenIds, delegationChildIds)) continue;
+ if (!findWorkbenchProject(session.workingDir, input.projectDirs, input.caseInsensitive)) continue;
+ const delegation = delegationByChild.get(session.id) ?? null;
+ const activity = input.activity.get(session.id) ?? null;
+ const interrupted = hasPendingSessionInterruption(session);
+ const state = deriveWorkbenchSessionState({
+ activityPhase: activity?.phase ?? null,
+ interrupted,
+ errored: input.erroredIds.has(session.id),
+ delegationStatus: delegation?.status ?? null,
+ });
+ const judgment = judgments[session.id];
+ const verdict = shownVerdict(judgment);
+ const live = state === 'running' || state === 'waiting' || state === 'queued';
+ const lastActiveMs = Math.max(toMs(session.userSendAt), toMs(session.updatedAt), delegation?.updatedAt ?? 0);
+ // 项目里的 Cindy 任务(含主人自己开的)一律上工作台,不管伙伴判断过没有——它们是伙伴随时知道的
+ // 项目事务;只看最近 30 天,在跑 / 等你 / 排队的与伙伴的后台任务不受此限。
+ if (!live && !delegation && lastActiveMs < since) continue;
+ tiles.push({
+ type: 'session',
+ key: `session:${session.id}`,
+ id: session.id,
+ title: judgment?.title ?? cleanWorkbenchTitle(session.title),
+ state,
+ origin: delegation ? 'delegated' : (importedSessionOrigin(session.id, session.agentKind) ?? 'existing'),
+ verdict,
+ next: verdict ? judgment!.next : null,
+ startedAtMs: state === 'running'
+ ? (activity?.startedAtMs ?? delegation?.acceptedAt ?? null)
+ : null,
+ lastActiveMs,
+ line: sessionLine(state, session, activity, delegation, interrupted),
+ });
+ }
+
+ const candidateUpdatedAt = new Map(
+ (input.candidates ?? []).map((candidate) => [
+ externalWorkbenchTaskId(candidate.source, candidate.id),
+ toMs(candidate.updatedAt),
+ ]),
+ );
+ for (const [taskId, judgment] of Object.entries(judgments)) {
+ const ref = parseWorkbenchTaskId(taskId);
+ const verdict = shownVerdict(judgment);
+ if (!ref || !verdict) continue;
+ const project = findWorkbenchProject(judgment.project, input.projectDirs, input.caseInsensitive);
+ if (!project) continue;
+ if (ref.kind === 'github' || ref.kind === 'idea') {
+ tiles.push({
+ type: 'item',
+ key: `item:${taskId}`,
+ id: taskId,
+ itemKind: ref.kind === 'idea' ? 'idea' : ref.type,
+ number: ref.kind === 'github' ? ref.number : null,
+ title: judgment.title,
+ state: 'done',
+ verdict,
+ next: judgment.next,
+ ref: judgment.ref ?? null,
+ project,
+ startedAtMs: null,
+ lastActiveMs: toMs(judgment.updatedAt),
+ line: { kind: 'none' },
+ });
+ continue;
+ }
+ if (ref.kind !== 'external') continue;
+ tiles.push({
+ type: 'external',
+ key: `external:${taskId}`,
+ id: taskId,
+ title: judgment.title,
+ state: 'done',
+ origin: ref.source === 'claude' ? 'claude-code' : ref.source,
+ verdict,
+ next: judgment.next,
+ startedAtMs: null,
+ lastActiveMs: candidateUpdatedAt.get(taskId) ?? toMs(judgment.updatedAt),
+ line: { kind: 'none' },
+ });
+ }
+
+ for (const schedule of input.schedules) {
+ if (schedule.source === 'bot' || schedule.workspaceKind === 'dialogue') continue;
+ if (!findWorkbenchProject(schedule.workingDir, input.projectDirs, input.caseInsensitive)) continue;
+ const enabled = schedule.status === 'active';
+ const state = deriveWorkbenchAutomationState({ enabled });
+ tiles.push({
+ type: 'schedule',
+ key: `schedule:${schedule.id}`,
+ id: schedule.id,
+ title: schedule.name,
+ state,
+ schedule: { manual: schedule.manual, cronExpr: schedule.cronExpr, intervalMs: schedule.intervalMs },
+ startedAtMs: null,
+ lastActiveMs: Math.max(schedule.lastFinishedAt ?? 0, schedule.updatedAt ?? 0),
+ line: !enabled
+ ? { kind: 'paused' }
+ : schedule.manual
+ ? { kind: 'manual' }
+ : schedule.nextFireAt
+ ? { kind: 'next', at: schedule.nextFireAt }
+ : { kind: 'none' },
+ });
+ }
+
+ for (const routine of input.routines) {
+ const state = deriveWorkbenchAutomationState({
+ enabled: routine.enabled,
+ running: routine.activity === 'running',
+ queued: routine.activity === 'queued',
+ });
+ const last = routine.lastRun ?? null;
+ tiles.push({
+ type: 'routine',
+ key: `routine:${routine.id}`,
+ id: routine.id,
+ title: routine.name,
+ state,
+ triggers: routine.triggers,
+ startedAtMs: null,
+ lastActiveMs: Math.max(last?.finishedAt ?? last?.createdAt ?? 0, routine.updatedAt),
+ line: state === 'running'
+ ? { kind: 'none' }
+ : state === 'queued'
+ ? { kind: 'queued' }
+ : !routine.enabled
+ ? { kind: 'disabled' }
+ : last
+ ? {
+ kind: 'last-run',
+ ok: last.status === 'success' || last.status === 'skipped',
+ text: boundWorkbenchSummary(last.resultText ?? last.error),
+ }
+ : { kind: 'never-run' },
+ });
+ }
+
+ return tiles.sort((a, b) => workbenchTileRank(a) - workbenchTileRank(b) || b.lastActiveMs - a.lastActiveMs);
+}
+
+// ─── 工作台列表的分组 ─────────────────────────────────────────────
+
+/** 列表分四组,顺序固定:等你 → 在做 → 待做 → 做完。状态由所在组表达,条目里不再写状态词。 */
+export type WorkbenchGroupKey = 'waiting' | 'running' | 'todo' | 'done';
+
+export const WORKBENCH_GROUP_ORDER: readonly WorkbenchGroupKey[] = ['waiting', 'running', 'todo', 'done'];
+
+/**
+ * 一条归哪一组:
+ * - 等你:在等主人回复,或任务停在出错 / 被打断 / 后台任务失败(要主人拿主意);
+ * - 在做:正在跑的任务与自动化;
+ * - 待做:伙伴判为没做完 / 聊过没下文的、排队中的、PR / issue / 建议条目;
+ * - 做完:其余——收尾了的后台任务、待命或停用的自动化。
+ */
+export function workbenchTileGroup(tile: WorkbenchTile): WorkbenchGroupKey {
+ if (tile.state === 'waiting') return 'waiting';
+ if (tile.state === 'stopped' && (tile.type === 'session' || tile.type === 'external')) return 'waiting';
+ if (tile.state === 'running') return 'running';
+ if (tile.state === 'queued' || tile.type === 'item') return 'todo';
+ if ('verdict' in tile && tile.verdict) return 'todo';
+ return 'done';
+}
+
+/**
+ * 哪些组的条目带「跟进」:待做与等你——主人点一下,伙伴在左边接着干。
+ * 在做的已经在跑,做完的不需要再推。
+ */
+export function workbenchGroupHasFollowUp(key: WorkbenchGroupKey): boolean {
+ return key === 'todo' || key === 'waiting';
+}
+
+export interface WorkbenchTileGroup {
+ key: WorkbenchGroupKey;
+ /** 要列出的条目(做完一组最多 30 条)。 */
+ tiles: WorkbenchTile[];
+ /** 这一组的总数(标题旁显示)。 */
+ total: number;
+ /** 更早、没有列出的条数,显示成一行「更早的 N 个」。 */
+ hiddenCount: number;
+ /** 做完一组默认折叠,只在标题旁显示数量。 */
+ defaultCollapsed: boolean;
+}
+
+/** 做完一组最多列出的条数。 */
+export const WORKBENCH_DONE_MAX = 30;
+
+/** 按固定顺序分组,组内保持输入顺序(`buildWorkbenchTiles` 已按最近活动排好);空组不出。 */
+export function groupWorkbenchTiles(tiles: readonly WorkbenchTile[]): WorkbenchTileGroup[] {
+ const buckets = new Map<WorkbenchGroupKey, WorkbenchTile[]>(WORKBENCH_GROUP_ORDER.map((key) => [key, []]));
+ for (const tile of tiles) buckets.get(workbenchTileGroup(tile))!.push(tile);
+ return WORKBENCH_GROUP_ORDER.flatMap((key): WorkbenchTileGroup[] => {
+ const grouped = buckets.get(key)!;
+ if (grouped.length === 0) return [];
+ if (key !== 'done') return [{ key, tiles: grouped, total: grouped.length, hiddenCount: 0, defaultCollapsed: false }];
+ grouped.sort((a, b) => b.lastActiveMs - a.lastActiveMs);
+ return [{
+ key,
+ tiles: grouped.slice(0, WORKBENCH_DONE_MAX),
+ total: grouped.length,
+ hiddenCount: Math.max(0, grouped.length - WORKBENCH_DONE_MAX),
+ defaultCollapsed: true,
+ }];
+ });
+}
+
+// ─── 空状态项目清单的过滤与分档 ─────────────────────────────────────
+
+/** 主进程给的本机路径(主目录、应用数据目录、系统临时目录);拿不到时为 null。 */
+export interface WorkbenchPathHints {
+ homeDir: string | null;
+ userDataDir: string | null;
+ tempDirs: readonly string[];
+}
+
+/** 主目录下的工具 / 缓存目录:这些目录里的会话不是用户的项目。 */
+const HOME_TOOL_DIRS = [
+ 'Library/Caches',
+ 'Library/Application Support/Cindy',
+ '.cache',
+ '.codex',
+ '.claude',
+ '.cindy',
+ '.cursor',
+ '.npm',
+ '.Trash',
+];
+const SYSTEM_TEMP_DIRS = ['/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp', '/var/folders', '/private/var/folders'];
+/** 主进程路径没送到时的兜底:按常见主目录形态识别。 */
+const HOME_DIR_PATTERN = /^(?:\/Users\/[^/]+|\/home\/[^/]+|[a-z]:\/users\/[^/]+)$/i;
+
+function isSameOrUnder(dir: string, root: string): boolean {
+ return dir === root || dir.startsWith(`${root.endsWith('/') ? root.slice(0, -1) : root}/`);
+}
+
+/** 主目录本身、Cindy 的应用数据目录(含各伙伴 Home 的 workspace)、系统与工具的临时 / 缓存目录。 */
+export function isNonProjectDir(
+ dir: string,
+ hints: WorkbenchPathHints | null,
+ caseInsensitive: boolean,
+): boolean {
+ const key = workbenchProjectKey(dir, caseInsensitive);
+ if (!key) return true;
+ const norm = (value: string | null | undefined) => workbenchProjectKey(value, caseInsensitive);
+ const homes = new Set<string>();
+ const hintedHome = norm(hints?.homeDir);
+ if (hintedHome) homes.add(hintedHome);
+ const inferredHome = /^(\/Users\/[^/]+|\/home\/[^/]+|[a-z]:\/users\/[^/]+)(?:\/|$)/i.exec(key)?.[1];
+ if (inferredHome) homes.add(inferredHome);
+ if (hintedHome === key || HOME_DIR_PATTERN.test(key)) return true;
+ const roots: string[] = [...SYSTEM_TEMP_DIRS.map((root) => norm(root) ?? root)];
+ for (const temp of hints?.tempDirs ?? []) {
+ const value = norm(temp);
+ if (value) roots.push(value);
+ }
+ const userData = norm(hints?.userDataDir);
+ if (userData) roots.push(userData);
+ for (const home of homes) {
+ for (const sub of HOME_TOOL_DIRS) {
+ const value = norm(`${home}/${sub}`);
+ if (value) roots.push(value);
+ }
+ }
+ return roots.some((root) => isSameOrUnder(key, root));
+}
+
+/**
+ * 目录名像自动生成的 id:UUID、长十六进制串、`cli_<hex>`、`<word>-<长数字>`,
+ * 或者名字大部分是十六进制与连字符且夹着数字。
+ */
+export function looksGeneratedDirName(name: string): boolean {
+ const base = name.trim().toLowerCase();
+ if (!base) return false;
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-/.test(base)) return true;
+ if (/^[0-9a-f]{12,}$/.test(base)) return true;
+ if (/^[a-z]+_[0-9a-f]{8,}$/.test(base)) return true;
+ if (/^[a-z]+-\d{6,}$/.test(base)) return true;
+ const hexish = [...base].filter((char) => /[0-9a-f-]/.test(char)).length;
+ const digits = [...base].filter((char) => /\d/.test(char)).length;
+ return base.length >= 10 && digits >= 3 && hexish / base.length >= 0.8;
+}
+
+export const WORKBENCH_PRIMARY_PROJECTS = 5;
+const STALE_SINGLE_SESSION_MS = 14 * 24 * 60 * 60 * 1000;
+
+/**
+ * 项目清单分档(纯函数,确定性):
+ * 1. 直接不列:`isNonProjectDir`;
+ * 2. 折叠:名字像生成的 id;只有 1 个会话且 14 天没动;
+ * 3. 第一档:git 仓库、Cindy 里已有任务或自动化、会话总数 ≥ 3;
+ * 4. 其余折叠。第一档按最近活动倒序最多 5 行,多出的并入折叠;折叠同样按最近活动倒序。
+ */
+export function tierWorkbenchProjectOptions(
+ options: readonly WorkbenchProjectOption[],
+ input: { hints: WorkbenchPathHints | null; caseInsensitive: boolean; now: number; maxPrimary?: number },
+): { primary: WorkbenchProjectOption[]; folded: WorkbenchProjectOption[] } {
+ const byRecency = (a: WorkbenchProjectOption, b: WorkbenchProjectOption) =>
+ b.latestActivityMs - a.latestActivityMs || a.name.localeCompare(b.name);
+ const primary: WorkbenchProjectOption[] = [];
+ const folded: WorkbenchProjectOption[] = [];
+ for (const option of options) {
+ if (isNonProjectDir(option.dir, input.hints, input.caseInsensitive)) continue;
+ const total = option.taskCount + option.claudeCount + option.codexCount;
+ const name = option.dir.split(/[\\/]/).filter(Boolean).pop() ?? option.name;
+ const staleSingle = total <= 1 && input.now - option.latestActivityMs > STALE_SINGLE_SESSION_MS;
+ if (looksGeneratedDirName(name) || staleSingle) {
+ folded.push(option);
+ } else if (option.isGitRepo || option.taskCount > 0 || option.automationCount > 0 || total >= 3) {
+ primary.push(option);
+ } else {
+ folded.push(option);
+ }
+ }
+ primary.sort(byRecency);
+ const max = input.maxPrimary ?? WORKBENCH_PRIMARY_PROJECTS;
+ return { primary: primary.slice(0, max), folded: [...primary.slice(max), ...folded].sort(byRecency) };
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index b14466d931..06e2575e05 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -28,6 +28,7 @@ import {
Terminal,
GitPullRequestArrow,
UsersRound,
+ LayoutGrid,
ListTodo,
Plus,
Puzzle,
@@ -142,6 +143,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {
subagents: Bot,
'background-tasks': ListTodo,
routines: ListTodo,
+ 'bot-workbench': LayoutGrid,
'resource-usage': Activity,
'cindy-make': Wrench,
};
@@ -156,6 +158,7 @@ const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {
subagents: 'rightSidebar.tabs.kinds.subagents',
'background-tasks': 'rightSidebar.tabs.kinds.backgroundTasks',
routines: 'routines.title',
+ 'bot-workbench': 'bots.workbench.title',
'resource-usage': 'rightSidebar.tabs.kinds.resourceUsage',
'cindy-make': 'settings.cindyMake.title',
};
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts
new file mode 100644
index 0000000000..d337bc86d2
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ bucket: {
+ tabs: [] as Array<{ id: string; kind: string; state: unknown }>,
+ activeTabId: null as string | null,
+ },
+}));
+
+vi.mock('../../store', () => ({
+ ensureHydrated: vi.fn(async () => undefined),
+ getBucket: vi.fn(() => mocks.bucket),
+ addTab: vi.fn(async (_sessionId: string, kind: string, state: unknown) => {
+ const tab = { id: 'workbench-new', kind, state };
+ mocks.bucket.tabs = [...mocks.bucket.tabs, tab];
+ mocks.bucket.activeTabId = tab.id;
+ return tab;
+ }),
+ reorderTabs: vi.fn(async () => undefined),
+}));
+vi.mock('../detachedSidebarRouting', () => ({
+ routeSidebarCommand: vi.fn(async () => 'attached'),
+}));
+vi.mock('../sidebarCommands', () => ({
+ requestRightSidebarVisibility: vi.fn(),
+}));
+
+import { addTab, reorderTabs } from '../../store';
+import { routeSidebarCommand } from '../detachedSidebarRouting';
+import { ensureBotWorkbenchTab } from '../openBotWorkbenchTab';
+import { requestRightSidebarVisibility } from '../sidebarCommands';
+
+describe('ensureBotWorkbenchTab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.bucket.tabs = [];
+ mocks.bucket.activeTabId = null;
+ vi.mocked(routeSidebarCommand).mockResolvedValue('attached');
+ });
+
+ it('creates the workbench first and opens the sidebar on the first visit', async () => {
+ mocks.bucket.tabs = [{ id: 'files', kind: 'file-browser', state: null }];
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ expect(routeSidebarCommand).toHaveBeenCalledWith(
+ { type: 'open-bot-workbench-tab', sessionId: 'bot-main', botId: 'bot-1' },
+ { allowOpen: false, userInitiated: false },
+ );
+ expect(addTab).toHaveBeenCalledWith('bot-main', 'bot-workbench', { botId: 'bot-1' });
+ expect(reorderTabs).toHaveBeenCalledWith('bot-main', ['workbench-new', 'files']);
+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {
+ sessionId: 'bot-main',
+ userInitiated: false,
+ });
+ });
+
+ it('leaves an existing workbench and the user sidebar choice alone', async () => {
+ mocks.bucket.tabs = [{ id: 'wb', kind: 'bot-workbench', state: { botId: 'bot-1' } }];
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ expect(addTab).not.toHaveBeenCalled();
+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();
+ });
+
+ it('lets a detached sidebar window handle it without popping the window open', async () => {
+ vi.mocked(routeSidebarCommand).mockResolvedValue('routed');
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ expect(addTab).not.toHaveBeenCalled();
+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
index baa3a9a1bc..31169ed9be 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
@@ -1,4 +1,5 @@
import { openRoutinesTab } from './openRoutinesTab';
+import { ensureBotWorkbenchTab } from './openBotWorkbenchTab';
/** 执行 main 已裁决并推给当前 renderer host 的 RSB command。 */
import type { RsbWindowCommand } from '../../../../shared/rightSidebarWindow';
@@ -23,6 +24,10 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<
await openRoutinesTab(command.sessionId, command.botId);
return;
}
+ if (command.type === 'open-bot-workbench-tab') {
+ await ensureBotWorkbenchTab(command.sessionId, command.botId);
+ return;
+ }
if (command.type === 'open-web-browser') {
await openUrlInSidebarBrowser(command.sessionId, command.url);
return;
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts
new file mode 100644
index 0000000000..acac21aa8e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts
@@ -0,0 +1,45 @@
+import { addOrFocusSingletonTab, addTab, ensureHydrated, getBucket, reorderTabs } from '../store';
+import { routeSidebarCommand } from './detachedSidebarRouting';
+import { requestRightSidebarVisibility } from './sidebarCommands';
+
+/** 工作台排在最前(工作台 / 文件 / 浏览器),其余标签保持原顺序。 */
+async function moveWorkbenchToFront(sessionId: string, tabId: string): Promise<void> {
+ const others = getBucket(sessionId).tabs.filter((candidate) => candidate.id !== tabId).map((candidate) => candidate.id);
+ if (others.length > 0) await reorderTabs(sessionId, [tabId, ...others]).catch(() => undefined);
+}
+
+/**
+ * 伙伴主任务页进入时确保右侧栏里有「工作台」标签。
+ *
+ * 只在标签还不存在时创建并展开右侧栏(首次进入默认打开);已存在时什么也不动,
+ * 用户之后收起右侧栏或切到文件 / 浏览器的选择都保留。这是程序自发的动作:
+ * detached 形态下只把命令交给已打开的子窗口,不因此弹出窗口或抢前台。
+ */
+export async function ensureBotWorkbenchTab(sessionId: string, botId: string): Promise<void> {
+ const route = await routeSidebarCommand(
+ { type: 'open-bot-workbench-tab', sessionId, botId },
+ { allowOpen: false, userInitiated: false },
+ );
+ if (route !== 'attached') return;
+ await ensureHydrated(sessionId);
+ if (getBucket(sessionId).tabs.some((tab) => tab.kind === 'bot-workbench')) return;
+ const tab = await addTab(sessionId, 'bot-workbench', { botId });
+ await moveWorkbenchToFront(sessionId, tab.id);
+ requestRightSidebarVisibility('open', { sessionId, userInitiated: false });
+}
+
+/**
+ * 用户点伙伴聊天头部的「工作台」:常驻入口。标签被关掉了就重建并排到最前,
+ * 还在就切到它;无论右侧栏当前收起还是分离出去,都把它打开。
+ * 与 `openRoutinesTab` 同一套路,保留用户已有的 attached / detached 选择。
+ */
+export async function openBotWorkbenchTab(sessionId: string, botId: string): Promise<void> {
+ const route = await routeSidebarCommand({ type: 'open-bot-workbench-tab', sessionId, botId });
+ if (route === 'attached') {
+ await ensureHydrated(sessionId);
+ const existed = getBucket(sessionId).tabs.some((tab) => tab.kind === 'bot-workbench');
+ const tab = await addOrFocusSingletonTab(sessionId, 'bot-workbench', { botId });
+ if (!existed) await moveWorkbenchToFront(sessionId, tab.id);
+ }
+ if (route === 'attached' || route === 'routed') requestRightSidebarVisibility('open', { sessionId });
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
new file mode 100644
index 0000000000..faac8f861c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
@@ -0,0 +1,39 @@
+import { LayoutGrid } from 'lucide-react';
+import { registerTabKind } from '../../registry';
+import type { TabKindPlugin, TabKindBodyProps } from '../../types';
+import { BotWorkbench } from '@/features/bots/BotWorkbench';
+
+interface BotWorkbenchTabState {
+ botId: string;
+}
+
+/**
+ * 伙伴工作台:只由伙伴主任务页自动创建(不进「+」菜单),每个任务至多一个。
+ * 只在已确认是本机的任务里渲染;device-link 远程或归属未解析时不显示内容。
+ */
+const plugin: TabKindPlugin<BotWorkbenchTabState> = {
+ kind: 'bot-workbench',
+ menu: {
+ kind: 'bot-workbench',
+ labelKey: 'bots.workbench.title',
+ icon: LayoutGrid,
+ order: 0,
+ enabled: true,
+ singleton: true,
+ hiddenFromMenu: true,
+ },
+ TabPillTitle: ({ t }) => <>{t('bots.workbench.title')}</>,
+ TabPillIcon: () => <LayoutGrid size={13} />,
+ TabBody: ({ state, ctx }: TabKindBodyProps<BotWorkbenchTabState>) =>
+ state.botId && ctx.deviceLinkDeviceId === null && !ctx.remoteHostId ? (
+ <BotWorkbench key={state.botId} botId={state.botId} sessionId={ctx.sessionId} />
+ ) : null,
+ defaultState: () => ({ botId: '' }),
+ hydrateState: (raw) => ({
+ botId:
+ raw && typeof raw === 'object' && typeof (raw as { botId?: unknown }).botId === 'string'
+ ? (raw as { botId: string }).botId
+ : '',
+ }),
+};
+registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
index ebc675d72d..bc3f4b799a 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
@@ -19,4 +19,5 @@ import './subagents';
import './background-tasks';
import './resource-usage';
import './routines';
+import './bot-workbench';
import './cindy-make';
diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.ts
index 26f53dc1c8..fff364d81a 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts
@@ -31,6 +31,7 @@ export type BuiltinTabKindId =
| 'subagents'
| 'background-tasks'
| 'routines'
+ | 'bot-workbench'
| 'resource-usage'
| 'cindy-make';
export type TabKindId = BuiltinTabKindId | `ghost:${string}`;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b83296b09b..89edb7a5d5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7798,6 +7798,121 @@
}
},
"bots": {
+ "workbench": {
+ "title": "Workbench",
+ "open": "Open workbench",
+ "emptyTitle": "Give {{name}} a project",
+ "emptyDescription": "Hand the work already on your computer to {{name}}. It first looks over the project's docs, recent commits and PRs, and past sessions, picks out what's unfinished or worth doing, and asks which one to continue.",
+ "scanning": "Looking for projects on this computer…",
+ "noProjects": "No projects with sessions yet. Pick a folder to hand to {{name}}.",
+ "pickFolder": "Choose another folder",
+ "cancelAdd": "Cancel",
+ "projectTasks_one": "{{count}} session",
+ "projectTasks_other": "{{count}} sessions",
+ "projectAutomations_one": "{{count}} automation",
+ "projectAutomations_other": "{{count}} automations",
+ "sourceCindy_one": "{{count}} Cindy session",
+ "sourceCindy_other": "{{count}} Cindy sessions",
+ "sourceClaude_one": "{{count}} Claude Code session",
+ "sourceClaude_other": "{{count}} Claude Code sessions",
+ "sourceCodex_one": "{{count}} Codex session",
+ "sourceCodex_other": "{{count}} Codex sessions",
+ "moreProjects": "{{count}} more",
+ "hideMoreProjects": "Show less",
+ "grant": "{{name}} can view, continue and stop {{scope}} in {{project}}, and will start new sessions for you.",
+ "grantTasks_one": "{{count}} session",
+ "grantTasks_other": "{{count}} sessions",
+ "grantCindy_one": "{{count}} Cindy session",
+ "grantCindy_other": "{{count}} Cindy sessions",
+ "grantClaude_one": "{{count}} Claude Code session",
+ "grantClaude_other": "{{count}} Claude Code sessions",
+ "grantCodex_one": "{{count}} Codex session",
+ "grantCodex_other": "{{count}} Codex sessions",
+ "grantAutomations_one": "{{count}} automation",
+ "grantAutomations_other": "{{count}} automations",
+ "grantEverything": "the sessions and automations",
+ "handOver": "Hand to {{name}}",
+ "handoverMessage": "I'm handing {{project}} over to you.",
+ "addProject": "Give {{name}} another project",
+ "removeProject": "Take {{project}} back from {{name}}",
+ "dirMissing": "Folder not found",
+ "dirUnavailable": "This folder can't be opened. Try another one.",
+ "tooManyDirs": "{{name}} can look after up to {{count}} projects",
+ "sendFailed": "Could not send to {{name}}. Try again.",
+ "tasksEmpty": "Nothing to pick up yet.",
+ "understanding": "{{name}} is getting to know {{project}}…",
+ "untitled": "Untitled session",
+ "continueMessage": "Continue “{{title}}”: {{text}}",
+ "verdict": {
+ "unfinished": "Unfinished",
+ "idea": "Not followed up"
+ },
+ "detail": {
+ "back": "Back to workbench",
+ "stop": "Stop this session",
+ "openInTasks": "Open in sessions",
+ "placeholder": "Add a note so {{name}} can continue…",
+ "send": "Send",
+ "sent": "Sent to {{name}}",
+ "judgment": "{{name}}'s take",
+ "empty": "Nothing to show yet.",
+ "loadFailed": "Couldn't read this session.",
+ "truncated": "Showing the most recent part only",
+ "ref": "Reference",
+ "noRef": "No reference attached.",
+ "openPr": "Open PR #{{number}} on GitHub",
+ "refBlocked": "This path is outside the handed-over projects, so it wasn't opened."
+ },
+ "openTask": "Open “{{title}}” ({{state}})",
+ "outputs": "Outputs",
+ "outputsEmpty": "Files {{name}} makes will show up here.",
+ "state": {
+ "running": "Running",
+ "waiting": "Waiting on you",
+ "queued": "Queued",
+ "stopped": "Stopped",
+ "automation": "Automation",
+ "done": "Done"
+ },
+ "group": {
+ "waiting": "Waiting on you",
+ "running": "Running",
+ "todo": "To do",
+ "done": "Done"
+ },
+ "followUp": {
+ "label": "Follow up",
+ "message": "Follow up on “{{title}}”",
+ "aria": "Follow up on “{{title}}”"
+ },
+ "olderCount_one": "{{count}} older",
+ "olderCount_other": "{{count}} older",
+ "kind": {
+ "existing": "Existing session",
+ "delegated": "You asked",
+ "claudeCode": "From Claude Code",
+ "codex": "From Codex",
+ "pi": "From Pi",
+ "pr": "PR #{{number}}",
+ "issue": "Issue #{{number}}",
+ "idea": "Suggestion",
+ "automationPlain": "Automation"
+ },
+ "cycle": {
+ "manual": "Manual",
+ "once": "Once",
+ "event": "On event"
+ },
+ "line": {
+ "waiting": "Waiting for your reply",
+ "queued": "Queued",
+ "interrupted": "Last run didn't finish",
+ "errored": "Last run hit an error",
+ "failed": "Didn't finish",
+ "paused": "Paused",
+ "disabled": "Turned off"
+ }
+ },
"remoteSettings": {
"empty": "Nothing here yet.",
"loadFailed": "Could not load settings. Try again.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1b7ed1e9bf..7fe06051f1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7796,6 +7796,110 @@
}
},
"bots": {
+ "workbench": {
+ "title": "ワークベンチ",
+ "open": "ワークベンチを開く",
+ "emptyTitle": "{{name}} にプロジェクトを任せる",
+ "emptyDescription": "このコンピューターにある作業を {{name}} に引き継ぎます。まずプロジェクトのドキュメント、最近のコミットと PR、これまでのセッションに目を通し、終わっていないものややる価値のあるものを選び出してから、どれを続けるか確認します。",
+ "scanning": "このコンピューターのプロジェクトを探しています…",
+ "noProjects": "セッションのあるプロジェクトがまだありません。フォルダーを選んで {{name}} に任せられます。",
+ "pickFolder": "別のフォルダーを選ぶ",
+ "cancelAdd": "キャンセル",
+ "projectTasks_other": "{{count}} 件のセッション",
+ "projectAutomations_other": "{{count}} 件の自動化",
+ "sourceCindy_other": "Cindy {{count}} 件のセッション",
+ "sourceClaude_other": "Claude Code {{count}} 件のセッション",
+ "sourceCodex_other": "Codex {{count}} 件のセッション",
+ "moreProjects": "ほか {{count}} 件",
+ "hideMoreProjects": "閉じる",
+ "grant": "{{name}} は {{project}} の{{scope}}を確認・続行・停止でき、新しいセッションも代わりに始めます。",
+ "grantTasks_other": "{{count}} 件のセッション",
+ "grantCindy_other": "Cindy の {{count}} 件のセッション",
+ "grantClaude_other": "Claude Code の {{count}} 件のセッション",
+ "grantCodex_other": "Codex の {{count}} 件のセッション",
+ "grantAutomations_other": "{{count}} 件の自動化",
+ "grantEverything": "セッションと自動化",
+ "handOver": "{{name}} に任せる",
+ "handoverMessage": "{{project}} を任せます。",
+ "addProject": "{{name}} に別のプロジェクトを任せる",
+ "removeProject": "{{project}} を {{name}} から外す",
+ "dirMissing": "フォルダーが見つかりません",
+ "dirUnavailable": "このフォルダーを開けません。別のフォルダーを選んでください。",
+ "tooManyDirs": "{{name}} に任せられるプロジェクトは最大 {{count}} 件です",
+ "sendFailed": "{{name}} に送信できませんでした。もう一度お試しください。",
+ "tasksEmpty": "続けるべきセッションはまだありません。",
+ "understanding": "{{name}} が {{project}} を把握しています…",
+ "untitled": "無題のセッション",
+ "continueMessage": "「{{title}}」を続けて:{{text}}",
+ "verdict": {
+ "unfinished": "未完了",
+ "idea": "話したまま"
+ },
+ "detail": {
+ "back": "ワークベンチに戻る",
+ "stop": "このセッションを停止",
+ "openInTasks": "セッション画面で開く",
+ "placeholder": "{{name}} に続けてもらう一言…",
+ "send": "送信",
+ "sent": "{{name}} に伝えました",
+ "judgment": "{{name}} の見立て",
+ "empty": "表示できる内容はまだありません。",
+ "loadFailed": "このセッションの記録を読み込めません。",
+ "truncated": "最近の内容のみ表示しています",
+ "ref": "参考",
+ "noRef": "参考リンクはありません。",
+ "openPr": "GitHub で PR #{{number}} を開く",
+ "refBlocked": "このパスは任せたプロジェクトの外にあるため開きませんでした。"
+ },
+ "openTask": "「{{title}}」を開く({{state}})",
+ "outputs": "成果物",
+ "outputsEmpty": "{{name}} が作ったファイルはここに表示されます。",
+ "state": {
+ "running": "実行中",
+ "waiting": "返信待ち",
+ "queued": "待機中",
+ "stopped": "停止中",
+ "automation": "自動化",
+ "done": "完了"
+ },
+ "group": {
+ "waiting": "返信待ち",
+ "running": "実行中",
+ "todo": "やること",
+ "done": "完了"
+ },
+ "followUp": {
+ "label": "進める",
+ "message": "「{{title}}」を進めて",
+ "aria": "「{{title}}」を進める"
+ },
+ "olderCount_other": "さらに前の {{count}} 件",
+ "kind": {
+ "existing": "既存のセッション",
+ "delegated": "あなたの依頼",
+ "claudeCode": "Claude Code から",
+ "codex": "Codex から",
+ "pi": "Pi から",
+ "pr": "PR #{{number}}",
+ "issue": "Issue #{{number}}",
+ "idea": "提案",
+ "automationPlain": "自動化"
+ },
+ "cycle": {
+ "manual": "手動",
+ "once": "1 回",
+ "event": "イベント時"
+ },
+ "line": {
+ "waiting": "あなたの返信を待っています",
+ "queued": "待機中",
+ "interrupted": "前回は最後まで実行されませんでした",
+ "errored": "前回エラーが発生しました",
+ "failed": "完了しませんでした",
+ "paused": "一時停止中",
+ "disabled": "オフ"
+ }
+ },
"remoteSettings": {
"empty": "まだ項目がありません。",
"loadFailed": "設定を読み込めませんでした。再試行してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8d6cd7fe2e..4a6ad670b4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7796,6 +7796,110 @@
}
},
"bots": {
+ "workbench": {
+ "title": "작업대",
+ "open": "워크벤치 열기",
+ "emptyTitle": "{{name}}에게 프로젝트 맡기기",
+ "emptyDescription": "컴퓨터에 있는 작업을 {{name}}에게 넘겨 이어서 하게 합니다. 먼저 프로젝트의 문서, 최근 커밋과 PR, 지난 세션을 살펴보고, 끝나지 않았거나 해 볼 만한 것을 골라낸 뒤 무엇을 이어서 할지 물어봅니다.",
+ "scanning": "컴퓨터에서 프로젝트를 찾는 중…",
+ "noProjects": "세션이 있는 프로젝트가 아직 없습니다. 폴더를 골라 {{name}}에게 맡길 수 있습니다.",
+ "pickFolder": "다른 폴더 선택",
+ "cancelAdd": "취소",
+ "projectTasks_other": "세션 {{count}}개",
+ "projectAutomations_other": "자동화 {{count}}개",
+ "sourceCindy_other": "Cindy 세션 {{count}}개",
+ "sourceClaude_other": "Claude Code 세션 {{count}}개",
+ "sourceCodex_other": "Codex 세션 {{count}}개",
+ "moreProjects": "{{count}}개 더 보기",
+ "hideMoreProjects": "접기",
+ "grant": "{{name}}은(는) {{project}}의 {{scope}}을(를) 보고, 이어서 하고, 멈출 수 있으며 새 세션도 대신 시작합니다.",
+ "grantTasks_other": "세션 {{count}}개",
+ "grantCindy_other": "Cindy 세션 {{count}}개",
+ "grantClaude_other": "Claude Code 세션 {{count}}개",
+ "grantCodex_other": "Codex 세션 {{count}}개",
+ "grantAutomations_other": "자동화 {{count}}개",
+ "grantEverything": "세션과 자동화",
+ "handOver": "{{name}}에게 맡기기",
+ "handoverMessage": "{{project}}을(를) 맡길게요.",
+ "addProject": "{{name}}에게 다른 프로젝트 맡기기",
+ "removeProject": "{{name}}에게서 {{project}} 돌려받기",
+ "dirMissing": "폴더를 찾을 수 없습니다",
+ "dirUnavailable": "이 폴더를 열 수 없습니다. 다른 폴더를 선택하세요.",
+ "tooManyDirs": "{{name}}에게는 프로젝트를 최대 {{count}}개까지 맡길 수 있습니다",
+ "sendFailed": "{{name}}에게 보내지 못했습니다. 다시 시도하세요.",
+ "tasksEmpty": "이어서 할 세션이 아직 없습니다.",
+ "understanding": "{{name}}이(가) {{project}}을(를) 파악하는 중…",
+ "untitled": "제목 없는 세션",
+ "continueMessage": "‘{{title}}’ 이어서: {{text}}",
+ "verdict": {
+ "unfinished": "미완료",
+ "idea": "후속 없음"
+ },
+ "detail": {
+ "back": "작업대로 돌아가기",
+ "stop": "이 세션 중지",
+ "openInTasks": "세션 화면에서 열기",
+ "placeholder": "{{name}}에게 이어서 하도록 한마디…",
+ "send": "보내기",
+ "sent": "{{name}}에게 전했습니다",
+ "judgment": "{{name}}의 판단",
+ "empty": "아직 표시할 내용이 없습니다.",
+ "loadFailed": "이 세션의 기록을 읽을 수 없습니다.",
+ "truncated": "최근 내용만 표시합니다",
+ "ref": "참고",
+ "noRef": "첨부된 참고 링크가 없습니다.",
+ "openPr": "GitHub에서 PR #{{number}} 열기",
+ "refBlocked": "맡긴 프로젝트 밖의 경로라서 열지 않았습니다."
+ },
+ "openTask": "‘{{title}}’ 열기({{state}})",
+ "outputs": "결과물",
+ "outputsEmpty": "{{name}}이(가) 만든 파일이 여기에 표시됩니다.",
+ "state": {
+ "running": "실행 중",
+ "waiting": "응답 대기",
+ "queued": "대기 중",
+ "stopped": "멈춤",
+ "automation": "자동화",
+ "done": "완료"
+ },
+ "group": {
+ "waiting": "응답 대기",
+ "running": "실행 중",
+ "todo": "할 일",
+ "done": "완료"
+ },
+ "followUp": {
+ "label": "진행",
+ "message": "「{{title}}」 이어서 진행해 줘",
+ "aria": "「{{title}}」 진행하기"
+ },
+ "olderCount_other": "이전 {{count}}개",
+ "kind": {
+ "existing": "기존 세션",
+ "delegated": "요청한 일",
+ "claudeCode": "Claude Code에서",
+ "codex": "Codex에서",
+ "pi": "Pi에서",
+ "pr": "PR #{{number}}",
+ "issue": "Issue #{{number}}",
+ "idea": "제안",
+ "automationPlain": "자동화"
+ },
+ "cycle": {
+ "manual": "수동",
+ "once": "1회",
+ "event": "이벤트 발생 시"
+ },
+ "line": {
+ "waiting": "응답을 기다리는 중",
+ "queued": "대기 중",
+ "interrupted": "지난번 실행이 끝나지 않았습니다",
+ "errored": "지난번 실행에서 오류가 났습니다",
+ "failed": "끝내지 못했습니다",
+ "paused": "일시 중지됨",
+ "disabled": "꺼짐"
+ }
+ },
"remoteSettings": {
"empty": "아직 항목이 없습니다.",
"loadFailed": "설정을 불러오지 못했습니다. 다시 시도하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index d5c41d3762..cfa69ebfeb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7796,6 +7796,110 @@
}
},
"bots": {
+ "workbench": {
+ "title": "工作台",
+ "open": "打开工作台",
+ "emptyTitle": "交给{{name}}一个项目",
+ "emptyDescription": "把电脑里已有的活交给{{name}}接着做。它会先看一遍项目的文档、最近的提交和 PR、做过的任务,挑出没做完和值得做的,再问你接着做哪件。",
+ "scanning": "正在查找电脑上的项目…",
+ "noProjects": "还没找到有任务的项目,可以选一个文件夹交给{{name}}。",
+ "pickFolder": "选其他文件夹",
+ "cancelAdd": "取消",
+ "projectTasks_other": "{{count}} 个任务",
+ "projectAutomations_other": "{{count}} 个自动化",
+ "sourceCindy_other": "Cindy {{count}} 个任务",
+ "sourceClaude_other": "Claude Code {{count}} 个任务",
+ "sourceCodex_other": "Codex {{count}} 个任务",
+ "moreProjects": "还有 {{count}} 个",
+ "hideMoreProjects": "收起",
+ "grant": "{{name}}可以查看、继续和停止 {{project}} 里的{{scope}},也会替你开新任务。",
+ "grantTasks_other": "{{count}} 个任务",
+ "grantCindy_other": "Cindy 的 {{count}} 个任务",
+ "grantClaude_other": "Claude Code 的 {{count}} 个任务",
+ "grantCodex_other": "Codex 的 {{count}} 个任务",
+ "grantAutomations_other": "{{count}} 个自动化",
+ "grantEverything": "任务和自动化",
+ "handOver": "交给{{name}}",
+ "handoverMessage": "把 {{project}} 交给你了。",
+ "addProject": "再交给{{name}}一个项目",
+ "removeProject": "不再交给{{name}}:{{project}}",
+ "dirMissing": "找不到这个文件夹",
+ "dirUnavailable": "这个文件夹打不开,换一个试试",
+ "tooManyDirs": "最多交给{{name}} {{count}} 个项目",
+ "sendFailed": "没能发给{{name}},请重试",
+ "tasksEmpty": "还没有需要接着做的任务。",
+ "understanding": "{{name}}正在了解 {{project}}…",
+ "untitled": "未命名任务",
+ "continueMessage": "接着做「{{title}}」:{{text}}",
+ "verdict": {
+ "unfinished": "没做完",
+ "idea": "聊过没下文"
+ },
+ "detail": {
+ "back": "返回工作台",
+ "stop": "停止这件任务",
+ "openInTasks": "在任务页打开",
+ "placeholder": "补一句,让{{name}}接着做…",
+ "send": "发送",
+ "sent": "已经告诉{{name}}了",
+ "judgment": "{{name}}的判断",
+ "empty": "还没有可显示的内容。",
+ "loadFailed": "读不到这件任务的记录。",
+ "truncated": "只显示最近的内容",
+ "ref": "参考",
+ "noRef": "没有附参考链接。",
+ "openPr": "在 GitHub 打开 PR #{{number}}",
+ "refBlocked": "这个路径不在交给伙伴的项目里,没有打开。"
+ },
+ "openTask": "打开「{{title}}」({{state}})",
+ "outputs": "产出",
+ "outputsEmpty": "{{name}}做出的文件会放在这里。",
+ "state": {
+ "running": "在做",
+ "waiting": "等你",
+ "queued": "排队",
+ "stopped": "停着",
+ "automation": "自动化",
+ "done": "做完"
+ },
+ "group": {
+ "waiting": "等你",
+ "running": "在做",
+ "todo": "待做",
+ "done": "做完"
+ },
+ "followUp": {
+ "label": "跟进",
+ "message": "跟进「{{title}}」",
+ "aria": "跟进「{{title}}」"
+ },
+ "olderCount_other": "更早的 {{count}} 个",
+ "kind": {
+ "existing": "原有任务",
+ "delegated": "你交代的",
+ "claudeCode": "来自 Claude Code",
+ "codex": "来自 Codex",
+ "pi": "来自 Pi",
+ "pr": "PR #{{number}}",
+ "issue": "Issue #{{number}}",
+ "idea": "建议",
+ "automationPlain": "自动化"
+ },
+ "cycle": {
+ "manual": "手动",
+ "once": "一次",
+ "event": "事件触发"
+ },
+ "line": {
+ "waiting": "等你回复",
+ "queued": "排队中",
+ "interrupted": "上次没跑完",
+ "errored": "上次出错了",
+ "failed": "没做完",
+ "paused": "已暂停",
+ "disabled": "已停用"
+ }
+ },
"remoteSettings": {
"empty": "暂无内容",
"loadFailed": "无法读取设置,请重试。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 590cb06913..6224bd5376 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7796,6 +7796,110 @@
}
},
"bots": {
+ "workbench": {
+ "title": "工作台",
+ "open": "打開工作台",
+ "emptyTitle": "交給{{name}}一個專案",
+ "emptyDescription": "把電腦裡已有的工作交給{{name}}接著做。它會先看一遍專案的文件、最近的提交和 PR、做過的任務,挑出沒做完和值得做的,再問你接著做哪件。",
+ "scanning": "正在尋找電腦上的專案…",
+ "noProjects": "還沒找到有任務的專案,可以選一個資料夾交給{{name}}。",
+ "pickFolder": "選其他資料夾",
+ "cancelAdd": "取消",
+ "projectTasks_other": "{{count}} 個任務",
+ "projectAutomations_other": "{{count}} 個自動化",
+ "sourceCindy_other": "Cindy {{count}} 個任務",
+ "sourceClaude_other": "Claude Code {{count}} 個任務",
+ "sourceCodex_other": "Codex {{count}} 個任務",
+ "moreProjects": "還有 {{count}} 個",
+ "hideMoreProjects": "收起",
+ "grant": "{{name}}可以查看、繼續和停止 {{project}} 裡的{{scope}},也會替你開新任務。",
+ "grantTasks_other": "{{count}} 個任務",
+ "grantCindy_other": "Cindy 的 {{count}} 個任務",
+ "grantClaude_other": "Claude Code 的 {{count}} 個任務",
+ "grantCodex_other": "Codex 的 {{count}} 個任務",
+ "grantAutomations_other": "{{count}} 個自動化",
+ "grantEverything": "任務和自動化",
+ "handOver": "交給{{name}}",
+ "handoverMessage": "把 {{project}} 交給你了。",
+ "addProject": "再交給{{name}}一個專案",
+ "removeProject": "不再交給{{name}}:{{project}}",
+ "dirMissing": "找不到這個資料夾",
+ "dirUnavailable": "這個資料夾打不開,換一個試試",
+ "tooManyDirs": "最多交給{{name}} {{count}} 個專案",
+ "sendFailed": "沒能傳給{{name}},請重試",
+ "tasksEmpty": "還沒有需要接著做的任務。",
+ "understanding": "{{name}}正在了解 {{project}}…",
+ "untitled": "未命名任務",
+ "continueMessage": "接著做「{{title}}」:{{text}}",
+ "verdict": {
+ "unfinished": "沒做完",
+ "idea": "聊過沒下文"
+ },
+ "detail": {
+ "back": "返回工作台",
+ "stop": "停止這件任務",
+ "openInTasks": "在任務頁開啟",
+ "placeholder": "補一句,讓{{name}}接著做…",
+ "send": "傳送",
+ "sent": "已經告訴{{name}}了",
+ "judgment": "{{name}}的判斷",
+ "empty": "還沒有可顯示的內容。",
+ "loadFailed": "讀不到這件任務的記錄。",
+ "truncated": "只顯示最近的內容",
+ "ref": "參考",
+ "noRef": "沒有附參考連結。",
+ "openPr": "在 GitHub 開啟 PR #{{number}}",
+ "refBlocked": "這個路徑不在交給夥伴的專案裡,沒有開啟。"
+ },
+ "openTask": "開啟「{{title}}」({{state}})",
+ "outputs": "產出",
+ "outputsEmpty": "{{name}}做出的檔案會放在這裡。",
+ "state": {
+ "running": "在做",
+ "waiting": "等你",
+ "queued": "排隊",
+ "stopped": "停著",
+ "automation": "自動化",
+ "done": "做完"
+ },
+ "group": {
+ "waiting": "等你",
+ "running": "在做",
+ "todo": "待做",
+ "done": "做完"
+ },
+ "followUp": {
+ "label": "跟進",
+ "message": "跟進「{{title}}」",
+ "aria": "跟進「{{title}}」"
+ },
+ "olderCount_other": "更早的 {{count}} 個",
+ "kind": {
+ "existing": "原有任務",
+ "delegated": "你交代的",
+ "claudeCode": "來自 Claude Code",
+ "codex": "來自 Codex",
+ "pi": "來自 Pi",
+ "pr": "PR #{{number}}",
+ "issue": "Issue #{{number}}",
+ "idea": "建議",
+ "automationPlain": "自動化"
+ },
+ "cycle": {
+ "manual": "手動",
+ "once": "一次",
+ "event": "事件觸發"
+ },
+ "line": {
+ "waiting": "等你回覆",
+ "queued": "排隊中",
+ "interrupted": "上次沒跑完",
+ "errored": "上次出錯了",
+ "failed": "沒做完",
+ "paused": "已暫停",
+ "disabled": "已停用"
+ }
+ },
"remoteSettings": {
"empty": "暫無內容",
"loadFailed": "無法讀取設定,請重試。",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 1f24b24a05..cb223c9086 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4783,6 +4783,36 @@ interface ElectronAPI {
session: import('@/lib/ccAgent.types').Session;
}>;
history: (botId: string) => Promise<unknown[]>;
+ workbench: {
+ get: (botId: string) => Promise<import('../shared/botWorkbench').BotWorkbench | null>;
+ addDirectory: (
+ botId: string,
+ path: string,
+ ) => Promise<{ ok: true } | { ok: false; errorCode: 'NOT_A_DIRECTORY' | 'TOO_MANY' }>;
+ removeDirectory: (botId: string, path: string) => Promise<void>;
+ readTask: (
+ botId: string,
+ taskId: string,
+ ) => Promise<
+ | { ok: true; taskId: string; transcript: import('../shared/botWorkbench').WorkbenchTranscript }
+ | { ok: false; errorCode: string; message: string }
+ >;
+ candidates: (
+ botId: string,
+ ) => Promise<
+ | {
+ ok: true;
+ candidates: Array<{
+ source: 'claude' | 'codex' | 'pi';
+ id: string;
+ projectDir: string | null;
+ updatedAt: string;
+ archived: boolean;
+ }>;
+ }
+ | { ok: false; errorCode: string; message: string }
+ >;
+ };
listSkills: (botId: string) => Promise<import('../shared/botSkill').BotSkillSummary[]>;
memory: {
list: (
@@ -4926,6 +4956,10 @@ interface ElectronAPI {
existing: number;
};
currentProjectDirs: string[];
+ /** 候选与本机已有项目里是 git 仓库的目录。 */
+ gitRepoDirs?: string[];
+ /** 主目录、应用数据目录、系统临时目录(伙伴工作台过滤非项目目录用)。 */
+ pathHints?: { homeDir: string | null; userDataDir: string | null; tempDirs: string[] };
}>;
importSelected: (
items: Array<{ source: 'codex' | 'claude'; id: string }>,
@@ -5320,6 +5354,7 @@ interface ElectronAPI {
onBotProfileChanged: (
cb: (payload: { botId: string; change: 'created' | 'updated' }) => void,
) => () => void;
+ onBotWorkbenchChanged: (cb: (payload: { botId: string }) => void) => () => void;
runBotLifecycleAction: (
request: import('../shared/botLifecycle').BotLifecycleActionRequest,
) => Promise<import('../shared/botLifecycle').BotLifecycleActionResult>;
diff --git a/apps/desktop/src/shared/__tests__/botWorkbench.test.ts b/apps/desktop/src/shared/__tests__/botWorkbench.test.ts
new file mode 100644
index 0000000000..be9d72c2e0
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/botWorkbench.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ boundWorkbenchSummary,
+ buildWorkbenchDigest,
+ canonicalWorkbenchTaskId,
+ cleanWorkbenchTitle,
+ validateWorkbenchRef,
+ externalWorkbenchTaskId,
+ parseWorkbenchTaskId,
+ deriveWorkbenchAutomationState,
+ deriveWorkbenchSessionState,
+ findWorkbenchProject,
+ importedSessionOrigin,
+ isWorkbenchTaskSource,
+} from '../botWorkbench';
+
+describe('deriveWorkbenchSessionState', () => {
+ it('maps live activity to running / waiting', () => {
+ expect(deriveWorkbenchSessionState({ activityPhase: 'running' })).toBe('running');
+ expect(deriveWorkbenchSessionState({ activityPhase: 'needs-interaction' })).toBe('waiting');
+ // Waiting for the user wins over a turn that is technically still running.
+ expect(deriveWorkbenchSessionState({ activityPhase: 'needs-interaction', delegationStatus: 'running' })).toBe('waiting');
+ });
+
+ it('only reports stopped on a reliable signal', () => {
+ expect(deriveWorkbenchSessionState({ interrupted: true })).toBe('stopped');
+ expect(deriveWorkbenchSessionState({ errored: true })).toBe('stopped');
+ expect(deriveWorkbenchSessionState({ activityPhase: 'error' })).toBe('stopped');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'failed' })).toBe('stopped');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'timed-out' })).toBe('stopped');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'cancelled' })).toBe('stopped');
+ // Idle with no evidence is not guessed as unfinished.
+ expect(deriveWorkbenchSessionState({})).toBe('done');
+ expect(deriveWorkbenchSessionState({ activityPhase: 'completed' })).toBe('done');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'completed' })).toBe('done');
+ });
+
+ it('keeps background-task queue and progress ahead of stale session signals', () => {
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'queued', errored: true })).toBe('queued');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'waiting' })).toBe('waiting');
+ expect(deriveWorkbenchSessionState({ delegationStatus: 'running', interrupted: true })).toBe('running');
+ // A new running turn replaces an old interruption.
+ expect(deriveWorkbenchSessionState({ activityPhase: 'running', interrupted: true })).toBe('running');
+ });
+});
+
+describe('deriveWorkbenchAutomationState', () => {
+ it('distinguishes running, queued, disabled and standing by', () => {
+ expect(deriveWorkbenchAutomationState({ enabled: true, running: true })).toBe('running');
+ expect(deriveWorkbenchAutomationState({ enabled: true, queued: true })).toBe('queued');
+ expect(deriveWorkbenchAutomationState({ enabled: false })).toBe('stopped');
+ expect(deriveWorkbenchAutomationState({ enabled: true })).toBe('automation');
+ });
+});
+
+describe('project membership', () => {
+ it('matches the project, its subdirectories and managed worktrees, but not a sibling with the same prefix', () => {
+ const dirs = ['/Users/me/Code/cindy'];
+ expect(findWorkbenchProject('/Users/me/Code/cindy/', dirs, false)).toBe('/Users/me/Code/cindy');
+ expect(findWorkbenchProject('/Users/me/Code/cindy/.cindy-worktrees/fix', dirs, false)).toBe('/Users/me/Code/cindy');
+ expect(findWorkbenchProject('/Users/me/Code/cindy/apps/desktop', dirs, false)).toBe('/Users/me/Code/cindy');
+ expect(findWorkbenchProject('/Users/me/Code/cindy-old', dirs, false)).toBeNull();
+ expect(findWorkbenchProject('/Users/me/Code', dirs, false)).toBeNull();
+ expect(findWorkbenchProject(null, dirs, false)).toBeNull();
+ });
+
+ it('picks the deepest handed-over project when projects are nested', () => {
+ const dirs = ['/Users/me/Code/cindy', '/Users/me/Code/cindy/apps/mobile'];
+ expect(findWorkbenchProject('/Users/me/Code/cindy/apps/mobile/src', dirs, false)).toBe('/Users/me/Code/cindy/apps/mobile');
+ expect(findWorkbenchProject('/Users/me/Code/cindy/apps/desktop', dirs, false)).toBe('/Users/me/Code/cindy');
+ });
+
+ it('folds case for Windows paths only when asked', () => {
+ expect(findWorkbenchProject('C:\\Code\\Cindy', ['c:/code/cindy'], true)).toBe('c:/code/cindy');
+ expect(findWorkbenchProject('C:\\Code\\Cindy', ['c:/code/cindy'], false)).toBeNull();
+ });
+});
+
+describe('helpers', () => {
+ it('recognizes imported sessions only by prefix and engine together', () => {
+ expect(importedSessionOrigin('claude-123', 'cc')).toBe('claude-code');
+ expect(importedSessionOrigin('codex-123', 'codex')).toBe('codex');
+ expect(importedSessionOrigin('claude-123', 'codex')).toBeNull();
+ expect(importedSessionOrigin('abc', 'cc')).toBeNull();
+ });
+
+ it('accepts only project task sources', () => {
+ expect(isWorkbenchTaskSource('desktop')).toBe(true);
+ expect(isWorkbenchTaskSource('plugin')).toBe(true);
+ expect(isWorkbenchTaskSource(undefined)).toBe(true);
+ for (const source of ['bot', 'scheduler', 'telegram', 'learn', 'review', 'shared']) {
+ expect(isWorkbenchTaskSource(source)).toBe(false);
+ }
+ });
+
+ it('bounds summaries', () => {
+ expect(boundWorkbenchSummary(' a\n\nb ')).toBe('a b');
+ expect(boundWorkbenchSummary('')).toBeNull();
+ expect(boundWorkbenchSummary('x'.repeat(500))).toHaveLength(160);
+ });
+});
+
+describe('cleanWorkbenchTitle', () => {
+ it('drops instruction blocks, markdown and noise, keeping the first readable line', () => {
+ expect(
+ cleanWorkbenchTitle('<system-reminder>\nYou are operating in a git worktree…\n</system-reminder>\n\n## 把 **图标** 导出来\n第二行'),
+ ).toBe('把 图标 导出来');
+ expect(cleanWorkbenchTitle('看看 https://github.com/makecindy/cindy/pull/5292 的 review')).toBe(
+ '看看 github.com/…/pull/5292 的 review',
+ );
+ expect(cleanWorkbenchTitle('[PR](https://github.com/a/b) `fix_icons`')).toBe('PR fix_icons');
+ expect(cleanWorkbenchTitle('- 列表里的一项')).toBe('列表里的一项');
+ });
+
+ it('bounds to 60 characters and falls back when nothing is left', () => {
+ expect(cleanWorkbenchTitle('字'.repeat(80))).toHaveLength(60);
+ expect(cleanWorkbenchTitle('<command-name>/clear</command-name>', '未命名任务')).toBe('未命名任务');
+ expect(cleanWorkbenchTitle(' \n ', '未命名任务')).toBe('未命名任务');
+ expect(cleanWorkbenchTitle(null, '未命名任务')).toBe('未命名任务');
+ });
+});
+
+describe('parseWorkbenchTaskId', () => {
+ it('distinguishes Cindy tasks from local Claude Code / Codex sessions', () => {
+ expect(parseWorkbenchTaskId('claude-abc')).toEqual({ kind: 'session', sessionId: 'claude-abc' });
+ expect(parseWorkbenchTaskId('claude:abc')).toEqual({ kind: 'external', source: 'claude', externalId: 'abc' });
+ expect(parseWorkbenchTaskId('codex:019a-77')).toEqual({ kind: 'external', source: 'codex', externalId: '019a-77' });
+ expect(parseWorkbenchTaskId(' ')).toBeNull();
+ expect(externalWorkbenchTaskId('codex', 't1')).toBe('codex:t1');
+ });
+});
+
+describe('workbench entry ids', () => {
+ it('parses session, Pi, PR, issue and idea ids and keeps a canonical form', () => {
+ expect(parseWorkbenchTaskId('session:abc')).toEqual({ kind: 'session', sessionId: 'abc' });
+ expect(parseWorkbenchTaskId('pi:p-1')).toEqual({ kind: 'external', source: 'pi', externalId: 'p-1' });
+ expect(parseWorkbenchTaskId('pr:makecindy/cindy#5292')).toEqual({
+ kind: 'github', type: 'pr', owner: 'makecindy', repo: 'cindy', number: 5292,
+ });
+ expect(parseWorkbenchTaskId('issue:me/repo.js#7')).toMatchObject({ kind: 'github', type: 'issue', repo: 'repo.js' });
+ expect(parseWorkbenchTaskId('idea:dark-icons')).toEqual({ kind: 'idea', slug: 'dark-icons' });
+ for (const id of ['pr:cindy#1', 'pr:a/b#x', 'issue:a b/c#1', 'idea:ab', 'idea:Dark', `idea:${'a'.repeat(41)}`]) {
+ expect(parseWorkbenchTaskId(id)).toBeNull();
+ }
+ expect(canonicalWorkbenchTaskId(parseWorkbenchTaskId('session:abc')!)).toBe('abc');
+ expect(canonicalWorkbenchTaskId(parseWorkbenchTaskId('pr:a/b#3')!)).toBe('pr:a/b#3');
+ });
+});
+
+describe('validateWorkbenchRef', () => {
+ const projects = ['/Users/me/Code/app'];
+ it('accepts https links and paths inside a handed-over project', () => {
+ expect(validateWorkbenchRef('https://github.com/a/b/pull/1', projects, false)).toEqual({
+ ok: true, ref: 'https://github.com/a/b/pull/1',
+ });
+ expect(validateWorkbenchRef('/Users/me/Code/app/docs/DESIGN.md', projects, false)).toEqual({
+ ok: true, ref: '/Users/me/Code/app/docs/DESIGN.md',
+ });
+ expect(validateWorkbenchRef('/users/me/code/APP/README.md', projects, true)).toMatchObject({ ok: true });
+ });
+ it.each([
+ 'http://example.com',
+ 'javascript:alert(1)',
+ 'file:///etc/passwd',
+ 'https://user:[email protected]',
+ '/etc/passwd',
+ '/Users/me/Code/app-old/x.md',
+ '/Users/me/Code/app/../secret',
+ 'docs/DESIGN.md',
+ '',
+ ])('rejects %s', (ref) => {
+ expect(validateWorkbenchRef(ref, projects, false)).toEqual({ ok: false });
+ });
+});
+
+describe('buildWorkbenchDigest', () => {
+ it('takes the first user message as purpose and the last three messages, both bounded', () => {
+ const head = [
+ { role: 'assistant' as const, text: 'hi', at: 1 },
+ { role: 'user' as const, text: `<system-reminder>x</system-reminder> 把图标 导出来 ${'a'.repeat(400)}`, at: 2 },
+ ];
+ const tail = [
+ { role: 'user' as const, text: 'one', at: 3 },
+ { role: 'assistant' as const, text: 'two', at: 4 },
+ { role: 'assistant' as const, text: '<system-reminder>only</system-reminder>', at: 5 },
+ { role: 'user' as const, text: 'three', at: 6 },
+ { role: 'assistant' as const, text: 'b'.repeat(500), at: 7 },
+ ];
+ const digest = buildWorkbenchDigest(head, tail);
+ expect(digest.purpose!.startsWith('把图标 导出来')).toBe(true);
+ expect(digest.purpose!.length).toBeLessThanOrEqual(200);
+ expect(digest.recent.map((item) => item.text.slice(0, 5))).toEqual(['two', 'three', 'bbbbb']);
+ expect(digest.recent[2]!.text.length).toBeLessThanOrEqual(300);
+ expect(buildWorkbenchDigest([], [])).toEqual({ purpose: null, recent: [] });
+ });
+});
diff --git a/apps/desktop/src/shared/botWorkbench.ts b/apps/desktop/src/shared/botWorkbench.ts
new file mode 100644
index 0000000000..2af5c6c414
--- /dev/null
+++ b/apps/desktop/src/shared/botWorkbench.ts
@@ -0,0 +1,379 @@
+/**
+ * 伙伴工作台:主进程与渲染层共用的数据形状与纯推导。
+ *
+ * 工作台上的每一条都是一件事:Cindy 任务、本机外部会话、PR / issue / 建议或自动化。状态只从
+ * 宿主已有的真实信号推导——运行中、等待交互、上一轮出错或被打断、后台任务状态、自动化的启停
+ * 与运行——不经过模型,也不另存一份状态。主进程(伙伴读取工作台的工具)和渲染层(右侧栏的
+ * 任务列表)共用这里的同一套规则(状态推导、标题清洗、条目 id、参考校验、摘要),两边说法一致。
+ */
+import { normalizeWorkingDirForGrouping, normalizeWorkingDirForStorage } from './workingDir';
+
+/** 主人最多交给一个伙伴几个项目;与存储层的上限同源。 */
+export const BOT_WORKBENCH_MAX_DIRECTORIES = 6;
+
+/** 主人交给伙伴的项目目录。目录本身由宿主记录,`exists` 是读取时现查的事实。 */
+export interface BotWorkbenchDirectory {
+ path: string;
+ name: string;
+ addedAt: string;
+ exists: boolean;
+}
+
+/**
+ * 伙伴对一件候选任务的理解:读过之后写下的人话标题、判断与下一步。
+ * - unfinished:没做完、可以接着做;
+ * - idea:聊过但没下文,建议往下做;
+ * - done:做完了,或与项目无关。工作台不显示。
+ */
+export type WorkbenchVerdict = 'unfinished' | 'idea' | 'done';
+
+export interface WorkbenchTaskJudgment {
+ title: string;
+ verdict: WorkbenchVerdict;
+ /** 一句「下一步」;done 可为空。 */
+ next: string | null;
+ /** 写判断时这件任务所在的已接手项目目录(移除项目后据此隐藏)。 */
+ project: string;
+ /** 可选的参考:https 链接,或已接手项目内的文件路径。 */
+ ref?: string | null;
+ updatedAt: string;
+}
+
+export const WORKBENCH_REF_MAX = 2_000;
+
+export interface BotWorkbench {
+ directories: BotWorkbenchDirectory[];
+ /** 按 task_id 记录的伙伴判断。 */
+ tasks: Record<string, WorkbenchTaskJudgment>;
+}
+
+/** 一件任务最近内容的只读摘录(工具与详情视图共用)。 */
+export interface WorkbenchTranscriptItem {
+ role: 'user' | 'assistant';
+ text: string;
+ at: number;
+}
+
+export interface WorkbenchTranscript {
+ items: WorkbenchTranscriptItem[];
+ truncated: boolean;
+}
+
+/** 一件会话候选的摘要:起始目的 + 最后几条,宿主预先算好,伙伴先凭它判断。 */
+export interface WorkbenchDigest {
+ /** 第一条用户消息,清洗后 ≤ 200 字。 */
+ purpose: string | null;
+ /** 最后 2–3 条用户 / 助手文字,各 ≤ 300 字,按时间正序。 */
+ recent: Array<{ role: 'user' | 'assistant'; text: string }>;
+}
+
+export const WORKBENCH_DIGEST_PURPOSE_MAX = 200;
+export const WORKBENCH_DIGEST_RECENT_MAX = 300;
+export const WORKBENCH_DIGEST_RECENT_COUNT = 3;
+
+function clip(text: string, max: number): string {
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
+}
+
+function flatten(text: string): string {
+ return stripInstructionBlocks(text).replace(/\s+/g, ' ').trim();
+}
+
+/**
+ * 由按时间正序的消息算摘要。`head` 是从开头读到的一段(取第一条用户消息),
+ * `tail` 是从结尾读到的一段(取最后几条);两段可以重叠或相同。
+ */
+export function buildWorkbenchDigest(
+ head: readonly WorkbenchTranscriptItem[],
+ tail: readonly WorkbenchTranscriptItem[],
+): WorkbenchDigest {
+ const firstUser = head.map((item) => (item.role === 'user' ? flatten(item.text) : '')).find(Boolean) ?? null;
+ const recent: WorkbenchDigest['recent'] = [];
+ for (let index = tail.length - 1; index >= 0 && recent.length < WORKBENCH_DIGEST_RECENT_COUNT; index -= 1) {
+ const text = flatten(tail[index].text);
+ if (text) recent.unshift({ role: tail[index].role, text: clip(text, WORKBENCH_DIGEST_RECENT_MAX) });
+ }
+ return { purpose: firstUser ? clip(firstUser, WORKBENCH_DIGEST_PURPOSE_MAX) : null, recent };
+}
+
+/** 只看近期:最近 30 天内活动过的候选才读摘要。 */
+export const WORKBENCH_RECENT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
+
+export const WORKBENCH_JUDGMENT_TITLE_MAX = 40;
+export const WORKBENCH_JUDGMENT_NEXT_MAX = 120;
+export const WORKBENCH_MAX_JUDGMENTS = 200;
+
+/**
+ * 工作台任务 id:Cindy 任务就是 session id;还没导入的本机外部会话带来源前缀,
+ * `claude:<sdkSessionId>` / `codex:<threadId>`。
+ */
+export type WorkbenchTaskRef =
+ | { kind: 'session'; sessionId: string }
+ | { kind: 'external'; source: 'claude' | 'codex' | 'pi'; externalId: string }
+ | { kind: 'github'; type: 'pr' | 'issue'; owner: string; repo: string; number: number }
+ | { kind: 'idea'; slug: string };
+
+const GITHUB_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,99})$/;
+
+/**
+ * 工作台条目 id:`session:<id>`(或直接 session id)、`claude:<id>`、`codex:<id>`、`pi:<id>`、
+ * `pr:<owner>/<repo>#<n>`、`issue:<owner>/<repo>#<n>`、`idea:<slug>`(slug 为 3–40 位小写字母、
+ * 数字与连字符)。格式不对返回 null。
+ */
+export function parseWorkbenchTaskId(taskId: string): WorkbenchTaskRef | null {
+ const id = taskId.trim();
+ if (!id || id.length > 256) return null;
+ const external = /^(claude|codex|pi):(.+)$/.exec(id);
+ if (external) return { kind: 'external', source: external[1] as 'claude' | 'codex' | 'pi', externalId: external[2] };
+ const github = /^(pr|issue):([^/\s]+)\/([^#\s]+)#(\d{1,9})$/.exec(id);
+ if (github) {
+ if (!GITHUB_NAME.test(github[2]) || !GITHUB_NAME.test(github[3])) return null;
+ return { kind: 'github', type: github[1] as 'pr' | 'issue', owner: github[2], repo: github[3], number: Number(github[4]) };
+ }
+ if (/^(pr|issue):/.test(id)) return null;
+ const idea = /^idea:(.*)$/.exec(id);
+ if (idea) return /^[a-z0-9-]{3,40}$/.test(idea[1]) ? { kind: 'idea', slug: idea[1] } : null;
+ const session = /^session:(.+)$/.exec(id);
+ return { kind: 'session', sessionId: session ? session[1] : id };
+}
+
+/** 判断存储与界面里用的规范 id:Cindy 任务用裸 session id,其它原样。 */
+export function canonicalWorkbenchTaskId(ref: WorkbenchTaskRef): string {
+ if (ref.kind === 'session') return ref.sessionId;
+ if (ref.kind === 'external') return `${ref.source}:${ref.externalId}`;
+ if (ref.kind === 'github') return `${ref.type}:${ref.owner}/${ref.repo}#${ref.number}`;
+ return `idea:${ref.slug}`;
+}
+
+/**
+ * 参考校验:只接受 https 链接,或落在某个已接手项目目录内的绝对路径(不允许 `..` 越界)。
+ * 通过时返回规整后的值。
+ */
+export function validateWorkbenchRef(
+ ref: string,
+ projectDirs: readonly string[],
+ caseInsensitive: boolean,
+): { ok: true; ref: string } | { ok: false } {
+ const value = ref.trim();
+ if (!value || value.length > WORKBENCH_REF_MAX) return { ok: false };
+ if (/^https:\/\//i.test(value)) {
+ try {
+ const url = new URL(value);
+ return url.protocol === 'https:' && !url.username && !url.password ? { ok: true, ref: url.toString() } : { ok: false };
+ } catch {
+ return { ok: false };
+ }
+ }
+ const normalized = normalizeWorkingDirForStorage(value);
+ if (!normalized || !/^(\/|[A-Za-z]:\/)/.test(normalized)) return { ok: false };
+ if (normalized.split('/').some((segment) => segment === '..' || segment === '.')) return { ok: false };
+ const key = caseInsensitive ? normalized.toLowerCase() : normalized;
+ const inside = projectDirs.some((dir) => {
+ const root = normalizeWorkingDirForStorage(dir);
+ if (!root) return false;
+ const rootKey = caseInsensitive ? root.toLowerCase() : root;
+ return key === rootKey || key.startsWith(`${rootKey.endsWith('/') ? rootKey.slice(0, -1) : rootKey}/`);
+ });
+ return inside ? { ok: true, ref: normalized } : { ok: false };
+}
+
+export function externalWorkbenchTaskId(source: 'claude' | 'codex' | 'pi', externalId: string): string {
+ return `${source}:${externalId}`;
+}
+
+function shortenUrl(raw: string): string {
+ try {
+ const url = new URL(raw);
+ const segments = url.pathname.split('/').filter(Boolean);
+ const host = url.host.replace(/^www\./, '');
+ if (segments.length === 0) return host;
+ if (segments.length <= 2) return `${host}/${segments.join('/')}`;
+ return `${host}/…/${segments.slice(-2).join('/')}`;
+ } catch {
+ return raw;
+ }
+}
+
+/** 去掉尖括号指令块(如 `<system-reminder>…</system-reminder>`)与残留标签。 */
+export function stripInstructionBlocks(text: string): string {
+ let out = text;
+ for (let pass = 0; pass < 4; pass += 1) {
+ const next = out.replace(/<([A-Za-z][\w-]*)(?:\s[^<>]*)?>[\s\S]*?<\/\1>/g, ' ');
+ if (next === out) break;
+ out = next;
+ }
+ return out.replace(/<\/?[A-Za-z][\w-]*(?:\s[^<>]*)?\/?>/g, ' ');
+}
+
+export const WORKBENCH_TITLE_MAX = 60;
+
+/**
+ * 把一件任务的原始标题(常常是第一条消息原文)整理成能读的一行:去掉指令块、
+ * Markdown 标记与多余空白,URL 只留域名与路径末段,取第一行截到 60 字。
+ * 清洗后为空时返回 `fallback`。
+ */
+export function cleanWorkbenchTitle(raw: string | null | undefined, fallback = ''): string {
+ if (typeof raw !== 'string') return fallback;
+ let text = stripInstructionBlocks(raw);
+ text = text.replace(/\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g, (_all, label: string, url: string) => label.trim() || url);
+ text = text.replace(/https?:\/\/[^\s<>()\]]+/g, (url) => shortenUrl(url));
+ const line = text
+ .split(/\r?\n/)
+ .map((row) =>
+ row
+ .replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/, '')
+ .replace(/`+|\*\*|__|~~/g, '')
+ .replace(/\s+/g, ' ')
+ .trim(),
+ )
+ .find(Boolean);
+ if (!line) return fallback;
+ return line.length > WORKBENCH_TITLE_MAX ? `${line.slice(0, WORKBENCH_TITLE_MAX - 1)}…` : line;
+}
+
+/** 一格任务的状态。`automation` 表示一条正常待命的自动化(下次运行 / 上次结果)。 */
+export type WorkbenchTaskState = 'running' | 'waiting' | 'queued' | 'stopped' | 'automation' | 'done';
+
+/** 一格任务从哪里来:原有任务、伙伴替主人开的后台任务、本机其他工具 / 其它 Cindy 里的会话。 */
+export type WorkbenchTaskOrigin = 'existing' | 'delegated' | 'claude-code' | 'codex' | 'pi';
+
+export type WorkbenchDelegationStatus =
+ | 'queued'
+ | 'running'
+ | 'waiting'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ | 'timed-out';
+
+/**
+ * 推导一件普通任务状态所需的信号。全部来自宿主已有状态:
+ * - `activityPhase`:与侧栏、灵动岛同源的活动快照 phase(running / needs-interaction /
+ * completed / error / idle),没有快照时为 null;
+ * - `interrupted`:上一轮开始后没有结束记录(应用退出等打断),见
+ * `hasPendingSessionInterruption`;
+ * - `errored`:上一轮以错误结束且主人还没处理(侧栏的红点、主进程的终态错误行);
+ * - `delegationStatus`:这件任务是伙伴开的后台任务时,后台任务自己的状态。
+ */
+export interface WorkbenchSessionSignals {
+ activityPhase?: string | null;
+ interrupted?: boolean;
+ errored?: boolean;
+ delegationStatus?: WorkbenchDelegationStatus | null;
+}
+
+/**
+ * 普通任务的状态。优先级:排队 > 等你 > 在做 > 停着 > 做完。
+ *
+ * 「停着」只在有可靠信号时给:上一轮被打断、上一轮出错未处理,或伙伴开的后台任务
+ * 以失败 / 超时 / 取消收尾。其余没有在跑、也没有在等的任务一律算「做完」——宿主
+ * 无法可靠判断一件空闲的任务是否"还差一点",不猜。
+ */
+export function deriveWorkbenchSessionState(signals: WorkbenchSessionSignals): WorkbenchTaskState {
+ const delegation = signals.delegationStatus ?? null;
+ const phase = signals.activityPhase ?? null;
+ if (delegation === 'queued') return 'queued';
+ if (delegation === 'waiting' || phase === 'needs-interaction') return 'waiting';
+ if (delegation === 'running' || phase === 'running') return 'running';
+ if (
+ signals.interrupted === true ||
+ signals.errored === true ||
+ phase === 'error' ||
+ delegation === 'failed' ||
+ delegation === 'timed-out' ||
+ delegation === 'cancelled'
+ ) {
+ return 'stopped';
+ }
+ return 'done';
+}
+
+export interface WorkbenchAutomationSignals {
+ /** 自动化是否启用(伙伴例行任务的 enabled / 普通自动化的 status === 'active')。 */
+ enabled: boolean;
+ running?: boolean;
+ queued?: boolean;
+}
+
+/** 自动化的状态:正在跑 > 排队 > 停用(停着) > 正常待命。 */
+export function deriveWorkbenchAutomationState(signals: WorkbenchAutomationSignals): WorkbenchTaskState {
+ if (signals.running) return 'running';
+ if (signals.queued) return 'queued';
+ if (!signals.enabled) return 'stopped';
+ return 'automation';
+}
+
+/**
+ * 项目身份键:与任务列表的项目分组同一套归一(worktree 归到主仓库、去尾斜杠),
+ * Windows 本机路径忽略大小写。只用于比较,不用于读写文件。
+ */
+export function workbenchProjectKey(
+ dir: string | null | undefined,
+ caseInsensitive: boolean,
+): string | null {
+ const normalized = normalizeWorkingDirForGrouping(dir);
+ if (!normalized) return null;
+ return caseInsensitive ? normalized.toLowerCase() : normalized;
+}
+
+/**
+ * 找出这个工作目录属于哪个已接手的项目:项目目录本身或它下面的任一子目录都算,按目录
+ * 边界比较(`/repo` 不包含 `/repo-old`);同时交了嵌套的项目时取最深的那个。
+ * 不属于任何一个时返回 null。
+ */
+export function findWorkbenchProject(
+ workingDir: string | null | undefined,
+ projectDirs: readonly string[],
+ caseInsensitive: boolean,
+): string | null {
+ const key = workbenchProjectKey(workingDir, caseInsensitive);
+ if (!key) return null;
+ let best: { dir: string; length: number } | null = null;
+ for (const dir of projectDirs) {
+ const root = workbenchProjectKey(dir, caseInsensitive);
+ if (!root) continue;
+ const prefix = root.endsWith('/') ? root : `${root}/`;
+ if (key !== root && !key.startsWith(prefix)) continue;
+ if (!best || root.length > best.length) best = { dir, length: root.length };
+ }
+ return best?.dir ?? null;
+}
+
+/** Windows 本机路径不区分大小写;与 `projectKeyComparisonKey` 的口径一致。 */
+export function isCaseInsensitivePlatform(platform: string | null | undefined): boolean {
+ return platform === 'win32';
+}
+
+/**
+ * 从本机 Claude Code / Codex 导入的任务:导入路径给它们固定的 id 前缀,且只会是对应的
+ * 引擎。二者同时满足才认,避免把普通任务误标成导入的。
+ */
+export function importedSessionOrigin(
+ sessionId: string,
+ agentKind: string | null | undefined,
+): 'claude-code' | 'codex' | null {
+ if (sessionId.startsWith('claude-') && agentKind === 'cc') return 'claude-code';
+ if (sessionId.startsWith('codex-') && agentKind === 'codex') return 'codex';
+ return null;
+}
+
+/**
+ * 能作为工作台任务的会话来源。只认主人自己在项目里开的任务(含插件为项目建的任务、
+ * 从本机工具导入的任务,它们都以 desktop 落库)。自动化的每次运行由自动化那一格代表,
+ * IM 渠道、学习、评审、伙伴自身等来源都不是"项目里的任务"。缺失按 desktop 兼容旧行。
+ */
+export function isWorkbenchTaskSource(source: string | null | undefined): boolean {
+ return source == null || source === 'desktop' || source === 'plugin';
+}
+
+/** 一句摘要的长度上限:格子底部一行、工具返回给伙伴的摘要都用它。 */
+export const WORKBENCH_SUMMARY_MAX_CHARS = 160;
+
+export function boundWorkbenchSummary(text: string | null | undefined): string | null {
+ if (typeof text !== 'string') return null;
+ const flat = text.replace(/\s+/g, ' ').trim();
+ if (!flat) return null;
+ return flat.length > WORKBENCH_SUMMARY_MAX_CHARS
+ ? `${flat.slice(0, WORKBENCH_SUMMARY_MAX_CHARS - 1)}…`
+ : flat;
+}
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index 31cc91c480..ea2770c435 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -40,6 +40,8 @@ export interface RsbWindowContext {
/** main → 子窗口的命令推送(如主窗终端快捷键转发 / detached RSB 内定位文件)。 */
export type RsbWindowCommand =
| { type: 'open-routines-tab'; sessionId: string; botId: string }
+ /** 伙伴主任务页:确保「工作台」标签存在(不存在时创建并展开右侧栏)。 */
+ | { type: 'open-bot-workbench-tab'; sessionId: string; botId: string }
| { type: 'open-terminal'; sessionId: string }
| { type: 'toggle-review-tab'; sessionId: string }
| { type: 'open-web-browser'; sessionId: string; url: string }
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index eac6234ae1..dda5a0be76 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -18,7 +18,7 @@
| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
| `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 |
| `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarSection.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 279 | 41 | 475 |
+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarSection.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 41 | 492 |
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 62 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 2 |
| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 256 | 41 | 357 |
@@ -39,7 +39,7 @@
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 31 | 0 | 59 |
| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 140 | 109 | 555 |
-| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 138 | 46 | 260 |
+| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 138 | 46 | 260 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 39 | 0 | 45 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 47 | 0 | 53 |
| `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |
@@ -48,7 +48,7 @@
| `desktop.window.resource-usage` | desktop | 资源用量窗口 | `?resourceUsageWindow=1` → renderer/resource-usage-entry.tsx(不走 router.tsx) | ResourceUsageWindowLayout, ResourceUsageWindowRoot | apps/desktop/src/main/resource-usage-window/controller.ts, apps/desktop/src/main/resource-usage-window/ipc.ts, apps/desktop/src/main/resource-usage-window/open-sender.ts, apps/desktop/src/main/resource-usage-window/registry.ts, apps/desktop/src/main/resource-usage-window/window.ts, apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx, apps/desktop/src/renderer/resource-usage-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 65 | 38 | 14 |
| `desktop.window.review-artifact-confirm` | desktop | Review 成果确认窗 | main/reviewer/reviewArtifactConfirmWindow.ts 内联 HTML/CSS(不走 renderer 路由) | reviewArtifactConfirmWindow | apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts | 8 | 18 | 2 |
| `desktop.window.session-drag-preview` | desktop | 会话拖拽预览 | main/session-drag-preview.ts 透明预览窗 | session-drag-preview | apps/desktop/src/main/session-drag-preview.ts | 0 | 1 | 0 |
-| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 104 | 45 | 179 |
+| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 104 | 45 | 179 |
| `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 |
| `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 70 | 38 | 19 |
| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ClipboardSharedTaskPrompt, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SharedTaskAdmissionDialog, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SharedTaskAdmissionDialog.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 210 | 62 |
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index ab29cf6cc5..e700832dee 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -263,9 +263,11 @@ harness + provider + model + effort + fastMode
恢复后只生效一次,取消优先撤销暂存回答。恢复依据宿主实际应用回执清理等待状态,
已应用的回答不再通知发起伙伴;确实未答的交互仍重新通知。渠道卡片的回答状态不表示引擎已恢复。
这些模式都只作用于调用伙伴拥有的后台任务;通用 Session control 类不因此开放给伙伴。
+ 主人通过工作台交给伙伴的项目里的原有任务,另走 6.3 的工作台工具,不经过这些后台任务入口。
伙伴可以登记、列出、重命名和隐藏账号项目,也可以把已有的非伙伴任务移入或移出项目。
移动任务必须已经持有该任务的 session id,不能按标题枚举其他任务。远程伙伴不获得这些工具。
- 这不包含停止、插话、改运行时、改名、归档、标签或读取其他任务的历史与输入队列。
+ 这不包含停止、插话、改运行时、改名、归档、标签或读取其他任务的历史与输入队列;
+ 唯一例外是 6.3:主人明确交给伙伴的项目里的任务可以查看、继续与停止当前轮。
`check_session_task.control.last_stop_request` 保留最近一次优雅停止请求的时间、返回状态和轮次;
它是历史回执,实际是否停稳仍看 `stop_status`,重启不会重放停止请求或冻结下一轮。
@@ -437,6 +439,117 @@ Session 任务遵守同一套机制与呈现契约:
此展示依赖服务端透传发送者和 `mutable-content`、以及包含通知扩展的新版 iOS 安装包;
旧服务端或旧安装包继续显示原通知,不因客户端单侧升级停止推送。
+### 6.3 工作台:主人交给伙伴的项目
+
+2026-10-01 产品裁决(用户已同意):伙伴可以查看、继续、停止「用户明确交给它的项目」里的任务。
+同日用户实机试用后多次修订,最终口径:
+
+1. **接手 = 理解,不是搬运**——伙伴先读懂项目里已有的工作,写下判断;主人点头(或点「跟进」)的那一件才
+ 继续。不批量导入、不搬运已完成的外部会话。
+2. **项目是目录,素材不只是会话**——伙伴要先看项目本身(文档、git、PR 与 issue),会话只看起始目的和
+ 最后几条,不读全文;一律只看近期(30 天内),读取有界、带缓存。
+3. **项目里的任务都是伙伴知道的项目事务**——已接手项目里的 Cindy 任务(包括主人之后自己开的)不论伙伴判断
+ 过没有都在工作台上、也都在 `get_workbench` 里;只有还没导入的外部会话要等伙伴判断后才上工作台。
+
+- **授权来源**:只来自主人在伙伴工作台里点「交给<伙伴>」的那一次。宿主把项目目录记在该伙伴
+ Home 的 `workbench.json`(`directories`,最多 6 个,去重),主人可以随时在工作台上移除,移除
+ 即收回。模型不能自己添加项目,工具不接受 botId。移除在进行中的调用里同样生效:返回内容、投递、停止
+ 之前宿主会再确认一次项目仍在。
+- **范围**:已接手项目里的普通本机任务(项目目录本身及其子目录,按目录边界比较;worktree 归到主仓库;
+ 交了嵌套的项目时归到最深的那个);工作目录
+ 落在已接手项目内的本机 Claude Code / Codex / Pi 会话;已接手项目 GitHub 远端上的 PR 与 issue;
+ 伙伴从项目文档里提出的建议。任何伙伴自己的隐藏任务(主任务、群专线、历史等伙伴 session)、伙伴开的
+ 后台任务(仍走 6.1 的 `message_session_task` / `stop_session_task`)、自动化的运行任务、IM 渠道任务、
+ Orca worker、远端任务、已归档或已删除的任务都不在范围内;项目之外的任务仍不可触达。
+- **交接**:主人点「交给<伙伴>」只做两件事——记下目录;以主人身份发一句「把 <项目> 交给你了。」。
+ 用户可见消息里不出现工具名或内部指令,也不导入任何会话。
+- **本机会话从哪里读**(`maker-ipc/botWorkbenchSessionRoots.ts`,纯函数):转录是固定目录下的文件,
+ 与哪个数据库无关——Claude Code 读 `$CLAUDE_CONFIG_DIR/projects` 与 `~/.claude/projects`(只进与项目
+ 存储名相同或以它为前缀的文件夹);Codex 读 `$CODEX_HOME`、`~/.codex`、Codex.app,以及 Cindy 各 profile
+ (`Cindy`、`CindyGlobal`、`CindyDev`、历史 `xdt-maker`)与当前运行(含 dev 沙盒)的 `codex-home`,以及多账号
+ 登录的 `codex-accounts/<当前账号>/<供应商>`(与 `codexAccountHome` 同一派生,只取当前 Cindy 账号那一层),每个
+ home 取 `sessions/`(只进最近 30 天的日期子目录)与 `archived_sessions/`;Pi 读上述 profile 的
+ `pi-agent-home/sessions`。所有根都按项目 cwd 过滤、只看 mtime 在 30 天内的。「当前库里已有这一条」
+ 只用来避免同一件事显示两次,不用来排除来源。
+- **读取边界**(`maker-ipc/botWorkbenchTranscripts.ts`):近期文件先只读开头 16KB 找 cwd,不在项目里的
+ 直接丢掉;项目里最新的至多 30 条才读头尾各 64KB 算摘要(首行超长时跳过它再取头部,至多往后找 1MB),
+ 按文件 mtime + size 缓存。Cindy 任务的摘要是两条有界查询(第一条用户消息、最后 3 条),按 updatedAt
+ 缓存。更早的只计数(`olderCount`),不读。
+- **项目素材 brief**(`maker-ipc/botWorkbenchBrief.ts`):宿主现算、只给事实不下结论——顶层与
+ `docs/` 下两级以内的 Markdown 路径(最多 30 个,只给路径;顺序为顶层 README / DESIGN / AGENTS / CLAUDE →
+ docs 里同名的 → `docs/product-rules` → `docs/dev-rules` → 其余);不是 git 仓库时给最近 14 天改过的文件
+ (最多 20 个,跳过隐藏目录与 node_modules 等);git
+ 当前分支、未提交改动数、最近 14 天的提交(最多 30 条)、最近有提交的本地分支(最多 10 个),每条
+ 命令 3 秒超时;远端是 GitHub 且本机 gh 已登录时,我打开的 PR 与指派给我 / 我开的 issue(各最多 10 条,
+ 8 秒超时),复用已有 gh 登录,没有凭证返回 `unavailable: 'no-credential'`,不弹登录。按项目缓存 60 秒,
+ 目录 mtime、`.git/HEAD` 或 `.git/index` 变化即失效。
+- **理解(伙伴侧工具)**:
+ - `get_workbench`:每个项目带 brief;会话只列最近 30 天:项目里的 Cindy 任务(含主人自己开的、没判断过的)
+ 优先,最多 30 条,剩余名额给本机 Claude Code / Codex / Pi 会话,合计最多 40 条,每条带稳定的 `taskId`(Cindy 任务用 session id,本机会话用
+ `claude:<id>` / `codex:<id>` / `pi:<id>`)、来源、清洗过的标题、最近活动、运行状态(只有 Cindy 任务有)、
+ `digest`(起始目的 ≤ 200 字 + 最后 2–3 条各 ≤ 300 字)和伙伴之前写过的判断;伙伴写过的 PR / issue /
+ 建议条目原样带回;另附 `olderCount`、伙伴自己的例行任务与项目里的自动化。
+ - `read_workbench_task`:digest 不够判断时才用;只读一件会话最近的用户 / 助手文字(约 4000 字),
+ 本机会话只读转录头尾,不写库、不导入。PR / issue / 建议没有对话记录,返回 `TASK_NOT_READABLE`。
+ - `set_workbench_task` / `set_workbench_tasks`(批量 1–30 条,逐条校验、一次广播):伙伴写下理解——
+ 人话标题(≤ 40 字)、判断(`unfinished` 没做完 / `idea` 聊过没下文或值得做 / `done` 做完或无关)、一句
+ 下一步(≤ 120 字,done 可空)与可选 `ref`。条目 id 除会话外还可以是 `pr:<owner>/<repo>#<n>`、
+ `issue:<owner>/<repo>#<n>`(仓库必须是某个已接手项目的 GitHub 远端)与 `idea:<slug>`
+ (`[a-z0-9-]{3,40}`;交了多个项目时用 `project` 指明归属)。`ref` 只接受 https 链接(不带账号密码)
+ 或已接手项目内的绝对路径(不允许 `..` 越界),否则 `INVALID_REF`。按 taskId 整条替换存进
+ `workbench.json` 的 `tasks`,上限 200 条,超出先淘汰最旧的 done;写入即广播,工作台立刻刷新。
+ - `continue_workbench_task`:主人点头后才用。Cindy 任务直接以伙伴身份投递(复用跨任务投递路径,忙时
+ 排队);Claude Code / Codex 会话先只导入这一条(设置页同一条单条导入路径),判断改挂到新任务 id 再投递。
+ Pi 会话、导入不了的会话(例如转录在另一个 Cindy profile 里)以及 PR / issue / 建议条目:宿主按条目
+ 所属项目目录开一条伙伴后台任务(与 `start_session_task` 同一条服务端路径),目标 = 条目标题 + 伙伴的
+ 话 + 参考与摘要,原条目从工作台移除,之后它就是一条普通的「你交代的」后台任务。没写过判断的 PR /
+ issue / 建议不能继续。`stop_workbench_task` 请求优雅停止当前一轮,不删除任务。
+ - 工具说明写清做法:先 `get_workbench`,再用自己的文件工具读 brief 里最前面的一两份文档(README / DESIGN /
+ AGENTS 之类),然后看提交(非 git 目录看最近改过的文件)和 digest,用 `set_workbench_tasks` 一次写完,只对
+ 拿不准的几件 `read_workbench_task`;判断要体现对项目的理解,不只复述会话;文档、最近的 PR 与 issue 同样是
+ 素材。主人提到项目、让跟进或问进展时先看工作台。写完后在聊天里用几句话告诉主人没做完
+ 的几件与值得做的几件,问主人接着做哪件,不自作主张开始做。只有本机、在用的伙伴主任务可以调用;远程
+ 伙伴不提供工作台。
+- **校验位置**:每次调用在 main 里确定性校验(`maker-ipc/botWorkbenchAccess.ts`),越权返回明确
+ 错误码且不读、不写、不投递;工作台详情视图读同一份摘录时也按该伙伴已接手的项目判定范围。
+- **工作台显示什么**:已接手项目里最近 30 天的 Cindy 任务一律列出——包括主人自己开的、伙伴还没判断过的;
+ 新开的任务随任务列表的实时数据(`sessionsStore`,与左侧任务列表同源)立刻出现;伙伴开的后台任务照常列出。
+ 本机外部会话(Claude Code / Codex / Pi,还没导入的)与 PR / issue / 建议只在伙伴判为没做完 / 聊过没下文时
+ 列出。伙伴还在读时(项目里有候选没判断,且伙伴
+ 主任务正在运行),列表上方显示一行「<伙伴>正在了解 <项目>…」。
+- **列表形态**(2026-10-01 用户实机后裁决:不用格子卡片,读起来累):单列,按「等你 / 在做 / 待做 / 做完」
+ 四组排列,组标题带数量,空组不出,「做完」默认折叠。等你 = 等回复或出错 / 被打断 / 后台任务失败;
+ 在做 = 正在跑的任务与自动化;待做 = 伙伴判为没做完 / 聊过没下文的、排队中的、PR / issue / 建议;
+ 做完 = 其余(空闲的 Cindy 任务、收尾的后台任务、待命或停用的自动化),按最近活动倒序最多列 30 条,更早的只显示
+ 「更早的 N 个」;伙伴自己开的后台任务按真实状态进组,不加标签。每条两层,
+ 只有「事情 + 伙伴的意见」:完整标题(最多 3 行)+ 伙伴写的下一步(最多 2 行);没有下一步时,在做的写
+ 「在做 · 用时」,自动化写周期与下次运行,排队的写「排队中」,做完的不写。「等你」组在第二层前加状态点与
+ 一句等的是什么。来源、相对时间不在列表里显示(详情里仍有)。条目关联 PR 时(`pr:` 条目,或 Cindy 任务里出现过
+ PR 链接)第二层末尾带一个 PR 状态标(图标 + 「#<编号> · 状态」,状态与颜色同侧栏的 `PR_STATUS_*`):Cindy
+ 任务复用 PrRefsContext,条目可见时登记消费者、随同一套周期与聚焦刷新;`pr:` 条目可见时经同一个
+ `gitContext.getPrStatuses`(main 侧 60 秒缓存)查一次,拿不到(如没有 gh 登录)只显示编号。
+- **推进方式:右边点「跟进」,左边伙伴干活**。「待做」与「等你」两组每条右侧有一个安静的「跟进」按钮:点击即以主人
+ 身份往伙伴聊天发「跟进「<标题>」」(不带 id、不带工具名),按钮转圈直到伙伴主任务开始运行(伙伴正忙时等它
+ 接下这一轮),超时 30 秒复原;条目怎么移动完全由真实状态决定,不做乐观更新。伙伴收到后先 `get_workbench`
+ 按标题找到那一条,再 `continue_workbench_task`;找不到同名的就问主人,重名时列出候选让主人选。「在做」「做完」
+ 没有跟进按钮;点条目本身仍打开详情。
+- **状态来自宿主**:运行状态由宿主从已有信号推导(运行中、等待交互、上一轮被打断或出错、后台任务
+ 状态、自动化启停与运行),规则在 `shared/botWorkbench.ts`,不经过模型、不另存状态。
+ 原始标题经同一个清洗函数处理(去掉指令块与 Markdown、URL 只留域名与路径末段、取第一行截到 60 字)。
+- **详情在右栏内打开**:点一条在工作台标签内切到详情,不换路由、不跳任务页:伙伴的判断与下一步、
+ 关联的 PR(点击用系统浏览器打开)、最近内容(同一份有界只读摘录;PR / issue / 建议改为显示参考,点击时链接交给系统浏览器、路径再次校验
+ 仍在已接手项目内才打开)、底部「补一句,让<伙伴>接着做…」——发送即以主人身份往伙伴聊天发
+ 「接着做「<标题>」:<内容>」,由伙伴决定是否继续,不绕过伙伴;正在跑的 Cindy 任务可停止,已在
+ Cindy 里的任务另给「在任务页打开」。
+- **伙伴自己的自动化**:伙伴的例行任务(含从 Hermes / OpenClaw 导入来的自动化)始终列在工作台的任务列表里,
+ 还没接手任何项目时也显示在「交给<伙伴>一个项目」下方;待命与停用的都归「做完」,第二层写周期与下次运行或
+ 「已停用」。导入来的自动化
+ 待适配的具体原因存于加密的导入环境里,工作台暂不单独呈现。
+- 伙伴用 `start_session_task` 在已接手项目里开的任务照常是后台任务,同时出现在工作台的任务列表里。
+- 界面:工作台是本机伙伴主任务全局右侧栏里的一个标签(与文件、浏览器并列),首次进入时自动创建
+ 并展开右侧栏;伙伴聊天头部常驻「工作台」入口,标签被关掉后可重新打开;伙伴页保留全局右侧栏的其它能力。
+ Mobile 与远程伙伴暂不提供。
+
## 7. 实现红线
- 生命周期、fallback、所有权和重放判定必须在宿主代码中确定性实现,不能只写进 prompt。
@@ -472,6 +585,8 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘
- 伙伴会话的上下文里没有项目 / 全局 AGENTS.md、CLAUDE.md 与 Cindy 产品提示词。
- `start_session_task` 能:任务卡实时更新到终态、挂起交互回到伙伴代答、完成唤醒信号对用户不可见;每次执行收口另存可展开的结果入口(按任务与执行轮次去重),历史原卡不移动。结果入口直接展示该次结果与文件,超时复用既有终态归一;当次失败原因随回执保存,桌面与手机仅在用户展开错误详情后显示,续跑不改写旧回执。忙时排队、过程收拢和重新打开不影响读取;阅读历史时沿用新消息提示,不强拉到底部。
父任务异常恢复后仍投递到当前主任务;check / message / stop 都只能控制它创建的 Session 任务。
+ 主人交给伙伴的项目里的原有任务只能经 6.3 的工作台工具查看、继续与停止,越权(项目外、伙伴隐藏任务、
+ 非主任务调用、远程、归档)一律被宿主拒绝。
- 伙伴主聊天通知优先使用当前已完成轮次的最终回复纯文本摘要;Markdown 转为可读文字后才截断,遵守推送协议的 UTF-16 长度上限且不拆分代理对。无可用正文时使用本地化新回复兜底;沿用通知开关及系统预览隐私,静默自动化仍不外发。普通任务保留任务通知语义。
- 完成信号临时失败与 Host 重启后会幂等补投;等待事项在重启恢复期间保持可见且不消耗执行期限。
- `send_to_agent` 的同一伙伴对最多 12 条、单方最多连续 2 条;达到上限和空闲超时都会结束本轮。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 4755390c37..c08affb605 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -183,6 +183,10 @@ Anthropic Messages API / wire protocol 的用户可见名称。四语统一保
Cindy 在 X 上发出的那条公开回复。zh-CN 取「回帖」以强调它是**一条公开帖子**而不是私聊消息——这正是 X 与 Slack / Telegram 的性质差异, 也是风险告知的核心。与「消息」区分开: 后者按 task-and-conversation-naming 只用于任务内的单条往来。proposed 同上。
+### Workbench
+
+伙伴主任务右侧栏里的标签:主人交给伙伴的项目,以及项目里的任务、自动化与产出(docs/product-rules/cindy-bots-runtime.md「工作台」一节)。只指这个伙伴视图,不泛指任务列表或其它面板。先登记为 proposed,待 Chris 实机试用后再定。
+
### Security check
登录邮箱发码前的 CAPTCHA(Cloudflare Turnstile)挑战。中文用「安全验证」(腾讯/阿里系产品的通行叫法,2026-08-19 用户反馈弃用「人机验证」;与「验证码」= verification code 消歧——后者已被 login.codePlaceholder 占用指 6 位数字码);en 用 Security check 而非品牌词 Turnstile 或缩写 CAPTCHA。消费处:login.captcha.* 与 login.errors.CAPTCHA_*(desktop 五语 + mobile 影子 catalog)。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 411de14d3e..c16f6d96b6 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -2279,6 +2279,18 @@
"ko": "초대 코드"
},
"note": "共享任务加入表单中由房主提供、访客输入的代码;用户要求明确称为邀请码,避免被理解为任意邀请文本。"
+ },
+ {
+ "id": "bot-workbench",
+ "status": "proposed",
+ "en": "Workbench",
+ "translations": {
+ "zh-CN": "工作台",
+ "zh-TW": "工作台",
+ "ja": "ワークベンチ",
+ "ko": "작업대"
+ },
+ "note": "伙伴主任务右侧栏里的标签:主人交给伙伴的项目,以及项目里的任务、自动化与产出(docs/product-rules/cindy-bots-runtime.md「工作台」一节)。只指这个伙伴视图,不泛指任务列表或其它面板。先登记为 proposed,待 Chris 实机试用后再定。"
}
]
}
diff --git a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
new file mode 100644
index 0000000000..d1b22b1c45
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
+import { registerBotWorkbenchTools, type BotWorkbenchCallbacks } from '../xdt-helper/bot_workbench.js';
+
+function parse(result: { content: Array<{ type: string; text?: string }> }) {
+ const block = result.content[0];
+ if (block?.type !== 'text' || typeof block.text !== 'string') throw new Error('text expected');
+ return JSON.parse(block.text) as Record<string, unknown>;
+}
+
+const snapshot = {
+ projects: [{ name: 'tapmon-art', path: '/w/tapmon-art', exists: true, brief: null }],
+ tasks: [
+ {
+ taskId: 'claude:abc',
+ source: 'claude-code' as const,
+ imported: false,
+ title: '导出 Android 图标',
+ project: 'tapmon-art',
+ state: null,
+ kind: 'existing' as const,
+ lastActiveAt: '2026-10-01T00:00:00.000Z',
+ messageCount: null,
+ digest: { purpose: '导出 Android 图标', recent: [] },
+ judgment: null,
+ },
+ ],
+ items: [],
+ automations: [],
+ counts: { unfinished: 0, idea: 0, done: 0, unjudged: 1 },
+ truncated: false,
+ totalTasks: 1,
+ olderCount: 0,
+};
+
+function setup(sessionId: string | null = 'bot-session') {
+ const callbacks: BotWorkbenchCallbacks = {
+ get: vi.fn(async () => ({ ok: true as const, workbench: snapshot })),
+ read: vi.fn(async ({ taskId }: { taskId: string }) => ({
+ ok: true as const,
+ taskId,
+ transcript: { items: [{ role: 'user' as const, text: '导出图标', at: 1 }], truncated: false },
+ })),
+ set: vi.fn(async ({ taskId, title, verdict, next }: { taskId: string; title: string; verdict: 'unfinished' | 'idea' | 'done'; next?: string | null }) => ({
+ ok: true as const,
+ taskId,
+ judgment: { title, verdict, next: next ?? null, updatedAt: '2026-10-01T00:00:00.000Z' },
+ })),
+ setMany: vi.fn(async ({ items }: { items: Array<{ taskId: string }> }) => ({
+ ok: true as const,
+ saved: items.length,
+ results: items.map((item) => ({ taskId: item.taskId, ok: true as const })),
+ })),
+ continueTask: vi.fn(async ({ taskId }: { taskId: string }) => ({
+ ok: true as const,
+ taskId,
+ delivery: 'queued' as const,
+ queuedMessageId: 'q-1',
+ })),
+ stopTask: vi.fn(async ({ taskId }: { taskId: string }) => ({
+ ok: true as const,
+ taskId,
+ status: 'requested' as const,
+ })),
+ };
+ const reg = new XdtHelperToolRegistry();
+ registerBotWorkbenchTools(reg, {
+ getSessionContext: () => ({ sessionId: sessionId ?? undefined, agentKind: 'claude-code', workingDir: '/w' }),
+ callbacks,
+ });
+ return { reg, callbacks };
+}
+
+describe('bot workbench tools', () => {
+ it('reads the workbench through the caller Session only', async () => {
+ const { reg, callbacks } = setup();
+ const result = parse(await reg.call('get_workbench', {}));
+ expect(result).toMatchObject({ ok: true, workbench: { totalTasks: 1 } });
+ expect(callbacks.get).toHaveBeenCalledWith({ callerSessionId: 'bot-session' });
+ });
+
+ it('continues and stops a task by id, never by a caller-supplied Bot or project', async () => {
+ const { reg, callbacks } = setup();
+ expect(parse(await reg.call('continue_workbench_task', { task_id: 'task-1', message: '把剩下的导出做完' })))
+ .toMatchObject({ ok: true, task_id: 'task-1', delivery: 'queued', queued_message_id: 'q-1' });
+ expect(callbacks.continueTask).toHaveBeenCalledWith({
+ callerSessionId: 'bot-session',
+ taskId: 'task-1',
+ message: '把剩下的导出做完',
+ });
+ expect(parse(await reg.call('stop_workbench_task', { task_id: 'task-1' })))
+ .toMatchObject({ ok: true, task_id: 'task-1', status: 'requested' });
+ expect(callbacks.stopTask).toHaveBeenCalledWith({ callerSessionId: 'bot-session', taskId: 'task-1' });
+ });
+
+ it('reads a candidate and records a judgment for it', async () => {
+ const { reg, callbacks } = setup();
+ expect(parse(await reg.call('read_workbench_task', { task_id: 'claude:abc' })))
+ .toMatchObject({ ok: true, task_id: 'claude:abc', transcript: { truncated: false } });
+ expect(callbacks.read).toHaveBeenCalledWith({ callerSessionId: 'bot-session', taskId: 'claude:abc' });
+ expect(
+ parse(await reg.call('set_workbench_task', { task_id: 'claude:abc', title: '导出图标', verdict: 'unfinished', next: '补 xxhdpi' })),
+ ).toMatchObject({ ok: true, judgment: { verdict: 'unfinished', next: '补 xxhdpi' } });
+ expect(callbacks.set).toHaveBeenCalledWith({
+ callerSessionId: 'bot-session',
+ taskId: 'claude:abc',
+ title: '导出图标',
+ verdict: 'unfinished',
+ next: '补 xxhdpi',
+ });
+ });
+
+ it('writes a batch of judgments with optional refs in one call', async () => {
+ const { reg, callbacks } = setup();
+ const result = parse(await reg.call('set_workbench_tasks', {
+ items: [
+ { task_id: 'claude:abc', title: '导出图标', verdict: 'unfinished', next: '补 xxhdpi' },
+ { task_id: 'pr:makecindy/cindy#5292', title: '工作台 PR', verdict: 'unfinished', next: '处理 review', ref: 'https://github.com/makecindy/cindy/pull/5292' },
+ { task_id: 'idea:dark-icons', title: '暗色图标', verdict: 'idea', next: '按 DESIGN.md 补一套', ref: '/w/tapmon-art/DESIGN.md', project: '/w/tapmon-art' },
+ ],
+ }));
+ expect(result).toMatchObject({ ok: true, saved: 3 });
+ expect(callbacks.setMany).toHaveBeenCalledWith({
+ callerSessionId: 'bot-session',
+ items: [
+ { taskId: 'claude:abc', title: '导出图标', verdict: 'unfinished', next: '补 xxhdpi' },
+ { taskId: 'pr:makecindy/cindy#5292', title: '工作台 PR', verdict: 'unfinished', next: '处理 review', ref: 'https://github.com/makecindy/cindy/pull/5292' },
+ { taskId: 'idea:dark-icons', title: '暗色图标', verdict: 'idea', next: '按 DESIGN.md 补一套', ref: '/w/tapmon-art/DESIGN.md', project: '/w/tapmon-art' },
+ ],
+ });
+ });
+
+ it('caps the batch at 30 items before reaching the host', async () => {
+ const { reg, callbacks } = setup();
+ const items = Array.from({ length: 31 }, (_, index) => ({ task_id: `t-${index}`, title: 't', verdict: 'done' }));
+ expect(parse(await reg.call('set_workbench_tasks', { items })).ok).toBe(false);
+ expect(parse(await reg.call('set_workbench_tasks', { items: [] })).ok).toBe(false);
+ expect(callbacks.setMany).not.toHaveBeenCalled();
+ });
+
+ it('reports a background task started for a non-session entry', async () => {
+ const { reg, callbacks } = setup();
+ vi.mocked(callbacks.continueTask).mockResolvedValueOnce({
+ ok: true,
+ taskId: 'child-1',
+ delivery: 'started',
+ startedFrom: 'idea:dark-icons',
+ });
+ expect(parse(await reg.call('continue_workbench_task', { task_id: 'idea:dark-icons', message: '开始做' })))
+ .toMatchObject({ ok: true, task_id: 'child-1', started_from: 'idea:dark-icons' });
+ });
+
+ it('rejects judgments outside the schema before reaching the host', async () => {
+ const { reg, callbacks } = setup();
+ expect(parse(await reg.call('set_workbench_task', { task_id: 't', title: 'x'.repeat(41), verdict: 'done' })).ok).toBe(false);
+ expect(parse(await reg.call('set_workbench_task', { task_id: 't', title: '标题', verdict: 'maybe' })).ok).toBe(false);
+ expect(callbacks.set).not.toHaveBeenCalled();
+ });
+
+ it('passes host denials through with their error code', async () => {
+ const { reg, callbacks } = setup();
+ vi.mocked(callbacks.continueTask).mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'TASK_OUTSIDE_WORKBENCH',
+ message: '这件任务不在主人交给你的项目里',
+ });
+ expect(parse(await reg.call('continue_workbench_task', { task_id: 'other', message: 'hi' })))
+ .toMatchObject({ ok: false, errorCode: 'TASK_OUTSIDE_WORKBENCH' });
+ });
+
+ it('rejects blank messages before reaching the host', async () => {
+ const { reg, callbacks } = setup();
+ expect(parse(await reg.call('continue_workbench_task', { task_id: 'task-1', message: ' ' })))
+ .toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ expect(callbacks.continueTask).not.toHaveBeenCalled();
+ });
+
+ it('requires a bound Bot session', async () => {
+ const { reg, callbacks } = setup(null);
+ expect(parse(await reg.call('get_workbench', {}))).toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });
+ expect(parse(await reg.call('stop_workbench_task', { task_id: 'task-1' })))
+ .toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });
+ expect(callbacks.get).not.toHaveBeenCalled();
+ expect(callbacks.stopTask).not.toHaveBeenCalled();
+ });
+
+ it('no longer offers the card-writing tool', () => {
+ const { reg } = setup();
+ expect(reg.has('update_workbench')).toBe(false);
+ for (const name of ['get_workbench', 'read_workbench_task', 'set_workbench_task', 'set_workbench_tasks', 'continue_workbench_task', 'stop_workbench_task']) {
+ expect(reg.has(name)).toBe(true);
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 5a6a4e6303..d132663e63 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -79,6 +79,10 @@ import {
registerBotSkillTools,
type BotSkillCallbacks,
} from './xdt-helper/bot_skills.js';
+import {
+ registerBotWorkbenchTools,
+ type BotWorkbenchCallbacks,
+} from './xdt-helper/bot_workbench.js';
import {
registerBotCapabilityTools,
withCindyGatedBotToolDescriptions,
@@ -772,6 +776,11 @@ export interface XdtHelperMcpDeps {
* the caller Session.
*/
botSkills?: BotSkillCallbacks;
+ /**
+ * Bot workbench: read the projects the owner handed to the Bot and continue / stop tasks
+ * inside them. Host resolves the Bot from the caller Session and authorizes every target.
+ */
+ botWorkbench?: BotWorkbenchCallbacks;
botCapabilities?: BotCapabilityCallbacks;
/**
* 官方反馈 issue 提交回调(弹确认卡片 → 用户确认 → POST server)。host 注入后,
@@ -972,6 +981,12 @@ export function createXdtHelperMcpServer(
callbacks: deps.botSkills,
});
}
+ if (deps.botWorkbench) {
+ registerBotWorkbenchTools(registry, {
+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ callbacks: deps.botWorkbench,
+ });
+ }
if (deps.botCapabilities) {
registerBotCapabilityTools(registry, {
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
new file mode 100644
index 0000000000..e00b0b169d
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
@@ -0,0 +1,389 @@
+import { z } from 'zod';
+
+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
+import type { ControlResult, LiziMcpSessionContext } from '../types.js';
+import { errorPayload, okPayload } from './_payload.js';
+
+/**
+ * 伙伴工作台:主人把本机项目交给伙伴后,伙伴先读懂项目里的任务,再按主人的意思继续。
+ *
+ * 权限只来自主人在工作台里的那次「交给伙伴」:宿主从 callerSessionId 反查伙伴
+ * (只认本机、在用的伙伴主任务),目标必须落在该伙伴已接手的项目里——Cindy 任务要是
+ * 普通本机任务、未归档删除、不是任何伙伴自己的隐藏任务;本机 Claude Code / Codex / Pi 会话的
+ * 工作目录要在已接手项目内;PR / issue 要属于已接手项目的 GitHub 远端;参考链接只认 https
+ * 或项目内路径。工具层不接受 botId,越权一律由宿主确定性拒绝。
+ */
+
+export type WorkbenchTaskStateWire =
+ | 'running'
+ | 'waiting'
+ | 'queued'
+ | 'stopped'
+ | 'automation'
+ | 'done';
+
+export type WorkbenchVerdictWire = 'unfinished' | 'idea' | 'done';
+
+export interface WorkbenchBriefGithubItemWire {
+ number: number;
+ title: string;
+ state: string;
+ updatedAt: string;
+ url: string;
+}
+
+/** 宿主现算的项目素材:有界、只看近期、带缓存。 */
+export interface WorkbenchProjectBriefWire {
+ /** 顶层与 docs/ 下两级以内的 Markdown 路径,重要的在前(只给路径,要看再用文件工具读)。 */
+ docs: string[];
+ /** 不是 git 仓库时最近 14 天改过的文件(最多 20 个)。 */
+ recent: Array<{ path: string; modifiedAt: string }>;
+ git: {
+ branch: string | null;
+ changes: number | null;
+ commits: Array<{ sha: string; date: string; author: string; subject: string }>;
+ branches: Array<{ name: string; date: string }>;
+ /** 查 PR / issue 用的 GitHub 仓库(fork 工作流优先 upstream)。 */
+ remote: string | null;
+ /** upstream 与 origin 里的 GitHub 仓库;pr: / issue: 条目可以用其中任意一个。 */
+ remotes: string[];
+ } | null;
+ github:
+ | { repo: string; pullRequests: WorkbenchBriefGithubItemWire[]; issues: WorkbenchBriefGithubItemWire[] }
+ | { unavailable: 'no-credential' | 'not-github' | 'error' };
+}
+
+export interface WorkbenchProjectWire {
+ name: string;
+ path: string;
+ exists: boolean;
+ brief: WorkbenchProjectBriefWire | null;
+}
+
+export interface WorkbenchJudgmentWire {
+ title: string;
+ verdict: WorkbenchVerdictWire;
+ next: string | null;
+ ref?: string | null;
+ updatedAt: string;
+}
+
+/** 会话的起始目的与最近几条;宿主只读头尾,不读全文。 */
+export interface WorkbenchDigestWire {
+ purpose: string | null;
+ recent: Array<{ role: 'user' | 'assistant'; text: string }>;
+}
+
+export interface WorkbenchTaskWire {
+ /** Cindy 任务是 session id;还没接过来的本机会话是 `claude:<id>` / `codex:<id>` / `pi:<id>`。 */
+ taskId: string;
+ source: 'cindy' | 'claude-code' | 'codex' | 'pi';
+ /** 已经是 Cindy 里的任务(本机会话被继续过之后也会变成 true)。 */
+ imported: boolean;
+ /** 清洗过的原始标题。 */
+ title: string;
+ project: string;
+ /** 只有 Cindy 任务有运行状态;本机会话为 null。 */
+ state: WorkbenchTaskStateWire | null;
+ /** delegated = 你开的后台任务。 */
+ kind: 'existing' | 'delegated';
+ lastActiveAt: string | null;
+ messageCount: number | null;
+ digest: WorkbenchDigestWire | null;
+ /** 你之前写下的判断;还没读过为 null。 */
+ judgment: WorkbenchJudgmentWire | null;
+}
+
+/** 你写下的 PR / issue / 建议条目。 */
+export interface WorkbenchItemWire {
+ taskId: string;
+ project: string;
+ judgment: WorkbenchJudgmentWire;
+}
+
+export interface WorkbenchAutomationWire {
+ id: string;
+ name: string;
+ /** routine = 你自己的例行任务;automation = 已接手项目里的自动化。 */
+ kind: 'routine' | 'automation';
+ state: WorkbenchTaskStateWire;
+ project: string | null;
+ nextRunAt: string | null;
+ lastResult: string | null;
+}
+
+export interface BotWorkbenchSnapshotWire {
+ projects: WorkbenchProjectWire[];
+ tasks: WorkbenchTaskWire[];
+ items: WorkbenchItemWire[];
+ automations: WorkbenchAutomationWire[];
+ counts: Record<WorkbenchVerdictWire | 'unjudged', number>;
+ /** 候选多于返回条数时为 true;totalTasks 是实际总数。 */
+ truncated: boolean;
+ totalTasks: number;
+ /** 超过 30 天没动、没有列出的会话数。 */
+ olderCount: number;
+}
+
+export interface WorkbenchJudgmentInputWire {
+ taskId: string;
+ title: string;
+ verdict: WorkbenchVerdictWire;
+ next?: string | null;
+ ref?: string | null;
+ project?: string | null;
+}
+
+export interface WorkbenchTranscriptWire {
+ items: Array<{ role: 'user' | 'assistant'; text: string; at: number }>;
+ truncated: boolean;
+}
+
+export type WorkbenchStopStatusWire =
+ | 'no-active-turn'
+ | 'waiting-for-safe-point'
+ | 'requested'
+ | 'unconfirmed';
+
+export interface BotWorkbenchCallbacks {
+ get(params: { callerSessionId: string }): Promise<ControlResult<{ workbench: BotWorkbenchSnapshotWire }, string>>;
+ read(params: {
+ callerSessionId: string;
+ taskId: string;
+ }): Promise<ControlResult<{ taskId: string; transcript: WorkbenchTranscriptWire }, string>>;
+ set(
+ params: { callerSessionId: string } & WorkbenchJudgmentInputWire,
+ ): Promise<ControlResult<{ taskId: string; judgment: WorkbenchJudgmentWire }, string>>;
+ setMany(params: {
+ callerSessionId: string;
+ items: WorkbenchJudgmentInputWire[];
+ }): Promise<
+ ControlResult<
+ {
+ saved: number;
+ results: Array<{ taskId: string; ok: true } | { taskId: string; ok: false; errorCode: string; message: string }>;
+ },
+ string
+ >
+ >;
+ continueTask(params: {
+ callerSessionId: string;
+ taskId: string;
+ message: string;
+ }): Promise<
+ ControlResult<
+ {
+ taskId: string;
+ delivery: 'started' | 'queued';
+ queuedMessageId?: string;
+ importedFrom?: string;
+ startedFrom?: string;
+ },
+ string
+ >
+ >;
+ stopTask(params: {
+ callerSessionId: string;
+ taskId: string;
+ }): Promise<ControlResult<{ taskId: string; status: WorkbenchStopStatusWire }, string>>;
+}
+
+export interface BotWorkbenchToolDeps {
+ getSessionContext: () => LiziMcpSessionContext;
+ callbacks: BotWorkbenchCallbacks;
+}
+
+export const WORKBENCH_MESSAGE_MAX_CHARS = 4_000;
+export const WORKBENCH_BATCH_MAX = 30;
+
+function missingSession() {
+ return errorPayload('NOT_A_BOT_SESSION', '当前调用未绑定伙伴主任务。');
+}
+
+const TASK_ID = z
+ .string()
+ .min(1)
+ .max(256)
+ .describe('get_workbench 返回的 taskId;或你新写的 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n>、idea:<slug>');
+
+const JUDGMENT_FIELDS = {
+ task_id: TASK_ID,
+ title: z.string().min(1).max(40).describe('人话标题'),
+ verdict: z.enum(['unfinished', 'idea', 'done']).describe('你的判断'),
+ next: z.string().max(120).optional().describe('一句下一步;done 可省略'),
+ ref: z
+ .string()
+ .max(2000)
+ .optional()
+ .describe('可选参考:https 链接,或已接手项目内的文件绝对路径(例如 docs/design.md)'),
+ project: z.string().max(1024).optional().describe('idea 条目归属的项目路径;只交了一个项目时可省略'),
+};
+
+function judgmentInput(item: {
+ task_id: string;
+ title: string;
+ verdict: WorkbenchVerdictWire;
+ next?: string;
+ ref?: string;
+ project?: string;
+}): WorkbenchJudgmentInputWire {
+ return {
+ taskId: item.task_id,
+ title: item.title,
+ verdict: item.verdict,
+ next: item.next ?? null,
+ ...(item.ref ? { ref: item.ref } : {}),
+ ...(item.project ? { project: item.project } : {}),
+ };
+}
+
+export function registerBotWorkbenchTools(
+ registry: XdtHelperToolRegistry,
+ deps: BotWorkbenchToolDeps,
+): void {
+ const callerSessionId = () => deps.getSessionContext().sessionId ?? null;
+
+ registry.register({
+ name: 'get_workbench',
+ category: 'bots',
+ description:
+ '读取你的工作台:主人交给你的项目,每个项目的素材(brief:文档路径、git 分支与最近 14 天提交、我打开的 PR 与 issue),'
+ + '项目里最近 30 天的会话(项目里的 Cindy 任务——包括主人自己开的——不管你判断过没有都在,最多 30 条;再补本机 Claude Code / Codex / Pi 会话,合计最多 40 条;更早的只给 olderCount),你写过的 PR / issue / 建议条目,你的例行任务与项目里的自动化。'
+ + '主人提到这个项目、让你跟进或问进展时,先看工作台;主人自己在项目里开的任务也在里面,它们属于你知道的项目事务,不需要主人逐个告诉你。'
+ + '每条会话带 digest:起始目的与最后几条对话,足够大多数判断,不用逐个读全文。'
+ + '接手的做法:主人把项目交给你时,先调用它;再用你自己的文件工具读 brief.docs 里最前面的一两份(README / DESIGN / AGENTS 之类),弄清项目是做什么的、在往哪走;'
+ + '然后看最近的提交(不是 git 仓库时看 brief.recent)和会话 digest,一次性用 set_workbench_tasks 批量写下判断;只有拿不准的几件才 read_workbench_task。'
+ + '判断与下一步要体现你对项目的理解(它在项目里处于什么位置、和哪份文档或哪次提交有关),不要只复述会话。'
+ + '项目文档(如 DESIGN.md)、最近的 PR 与 issue 同样是素材:值得做的写成 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n> 或 idea:<slug> 条目,带上 ref。'
+ + '判断标准:最后一条是没被执行的要求、报错中断、明确留下的待办 → unfinished;讨论过方案或想法但之后没人动 → idea;已交付、纯问答、与项目无关 → done。'
+ + '写完后在聊天里用几句话告诉主人:没做完的几件各一句下一步,值得做的几件各一句建议,问主人要接着做哪件。不要自作主张开始做;只有主人点头的那件才 continue_workbench_task。'
+ + '主人在工作台上点「跟进」时会发来「跟进「<标题>」」(其它语言如 Follow up on “<标题>”):先调用本工具按标题找到那一条,'
+ + '再 continue_workbench_task——会话条目发一句承接上文、收到就能接着做的指令;PR / issue / 建议条目会在项目目录开后台任务。'
+ + '找不到同名条目就问主人是哪一件,不要猜;有几条同名时列出候选让主人选。'
+ + '要在项目里开全新的任务时用 start_session_task,把 working_dir 设为该项目路径。',
+ inputShape: {},
+ handler: async () => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ const result = await deps.callbacks.get({ callerSessionId: sessionId });
+ return result.ok
+ ? okPayload({ workbench: result.workbench })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+
+ registry.register({
+ name: 'read_workbench_task',
+ category: 'bots',
+ description:
+ '只读一件候选会话最近的内容(用户与助手的文字,去掉工具结果与系统提示,最多约 4000 字,保留最近的)。'
+ + 'digest 不够判断时才用。本机 Claude Code / Codex / Pi 会话只读转录文件头尾,不会导入。PR / issue / 建议条目没有对话记录,看 ref。只能读主人交给你的项目里的会话。',
+ inputShape: { task_id: TASK_ID },
+ handler: async ({ task_id }) => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ const result = await deps.callbacks.read({ callerSessionId: sessionId, taskId: task_id });
+ return result.ok
+ ? okPayload({ task_id: result.taskId, transcript: result.transcript })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+
+ registry.register({
+ name: 'set_workbench_task',
+ category: 'bots',
+ description:
+ '写下你对一件事的理解,主人的工作台立刻显示。整条替换之前的判断。多件时用 set_workbench_tasks。'
+ + 'task_id:get_workbench 返回的会话 taskId,或你新写的 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n>(须是已接手项目的 GitHub 仓库)、idea:<slug>(小写字母数字与连字符,3–40 位)。'
+ + 'title:人话标题,不超过 40 字,说清这件事是什么;verdict:unfinished(没做完、可以接着做)/ idea(聊过但没下文,建议往下做)/ done(做完或与项目无关,工作台不显示);'
+ + 'next:一句下一步,不超过 120 字,unfinished / idea 必填;ref:可选参考(https 链接或项目内文件路径)。只写有依据的判断,不要编造。',
+ inputShape: JUDGMENT_FIELDS,
+ handler: async (args) => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ const result = await deps.callbacks.set({ callerSessionId: sessionId, ...judgmentInput(args) });
+ return result.ok
+ ? okPayload({ task_id: result.taskId, judgment: result.judgment })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+
+ registry.register({
+ name: 'set_workbench_tasks',
+ category: 'bots',
+ description:
+ `批量写下判断(1–${WORKBENCH_BATCH_MAX} 条),字段与 set_workbench_task 相同。逐条校验,一条不合格不影响其它条;返回每条的结果。`
+ + '接手项目时优先用它:看完 get_workbench 的 brief 与 digest 后一次写完。',
+ inputShape: {
+ items: z.array(z.object(JUDGMENT_FIELDS)).min(1).max(WORKBENCH_BATCH_MAX).describe('判断列表'),
+ },
+ handler: async ({ items }) => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ const result = await deps.callbacks.setMany({
+ callerSessionId: sessionId,
+ items: items.map((item) => judgmentInput(item)),
+ });
+ return result.ok
+ ? okPayload({ saved: result.saved, results: result.results })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+
+ registry.register({
+ name: 'continue_workbench_task',
+ category: 'bots',
+ description:
+ '主人点头后(包括主人在工作台上点「跟进」),让工作台上的一件任务接着做:给它发一句话,消息以你的名义投递,任务正忙时排到当前一轮之后。'
+ + '如果它还是没接过来的本机 Claude Code / Codex 会话,宿主先只导入这一条,再投递;返回里的 task_id 是导入后的新任务 id,之后用它。'
+ + 'Pi 会话、导入不了的会话,以及 PR / issue / 建议条目:宿主在该项目目录里开一条你的后台任务(与 start_session_task 同一条路径),'
+ + '目标是条目标题 + 你的 message + 参考与摘要;返回 started_from 为原条目,task_id 是新后台任务,之后用 message_session_task 跟进。'
+ + '只能作用于主人交给你的项目里的任务;你自己用 start_session_task 开的后台任务继续用 message_session_task。'
+ + '把 message 写成那件任务收到就能直接开始做的一句指令,带上必要的背景;不要重复它已经做完的外部操作。',
+ inputShape: {
+ task_id: TASK_ID,
+ message: z
+ .string()
+ .min(1)
+ .max(WORKBENCH_MESSAGE_MAX_CHARS)
+ .describe('发给这件任务的一句话'),
+ },
+ handler: async ({ task_id, message }) => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ if (!message.trim()) return errorPayload('INVALID_ARGS', 'message 不能为空。');
+ const result = await deps.callbacks.continueTask({
+ callerSessionId: sessionId,
+ taskId: task_id,
+ message,
+ });
+ return result.ok
+ ? okPayload({
+ task_id: result.taskId,
+ delivery: result.delivery,
+ ...(result.queuedMessageId ? { queued_message_id: result.queuedMessageId } : {}),
+ ...(result.importedFrom ? { imported_from: result.importedFrom } : {}),
+ ...(result.startedFrom ? { started_from: result.startedFrom } : {}),
+ })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+
+ registry.register({
+ name: 'stop_workbench_task',
+ category: 'bots',
+ description:
+ '请求停止工作台上一件任务的当前一轮(优雅停止)。不删除任务,之后仍可用 continue_workbench_task 接着做。'
+ + '只在主人要求,或任务明显走偏、在做重复无用的事时使用。status=requested / waiting-for-safe-point / unconfirmed 表示已请求但引擎可能还没停稳,不要说成已停止。'
+ + '你自己开的后台任务用 stop_session_task。',
+ inputShape: { task_id: TASK_ID },
+ handler: async ({ task_id }) => {
+ const sessionId = callerSessionId();
+ if (!sessionId) return missingSession();
+ const result = await deps.callbacks.stopTask({ callerSessionId: sessionId, taskId: task_id });
+ return result.ok
+ ? okPayload({ task_id: result.taskId, status: result.status })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index ec5485256d..8efbf3d5f2 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -141,6 +141,26 @@ export {
type BotSkillSummaryWire,
type BotSkillToolDeps,
} from './bot_skills.js';
+export {
+ registerBotWorkbenchTools,
+ WORKBENCH_BATCH_MAX,
+ WORKBENCH_MESSAGE_MAX_CHARS,
+ type BotWorkbenchCallbacks,
+ type BotWorkbenchSnapshotWire,
+ type BotWorkbenchToolDeps,
+ type WorkbenchAutomationWire,
+ type WorkbenchDigestWire,
+ type WorkbenchItemWire,
+ type WorkbenchJudgmentInputWire,
+ type WorkbenchJudgmentWire,
+ type WorkbenchProjectBriefWire,
+ type WorkbenchProjectWire,
+ type WorkbenchStopStatusWire,
+ type WorkbenchTaskStateWire,
+ type WorkbenchTaskWire,
+ type WorkbenchTranscriptWire,
+ type WorkbenchVerdictWire,
+} from './bot_workbench.js';
export {
registerCreateTeammateTool,
type CreateTeammateCallbacks,