Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(bots): 按逐任务真实责任显示伙伴头像和工作台 (#5870)

Chris Zhang184684c26691
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
index a5cf959ea5..8470d39ddb 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
@@ -11,6 +11,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { messages, sessions } from '../../schema';
+import * as trustedRenderer from '../../../security/trustedAppRenderer.js';
import type { SessionRouteLock } from '../../sessionRouteLock';
type SessionRouteLockMock = SessionRouteLock &
@@ -392,3 +393,34 @@ describe('bounded reconciliation read', () => {
() => batch({}, Array.from({ length: 33 }, () => 'target')))).rejects.toThrow('INVALID_PARAMS');
});
});
+
+describe('exact-subset task pagination', () => {
+ it('selects newest responsible rows before limiting and preserves stable tied-time continuation', async () => {
+ const trust = vi.spyOn(trustedRenderer, 'assertTrustedAppRendererEvent').mockImplementation(() => {});
+ try {
+ const insert = h.sqlite!.prepare("INSERT INTO sessions (id,status,source,created_at,updated_at,list_preview,list_message_count) VALUES (?,'archived','desktop',1,?,'cached',0)");
+ const ids = Array.from({ length: 205 }, (_, n) => `owned-${String(n).padStart(3, '0')}`);
+ for (let n = 0; n < ids.length; n++) insert.run(ids[n], Math.floor(n / 3));
+ insert.run('unrelated', 1000);
+ h.sqlite!.prepare("INSERT INTO sessions (id,status,source,created_at,updated_at) VALUES ('hidden','archived','bot',1,2000),('active','active','desktop',1,3000)").run();
+ const list = h.handlers.get('local-db:sessions:list')!;
+ const wanted = [...ids, 'hidden', 'active'];
+ const first = await list({}, 200, 'archived', { ids: wanted, fresh: true }) as Array<{id: string; updatedAt: string}>;
+ expect(first.map(row => row.id)).toEqual(ids.slice(5).reverse());
+ const tail = first.at(-1)!;
+ const second = await list({}, 200, 'archived', { ids: wanted, fresh: true, before: { id: tail.id, updatedAt: Date.parse(tail.updatedAt) } }) as Array<{id: string}>;
+ expect(second.map(row => row.id)).toEqual(ids.slice(0, 5).reverse());
+ expect(await list({}, 200, 'archived', { ids: [] })).toEqual([]);
+ for (const options of [{ ids: ['target'], includePinned: true }, { ids: [123] }, { ids: ['x'.repeat(257)] }, { ids: Array(10001).fill('target') }]) {
+ await expect(list({}, 200, 'archived', options)).rejects.toThrow('INVALID_PARAMS');
+ }
+ } finally { trust.mockRestore(); }
+ });
+ it('rejects remote and untrusted exact-subset calls rather than broadening discovery', async () => {
+ const list = h.handlers.get('local-db:sessions:list')!;
+ await expect(list({}, 200, 'archived', { ids: ['target'] })).rejects.toThrow();
+ const { runDeviceLinkInvokeContext } = await import('../../../device-link/invoke-context.js');
+ await expect(runDeviceLinkInvokeContext({ controllerDeviceId: 'phone', channel: 'local-db:sessions:list' },
+ () => list({}, 200, 'archived', { ids: ['target'] }))).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 558cc6c63a..d16b3ec2ae 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -65,16 +65,17 @@ import {
import { syncBotProfileFromFolder } from '../../maker-ipc/botProfileFolderSync.js';
import { requestBotRuntimeEpochRefresh } from '../../maker-ipc/botRuntimeEpochRefreshSignal.js';
import { createLogger } from '../../logger.js';
+import { collectTaskResponsibilityScopes } from '../../maker-ipc/botTaskResponsibility.js';
import {
addBotWorkbenchDirectory,
broadcastBotWorkbenchChanged,
readBotWorkbench,
- readBotWorkbenchDirectoryPaths,
removeBotWorkbenchDirectory,
} from '../../maker-ipc/botWorkbenchService.js';
import {
listBotWorkbenchCandidatesForOwner,
readBotWorkbenchTaskForOwner,
+ readBotResponsibleSessionIds,
} from '../../maker-ipc/botWorkbenchTools.js';
import {
NEW_BOT_DEFAULT_PI_EFFORT,
@@ -2143,7 +2144,9 @@ export function registerBotIpc(): void {
const owner = captureBotOperationOwner();
const workbench = await readBotWorkbench(owner.userDataDir, botId);
owner.assertCurrent();
- return workbench;
+ const responsibleSessionIds = await readBotResponsibleSessionIds(owner.userDataDir, botId);
+ owner.assertCurrent();
+ return { ...workbench, responsibleSessionIds };
});
for (const operation of ['list', 'update', 'act'] as const) {
ipcMain.handle(`local-db:bots:todos:${operation}`, async (event, rawBotId: unknown, input: unknown) => {
@@ -2166,8 +2169,7 @@ export function registerBotIpc(): void {
if (result.ok) broadcastBotWorkbenchChanged(botId);
return result;
});
- // 侧栏「<伙伴>在跟进」:每个在用的本机伙伴接手了哪些项目。只给路径列表,不做文件系统探测,
- // 也不带判断与会话内容;渲染层按任务的工作目录自己匹配。
+ // Exact per-task responsibility IDs from the current owner, without message bodies.
ipcMain.handle('local-db:bots:workbench:follow-scopes', async (event) => {
assertTrustedAppRendererEvent(event);
const owner = captureBotOperationOwner();
@@ -2175,12 +2177,13 @@ export function registerBotIpc(): void {
.select({ id: botProfiles.id })
.from(botProfiles)
.where(eq(botProfiles.status, 'active'));
- const scopes = await Promise.all(bots.map(async (bot) => ({
- botId: bot.id,
- directories: await readBotWorkbenchDirectoryPaths(owner.userDataDir, bot.id),
- })));
+ // Older renderers receive empty directories rather than claiming projects.
+ const scopes = await collectTaskResponsibilityScopes(
+ bots.map((bot) => bot.id),
+ (botId) => readBotResponsibleSessionIds(owner.userDataDir, botId),
+ );
owner.assertCurrent();
- return scopes.filter((scope) => scope.directories.length > 0);
+ return scopes;
});
// 工作台详情视图:只读一件任务的最近内容(有界)。范围限于该伙伴已接手的项目,
// 外部会话只读转录尾部,不写库、不导入。
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index c26b06e02a..bc27353604 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -1273,6 +1273,21 @@ export function registerSessionIpc(
before = { updatedAt: value.updatedAt, id: value.id };
}
+ const rawIds = options && typeof options === 'object' ? (options as { ids?: unknown }).ids : undefined;
+ let ids: string[] | undefined;
+ if (rawIds !== undefined) {
+ // Exact-subset pagination remains local-only, like the continuation cursor.
+ assertTrustedAppRendererEvent(event);
+ if (!Array.isArray(rawIds) || rawIds.length > 10_000 || usageHistory || includePinned) {
+ throwIpcError('INVALID_PARAMS', 'Invalid session list IDs');
+ }
+ ids = [...new Set(rawIds.map((id, index) => {
+ const value = requireString(id, `ids[${index}]`);
+ if (value.length > 256) throwIpcError('INVALID_PARAMS', 'Session list ID too long');
+ return value;
+ }))];
+ }
+
// 支持 Sidebar Filter 的 Active/Archived/All status 过滤。
// - 'active' / 'archived' → WHERE status = ?
// - 'all' / undefined / 其它非法值 → WHERE status != 'deleted'
@@ -1281,6 +1296,7 @@ export function registerSessionIpc(
const statusFilter: 'active' | 'archived' | null =
status === 'active' || status === 'archived' ? status : null;
const loadRows = async () => {
+ if (ids?.length === 0) return [];
// 按 DESKTOP_VISIBLE_SESSION_SOURCES 白名单过滤 — 包含 IM 渠道
// (feishu/slack/discord)与本机自动化(scheduler/learn/shared);
// feishu 会话以「对话」分组展示(workspaceKind='dialogue')。/review 审查任务
@@ -1288,7 +1304,7 @@ export function registerSessionIpc(
const sourceFilter = inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES);
const statusWhere = () =>
statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');
- const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap, before);
+ const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere(), ids ? inArray(sessions.id, ids) : undefined), cap, before);
let mergedRows = rows;
if (includePinned) {
@@ -1321,7 +1337,7 @@ export function registerSessionIpc(
// forceRefresh / status 重拉带 fresh,不并入写前那次查询。
const result = usageHistory
? await loadUsageHistoryRows()
- : userId && !fresh && !before
+ : userId && !fresh && !before && !ids
? await runSessionListSingleFlight(
buildSessionListFlightKey({
userId,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
new file mode 100644
index 0000000000..e99c71a047
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
@@ -0,0 +1,64 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { botProfileDir } from '../botProfileFolder.js';
+import { collectTaskResponsibilityScopes, readTaskResponsibilities, responsibleSessionIds, setTaskResponsibility } from '../botTaskResponsibility.js';
+
+// Lock mechanics have their own cross-process suite; exercise this store's guarded write.
+vi.mock('../../device-link/crossProcessLock.js', () => ({
+ withCrossProcessLock: async (_file: string, _options: unknown, run: (lock: { held: true }) => unknown) => run({ held: true }),
+}));
+let root: string;
+beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), 'bot-task-responsibility-')); });
+afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });
+
+describe('task responsibility', () => {
+ it('uses only verified creation and explicit records; releases override creation across reads', async () => {
+ expect(await readTaskResponsibilities(root, 'one')).toEqual({});
+ await setTaskResponsibility(root, 'one', 'taken', true, () => {});
+ await setTaskResponsibility(root, 'one', 'created', false, () => {});
+ expect(responsibleSessionIds(['created', 'across-project'], await readTaskResponsibilities(root, 'one')))
+ .toEqual(['across-project', 'taken']);
+ await setTaskResponsibility(root, 'one', 'taken', false, () => {});
+ expect(responsibleSessionIds(['created'], await readTaskResponsibilities(root, 'one'))).toEqual([]);
+ expect(await readTaskResponsibilities(root, 'two')).toEqual({});
+ expect(await readTaskResponsibilities(root + '-other-owner', 'one')).toEqual({});
+ });
+ it('does not touch workbench judgments or Todo when taking or releasing', async () => {
+ const home = botProfileDir(root, 'one');
+ await fs.mkdir(home, { recursive: true });
+ for (const name of ['workbench.json', 'todos.v1.json']) await fs.writeFile(path.join(home, name), 'original');
+ await setTaskResponsibility(root, 'one', 'taken', true, () => {});
+ await setTaskResponsibility(root, 'one', 'taken', false, () => {});
+ for (const name of ['workbench.json', 'todos.v1.json']) expect(await fs.readFile(path.join(home, name), 'utf8')).toBe('original');
+ });
+ it('fails closed on corruption and preserves the damaged file', async () => {
+ const home = botProfileDir(root, 'one');
+ await fs.mkdir(home, { recursive: true });
+ const file = path.join(home, 'task-responsibility.v1.json');
+ await fs.writeFile(file, '{broken');
+ await expect(readTaskResponsibilities(root, 'one')).rejects.toThrow();
+ await expect(setTaskResponsibility(root, 'one', 'new', true, () => {})).rejects.toThrow();
+ expect(await fs.readFile(file, 'utf8')).toBe('{broken');
+ });
+ it('rejects an owner change before commit and leaves no temporary file', async () => {
+ let checks = 0;
+ await expect(setTaskResponsibility(root, 'one', 'new', true, () => {
+ if (++checks === 3) throw new Error('OWNER_SCOPE_CHANGED');
+ })).rejects.toThrow('OWNER_SCOPE_CHANGED');
+ expect(await readTaskResponsibilities(root, 'one')).toEqual({});
+ expect(await fs.readdir(botProfileDir(root, 'one'))).toEqual([]);
+ });
+});
+
+it('keeps healthy companions visible while failing closed for a damaged release store', async () => {
+ await setTaskResponsibility(root, 'healthy', 'owned', true, () => {});
+ await setTaskResponsibility(root, 'damaged', 'created', false, () => {});
+ const file = path.join(botProfileDir(root, 'damaged'), 'task-responsibility.v1.json');
+ await fs.writeFile(file, '{broken');
+ const scopes = await collectTaskResponsibilityScopes(['damaged', 'healthy'], async (botId) =>
+ responsibleSessionIds(botId === 'damaged' ? ['created'] : [], await readTaskResponsibilities(root, botId)));
+ expect(scopes).toEqual([{ botId: 'healthy', directories: [], sessionIds: ['owned'] }]);
+ expect(await fs.readFile(file, 'utf8')).toBe('{broken');
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibilityAuthority.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibilityAuthority.test.ts
new file mode 100644
index 0000000000..81fc2c2497
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibilityAuthority.test.ts
@@ -0,0 +1,44 @@
+import { readFileSync } from 'node:fs';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { and, desc, eq, isNotNull } from 'drizzle-orm';
+import ts from 'typescript';
+import { expect, it } from 'vitest';
+import { botDelegations, botProfiles, botSessionLinks, sessions } from '../../localDb/schema.js';
+
+// Exercise the real authority queries against SQLite, without Electron startup.
+const source = readFileSync(new URL('../botWorkbenchTools.ts', import.meta.url), 'utf8');
+function bind(name: string, end: string, db: ReturnType<typeof drizzle>) {
+ const start = source.indexOf(`async function ${name}`);
+ const chunk = source.slice(start, source.indexOf(end, start));
+ const js = ts.transpileModule(`${chunk}; return ${name};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ const deps = { getDbClient: () => ({ drizzle: db }), and, desc, eq, isNotNull, botDelegations, botProfiles, botSessionLinks, sessions };
+ return new Function(...Object.keys(deps), js)(...Object.values(deps));
+}
+
+it('derives caller identity from the active local canonical link and creation only from its own delegation rows', async () => {
+ const sqlite = new Database(':memory:');
+ try {
+ sqlite.exec(`CREATE TABLE sessions(id TEXT, source TEXT, status TEXT, remote_host_id TEXT);
+ CREATE TABLE bot_profiles(id TEXT, status TEXT);
+ CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT, role TEXT, archived_at INTEGER);
+ CREATE TABLE bot_delegations(requesting_bot_id TEXT, child_session_id TEXT, status TEXT, last_error TEXT, created_at INTEGER);
+ INSERT INTO sessions VALUES ('canonical','bot','active',NULL),('human','desktop','active',NULL),('group','bot','active',NULL),('remote','bot','active','host');
+ INSERT INTO bot_profiles VALUES ('one','active'),('two','active');
+ INSERT INTO bot_session_links VALUES ('canonical','one','canonical',NULL),('group','one','group',NULL),('remote','one','canonical',NULL);
+ INSERT INTO bot_delegations VALUES ('one','own-across-directory','completed',NULL,1),('two','their-task','running',NULL,2),('one',NULL,'pending',NULL,3);`);
+ const db = drizzle(sqlite);
+ const resolve = bind('resolveWorkbenchCaller', 'async function readWorkbenchTarget', db);
+ const creations = bind('listBotDelegationChildren', '/** Exact responsibility IDs', db);
+ expect(await resolve('canonical')).toEqual({ ok: true, botId: 'one' });
+ expect(await resolve('human')).toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });
+ expect(await resolve('group')).toMatchObject({ ok: false, errorCode: 'BOT_MAIN_TASK_REQUIRED' });
+ expect(await resolve('remote')).toMatchObject({ ok: false, errorCode: 'REMOTE_WORKBENCH_UNAVAILABLE' });
+ expect([...(await creations('one')).keys()]).toEqual(['own-across-directory']);
+ expect([...(await creations('two')).keys()]).toEqual(['their-task']);
+ sqlite.exec("UPDATE bot_session_links SET archived_at=1 WHERE session_id='canonical'");
+ expect(await resolve('canonical')).toMatchObject({ ok: false, errorCode: 'BOT_SESSION_INACTIVE' });
+ } finally { sqlite.close(); }
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
index 84849e3d8f..8c4616f3b8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchAccess.test.ts
@@ -52,6 +52,8 @@ const transcript = { items: [{ role: 'user' as const, text: '导出图标', at:
function setup(overrides: Partial<BotWorkbenchAccessDeps> = {}) {
const deps: BotWorkbenchAccessDeps = {
+ readResponsibleSessionIds: vi.fn(async () => []),
+ saveResponsibility: vi.fn(async () => undefined),
resolveCaller: vi.fn(async () => ({ ok: true as const, botId: 'bot-1' })),
readState: vi.fn(async () => ({ directories: [PROJECT], tasks: {} })),
readTarget: vi.fn(async () => target()),
@@ -448,6 +450,7 @@ describe('workbench snapshot', () => {
},
},
})),
+ readResponsibleSessionIds: vi.fn(async () => ['running', 'delegated-1']),
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 },
@@ -471,28 +474,23 @@ describe('workbench snapshot', () => {
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.candidates).toEqual([{ taskId: 'claude:abc', source: 'claude-code', title: '把图标导出来', project: 'tapmon-art' }]);
expect(result.workbench.tasks[0]!.digest).toMatchObject({ purpose: '导出图标' });
- expect(result.workbench.counts).toEqual({ unfinished: 1, idea: 0, done: 0, unjudged: 1 });
+ expect(result.workbench.counts).toEqual({ unfinished: 0, idea: 0, done: 0, unjudged: 1 });
expect(result.workbench.automations.map((item) => item.id)).toEqual(['s-1']);
- expect(result.workbench.totalTasks).toBe(3);
+ expect(result.workbench.totalTasks).toBe(2);
+ expect(result.workbench.totalCandidates).toBe(1);
// 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 () => {
+ it('keeps owner-opened project tasks in discovery without reading bodies or claiming responsibility', async () => {
const NOW = 100 * 24 * 60 * 60 * 1000;
- const { access } = setup({
+ const { access, deps } = setup({
now: () => NOW,
listProjectTasks: vi.fn(async () =>
Array.from({ length: 35 }, (_, index) => ({
@@ -512,10 +510,28 @@ describe('workbench snapshot', () => {
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 });
+ expect(ids).toEqual([]);
+ expect(result.workbench.candidates.length).toBe(40);
+ expect(deps.readSessionDigest).not.toHaveBeenCalled();
+ expect(result.workbench).toMatchObject({ truncated: false, totalTasks: 0, totalCandidates: 55, candidatesTruncated: true });
+ });
+
+ it('caps responsible tasks and discovery candidates independently without reading candidate bodies', async () => {
+ const NOW = 100 * 24 * 60 * 60 * 1000;
+ const owned = Array.from({ length: 35 }, (_, n) => `owned-${n}`);
+ const { access, deps } = setup({
+ now: () => NOW,
+ readResponsibleSessionIds: vi.fn(async () => owned),
+ listProjectTasks: vi.fn(async () => [...owned, ...Array.from({ length: 45 }, (_, n) => `candidate-${n}`)]
+ .map((id, n) => ({ id, title: id, workingDir: PROJECT, agentKind: 'cc', summary: null, lastActiveAt: NOW - n }))),
+ listExternalCandidates: sessions(),
+ });
+ const result = await access.get({ callerSessionId: 'bot-main' });
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.workbench.tasks).toHaveLength(30);
+ expect(result.workbench.candidates).toHaveLength(40);
+ expect(result.workbench).toMatchObject({ totalTasks: 35, truncated: true, totalCandidates: 45, candidatesTruncated: true });
+ expect(vi.mocked(deps.readSessionDigest).mock.calls.map(([id]) => id)).toEqual(owned.slice(0, 30));
});
it('keeps going without a brief when building it fails', async () => {
@@ -546,3 +562,55 @@ describe('workbench snapshot', () => {
expect(deps.listExternalCandidates).not.toHaveBeenCalled();
});
});
+
+
+describe('explicit per-task responsibility', () => {
+ it('takes one authorized task without starting it, then releases without touching its lifecycle', async () => {
+ const { access, deps } = setup();
+ await expect(access.setResponsibility({ callerSessionId: 'main', taskId: 'session:task-1', responsible: true }))
+ .resolves.toEqual({ ok: true, taskId: 'task-1', responsible: true });
+ expect(deps.saveResponsibility).toHaveBeenCalledWith('bot-1', 'task-1', true);
+ expect(deps.sendToSession).not.toHaveBeenCalled();
+ expect(deps.startBackgroundTask).not.toHaveBeenCalled();
+ vi.mocked(deps.readResponsibleSessionIds).mockResolvedValue(['task-1']);
+ vi.mocked(deps.readTarget).mockResolvedValue(target({ status: 'archived', workingDir: '/moved' }));
+ await expect(access.setResponsibility({ callerSessionId: 'main', taskId: 'task-1', responsible: false }))
+ .resolves.toMatchObject({ ok: true, responsible: false });
+ expect(deps.saveResponsibility).toHaveBeenLastCalledWith('bot-1', 'task-1', false);
+ });
+ it('does not let project access, another bot or revoked identity impersonate responsibility', async () => {
+ const { access, deps } = setup();
+ await expect(access.setResponsibility({ callerSessionId: 'main', taskId: 'task-1', responsible: false }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_NOT_RESPONSIBLE' });
+ vi.mocked(deps.readTarget).mockResolvedValue(target({ delegationChild: true }));
+ await expect(access.setResponsibility({ callerSessionId: 'main', taskId: 'task-1', responsible: true }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_IS_BACKGROUND_TASK' });
+ vi.mocked(deps.resolveCaller).mockResolvedValue({ ok: false, errorCode: 'NOT_A_BOT_SESSION', message: 'no' });
+ await expect(access.setResponsibility({ callerSessionId: 'other', taskId: 'task-1', responsible: true }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });
+ expect(deps.saveResponsibility).not.toHaveBeenCalled();
+ });
+ it.each([{ remoteHostId: 'remote' }, { botLinked: true }, { status: 'deleted' }])('rejects inaccessible targets %j', async (patch) => {
+ const { access, deps } = setup({ readTarget: vi.fn(async () => target(patch)) });
+ expect((await access.setResponsibility({ callerSessionId: 'main', taskId: 'task-1', responsible: true })).ok).toBe(false);
+ expect(deps.saveResponsibility).not.toHaveBeenCalled();
+ });
+ it('lists own created tasks across projects even when no project is authorized', async () => {
+ const { access, deps } = setup({
+ readState: vi.fn(async () => ({ directories: [], tasks: {} })),
+ readResponsibleSessionIds: vi.fn(async () => ['child']),
+ listDelegations: vi.fn(async () => new Map([['child', 'completed' as const]])),
+ listProjectTasks: vi.fn(async () => [{ id: 'child', title: 'Created elsewhere', workingDir: '/other', agentKind: 'cc', summary: null, lastActiveAt: 1 }]),
+ });
+ const result = await access.get({ callerSessionId: 'main' });
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.workbench.tasks.map(t => t.taskId)).toEqual(['child']);
+ expect(deps.listProjectTasks).toHaveBeenCalledWith([], new Set(['child']));
+ });
+ it('does not save a responsibility after the account changes', async () => {
+ const { access, deps } = setup({ isOwnerScopeCurrent: () => false });
+ await expect(access.setResponsibility({ callerSessionId: 'main', taskId: 'task-1', responsible: true }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'OWNER_SCOPE_CHANGED' });
+ expect(deps.saveResponsibility).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts
index b79f0475c9..02105245d1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkbenchTranscripts.test.ts
@@ -174,6 +174,12 @@ describe('listExternalSessionsForProjects', () => {
expect(byKey.get(`codex:${uuid}`)!.digest).toMatchObject({ purpose: '修 CI' });
expect(byKey.get('pi:p1')).toMatchObject({ title: '写文档', cwd: project });
+ const metadata = await listExternalSessionsForProjects({
+ roots: { claude: [claudeRoot], codex: [codexRoot], codexAccounts: [accountsRoot], pi: [piRoot] },
+ projectDirs: [project], caseInsensitive: false, since: now - 30 * DAY, now, metadataOnly: true,
+ });
+ expect(metadata.sessions.every(item => item.digest === null && item.title === item.id)).toBe(true);
+
const capped = await listExternalSessionsForProjects({
roots: { claude: [claudeRoot], codex: [codexRoot], codexAccounts: [accountsRoot], pi: [piRoot] },
projectDirs: [project],
diff --git a/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
new file mode 100644
index 0000000000..045f201823
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
@@ -0,0 +1,87 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { botProfileDir } from './botProfileFolder.js';
+
+/** Per-task responsibility, independent of project discovery, judgments and Todo.
+ * Releases override creation evidence; nothing is inferred from conversation text.
+ */
+export type TaskResponsibilities = Record<string, { responsible: boolean; updatedAt: string }>;
+const MAX_RECORDS = 10_000;
+const MAX_BYTES = 4 * 1024 * 1024;
+
+function filePath(root: string, botId: string): string {
+ return path.join(botProfileDir(root, botId), 'task-responsibility.v1.json');
+}
+
+export async function readTaskResponsibilities(root: string, botId: string): Promise<TaskResponsibilities> {
+ try {
+ const file = filePath(root, botId);
+ if ((await fs.stat(file)).size > MAX_BYTES) throw new Error('Task responsibility store too large');
+ const raw = JSON.parse(await fs.readFile(file, 'utf8'));
+ if (raw?.version !== 1 || !raw.tasks || typeof raw.tasks !== 'object' || Array.isArray(raw.tasks)) {
+ throw new Error('Invalid task responsibility store');
+ }
+ const entries = Object.entries(raw.tasks);
+ if (entries.length > MAX_RECORDS || entries.some(([id, value]) => {
+ const entry = value as TaskResponsibilities[string] | null;
+ return !id || id.length > 256 || !entry || typeof entry.responsible !== 'boolean'
+ || typeof entry.updatedAt !== 'string' || !Number.isFinite(Date.parse(entry.updatedAt));
+ })) throw new Error('Invalid task responsibility record');
+ return Object.fromEntries(entries) as TaskResponsibilities;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
+ throw error; // A damaged release must never resurrect creation evidence.
+ }
+}
+
+export function responsibleSessionIds(createdIds: Iterable<string>, records: TaskResponsibilities): string[] {
+ const ids = new Set(createdIds);
+ for (const [id, entry] of Object.entries(records)) {
+ if (entry.responsible) ids.add(id);
+ else ids.delete(id);
+ }
+ return [...ids].sort();
+}
+
+/** Atomic, cross-process update; preserve tombstones and reject capacity overflow. */
+export async function setTaskResponsibility(
+ root: string, botId: string, sessionId: string, responsible: boolean, assertCurrent: () => void,
+): Promise<void> {
+ if (!sessionId || sessionId.length > 256 || typeof responsible !== 'boolean') throw new Error('Invalid task responsibility');
+ const file = filePath(root, botId);
+ assertCurrent();
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await withCrossProcessLock(file + '.lock', { label: 'bot-task-responsibility' }, async (lock) => {
+ if (!lock.held) throw new Error('Task responsibility store busy');
+ assertCurrent();
+ const tasks = await readTaskResponsibilities(root, botId);
+ if (!Object.hasOwn(tasks, sessionId) && Object.keys(tasks).length >= MAX_RECORDS) throw new Error('Task responsibility store full');
+ const next = { ...tasks, [sessionId]: { responsible, updatedAt: new Date().toISOString() } };
+ const temp = file + '.' + randomUUID() + '.tmp';
+ try {
+ await fs.writeFile(temp, JSON.stringify({ version: 1, tasks: next }) + '\n', { encoding: 'utf8', mode: 0o600 });
+ assertCurrent();
+ await fs.rename(temp, file);
+ } finally {
+ await fs.rm(temp, { force: true }).catch(() => {});
+ }
+ assertCurrent();
+ });
+}
+
+/** Fail closed for a damaged companion, without removing other companions' marks. */
+export async function collectTaskResponsibilityScopes(
+ botIds: readonly string[], readIds: (botId: string) => Promise<string[]>,
+): Promise<Array<{ botId: string; directories: string[]; sessionIds: string[] }>> {
+ const scopes = await Promise.all(botIds.map(async (botId) => {
+ try {
+ return { botId, directories: [], sessionIds: await readIds(botId) };
+ } catch {
+ // Do not fall back to creation evidence: a damaged file may contain releases.
+ return { botId, directories: [], sessionIds: [] };
+ }
+ }));
+ return scopes.filter((scope) => scope.sessionIds.length > 0);
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
index fd2809162c..2c6e775b64 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts
@@ -9,8 +9,8 @@
* 接手 = 理解,不是搬运:项目是目录。宿主先给每个项目一份有界的素材(文档清单、近期提交与
* 分支、我的 PR / issue)和近期会话的摘要(起始目的 + 最后几条),伙伴凭这些一次性写下判断
* (没做完 / 聊过没下文 / 做完),只对拿不准的再读;条目可以是会话,也可以是 PR、issue
- * 或伙伴从素材里摸出来的建议。项目里的 Cindy 任务(含主人自己开的)不论有无判断都带回,
- * 是伙伴随时知道的项目事务。主人点头(或在工作台点「跟进」)的那件才继续。
+ * 或伙伴从素材里摸出来的建议。项目只授予发现范围;逐任务责任来自创建凭据或明确接手,
+ * 不从目录或判断推断。普通候选只给元数据,主人点头的那件才继续。
*
* 每次调用都在 main 里确定性校验:
* 1. 调用方 session → 伙伴:只认本机、在用的伙伴主任务(canonical);
@@ -50,8 +50,7 @@ type Failure = { ok: false; errorCode: string; message: string };
/** 工具一次最多带回的会话候选数;多出来的只报总数。 */
export const WORKBENCH_TOOL_MAX_TASKS = 40;
/**
- * 其中项目里的 Cindy 任务(含主人自己开的)优先占的条数:它们属于伙伴随时知道的项目事务,
- * 不受判断影响;剩下的名额给本机外部会话。
+ * 逐任务负责的 Cindy 任务优先占用的条数;其余名额只返回项目发现元数据。
*/
export const WORKBENCH_TOOL_MAX_CINDY_TASKS = 30;
export const WORKBENCH_TOOL_MAX_MESSAGE_CHARS = 4_000;
@@ -167,6 +166,8 @@ export interface WorkbenchScheduleRow {
export interface BotWorkbenchAccessDeps {
resolveCaller(callerSessionId: string): Promise<WorkbenchCallerResult>;
+ readResponsibleSessionIds(botId: string): Promise<string[]>;
+ saveResponsibility(botId: string, sessionId: string, responsible: boolean): Promise<void>;
readState(botId: string): Promise<{ directories: string[]; tasks: Record<string, WorkbenchTaskJudgment> }>;
projectExists?(dir: string): Promise<boolean>;
readTarget(sessionId: string): Promise<WorkbenchTargetFacts | null>;
@@ -447,6 +448,35 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
};
return {
+ async setResponsibility(params: { callerSessionId: string; taskId: string; responsible: boolean }) {
+ if (typeof params.responsible !== 'boolean') return { ok: false as const, errorCode: 'INVALID_ARGS', message: 'Invalid responsibility' };
+ const caller = await deps.resolveCaller(params.callerSessionId);
+ if (!caller.ok) return caller;
+ const ref = parseWorkbenchTaskId(params.taskId);
+ if (!ref || ref.kind !== 'session') return { ok: false as const, errorCode: 'INVALID_ARGS', message: 'A Cindy task ID is required' };
+ const existing = new Set(await deps.readResponsibleSessionIds(caller.botId));
+ const created = await deps.listDelegations(caller.botId);
+ const facts = await deps.readTarget(ref.sessionId);
+ if (!facts || facts.status === 'deleted' || facts.botLinked || facts.source === 'bot' || facts.remoteHostId) {
+ return { ok: false as const, errorCode: 'TASK_NOT_ACCESSIBLE', message: 'Task is unavailable' };
+ }
+ if (params.responsible && (facts.status !== 'active' || facts.orcaRole === 'worker' || !isWorkbenchTaskSource(facts.source))) {
+ return { ok: false as const, errorCode: 'TASK_NOT_ACCESSIBLE', message: 'Task cannot be taken' };
+ }
+ if (params.responsible && !created.has(ref.sessionId)) {
+ const state = await deps.readState(caller.botId);
+ const decision = authorizeWorkbenchTarget(facts, state.directories, deps.caseInsensitive);
+ if (!decision.ok) return decision;
+ const revoked = await stillGranted(caller.botId, decision.projectDir);
+ if (revoked) return revoked;
+ } else if (!params.responsible && !existing.has(ref.sessionId)) {
+ return { ok: false as const, errorCode: 'TASK_NOT_RESPONSIBLE', message: 'You do not own this responsibility' };
+ }
+ if (!scopeCurrent()) return scopeChanged;
+ await deps.saveResponsibility(caller.botId, ref.sessionId, params.responsible);
+ deps.notifyChanged(caller.botId);
+ return { ok: true as const, taskId: ref.sessionId, responsible: params.responsible };
+ },
async get(params: { callerSessionId: string }) {
const caller = await deps.resolveCaller(params.callerSessionId);
if (!caller.ok) return caller;
@@ -454,10 +484,9 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
const projectDirs = workbench.directories;
const since = now() - WORKBENCH_RECENT_WINDOW_MS;
const delegations = await deps.listDelegations(caller.botId);
+ const responsible = new Set(await deps.readResponsibleSessionIds(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 || responsible.size ? deps.listProjectTasks(projectDirs, responsible) : Promise.resolve([]),
projectDirs.length ? listExternals(projectDirs) : Promise.resolve({ sessions: [], olderCount: 0, overflowCount: 0 }),
deps.listRoutines(caller.botId),
projectDirs.length ? deps.listSchedules() : Promise.resolve([]),
@@ -471,6 +500,7 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
source: 'cindy' | 'claude-code' | 'codex' | 'pi';
title: string;
project: string;
+ responsible: boolean;
lastActiveMs: number;
messageCount: number | null;
row?: WorkbenchTaskRow;
@@ -480,10 +510,10 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
let olderCount = externals.olderCount;
for (const row of rows) {
const project = findWorkbenchProject(row.workingDir, projectDirs, deps.caseInsensitive);
- if (!project) continue;
+ if (!project && !responsible.has(row.id)) continue;
const lastActiveMs = row.lastActiveAt ?? 0;
// 只看近期;伙伴自己的后台任务不管多久都列出。
- if (lastActiveMs < since && !delegations.has(row.id)) {
+ if (lastActiveMs < since && !responsible.has(row.id)) {
olderCount += 1;
continue;
}
@@ -491,7 +521,8 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
taskId: row.id,
source: importedSessionOrigin(row.id, row.agentKind) ?? 'cindy',
title: cleanWorkbenchTitle(row.title, UNTITLED),
- project: projectName(project),
+ project: project ? projectName(project) : projectName(row.workingDir ?? ''),
+ responsible: responsible.has(row.id),
lastActiveMs,
messageCount: row.messageCount ?? null,
row,
@@ -506,17 +537,18 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
source: external.source === 'claude' ? 'claude-code' : external.source,
title: cleanWorkbenchTitle(external.title, UNTITLED),
project: projectName(project),
+ responsible: false,
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 cindy = all.filter((candidate) => candidate.row && candidate.responsible).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);
+ .filter((candidate) => !candidate.responsible)
+ .slice(0, WORKBENCH_TOOL_MAX_TASKS);
+ const shown = cindy.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;
@@ -610,11 +642,14 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
brief: briefs[index],
})),
tasks,
+ candidates: external.map(({ taskId, source, title, project }) => ({ taskId, source, title, project })),
items,
automations,
counts,
- truncated: all.length > shown.length || (externals.overflowCount ?? 0) > 0,
- totalTasks: all.length + (externals.overflowCount ?? 0),
+ truncated: all.filter(candidate => candidate.responsible).length > shown.length,
+ totalTasks: all.filter(candidate => candidate.responsible).length,
+ totalCandidates: all.filter(candidate => !candidate.responsible).length + (externals.overflowCount ?? 0),
+ candidatesTruncated: all.filter(candidate => !candidate.responsible).length > external.length || (externals.overflowCount ?? 0) > 0,
olderCount,
},
};
@@ -710,6 +745,9 @@ export function createBotWorkbenchAccess(deps: BotWorkbenchAccessDeps) {
}
const revoked = await stillGranted(allowed.botId, target.projectDir);
if (revoked) return revoked;
+ if (!scopeCurrent()) return scopeChanged;
+ await deps.saveResponsibility(allowed.botId, sessionId, true);
+ deps.notifyChanged(allowed.botId);
const sent = await deps.sendToSession({
targetSessionId: sessionId,
message,
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
index 08caef41e2..19c3fb0233 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -53,6 +53,7 @@ import {
readSessionDigest,
readSessionTranscript,
} from './botWorkbenchTranscripts.js';
+import { readTaskResponsibilities, responsibleSessionIds, setTaskResponsibility } from './botTaskResponsibility.js';
import { workbenchSessionRoots } from './botWorkbenchSessionRoots.js';
import { checkHandoverDirectory, findHandedProject } from './botWorkbenchHandover.js';
import { createBriefCache, type WorkbenchBriefGithubItem } from './botWorkbenchBrief.js';
@@ -139,7 +140,7 @@ async function listWorkbenchProjectTasks(
const prefixes = projectDirs
.map((dir) => normalizeWorkingDirForGrouping(dir))
.filter((dir): dir is string => Boolean(dir));
- if (prefixes.length === 0) return [];
+ if (prefixes.length === 0 && alwaysInclude.size === 0) return [];
const db = getDbClient().drizzle;
const hiddenIds = db.select({ id: botSessionLinks.sessionId }).from(botSessionLinks);
const rows = await db
@@ -152,25 +153,30 @@ async function listWorkbenchProjectTasks(
orcaRole: sessions.orcaRole,
userSendAt: sessions.userSendAt,
updatedAt: sessions.updatedAt,
- listPreview: sessions.listPreview,
+ hasPreview: isNotNull(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}%`))),
+ or(
+ ...prefixes.map((prefix) => like(sessions.workingDir, `${prefix}%`)),
+ ...(alwaysInclude.size ? [inArray(sessions.id, [...alwaysInclude])] : []),
+ ),
),
)
- .orderBy(desc(sessions.updatedAt))
- .limit(500);
+ .orderBy(
+ ...(alwaysInclude.size ? [desc(inArray(sessions.id, [...alwaysInclude]))] : []),
+ desc(sessions.updatedAt),
+ )
+ .limit(Math.max(500, alwaysInclude.size));
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));
+ .filter((row) => row.userSendAt != null || row.hasPreview || alwaysInclude.has(row.id));
const messageCounts = new Map<string, number>();
if (kept.length > 0) {
const counted = await db
@@ -190,7 +196,7 @@ async function listWorkbenchProjectTasks(
title: row.title,
workingDir: row.workingDir ?? null,
agentKind: row.agentKind ?? null,
- summary: row.listPreview ?? null,
+ summary: null,
// 与渲染层同一口径:主人发消息与任务本身的最近更新取较晚的那个。
lastActiveAt: Math.max(row.userSendAt ?? 0, row.updatedAt ?? 0) || null,
messageCount: messageCounts.get(row.id) ?? null,
@@ -220,6 +226,35 @@ async function listBotDelegationChildren(botId: string): Promise<Map<string, Wor
return out;
}
+/** Exact responsibility IDs, including archived children, without reading messages. */
+export async function readBotResponsibleSessionIds(userDataDir: string, botId: string): Promise<string[]> {
+ return responsibleSessionIds(
+ (await listBotDelegationChildren(botId)).keys(),
+ await readTaskResponsibilities(userDataDir, botId),
+ );
+}
+
+/** Capture the creator before a generic create-mode handoff crosses async boundaries. */
+export async function captureBotCreatedTaskResponsibility(callerSessionId?: string) {
+ if (!callerSessionId || isAppSessionBoundaryPending()) return null;
+ const scope = activeOwnerScopeKey();
+ const root = ownerScopedUserDataPath();
+ const caller = await resolveWorkbenchCaller(callerSessionId);
+ if (!caller.ok) return null;
+ const assertCurrent = () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scope) throw new Error('OWNER_SCOPE_CHANGED');
+ };
+ assertCurrent();
+ return async (sessionId: string) => {
+ assertCurrent();
+ const target = await readWorkbenchTarget(sessionId);
+ if (!target || target.status !== 'active' || target.botLinked || target.remoteHostId || target.orcaRole === 'worker') return;
+ assertCurrent();
+ await setTaskResponsibility(root, caller.botId, sessionId, true, assertCurrent);
+ broadcastBotWorkbenchChanged(caller.botId);
+ };
+}
+
async function listBotRoutines(botId: string) {
const routines = await routineTools.list(botId);
return Promise.all(
@@ -266,7 +301,7 @@ function appPath(name: 'appData' | 'userData'): string | null {
/**
* 已接手项目里近期的本机 Claude Code / Codex / Pi 会话。根目录见 `workbenchSessionRoots`
- * (含其它 Cindy profile 的 codex-home 与 pi-agent-home),按 cwd 过滤,只读近期转录的头尾。
+ * (含其它 Cindy profile 的 codex-home 与 pi-agent-home),按 cwd 元数据过滤,不预读消息摘要。
*/
async function listExternalCandidates(projectDirs: readonly string[]) {
const now = Date.now();
@@ -283,6 +318,7 @@ async function listExternalCandidates(projectDirs: readonly string[]) {
}),
projectDirs,
caseInsensitive: isCaseInsensitivePlatform(process.platform),
+ metadataOnly: true,
since: now - WORKBENCH_RECENT_WINDOW_MS,
now,
});
@@ -402,6 +438,12 @@ function createDesktopBotWorkbenchAccess(send: BotWorkbenchSendDeps): BotWorkben
rekeyJudgment: (botId, from, to) => rekeyBotWorkbenchJudgment(userDataDir, botId, from, to),
notifyChanged: broadcastBotWorkbenchChanged,
listDelegations: listBotDelegationChildren,
+ readResponsibleSessionIds: (botId) => readBotResponsibleSessionIds(userDataDir, botId),
+ saveResponsibility: (botId, sessionId, responsible) => setTaskResponsibility(
+ userDataDir, botId, sessionId, responsible, () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scopeKey) throw new Error('OWNER_SCOPE_CHANGED');
+ },
+ ),
readActivityPhase: async (sessionId) => (await readCanonicalSessionActivity(sessionId)).phase,
listRoutines: listBotRoutines,
listSchedules: listProjectSchedules,
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts
index c046966b26..7eccabd5f0 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTranscripts.ts
@@ -469,6 +469,8 @@ export async function listExternalSessionsForProjects(input: {
since: number;
now: number;
max?: number;
+ /** Discovery may read cwd metadata, but must not parse message digests. */
+ metadataOnly?: boolean;
}): 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);
@@ -485,11 +487,11 @@ export async function listExternalSessionsForProjects(input: {
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);
+ const digest = input.metadataOnly ? null : await readFileDigest(file.source, file.id, file.file, file).catch(() => null);
return {
source: file.source,
id: file.id,
- title: digest?.purpose ?? '',
+ title: digest?.purpose ?? (input.metadataOnly ? file.id : ''),
cwd: file.cwd,
updatedAt: file.mtimeMs,
file: file.file,
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
index 310a281cc2..4999ad055c 100644
--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts
+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
@@ -28,6 +28,7 @@ export function buildTeammateGuide(
'The application in this guide is the host providing teammate, task and settings tools, not the model provider or agent CLI. Use the host tools for these operations; provider documentation cannot tell you the application’s current settings or available controls.',
...(helperAvailable ? [
TEAMMATE_CONTROL_GUIDANCE,
+ 'Where local workbench tools are available, project authorization is a discovery scope, not responsibility for every task there. get_workbench separates responsible tasks from discovery candidates. Only your host-verified creations or individual tasks you explicitly agree to handle belong to your responsible list. Use set_workbench_task_responsibility to take or release one task; judgments, directory matches and message history do not prove responsibility. A take records a relationship without starting execution, subscribing to all messages or promising unattended management. Release does not stop, move, archive or delete a task and does not affect Todo. Continue agreed work through the existing task tools.',
'For recurring work, first call routine_list and reuse the existing rule. Prefer an available event source, or a deterministic command/script pre-run check, over waking a model just to poll. Install and test scripts through schedule_set_pre_run_hook, then save its command as routine_save.preRunHook and read back with routine_list. Exit 2 means skip the model; exit 0 supplies a concise change summary; errors/timeouts must be nonzero failures, never fabricated no-change results. Use stable upstream event IDs or durable cursors and acknowledge only successfully handled changes; do not add arbitrary time windows or advance a cursor before delivery succeeds. For a check, explicitly set silentWhenIdle=true: no preamble, progress or no-change report. Call schedule_notify_current_run only for a new actionable result or a check failure requiring attention, then write one concise final report. Explicit reminders and scheduled sends are the work itself: set silentWhenIdle=false when creating those rules, preserve existing user choices, and never swallow their intended delivery. Omitted quiet settings preserve delivery. Advanced settings expose the saved quiet/check configuration; the user need not edit files. Preserve the standing authorization, owner and failure visibility.',
'The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill and distinguish it from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.',
'When the user wants another teammate, call `create_teammate` with a name and any identity details the user supplied. New teammates receive this same baseline and follow the user’s available default model; do not generate a fixed number of role Skills, prewrite a greeting, or require a profile form. Their personality, personal learning and memory remain independent.',
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/botTaskCreationResponsibility.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/botTaskCreationResponsibility.test.ts
new file mode 100644
index 0000000000..fd5a042bdc
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/botTaskCreationResponsibility.test.ts
@@ -0,0 +1,79 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+
+// Run the actual Desktop callback without importing unrelated Electron services.
+const source = readFileSync(new URL('../mcp-providers.ts', import.meta.url), 'utf8');
+const start = source.indexOf(' sendToSession: async ({');
+const callback = source.slice(start, source.indexOf(' sessionTasks:', start));
+const wired = ts.transpileModule(`return {${callback}}.sendToSession;`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+}).outputText;
+
+function fixture() {
+ const record = vi.fn(async (_id: string) => { void _id; });
+ const capture = vi.fn(async (_caller: string) => { void _caller; return record; });
+ const send = vi.fn(async (_params: unknown) => { void _params; return { ok: true, wakeKind: 'created', targetSessionId: 'new-task' }; });
+ const call = new Function('tryGetOrcaCollabService', 'captureBotCreatedTaskResponsibility', wired)(
+ () => ({ sendToSession: send }), capture,
+ ) as (params: { targetSessionId?: string; dispatcherSessionId: string; message: string; workingDir?: string }) => Promise<Record<string, unknown>>;
+ return { call, record, capture, send };
+}
+
+it('records only a successful fresh creation, using the original caller and the returned ID', async () => {
+ const f = fixture();
+ const result = await f.call({ dispatcherSessionId: 'canonical-bot', message: 'Work', workingDir: '/other-project' });
+ expect(result).toMatchObject({ ok: true, targetSessionId: 'new-task' });
+ expect(f.capture).toHaveBeenCalledWith('canonical-bot');
+ expect(f.record).toHaveBeenCalledWith('new-task');
+ expect(f.send).toHaveBeenCalledOnce();
+});
+
+it('does not turn a message to an existing task into responsibility', async () => {
+ const f = fixture();
+ f.send.mockResolvedValueOnce({ ok: true, wakeKind: 'queued', targetSessionId: 'existing' });
+ await f.call({ targetSessionId: 'existing', dispatcherSessionId: 'canonical-bot', message: 'A message' });
+ expect(f.capture).not.toHaveBeenCalled();
+ expect(f.record).not.toHaveBeenCalled();
+});
+
+it('preserves creation success if the relationship write fails, without replaying execution', async () => {
+ const f = fixture();
+ f.record.mockRejectedValueOnce(new Error('OWNER_SCOPE_CHANGED'));
+ expect(await f.call({ dispatcherSessionId: 'canonical-bot', message: 'Work' }))
+ .toMatchObject({ ok: true, targetSessionId: 'new-task', responsibilityRecorded: false });
+ expect(f.send).toHaveBeenCalledOnce();
+});
+
+it('records no relationship when creation fails', async () => {
+ const f = fixture();
+ f.send.mockResolvedValueOnce({ ok: false, wakeKind: 'created', targetSessionId: 'missing' });
+ expect(await f.call({ dispatcherSessionId: 'canonical-bot', message: 'Work' })).toMatchObject({ ok: false });
+ expect(f.record).not.toHaveBeenCalled();
+});
+
+
+it.each(['ordinary-caller', 'remote-target', 'worker-target', 'owner-switch'])('does not record an unverified creator/target after %s', async reason => {
+ const captureSource = readFileSync(new URL('../../maker-ipc/botWorkbenchTools.ts', import.meta.url), 'utf8');
+ const begin = captureSource.indexOf('export async function captureBotCreatedTaskResponsibility');
+ const chunk = captureSource.slice(begin, captureSource.indexOf('async function listBotRoutines', begin)).replace('export ', '');
+ const js = ts.transpileModule(`${chunk}; return captureBotCreatedTaskResponsibility;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ let owner = 'owner-one';
+ const save = vi.fn(async () => {});
+ const deps = {
+ isAppSessionBoundaryPending: () => false,
+ activeOwnerScopeKey: () => owner,
+ ownerScopedUserDataPath: () => '/synthetic-owner-home',
+ resolveWorkbenchCaller: async () => reason === 'ordinary-caller' ? { ok: false } : { ok: true, botId: 'creator' },
+ readWorkbenchTarget: async () => ({ status: 'active', botLinked: false, remoteHostId: reason === 'remote-target' ? 'remote' : null, orcaRole: reason === 'worker-target' ? 'worker' : null }),
+ setTaskResponsibility: save,
+ broadcastBotWorkbenchChanged: vi.fn(),
+ };
+ const capture = new Function(...Object.keys(deps), js)(...Object.values(deps));
+ const recorder = await capture('caller');
+ if (reason === 'owner-switch') {
+ owner = 'owner-two';
+ await expect(recorder('new-task')).rejects.toThrow('OWNER_SCOPE_CHANGED');
+ } else if (recorder) await recorder('new-task');
+ expect(save).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index aa1eaf5703..58da98adc6 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -76,6 +76,7 @@ import {
} from '../maker-ipc/botSkillService.js';
import {
addBotWorkbenchProjectForCaller,
+ captureBotCreatedTaskResponsibility,
removeBotWorkbenchProjectForCaller,
runBotWorkbenchTool,
type BotWorkbenchSendDeps,
@@ -690,7 +691,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
|| model !== undefined
|| effort !== undefined
|| fast !== undefined;
- return await svc.sendToSession({
+ const recordCreation = targetSessionId ? null : await captureBotCreatedTaskResponsibility(dispatcherSessionId);
+ const result = await svc.sendToSession({
targetSessionId,
message,
dispatcherSessionId,
@@ -709,6 +711,11 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
}
: {}),
});
+ if (result.ok && result.wakeKind === 'created' && recordCreation) {
+ try { await recordCreation(result.targetSessionId); }
+ catch { return { ...result, responsibilityRecorded: false }; }
+ }
+ return result;
} catch (err) {
return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
}
@@ -921,6 +928,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
return {ok:true,...await access.ingest(input as Parameters<typeof access.ingest>[0])};
} catch(error) { return {ok:false,errorCode:error instanceof TodoError ? error.code : 'INTERNAL',message:error instanceof Error?error.message:'INTERNAL'}; }
},
+ setResponsibility: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.setResponsibility(params)),
get: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.get(params)),
read: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.read(params)),
set: (params) => runBotWorkbenchTool(workbenchSend, (access) => access.set(params)),
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b7d3c6f3e6..8c71639917 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -411,6 +411,8 @@ type DiscordBotSessionAuthCheckWire = {
type LocalDbSessionListOptions = {
/** Local list continuation; does not change the default capped query. */
before?: { updatedAt: number; id: string };
+ /** Local renderer-only exact subset, filtered before sorting and pagination. */
+ ids?: string[];
includePinned?: boolean;
fresh?: boolean;
usageHistory?: boolean;
diff --git a/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx b/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx
index b93ffa8da2..e6f127f22a 100644
--- a/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx
@@ -6,7 +6,7 @@ import type { BotProfile } from './botStore';
export { useSessionFollowers } from './botFollowScopes';
/**
- * 普通任务行上的「<伙伴>在跟进」:这件任务所在的项目交给了哪个伙伴。只显示第一位伙伴的
+ * 普通任务行上的「<伙伴>在跟进」:这件任务由哪个伙伴创建或明确接手。只显示第一位伙伴的
* 14px 头像(头像底色是伙伴身份,不是状态),悬停说明全部伙伴。没有伙伴跟进时不占位。
* 行组件用 `useSessionFollowers(session)` 取伙伴列表,自己决定要不要为标记让位。
*/
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index 0171f7b609..e70416bf05 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -55,7 +55,6 @@ import { useAgentIslandActivityMap } from '@/state/agentIslandActivity';
import {
BOT_WORKBENCH_MAX_DIRECTORIES,
isCaseInsensitivePlatform,
- findWorkbenchProject,
parseWorkbenchTaskId,
validateWorkbenchRef,
type BotWorkbench as BotWorkbenchData,
@@ -88,8 +87,8 @@ import {
*
* - 没接手项目时:从已有项目里选一个 →「交给<伙伴>」,两次点击完成接手。接手 = 理解:
* 只记下目录、告诉伙伴一声,不批量导入;伙伴随后读候选、写判断,条目随之出现。
- * - 接手后:项目胶囊、伙伴还在读时一行「正在了解…」、单列任务列表、最近产出。项目里最近
- * 30 天的 Cindy 任务(含主人自己开的)都在,随任务列表实时更新。列表按 等你 / 在做 / 待做 /
+ * - 接手后:项目胶囊、伙伴还在读时一行「正在了解…」、单列任务列表、最近产出。
+ * 由伙伴创建或逐件明确接手的 Cindy 任务在此显示,随任务列表实时更新。列表按 等你 / 在做 / 待做 /
* 做完 分组(做完默认折叠),每条两层:完整标题 + 伙伴的意见(末尾可带 PR 状态标)。
* - 推进:待做 / 等你 两组的「跟进」以主人身份让伙伴在左边接着干;点一条在本标签内打开详情:
* 伙伴的判断、PR、最近内容、补一句让伙伴接着做。
@@ -229,17 +228,19 @@ function useWorkbenchData(botId: string): BotWorkbenchData | null {
return;
}
let alive = true;
+ let request = 0;
const load = () => {
+ const seq = ++request;
const owner = getDataOwnerGeneration();
void api
.get(botId)
.then((next) => {
- if (alive && isDataOwnerGenerationCurrent(owner)) {
- setData(next ? { directories: next.directories ?? [], tasks: next.tasks ?? {} } : EMPTY_WORKBENCH);
+ if (alive && seq === request && isDataOwnerGenerationCurrent(owner)) {
+ setData(next ? { directories: next.directories ?? [], tasks: next.tasks ?? {}, responsibleSessionIds: next.responsibleSessionIds ?? [] } : EMPTY_WORKBENCH);
}
})
.catch(() => {
- if (alive) setData((previous) => previous ?? EMPTY_WORKBENCH);
+ if (alive && seq === request && isDataOwnerGenerationCurrent(owner)) setData(EMPTY_WORKBENCH);
});
};
setData(null);
@@ -250,9 +251,11 @@ function useWorkbenchData(botId: string): BotWorkbenchData | null {
// 伙伴继续一条本机会话时会先把它导入;刷新任务列表,让新任务出现在格子里。
emitRefresh();
});
+ const offDelegation = window.electronAPI?.maker?.onBotDelegationChanged?.(() => load());
return () => {
alive = false;
off?.();
+ offDelegation?.();
};
}, [botId]);
return data;
@@ -323,9 +326,10 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
const candidates = useExternalCandidates(botId, projectDirs.join('\n'));
const [archivedOpen, setArchivedOpen] = useState(false);
const [listRevision, setListRevision] = useState(0);
+ const responsibleIds = useMemo(() => workbench?.responsibleSessionIds ?? [], [workbench]);
const listScope = `${botId}:${projectDirs.join('\n')}:${listRevision}`;
- const activePages = useWorkbenchSessionPages(listScope, 'active', Boolean(workbench));
- const archivedPages = useWorkbenchSessionPages(listScope, 'archived', archivedOpen);
+ const activePages = useWorkbenchSessionPages(listScope, 'active', Boolean(workbench), responsibleIds);
+ const archivedPages = useWorkbenchSessionPages(listScope, 'archived', archivedOpen, responsibleIds);
const sessionRows = activePages.rows;
const refreshList = useCallback(() => { setListRevision(value => value + 1); emitRefresh(); }, []);
@@ -339,6 +343,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
() =>
buildWorkbenchTiles({
sessions: sessionRows,
+ responsibleSessionIds: responsibleIds,
hiddenIds,
projectDirs,
caseInsensitive,
@@ -352,6 +357,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
}),
[
sessionRows,
+ responsibleIds,
hiddenIds,
projectDirs,
caseInsensitive,
@@ -367,10 +373,10 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
const listedIds = useMemo(() => new Set(tiles.filter(tile => tile.type === 'session').map(tile => tile.id)), [tiles]);
const activeSessionRows = useMemo(() => sessionRows.filter(row => listedIds.has(row.id)), [sessionRows, listedIds]);
- const delegationChildIds = useMemo(() => new Set(delegations.flatMap(row => row.childSessionId ? [row.childSessionId] : [])), [delegations]);
+ const responsibleIdSet = useMemo(() => new Set(responsibleIds), [responsibleIds]);
const archivedSessionRows = useMemo(() => archivedPages.rows.filter(row =>
- row.status === 'archived' && isWorkbenchCandidateSession({ ...row, status: 'active' }, hiddenIds, delegationChildIds)
- && findWorkbenchProject(row.workingDir, projectDirs, caseInsensitive)), [archivedPages.rows, hiddenIds, projectDirs, caseInsensitive, delegationChildIds]);
+ row.status === 'archived' && isWorkbenchCandidateSession({ ...row, status: 'active' }, hiddenIds, responsibleIdSet)
+ && responsibleIdSet.has(row.id)), [archivedPages.rows, hiddenIds, responsibleIdSet]);
const pageAction = (page: typeof activePages) => page.loading
? <Spinner size={14} className="mx-5 my-3" role="status" aria-label={t('ccAgent.common.loading')} />
: page.error || page.hasMore ? <Button size="sm" variant="secondary" className="mx-4 my-2" onClick={() => void page.load()}>{t(page.error ? 'commonUi.retry' : 'settings.contacts.list.loadMore')}</Button> : null;
@@ -545,7 +551,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
</>
)}
- {!picking && <>
+ {(!picking || responsibleIds.length > 0) && <>
<WorkbenchSessionList sessions={activeSessionRows} onChanged={refreshList} />
{pageAction(activePages)}
<section className="pb-3 pt-2">
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
index bafbe59210..fbcadfd206 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
@@ -23,6 +23,7 @@ vi.mock('../botStore', () => ({
import { BotFollowMark, useSessionFollowers } from '../BotFollowMark';
import { __testing } from '../botFollowScopes';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
function Row({ session: value }: { session: Session }) {
return <BotFollowMark followers={useSessionFollowers(value)} />;
@@ -36,7 +37,7 @@ const session = (patch: Partial<Session> = {}) => ({
}) as Session;
let changed: (() => void) | null = null;
-const followScopes = vi.fn(async () => [{ botId: 'bot-1', directories: ['/Users/me/repo'] }]);
+const followScopes = vi.fn(async () => [{ botId: 'bot-1', sessionIds: ['s1', 's2'] }]);
beforeEach(() => {
__testing.reset();
@@ -54,7 +55,7 @@ afterEach(() => {
});
describe('BotFollowMark', () => {
- it('marks a task inside a handed-over project with its Bot, loading the scopes once for all rows', async () => {
+ it('marks an exact responsible task with its Bot, loading the scopes once for all rows', async () => {
await act(async () => {
render(<><Row session={session()} /><Row session={session({ id: 's2' })} /></>);
});
@@ -64,10 +65,10 @@ describe('BotFollowMark', () => {
expect(followScopes).toHaveBeenCalledTimes(1);
});
- it('stays empty outside the project, for Bot-owned or remote tasks, and for hidden Bots', async () => {
+ it('stays empty for unrelated tasks, for Bot-owned or remote tasks, and for hidden Bots', async () => {
await act(async () => {
render(<>
- <Row session={session({ workingDir: '/Users/me/repo-old' })} />
+ <Row session={session({ id: 'unrelated', workingDir: '/Users/me/repo' })} />
<Row session={session({ source: 'bot' })} />
<Row session={session({ remoteHostId: 'ssh-1' })} />
</>);
@@ -97,11 +98,44 @@ describe('BotFollowMark', () => {
it('reloads when a workbench changes', async () => {
await act(async () => { render(<Row session={session()} />); });
followScopes.mockResolvedValueOnce([
- { botId: 'bot-1', directories: ['/Users/me/repo'] },
- { botId: 'bot-2', directories: ['/Users/me'] },
+ { botId: 'bot-1', sessionIds: ['s1', 's2'] },
+ { botId: 'bot-2', sessionIds: ['s1'] },
]);
await act(async () => { changed?.(); });
expect(screen.getByTestId('bot-follow-mark').getAttribute('aria-label'))
.toBe('bots.workbench.followingMark:Dash and Lizi');
});
});
+
+it('never marks same-directory bystanders, but marks a responsible task after a project move', async () => {
+ await act(async () => render(<><Row session={session({ id: 'unrelated' })} /><Row session={session({ workingDir: '/moved' })} /></>));
+ expect(screen.getAllByTestId('bot-follow-mark')).toHaveLength(1);
+});
+it('does not infer responsibility from an older host directory-only payload', async () => {
+ followScopes.mockResolvedValueOnce([{ botId: 'bot-1', directories: ['/Users/me/repo'] }] as any);
+ await act(async () => render(<Row session={session()} />));
+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();
+});
+it('removes marks when a task is released', async () => {
+ await act(async () => render(<Row session={session()} />));
+ expect(screen.getByTestId('bot-follow-mark')).toBeTruthy();
+ followScopes.mockResolvedValueOnce([]);
+ await act(async () => changed?.());
+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();
+});
+
+
+it('keeps different companions on their own task IDs, including directory-free tasks', async () => {
+ followScopes.mockResolvedValueOnce([{ botId: 'bot-1', sessionIds: ['s1'] }, { botId: 'bot-2', sessionIds: ['s2'] }]);
+ await act(async () => render(<><Row session={session({ workingDir: null })} /><Row session={session({ id: 's2' })} /><Row session={session({ deviceLinkDeviceId: 'remote' })} /></>));
+ expect(screen.getAllByTestId('bot-follow-mark').map(mark => mark.getAttribute('aria-label'))).toEqual(['bots.workbench.followingMark:Dash', 'bots.workbench.followingMark:Lizi']);
+});
+it('ignores a late responsibility snapshot after switching owners', async () => {
+ let finish!: (value: Array<{ botId: string; sessionIds: string[] }>) => void;
+ followScopes.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const view = render(<Row session={session()} />);
+ await act(async () => { setDataOwnerGeneration('next-owner'); view.rerender(<Row session={session()} />); });
+ followScopes.mockResolvedValueOnce([]);
+ await act(async () => { finish([{ botId: 'bot-1', sessionIds: ['s1'] }]); changed?.(); });
+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
index 99f1a17792..56e1c37b62 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
@@ -63,6 +63,7 @@ function delegation(childSessionId: string, status: WorkbenchDelegationInput['st
}
const base = {
+ responsibleSessionIds: ['running', 'asking', 'bg-queued', 'unjudged-idle', 'unjudged-errored', 'judged-unfinished', 'judged-done', 'claude-imported', 'kept', 'waiting', 'errored', 'queued-bg', 'judged', 'finished-bg', 'failed-bg'],
hiddenIds: new Set<string>(),
projectDirs: [ART],
caseInsensitive: false,
@@ -75,6 +76,16 @@ const base = {
};
describe('buildWorkbenchTiles', () => {
+ it('keeps verified creations outside all projects and without a directory, then honors release', () => {
+ const input = {
+ ...base,
+ projectDirs: [],
+ responsibleSessionIds: ['created-across', 'created-without-dir'],
+ sessions: [session('created-across', { workingDir: CINDY }), session('created-without-dir', { workingDir: null, userSendAt: null, _count: { messages: 0 } })],
+ };
+ expect(buildWorkbenchTiles(input).map(tile => tile.id).sort()).toEqual(['created-across', 'created-without-dir']);
+ expect(buildWorkbenchTiles({ ...input, responsibleSessionIds: [] })).toEqual([]);
+ });
it('derives each tile state from host signals only', () => {
const tiles = buildWorkbenchTiles({
...base,
@@ -99,7 +110,7 @@ describe('buildWorkbenchTiles', () => {
expect(byId.get('bg-queued')).toMatchObject({ state: 'queued', origin: 'delegated' });
});
- it('lists every recent Cindy task, but external sessions only when judged worth continuing', () => {
+ it('lists responsible Cindy tasks, never claiming external candidates from old judgments', () => {
const judgment = (verdict: 'unfinished' | 'idea' | 'done', title: string, project = ART) => ({
title,
verdict,
@@ -131,12 +142,10 @@ describe('buildWorkbenchTiles', () => {
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 的)都在;外部会话只留判为值得继续的。
+ // 逐任务负责的 Cindy 任务都在;旧外部判断不代表接手。
expect([...byId.keys()].sort()).toEqual(
[
'claude-imported',
- 'claude:ext-1',
- 'codex:ext-2',
'judged-done',
'judged-unfinished',
'running',
@@ -149,30 +158,25 @@ describe('buildWorkbenchTiles', () => {
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' });
+ expect(byId.has('claude:ext-1')).toBe(false);
+ expect(byId.has('codex:ext-2')).toBe(false);
// 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',
+ null,
+ null,
]);
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()],
+ ['todo', ['claude-imported', 'judged-unfinished'].sort()],
['done', ['judged-done', 'unjudged-idle']],
]);
});
- it('shows Pi sessions and PR / issue / idea entries the Bot wrote down, labelled by kind', () => {
+ it('keeps PR / issue / idea materials while excluding old Pi discovery judgments', () => {
const judgment = (verdict: 'unfinished' | 'idea' | 'done', title: string, extra: Record<string, unknown> = {}) => ({
title,
verdict,
@@ -194,8 +198,8 @@ describe('buildWorkbenchTiles', () => {
},
});
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.keys()].sort()).toEqual(['idea:dark-icons', 'issue:me/art#7', 'pr:me/art#12']);
+ expect(byId.has('pi:p1')).toBe(false);
expect(byId.get('pr:me/art#12')).toMatchObject({
type: 'item',
itemKind: 'pr',
@@ -212,6 +216,7 @@ describe('buildWorkbenchTiles', () => {
const tiles = buildWorkbenchTiles({
...base,
now,
+ responsibleSessionIds: ['stale-bg'],
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' }),
@@ -220,8 +225,7 @@ describe('buildWorkbenchTiles', () => {
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');
+ expect(tiles.map((tile) => tile.id).sort()).toEqual(['stale-bg']);
});
it('keeps Bot hidden sessions, other projects, drafts, remote, archived and non-task sources out', () => {
@@ -295,6 +299,7 @@ describe('buildWorkbenchTiles', () => {
const tiles = buildWorkbenchTiles({
...base,
projectDirs: [],
+ responsibleSessionIds: [],
sessions: [session('kept')],
routines: [{ id: 'r-1', name: '每日提醒', enabled: true, triggers: [], updatedAt: 1 }],
});
@@ -382,6 +387,7 @@ describe('groupWorkbenchTiles', () => {
const tiles = buildWorkbenchTiles({
...base,
now,
+ responsibleSessionIds: Array.from({ length: 33 }, (_, i) => `t-${i}`),
sessions: Array.from({ length: 33 }, (_, index) =>
session(`t-${index}`, {
updatedAt: new Date(now - (index + 1) * 60_000).toISOString(),
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx
index f968a3168a..f564a2fdb7 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx
@@ -162,3 +162,41 @@ it('does not resurrect a sidebar deletion when an older list response arrives',
await act(async () => resolve([page[0]]));
expect(result.current.rows).toEqual([]);
});
+
+it('reads exact responsibility IDs across directories and archives, excludes same-project bystanders', async () => {
+ mocks.list.mockResolvedValue([{ ...page[0], id: 'owned', workingDir: '/elsewhere' }]);
+ const { result, rerender } = renderHook(({ ids }) => useWorkbenchSessionPages('bot', 'archived', true, ids),
+ { initialProps: { ids: ['owned'] } });
+ await waitFor(() => expect(result.current.rows.map(r => r.id)).toEqual(['owned']));
+ expect(mocks.list).toHaveBeenCalledWith(200, 'archived', { fresh: true, before: undefined, ids: ['owned'] });
+ act(() => mocks.patch('unrelated', { status: 'archived' }, { ...page[1], id: 'unrelated' }));
+ expect(result.current.rows.map(r => r.id)).toEqual(['owned']);
+ rerender({ ids: [] });
+ await waitFor(() => expect(result.current.rows).toEqual([]));
+});
+it('does not infer tasks from a host without responsibility IDs', async () => {
+ const { result } = renderHook(() => useWorkbenchSessionPages('old-host', 'active', true, []));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.rows).toEqual([]);
+ expect(mocks.list).not.toHaveBeenCalled();
+});
+
+it('shows the newest responsible tasks first across pages and reorders update patches', async () => {
+ const ids = Array.from({ length: 201 }, (_, n) => `owned-${String(n).padStart(3, '0')}`);
+ const newest = { ...page[0], id: ids[200], updatedAt: new Date(5000).toISOString() };
+ const older = { ...page[0], id: ids[0], updatedAt: new Date(1).toISOString() };
+ const first = [newest, ...ids.slice(1, 200).map((id, n) => ({ ...page[0], id, updatedAt: new Date(4999 - n).toISOString() }))];
+ mocks.list.mockResolvedValueOnce(first).mockResolvedValueOnce([older]);
+ const { result } = renderHook(() => useWorkbenchSessionPages('b', 'archived', true, ids));
+ await waitFor(() => expect(result.current.rows).toHaveLength(200));
+ expect(result.current.rows[0].id).toBe(ids[200]);
+ expect(result.current.hasMore).toBe(true);
+ await act(() => result.current.load());
+ expect(mocks.list).toHaveBeenLastCalledWith(200, 'archived', {
+ fresh: true, ids, before: { updatedAt: 4801, id: ids[199] },
+ });
+ expect(result.current.rows.at(-1)?.id).toBe(ids[0]);
+ act(() => mocks.patch(ids[0], { updatedAt: new Date(6000).toISOString() }));
+ expect(result.current.rows[0].id).toBe(ids[0]);
+ expect(result.current.hasMore).toBe(false);
+});
diff --git a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
index c72b86edc1..4f190ccc24 100644
--- a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
+++ b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
@@ -1,8 +1,5 @@
-/**
- * 侧栏「<伙伴>在跟进」的数据:每个在用的本机伙伴接手了哪些项目。
- *
- * 整个窗口共享一份:第一次有任务行订阅时读一次,之后只在伙伴工作台变化或换账号时重读。
- * 任务行各自只做本地匹配(与工作台同一套项目归属规则 `findWorkbenchProject`),不各自发 IPC。
+/** Window-shared exact task responsibility IDs. Project discovery never implies ownership.
+ * Older hosts without task IDs produce no marks; changes and owner switches reload the snapshot.
*/
import { useMemo, useSyncExternalStore } from 'react';
@@ -10,18 +7,14 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts
import type { Session } from '@/lib/ccAgent.types';
import { createLogger } from '@/lib/logger';
-import {
- findWorkbenchProject,
- isCaseInsensitivePlatform,
- isWorkbenchTaskSource,
-} from '../../../shared/botWorkbench';
+import { isWorkbenchTaskSource } from '../../../shared/botWorkbench';
import { ensureBotProfilesLoaded, hasLoadedBotProfiles, useBotProfiles, type BotProfile } from './botStore';
const log = createLogger('BotFollowScopes');
export interface BotFollowScope {
botId: string;
- directories: readonly string[];
+ sessionIds?: readonly string[];
}
const EMPTY: readonly BotFollowScope[] = [];
@@ -61,6 +54,9 @@ function load(attempt = 0): void {
emit();
})
.catch((error: unknown) => {
+ if (seq !== loadSeq || !isDataOwnerGenerationCurrent(loadOwner)) return;
+ scopes = EMPTY;
+ emit();
log.warn('Bot follow scopes load failed', error);
const delay = RETRY_DELAYS_MS[attempt];
if (seq !== loadSeq || delay === undefined) return;
@@ -84,7 +80,8 @@ function subscribe(listener: () => void): () => void {
if (!changeSubscribed) {
// 窗口级订阅,不随任务行挂载 / 卸载反复增删(侧栏滚动时行会频繁重建)。
const off = window.electronAPI?.maker?.onBotWorkbenchChanged?.(() => load());
- changeSubscribed = off !== undefined;
+ const offDelegation = window.electronAPI?.maker?.onBotDelegationChanged?.(() => load());
+ changeSubscribed = off !== undefined || offDelegation !== undefined;
}
ensureOwner();
if (!requested) {
@@ -110,24 +107,23 @@ function getSnapshot(): readonly BotFollowScope[] {
/** 能被伙伴跟进的任务:本机、未归档、普通来源、不是伙伴自己的任务或 Orca worker。 */
function isFollowableSession(session: Session): boolean {
- if (session.status !== 'active' || !session.workingDir) return false;
+ if (session.status !== 'active') return false;
if (session.remoteHostId || session.deviceLinkDeviceId) return false;
if (session.source === 'bot' || session.orcaRole === 'worker') return false;
return isWorkbenchTaskSource(session.source);
}
-/** 正在跟进这件任务所在项目的伙伴(按名字排序;隐藏、停用的伙伴不显示)。 */
+/** 正在负责这件任务的伙伴(按名字排序;隐藏、停用的伙伴不显示)。 */
export function useSessionFollowers(session: Session): BotProfile[] {
const followScopes = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
const profiles = useBotProfiles();
const followable = isFollowableSession(session);
- const workingDir = session.workingDir;
+ const sessionId = session.id;
return useMemo(() => {
if (!followable || followScopes.length === 0) return [];
- const caseInsensitive = isCaseInsensitivePlatform(window.electronAPI?.platform);
const following = new Set(
followScopes
- .filter((scope) => findWorkbenchProject(workingDir, scope.directories, caseInsensitive) !== null)
+ .filter((scope) => Array.isArray(scope.sessionIds) && scope.sessionIds.includes(sessionId))
.map((scope) => scope.botId),
);
if (following.size === 0) return [];
@@ -135,7 +131,7 @@ export function useSessionFollowers(session: Session): BotProfile[] {
.filter((bot) => following.has(bot.id) && bot.enabled && !bot.hiddenAt
&& (bot.status === undefined || bot.status === 'active'))
.sort((a, b) => a.name.localeCompare(b.name));
- }, [followable, followScopes, profiles, workingDir]);
+ }, [followable, followScopes, profiles, sessionId]);
}
export const __testing = {
diff --git a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
index e604f16ca6..ebb85417fc 100644
--- a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
+++ b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
@@ -6,8 +6,8 @@
* 输出两样东西:
* - 空状态的项目清单:复用任务列表的项目分组(`groupSessions`),合并本机 Claude Code /
* Codex 的可导入候选与项目里的自动化;
- * - 已接手项目的任务列表:项目里最近 30 天的 Cindy 任务一律列出(含主人自己开的,不管伙伴判断过没有);
- * 本机外部会话与伙伴从项目素材里写下的 PR / issue / 建议只在伙伴判为「没做完 / 聊过没下文」时列出;
+ * - 负责的任务列表:Cindy 任务只按创建凭据或明确逐任务责任列出,不依赖目录或旧判断;
+ * 外部会话保留为发现参考,不因旧判断上负责列表;PR / issue / 建议沿用既有素材条目;
* 另有伙伴自己开的后台任务与自动化;状态用 `shared/botWorkbench.ts` 与主进程同一套规则推导,
* 再由 `groupWorkbenchTiles` 分成 等你 / 在做 / 待做 / 做完 四组。
*/
@@ -22,7 +22,6 @@ import {
deriveWorkbenchSessionState,
findWorkbenchProject,
importedSessionOrigin,
- WORKBENCH_RECENT_WINDOW_MS,
externalWorkbenchTaskId,
isWorkbenchTaskSource,
parseWorkbenchTaskId,
@@ -212,8 +211,8 @@ export function isWorkbenchCandidateSession(
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;
+ if (!session.workingDir) return false;
return session.userSendAt != null || (session._count?.messages ?? 0) > 0;
}
@@ -380,12 +379,13 @@ function sessionLine(
}
/**
- * 已接手项目的条目:项目里最近 30 天的 Cindy 任务(含主人自己开的,不论有无判断)、伙伴开的后台任务、
- * 伙伴判为没做完 / 聊过没下文的本机外部会话与 PR / issue / 建议、项目里的自动化、伙伴自己的例行任务
+ * 责任条目:逐任务明确接手的 Cindy 任务、伙伴自己创建的任务(不限目录或最近活动)、
+ * PR / issue / 建议、项目里的自动化、伙伴自己的例行任务
* (含导入来的自动化)。排列见 `workbenchTileRank`,分组见 `groupWorkbenchTiles`。
*/
export function buildWorkbenchTiles(input: {
sessions: readonly Session[];
+ responsibleSessionIds?: readonly string[];
hiddenIds: ReadonlySet<string>;
projectDirs: readonly string[];
caseInsensitive: boolean;
@@ -397,10 +397,9 @@ export function buildWorkbenchTiles(input: {
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)) {
@@ -409,11 +408,12 @@ export function buildWorkbenchTiles(input: {
}
}
const delegationChildIds = new Set(delegationByChild.keys());
+ const responsibleIds = new Set(input.responsibleSessionIds ?? delegationChildIds);
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;
+ if (!isWorkbenchCandidateSession(session, input.hiddenIds, responsibleIds)) continue;
+ if (!responsibleIds.has(session.id)) continue;
const delegation = delegationByChild.get(session.id) ?? null;
const activity = input.activity.get(session.id) ?? null;
const interrupted = hasPendingSessionInterruption(session);
@@ -425,11 +425,8 @@ export function buildWorkbenchTiles(input: {
});
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;
+ // Responsibility survives project moves and idle time; status remains host-derived.
tiles.push({
type: 'session',
key: `session:${session.id}`,
@@ -447,12 +444,6 @@ export function buildWorkbenchTiles(input: {
});
}
- 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);
@@ -478,20 +469,6 @@ export function buildWorkbenchTiles(input: {
});
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) {
diff --git a/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts
index 9ea76cee22..41b0684277 100644
--- a/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts
+++ b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { Session } from '@/lib/ccAgent.types';
import * as sessionService from '@/lib/sessionService';
import {
@@ -16,7 +16,11 @@ export function useWorkbenchSessionPages(
scope: string,
status: 'active' | 'archived',
enabled: boolean,
+ responsibleIds?: readonly string[],
) {
+ const idKey = responsibleIds === undefined ? undefined : JSON.stringify([...new Set(responsibleIds)].sort());
+ const ids = useMemo<string[] | undefined>(() => idKey === undefined ? undefined : JSON.parse(idKey), [idKey]);
+ const allowed = useMemo(() => ids ? new Set(ids) : null, [ids]);
const [rows, setRows] = useState<Session[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
@@ -42,9 +46,11 @@ export function useWorkbenchSessionPages(
...(patch._count ? { _count: { ...current._count, ...patch._count } } : {}),
});
}
- return [...next.values()].filter((row) => row.status === status);
+ return [...next.values()]
+ .filter((row) => row.status === status && (!allowed || allowed.has(row.id)))
+ .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt) || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0));
},
- [status],
+ [status, allowed],
);
const load = useCallback(
async function readPages(refresh = false): Promise<void> {
@@ -68,11 +74,16 @@ export function useWorkbenchSessionPages(
// Reconcile the already loaded window, not just its head: missing rows may
// have been deleted or moved while disconnected. Never scan unseen history.
for (; fetched < pages;) {
- const page = await sessionService.list(PAGE_SIZE, status, { fresh: true, before });
+ let page: Session[];
+ if (ids?.length === 0) {
+ page = [];
+ } else {
+ page = await sessionService.list(PAGE_SIZE, status, { fresh: true, before, ...(ids ? { ids } : {}) });
+ }
+ more = page.length === PAGE_SIZE;
if (version !== generation.current || !isDataOwnerGenerationCurrent(owner)) return;
collected.push(...page);
fetched++;
- more = page.length === PAGE_SIZE;
const tail = page.at(-1);
if (tail) before = { updatedAt: Date.parse(tail.updatedAt), id: tail.id };
if (!more) break;
@@ -105,7 +116,7 @@ export function useWorkbenchSessionPages(
}
}
},
- [status, applyMutations],
+ [status, applyMutations, ids],
);
useEffect(() => {
const reset = () => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f2e779ea26..9d8276ce04 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8608,7 +8608,7 @@
"message": "Follow up on “{{title}}”",
"aria": "Follow up on “{{title}}”"
},
- "followingMark": "Looked after by {{names}}",
+ "followingMark": "This task is looked after by {{names}}",
"olderCount_one": "{{count}} older",
"olderCount_other": "{{count}} older",
"kind": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index dbf2810849..34007f38f7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8571,7 +8571,7 @@
"message": "「{{title}}」を進めて",
"aria": "「{{title}}」を進める"
},
- "followingMark": "このプロジェクトの担当: {{names}}",
+ "followingMark": "このセッションの担当: {{names}}",
"olderCount_other": "さらに前の {{count}} 件",
"kind": {
"existing": "既存のセッション",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0a8db6b210..be6eac0efe 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8571,7 +8571,7 @@
"message": "「{{title}}」 이어서 진행해 줘",
"aria": "「{{title}}」 진행하기"
},
- "followingMark": "이 프로젝트 담당: {{names}}",
+ "followingMark": "이 세션 담당: {{names}}",
"olderCount_other": "이전 {{count}}개",
"kind": {
"existing": "기존 세션",
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 8b6e006a57..6a93aede2f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8571,7 +8571,7 @@
"message": "跟进「{{title}}」",
"aria": "跟进「{{title}}」"
},
- "followingMark": "{{names}}在跟进这个项目",
+ "followingMark": "{{names}}在跟进这个任务",
"olderCount_other": "更早的 {{count}} 个",
"kind": {
"existing": "原有任务",
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 e26391c6a1..5afadec9dd 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8571,7 +8571,7 @@
"message": "跟進「{{title}}」",
"aria": "跟進「{{title}}」"
},
- "followingMark": "{{names}}在跟進這個專案",
+ "followingMark": "{{names}}在跟進這個任務",
"olderCount_other": "更早的 {{count}} 個",
"kind": {
"existing": "原有任務",
diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.ts
index 92d9a5c296..34be9a24e5 100644
--- a/apps/desktop/src/renderer/lib/sessionService.ts
+++ b/apps/desktop/src/renderer/lib/sessionService.ts
@@ -57,6 +57,8 @@ const getInFlight = new Map<string, Promise<Session>>();
export type SessionListOptions = {
/** Local list continuation; does not change the default capped query. */
before?: { updatedAt: number; id: string };
+ /** Local renderer-only exact subset, filtered before sorting and pagination. */
+ ids?: string[];
includePinned?: boolean;
/** forceRefresh / status 重拉:绕开 main 侧 in-flight 合并。 */
fresh?: boolean;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f14fb96da6..cbb1f15577 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4870,8 +4870,8 @@ interface ElectronAPI {
}
| { ok: false; errorCode: string; message: string }
>;
- /** 每个在用的本机伙伴接手的项目目录(侧栏「在跟进」标记用)。 */
- followScopes: () => Promise<Array<{ botId: string; directories: string[] }>>;
+ /** 每个在用本机伙伴的逐任务责任 ID;旧宿主缺字段时不推断。 */
+ followScopes: () => Promise<Array<{ botId: string; sessionIds?: string[] }>>;
};
listSkills: (botId: string) => Promise<import('../shared/botSkill').BotSkillSummary[]>;
memory: {
diff --git a/apps/desktop/src/shared/botWorkbench.ts b/apps/desktop/src/shared/botWorkbench.ts
index 3e48eb0062..044f8bf791 100644
--- a/apps/desktop/src/shared/botWorkbench.ts
+++ b/apps/desktop/src/shared/botWorkbench.ts
@@ -45,6 +45,8 @@ export interface WorkbenchTaskJudgment {
export const WORKBENCH_REF_MAX = 2_000;
export interface BotWorkbench {
+ /** Verified creation plus explicit take/release. Older hosts omit it; never infer from directories. */
+ responsibleSessionIds?: string[];
directories: BotWorkbenchDirectory[];
/** 按 task_id 记录的伙伴判断。 */
tasks: Record<string, WorkbenchTaskJudgment>;
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index e28b76087c..ca19476b51 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -479,21 +479,36 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
以下原项目工具仍供项目素材和普通任务使用,不再作为新 Todo 的存储接口。
2026-10-01 产品裁决(用户已同意):伙伴可以查看、继续「用户明确交给它的项目」里的任务(停止走通用的
-`stop_session_turn`,沿用当前 Agent 权限)。2026-10-02 起工作台是伙伴的「负责范围」:不设项目数上限,主人可以口头交代。
+`stop_session_turn`,沿用当前 Agent 权限)。2026-10-02 起主人可以口头交代项目;2026-10-12 起项目范围与逐任务责任分离。
同日用户实机试用后多次修订,最终口径:
1. **接手 = 理解,不是搬运**——伙伴先读懂项目里已有的工作,写下判断;主人点头(或点「跟进」)的那一件才
继续。不批量导入、不搬运已完成的外部会话。
2. **项目是目录,素材不只是会话**——伙伴要先看项目本身(文档、git、PR 与 issue),会话只看起始目的和
- 最后几条,不读全文;一律只看近期(30 天内),读取有界、带缓存。
-3. **项目里的任务都是伙伴知道的项目事务**——已接手项目里的 Cindy 任务(包括主人之后自己开的)不论伙伴判断
- 过没有都在工作台上、也都在 `get_workbench` 里;只有还没导入的外部会话要等伙伴判断后才上工作台。
+ 最后几条,不读全文;项目发现只看近期(30 天内),读取有界、带缓存,已负责的任务不限活动时间。
+3. **逐任务责任(2026-10-12 修订)**——项目授权只决定发现范围。普通任务无责任关系就不挂伙伴头像,
+ 也不进入伙伴的负责列表。责任只来自宿主可验证的创建来源,或伙伴明确接手单个任务的持久记录。
+ 同目录、标题、最近消息、旧判断均不是证据,不做全目录回填。普通项目列表、任务生命周期和 Todo 不变。
+
+责任独立保存在伙伴 Home 的 `task-responsibility.v1.json`,不改旧工作台文件或 Todo。历史仅从
+`bot_delegations.requesting_bot_id/child_session_id` 读取可验证创建关系;通用 `send_to_session` 新建成功
+后记录真实创建回执,历史缺少创建证明时不猜测。解除记录覆盖创建来源,防止刷新或重启后重新出现。
+损坏记录失败关闭,不能用空对象覆盖;账号切换时丢弃旧读取与写入。存储采用跨进程锁和原子替换,
+容量溢出明确拒绝,不淘汰责任或解除记录。
+
+`set_workbench_task_responsibility(task_id, responsible)` 只允许本机在用伙伴主任务反查自身身份,
+不接受 botId。普通任务接手须仍在已授权项目内,目标不可是远端、隐藏伙伴任务、归档/删除、Orca worker
+或他人委派。解除自身关系允许任务已归档或移动项目,不停止、不移动、不归档、不重建原任务。
+伙伴自己创建的跨目录任务仍显示;没有项目授权时也显示。工作台活跃与归档列表按同一责任 ID 集合,
+复用原任务组件和菜单,按现有 `sessions:get-many` 有界取数;不扫描无关任务历史。
+明确 `continue_workbench_task` 在投递前保存单任务接手,保存失败不执行投递。单纯登记接手不启动执行,
+不自动订阅所有消息,不宣称已在自动管理;后续执行仍用既有任务工具和权限。Todo 独立保持。
- **授权来源**:只来自主人的「交给<伙伴>」——在伙伴工作台里点选,或主人本人那一轮口头交代、伙伴用
`add_workbench_project` 记下(沿用当前 Agent 权限,见 6.4;只收存在的绝对路径目录,不收磁盘根目录、
主目录与 Cindy 数据目录,符号链接按它指向的真实目录同样判定)。宿主把项目目录记在该伙伴 Home 的 `workbench.json`(`directories`,去重;
不设产品上限,只有 50 个的防护上限),主人可以随时在工作台上移除,或让伙伴用 `remove_workbench_project`
- 移除,移除即收回,项目里的任务、文件与伙伴写过的判断都不动。工具不接受 botId。移除在进行中的调用里同样
+ 移除,移除即收回项目发现授权,项目里的任务、文件、逐任务责任、Todo 与伙伴写过的判断都不动。工具不接受 botId。移除在进行中的调用里同样
生效:返回内容、投递之前宿主会再确认一次项目仍在。
- **范围**:已接手项目里的普通本机任务(项目目录本身及其子目录,按目录边界比较;worktree 归到主仓库;
交了嵌套的项目时归到最深的那个);工作目录
@@ -512,7 +527,7 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
`pi-agent-home/sessions`。所有根都按项目 cwd 过滤、只看 mtime 在 30 天内的。「当前库里已有这一条」
只用来避免同一件事显示两次,不用来排除来源。
- **读取边界**(`maker-ipc/botWorkbenchTranscripts.ts`):近期文件先只读开头 16KB 找 cwd,不在项目里的
- 直接丢掉;项目里最新的至多 30 条才读头尾各 64KB 算摘要(首行超长时跳过它再取头部,至多往后找 1MB),
+ 直接丢掉;项目里最新的至多 30 条只带元数据,不预读消息摘要;明确读取时才读头尾各 64KB(首行超长时跳过它再取头部,至多往后找 1MB),
按文件 mtime + size 缓存。Cindy 任务的摘要是两条有界查询(第一条用户消息、最后 3 条),按 updatedAt
缓存。更早的只计数(`olderCount`),不读。
- **项目素材 brief**(`maker-ipc/botWorkbenchBrief.ts`):宿主现算、只给事实不下结论——顶层与
@@ -524,12 +539,15 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
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`、伙伴自己的例行任务与项目里的自动化。项目很多时只有最近交代的
- 前 8 个现算 brief,其余项目 `brief` 为 null,伙伴需要时用自己的文件工具看。
+ - `get_workbench`:每个项目带 brief;`tasks` 只给逐任务负责的 Cindy 任务(最多 30 条),
+ 含真实状态、判断与有界 digest;伙伴自建任务不限目录或活动时间。`candidates` 独立给最多 40 条
+ 项目发现元数据(ID、来源、标题、项目),不表示责任、不读取普通候选任务正文。需要内容时明确调用
+ `read_workbench_task`。PR / issue / 建议判断、例行任务与已授权项目自动化沿用已有来源。
+ 工作台界面的负责列表沿用更新时间倒序(同时间按 ID 倒序)的稳定分页;本机可信 Renderer
+ 通过既有 `sessions:list` 的可选 `ids` 精确子集参数先过滤再选页,活跃与归档分别读取。
+ 该参数最多 10000 个 ID,不用于 usageHistory / includePinned,远端调用不接受;普通列表不传时行为不变。
+ 侧栏逐伙伴隔离责任读取错误:损坏伙伴不显示标记且不回退认领,其余伙伴保留真实标记;不改写坏文件。
+ 项目很多时前 8 个现算 brief,其余为 null。`totalTasks/truncated` 仅计负责的任务;发现用 `totalCandidates/candidatesTruncated/olderCount` 独立报告。
- `read_workbench_task`:digest 不够判断时才用;只读一件会话最近的用户 / 助手文字(约 4000 字),
本机会话只读转录头尾,不写库、不导入。PR / issue / 建议没有对话记录,返回 `TASK_NOT_READABLE`。
- `set_workbench_task` / `set_workbench_tasks`(批量 1–30 条,逐条校验、一次广播):伙伴写下理解——
@@ -555,11 +573,10 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
伙伴不提供工作台。读写工作台与继续任务沿用当前 Agent 权限(6.4)。
- **校验位置**:每次调用在 main 里确定性校验(`maker-ipc/botWorkbenchAccess.ts`),越权返回明确
错误码且不读、不写、不投递;工作台详情视图读同一份摘录时也按该伙伴已接手的项目判定范围。
-- **工作台显示什么**:已接手项目里最近 30 天的 Cindy 任务一律列出——包括主人自己开的、伙伴还没判断过的;
- 新开的任务随任务列表的实时数据(`sessionsStore`,与左侧任务列表同源)立刻出现;伙伴开的后台任务照常列出。
- 本机外部会话(Claude Code / Codex / Pi,还没导入的)与 PR / issue / 建议只在伙伴判为没做完 / 聊过没下文时
- 列出。伙伴还在读时(项目里有候选没判断,且伙伴
- 主任务正在运行),列表上方显示一行「<伙伴>正在了解 <项目>…」。
+- **工作台显示什么**:Cindy 任务只按可验证逐任务责任列出,原项目普通列表保持完整。
+ 伙伴自己创建的任务跨目录、没有项目授权也出现;普通任务明确接手才出现,解除后从伙伴列表消失。
+ 任务状态、归档和列表刷新沿用原组件;旧外部会话判断保留为发现参考,不进入负责列表。
+ 项目发现元数据和已授权素材单独保留,Todo 独立显示。
- **列表形态**(2026-10-01 用户实机后裁决:不用格子卡片,读起来累):单列,按「等你 / 在做 / 待做 / 做完」
四组排列,组标题带数量,空组不出,「做完」默认折叠。等你 = 等回复或出错 / 被打断 / 后台任务失败;
在做 = 正在跑的任务与自动化;待做 = 伙伴判为没做完 / 聊过没下文的、排队中的、PR / issue / 建议;
@@ -588,12 +605,12 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
还没接手任何项目时也显示在「交给<伙伴>一个项目」下方;待命与停用的都归「做完」,第二层写周期与下次运行或
「已停用」。导入来的自动化
待适配的具体原因存于加密的导入环境里,工作台暂不单独呈现。
-- 伙伴用 `start_session_task` 在已接手项目里开的任务照常是后台任务,同时出现在工作台的任务列表里。
-- **侧栏「在跟进」标记**:普通任务所在的项目交给了伙伴时,左侧任务行标题后(任务标签之后)显示该伙伴的
- 14px 头像,悬停说明「<伙伴>在跟进这个项目」;有多个伙伴时显示按名字排第一的,悬停列出全部。只认本机、
- 在用、未隐藏的伙伴;哪些任务算、项目怎么匹配与上面的「范围」同一套规则(`findWorkbenchProject`)。
- 数据经 `local-db:bots:workbench:follow-scopes` 一次取回各伙伴的项目路径(只给路径,不带判断与会话内容),
- 整个窗口共享一份,工作台变化或换账号时重读。
+- 伙伴用 `start_session_task` 自己开的任务照常是后台任务,无论目录都在负责列表里;显式解除责任后隐藏,执行回传契约不变。
+- **侧栏「在跟进」标记**:只在任务 ID 对应可验证责任关系时显示原 14px 伙伴头像,
+ 悬停说明该伙伴在跟进这个任务;多伙伴分别保存自身关系,按名字展示,不互相认领。
+ 只认本机、在用、未隐藏的伙伴,远端镜像不套用本机 ID。`follow-scopes` 只返回逐任务
+ `sessionIds`,不带正文,旧 `directories` 字段保留空数组,防止旧渲染端按项目误认领。工作台/委派变化或换账号时重读;旧宿主只有目录、缺字段或读取失败
+ 时不推断、不显示。Light/Dark 保留原组件样式,引擎图标、状态和任务菜单均保持。
- 界面:工作台是本机伙伴主任务全局右侧栏里的一个标签(与文件、浏览器并列),首次进入时自动创建
并展开右侧栏;已有侧栏布局选择时不自动创建或展开。关闭标签或收起侧栏后,返回伙伴、切换页面和重启
都保留选择;伙伴聊天头部常驻「工作台」入口,用户点击后重新创建或激活标签并展开。伙伴页保留全局右侧栏的其它能力。
diff --git a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
index 45f2761363..b0a34380a7 100644
--- a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
@@ -37,6 +37,7 @@ const snapshot = {
function setup(sessionId: string | null = 'bot-session', todos?:BotWorkbenchCallbacks['todos']) {
const callbacks: BotWorkbenchCallbacks = {
...(todos ? {todos} : {}),
+ setResponsibility: vi.fn(async ({ taskId, responsible }) => ({ ok: true as const, taskId, responsible })),
get: vi.fn(async () => ({ ok: true as const, workbench: snapshot })),
read: vi.fn(async ({ taskId }: { taskId: string }) => ({
ok: true as const,
@@ -225,3 +226,27 @@ describe('teammate affair discovery tools',()=>{
expect(response.isError).toBe(true);expect(callback).not.toHaveBeenCalled();
});
});
+
+it('takes/releases by exact task ID with caller-derived bot identity', async () => {
+ const { reg, callbacks } = setup();
+ for (const responsible of [true, false]) {
+ expect(parse(await reg.call('set_workbench_task_responsibility', { task_id: 'one', responsible })))
+ .toMatchObject({ ok: true, task_id: 'one', responsible });
+ expect(callbacks.setResponsibility).toHaveBeenLastCalledWith({ callerSessionId: 'bot-session', taskId: 'one', responsible });
+ }
+ vi.mocked(callbacks.setResponsibility!).mockClear();
+ expect(parse(await reg.call('set_workbench_task_responsibility', { task_id: 'one', responsible: true, bot_id: 'other' })).ok).toBe(false);
+ expect(parse(await reg.call('set_workbench_task_responsibility', { task_id: 'one', responsible: 'yes' })).ok).toBe(false);
+ expect(callbacks.setResponsibility).not.toHaveBeenCalled();
+});
+
+
+it('keeps older hosts usable without advertising an unavailable responsibility writer', () => {
+ const { callbacks } = setup();
+ delete callbacks.setResponsibility;
+ const reg = new XdtHelperToolRegistry();
+ registerBotWorkbenchTools(reg, { callbacks, getSessionContext: () => ({ sessionId: 'main', agentKind: 'claude-code', workingDir: '/w' }) });
+ const names = reg.list('bots').map(tool => tool.name);
+ expect(names).toContain('get_workbench');
+ expect(names).not.toContain('set_workbench_task_responsibility');
+});
diff --git a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
index d6bad57266..0ac1351e19 100644
--- a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
@@ -459,3 +459,10 @@ describe('send_to_session · working_dir (#811)', () => {
expect(parse(res)).toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
});
});
+
+
+it('reports a failed responsibility write without hiding successful task creation', async () => {
+ const { registry, sendToSession } = setup({ result: { ok: true, targetSessionId: 'new-task', agentKind: 'claude-code', wakeKind: 'created', responsibilityRecorded: false, targetTitle: null, targetLastUserSendAt: null } });
+ expect(parse(await registry.call('send_to_session', { message: 'Work' }))).toMatchObject({ ok: true, target_session_id: 'new-task', responsibility_recorded: false });
+ expect(sendToSession).toHaveBeenCalledOnce();
+});
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
index 165096177e..94bc7ffc4e 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
@@ -117,12 +117,16 @@ export interface WorkbenchAutomationWire {
export interface BotWorkbenchSnapshotWire {
projects: WorkbenchProjectWire[];
tasks: WorkbenchTaskWire[];
+ /** Project discovery metadata; discovery does not confer responsibility. */
+ candidates?: Array<{ taskId: string; source: string; title: string; project: string }>;
items: WorkbenchItemWire[];
automations: WorkbenchAutomationWire[];
counts: Record<WorkbenchVerdictWire | 'unjudged', number>;
- /** 候选多于返回条数时为 true;totalTasks 是实际总数。 */
+ /** Responsible tasks only; discovery counts are reported separately. */
truncated: boolean;
totalTasks: number;
+ totalCandidates?: number;
+ candidatesTruncated?: boolean;
/** 超过 30 天没动、没有列出的会话数。 */
olderCount: number;
}
@@ -142,6 +146,7 @@ export interface WorkbenchTranscriptWire {
}
export interface BotWorkbenchCallbacks {
+ setResponsibility?: (params: { callerSessionId: string; taskId: string; responsible: boolean }) => Promise<ControlResult<{ taskId: string; responsible: boolean }, string>>;
todos?: (
callerSessionId: string,
operation: 'list' | 'update' | 'preflight' | 'ingest',
@@ -252,13 +257,29 @@ export function registerBotWorkbenchTools(
const callerSessionId = () => deps.getSessionContext().sessionId ?? null;
if (deps.callbacks.todos) registerTodoTools(registry, callerSessionId, deps.callbacks.todos);
+ if (deps.callbacks.setResponsibility) {
+ const change = deps.callbacks.setResponsibility;
+ registry.register({
+ name: 'set_workbench_task_responsibility',
+ category: 'bots',
+ description: 'Explicitly take or release responsibility for one Cindy task. Only take work you have agreed to handle within an authorized project. Creation is verified by the host. Release only changes your responsibility; it does not stop, move, archive or delete the task, and does not affect Todo. Taking responsibility alone does not start execution, subscribe to messages or promise automatic management. Use existing task tools to act. Project discovery and judgments are not responsibility.',
+ inputShape: { task_id: z.string().min(1).max(256), responsible: z.boolean() },
+ handler: async ({ task_id, responsible }) => {
+ const id = callerSessionId();
+ if (!id) return missingSession();
+ const result = await change({ callerSessionId: id, taskId: task_id, responsible });
+ return result.ok ? okPayload({ task_id: result.taskId, responsible: result.responsible }) : errorPayload(result.errorCode, result.message);
+ },
+ });
+ }
+
registry.register({
name: 'get_workbench',
category: 'bots',
description:
- '读取已接手项目内的普通任务、项目素材和旧工作台判断。普通任务保留自己的生命周期。' +
+ '读取逐件负责的任务、项目素材和旧工作台判断。tasks 只含你自己创建或明确接手的任务;candidates 是项目发现元数据,不表示由你负责,也不自动读取其正文。普通任务保留自己的生命周期。' +
'伙伴事务清单请用 list_teammate_todos / update_teammate_todo,可没有项目;不要逐个复制任务。' +
- '会话限近期30天/30条,连外部会话最多40条;会话判断不返回ref,不能据此覆盖未知旧引用。' +
+ '负责的任务最多30条、不按目录或活动时间排除;项目发现候选最多40条,只给元数据;会话判断不返回ref,不能据此覆盖未知旧引用。' +
'旧判断有200条上限、done优先淘汰,不是新Todo历史。项目过滤仅影响此项目视图。',
inputShape: {},
handler: async () => {
@@ -372,10 +393,10 @@ export function registerBotWorkbenchTools(
name: 'add_workbench_project',
category: 'bots',
description:
- '把主人这台电脑上的一个项目目录交给你跟进,工作台立刻多出这个项目;之后它就在你的负责范围里,主人事先安排的那几轮也能处理它里面的任务。'
+ '把主人这台电脑上的一个项目目录加入你的发现范围,工作台立刻多出这个项目;这不代表接管项目里所有任务。逐任务责任另用 set_workbench_task_responsibility 明确登记。'
+ '只在主人本人这一轮明确说要交给你(例如「这个项目以后你盯着」「把 ~/code/foo 交给你」)时用;不要因为聊到某个项目就自己加。'
+ 'path 填绝对路径;主人只说了项目名时先用 list_projects 找到它的路径。不能交整个磁盘根目录或主目录。'
- + '加完先 get_workbench 接手,再用几句话告诉主人你看到了什么。',
+ + '加完先 get_workbench 看素材与候选,再用几句话告诉主人你看到了什么;逐任务接手另行明确。',
inputShape: {
path: z.string().min(1).max(4096).describe('项目目录的绝对路径'),
},
@@ -393,7 +414,7 @@ export function registerBotWorkbenchTools(
name: 'remove_workbench_project',
category: 'bots',
description:
- '主人本人这一轮说不用你再管某个项目时,把它从你的工作台移除。项目里的任务、文件和你写过的判断都不会被删,只是不再归你跟进。'
+ '主人本人这一轮说不用你再管某个项目时,把它从你的工作台移除。项目里的任务、文件和你写过的判断都不会被删,只收回项目发现授权,逐任务责任和 Todo 保持独立。'
+ 'path 用 get_workbench 里该项目的 path(也可以写 ~/ 开头)。工作台里没有这个项目时返回 PROJECT_NOT_IN_WORKBENCH,什么都没移除,照实告诉主人。',
inputShape: {
path: z.string().min(1).max(4096).describe('要移除的项目路径'),
diff --git a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
index 17d531f8a3..13c3614034 100644
--- a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
+++ b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
@@ -39,6 +39,7 @@ export type SendToSessionCallback = (params: {
}) => Promise<
ControlResult<
{
+ responsibilityRecorded?: false;
targetSessionId: string;
agentKind: ControlWorkerAgent;
wakeKind: "resumed" | "already-active" | "created" | "queued";
@@ -239,6 +240,7 @@ export function registerSendToSessionTool(
target_session_id: result.targetSessionId,
agent_kind: result.agentKind,
wake_kind: result.wakeKind,
+ ...(result.responsibilityRecorded === false ? { responsibility_recorded: false, responsibility_note: "Task creation succeeded, but the responsibility record could not be saved. Do not recreate or resend this task; reconcile the responsibility with the host." } : {}),
...(result.wakeKind === "created"
? { note: createdNote(result.targetSessionId) }
: {}),