Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(bots): implement independent teammate Todo workflows

zqchris2f8757950249
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
index b5e0e13348..115ccb8518 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceProvider.test.ts
@@ -66,7 +66,7 @@ it('rejects a previously discovered hidden companion and allows it again after r
await expect(get()).resolves.toMatchObject({
display: { title: 'Sora' },
- links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'session-1' } }],
+ links: expect.arrayContaining([{ rel: 'conversation', target: { kind: 'session', sessionId: 'session-1' } },expect.objectContaining({rel:'todos',target:{kind:'resource',ref:{collectionId:'teammates',kind:'bot',id:'todos:bot-1'}}})]),
});
const receiveRemote = vi.fn(async () => ({ ok: false as const, errorCode: 'TEST_RECEIPT', message: 'test' }));
const verifyRemoteMessage = vi.fn(async () => true);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts
new file mode 100644
index 0000000000..5ec131ab6a
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { mkdtemp, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+const env = vi.hoisted(() => ({ visible: true, current: true, access: vi.fn(), get: vi.fn() }));
+vi.mock('../../../agent-island/service.js', () => ({ getAgentIslandService: () => null }));
+vi.mock('../../../maker-ipc/botRemoteResourceInvalidation.js', () => ({
+ scheduleBotRemoteResourceChangedForSession: vi.fn(),
+}));
+vi.mock('../../../maker-ipc/workingStatus.js', () => ({ getWorkingStatusCopy: vi.fn() }));
+vi.mock('../../client/current.js', () => ({ getDbClient: () => null }));
+vi.mock('../../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => env.current,
+}));
+vi.mock('../../../maker-ipc/botTodoAccess.js', () => ({ todoAccess: env.access }));
+vi.mock('../bots.js', () => ({
+ getBotRemoteResourceSource: env.get,
+ listBotRemoteResourceSources: async () => [],
+}));
+import { createBotTodoStore } from '../../../maker-ipc/botTodoStore';
+import { remoteResourceRegistry } from '../../../device-link/remoteResourceRegistry';
+import { registerBotRemoteResourceProvider } from '../botRemoteResourceProvider';
+let root = '';
+const source = {
+ id: 'bot-one',
+ name: 'Sora',
+ description: '',
+ avatar: '',
+ avatarColor: 'teal',
+ status: 'active' as const,
+ canonicalSessionId: 'session-one',
+ lastMessagePreview: null,
+ lastMessageAt: null,
+ lastMessageRole: null,
+ needsAttention: false,
+ hiddenAt: null,
+ pinnedAt: null,
+ activityAt: 1,
+ currentVersion: 1,
+ updatedAt: 1,
+};
+const context = { controllerDeviceId: 'phone' },
+ client = { protocolVersion: 1, primitives: ['teammate-todos'], locale: 'zh-CN' },
+ ref = { collectionId: 'teammates', kind: 'bot', id: 'todos:bot-one' };
+beforeEach(async () => {
+ env.visible = true;
+ env.current = true;
+ env.get.mockReset();
+ env.access.mockReset();
+ env.get.mockImplementation(async (id: string) =>
+ id === 'bot-one' && env.visible ? source : null,
+ );
+ root = await mkdtemp(path.join(os.tmpdir(), 'remote-todo-'));
+ const store = createBotTodoStore(path.join(root, 'todos.v1.json'), async () => ({}));
+ env.access.mockImplementation(async () => ({
+ list: async () => ({ items: (await store.read()).items, version: 1 }),
+ patch: store.patch,
+ act: vi.fn(),
+ }));
+ registerBotRemoteResourceProvider();
+});
+afterEach(async () => rm(root, { recursive: true, force: true }));
+it('uses existing resource get/invoke, preserving the same store across controllers and full-set pagination', async () => {
+ const access = await env.access();
+ for (let n = 0; n < 36; n++)
+ await access.patch({ key: 'k' + n, title: '事务 ' + n, outcome: '验收通过' });
+ const get = () =>
+ remoteResourceRegistry.get(context, {
+ client,
+ ref,
+ query: JSON.stringify({ offset: 25, query: '事务' }),
+ });
+ const resource = await get();
+ const page = resource.blocks?.[0].data as {
+ items: Array<{ id: string; revision: number }>;
+ total: number;
+ };
+ expect(page.total).toBe(36);
+ expect(page.items).toHaveLength(11);
+ await remoteResourceRegistry.invoke(context, {
+ client,
+ collectionId: 'teammates',
+ resourceRef: ref,
+ actionId: 'todo-update',
+ input: { id: page.items[0].id, expectedRevision: page.items[0].revision, progress: '手机修改' },
+ });
+ expect(
+ (await access.list()).items.find((t: { id: string }) => t.id === page.items[0].id).progress,
+ ).toBe('手机修改');
+ await expect(
+ remoteResourceRegistry.invoke(context, {
+ client,
+ collectionId: 'teammates',
+ resourceRef: ref,
+ actionId: 'todo-update',
+ input: { id: page.items[0].id, expectedRevision: 1, progress: '旧修订' },
+ }),
+ ).rejects.toThrow('CONFLICT');
+});
+it('does not read invisible teammates or leak a result across account changes', async () => {
+ env.visible = false;
+ await expect(remoteResourceRegistry.get(context, { client, ref })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(env.access).not.toHaveBeenCalled();
+ env.visible = true;
+ env.access.mockImplementationOnce(async () => ({
+ list: async () => {
+ env.current = false;
+ return { items: [] };
+ },
+ }));
+ await expect(remoteResourceRegistry.get(context, { client, ref })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ env.current = true;
+ await expect(
+ remoteResourceRegistry.invoke(context, {
+ client,
+ collectionId: 'teammates',
+ resourceRef: { ...ref, id: 'other-bot' },
+ actionId: 'todo-update',
+ input: { title: 'x' },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts
index c0e39e04d7..81931a7eb0 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteResourceProvider.ts
@@ -1,3 +1,6 @@
+import { createHash } from 'node:crypto';
+import { todoAccess } from '../../maker-ipc/botTodoAccess.js';
+import { queryTodoItems, type TodoListQuery, type TodoPatch } from '@cindy/maker-shared/teammate-todo';
import { and, desc, inArray, isNull } from 'drizzle-orm';
import { getDbClient } from '../client/current.js';
import { botSessionLinks } from '../schema.js';
@@ -86,6 +89,19 @@ export function registerBotRemoteResourceProvider(management?: typeof botRemoteM
};
},
async get(context, request) {
+ if (request.ref.id.startsWith('todos:')) {
+ const scope = captureDataOwnerBroadcastScope();
+ const botId = request.ref.id.slice(6);
+ const candidate = await getBotRemoteResourceSource(botId);
+ const [source] = candidate ? visibleBotRemoteResourceSources([candidate]) : [];
+ if (!source || !isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Teammate unavailable');
+ const all = await (await todoAccess(botId)).list();
+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');
+ const page = queryTodoItems(all.items, request.query ? JSON.parse(request.query) as TodoListQuery : {});
+ return {ref:request.ref,revision:createHash('sha256').update(JSON.stringify(all.items)).digest('hex'),display:{title:source.name},links:[],
+ blocks:[{id:'todos',primitive:'teammate-todos',fallbackMarkdown:page.items.map(t=>t.title+' — '+t.progress).join('\n'),data:page}]};
+ }
+
if (management && (request.ref.id === 'create' || request.ref.id.startsWith('settings:'))) {
const resource = await management.getEditor(context, request.ref.id, request.client.locale, { query: request.query, primitives: request.client.primitives });
if (request.ref.id === 'create') resource.actions = [...(resource.actions ?? []), { id: 'open-agent-import', label: { fallback: 'Import an Agent', translations: { 'zh-CN': '从其他 Agent 导入', 'zh-TW': '從其他 Agent 匯入', ja: 'Agent からインポート', ko: 'Agent에서 가져오기' } } }];
@@ -126,9 +142,24 @@ export function registerBotRemoteResourceProvider(management?: typeof botRemoteM
entries: [{ id: 'memories', title: editorCopy.memories, resourceId: `settings:${source.id}/memory` }],
} });
}
+ resource.links = [...(resource.links ?? []), {rel:'todos',label:{fallback:'Todos',translations:{'zh-CN':'待办','zh-TW':'待辦',ja:'Todo',ko:'할 일'}},target:{kind:'resource',ref:{collectionId:TEAMMATES_REMOTE_COLLECTION_ID,kind:'bot',id:'todos:'+source.id}}}];
return { ...resource, teammateMessaging: { version: 1, available: source.status === 'active' } };
},
async invoke(context, request) {
+ if (request.actionId === 'todo-update' || request.actionId === 'todo-act') {
+ const scope = captureDataOwnerBroadcastScope();
+ if (!request.resourceRef?.id.startsWith('todos:')) throw new RemoteResourceRegistryError('NOT_FOUND', 'Todo resource required');
+ const botId = request.resourceRef.id.slice(6);
+ const candidate = await getBotRemoteResourceSource(botId);
+ const [source] = candidate ? visibleBotRemoteResourceSources([candidate]) : [];
+ if (!source || !isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Teammate unavailable');
+ const access = await todoAccess(botId);
+ const input = request.input ?? {};
+ const result = request.actionId === 'todo-update' ? await access.patch(input as TodoPatch) : await access.act(input.id as string,input.revision as number,input.requestId as string,request.client.locale);
+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throw new RemoteResourceRegistryError('NOT_FOUND', 'Account changed');
+ return {effects:[],todo:result};
+ }
+
if (management && request.actionId === 'open-agent-import' && request.resourceRef?.id === 'create') return {
effects: [{ kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'companion-import', kind: 'import', id: 'sources' } } }],
};
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 80a8c10aa0..8593be0b6e 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1,3 +1,5 @@
+import { todoAccess } from '../../maker-ipc/botTodoAccess.js';
+import type { TodoPatch } from '@cindy/maker-shared/teammate-todo';
/** Cindy Bots 的 main-side 权威数据边界。
*
* Bot profile 与 Session 归属只在这里写入 SQLite;renderer 只读取投影,
@@ -2122,6 +2124,17 @@ export function registerBotIpc(): void {
owner.assertCurrent();
return workbench;
});
+ for (const operation of ['list', 'update', 'act'] as const) {
+ ipcMain.handle(`local-db:bots:todos:${operation}`, async (event, rawBotId: unknown, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const owner = captureBotOperationOwner();
+ const access = await todoAccess(readText(rawBotId, 'botId', 128, true));
+ owner.assertCurrent();
+ const result = operation === 'list' ? await access.list() : operation === 'update' ? await access.patch(input as TodoPatch)
+ : await access.act((input as {id:string}).id, (input as {revision:number}).revision, (input as {requestId:string}).requestId,(input as {locale?:string}).locale);
+ owner.assertCurrent();return result;
+ });
+ }
ipcMain.handle('local-db:bots:workbench:add-directory', async (event, rawBotId: unknown, rawPath: unknown) => {
assertTrustedAppRendererEvent(event);
const botId = readText(rawBotId, 'botId', 128, true);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts
new file mode 100644
index 0000000000..1d508da1c7
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts
@@ -0,0 +1,153 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const env = vi.hoisted(() => ({
+ owner: 'owner-one',
+ root: '',
+ active: true,
+ pending: false,
+ projects: ['/cindy'],
+ notify: vi.fn(),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => env.owner,
+ ownerScopedUserDataPath: () => env.root,
+ isAppSessionBoundaryPending: () => env.pending,
+}));
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({
+ drizzle: {
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ limit: async () => [
+ {
+ id: 'bot-one',
+ status: env.active ? 'active' : 'deleted',
+ sessionId: 'canonical-one',
+ },
+ ],
+ }),
+ }),
+ }),
+ },
+ }),
+}));
+vi.mock('../botWorkbenchService.js', () => ({
+ readBotWorkbenchState: async () => ({ directories: env.projects, tasks: {} }),
+ broadcastBotWorkbenchChanged: env.notify,
+}));
+vi.mock('../botRemoteResourceInvalidation.js', () => ({
+ broadcastBotRemoteResourceChanged: env.notify,
+}));
+vi.mock('../botWorkbenchTools.js', () => ({
+ resolveWorkbenchCaller: async (id: string) =>
+ id === 'canonical-one'
+ ? { ok: true, botId: 'bot-one' }
+ : { ok: false, errorCode: 'NOT_A_BOT_SESSION' },
+}));
+import { configureBotTodoDispatch, todoAccess, todoForCaller } from '../botTodoAccess';
+let root = '';
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'todo-owner-'));
+ env.root = root;
+ env.owner = 'owner-one';
+ env.active = true;
+ env.pending = false;
+ env.notify.mockClear();
+});
+afterEach(async () => rm(root, { recursive: true, force: true }));
+const patch = {
+ key: 'same-feedback',
+ title: '修复同一问题',
+ outcome: '升级路径验收通过',
+ next: {
+ kind: 'advance' as const,
+ label: '继续验收',
+ instruction: '运行隔离数据验收,不发送消息',
+ },
+};
+describe('Todo public access', () => {
+ it('enforces current active canonical teammate and owner fences', async () => {
+ await expect(todoForCaller('ordinary-session')).rejects.toMatchObject({
+ code: 'NOT_A_BOT_SESSION',
+ });
+ const access = await todoForCaller('canonical-one');
+ await access.patch(patch);
+ env.owner = 'owner-two';
+ await expect(access.list()).rejects.toMatchObject({ code: 'OWNER_SCOPE_CHANGED' });
+ env.owner = 'owner-one';
+ env.active = false;
+ await expect(todoAccess('bot-one')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+ it('checks every scoped source and does not advance rejected events', async () => {
+ const access = await todoAccess('bot-one');
+ await expect(
+ access.ingest({
+ source: 'mail',
+ sequence: 1,
+ patch: {
+ ...patch,
+ sources: [
+ { kind: 'github', id: '1', label: 'Cindy', project: '/cindy' },
+ { kind: 'mail', id: '2', label: 'Unrelated', project: '/private' },
+ ],
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'SOURCE_OUTSIDE_SCOPE' });
+ expect(
+ await access.preflight([{ source: 'mail', sequence: 1, key: patch.key, project: '/cindy' }]),
+ ).toMatchObject([{ decision: 'review' }]);
+ });
+ it('single-click dispatches only once and preserves received vs accepted', async () => {
+ let resolve: (value: { ok: boolean }) => void = () => {};
+ const send = vi.fn(
+ () =>
+ new Promise<{ ok: boolean }>((r) => {
+ resolve = r;
+ }),
+ );
+ configureBotTodoDispatch(send);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
+ const first = access.act(todo.id, todo.revision, 'request-first');
+ await vi.waitFor(() => expect(send).toHaveBeenCalledOnce());
+ expect((await access.list()).items[0].action?.state).toBe('received');
+ await access.act(todo.id, todo.revision, 'request-second');
+ expect(send).toHaveBeenCalledOnce();
+ resolve({ ok: true });
+ await first;
+ const saved = (await access.list()).items[0];
+ expect(saved.action?.state).toBe('accepted');
+ expect(saved.status).toBe('open');
+ expect(send.mock.calls[0][0]).toMatchObject({
+ sessionId: 'canonical-one',
+ requestId: 'request-first',
+ });
+ });
+ it('does not blindly replay an uncertain dispatch', async () => {
+ const send = vi.fn(async () => {
+ throw new Error('uncertain delivery');
+ });
+ configureBotTodoDispatch(send);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
+ await expect(access.act(todo.id, todo.revision, 'request-first')).rejects.toThrow('uncertain');
+ expect((await access.list()).items[0].action?.state).toBe('unknown');
+ await access.act(todo.id, todo.revision, 'request-retry');
+ expect(send).toHaveBeenCalledOnce();
+ });
+});
+
+it('successful no-action acknowledgement advances only its source cursor without requiring a Todo', async () => {
+ const access = await todoAccess('bot-one');
+ expect(await access.ingest({ source: 'mail', sequence: 1, skip: 'no-action' })).toMatchObject({
+ duplicate: false,
+ todo: null,
+ });
+ expect(await access.preflight([{ source: 'mail', sequence: 1, key: 'unused' }])).toMatchObject([
+ { decision: 'duplicate' },
+ ]);
+ expect((await access.list()).items).toEqual([]);
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
new file mode 100644
index 0000000000..f6e409afa2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
@@ -0,0 +1,200 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createBotTodoStore } from '../botTodoStore';
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
+});
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'todo-contract-'));
+ roots.push(root);
+ return { root, file: path.join(root, 'todos.v1.json') };
+}
+const p = {
+ key: 'quote:1',
+ title: '比较报价',
+ outcome: '报价比较并获得用户确认',
+ next: {
+ label: '比较报价',
+ instruction: '读取已授权报价,准备比较,不发送邮件',
+ kind: 'advance' as const,
+ },
+ sources: [
+ { kind: 'mail' as const, id: 'mail1', label: '报价邮件', ref: 'https://example.test/quote' },
+ ],
+};
+describe('host Todo persistence', () => {
+ it('preserves fields after partial writes across independent store instances', async () => {
+ const { file } = await fixture(),
+ a = createBotTodoStore(file, async () => ({})),
+ b = createBotTodoStore(file, async () => ({}));
+ const t = await a.patch(p);
+ await b.patch({ id: t.id, expectedRevision: t.revision, progress: '草稿已准备' });
+ const result = (await a.read()).items[0];
+ expect(result.sources[0].ref).toBe(p.sources[0].ref);
+ expect(result.next).toEqual(p.next);
+ const races = await Promise.allSettled([
+ a.patch({ id: t.id, expectedRevision: 2, title: '新标题' }),
+ b.patch({ id: t.id, expectedRevision: 2, title: '并发旧标题' }),
+ ]);
+ expect(races.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
+ expect((await a.read()).items[0].revision).toBe(3);
+ });
+ it('acknowledges only successful events, merges the same key, and suppresses cross-source repeats', async () => {
+ const { file } = await fixture(),
+ s = createBotTodoStore(file, async () => ({}));
+ await expect(
+ s.ingest({ source: 'mail', sequence: 1, patch: { key: 'bad' } }),
+ ).rejects.toThrow();
+ expect((await s.read()).cursors.mail).toBeUndefined();
+ const saved = await s.ingest({ source: 'mail', sequence: 1, patch: p });
+ expect(saved.todo).toBeTruthy();
+ expect((await s.ingest({ source: 'mail', sequence: 1, patch: p })).duplicate).toBe(true);
+ const t = (await s.read()).items[0];
+ await s.patch({ id: t.id, expectedRevision: t.revision, operation: 'delete' });
+ expect(
+ (
+ await s.ingest({
+ source: 'feishu',
+ sequence: 1,
+ patch: { ...p, sources: [{ kind: 'feishu', id: 'f1', label: '同事转述' }] },
+ })
+ ).suppressed,
+ ).toBe(true);
+ expect((await s.read()).items).toHaveLength(1);
+ const deleted = (await s.read()).items[0];
+ await s.patch({ id: deleted.id, expectedRevision: deleted.revision, operation: 'restore' });
+ const active = (await s.read()).items[0];
+ await s.ingest({
+ source: 'feishu',
+ sequence: 2,
+ patch: {
+ id: active.id,
+ expectedRevision: active.revision,
+ sources: [{ kind: 'feishu', id: 'f2', label: '另一条反馈' }],
+ },
+ });
+ expect((await s.read()).items[0].sources).toHaveLength(2);
+ });
+ it('records receipts without dispatch replay, and ignores a stale receipt after the next step changes', async () => {
+ const { file } = await fixture(),
+ s = createBotTodoStore(file, async () => ({})),
+ t = await s.patch(p);
+ expect((await s.prepareAction(t.id, t.revision, 'request-1')).dispatch).toBe(true);
+ expect((await s.prepareAction(t.id, t.revision, 'request-2')).dispatch).toBe(false);
+ await s.settleAction(t.id, 'request-1', { ok: false, uncertain: true });
+ expect((await s.prepareAction(t.id, t.revision, 'request-3')).dispatch).toBe(false);
+ await s.patch({
+ id: t.id,
+ expectedRevision: t.revision,
+ next: { kind: 'decide', label: '确认报价', instruction: '让用户确认比较结果' },
+ });
+ expect(await s.settleAction(t.id, 'request-1', { ok: true })).toBeNull();
+ expect((await s.read()).items[0].action).toBeNull();
+ });
+ it('fails closed on corruption and rejects owner changes without writing', async () => {
+ const { file } = await fixture();
+ await writeFile(file, '{invalid');
+ const s = createBotTodoStore(file, async () => ({}));
+ await expect(s.patch(p)).rejects.toThrow();
+ expect(await readFile(file, 'utf8')).toBe('{invalid');
+ const f = await fixture();
+ let current = true;
+ const scoped = createBotTodoStore(
+ f.file,
+ async () => ({}),
+ () => {
+ if (!current) throw new Error('OWNER_SCOPE_CHANGED');
+ },
+ );
+ current = false;
+ await expect(scoped.patch(p)).rejects.toThrow('OWNER_SCOPE_CHANGED');
+ await expect(readFile(f.file)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+ it('imports old affairs with stable IDs, but never duplicates ordinary Session judgments', async () => {
+ const { file } = await fixture();
+ const j = {
+ project: '/cindy',
+ title: '旧承诺',
+ verdict: 'unfinished' as const,
+ next: '继续验收',
+ ref: 'https://example.test/old',
+ updatedAt: '2026-10-01T00:00:00Z',
+ };
+ const legacy = async () => ({
+ 'pr:makecindy/cindy#12': j,
+ 'idea:foo': j,
+ 'ordinary-session': j,
+ });
+ const a = createBotTodoStore(file, legacy),
+ b = createBotTodoStore(file, legacy);
+ expect((await a.read()).items).toHaveLength(2);
+ expect((await a.read()).items.map((t) => t.id)).toEqual(
+ (await b.read()).items.map((t) => t.id),
+ );
+ const t = (await a.read()).items[0];
+ await a.patch({ id: t.id, expectedRevision: t.revision, progress: '最新进展' });
+ expect((await b.read()).items).toHaveLength(2);
+ });
+ it('keeps two owners and two teammates isolated in separate homes', async () => {
+ const one = await fixture(),
+ two = await fixture();
+ const a = createBotTodoStore(path.join(one.root, 'a.json'), async () => ({})),
+ b = createBotTodoStore(path.join(one.root, 'b.json'), async () => ({})),
+ other = createBotTodoStore(two.file, async () => ({}));
+ await a.patch(p);
+ expect((await b.read()).items).toEqual([]);
+ expect((await other.read()).items).toEqual([]);
+ });
+});
+
+it('accepts only a matching attempt receipt and never turns it into affair completion', async () => {
+ const { file } = await fixture(),
+ s = createBotTodoStore(file, async () => ({})),
+ t = await s.patch(p);
+ await s.prepareAction(t.id, 1, 'attempt-one');
+ await s.settleAction(t.id, 'attempt-one', { ok: true });
+ await expect(
+ s.patch({
+ id: t.id,
+ expectedRevision: 1,
+ progress: '旧回执',
+ resolvedActionRequestId: 'older-attempt',
+ }),
+ ).rejects.toThrow('STALE_RECEIPT');
+ await expect(
+ s.patch({ id: t.id, expectedRevision: 1, resolvedActionRequestId: 'attempt-one' }),
+ ).rejects.toThrow('RECEIPT_EVIDENCE_REQUIRED');
+ const saved = await s.patch({
+ id: t.id,
+ expectedRevision: 1,
+ progress: '尝试失败,服务未发送;可重试',
+ resolvedActionRequestId: 'attempt-one',
+ });
+ expect(saved.action).toBeNull();
+ expect(saved.status).toBe('open');
+ expect((await s.prepareAction(t.id, saved.revision, 'attempt-two')).dispatch).toBe(true);
+});
+
+it('expired deferral allows advancing the same next step without altering its real deadline', async () => {
+ const { file } = await fixture(),
+ s = createBotTodoStore(file, async () => ({}));
+ const t = await s.patch({
+ ...p,
+ sourceDeadline: { kind: 'date', date: '2026-10-10', timeZone: 'UTC' },
+ });
+ const later = await s.patch({
+ id: t.id,
+ expectedRevision: 1,
+ operation: 'later',
+ until: new Date(Date.now() + 86400000).toISOString(),
+ });
+ await expect(s.prepareAction(t.id, later.revision, 'before')).rejects.toThrow('NO_NEXT_ACTION');
+ const expired = await s.read();
+ expired.items[0].decision = { kind: 'later', until: '2020-01-01T00:00:00Z' };
+ await writeFile(file, JSON.stringify(expired));
+ expect((await s.prepareAction(t.id, later.revision, 'after')).dispatch).toBe(true);
+ expect((await s.read()).items[0].sourceDeadline?.date).toBe('2026-10-10');
+});
diff --git a/apps/desktop/src/main/maker-ipc/botTodoAccess.ts b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
new file mode 100644
index 0000000000..485d741494
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
@@ -0,0 +1,152 @@
+import path from 'node:path';
+import { eq } from 'drizzle-orm';
+import {
+ TodoError,
+ todoActionText,
+ preflightTodoEvents,
+ type TodoPatch,
+ type TeammateTodo,
+} from '@cindy/maker-shared/teammate-todo';
+import {
+ activeOwnerScopeKey,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+} from '../appSessionState.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { botProfiles } from '../localDb/schema.js';
+import { botProfileDir } from './botProfileFolder.js';
+import { broadcastBotWorkbenchChanged, readBotWorkbenchState } from './botWorkbenchService.js';
+import { broadcastBotRemoteResourceChanged } from './botRemoteResourceInvalidation.js';
+import { resolveWorkbenchCaller } from './botWorkbenchTools.js';
+import { createBotTodoStore, type TodoIngestInput, type TodoIngestResult } from './botTodoStore.js';
+
+export interface BotTodoAccess {
+ list(): Promise<{ items: TeammateTodo[]; version: 1 }>;
+ patch(input: TodoPatch): Promise<TeammateTodo>;
+ ingest(input: TodoIngestInput): Promise<TodoIngestResult>;
+ preflight(
+ events: Parameters<typeof preflightTodoEvents>[1],
+ ): Promise<ReturnType<typeof preflightTodoEvents>>;
+ act(
+ id: string,
+ revision: number,
+ requestId: string,
+ locale?: string,
+ ): Promise<TeammateTodo | null>;
+}
+type Dispatch = (p: {
+ sessionId: string;
+ message: string;
+ displayText: string;
+ requestId: string;
+ assertCurrent: () => void;
+}) => Promise<{ ok: boolean; error?: string }>;
+let dispatch: Dispatch | null = null;
+export function configureBotTodoDispatch(value: Dispatch) {
+ dispatch = value;
+}
+export async function todoAccess(botId: string): Promise<BotTodoAccess> {
+ const owner = activeOwnerScopeKey(),
+ root = ownerScopedUserDataPath();
+ const assertCurrent = () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner)
+ throw new TodoError('OWNER_SCOPE_CHANGED');
+ };
+ assertCurrent();
+ const [bot] = await getDbClient()
+ .drizzle.select({
+ id: botProfiles.id,
+ status: botProfiles.status,
+ sessionId: botProfiles.canonicalSessionId,
+ })
+ .from(botProfiles)
+ .where(eq(botProfiles.id, botId))
+ .limit(1);
+ assertCurrent();
+ if (!bot || bot.status !== 'active') throw new TodoError('NOT_FOUND');
+ const readLegacy = () => readBotWorkbenchState(root, botId);
+ const store = createBotTodoStore(
+ path.join(botProfileDir(root, botId), 'todos.v1.json'),
+ async () => (await readLegacy()).tasks,
+ assertCurrent,
+ );
+ const changed = () => {
+ assertCurrent();
+ broadcastBotWorkbenchChanged(botId);
+ broadcastBotRemoteResourceChanged(botId);
+ };
+ return {
+ list: async () => {
+ const state = await store.read();
+ return { items: state.items, version: 1 as const };
+ },
+ patch: async (p: TodoPatch) => {
+ const state = await readLegacy();
+ for (const s of p.sources ?? [])
+ if (s.project && !state.directories.includes(s.project))
+ throw new TodoError('SOURCE_OUTSIDE_SCOPE');
+ const saved = await store.patch(p);
+ changed();
+ return saved;
+ },
+ ingest: async (p: TodoIngestInput) => {
+ const scope = await readLegacy();
+ for (const s of p.patch?.sources ?? [])
+ if (s.project && !scope.directories.includes(s.project))
+ throw new TodoError('SOURCE_OUTSIDE_SCOPE');
+ const saved = await store.ingest(p);
+ changed();
+ return saved;
+ },
+ preflight: async (events: Parameters<typeof preflightTodoEvents>[1]) =>
+ preflightTodoEvents(await store.read(), events, (await readLegacy()).directories),
+ act: async (id: string, revision: number, requestId: string, locale?: string) => {
+ if (!bot.sessionId || !dispatch) throw new TodoError('HOST_NOT_READY');
+ const prepared = await store.prepareAction(id, revision, requestId);
+ changed();
+ if (!prepared.dispatch) return prepared.todo;
+ try {
+ assertCurrent();
+ const t = prepared.todo;
+ const result = await dispatch({
+ sessionId: bot.sessionId,
+ requestId,
+ displayText: todoActionText(
+ t.title,
+ t.next?.label ?? t.title,
+ typeof locale === 'string' ? locale : 'en',
+ ),
+ message: JSON.stringify({
+ kind: 'todo-action',
+ todo_id: t.id,
+ revision: t.revision,
+ next: t.next,
+ outcome: t.outcome,
+ scope:
+ 'Advance only this agreed next step under existing permissions. Read the same Todo, preserve sources, and update it after a real receipt. Recording or reading external messages does not authorize sending, spending or broader access.',
+ }),
+ assertCurrent,
+ });
+ const settled = await store.settleAction(id, requestId, result);
+ changed();
+ return settled;
+ } catch (error) {
+ // An uncertain dispatch is never automatically replayed (especially external sends).
+ await store.settleAction(id, requestId, {
+ ok: false,
+ uncertain: true,
+ error: error instanceof Error ? error.message : 'UNKNOWN',
+ });
+ changed();
+ throw error;
+ }
+ },
+ };
+}
+export async function todoForCaller(callerSessionId: string): Promise<BotTodoAccess> {
+ const owner = activeOwnerScopeKey();
+ const caller = await resolveWorkbenchCaller(callerSessionId);
+ if (!caller.ok) throw new TodoError(caller.errorCode);
+ if (owner !== activeOwnerScopeKey()) throw new TodoError('OWNER_SCOPE_CHANGED');
+ return todoAccess(caller.botId);
+}
diff --git a/apps/desktop/src/main/maker-ipc/botTodoStore.ts b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
new file mode 100644
index 0000000000..26db74ec3c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
@@ -0,0 +1,307 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { randomUUID, createHash } from 'node:crypto';
+import {
+ applyTodoPatch,
+ emptyTodoState,
+ TodoError,
+ todoVisible,
+ validateTodoDeadline,
+ type TodoPatch,
+ type TodoState,
+ type TeammateTodo,
+} from '@cindy/maker-shared/teammate-todo';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import type { WorkbenchTaskJudgment } from '../../shared/botWorkbench.js';
+import { parseWorkbenchTaskId } from '../../shared/botWorkbench.js';
+
+export interface TodoIngestInput {
+ source: string;
+ sequence: number;
+ patch?: TodoPatch;
+ skip?: 'duplicate' | 'suppressed' | 'outside-scope' | 'no-action';
+}
+export interface TodoIngestResult {
+ duplicate: boolean;
+ suppressed?: boolean;
+ todo?: TeammateTodo | null;
+}
+export interface BotTodoStore {
+ read(): Promise<TodoState>;
+ patch(patch: TodoPatch): Promise<TeammateTodo>;
+ ingest(input: TodoIngestInput): Promise<TodoIngestResult>;
+ prepareAction(
+ id: string,
+ revision: number,
+ requestId: string,
+ ): Promise<{ todo: TeammateTodo; dispatch: boolean }>;
+ settleAction(
+ id: string,
+ requestId: string,
+ result: { ok: boolean; uncertain?: boolean; error?: string },
+ ): Promise<TeammateTodo | null>;
+}
+/** A separate versioned affair store preserves the old task/project file unchanged. */
+export function createBotTodoStore(
+ file: string,
+ legacy: () => Promise<Record<string, WorkbenchTaskJudgment>>,
+ assertCurrent = () => {},
+): BotTodoStore {
+ async function read(): Promise<TodoState> {
+ assertCurrent();
+ let state: TodoState;
+ try {
+ const raw = JSON.parse(await fs.readFile(file, 'utf8')) as TodoState;
+ if (
+ raw.version !== 1 ||
+ !Array.isArray(raw.items) ||
+ !raw.cursors ||
+ !raw.receipts ||
+ raw.items.some(
+ (t) =>
+ !t ||
+ typeof t.id !== 'string' ||
+ !Number.isInteger(t.revision) ||
+ !Array.isArray(t.sources) ||
+ !Array.isArray(t.history) ||
+ !Array.isArray(t.associations) ||
+ !['open', 'done'].includes(t.status),
+ )
+ )
+ throw new TodoError('CORRUPT_STORE');
+ if (
+ typeof raw.cursors !== 'object' ||
+ typeof raw.receipts !== 'object' ||
+ Array.isArray(raw.cursors) ||
+ Array.isArray(raw.receipts) ||
+ Object.entries(raw.cursors).some(
+ ([key, value]) => !key || !Number.isSafeInteger(value) || value < 0,
+ ) ||
+ Object.values(raw.receipts).some((value) => typeof value !== 'string')
+ )
+ throw new TodoError('CORRUPT_STORE');
+ const ids = new Set<string>(),
+ keys = new Set<string>();
+ for (const t of raw.items) {
+ if (ids.has(t.id) || keys.has(t.key)) throw new TodoError('CORRUPT_STORE');
+ ids.add(t.id);
+ keys.add(t.key);
+ if (
+ t.sources.some(
+ (s) =>
+ !s ||
+ typeof s.id !== 'string' ||
+ !s.id ||
+ typeof s.label !== 'string' ||
+ !['conversation', 'mail', 'feishu', 'github', 'community', 'task'].includes(s.kind) ||
+ (s.ref !== undefined && (typeof s.ref !== 'string' || !/^https:\/\//.test(s.ref))),
+ ) ||
+ t.associations.some(
+ (a) =>
+ !a ||
+ !['task', 'pr'].includes(a.kind) ||
+ typeof a.id !== 'string' ||
+ typeof a.label !== 'string',
+ ) ||
+ t.history.some(
+ (h) =>
+ !h ||
+ typeof h.summary !== 'string' ||
+ !h.summary ||
+ !Number.isFinite(Date.parse(h.at)),
+ ) ||
+ (t.next !== null &&
+ (!t.next ||
+ typeof t.next.label !== 'string' ||
+ typeof t.next.instruction !== 'string' ||
+ !['advance', 'view', 'decide'].includes(t.next.kind))) ||
+ (t.decision !== null &&
+ (!t.decision ||
+ !['deleted', 'muted', 'later'].includes(t.decision.kind) ||
+ (t.decision.kind === 'later' && !Number.isFinite(Date.parse(t.decision.until!))))) ||
+ (t.action !== null &&
+ (!t.action ||
+ typeof t.action.requestId !== 'string' ||
+ !['received', 'accepted', 'failed', 'unknown'].includes(t.action.state)))
+ )
+ throw new TodoError('CORRUPT_STORE');
+ if (
+ !t.id ||
+ !t.key ||
+ !Number.isSafeInteger(t.revision) ||
+ t.revision < 1 ||
+ !t.title ||
+ !t.outcome ||
+ typeof t.progress !== 'string' ||
+ typeof t.value !== 'string' ||
+ !['assigned', 'discovered'].includes(t.origin) ||
+ !Number.isFinite(Date.parse(t.createdAt)) ||
+ !Number.isFinite(Date.parse(t.updatedAt))
+ )
+ throw new TodoError('CORRUPT_STORE');
+ try {
+ validateTodoDeadline(t.sourceDeadline);
+ if (t.deadlineOverride) validateTodoDeadline(t.deadlineOverride.value);
+ if (t.deadlineCandidate) validateTodoDeadline(t.deadlineCandidate.value);
+ } catch {
+ throw new TodoError('CORRUPT_STORE');
+ }
+ }
+ state = raw;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ state = emptyTodoState();
+ // Old session judgments remain task metadata. Only actual old PR/idea Todo entries migrate.
+ for (const [legacyId, j] of Object.entries(await legacy())) {
+ const ref = parseWorkbenchTaskId(legacyId);
+ if (!ref || !['github', 'idea'].includes(ref.kind)) continue;
+ const at = j.updatedAt;
+ state.items.push({
+ id: 'todo:legacy-' + createHash('sha256').update(legacyId).digest('hex').slice(0, 24),
+ revision: 1,
+ key: 'legacy:' + legacyId,
+ origin: j.verdict === 'idea' ? 'discovered' : 'assigned',
+ title: j.title,
+ progress: j.next ?? '',
+ outcome: j.title,
+ value: '',
+ next:
+ j.verdict === 'done'
+ ? null
+ : { label: 'Continue', instruction: j.next || j.title, kind: 'advance' },
+ sources: [
+ {
+ kind: ref.kind === 'github' ? 'github' : 'conversation',
+ id: legacyId,
+ label: j.title,
+ ...(j.ref && /^https:\/\//.test(j.ref) ? { ref: j.ref } : {}),
+ project: j.project,
+ },
+ ],
+ associations:
+ ref.kind === 'github' && ref.type === 'pr'
+ ? [{ kind: 'pr', id: legacyId, label: j.title }]
+ : [],
+ status: j.verdict === 'done' ? 'done' : 'open',
+ createdAt: at,
+ updatedAt: at,
+ sourceDeadline: null,
+ deadlineCandidate: null,
+ suggestedDate: null,
+ decision: null,
+ history:
+ j.verdict === 'done'
+ ? [
+ {
+ summary: j.next || 'Legacy completion evidence was not recorded',
+ ...(j.ref ? { ref: j.ref } : {}),
+ at,
+ },
+ ]
+ : [],
+ action: null,
+ legacyId,
+ });
+ }
+ }
+ assertCurrent();
+ return state;
+ }
+ async function mutate<T>(fn: (state: TodoState) => T): Promise<T> {
+ assertCurrent();
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ return withCrossProcessLock(
+ file + '.lock',
+ { label: 'teammate-todo', waitMs: 12000 },
+ async (held) => {
+ if (!held.held) throw new TodoError('BUSY');
+ assertCurrent();
+ const state = await read(),
+ result = fn(state);
+ assertCurrent();
+ const temp = file + '.' + randomUUID() + '.tmp';
+ try {
+ await fs.writeFile(temp, JSON.stringify(state) + '\n', { encoding: 'utf8', mode: 0o600 });
+ assertCurrent();
+ await fs.rename(temp, file);
+ } finally {
+ await fs.rm(temp, { force: true }).catch(() => {});
+ }
+ assertCurrent();
+ return result;
+ },
+ );
+ }
+ return {
+ read,
+ patch: (patch: TodoPatch) => mutate((s) => applyTodoPatch(s, patch, 'todo:' + randomUUID())),
+ ingest: (params: {
+ source: string;
+ sequence: number;
+ patch?: TodoPatch;
+ skip?: 'duplicate' | 'suppressed' | 'outside-scope' | 'no-action';
+ }) =>
+ mutate((s) => {
+ if (
+ !/^[A-Za-z0-9:_./-]{1,512}$/.test(params.source) ||
+ ['__proto__', 'prototype', 'constructor'].includes(params.source) ||
+ !Number.isSafeInteger(params.sequence) ||
+ params.sequence < 0
+ )
+ throw new TodoError('INVALID_EVENT');
+ const receipt = params.source + ':' + params.sequence;
+ if (
+ params.sequence <=
+ (Object.hasOwn(s.cursors, params.source) ? s.cursors[params.source] : -1) ||
+ Object.hasOwn(s.receipts, receipt)
+ )
+ return { duplicate: true };
+ if (!params.patch && !params.skip) throw new TodoError('INVALID_EVENT');
+ const existing = s.items.find(
+ (t) => t.key === params.patch?.key || t.id === params.patch?.id,
+ );
+ const suppressed = (!!existing && !todoVisible(existing)) || existing?.status === 'done';
+ const saved =
+ params.patch && !suppressed
+ ? applyTodoPatch(s, params.patch, 'todo:' + randomUUID())
+ : null;
+ s.cursors[params.source] = params.sequence;
+ // The monotonic cursor already proves older receipts; retain only the latest per stream.
+ for (const key of Object.keys(s.receipts)) {
+ const split = key.lastIndexOf(':');
+ if (key.slice(0, split) === params.source) delete s.receipts[key];
+ }
+ s.receipts[receipt] = saved?.id ?? params.skip ?? 'suppressed';
+ return { duplicate: false, suppressed, todo: saved };
+ }),
+ prepareAction: (id: string, revision: number, requestId: string) =>
+ mutate((s) => {
+ const t = s.items.find((t) => t.id === id);
+ if (!t) throw new TodoError('NOT_FOUND');
+ if (t.action && (t.action.requestId === requestId || t.action.state !== 'failed'))
+ return { todo: t, dispatch: false };
+ if (t.revision !== revision) throw new TodoError('CONFLICT');
+ if (t.decision?.kind === 'later' && todoVisible(t)) t.decision = null;
+ if (t.status !== 'open' || t.decision || !t.next || t.next.kind === 'view')
+ throw new TodoError('NO_NEXT_ACTION');
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(requestId)) throw new TodoError('INVALID_REQUEST_ID');
+ t.action = { requestId, revision: t.revision, state: 'received' };
+ return { todo: structuredClone(t), dispatch: true };
+ }),
+ settleAction: (
+ id: string,
+ requestId: string,
+ result: { ok: boolean; uncertain?: boolean; error?: string },
+ ) =>
+ mutate((s) => {
+ const t = s.items.find((t) => t.id === id);
+ if (!t?.action || t.action.requestId !== requestId) return null;
+ t.action = {
+ ...t.action,
+ state: result.ok ? 'accepted' : result.uncertain ? 'unknown' : 'failed',
+ ...(result.error ? { error: result.error.slice(0, 500) } : {}),
+ };
+ return t;
+ }),
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
index 54c9257444..08caef41e2 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -67,7 +67,7 @@ import {
} from './botWorkbenchAccess.js';
/** 伙伴主任务才能用工作台;远端、归档、非主任务一律拒绝。 */
-async function resolveWorkbenchCaller(callerSessionId: string): Promise<WorkbenchCallerResult> {
+export async function resolveWorkbenchCaller(callerSessionId: string): Promise<WorkbenchCallerResult> {
const db = getDbClient().drizzle;
const [row] = await db
.select({
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 13e3b53f4a..0889e142fe 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,3 +1,4 @@
+import { configureBotTodoDispatch } from './botTodoAccess.js';
import { assertBotTaskCoordination, classifySessionMessagePurpose, coordinationInput } from './botTaskCoordination.js';
import type { BotTaskCoordination, SessionMessagePurpose } from '../../shared/botTaskCoordination.js';
import { openSession, setSessionOpeningModelAdmission } from '../localDb/sessionOpening.js';
@@ -9888,6 +9889,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
+ configureBotTodoDispatch(async ({sessionId,message,displayText,requestId,assertCurrent}) => {
+ assertCurrent();
+ const result = await sendToSessionInternal({targetSessionId:sessionId,message,persistedContent:displayText,clientId:requestId,onAccepted:assertCurrent,
+ autoReviewUserText:{kind:'delegated-continuation'}});
+ assertCurrent();return {ok:result.ok, ...(!result.ok ? {error:result.message} : {})};
+ });
+
async function sendToSessionInternal(params: {
botTaskCoordination?: BotTaskCoordination;
targetSessionId?: string;
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
index 175891e269..310a281cc2 100644
--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts
+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
@@ -2,7 +2,7 @@ import { TEAMMATE_CONTROL_GUIDANCE } from '@cindy/mcps';
/** Single host-owned baseline: preloaded text and native SKILL.md share this source. */
export const TEAMMATE_GUIDE_NAME = 'teammate-guide';
-export const TEAMMATE_GUIDE_DESCRIPTION = 'Shared operating procedures for every teammate: maintain Todo commitments, manage tasks, contact and create teammates, change model defaults, use tools, and maintain personal Skills and memory.';
+export const TEAMMATE_GUIDE_DESCRIPTION = 'Shared operating procedures for every teammate: maintain assigned and discovered Todo affairs, manage tasks, contact and create teammates, change model defaults, use tools, and maintain personal Skills and memory.';
export function buildTeammateGuide(
options: { helperAvailable?: boolean; cindyAvailable?: boolean; ownSkillsEnabled?: boolean; pluginAuthorizationCardsEnabled?: boolean } = {},
@@ -34,11 +34,11 @@ export function buildTeammateGuide(
'When the user asks to change the application’s default model, use `get_app_default_model` to read the actual current selection and enabled options, then `set_app_default_model` with the returned id and a supported effort if requested. Check the confirmed result. This changes the same default used by new tasks and following teammates; it does not overwrite existing task choices or explicit teammate/global teammate chains. Do not use this global setter when asked to change only this teammate, edit configuration files, guess providers, enable hidden models, or call an auxiliary model.',
`Use \`get_capabilities\` with \`scope: runtime\` to inspect registered tools and explicit availability reasons when needed. Use direct teammate tools for your own memory and teammates. When work needs another capability, use \`find_teammate_capabilities\` through the helper’s teammate tools to search existing Skills, MCP connections or built-in tools, and inspect actual availability. Tools and MCP connections follow Cindy by default; use \`set_teammate_capability\` only to change an explicit selection. References reuse existing installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,
"A real background task is a standalone Session in the user's task list. Prefer completing work in the current chat. Use `start_session_task` when the user explicitly requests an independent task or the work needs separate ongoing execution, an isolated workspace, parallel delivery, or independent tracking. Use `check_session_task`, `message_session_task`, and `stop_session_task` to control that same task when needed. Completion returns automatically; you remain responsible for reviewing and presenting the result.",
- 'Todo maintenance is a shared operating responsibility alongside task execution. A Todo is a commitment you made to the user in conversation, including everyday work before any project or task exists. Projects, Sessions and PRs are optional references, not the identity or prerequisite of that commitment. Ordinary task titles, engine status and archive state belong to the existing task list; do not reinterpret them as Todo completion.',
- 'Each turn, check whether the conversation adds a clear commitment or changes its scope, progress, next step or completion evidence. Also check when you receive a task result, a user correction or new facts during authorized proactive follow-up. Use the live Todo/workbench tools to read relevant existing entries when the user asks for current progress, requests follow-up, or something relevant changes. Only write changes through `set_workbench_task` or `set_workbench_tasks`, reusing the same id for the same commitment. Retrying execution or linking a PR does not create a second commitment. Keep unaccepted suggestions distinct (`idea` where supported); recording an idea does not authorize starting work, and ongoing authorized work does not need repeated permission. No change means no fabricated Todo or redundant write; a progress query can still require a read.',
- 'Write the current title, facts and one next step together: setters replace the entire entry, so preserve its still-valid reference and project fields. For Session judgments, `get_workbench` omits `ref` and `read_workbench_task` returns only conversation text. An omitted field is not proof that no reference exists: recover it from a confirmed prior write receipt matching the current judgment’s updatedAt if available; otherwise do not overwrite that judgment and explain the safe-update limitation briefly. Do not encode state in title prefixes or leave old PR prose after a verified merge. Use `done` only when evidence satisfies the agreed outcome; an idle/stopped task or a merged PR alone need not satisfy it. If acceptance remains, keep it unfinished and name the next verification; unknown facts remain explicitly unverified. For current tools, keep a concise completion basis in `next` and its supporting reference in `ref` where available; these are not structured completion metadata.',
- 'Current workbench tools are a limited project-scoped store: only a local active teammate main Session can use them, supported ids and references must pass the host checks, and even `idea` requires an entrusted project. They do not yet support project-free Todos, independent optional task/PR associations, or a browsable completed section. `get_workbench` returns retained project PR/issue/idea items with `done`; Session judgments, including `done`, appear only if their Sessions pass the recent-window and count filters. The current UI hides done judgments, the 200-entry bound can evict old completed judgments, and continuing an item as a background task can remove its judgment. Do not invent unsupported fields, create a fake project, disguise an everyday commitment as a project idea, write raw storage, or claim these gaps are implemented. State the specific recording limitation briefly and retain the commitment in the conversation until a supported tool can save it.',
- 'Inspect every write result, including each batch item, then attempt to read back supported entries with `get_workbench`. Its Session list is limited to recent candidates and a count bound, so an older or omitted Session judgment can save successfully without appearing in that read. An explicit successful write receipt confirms saving; if readback cannot show it, distinguish saved-but-not-visible from a failed write and from content verified by readback. Do not retry a successful write just to make it appear. A partial failure is not a successful whole update; report unsaved items plainly. Reply with only the useful result and remaining work, without tool logs or internal coordination messages. Update on received events and during already-authorized follow-up; guidance alone cannot run while you are not awakened. Do not install a timer merely to maintain Todo or promise unattended real-time updates.',
+ 'Todo maintenance is a shared responsibility alongside task execution. Use `list_teammate_todos` and `update_teammate_todo` for your own affairs; read by id/key when known, otherwise use the returned total and pagination: explicit user requests and actionable discoveries from information you are already authorized to access. Distinguish assigned from discovered, include sources, why it matters, an outcome and one concrete next action. No project or execution task is required. Optional task/PR links never duplicate an affair. Ordinary task titles, engine states and archives retain their own lifecycle; project filters or removal never delete Todos.',
+ 'Each turn check for relevant new requests, corrections, progress or completion evidence, and maintain the same stable Todo id/key on task results and authorized follow-up. Read relevant records for progress questions even without a change; only write actual changes. Updates are partial: omitted fields preserve sources, links and deadlines. Use id plus expectedRevision for existing entries; on CONFLICT re-read and reconcile rather than overwrite. Read back or inspect the successful returned record; errors are not saving. Never encode state in title prefixes or leave old PR prose after new verified facts. Complete only with a verifiable completion summary/reference satisfying outcome. Task end, merge and archive do not by themselves finish every affair; remaining acceptance is the next step. Reopening retains completion history.',
+ 'For proactive discovery, reuse available authorized events and existing routines, not new periodic scans. A project teammate filters to its entrusted responsibilities first; personal teammates still use only available authorized sources. Never claim an unconnected mailbox, Feishu account or community was scanned, or read unrelated private message bodies. Apply cheap scope rules and stable event/problem ids, then `preflight_teammate_todo_events` against cursors, existing affairs and ignore records before fetching relevant bodies or using a model. Merge the same feedback from different sources into one key. Commit successful events in source order using `record_teammate_todo_event`; failure must not advance the cursor. Batch relevant summaries/cache results within the existing configured budget, never repeatedly scan full histories or wake an idle model to find no changes. No source event means no rescan. These tools maintain records and preflight supplied events; they do not install connectors, scanners or timers.',
+ 'Deletion and not-suggesting-again retain a cross-source suppression for this issue only, not its whole project or source. Restore only at the user’s request; do not recreate a rejected issue from another source or silently bypass it because new facts arrived. Later is a separate deferral, not completion or an extended deadline. Preserve source deadline precision, time zone and quote; ambiguous relative dates need a candidate and visible confirmation, not a fabricated deadline. User overrides and clearing survive later source updates; suggested dates are distinct. Do not install reminder timers or execute merely because a date passed.',
+ 'When the host delivers a todo-action with a stable Todo id, read that affair and advance its named next step without requiring the user to type it again. Stay within existing authorization: recording or reading an external message does not authorize sending, spending or wider access. A received or queued action is not proof of execution or completion. Maintain the same affair on actual receipts; acknowledge a finished attempt with resolvedActionRequestId matching its stored requestId and a factual progress summary, then offer the next step. A stale receipt must not acknowledge a newer attempt. Keep uncertain deliveries unverified and never blindly replay external sends. Prepare an actionable draft or decision when approval is required. Be useful without pressure or repeated nagging. Guidance runs on received events and authorized turns, not while unwoken. Report only the useful result and remaining work; no internal coordination or tool logs.',
'Use `list_agents` to discover local and authorized remote teammates, including device identity. Use the exact returned id; never route by name. Use `send_to_agent` only to send one bounded asynchronous message to a named teammate. It is not a task and has no progress or cancellation. Do not substitute a message to a teammate for `start_session_task`.',
'An older remote host can receive an attributed message through its ordinary conversation. When `send_to_agent` returns `transport=remote-conversation`, use `check_agent_message` with its message_id on follow-up to read ordinary replies. Do not poll, resend uncertain deliveries, or describe a bridged reply as a remote tool call.',
"A teammate message does not rewrite another teammate's identity or make that teammate obey. If the user asks for obedience or control, explain this boundary and offer either a message or a tracked Session task, whichever matches the work.",
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 29c05495ed..776c9d90e9 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -1,3 +1,5 @@
+import { todoForCaller } from '../maker-ipc/botTodoAccess.js';
+import { TodoError, queryTodoItems, type TodoListQuery, type TodoPatch, type preflightTodoEvents } from '@cindy/maker-shared/teammate-todo';
import { t } from '../i18n.js';
import { executeTaskTags } from '../localDb/ipc/taskTags.js';
import { getPluginMarketService } from '../plugin-market/service.js';
@@ -904,6 +906,23 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// botWorkbenchAccess 里逐次确定性校验;投递复用 send_to_session 的同一条宿主路径。
// 停止走通用的 stop_session_turn。
botWorkbench: {
+ todos: async (caller, operation, input) => {
+ try {
+ const access = await todoForCaller(caller);
+ if (operation === 'list') {
+ const all = await access.list();
+ const q = (input ?? {}) as TodoListQuery & {id?:string;key?:string};
+ if (q.id || q.key) {
+ const items = all.items.filter(t => q.id ? t.id === q.id : t.key === q.key);
+ return {ok:true,items,total:items.length};
+ }
+ return {ok:true,...queryTodoItems(all.items,q)};
+ }
+ if (operation === 'update') return {ok:true,todo:await access.patch(input as TodoPatch)};
+ if (operation === 'preflight') return {ok:true,events:await access.preflight(input as Parameters<typeof preflightTodoEvents>[1])};
+ 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'}; }
+ },
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 d9108c6b6d..4fccb792a5 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5565,6 +5565,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('local-db:bots:create-canonical-session', body),
history: (botId: string): Promise<unknown[]> =>
ipcRenderer.invoke('local-db:bots:history', botId),
+ todos: {
+ list: (botId: string) => ipcRenderer.invoke('local-db:bots:todos:list', botId),
+ update: (botId: string, patch: import('@cindy/maker-shared/teammate-todo').TodoPatch) => ipcRenderer.invoke('local-db:bots:todos:update', botId, patch),
+ act: (botId: string, input: {id:string;revision:number;requestId:string;locale?:string}) => ipcRenderer.invoke('local-db:bots:todos:act', botId, input),
+ },
workbench: {
get: (botId: string): Promise<unknown> =>
ipcRenderer.invoke('local-db:bots:workbench:get', botId),
diff --git a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
new file mode 100644
index 0000000000..d5ce14e206
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
@@ -0,0 +1,712 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { MoreHorizontal, Plus, ChevronDown, ChevronRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import {
+ effectiveTodoDeadline,
+ todoDateLabel,
+ todoOverdue,
+ todoLocalDate,
+ todoVisible,
+ type TeammateTodo,
+ type TodoPatch,
+} from '@cindy/maker-shared/teammate-todo';
+import './botTodo.css';
+
+export interface TodoTransport {
+ list(): Promise<{ items: TeammateTodo[] }>;
+ update(p: TodoPatch): Promise<TeammateTodo>;
+ act(input: {
+ id: string;
+ revision: number;
+ requestId: string;
+ locale?: string;
+ }): Promise<TeammateTodo | null>;
+}
+export function BotTodoList({ botId }: { botId: string }) {
+ const transport = useRef<TodoTransport | null>(null);
+ transport.current = {
+ list: () => window.electronAPI.localDb.bots.todos.list(botId),
+ update: (p) => window.electronAPI.localDb.bots.todos.update(botId, p),
+ act: (p) => window.electronAPI.localDb.bots.todos.act(botId, p),
+ };
+ return (
+ <TodoPanel
+ key={
+ getDataOwnerGeneration().dataOwnerId +
+ ':' +
+ getDataOwnerGeneration().generation +
+ ':' +
+ botId
+ }
+ transport={{
+ list: () => transport.current!.list(),
+ update: (p) => transport.current!.update(p),
+ act: (p) => transport.current!.act(p),
+ }}
+ botId={botId}
+ />
+ );
+}
+/** The production panel also mounts in isolated component acceptance fixtures. No demo data. */
+export function TodoPanel({ transport, botId }: { transport: TodoTransport; botId?: string }) {
+ const { t, i18n } = useTranslation();
+ const tr = (k: string, values?: Record<string, unknown>): string =>
+ String(t('teammateTodo.' + k, values));
+ const [items, setItems] = useState<TeammateTodo[]>([]),
+ [loading, setLoading] = useState(true),
+ [error, setError] = useState(''),
+ [busy, setBusy] = useState(false);
+ const [query, setQuery] = useState(''),
+ [view, setView] = useState<'open' | 'hidden'>('open'),
+ [origin, setOrigin] = useState('all'),
+ [order, setOrder] = useState('dueOrder'),
+ [page, setPage] = useState(0),
+ [doneOpen, setDoneOpen] = useState(false);
+ const [detail, setDetail] = useState<string | null>(null),
+ [form, setForm] = useState<Partial<
+ Record<
+ 'title' | 'outcome' | 'progress' | 'date' | 'time' | 'zone' | 'summary' | 'ref' | 'until',
+ string
+ >
+ > | null>(null),
+ [mode, setMode] = useState<'edit' | 'deadline' | 'complete' | 'later'>('edit');
+ const pending = useRef(false);
+ const scope = useRef(getDataOwnerGeneration()),
+ epoch = useRef(0),
+ mounted = useRef(true),
+ initialOrder = useRef<string[]>([]),
+ api = useRef(transport);
+ api.current = transport;
+ const current = () => mounted.current && isDataOwnerGenerationCurrent(scope.current);
+ const sorted = (rows: TeammateTodo[], kind: string) =>
+ [...rows].sort((a, b) =>
+ kind === 'dueOrder'
+ ? (effectiveTodoDeadline(a)?.date ?? '9999').localeCompare(
+ effectiveTodoDeadline(b)?.date ?? '9999',
+ ) ||
+ a.createdAt.localeCompare(b.createdAt) ||
+ a.id.localeCompare(b.id)
+ : a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
+ );
+ const refresh = useCallback(async () => {
+ const request = ++epoch.current;
+ try {
+ const data = await api.current.list();
+ if (!current() || request !== epoch.current) return;
+ setItems(data.items);
+ initialOrder.current = [
+ ...initialOrder.current,
+ ...sorted(data.items, 'dueOrder')
+ .map((x) => x.id)
+ .filter((id) => !initialOrder.current.includes(id)),
+ ];
+ setError('');
+ } catch {
+ if (current()) setError('error');
+ } finally {
+ if (current()) setLoading(false);
+ }
+ }, []);
+ useEffect(() => {
+ mounted.current = true;
+ void refresh();
+ const unsub = botId
+ ? window.electronAPI.maker.onBotWorkbenchChanged((event) => {
+ if (event.botId === botId) void refresh();
+ })
+ : undefined;
+ return () => {
+ mounted.current = false;
+ epoch.current++;
+ unsub?.();
+ };
+ }, [botId, refresh]);
+ const selected = items.find((x) => x.id === detail);
+ const matches = (x: TeammateTodo) =>
+ (origin === 'all' || x.origin === origin) &&
+ (!query ||
+ [x.title, x.progress, ...x.sources.map((s) => s.label)]
+ .join(' ')
+ .toLocaleLowerCase()
+ .includes(query.toLocaleLowerCase()));
+ const rows = items
+ .filter((x) => x.status === 'open' && (view === 'hidden' ? !todoVisible(x) : todoVisible(x)))
+ .filter(matches)
+ .sort((a, b) => initialOrder.current.indexOf(a.id) - initialOrder.current.indexOf(b.id));
+ const completed = items.filter((x) => x.status === 'done' && todoVisible(x)).filter(matches);
+ const visiblePage = Math.min(page, Math.max(0, Math.ceil(rows.length / 25) - 1));
+ const run = async (fn: () => Promise<unknown>, close = false) => {
+ if (pending.current) return;
+ pending.current = true;
+ setBusy(true);
+ setError('');
+ try {
+ await fn();
+ if (current()) {
+ if (close) {
+ setForm(null);
+ setDetail(null);
+ }
+ await refresh();
+ }
+ } catch (e) {
+ if (current()) setError(String(e).includes('CONFLICT') ? 'conflict' : 'error');
+ } finally {
+ pending.current = false;
+ if (current()) setBusy(false);
+ }
+ };
+ const update = (x: TeammateTodo, patch: TodoPatch, close = false) =>
+ run(() => api.current.update({ ...patch, id: x.id, expectedRevision: x.revision }), close);
+ const edit = (x: TeammateTodo | undefined, m: typeof mode) => {
+ setDetail(x?.id ?? 'new');
+ setMode(m);
+ const d = x ? effectiveTodoDeadline(x) : null;
+ setForm({
+ title: x?.title ?? '',
+ outcome: x?.outcome ?? '',
+ progress: x?.progress ?? '',
+ date: d?.at
+ ? todoLocalDate(new Date(d.at), Intl.DateTimeFormat().resolvedOptions().timeZone)
+ : (d?.date ?? ''),
+ time: d?.at ?? '',
+ zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ summary: '',
+ ref: '',
+ until: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
+ });
+ };
+ const act = (x: TeammateTodo, confirmed = false) => {
+ if (
+ x.status === 'done' ||
+ !x.next ||
+ x.next.kind === 'view' ||
+ (x.next.kind === 'decide' && !confirmed) ||
+ (x.action && x.action.state !== 'failed')
+ ) {
+ setDetail(x.id);
+ setForm(null);
+ return;
+ }
+ void run(() =>
+ api.current.act({
+ id: x.id,
+ revision: x.revision,
+ requestId: crypto.randomUUID(),
+ locale: i18n.language,
+ }),
+ );
+ };
+ const label = (x: TeammateTodo) =>
+ x.status === 'done'
+ ? tr('evidence')
+ : x.action
+ ? tr(
+ x.action.state === 'failed'
+ ? 'failed'
+ : x.action.state === 'accepted'
+ ? 'accepted'
+ : x.action.state === 'unknown'
+ ? 'unknown'
+ : 'received',
+ )
+ : x.legacyId && x.next?.label === 'Continue'
+ ? tr('continue')
+ : (x.next?.label ?? tr('view'));
+ const list = (data: TeammateTodo[]) =>
+ data.map((x) => (
+ <li className="todo-row" key={x.id} data-todo-id={x.id}>
+ <button
+ className="todo-heading"
+ onClick={() => {
+ setDetail(x.id);
+ setForm(null);
+ }}
+ title={x.title}
+ aria-label={x.title}
+ >
+ <span className="todo-title">{x.title}</span>
+ <span className="todo-progress">
+ {!todoVisible(x) && x.decision
+ ? tr(
+ x.decision.kind === 'deleted'
+ ? 'deleted'
+ : x.decision.kind === 'muted'
+ ? 'muted'
+ : 'deferred',
+ ) + ' · '
+ : ''}
+ {x.origin === 'discovered' ? tr('discovered') + ' · ' : ''}
+ {x.progress || x.next?.instruction || x.outcome}
+ </span>
+ </button>
+ <div className="todo-rail">
+ <button
+ className={'todo-date' + (todoOverdue(x) && x.status !== 'done' ? ' todo-overdue' : '')}
+ aria-label={tr('deadline')}
+ onClick={() => edit(x, 'deadline')}
+ >
+ {!effectiveTodoDeadline(x) && x.deadlineCandidate
+ ? tr('candidate') + ' '
+ : !effectiveTodoDeadline(x) && x.suggestedDate
+ ? tr('suggested') + ' '
+ : ''}
+ {todoDateLabel(x, i18n.language)}
+ {todoOverdue(x) && x.status !== 'done' ? ' · ' + tr('overdue') : ''}
+ </button>
+ <Button
+ className="todo-action"
+ variant="secondary"
+ title={label(x)}
+ disabled={busy}
+ onClick={() => act(x)}
+ >
+ <span>{label(x)}</span>
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ className="todo-more"
+ variant="secondary"
+ tone="quiet"
+ aria-label={tr('more')}
+ >
+ <MoreHorizontal size={16} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => edit(x, 'edit')}>{tr('edit')}</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => edit(x, 'deadline')}>
+ {tr('deadline')}
+ </DropdownMenuItem>
+ {x.status === 'done' ? (
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'reopen' })}>
+ {tr('reopen')}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem onSelect={() => edit(x, 'complete')}>
+ {tr('complete')}
+ </DropdownMenuItem>
+ )}
+ {x.decision ? (
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'restore' })}>
+ {tr('restore')}
+ </DropdownMenuItem>
+ ) : (
+ <>
+ <DropdownMenuItem onSelect={() => edit(x, 'later')}>
+ {tr('later')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'delete' })}>
+ {tr('delete')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => void update(x, { operation: 'mute' })}>
+ {tr('mute')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </li>
+ ));
+ const localInput = (value: string | undefined) => {
+ if (!value) return '';
+ const d = new Date(value);
+ return Number.isFinite(d.getTime())
+ ? todoLocalDate(d, Intl.DateTimeFormat().resolvedOptions().timeZone) +
+ 'T' +
+ [d.getHours(), d.getMinutes()].map((v) => String(v).padStart(2, '0')).join(':')
+ : '';
+ };
+ const field = (key: keyof NonNullable<typeof form>, labelKey: string = key, type = 'text') => (
+ <label className="todo-field">
+ {tr(labelKey)}
+ {['outcome', 'progress', 'summary'].includes(key) ? (
+ <textarea
+ value={form?.[key] ?? ''}
+ rows={3}
+ onChange={(e) => setForm({ ...form, [key]: e.target.value })}
+ />
+ ) : (
+ <input
+ type={type}
+ value={type === 'datetime-local' ? localInput(form?.[key]) : (form?.[key] ?? '')}
+ onChange={(e) => {
+ if (type !== 'datetime-local') {
+ setForm({ ...form, [key]: e.target.value });
+ return;
+ }
+ const date = new Date(e.target.value),
+ value = Number.isFinite(date.getTime()) ? date.toISOString() : '';
+ setForm({
+ ...form,
+ [key]: value,
+ ...(key === 'time' && value ? { date: todoLocalDate(date, form!.zone!) } : {}),
+ });
+ }}
+ />
+ )}
+ </label>
+ );
+ const save = () => {
+ if (!form) return;
+ let patch: TodoPatch =
+ mode === 'edit'
+ ? { title: form.title, outcome: form.outcome, progress: form.progress }
+ : mode === 'deadline'
+ ? {
+ deadlineOverride: {
+ value: form.date
+ ? {
+ kind: form.time ? 'instant' : 'date',
+ date: form.date,
+ timeZone: form.zone!,
+ ...(form.time ? { at: form.time } : {}),
+ }
+ : null,
+ },
+ }
+ : mode === 'complete'
+ ? {
+ operation: 'complete',
+ completion: { summary: form.summary!, ...(form.ref ? { ref: form.ref } : {}) },
+ }
+ : { operation: 'later', until: form.until };
+ if (selected) void update(selected, patch, true);
+ else
+ void run(
+ () =>
+ api.current.update({
+ ...patch,
+ key: 'user:' + crypto.randomUUID(),
+ origin: 'assigned',
+ next: { kind: 'advance', label: tr('continue'), instruction: form.outcome! },
+ }),
+ true,
+ );
+ };
+ return (
+ <section className="todo-panel" aria-label={tr('title')}>
+ <header className="todo-header">
+ <h2>{tr('title')}</h2>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ aria-label={tr('new')}
+ onClick={() => edit(undefined, 'edit')}
+ >
+ <Plus size={16} />
+ </Button>
+ </header>
+ <div className="todo-tools">
+ <input
+ aria-label={tr('search')}
+ placeholder={tr('search')}
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setPage(0);
+ }}
+ />
+ <select
+ aria-label={tr('open')}
+ value={view}
+ onChange={(e) => {
+ setView(e.target.value as typeof view);
+ setPage(0);
+ }}
+ >
+ <option value="open">{tr('open')}</option>
+ <option value="hidden">{tr('hidden')}</option>
+ </select>
+ </div>
+ <div className="todo-filters">
+ <select
+ aria-label={tr('origin')}
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setPage(0);
+ }}
+ >
+ {['all', 'assigned', 'discovered'].map((k) => (
+ <option key={k} value={k}>
+ {tr(k)}
+ </option>
+ ))}
+ </select>
+ <select
+ aria-label={tr('order')}
+ value={order}
+ onChange={(e) => {
+ setOrder(e.target.value);
+ initialOrder.current = sorted(items, e.target.value).map((x) => x.id);
+ setPage(0);
+ }}
+ >
+ {['dueOrder', 'createdOrder'].map((k) => (
+ <option key={k} value={k}>
+ {tr(k)}
+ </option>
+ ))}
+ </select>
+ </div>
+ {error && (
+ <p role="alert" className="todo-error">
+ {tr(error)}{' '}
+ <Button variant="secondary" tone="quiet" onClick={() => void refresh()}>
+ {tr('retry')}
+ </Button>
+ </p>
+ )}
+ {loading ? (
+ <p role="status">{tr('loading')}</p>
+ ) : rows.length ? (
+ <ul className="todo-list">{list(rows.slice(visiblePage * 25, visiblePage * 25 + 25))}</ul>
+ ) : (
+ <p className="todo-empty">{tr(query ? 'noMatch' : 'empty')}</p>
+ )}
+ {rows.length > 25 && (
+ <nav className="todo-pages" aria-label={tr('title')}>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ disabled={!visiblePage}
+ onClick={() => setPage(visiblePage - 1)}
+ >
+ {tr('previous')}
+ </Button>
+ <span>
+ {tr('page', {
+ start: visiblePage * 25 + 1,
+ end: Math.min(rows.length, visiblePage * 25 + 25),
+ count: rows.length,
+ })}
+ </span>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ disabled={(visiblePage + 1) * 25 >= rows.length}
+ onClick={() => setPage(visiblePage + 1)}
+ >
+ {tr('following')}
+ </Button>
+ </nav>
+ )}
+ <button
+ className="todo-done-toggle"
+ aria-expanded={doneOpen}
+ onClick={() => setDoneOpen(!doneOpen)}
+ >
+ {doneOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />} {tr('done')} ·{' '}
+ {completed.length}
+ </button>
+ {doneOpen && <ul className="todo-list">{list(completed)}</ul>}
+ <ConfirmDialog
+ open={detail !== null}
+ onOpenChange={(open) => {
+ if (!open && !pending.current) {
+ setDetail(null);
+ setForm(null);
+ }
+ }}
+ title={selected?.title ?? tr('new')}
+ presentation="standard"
+ showCloseButton
+ confirmText={form ? tr('save') : tr('close')}
+ cancelText={tr('cancel')}
+ onConfirm={form ? save : () => setDetail(null)}
+ loading={busy}
+ content={
+ <div className="todo-detail">
+ {error && (
+ <p role="alert" className="todo-error">
+ {tr(error)}
+ </p>
+ )}
+ {form ? (
+ <>
+ {mode === 'edit' ? (
+ <>
+ {field('title', 'name')}
+ {field('outcome')}
+ {field('progress')}
+ </>
+ ) : mode === 'deadline' ? (
+ <>
+ {field('date', 'date', 'date')}
+ {field('time', 'time', 'datetime-local')}
+ <p>
+ {tr('zone')} · {form.zone}
+ </p>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ onClick={() => setForm({ ...form, date: '', time: '' })}
+ >
+ {tr('clearDate')}
+ </Button>
+ {selected?.deadlineCandidate && (
+ <>
+ <p>{selected.deadlineCandidate.reason}</p>
+ <Button
+ onClick={() =>
+ void update(selected, { operation: 'confirm-deadline' }, true)
+ }
+ >
+ {tr('confirmDate')}
+ </Button>
+ </>
+ )}
+ </>
+ ) : mode === 'complete' ? (
+ <>
+ {field('summary')}
+ {field('ref', 'link')}
+ </>
+ ) : (
+ <>
+ {field('until', 'until', 'datetime-local')}
+ <p>{tr('laterConflict')}</p>
+ </>
+ )}
+ </>
+ ) : (
+ selected && (
+ <>
+ {selected.next &&
+ selected.next.kind !== 'view' &&
+ selected.status === 'open' &&
+ (!selected.action || selected.action.state === 'failed') && (
+ <Button onClick={() => act(selected, true)}>{selected.next.label}</Button>
+ )}
+ <p>{selected.progress}</p>
+ {[
+ ['outcome', selected.outcome],
+ ['value', selected.value],
+ ['next', selected.next?.instruction],
+ ]
+ .filter(([, v]) => v)
+ .map(([k, v]) => (
+ <div key={k}>
+ <h3>{tr(k!)}</h3>
+ <p>{v}</p>
+ </div>
+ ))}
+ {selected.action && (
+ <p role="status">
+ {tr(selected.action.state === 'failed' ? 'error' : selected.action.state)}
+ {selected.action.error ? ' · ' + tr('error') : ''}
+ </p>
+ )}
+ {selected.sourceDeadline && (
+ <div>
+ <h3>{tr('sourceDeadline')}</h3>
+ <p>
+ {selected.sourceDeadline.date} {selected.sourceDeadline.at} ·{' '}
+ {selected.sourceDeadline.timeZone}
+ </p>
+ <p>{selected.sourceDeadline.quote}</p>
+ </div>
+ )}
+ {selected.deadlineOverride && (
+ <p>
+ {tr('override')} ·{' '}
+ {effectiveTodoDeadline(selected)
+ ? [
+ effectiveTodoDeadline(selected)?.date,
+ effectiveTodoDeadline(selected)?.at,
+ effectiveTodoDeadline(selected)?.timeZone,
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ : tr('clearDate')}
+ </p>
+ )}
+ {selected.deadlineCandidate && (
+ <div>
+ <h3>{tr('deadlineReason')}</h3>
+ <p>{selected.deadlineCandidate.reason}</p>
+ <Button
+ onClick={() => void update(selected, { operation: 'confirm-deadline' })}
+ >
+ {tr('confirmDate')}
+ </Button>
+ </div>
+ )}
+ {selected.decision?.until && (
+ <p>
+ {tr('reminder')} · {selected.decision.until}
+ </p>
+ )}
+ {!!selected.sources.length && (
+ <div>
+ <h3>{tr('sources')}</h3>
+ {selected.sources.map((s) => (
+ <p key={s.kind + ':' + s.id}>
+ {s.ref ? (
+ <a href={s.ref} target="_blank" rel="noreferrer">
+ {s.label}
+ </a>
+ ) : (
+ s.label
+ )}
+ {s.observedAt ? ' · ' + s.observedAt : ''}
+ </p>
+ ))}
+ </div>
+ )}
+ {!!selected.associations.length && (
+ <div>
+ <h3>{tr('associations')}</h3>
+ {selected.associations.map((a) => (
+ <p key={a.kind + ':' + a.id}>
+ {a.label} · {a.id}
+ </p>
+ ))}
+ </div>
+ )}
+ {!!selected.history.length && (
+ <div>
+ <h3>{tr('history')}</h3>
+ {selected.history.map((h, n) => (
+ <p key={n}>
+ {h.summary === 'Legacy completion evidence was not recorded'
+ ? tr('legacyEvidence')
+ : h.summary}{' '}
+ · {h.at}
+ {h.ref && /^https:\/\//.test(h.ref) && (
+ <a href={h.ref} target="_blank" rel="noreferrer">
+ {' '}
+ · {tr('evidence')}
+ </a>
+ )}
+ </p>
+ ))}
+ </div>
+ )}
+ <Button variant="secondary" onClick={() => edit(selected, 'edit')}>
+ {tr('edit')}
+ </Button>
+ </>
+ )
+ )}
+ </div>
+ }
+ />
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index 986dc43570..1dcbc9f40b 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -1,3 +1,4 @@
+import { BotTodoList } from './BotTodoList';
import { WorkbenchSessionList } from './WorkbenchSessionList';
import { useWorkbenchSessionPages } from './useWorkbenchSessionPages';
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
@@ -511,6 +512,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
return (
<div className="h-full min-h-0 overflow-y-auto overflow-x-hidden bg-[var(--surface)]">
+ <BotTodoList botId={botId} />
{picking ? (
<ProjectPicker
botId={botId}
@@ -556,7 +558,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
{/* 还没接手项目时,伙伴已有的自动化(例行任务、导入来的自动化)照常列在下面。 */}
{!picking || routineTiles.length > 0 ? (
<TaskGroups
- tiles={picking ? routineTiles : tiles.filter(tile => tile.type !== 'session')}
+ tiles={picking ? routineTiles : tiles.filter(tile => tile.type !== 'session' && tile.type !== 'item')}
now={now}
language={i18n.language}
showEmpty={false}
diff --git a/apps/desktop/src/renderer/features/bots/botTodo.css b/apps/desktop/src/renderer/features/bots/botTodo.css
new file mode 100644
index 0000000000..2e382d4b0b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/botTodo.css
@@ -0,0 +1,191 @@
+.todo-panel {
+ padding: 12px 16px;
+ color: var(--text-primary);
+ border-bottom: 1px solid var(--border-default);
+}
+.todo-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 8px;
+}
+.todo-header h2 {
+ font-size: 14px;
+ line-height: 22px;
+ font-weight: 600;
+}
+.todo-tools {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 112px;
+ gap: 8px;
+}
+.todo-tools input,
+.todo-tools select,
+.todo-filters select,
+.todo-field input,
+.todo-field textarea {
+ min-width: 0;
+ background: var(--surface-elevated);
+ color: var(--text-primary);
+ border: 1px solid var(--border-default);
+ border-radius: 8px;
+ padding: 7px 8px;
+ font-size: 13px;
+ line-height: 20px;
+}
+.todo-filters {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ margin: 8px 0;
+}
+.todo-filters select {
+ max-width: 50%;
+ border-color: transparent;
+ background: transparent;
+ padding: 2px;
+}
+.todo-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+.todo-row {
+ padding: 10px 0;
+ border-bottom: 1px solid var(--border-default);
+ min-width: 0;
+}
+.todo-heading {
+ display: flex;
+ flex-direction: column;
+ text-align: left;
+ width: 100%;
+ min-width: 0;
+ border-radius: 4px;
+}
+.todo-title,
+.todo-progress {
+ display: block;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.todo-title {
+ font-size: 14px;
+ line-height: 22px;
+ font-weight: 500;
+}
+.todo-progress {
+ font-size: 13px;
+ line-height: 20px;
+ font-weight: 400;
+ color: var(--text-secondary);
+}
+.todo-rail {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 132px 32px;
+ gap: 8px;
+ align-items: center;
+ margin-top: 8px;
+ height: 32px;
+}
+.todo-date {
+ min-width: 0;
+ text-align: left;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ line-height: 18px;
+ height: 32px;
+ color: var(--text-secondary);
+ border-radius: 4px;
+}
+.todo-overdue {
+ color: var(--text-danger);
+}
+.todo-rail .todo-action {
+ width: 132px;
+ min-width: 0;
+ height: 32px;
+ min-height: 32px;
+ padding: 0 10px;
+ display: flex;
+ align-items: center;
+ font-size: 13px;
+ line-height: 20px;
+ border-radius: 999px;
+}
+.todo-action span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+}
+.todo-rail .todo-more {
+ width: 32px;
+ height: 32px;
+ min-height: 32px;
+ padding: 0;
+ border-radius: 8px;
+}
+.todo-done-toggle {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--text-secondary);
+ padding: 12px 0;
+}
+.todo-pages {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 12px;
+ line-height: 18px;
+}
+.todo-empty {
+ padding: 16px 0;
+ font-size: 13px;
+ line-height: 20px;
+ color: var(--text-secondary);
+}
+.todo-error {
+ font-size: 13px;
+ line-height: 20px;
+ color: var(--text-danger);
+ overflow-wrap: anywhere;
+}
+.todo-detail {
+ display: grid;
+ gap: 12px;
+ font-size: 14px;
+ line-height: 22px;
+ overflow-wrap: anywhere;
+}
+.todo-detail h3 {
+ font-size: 13px;
+ line-height: 20px;
+ color: var(--text-secondary);
+ font-weight: 500;
+}
+.todo-detail a {
+ color: var(--text-primary);
+ text-decoration: underline;
+}
+.todo-field {
+ display: grid;
+ gap: 4px;
+ font-size: 13px;
+ line-height: 20px;
+}
+.todo-field input,
+.todo-field textarea {
+ width: 100%;
+}
+.todo-panel :focus-visible {
+ outline: 2px solid var(--text-primary);
+ outline-offset: 2px;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ed7df3a280..8a6c399ae5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -15039,5 +15039,84 @@
"idempotencyConflict": "This retry identifier was already used for a different message.",
"privateUnconfirmed": "Private message delivery is unconfirmed. Retry with the same identifier.",
"verificationUnavailable": "Group authorization could not be verified. Try again when the connection recovers."
+ },
+ "teammateTodo": {
+ "title": "Todos",
+ "new": "New todo",
+ "search": "Search todos",
+ "open": "Open",
+ "done": "Completed",
+ "hidden": "Dismissed / later",
+ "empty": "No todos",
+ "noMatch": "No matching todos",
+ "loading": "Loading…",
+ "retry": "Retry",
+ "error": "The action did not finish. Try again.",
+ "conflict": "This todo changed. Review it before editing.",
+ "received": "Received",
+ "accepted": "View progress",
+ "unknown": "Check progress",
+ "failed": "Retry next step",
+ "view": "View details",
+ "evidence": "View evidence",
+ "more": "More actions",
+ "discovered": "Discovered",
+ "assigned": "Assigned",
+ "suggested": "Suggested",
+ "candidate": "Confirm date",
+ "overdue": "Overdue",
+ "today": "Today",
+ "next": "Next step",
+ "outcome": "Completion condition",
+ "value": "Why it matters",
+ "sources": "Sources",
+ "associations": "Related work",
+ "deadline": "Due date",
+ "sourceDeadline": "Source deadline",
+ "clearDate": "Clear due date",
+ "date": "Date",
+ "time": "Exact time (optional)",
+ "zone": "Time zone",
+ "save": "Save",
+ "cancel": "Cancel",
+ "delete": "Delete this todo",
+ "mute": "Do not suggest this issue again",
+ "later": "Do later",
+ "until": "Do later until",
+ "restore": "Restore",
+ "reopen": "Reopen",
+ "complete": "Mark complete",
+ "summary": "Completion evidence",
+ "confirmDate": "Confirm date",
+ "deadlineReason": "Why the date needs confirmation",
+ "override": "Your deadline",
+ "reminder": "Deferred until",
+ "edit": "Edit todo",
+ "name": "Title",
+ "progress": "Progress",
+ "link": "Evidence link (optional)",
+ "saved": "Saved",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "Previous",
+ "following": "Next",
+ "order": "Sort",
+ "dueOrder": "Due first",
+ "createdOrder": "Creation order",
+ "origin": "Origin",
+ "all": "All",
+ "close": "Close",
+ "laterConflict": "Deferring does not extend the deadline",
+ "legacyEvidence": "Legacy completion evidence needs verification",
+ "noPermission": "This source is not connected or authorized",
+ "copy": "Copy",
+ "undo": "Undo",
+ "history": "Completion history",
+ "clockNote": "Date-only deadlines end in the shown time zone; exact times retain their zone.",
+ "deleted": "Deleted",
+ "muted": "Not suggested again",
+ "deferred": "Deferred",
+ "continue": "Continue",
+ "addTime": "Add time",
+ "dateOnly": "Date only"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d13a6bbde1..f7e3d170b8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -15002,5 +15002,84 @@
"idempotencyConflict": "この再試行識別子は別のメッセージに使用されています。",
"privateUnconfirmed": "個別メッセージの配信は未確認です。同じ識別子で再試行してください。",
"verificationUnavailable": "グループの権限を確認できませんでした。接続が回復してから再試行してください。"
+ },
+ "teammateTodo": {
+ "title": "Todo",
+ "new": "Todoを追加",
+ "search": "Todoを検索",
+ "open": "未完了",
+ "done": "完了",
+ "hidden": "非表示 / あとで",
+ "empty": "Todoはありません",
+ "noMatch": "一致するTodoはありません",
+ "loading": "読み込み中…",
+ "retry": "再試行",
+ "error": "操作が完了しませんでした。再試行してください。",
+ "conflict": "Todoが更新されました。確認してから編集してください。",
+ "received": "受付済み",
+ "accepted": "進捗を見る",
+ "unknown": "進捗を確認",
+ "failed": "次の手順を再試行",
+ "view": "詳細を見る",
+ "evidence": "完了の根拠を見る",
+ "more": "その他の操作",
+ "discovered": "見つけた項目",
+ "assigned": "依頼",
+ "suggested": "提案",
+ "candidate": "日付を確認",
+ "overdue": "期限超過",
+ "today": "今日",
+ "next": "次の手順",
+ "outcome": "完了条件",
+ "value": "取り組む理由",
+ "sources": "情報源",
+ "associations": "関連",
+ "deadline": "期限",
+ "sourceDeadline": "情報源の期限",
+ "clearDate": "期限を解除",
+ "date": "日付",
+ "time": "時刻(任意)",
+ "zone": "タイムゾーン",
+ "save": "保存",
+ "cancel": "キャンセル",
+ "delete": "この項目を削除",
+ "mute": "この問題を今後提案しない",
+ "later": "あとで",
+ "until": "延期先",
+ "restore": "復元",
+ "reopen": "再開",
+ "complete": "完了にする",
+ "summary": "完了の根拠",
+ "confirmDate": "日付を確定",
+ "deadlineReason": "日付の確認が必要な理由",
+ "override": "設定した期限",
+ "reminder": "延期先",
+ "edit": "Todoを編集",
+ "name": "タイトル",
+ "progress": "進捗",
+ "link": "根拠のリンク(任意)",
+ "saved": "保存済み",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "前へ",
+ "following": "次へ",
+ "order": "並び順",
+ "dueOrder": "期限順",
+ "createdOrder": "作成順",
+ "origin": "種類",
+ "all": "すべて",
+ "close": "閉じる",
+ "laterConflict": "延期しても期限は変わりません",
+ "legacyEvidence": "旧記録の完了の根拠は未確認です",
+ "noPermission": "未接続または未承認の情報源です",
+ "copy": "コピー",
+ "undo": "元に戻す",
+ "history": "完了履歴",
+ "clockNote": "日付のみの期限は表示されたタイムゾーンの一日の終わりです。日時にはタイムゾーンが保持されます。",
+ "deleted": "削除済み",
+ "muted": "今後提案しない",
+ "deferred": "延期中",
+ "continue": "続ける",
+ "addTime": "時刻を追加",
+ "dateOnly": "日付のみ"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 254dcd93d6..99fb8061cd 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -15002,5 +15002,84 @@
"idempotencyConflict": "이 재시도 식별자는 다른 메시지에 이미 사용되었습니다.",
"privateUnconfirmed": "개인 메시지 전달이 확인되지 않았습니다. 같은 식별자로 다시 시도해 주세요.",
"verificationUnavailable": "그룹 권한을 확인할 수 없습니다. 연결이 복구되면 다시 시도하세요."
+ },
+ "teammateTodo": {
+ "title": "할 일",
+ "new": "할 일 추가",
+ "search": "할 일 검색",
+ "open": "미완료",
+ "done": "완료",
+ "hidden": "숨김 / 나중에",
+ "empty": "할 일이 없습니다",
+ "noMatch": "일치하는 할 일이 없습니다",
+ "loading": "불러오는 중…",
+ "retry": "다시 시도",
+ "error": "작업이 완료되지 않았습니다. 다시 시도하세요.",
+ "conflict": "할 일이 변경되었습니다. 확인 후 수정하세요.",
+ "received": "접수됨",
+ "accepted": "진행 보기",
+ "unknown": "진행 확인",
+ "failed": "다음 단계 재시도",
+ "view": "상세 보기",
+ "evidence": "완료 근거 보기",
+ "more": "더 많은 작업",
+ "discovered": "발견",
+ "assigned": "요청",
+ "suggested": "제안",
+ "candidate": "날짜 확인",
+ "overdue": "기한 지남",
+ "today": "오늘",
+ "next": "다음 단계",
+ "outcome": "완료 조건",
+ "value": "처리할 이유",
+ "sources": "출처",
+ "associations": "관련 항목",
+ "deadline": "기한",
+ "sourceDeadline": "출처 기한",
+ "clearDate": "기한 삭제",
+ "date": "날짜",
+ "time": "정확한 시각 (선택)",
+ "zone": "시간대",
+ "save": "저장",
+ "cancel": "취소",
+ "delete": "이 항목 삭제",
+ "mute": "이 문제를 다시 제안하지 않기",
+ "later": "나중에 처리",
+ "until": "미룰 날짜",
+ "restore": "복원",
+ "reopen": "다시 열기",
+ "complete": "완료로 표시",
+ "summary": "완료 근거",
+ "confirmDate": "날짜 확정",
+ "deadlineReason": "날짜 확인이 필요한 이유",
+ "override": "설정한 기한",
+ "reminder": "미룬 시각",
+ "edit": "할 일 수정",
+ "name": "제목",
+ "progress": "진행 상황",
+ "link": "근거 링크 (선택)",
+ "saved": "저장됨",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "이전",
+ "following": "다음",
+ "order": "정렬",
+ "dueOrder": "기한순",
+ "createdOrder": "생성순",
+ "origin": "유형",
+ "all": "전체",
+ "close": "닫기",
+ "laterConflict": "미루어도 실제 기한은 연장되지 않습니다",
+ "legacyEvidence": "이전 완료 기록의 근거를 확인해야 합니다",
+ "noPermission": "연결되지 않았거나 승인되지 않은 출처입니다",
+ "copy": "복사",
+ "undo": "실행 취소",
+ "history": "완료 기록",
+ "clockNote": "날짜만 있는 기한은 표시된 시간대의 하루가 끝날 때입니다. 정확한 시각은 시간대를 유지합니다.",
+ "deleted": "삭제됨",
+ "muted": "다시 제안하지 않음",
+ "deferred": "미뤄짐",
+ "continue": "계속",
+ "addTime": "시각 추가",
+ "dateOnly": "날짜만"
}
}
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 a0fe6a0b58..e5f748835c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -15002,5 +15002,84 @@
"idempotencyConflict": "此重试标识已用于另一条消息。",
"privateUnconfirmed": "私聊未确认送达,请使用同一重试标识重试。",
"verificationUnavailable": "暂时无法核验群聊授权,请在连接恢复后重试。"
+ },
+ "teammateTodo": {
+ "title": "待办",
+ "new": "新建待办",
+ "search": "搜索待办",
+ "open": "未完成",
+ "done": "已完成",
+ "hidden": "已忽略 / 稍后",
+ "empty": "暂无待办",
+ "noMatch": "没有匹配的待办",
+ "loading": "正在读取…",
+ "retry": "重试",
+ "error": "操作未完成,请重试。",
+ "conflict": "待办已更新,请重新查看后再修改。",
+ "received": "已收到",
+ "accepted": "查看进展",
+ "unknown": "核实进展",
+ "failed": "重试下一步",
+ "view": "查看详情",
+ "evidence": "查看依据",
+ "more": "更多操作",
+ "discovered": "发现",
+ "assigned": "交办",
+ "suggested": "建议",
+ "candidate": "待确认",
+ "overdue": "已逾期",
+ "today": "今天",
+ "next": "下一步",
+ "outcome": "完成条件",
+ "value": "为什么值得处理",
+ "sources": "来源依据",
+ "associations": "关联",
+ "deadline": "到期时间",
+ "sourceDeadline": "来源期限",
+ "clearDate": "清除到期",
+ "date": "日期",
+ "time": "确切时间(可选)",
+ "zone": "时区",
+ "save": "保存",
+ "cancel": "取消",
+ "delete": "删除此条",
+ "mute": "此问题不再提示",
+ "later": "稍后处理",
+ "until": "稍后至",
+ "restore": "恢复",
+ "reopen": "重新打开",
+ "complete": "标记完成",
+ "summary": "完成依据",
+ "confirmDate": "确认日期",
+ "deadlineReason": "日期待确认的原因",
+ "override": "你设置的期限",
+ "reminder": "稍后至",
+ "edit": "编辑待办",
+ "name": "标题",
+ "progress": "当前进展",
+ "link": "依据链接(可选)",
+ "saved": "已保存",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "上一页",
+ "following": "下一页",
+ "order": "排序",
+ "dueOrder": "到期优先",
+ "createdOrder": "创建顺序",
+ "origin": "来源类型",
+ "all": "全部",
+ "close": "关闭",
+ "laterConflict": "稍后处理不延长真实期限",
+ "legacyEvidence": "旧记录的完成依据待核实",
+ "noPermission": "此来源未连接或尚未授权",
+ "copy": "复制",
+ "undo": "撤销",
+ "history": "完成记录",
+ "clockNote": "仅日期按所示时区当天结束;确切时刻保留时区。",
+ "deleted": "已删除",
+ "muted": "不再提示",
+ "deferred": "稍后处理",
+ "continue": "继续",
+ "addTime": "添加时间",
+ "dateOnly": "仅日期"
}
}
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 b155c55fae..8bab72af62 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -15002,5 +15002,84 @@
"idempotencyConflict": "此重試識別碼已用於另一則訊息。",
"privateUnconfirmed": "尚未確認私訊送達,請使用相同的重試識別碼重試。",
"verificationUnavailable": "暫時無法核驗群聊授權,請在連線恢復後重試。"
+ },
+ "teammateTodo": {
+ "title": "待辦",
+ "new": "新增待辦",
+ "search": "搜尋待辦",
+ "open": "未完成",
+ "done": "已完成",
+ "hidden": "已忽略 / 稍後",
+ "empty": "暫無待辦",
+ "noMatch": "沒有符合的待辦",
+ "loading": "正在讀取…",
+ "retry": "重試",
+ "error": "操作未完成,請重試。",
+ "conflict": "待辦已更新,請重新查看後再修改。",
+ "received": "已收到",
+ "accepted": "查看進度",
+ "unknown": "核實進度",
+ "failed": "重試下一步",
+ "view": "查看詳情",
+ "evidence": "查看依據",
+ "more": "更多操作",
+ "discovered": "发现",
+ "assigned": "交办",
+ "suggested": "建議",
+ "candidate": "待確認",
+ "overdue": "已逾期",
+ "today": "今天",
+ "next": "下一步",
+ "outcome": "完成條件",
+ "value": "為何值得處理",
+ "sources": "來源依據",
+ "associations": "关联",
+ "deadline": "到期時間",
+ "sourceDeadline": "來源期限",
+ "clearDate": "清除到期",
+ "date": "日期",
+ "time": "確切時間(選填)",
+ "zone": "時區",
+ "save": "儲存",
+ "cancel": "取消",
+ "delete": "刪除此項",
+ "mute": "此問題不再提示",
+ "later": "稍後處理",
+ "until": "稍後至",
+ "restore": "恢復",
+ "reopen": "重新開啟",
+ "complete": "標記完成",
+ "summary": "完成依據",
+ "confirmDate": "確認日期",
+ "deadlineReason": "日期待確認的原因",
+ "override": "你設定的期限",
+ "reminder": "稍後至",
+ "edit": "编辑待办",
+ "name": "標題",
+ "progress": "目前進度",
+ "link": "依據連結(選填)",
+ "saved": "已儲存",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "上一頁",
+ "following": "下一頁",
+ "order": "排序",
+ "dueOrder": "到期優先",
+ "createdOrder": "建立順序",
+ "origin": "來源類型",
+ "all": "全部",
+ "close": "關閉",
+ "laterConflict": "稍後處理不延長真實期限",
+ "legacyEvidence": "舊記錄的完成依據待核實",
+ "noPermission": "此來源未連接或尚未授權",
+ "copy": "複製",
+ "undo": "復原",
+ "history": "完成記錄",
+ "clockNote": "僅日期按所示時區當天結束;確切時刻保留時區。",
+ "deleted": "已刪除",
+ "muted": "不再提示",
+ "deferred": "稍後處理",
+ "continue": "繼續",
+ "addTime": "新增時間",
+ "dateOnly": "僅日期"
}
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index b325ac9523..48bfe64b4c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4824,6 +4824,11 @@ interface ElectronAPI {
session: import('@/lib/ccAgent.types').Session;
}>;
history: (botId: string) => Promise<unknown[]>;
+ todos: {
+ list: (botId:string) => Promise<{items:import('@cindy/maker-shared/teammate-todo').TeammateTodo[];version:1}>;
+ update: (botId:string, patch:import('@cindy/maker-shared/teammate-todo').TodoPatch) => Promise<import('@cindy/maker-shared/teammate-todo').TeammateTodo>;
+ act: (botId:string, input:{id:string;revision:number;requestId:string;locale?:string}) => Promise<import('@cindy/maker-shared/teammate-todo').TeammateTodo | null>;
+ };
workbench: {
get: (botId: string) => Promise<import('../shared/botWorkbench').BotWorkbench | null>;
addDirectory: (
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
index 7c1f4efa1c..0a562cf816 100644
--- a/apps/mobile/src/device-link/remoteResources.ts
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -44,6 +44,7 @@ const RICH_REMOTE_RESOURCE_PRIMITIVES: readonly string[] = [
BOT_GROUP_CHAT_PRIMITIVE,
'plugin-capabilities',
'plugin-card-actions',
+ 'teammate-todos',
];
/** Routines remain a desktop feature; other portable collections stay available. */
@@ -369,11 +370,13 @@ export async function getRemoteResource(
ref: RemoteResourceRef,
locale?: string,
supportedPrimitives: readonly string[] = [],
+ query?: string,
): Promise<RemoteResource> {
assertMobileRemoteCollectionSupported(ref.collectionId);
const raw = await invoke<unknown>(target.deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{
client: { ...clientDescriptor(locale), primitives: [...MOBILE_REMOTE_RESOURCE_PRIMITIVES, ...supportedPrimitives] },
ref,
+ ...(query ? {query} : {}),
}]);
const normalized = normalizeRemoteCollectionItem(raw, ref.collectionId);
if (!normalized || normalized.ref.kind !== ref.kind || normalized.ref.id !== ref.id) {
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index 4c32b0e9f9..ae66fffea9 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -814,5 +814,84 @@
"automationInvalid": "The automation definition could not be converted; it was not created.",
"itemFailed": "This item is unfinished. Retry or view import details.",
"chatPartial": "Your teammate is created, but some content was not fully saved. The items below still need attention; other content and chat remain available."
+ },
+ "teammateTodo": {
+ "title": "Todos",
+ "new": "New todo",
+ "search": "Search todos",
+ "open": "Open",
+ "done": "Completed",
+ "hidden": "Dismissed / later",
+ "empty": "No todos",
+ "noMatch": "No matching todos",
+ "loading": "Loading…",
+ "retry": "Retry",
+ "error": "The action did not finish. Try again.",
+ "conflict": "This todo changed. Review it before editing.",
+ "received": "Received",
+ "accepted": "View progress",
+ "unknown": "Check progress",
+ "failed": "Retry next step",
+ "view": "View details",
+ "evidence": "View evidence",
+ "more": "More actions",
+ "discovered": "Discovered",
+ "assigned": "Assigned",
+ "suggested": "Suggested",
+ "candidate": "Confirm date",
+ "overdue": "Overdue",
+ "today": "Today",
+ "next": "Next step",
+ "outcome": "Completion condition",
+ "value": "Why it matters",
+ "sources": "Sources",
+ "associations": "Related work",
+ "deadline": "Due date",
+ "sourceDeadline": "Source deadline",
+ "clearDate": "Clear due date",
+ "date": "Date",
+ "time": "Exact time (optional)",
+ "zone": "Time zone",
+ "save": "Save",
+ "cancel": "Cancel",
+ "delete": "Delete this todo",
+ "mute": "Do not suggest this issue again",
+ "later": "Do later",
+ "until": "Do later until",
+ "restore": "Restore",
+ "reopen": "Reopen",
+ "complete": "Mark complete",
+ "summary": "Completion evidence",
+ "confirmDate": "Confirm date",
+ "deadlineReason": "Why the date needs confirmation",
+ "override": "Your deadline",
+ "reminder": "Deferred until",
+ "edit": "Edit todo",
+ "name": "Title",
+ "progress": "Progress",
+ "link": "Evidence link (optional)",
+ "saved": "Saved",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "Previous",
+ "following": "Next",
+ "order": "Sort",
+ "dueOrder": "Due first",
+ "createdOrder": "Creation order",
+ "origin": "Origin",
+ "all": "All",
+ "close": "Close",
+ "laterConflict": "Deferring does not extend the deadline",
+ "legacyEvidence": "Legacy completion evidence needs verification",
+ "noPermission": "This source is not connected or authorized",
+ "copy": "Copy",
+ "undo": "Undo",
+ "history": "Completion history",
+ "clockNote": "Date-only deadlines end in the shown time zone; exact times retain their zone.",
+ "deleted": "Deleted",
+ "muted": "Not suggested again",
+ "deferred": "Deferred",
+ "continue": "Continue",
+ "addTime": "Add time",
+ "dateOnly": "Date only"
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index 339ceb125b..e460eb7152 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -814,5 +814,84 @@
"automationInvalid": "自動化の定義を変換できず、作成されていません。",
"itemFailed": "この項目は未完了です。再試行するか詳細を確認してください。",
"chatPartial": "パートナーは作成されましたが、一部の情報は完全に保存されていません。以下の項目は対応が必要です。他の情報とチャットは利用できます。"
+ },
+ "teammateTodo": {
+ "title": "Todo",
+ "new": "Todoを追加",
+ "search": "Todoを検索",
+ "open": "未完了",
+ "done": "完了",
+ "hidden": "非表示 / あとで",
+ "empty": "Todoはありません",
+ "noMatch": "一致するTodoはありません",
+ "loading": "読み込み中…",
+ "retry": "再試行",
+ "error": "操作が完了しませんでした。再試行してください。",
+ "conflict": "Todoが更新されました。確認してから編集してください。",
+ "received": "受付済み",
+ "accepted": "進捗を見る",
+ "unknown": "進捗を確認",
+ "failed": "次の手順を再試行",
+ "view": "詳細を見る",
+ "evidence": "完了の根拠を見る",
+ "more": "その他の操作",
+ "discovered": "見つけた項目",
+ "assigned": "依頼",
+ "suggested": "提案",
+ "candidate": "日付を確認",
+ "overdue": "期限超過",
+ "today": "今日",
+ "next": "次の手順",
+ "outcome": "完了条件",
+ "value": "取り組む理由",
+ "sources": "情報源",
+ "associations": "関連",
+ "deadline": "期限",
+ "sourceDeadline": "情報源の期限",
+ "clearDate": "期限を解除",
+ "date": "日付",
+ "time": "時刻(任意)",
+ "zone": "タイムゾーン",
+ "save": "保存",
+ "cancel": "キャンセル",
+ "delete": "この項目を削除",
+ "mute": "この問題を今後提案しない",
+ "later": "あとで",
+ "until": "延期先",
+ "restore": "復元",
+ "reopen": "再開",
+ "complete": "完了にする",
+ "summary": "完了の根拠",
+ "confirmDate": "日付を確定",
+ "deadlineReason": "日付の確認が必要な理由",
+ "override": "設定した期限",
+ "reminder": "延期先",
+ "edit": "Todoを編集",
+ "name": "タイトル",
+ "progress": "進捗",
+ "link": "根拠のリンク(任意)",
+ "saved": "保存済み",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "前へ",
+ "following": "次へ",
+ "order": "並び順",
+ "dueOrder": "期限順",
+ "createdOrder": "作成順",
+ "origin": "種類",
+ "all": "すべて",
+ "close": "閉じる",
+ "laterConflict": "延期しても期限は変わりません",
+ "legacyEvidence": "旧記録の完了の根拠は未確認です",
+ "noPermission": "未接続または未承認の情報源です",
+ "copy": "コピー",
+ "undo": "元に戻す",
+ "history": "完了履歴",
+ "clockNote": "日付のみの期限は表示されたタイムゾーンの一日の終わりです。日時にはタイムゾーンが保持されます。",
+ "deleted": "削除済み",
+ "muted": "今後提案しない",
+ "deferred": "延期中",
+ "continue": "続ける",
+ "addTime": "時刻を追加",
+ "dateOnly": "日付のみ"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index ad09ad81f7..4e78721349 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -814,5 +814,84 @@
"automationInvalid": "자동화 정의를 변환할 수 없어 생성되지 않았습니다.",
"itemFailed": "아직 완료되지 않은 항목입니다. 다시 시도하거나 세부 정보를 확인하세요.",
"chatPartial": "파트너가 생성되었지만 일부 자료는 완전히 저장되지 않았습니다. 아래 항목은 추가 처리가 필요하며 다른 내용과 채팅은 계속 사용할 수 있습니다."
+ },
+ "teammateTodo": {
+ "title": "할 일",
+ "new": "할 일 추가",
+ "search": "할 일 검색",
+ "open": "미완료",
+ "done": "완료",
+ "hidden": "숨김 / 나중에",
+ "empty": "할 일이 없습니다",
+ "noMatch": "일치하는 할 일이 없습니다",
+ "loading": "불러오는 중…",
+ "retry": "다시 시도",
+ "error": "작업이 완료되지 않았습니다. 다시 시도하세요.",
+ "conflict": "할 일이 변경되었습니다. 확인 후 수정하세요.",
+ "received": "접수됨",
+ "accepted": "진행 보기",
+ "unknown": "진행 확인",
+ "failed": "다음 단계 재시도",
+ "view": "상세 보기",
+ "evidence": "완료 근거 보기",
+ "more": "더 많은 작업",
+ "discovered": "발견",
+ "assigned": "요청",
+ "suggested": "제안",
+ "candidate": "날짜 확인",
+ "overdue": "기한 지남",
+ "today": "오늘",
+ "next": "다음 단계",
+ "outcome": "완료 조건",
+ "value": "처리할 이유",
+ "sources": "출처",
+ "associations": "관련 항목",
+ "deadline": "기한",
+ "sourceDeadline": "출처 기한",
+ "clearDate": "기한 삭제",
+ "date": "날짜",
+ "time": "정확한 시각 (선택)",
+ "zone": "시간대",
+ "save": "저장",
+ "cancel": "취소",
+ "delete": "이 항목 삭제",
+ "mute": "이 문제를 다시 제안하지 않기",
+ "later": "나중에 처리",
+ "until": "미룰 날짜",
+ "restore": "복원",
+ "reopen": "다시 열기",
+ "complete": "완료로 표시",
+ "summary": "완료 근거",
+ "confirmDate": "날짜 확정",
+ "deadlineReason": "날짜 확인이 필요한 이유",
+ "override": "설정한 기한",
+ "reminder": "미룬 시각",
+ "edit": "할 일 수정",
+ "name": "제목",
+ "progress": "진행 상황",
+ "link": "근거 링크 (선택)",
+ "saved": "저장됨",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "이전",
+ "following": "다음",
+ "order": "정렬",
+ "dueOrder": "기한순",
+ "createdOrder": "생성순",
+ "origin": "유형",
+ "all": "전체",
+ "close": "닫기",
+ "laterConflict": "미루어도 실제 기한은 연장되지 않습니다",
+ "legacyEvidence": "이전 완료 기록의 근거를 확인해야 합니다",
+ "noPermission": "연결되지 않았거나 승인되지 않은 출처입니다",
+ "copy": "복사",
+ "undo": "실행 취소",
+ "history": "완료 기록",
+ "clockNote": "날짜만 있는 기한은 표시된 시간대의 하루가 끝날 때입니다. 정확한 시각은 시간대를 유지합니다.",
+ "deleted": "삭제됨",
+ "muted": "다시 제안하지 않음",
+ "deferred": "미뤄짐",
+ "continue": "계속",
+ "addTime": "시각 추가",
+ "dateOnly": "날짜만"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 5b41fab86f..ca86347be2 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -814,5 +814,84 @@
"automationInvalid": "自动化定义无法转换,尚未创建。",
"itemFailed": "此项未完成,可重试并查看导入详情。",
"chatPartial": "伙伴已创建,但部分资料未完整保存。以下项目仍需处理;其他内容和对话可以正常使用。"
+ },
+ "teammateTodo": {
+ "title": "待办",
+ "new": "新建待办",
+ "search": "搜索待办",
+ "open": "未完成",
+ "done": "已完成",
+ "hidden": "已忽略 / 稍后",
+ "empty": "暂无待办",
+ "noMatch": "没有匹配的待办",
+ "loading": "正在读取…",
+ "retry": "重试",
+ "error": "操作未完成,请重试。",
+ "conflict": "待办已更新,请重新查看后再修改。",
+ "received": "已收到",
+ "accepted": "查看进展",
+ "unknown": "核实进展",
+ "failed": "重试下一步",
+ "view": "查看详情",
+ "evidence": "查看依据",
+ "more": "更多操作",
+ "discovered": "发现",
+ "assigned": "交办",
+ "suggested": "建议",
+ "candidate": "待确认",
+ "overdue": "已逾期",
+ "today": "今天",
+ "next": "下一步",
+ "outcome": "完成条件",
+ "value": "为什么值得处理",
+ "sources": "来源依据",
+ "associations": "关联",
+ "deadline": "到期时间",
+ "sourceDeadline": "来源期限",
+ "clearDate": "清除到期",
+ "date": "日期",
+ "time": "确切时间(可选)",
+ "zone": "时区",
+ "save": "保存",
+ "cancel": "取消",
+ "delete": "删除此条",
+ "mute": "此问题不再提示",
+ "later": "稍后处理",
+ "until": "稍后至",
+ "restore": "恢复",
+ "reopen": "重新打开",
+ "complete": "标记完成",
+ "summary": "完成依据",
+ "confirmDate": "确认日期",
+ "deadlineReason": "日期待确认的原因",
+ "override": "你设置的期限",
+ "reminder": "稍后至",
+ "edit": "编辑待办",
+ "name": "标题",
+ "progress": "当前进展",
+ "link": "依据链接(可选)",
+ "saved": "已保存",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "上一页",
+ "following": "下一页",
+ "order": "排序",
+ "dueOrder": "到期优先",
+ "createdOrder": "创建顺序",
+ "origin": "来源类型",
+ "all": "全部",
+ "close": "关闭",
+ "laterConflict": "稍后处理不延长真实期限",
+ "legacyEvidence": "旧记录的完成依据待核实",
+ "noPermission": "此来源未连接或尚未授权",
+ "copy": "复制",
+ "undo": "撤销",
+ "history": "完成记录",
+ "clockNote": "仅日期按所示时区当天结束;确切时刻保留时区。",
+ "deleted": "已删除",
+ "muted": "不再提示",
+ "deferred": "稍后处理",
+ "continue": "继续",
+ "addTime": "添加时间",
+ "dateOnly": "仅日期"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index f9918ce2eb..ba23c66e19 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -814,5 +814,84 @@
"automationInvalid": "自動化定義無法轉換,尚未建立。",
"itemFailed": "此項未完成,可重試並查看匯入詳情。",
"chatPartial": "夥伴已建立,但部分資料未完整儲存。以下項目仍需處理;其他內容和對話可以正常使用。"
+ },
+ "teammateTodo": {
+ "title": "待辦",
+ "new": "新增待辦",
+ "search": "搜尋待辦",
+ "open": "未完成",
+ "done": "已完成",
+ "hidden": "已忽略 / 稍後",
+ "empty": "暫無待辦",
+ "noMatch": "沒有符合的待辦",
+ "loading": "正在讀取…",
+ "retry": "重試",
+ "error": "操作未完成,請重試。",
+ "conflict": "待辦已更新,請重新查看後再修改。",
+ "received": "已收到",
+ "accepted": "查看進度",
+ "unknown": "核實進度",
+ "failed": "重試下一步",
+ "view": "查看詳情",
+ "evidence": "查看依據",
+ "more": "更多操作",
+ "discovered": "发现",
+ "assigned": "交办",
+ "suggested": "建議",
+ "candidate": "待確認",
+ "overdue": "已逾期",
+ "today": "今天",
+ "next": "下一步",
+ "outcome": "完成條件",
+ "value": "為何值得處理",
+ "sources": "來源依據",
+ "associations": "关联",
+ "deadline": "到期時間",
+ "sourceDeadline": "來源期限",
+ "clearDate": "清除到期",
+ "date": "日期",
+ "time": "確切時間(選填)",
+ "zone": "時區",
+ "save": "儲存",
+ "cancel": "取消",
+ "delete": "刪除此項",
+ "mute": "此問題不再提示",
+ "later": "稍後處理",
+ "until": "稍後至",
+ "restore": "恢復",
+ "reopen": "重新開啟",
+ "complete": "標記完成",
+ "summary": "完成依據",
+ "confirmDate": "確認日期",
+ "deadlineReason": "日期待確認的原因",
+ "override": "你設定的期限",
+ "reminder": "稍後至",
+ "edit": "编辑待办",
+ "name": "標題",
+ "progress": "目前進度",
+ "link": "依據連結(選填)",
+ "saved": "已儲存",
+ "page": "{{start}}–{{end}} / {{count}}",
+ "previous": "上一頁",
+ "following": "下一頁",
+ "order": "排序",
+ "dueOrder": "到期優先",
+ "createdOrder": "建立順序",
+ "origin": "來源類型",
+ "all": "全部",
+ "close": "關閉",
+ "laterConflict": "稍後處理不延長真實期限",
+ "legacyEvidence": "舊記錄的完成依據待核實",
+ "noPermission": "此來源未連接或尚未授權",
+ "copy": "複製",
+ "undo": "復原",
+ "history": "完成記錄",
+ "clockNote": "僅日期按所示時區當天結束;確切時刻保留時區。",
+ "deleted": "已刪除",
+ "muted": "不再提示",
+ "deferred": "稍後處理",
+ "continue": "繼續",
+ "addTime": "新增時間",
+ "dateOnly": "僅日期"
}
}
diff --git a/apps/mobile/src/session/ChatIdentityHeader.tsx b/apps/mobile/src/session/ChatIdentityHeader.tsx
index 6cf5892968..789fc4cf23 100644
--- a/apps/mobile/src/session/ChatIdentityHeader.tsx
+++ b/apps/mobile/src/session/ChatIdentityHeader.tsx
@@ -14,8 +14,9 @@ export const CHAT_HEADER_MARK_SIZE = 32;
* 设置。点身份区和设置按钮打开同一份资料 / 设置。
*/
export function ChatIdentityHeader({
- mark, title, subtitle, identityLabel, identityHint, controlsReady = true, onBack, onOpenSettings, settingsLabel, testIDPrefix, settingsTestID,
+ accessory, mark, title, subtitle, identityLabel, identityHint, controlsReady = true, onBack, onOpenSettings, settingsLabel, testIDPrefix, settingsTestID,
}: {
+ accessory?: ReactNode;
mark: ReactNode;
title: string;
/** A short line under the title: presence + computer name, or member names. */
@@ -47,6 +48,7 @@ export function ChatIdentityHeader({
{typeof subtitle === 'string' ? <Text numberOfLines={1} style={styles.subtitle}>{subtitle}</Text> : subtitle}
</View>
</Pressable>
+ {accessory}
<HomeHeaderGlassButton testID={settingsTestID ?? `${testIDPrefix}.settings`} disabled={!controlsReady} accessibilityLabel={settingsLabel} onPress={open}>
<Settings2 size={iconSize.lg} strokeWidth={iconStroke.regular} color={colors.textPrimary} />
</HomeHeaderGlassButton>
diff --git a/apps/mobile/src/session/CompanionHeader.tsx b/apps/mobile/src/session/CompanionHeader.tsx
index 57aeda2a80..9c8d2d022e 100644
--- a/apps/mobile/src/session/CompanionHeader.tsx
+++ b/apps/mobile/src/session/CompanionHeader.tsx
@@ -1,10 +1,13 @@
+import { ListTodo } from 'lucide-react-native';
+import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';
+import { CompanionTodos } from './CompanionTodos';
import { useEffect, useRef, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { resolveRemoteText, type RemoteResource } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
-import { radius, spacing, useThemedStyles, type ThemeColors } from '@/theme';
+import { radius, spacing, iconSize, iconStroke, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { CHAT_HEADER_MARK_SIZE, ChatIdentityHeader, ChatIdentitySubtitle } from './ChatIdentityHeader';
import { CompanionPresenceRing } from './CompanionPresenceRing';
import { CompanionProfileSheet } from './CompanionProfileSheet';
@@ -31,8 +34,10 @@ export function CompanionHeader(props: {
function CompanionHeaderContent({ resource, deviceId, deviceName, online, controlsReady = true, working = false, onSearch, onBack, settingsRequest }: Parameters<typeof CompanionHeader>[0]) {
const { t, i18n } = useTranslation();
const styles = useThemedStyles(makeStyles);
+ const {colors}=useTheme();
const navigation = useTeammateNavigation();
const [profile, setProfile] = useState(false);
+ const [todos, setTodos] = useState(false);
const [initialPage, setInitialPage] = useState<'home' | 'memory' | 'capabilities'>('home');
useEffect(() => { if (settingsRequest) { setInitialPage(settingsRequest.page); setProfile(true); } }, [settingsRequest]);
const pending = useRef<(() => void) | null>(null);
@@ -55,7 +60,9 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, contro
controlsReady={controlsReady}
onBack={onBack}
onOpenSettings={() => { setInitialPage('home'); setProfile(true); }}
+ accessory={resource.links?.some(link=>link.target.kind==='resource'&&link.target.ref.id==='todos:'+resource.ref.id)?<HomeHeaderGlassButton testID="companion.todos.open" accessibilityLabel={t('devices.teammateTodo.title')} onPress={()=>setTodos(true)}><ListTodo size={iconSize.lg} strokeWidth={iconStroke.regular} color={colors.textPrimary}/></HomeHeaderGlassButton>:undefined}
settingsLabel={t('devices.companionProfile.settingsTitle')} />
+ <CompanionTodos visible={todos} onClose={()=>setTodos(false)} botId={resource.ref.id} deviceId={deviceId} deviceName={deviceName} online={online}/>
<CompanionProfileSheet initialPage={initialPage} visible={profile} onClose={() => setProfile(false)} onClosed={() => { const action = pending.current; pending.current = null; action?.(); }}
resource={resource} collectionId={resource.ref.collectionId} deviceId={deviceId} deviceName={deviceName} online={online}
onDeleted={() => void navigation.chooseMode('teammates')}
diff --git a/apps/mobile/src/session/CompanionTodoRow.tsx b/apps/mobile/src/session/CompanionTodoRow.tsx
new file mode 100644
index 0000000000..879ecce177
--- /dev/null
+++ b/apps/mobile/src/session/CompanionTodoRow.tsx
@@ -0,0 +1,102 @@
+import { Pressable, View } from 'react-native';
+import { MoreHorizontal } from 'lucide-react-native';
+import { Text } from '@/components/AppText';
+import { useTheme, useThemedStyles } from '@/theme';
+import {
+ effectiveTodoDeadline,
+ todoDateLabel,
+ todoOverdue,
+ todoVisible,
+ type TeammateTodo,
+} from '@cindy/maker-shared/teammate-todo';
+import { makeTodoStyles as makeStyles } from './companionTodoStyles';
+/** Fixed text block followed by a date/action/menu rail, shared by every production row. */
+export function CompanionTodoRow({
+ item: x,
+ label,
+ locale,
+ busy,
+ onOpen,
+ onAction,
+ onDate,
+ onMore,
+ tr,
+}: {
+ item: TeammateTodo;
+ label: string;
+ locale: string;
+ busy: boolean;
+ onOpen(): void;
+ onAction(): void;
+ onDate(): void;
+ onMore(): void;
+ tr(key: string): string;
+}) {
+ const styles = useThemedStyles(makeStyles),
+ { colors } = useTheme();
+ return (
+ <View style={styles.row} testID="todo-row">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={x.title}
+ onPress={onOpen}
+ style={styles.heading}
+ >
+ <Text numberOfLines={1} style={styles.title}>
+ {x.title}
+ </Text>
+ <Text numberOfLines={1} style={styles.progress}>
+ {!todoVisible(x) && x.decision
+ ? tr(
+ x.decision.kind === 'deleted'
+ ? 'deleted'
+ : x.decision.kind === 'muted'
+ ? 'muted'
+ : 'deferred',
+ ) + ' · '
+ : ''}
+ {x.origin === 'discovered' ? tr('discovered') + ' · ' : ''}
+ {x.progress || x.next?.instruction || x.outcome}
+ </Text>
+ </Pressable>
+ <View style={styles.rail}>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={tr('deadline')}
+ onPress={onDate}
+ style={styles.date}
+ >
+ <Text numberOfLines={1} style={styles.caption}>
+ {!effectiveTodoDeadline(x) && x.deadlineCandidate
+ ? tr('candidate') + ' '
+ : !effectiveTodoDeadline(x) && x.suggestedDate
+ ? tr('suggested') + ' '
+ : ''}
+ {todoDateLabel(x, locale)}
+ {todoOverdue(x) && x.status !== 'done' ? ' · ' + tr('overdue') : ''}
+ </Text>
+ </Pressable>
+ <Pressable
+ disabled={busy}
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ accessibilityState={{ disabled: busy }}
+ onPress={onAction}
+ style={[styles.action, busy && styles.disabled]}
+ >
+ <Text numberOfLines={1} style={styles.actionText}>
+ {label}
+ </Text>
+ </Pressable>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={tr('more')}
+ onPress={onMore}
+ style={styles.icon}
+ >
+ <MoreHorizontal color={colors.textSecondary} size={20} />
+ </Pressable>
+ </View>
+ </View>
+ );
+}
diff --git a/apps/mobile/src/session/CompanionTodos.tsx b/apps/mobile/src/session/CompanionTodos.tsx
new file mode 100644
index 0000000000..23a72f7e36
--- /dev/null
+++ b/apps/mobile/src/session/CompanionTodos.tsx
@@ -0,0 +1,669 @@
+import { TodoDateInput } from './TodoDateInput';
+import { CompanionTodoRow } from './CompanionTodoRow';
+import { makeTodoStyles as makeStyles } from './companionTodoStyles';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ActivityIndicator, Linking, Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { Plus, ChevronDown, ChevronRight } from 'lucide-react-native';
+import { randomUUID } from 'expo-crypto';
+import { useTranslation } from 'react-i18next';
+import { useAuth } from '@/auth/AuthContext';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { getRemoteResource, invokeRemoteResourceAction } from '@/device-link/remoteResources';
+import { Text, TextInput } from '@/components/AppText';
+import {
+ fontWeight,
+ lineHeight,
+ radius,
+ spacing,
+ typeScale,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from '@/theme';
+import { CompanionSheet } from './CompanionSheet';
+import {
+ effectiveTodoDeadline,
+ todoDateLabel,
+ todoOverdue,
+ todoLocalDate,
+ type TeammateTodo,
+ type TodoPatch,
+ type TodoListQuery,
+} from '@cindy/maker-shared/teammate-todo';
+
+interface Props {
+ visible: boolean;
+ onClose(): void;
+ deviceId: string;
+ deviceName: string;
+ botId: string;
+ online: boolean;
+}
+interface Page {
+ items: TeammateTodo[];
+ total: number;
+ completedTotal: number;
+ offset: number;
+ limit: number;
+}
+export function CompanionTodos(props: Props) {
+ const { accountGeneration } = useAuth();
+ return (
+ <CompanionTodosContent
+ key={`${accountGeneration}:${props.deviceId}:${props.botId}`}
+ {...props}
+ />
+ );
+}
+function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId, online }: Props) {
+ const { t, i18n } = useTranslation();
+ const tr = (key: string, args?: Record<string, unknown>): string =>
+ String(t('devices.teammateTodo.' + key, args));
+ const { invoke, openLink, onRemoteResourceChanged } = useDeviceLink();
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const [page, setPage] = useState<Page>({
+ items: [],
+ total: 0,
+ completedTotal: 0,
+ offset: 0,
+ limit: 25,
+ }),
+ [query, setQuery] = useState(''),
+ [filter, setFilter] = useState<TodoListQuery>({
+ view: 'open',
+ order: 'due',
+ }),
+ [offset, setOffset] = useState(0);
+ const [loading, setLoading] = useState(false),
+ [busy, setBusy] = useState(false),
+ [error, setError] = useState(''),
+ [detail, setDetail] = useState<TeammateTodo | null>(null),
+ [editing, setEditing] = useState<false | 'edit' | 'deadline' | 'complete' | 'later'>(false);
+ const [form, setForm] = useState<Record<string, string>>({});
+ const [showActions, setShowActions] = useState(false);
+ const pending = useRef(false);
+ const epoch = useRef(0),
+ binding = useRef(''),
+ mounted = useRef(true);
+ binding.current = `${deviceId}:${botId}:${visible}:${online}`;
+ const readingOrder = useRef<{ key: string; ids: string[] }>({ key: '', ids: [] });
+ const ref = { collectionId: 'teammates', kind: 'bot', id: 'todos:' + botId };
+ const reload = useCallback(async () => {
+ if (!visible || !online) return;
+ const scope = binding.current,
+ n = ++epoch.current;
+ setLoading(true);
+ try {
+ await openLink(deviceId);
+ const resource = await getRemoteResource(
+ invoke,
+ { deviceId, deviceName },
+ ref,
+ i18n.language,
+ ['teammate-todos'],
+ JSON.stringify({ query, offset, ...filter }),
+ );
+ if (!mounted.current || scope !== binding.current || n !== epoch.current) return;
+ const data = resource.blocks?.find((b) => b.primitive === 'teammate-todos')?.data as
+ Page | undefined;
+ if (
+ !data ||
+ !Array.isArray(data.items) ||
+ !Number.isSafeInteger(data.total) ||
+ data.items.length > 25
+ )
+ throw new Error('INVALID_RESPONSE');
+ const orderKey = JSON.stringify({ scope, query, offset: data.offset, ...filter });
+ if (readingOrder.current.key === orderKey) {
+ const ranks = new Map(readingOrder.current.ids.map((id, index) => [id, index]));
+ data.items = [...data.items].sort(
+ (a, b) =>
+ (ranks.get(a.id) ?? Number.MAX_SAFE_INTEGER) -
+ (ranks.get(b.id) ?? Number.MAX_SAFE_INTEGER),
+ );
+ }
+ readingOrder.current = { key: orderKey, ids: data.items.map((item) => item.id) };
+ setPage(data);
+ setDetail((old) => (old ? (data.items.find((x) => x.id === old.id) ?? old) : null));
+ setError('');
+ } catch {
+ if (mounted.current && scope === binding.current) setError('error');
+ } finally {
+ if (mounted.current && scope === binding.current) setLoading(false);
+ }
+ }, [
+ visible,
+ online,
+ deviceId,
+ deviceName,
+ invoke,
+ openLink,
+ query,
+ offset,
+ filter,
+ i18n.language,
+ ]);
+ useEffect(() => {
+ mounted.current = true;
+ const timer = setTimeout(() => void reload(), query ? 250 : 0);
+ return () => {
+ clearTimeout(timer);
+ epoch.current++;
+ };
+ }, [reload]);
+ useEffect(
+ () => () => {
+ mounted.current = false;
+ },
+ [],
+ );
+ useEffect(
+ () =>
+ onRemoteResourceChanged((id, payload) => {
+ if (
+ id === deviceId &&
+ payload.collectionId === 'teammates' &&
+ (!payload.resourceRefs ||
+ payload.resourceRefs.some((ref) => ref.id === botId || ref.id === 'todos:' + botId))
+ )
+ void reload();
+ }),
+ [onRemoteResourceChanged, deviceId, botId, reload],
+ );
+ useEffect(() => {
+ if (!visible) {
+ setDetail(null);
+ setEditing(false);
+ setShowActions(false);
+ }
+ }, [visible]);
+ const run = async (input: Record<string, unknown>, actionId = 'todo-update') => {
+ if (pending.current || !online) return;
+ pending.current = true;
+ setBusy(true);
+ const scope = binding.current;
+ try {
+ await openLink(deviceId);
+ await invokeRemoteResourceAction(
+ invoke,
+ { deviceId, deviceName },
+ { collectionId: 'teammates', resourceRef: ref, actionId, input },
+ i18n.language,
+ );
+ if (mounted.current && scope === binding.current) {
+ setEditing(false);
+ setDetail(null);
+ setShowActions(false);
+ await reload();
+ }
+ } catch (e) {
+ if (mounted.current && scope === binding.current)
+ setError(String(e).includes('CONFLICT') ? 'conflict' : 'error');
+ } finally {
+ pending.current = false;
+ if (mounted.current && scope === binding.current) setBusy(false);
+ }
+ };
+ const update = (item: TeammateTodo, patch: TodoPatch) =>
+ void run({ ...patch, id: item.id, expectedRevision: item.revision });
+ const label = (x: TeammateTodo) =>
+ x.status === 'done'
+ ? tr('evidence')
+ : x.action
+ ? tr(
+ x.action.state === 'failed'
+ ? 'failed'
+ : x.action.state === 'accepted'
+ ? 'accepted'
+ : x.action.state === 'unknown'
+ ? 'unknown'
+ : 'received',
+ )
+ : x.legacyId && x.next?.label === 'Continue'
+ ? tr('continue')
+ : (x.next?.label ?? tr('view'));
+ const act = (x: TeammateTodo, confirmed = false) => {
+ if (
+ x.status === 'done' ||
+ !x.next ||
+ x.next.kind === 'view' ||
+ (x.next.kind === 'decide' && !confirmed) ||
+ (x.action && x.action.state !== 'failed')
+ ) {
+ setDetail(x);
+ setEditing(false);
+ setShowActions(false);
+ return;
+ }
+ void run(
+ { id: x.id, revision: x.revision, requestId: randomUUID(), locale: i18n.language },
+ 'todo-act',
+ );
+ };
+ const edit = (x: TeammateTodo | null, mode: NonNullable<typeof editing>) => {
+ setDetail(x);
+ setEditing(mode);
+ setShowActions(false);
+ const d = x ? effectiveTodoDeadline(x) : null;
+ setForm({
+ title: x?.title ?? '',
+ outcome: x?.outcome ?? '',
+ progress: x?.progress ?? '',
+ date: d?.at
+ ? todoLocalDate(new Date(d.at), Intl.DateTimeFormat().resolvedOptions().timeZone)
+ : (d?.date ?? ''),
+ time: d?.at ?? '',
+ zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ summary: '',
+ ref: '',
+ until: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
+ });
+ };
+ const menu = (x: TeammateTodo) => {
+ setDetail(x);
+ setEditing(false);
+ setShowActions(true);
+ };
+ const button = (text: string, fn: () => void, style?: object, disabled = false) => (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={text}
+ accessibilityState={{ disabled: disabled || busy || !online }}
+ disabled={disabled || busy || !online}
+ onPress={fn}
+ style={[styles.button, style, (disabled || busy || !online) && styles.disabled]}
+ >
+ <Text numberOfLines={1} style={styles.buttonText}>
+ {text}
+ </Text>
+ </Pressable>
+ );
+ const field = (key: string, label = key) => (
+ <View key={key} style={styles.field}>
+ <Text style={styles.caption}>{tr(label)}</Text>
+ <TextInput
+ accessibilityLabel={tr(label)}
+ value={form[key] ?? ''}
+ onChangeText={(value) => setForm({ ...form, [key]: value })}
+ style={styles.input}
+ multiline={['outcome', 'summary', 'progress'].includes(key)}
+ autoCapitalize="none"
+ />
+ </View>
+ );
+ const save = () => {
+ const patch: TodoPatch =
+ editing === 'edit'
+ ? { title: form.title, outcome: form.outcome, progress: form.progress }
+ : editing === 'deadline'
+ ? {
+ deadlineOverride: {
+ value: form.date
+ ? {
+ kind: form.time ? 'instant' : 'date',
+ date: form.date,
+ timeZone: form.zone,
+ ...(form.time ? { at: form.time } : {}),
+ }
+ : null,
+ },
+ }
+ : editing === 'complete'
+ ? {
+ operation: 'complete',
+ completion: {
+ summary: form.summary,
+ ...(form.ref ? { ref: form.ref } : {}),
+ },
+ }
+ : { operation: 'later', until: form.until };
+ if (detail) update(detail, patch);
+ else
+ void run({
+ ...patch,
+ key: 'user:' + randomUUID(),
+ origin: 'assigned',
+ next: { kind: 'advance', label: tr('continue'), instruction: form.outcome },
+ });
+ };
+ const info = (key: string, value: string | undefined) =>
+ value ? (
+ <View style={styles.field}>
+ <Text style={styles.caption}>{tr(key)}</Text>
+ <Text selectable style={styles.body}>
+ {value}
+ </Text>
+ </View>
+ ) : null;
+ return (
+ <CompanionSheet
+ visible={visible}
+ title={tr('title')}
+ onClose={onClose}
+ onBack={
+ detail || editing || showActions
+ ? () => {
+ setDetail(null);
+ setEditing(false);
+ setShowActions(false);
+ }
+ : undefined
+ }
+ preventDismiss={busy}
+ testID="companion.todos"
+ >
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ contentContainerStyle={styles.content}
+ maintainVisibleContentPosition={{ minIndexForVisible: 0 }}
+ >
+ {!online && (
+ <Text accessibilityRole="alert" style={styles.body}>
+ {t('devices.resources.hostOffline')}
+ </Text>
+ )}
+ {!!error && (
+ <View>
+ <Text accessibilityRole="alert" style={styles.body}>
+ {tr(error)}
+ </Text>
+ {button(tr('retry'), () => void reload())}
+ </View>
+ )}
+ {showActions && detail ? (
+ <>
+ {button(tr('edit'), () => edit(detail, 'edit'))}
+ {button(tr('deadline'), () => edit(detail, 'deadline'))}
+ {button(tr(detail.status === 'done' ? 'reopen' : 'complete'), () =>
+ detail.status === 'done'
+ ? update(detail, { operation: 'reopen' })
+ : edit(detail, 'complete'),
+ )}
+ {detail.decision ? (
+ button(tr('restore'), () => update(detail, { operation: 'restore' }))
+ ) : (
+ <>
+ {button(tr('later'), () => edit(detail, 'later'))}
+ {button(tr('delete'), () => update(detail, { operation: 'delete' }))}
+ {button(tr('mute'), () => update(detail, { operation: 'mute' }))}
+ </>
+ )}
+ {button(tr('cancel'), () => setShowActions(false))}
+ </>
+ ) : editing ? (
+ <>
+ {editing === 'edit' ? (
+ ['title', 'outcome', 'progress'].map((key) =>
+ field(key, key === 'title' ? 'name' : key),
+ )
+ ) : editing === 'complete' ? (
+ ['summary', 'ref'].map((key) => field(key, key === 'ref' ? 'link' : key))
+ ) : editing === 'deadline' ? (
+ <>
+ {form.date ? (
+ <TodoDateInput
+ label={tr('date')}
+ kind="date"
+ value={
+ form.time
+ ? new Date(form.time)
+ : form.date
+ ? new Date(form.date + 'T12:00:00')
+ : new Date()
+ }
+ onChange={(date) =>
+ setForm({
+ ...form,
+ date: todoLocalDate(date, form.zone),
+ ...(form.time ? { time: date.toISOString() } : {}),
+ })
+ }
+ />
+ ) : (
+ button(tr('deadline'), () =>
+ setForm({
+ ...form,
+ date: todoLocalDate(new Date(), form.zone),
+ }),
+ )
+ )}
+ {form.time ? (
+ <>
+ <TodoDateInput
+ label={tr('time')}
+ kind="time"
+ value={new Date(form.time)}
+ onChange={(date) =>
+ setForm({
+ ...form,
+ date: todoLocalDate(date, form.zone),
+ time: date.toISOString(),
+ })
+ }
+ />
+ {button(tr('dateOnly'), () => setForm({ ...form, time: '' }))}
+ </>
+ ) : (
+ button(tr('addTime'), () => {
+ const date = form.date ? new Date(form.date + 'T12:00:00') : new Date();
+ setForm({
+ ...form,
+ date: todoLocalDate(date, form.zone),
+ time: date.toISOString(),
+ });
+ })
+ )}
+ {info('zone', form.zone)}
+ </>
+ ) : (
+ <TodoDateInput
+ label={tr('until')}
+ kind="datetime"
+ value={new Date(form.until)}
+ onChange={(date) => setForm({ ...form, until: date.toISOString() })}
+ />
+ )}
+ {editing === 'deadline' && (
+ <>
+ {button(tr('clearDate'), () => setForm({ ...form, date: '', time: '' }))}
+ {detail?.deadlineCandidate && (
+ <>
+ {info('deadlineReason', detail.deadlineCandidate.reason)}
+ {button(tr('confirmDate'), () =>
+ update(detail, { operation: 'confirm-deadline' }),
+ )}
+ </>
+ )}
+ </>
+ )}
+ {editing === 'later' && info('laterConflict', tr('laterConflict'))}
+ {button(tr('save'), save)}
+ {button(tr('cancel'), () => setEditing(false))}
+ </>
+ ) : detail ? (
+ <>
+ <Text selectable style={styles.title}>
+ {detail.title}
+ </Text>
+ {info('progress', detail.progress)}
+ {info('outcome', detail.outcome)}
+ {info('value', detail.value)}
+ {info('next', detail.next?.instruction)}
+ {detail.next &&
+ detail.next.kind !== 'view' &&
+ (!detail.action || detail.action.state === 'failed') &&
+ detail.status === 'open' &&
+ button(detail.next.label, () => act(detail, true))}
+ {info(
+ 'sourceDeadline',
+ detail.sourceDeadline
+ ? `${detail.sourceDeadline.date} ${detail.sourceDeadline.at ?? ''} · ${detail.sourceDeadline.timeZone}\n${detail.sourceDeadline.quote ?? ''}`
+ : undefined,
+ )}
+ {detail.deadlineOverride &&
+ info('override', effectiveTodoDeadline(detail)?.date ?? tr('clearDate'))}
+ {detail.deadlineCandidate && (
+ <>
+ {info('deadlineReason', detail.deadlineCandidate.reason)}
+ {button(tr('confirmDate'), () => update(detail, { operation: 'confirm-deadline' }))}
+ </>
+ )}
+ {info('reminder', detail.decision?.until)}
+ {!!detail.sources.length && (
+ <View style={styles.field}>
+ <Text style={styles.caption}>{tr('sources')}</Text>
+ {detail.sources.map((s) => (
+ <View key={s.kind + ':' + s.id}>
+ <Text selectable style={styles.body}>
+ {s.label}
+ {s.observedAt ? ' · ' + s.observedAt : ''}
+ </Text>
+ {s.ref && button(tr('view'), () => void Linking.openURL(s.ref!))}
+ </View>
+ ))}
+ </View>
+ )}
+ {!!detail.associations.length &&
+ info(
+ 'associations',
+ detail.associations.map((a) => a.label + ' · ' + a.id).join('\n'),
+ )}
+ {detail.history.map((h, n) => (
+ <View key={n}>
+ {info(
+ 'evidence',
+ (h.summary === 'Legacy completion evidence was not recorded'
+ ? tr('legacyEvidence')
+ : h.summary) +
+ ' · ' +
+ h.at,
+ )}
+ {h.ref &&
+ /^https:\/\//.test(h.ref) &&
+ button(tr('evidence'), () => void Linking.openURL(h.ref!))}
+ </View>
+ ))}
+ {button(tr('edit'), () => edit(detail, 'edit'))}
+ {button(tr('more'), () => menu(detail))}
+ </>
+ ) : (
+ <>
+ <View style={styles.toolbar}>
+ <TextInput
+ style={[styles.input, styles.flex]}
+ value={query}
+ onChangeText={(value) => {
+ setQuery(value);
+ setOffset(0);
+ }}
+ placeholder={tr('search')}
+ accessibilityLabel={tr('search')}
+ />
+ <Pressable
+ style={styles.icon}
+ accessibilityRole="button"
+ accessibilityLabel={tr('new')}
+ onPress={() => edit(null, 'edit')}
+ >
+ <Plus color={colors.textPrimary} size={20} />
+ </Pressable>
+ </View>
+ <View style={styles.toolbar}>
+ {button(
+ tr(filter.view === 'hidden' ? 'hidden' : 'open'),
+ () => {
+ setFilter({
+ ...filter,
+ view: filter.view === 'hidden' ? 'open' : 'hidden',
+ });
+ setOffset(0);
+ },
+ styles.flex,
+ )}
+ {button(
+ tr(filter.order === 'created' ? 'createdOrder' : 'dueOrder'),
+ () => {
+ setFilter({
+ ...filter,
+ order: filter.order === 'created' ? 'due' : 'created',
+ });
+ setOffset(0);
+ },
+ styles.flex,
+ )}
+ </View>
+ {loading && (
+ <ActivityIndicator accessibilityLabel={tr('loading')} color={colors.textSecondary} />
+ )}
+ {!loading && !page.items.length && (
+ <Text style={styles.body}>{tr(query ? 'noMatch' : 'empty')}</Text>
+ )}
+ {page.items.map((x) => (
+ <CompanionTodoRow
+ key={x.id}
+ item={x}
+ label={label(x)}
+ locale={i18n.language}
+ busy={busy || !online}
+ onOpen={() => {
+ setDetail(x);
+ setEditing(false);
+ setShowActions(false);
+ }}
+ onAction={() => act(x)}
+ onDate={() => edit(x, 'deadline')}
+ onMore={() => menu(x)}
+ tr={tr}
+ />
+ ))}
+ {page.total > 25 && (
+ <View style={styles.toolbar}>
+ {button(
+ tr('previous'),
+ () => setOffset(Math.max(0, page.offset - 25)),
+ undefined,
+ !page.offset,
+ )}
+ <Text style={styles.caption}>
+ {tr('page', {
+ start: page.offset + 1,
+ end: Math.min(page.offset + 25, page.total),
+ count: page.total,
+ })}
+ </Text>
+ {button(
+ tr('following'),
+ () => setOffset(page.offset + 25),
+ undefined,
+ page.offset + 25 >= page.total,
+ )}
+ </View>
+ )}
+ <Pressable
+ style={styles.disclosure}
+ accessibilityRole="button"
+ accessibilityState={{ expanded: filter.view === 'done' }}
+ onPress={() => {
+ setFilter({
+ ...filter,
+ view: filter.view === 'done' ? 'open' : 'done',
+ });
+ setOffset(0);
+ }}
+ >
+ {filter.view === 'done' ? (
+ <ChevronDown color={colors.textSecondary} size={16} />
+ ) : (
+ <ChevronRight color={colors.textSecondary} size={16} />
+ )}
+ <Text style={styles.caption}>
+ {tr('done')} · {page.completedTotal}
+ </Text>
+ </Pressable>
+ </>
+ )}
+ </ScrollView>
+ </CompanionSheet>
+ );
+}
diff --git a/apps/mobile/src/session/TodoDateInput.android.tsx b/apps/mobile/src/session/TodoDateInput.android.tsx
new file mode 100644
index 0000000000..7cf10d05cb
--- /dev/null
+++ b/apps/mobile/src/session/TodoDateInput.android.tsx
@@ -0,0 +1,80 @@
+import { useState } from 'react';
+import { Pressable, View } from 'react-native';
+import { Host } from '@expo/ui';
+import { DatePickerDialog, TimePickerDialog } from '@expo/ui/jetpack-compose';
+import { Text } from '@/components/AppText';
+import { useTheme, useThemedStyles } from '@/theme';
+import { makeTodoStyles } from './companionTodoStyles';
+import type { TodoDateInputProps } from './TodoDateInput';
+export function TodoDateInput({ label, value, kind, onChange }: TodoDateInputProps) {
+ const [part, setPart] = useState<'date' | 'time' | null>(null),
+ { mode, colors } = useTheme(),
+ styles = useThemedStyles(makeTodoStyles);
+ const chooseDate = (d: Date) => {
+ const merged = new Date(value);
+ merged.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
+ onChange(merged);
+ setPart(null);
+ };
+ const chooseTime = (d: Date) => {
+ const merged = new Date(value);
+ merged.setHours(d.getHours(), d.getMinutes(), 0, 0);
+ onChange(merged);
+ setPart(null);
+ };
+ return (
+ <View>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ onPress={() => setPart(kind === 'time' ? 'time' : 'date')}
+ style={styles.button}
+ >
+ <Text style={styles.buttonText}>
+ {kind === 'date'
+ ? value.toLocaleDateString()
+ : kind === 'time'
+ ? value.toLocaleTimeString([], {
+ hour: '2-digit',
+ minute: '2-digit',
+ })
+ : value.toLocaleString()}
+ </Text>
+ </Pressable>
+ {kind === 'datetime' && (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ onPress={() => setPart('time')}
+ style={styles.button}
+ >
+ <Text style={styles.buttonText}>
+ {value.toLocaleTimeString([], {
+ hour: '2-digit',
+ minute: '2-digit',
+ })}
+ </Text>
+ </Pressable>
+ )}
+ {part && (
+ <Host colorScheme={mode} seedColor={colors.textPrimary} matchContents>
+ {part === 'date' ? (
+ <DatePickerDialog
+ initialDate={new Date(
+ Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()),
+ ).toISOString()}
+ onDateSelected={chooseDate}
+ onDismissRequest={() => setPart(null)}
+ />
+ ) : (
+ <TimePickerDialog
+ initialDate={value.toISOString()}
+ onDateSelected={chooseTime}
+ onDismissRequest={() => setPart(null)}
+ />
+ )}
+ </Host>
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/session/TodoDateInput.ios.tsx b/apps/mobile/src/session/TodoDateInput.ios.tsx
new file mode 100644
index 0000000000..08c5665c74
--- /dev/null
+++ b/apps/mobile/src/session/TodoDateInput.ios.tsx
@@ -0,0 +1,25 @@
+import { Host } from '@expo/ui';
+import { DatePicker } from '@expo/ui/swift-ui';
+import { datePickerStyle, frame } from '@expo/ui/swift-ui/modifiers';
+import { useTheme } from '@/theme';
+import type { TodoDateInputProps } from './TodoDateInput';
+export function TodoDateInput({ label, value, kind, onChange }: TodoDateInputProps) {
+ const { mode } = useTheme();
+ return (
+ <Host colorScheme={mode} matchContents style={{ minHeight: 44 }}>
+ <DatePicker
+ title={label}
+ selection={value}
+ displayedComponents={
+ kind === 'datetime'
+ ? ['date', 'hourAndMinute']
+ : kind === 'time'
+ ? ['hourAndMinute']
+ : ['date']
+ }
+ onDateChange={onChange}
+ modifiers={[datePickerStyle('compact'), frame({ height: 44 })]}
+ />
+ </Host>
+ );
+}
diff --git a/apps/mobile/src/session/TodoDateInput.tsx b/apps/mobile/src/session/TodoDateInput.tsx
new file mode 100644
index 0000000000..43e0c8cbdc
--- /dev/null
+++ b/apps/mobile/src/session/TodoDateInput.tsx
@@ -0,0 +1,24 @@
+import { TextInput } from '@/components/AppText';
+import { useThemedStyles } from '@/theme';
+import { makeTodoStyles } from './companionTodoStyles';
+export interface TodoDateInputProps {
+ label: string;
+ value: Date;
+ kind: 'date' | 'time' | 'datetime';
+ onChange(date: Date): void;
+}
+/** Web fallback; native platforms use the existing Expo UI date/time controls. */
+export function TodoDateInput({ label, value, onChange }: TodoDateInputProps) {
+ const styles = useThemedStyles(makeTodoStyles);
+ return (
+ <TextInput
+ accessibilityLabel={label}
+ style={styles.input}
+ value={value.toLocaleString()}
+ onChangeText={(text) => {
+ const date = new Date(text);
+ if (Number.isFinite(date.getTime())) onChange(date);
+ }}
+ />
+ );
+}
diff --git a/apps/mobile/src/session/companionTodoStyles.ts b/apps/mobile/src/session/companionTodoStyles.ts
new file mode 100644
index 0000000000..0e84689200
--- /dev/null
+++ b/apps/mobile/src/session/companionTodoStyles.ts
@@ -0,0 +1,107 @@
+import { StyleSheet } from 'react-native';
+import { fontWeight, lineHeight, radius, spacing, typeScale, type ThemeColors } from '@/theme';
+export const makeTodoStyles = (c: ThemeColors) =>
+ StyleSheet.create({
+ content: {
+ paddingHorizontal: spacing.lg,
+ paddingBottom: spacing.lg,
+ gap: spacing.sm,
+ },
+ toolbar: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
+ flex: { flex: 1, minWidth: 0 },
+ row: {
+ paddingVertical: spacing.sm,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: c.border,
+ minWidth: 0,
+ },
+ heading: { minHeight: 46, minWidth: 0 },
+ title: {
+ fontSize: typeScale.subtitle,
+ lineHeight: lineHeight.subtitle,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ progress: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.regular,
+ color: c.textSecondary,
+ },
+ rail: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: spacing.sm,
+ marginTop: spacing.sm,
+ minHeight: 44,
+ },
+ date: { flex: 1, minWidth: 0, minHeight: 44, justifyContent: 'center' },
+ caption: {
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ fontWeight: fontWeight.regular,
+ color: c.textSecondary,
+ },
+ action: {
+ width: 144,
+ minHeight: 44,
+ justifyContent: 'center',
+ alignItems: 'center',
+ paddingHorizontal: spacing.sm,
+ borderRadius: radius.pill,
+ backgroundColor: c.surfaceChip,
+ },
+ actionText: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ maxWidth: '100%',
+ },
+ icon: {
+ width: 44,
+ minHeight: 44,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ button: {
+ minHeight: 44,
+ paddingHorizontal: spacing.sm,
+ justifyContent: 'center',
+ alignItems: 'center',
+ borderRadius: radius.control,
+ backgroundColor: c.surfaceChip,
+ },
+ buttonText: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.medium,
+ color: c.textPrimary,
+ },
+ disabled: { opacity: 0.5 },
+ body: {
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.regular,
+ color: c.textPrimary,
+ },
+ field: { gap: spacing.xs },
+ input: {
+ minHeight: 44,
+ padding: spacing.sm,
+ borderRadius: radius.control,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: c.border,
+ color: c.textPrimary,
+ fontSize: typeScale.bodySmall,
+ lineHeight: lineHeight.bodySmall,
+ fontWeight: fontWeight.regular,
+ backgroundColor: c.surfaceElevated,
+ },
+ disclosure: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: spacing.xs,
+ minHeight: 44,
+ },
+ });
diff --git a/docs/assets/teammate-todos/README.md b/docs/assets/teammate-todos/README.md
new file mode 100644
index 0000000000..54488c0a49
--- /dev/null
+++ b/docs/assets/teammate-todos/README.md
@@ -0,0 +1,15 @@
+# Teammate Todo component acceptance
+
+These are the implemented desktop `TodoPanel` and mobile `CompanionTodoRow`, rendered with isolated simulated records. They are **component fixtures**, not screenshots of the running Cindy application or a physical iPhone. They import production controls, CSS/theme registry and mobile theme/typography; no prototype markup is substituted.
+
+- Desktop: 360px right panel, light/dark, 2× screenshots: [light](desktop-light.png), [dark](desktop-dark.png).
+- Mobile: 393px viewport, React Native Web rendering of the native row, light/dark: [light](mobile-light.png), [dark](mobile-dark.png).
+- Actual desktop panel interactions: [completed evidence](desktop-completion-evidence.png), [failed save retaining input](desktop-save-error.png).
+
+32 automated layout cases cover desktop 360/320px and mobile 393/320px, each theme and 4/8/36/100 records. DOM checks assert shared action/menu boundaries, matching rail centers, title/date left edge, no horizontal overflow and mobile targets ≥44px. The desktop fixture also exercises full-set search beyond the first 25 records, projectless creation, details/Escape, completion evidence, folded completed readback, and failed-save input retention. Keyboard focus and 125% zoom were checked. All fixture traffic is restricted to localhost; no real Todo store or external action is used.
+
+Host tests use temporary homes and real atomic file writes/locks. They cover owner/canonical caller fences, source scope, concurrent revision conflicts, optional field/reference preservation, suppression across sources, successful/failed event cursors, received versus accepted dispatch, repeat clicks and uncertain/stale receipts. Remote get/invoke tests read and update the same isolated store. MCP schemas and existing task/partner prompt paths are checked; mobile typography and remote-resource regressions pass.
+
+Limits: physical iOS/Android, live Cindy GUI, existing user-profile upgrade and live-model prompt adherence/cache/latency were not exercised. No native configuration/dependency or runtime-fingerprint input changed. Full desktop/mobile package typechecks hit the local heap limit (desktop also at 8GB); a read-only upstream baseline reproduces the 4GB failure. Changed production files pass targeted checks using their package tsconfigs; the shared package full check passes. The MCP full check reports unrelated pre-existing test diagnostics; changed MCP files pass. CI remains the full-package verification authority.
+
+Todo storage is separate from project/task state; ordinary task components are retained. Source connections, scanning and reminders are not installed by these APIs. Available authorized events/routines may submit incremental evidence; without a wake event the guide cannot run. Completed records retain evidence, and source deadlines survive user overrides and deferral.
diff --git a/docs/assets/teammate-todos/desktop-completion-evidence.png b/docs/assets/teammate-todos/desktop-completion-evidence.png
new file mode 100644
index 0000000000..9b884a419b
Binary files /dev/null and b/docs/assets/teammate-todos/desktop-completion-evidence.png differ
diff --git a/docs/assets/teammate-todos/desktop-dark.png b/docs/assets/teammate-todos/desktop-dark.png
new file mode 100644
index 0000000000..697912b9e3
Binary files /dev/null and b/docs/assets/teammate-todos/desktop-dark.png differ
diff --git a/docs/assets/teammate-todos/desktop-light.png b/docs/assets/teammate-todos/desktop-light.png
new file mode 100644
index 0000000000..786678095d
Binary files /dev/null and b/docs/assets/teammate-todos/desktop-light.png differ
diff --git a/docs/assets/teammate-todos/desktop-save-error.png b/docs/assets/teammate-todos/desktop-save-error.png
new file mode 100644
index 0000000000..149d5b1b86
Binary files /dev/null and b/docs/assets/teammate-todos/desktop-save-error.png differ
diff --git a/docs/assets/teammate-todos/mobile-dark.png b/docs/assets/teammate-todos/mobile-dark.png
new file mode 100644
index 0000000000..86e4dc9d14
Binary files /dev/null and b/docs/assets/teammate-todos/mobile-dark.png differ
diff --git a/docs/assets/teammate-todos/mobile-light.png b/docs/assets/teammate-todos/mobile-light.png
new file mode 100644
index 0000000000..04f534ee1a
Binary files /dev/null and b/docs/assets/teammate-todos/mobile-light.png differ
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 441edfd195..b1bf96a0b0 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -459,32 +459,19 @@ Session 任务遵守同一套机制与呈现契约:
### 6.3 工作台:项目任务与伙伴 Todo
-Todo 是伙伴根据与用户的对话维护的承诺清单,可包括没有项目、没有执行任务的日常事务。
-项目、Session 和 PR 只是可选关联,不是 Todo 的归属或前提;顶部项目筛选、移除项目不得
-自动隐藏或删除这份清单。普通任务仍复用原有标题、状态、归档与引擎图标,不另造生命周期。
-同一承诺多次执行仍沿用同一条记录;停止执行不等于完成,合并只有满足约定结果时才可作为
-完成依据,仍需验收则保留明确下一步。已完成应可折叠查看,并能看见完成依据。
-
-**实现边界**:上述 Todo 归属与完成查看是产品方向,现有项目绑定工具与 UI 尚未实现。
-以下项目授权、读取与执行限制描述当前能力,不能用它们反推 Todo 必须归属于项目。
-目前 `get_workbench` 返回项目范围内保留的 PR / issue / idea 判断,会话判断另受近期窗口和
-数量过滤,不保证查回全部已存 `done`。`done` 被 UI 隐藏、旧完成判断可被
-200 条上限淘汰;继续为后台任务时也可能删除原判断。尚无无项目条目、独立关联列表或结构化
-完成依据字段。解除项目绑定、保留完成历史的接口及 UI 需另行实施,不能用伪项目绕过。
-
-**共用指南维护流程**:`teammate-guide` 将 Todo 维护与任务调用并列。每轮对话检查新增
-承诺、范围、进展、下一步与完成依据;收到任务结果、用户纠正及已授权主动跟进中新事实时
-同样检查。询问当前进度、要求跟进或发现变化时读取相关已有记录;只有变化才沿用 id 写回,
-纯进度查询允许只读。整条替换时保留仍有效的关联,多条
-变化批量写。只写有依据的状态,建议与已接下的承诺区分,记录不等于开工。逐条核对结果并
-尝试读回并区分回执确认保存、列表可见性和内容核对;失败与不支持的事项如实说明,没有变化不造条目、不做无意义调用。
-会话判断的读取不含旧 `ref`;没有 updatedAt 与当前判断一致的已确认写入回执可恢复原引用时,不整条覆盖该判断,不能把
-字段缺失当作没有引用。近期与数量限制可能让成功写入的旧会话不在读回列表中;成功回执
-确认保存,读回不可见不等于失败,不为出现于列表而重复写入。
-现工具仅能维护获准项目内的事项,无项目承诺先在对话中保留并说明无法持久记录;不得
-写原始存储或把日常事务冒充项目建议。当前可在 `done.next` 写简短完成依据、`ref` 放证据,
-不把它描述为已支持结构化完成记录或完成列表。提示词只规定收到事件时的维护行为,不能
-保证无唤醒时实时运行,也不因维护 Todo 自行新增定时器。
+Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授权信息中主动发现有行动价值的事项。项目、执行任务与 PR 都是可选关联;顶部项目筛选和移除不隐藏或删除 Todo。项目型伙伴的发现范围绑定其职责,个人伙伴也不越过信息源权限。
+
+实现使用伙伴目录下独立的 `todos.v1.json`,带稳定 id/key、乐观修订号与跨进程原子写入。旧工作台文件原样保留,旧 PR/issue/idea 条目按稳定 ID 兼容读取,普通 Session 判断继续属于任务元数据。新存储不静默淘汰完成历史;超容量明确拒绝。损坏文件失败关闭,不能用空列表覆盖。
+
+`list_teammate_todos`、`update_teammate_todo` 是与任务调用并列的伙伴公共能力,调用者由本机在用伙伴主任务反查。更新是部分合并,旧来源/引用默认保留;已有记录必须带修订号,冲突重新读取。完成必须记录依据,重开保留历史。到期支持日期/确切时刻及来源时区,模糊日期先待确认,用户覆盖/清除不被新来源替换;稍后只暂缓呈现,不延长真实期限。删除/不再提示保留同一问题的抑制记录,跨来源去重也遵守它,恢复不影响整个项目或来源。
+
+桌面右侧工作台与手机版伙伴 Todo 入口共享同一宿主记录。远程通过已有受信 device-link resource get/invoke 路径和账号/可见伙伴边界,不新增广域 IPC 权限。旧客户端有只读文本回退;新客户端专用组件按25条翻页并展示总数,搜索在完整记录中进行。
+
+具体动作通过既有伙伴输入路径推进,接收/排队与真实开始/完成各自独立;重复请求不重复投递,未知回执不能盲重试。邮件等来源正文不自动授予外发或费用授权,原授权流程仍适用。原普通任务组件、归档和引擎状态不变。
+
+共用 `teammate-guide` 要求对话变化、任务结果和已授权跟进维护同条;纯进度询问可读取,无变化不写。`preflight_teammate_todo_events` 先按职责、稳定来源游标、同问题 key 与忽略记录做确定性过滤,`record_teammate_todo_event` 原子提交成功处理结果。仅复用实际可用的连接与现有事件/routine;这些接口不提供全邮箱/飞书扫描器,也不新建定时器。失败不推进游标;无唤醒不承诺后台实时运行,预算沿用既有配置,不拍脑袋设固定模型阈值。
+
+以下原项目工具仍供项目素材和普通任务使用,不再作为新 Todo 的存储接口。
2026-10-01 产品裁决(用户已同意):伙伴可以查看、继续「用户明确交给它的项目」里的任务(停止走通用的
`stop_session_turn`,沿用当前 Agent 权限)。2026-10-02 起工作台是伙伴的「负责范围」:不设项目数上限,主人可以口头交代。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 45e0ac0559..c87edf69de 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -565,6 +565,10 @@ Codex Subagent 的可选扩展调配开关。默认关闭以保留 Codex 原生
Cindy 里的**持久 AI 助手实体**(原名 Bot):有长期身份、自有记忆与技能、模型候选链,可以通过有界私信互相沟通,也可以启动独立 Cindy 任务。产品定位参照「AI teammates」,故取人称名词而非机器名词。英文用法分两层:功能名与复数用 Teammates(侧栏标题),句中单数用小写 teammate(`this teammate`、`Archive teammate`)——故 checkCase 为 false。**与 IM 平台机器人严格区分**:Telegram Bot / Discord Bot / 飞书 bot / 企业微信机器人 / @BotFather / bot token 指的是消息平台上的 bot 账号,仍写作 Bot / 机器人,不改成本词;判据是「这个词指的是 Cindy 里那个持久助手实体」才用本词。覆盖 desktop 的 bots.* 命名空间、sidebar.tabs.bots、newChat.atMention.bot 与 mobile 的 devices.json bots.*。先登记为 proposed:改名刚落地,等 UI 走查与产品评审后再定 decided,届时再决定是否把「Bot」登记为各语言的 forbidden 译法(现在不能登记——存量 IM 平台 bot 文案会被大面积误伤)。
+### Todo
+
+伙伴独立事务清单,含交办与获准信息中的主动发现;项目、执行任务与PR仅可选关联。不替代Session任务生命周期。
+
### Token Plan
阿里云百炼与小米 MiMo 的外部订阅产品名称,四语统一保留官方英文写法;与 Coding Plan 是不同套餐和凭证类型,先登记为 proposed,避免供应商预设中混用产品名。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 9bdb988776..c2336402af 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -2397,6 +2397,19 @@
"ko": "작업대"
},
"note": "伙伴主任务右侧栏里的标签:主人交给伙伴的项目,以及项目里的任务、自动化与产出(docs/product-rules/cindy-bots-runtime.md「工作台」一节)。只指这个伙伴视图,不泛指任务列表或其它面板。先登记为 proposed,待 Chris 实机试用后再定。"
+ },
+ {
+ "id": "teammate-todo",
+ "status": "proposed",
+ "en": "Todo",
+ "translations": {
+ "zh-CN": "待办",
+ "zh-TW": "待辦",
+ "ja": "Todo",
+ "ko": "할 일"
+ },
+ "checkCase": false,
+ "note": "伙伴独立事务清单,含交办与获准信息中的主动发现;项目、执行任务与PR仅可选关联。不替代Session任务生命周期。"
}
]
}
diff --git a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
index 2a47591f7e..45f2761363 100644
--- a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
@@ -34,8 +34,9 @@ const snapshot = {
olderCount: 0,
};
-function setup(sessionId: string | null = 'bot-session') {
+function setup(sessionId: string | null = 'bot-session', todos?:BotWorkbenchCallbacks['todos']) {
const callbacks: BotWorkbenchCallbacks = {
+ ...(todos ? {todos} : {}),
get: vi.fn(async () => ({ ok: true as const, workbench: snapshot })),
read: vi.fn(async ({ taskId }: { taskId: string }) => ({
ok: true as const,
@@ -207,3 +208,20 @@ describe('bot workbench tools', () => {
}
});
});
+
+describe('teammate affair discovery tools',()=>{
+ it('registers project-free APIs and binds writes to the canonical caller context',async()=>{
+ const callback=vi.fn(async()=>({ok:true as const,todo:{id:'one'}}));const {reg}=setup('canonical',callback);
+ expect(parse(await reg.call('update_teammate_todo',{patch:{key:'mail:quote',title:'Compare quote',outcome:'User accepts comparison',origin:'discovered'}}))).toMatchObject({ok:true,todo:{id:'one'}});
+ expect(callback).toHaveBeenCalledWith('canonical','update',{key:'mail:quote',title:'Compare quote',outcome:'User accepts comparison',origin:'discovered'});
+ await reg.call('preflight_teammate_todo_events',{events:[{source:'mail',sequence:4,key:'quote'}]});
+ expect(callback).toHaveBeenLastCalledWith('canonical','preflight',[{source:'mail',sequence:4,key:'quote'}]);
+ });
+ it('rejects malformed action/evidence input before invoking the host',async()=>{
+ const callback=vi.fn(async()=>({ok:true as const}));const {reg}=setup(null,callback);
+ expect(parse(await reg.call('list_teammate_todos',{}))).toMatchObject({ok:false,errorCode:'NOT_A_BOT_SESSION'});
+ expect(callback).not.toHaveBeenCalled();
+ const live=setup('canonical',callback);const response=await live.reg.call('update_teammate_todo',{patch:{operation:'complete',completion:{summary:42}}});
+ expect(response.isError).toBe(true);expect(callback).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
index d99ce6782e..165096177e 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import type { TodoPatch } from '@cindy/maker-shared/teammate-todo';
import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import type { ControlResult, LiziMcpSessionContext } from '../types.js';
@@ -141,6 +142,12 @@ export interface WorkbenchTranscriptWire {
}
export interface BotWorkbenchCallbacks {
+ todos?: (
+ callerSessionId: string,
+ operation: 'list' | 'update' | 'preflight' | 'ingest',
+ input?: unknown,
+ ) => Promise<ControlResult<Record<string, unknown>, string>>;
+
get(params: { callerSessionId: string }): Promise<ControlResult<{ workbench: BotWorkbenchSnapshotWire }, string>>;
read(params: {
callerSessionId: string;
@@ -243,27 +250,16 @@ export function registerBotWorkbenchTools(
deps: BotWorkbenchToolDeps,
): void {
const callerSessionId = () => deps.getSessionContext().sessionId ?? null;
+ if (deps.callbacks.todos) registerTodoTools(registry, callerSessionId, deps.callbacks.todos);
registry.register({
name: 'get_workbench',
category: 'bots',
description:
- '读取你的工作台:主人交给你的项目,每个项目的素材(brief:文档路径、git 分支与最近 14 天提交、我打开的 PR 与 issue;项目很多时只有最近交代的前 8 个带 brief,其余为 null,需要时用文件工具自己看),'
- + '项目里最近 30 天的会话(项目里的 Cindy 任务——包括主人自己开的——不管你判断过没有都在,最多 30 条;再补本机 Claude Code / Codex / Pi 会话,合计最多 40 条;更早的只给 olderCount),你写过的 PR / issue / 建议条目,你的例行任务与项目里的自动化。'
- + 'Todo 是你在对话中答应主人的事务,可早于项目或任务;当前工具只支持已接手项目内的记录,不支持无项目 Todo,不要创建伪项目或把日常事务塞成项目 idea。'
- + '主人提到这个项目、让你跟进或问进展,或对话/任务回传/已授权跟进中发现承诺变化时,读相关记录;只有实际变化才沿用 id 写回,纯进度查询也可只读。项目里的任务是上下文,不应逐条复制为 Todo。'
- + '每条会话带 digest:起始目的与最后几条对话,足够大多数判断,不用逐个读全文。会话 judgment 不返回 ref,不能把缺字段当成没有旧引用;找不到 updatedAt 与当前判断一致的已确认写入回执时不要覆盖该判断。'
- + '接手的做法:主人把项目交给你时,先调用它;再用你自己的文件工具读 brief.docs 里最前面的一两份(README / DESIGN / AGENTS 之类),弄清项目是做什么的、在往哪走;'
- + '然后看最近的提交(不是 git 仓库时看 brief.recent)和会话 digest,只对实际变化的相关事项用 set_workbench_tasks 批量写下判断;只有拿不准的几件才 read_workbench_task。'
- + '判断与下一步要体现你对项目的理解(它在项目里处于什么位置、和哪份文档或哪次提交有关),不要只复述会话。'
- + '项目文档(如 DESIGN.md)、最近的 PR 与 issue 同样是素材:值得做的写成 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n> 或 idea:<slug> 条目,带上 ref。'
- + '判断标准:已接下但约定结果未达成 → unfinished;尚未接下的建议 → idea;有可核实依据达到约定结果 → done。纯问答与无关内容不新建条目;停止、空闲、PR 合并不自动等于承诺完成,仍待验收时写明下一步。'
- + 'get_workbench 返回尚保留且仍在项目范围内的 PR/issue/idea done 条目;会话 done 判断还受前述近期窗口和数量过滤,不能保证查回所有已存完成记录。当前界面隐藏 done,最多 200 条且旧 done 优先淘汰;继续为后台任务时也可能移除原判断,不能当完整完成历史。'
- + '写后检查逐条结果并尝试读回确认。会话列表受近期窗口和数量上限约束,写入成功的旧会话可能不在返回中;成功回执确认保存,列表缺席不等于写失败,不能为此重复写。聊天简短区分已保存但列表不可见、已读回核对和未保存;记录建议不等于开工授权。已有同范围授权时继续跟进,不重复求许可;没有授权的建议不能自行开始。'
- + '主人在工作台上点「跟进」时会发来「跟进「<标题>」」(其它语言如 Follow up on “<标题>”):先调用本工具按标题找到那一条,'
- + '再 continue_workbench_task——会话条目发一句承接上文、收到就能接着做的指令;PR / issue / 建议条目会在项目目录开后台任务。'
- + '找不到同名条目就问主人是哪一件,不要猜;有几条同名时列出候选让主人选。'
- + '要在项目里开全新的任务时用 start_session_task,把 working_dir 设为该项目路径。',
+ '读取已接手项目内的普通任务、项目素材和旧工作台判断。普通任务保留自己的生命周期。' +
+ '伙伴事务清单请用 list_teammate_todos / update_teammate_todo,可没有项目;不要逐个复制任务。' +
+ '会话限近期30天/30条,连外部会话最多40条;会话判断不返回ref,不能据此覆盖未知旧引用。' +
+ '旧判断有200条上限、done优先淘汰,不是新Todo历史。项目过滤仅影响此项目视图。',
inputShape: {},
handler: async () => {
const sessionId = callerSessionId();
@@ -296,10 +292,10 @@ export function registerBotWorkbenchTools(
name: 'set_workbench_task',
category: 'bots',
description:
- '维护一件已接手项目内的事务判断。按 task_id 整条替换,多件变化用 set_workbench_tasks;保留仍有效的 ref/project。get_workbench 的会话判断没有 ref,无法从 updatedAt 与当前判断一致的已确认回执找回旧 ref 时不要覆盖。写后检查结果并尝试读回;成功回执已确认保存,近期/数量过滤导致列表不可见不等于失败,不重复写。当前不支持无项目 Todo 或独立的可选任务/PR 关联。'
- + 'task_id:get_workbench 返回的会话 taskId,或你新写的 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n>(须是已接手项目的 GitHub 仓库)、idea:<slug>(小写字母数字与连字符,3–40 位)。'
- + '同一承诺沿用原 id,重复执行不重复建条目。title:当前人话标题,不超过 40 字,不用状态前缀;verdict:unfinished(约定未完成)/ idea(尚未接下的建议)/ done(有依据完成,当前界面隐藏)。无关内容不新建;记录不自动开工。'
- + 'next:当前进展与下一步,不超过 120 字,unfinished / idea 必填;done 时写完成依据,ref 放支持依据的 https 链接或项目内文件路径。没有专门完成依据字段。停止或合并仍待验收则保持 unfinished;事实未知写待核实。只写有依据的判断,不要编造。',
+ '维护一件已接手项目内的事务判断。按 task_id 整条替换,多件变化用 set_workbench_tasks;保留仍有效的 ref/project。get_workbench 的会话判断没有 ref,无法从 updatedAt 与当前判断一致的已确认回执找回旧 ref 时不要覆盖。写后检查结果并尝试读回;成功回执已确认保存,近期/数量过滤导致列表不可见不等于失败,不重复写。当前不支持无项目 Todo 或独立的可选任务/PR 关联。' +
+ 'task_id:get_workbench 返回的会话 taskId,或你新写的 pr:<owner>/<repo>#<n>、issue:<owner>/<repo>#<n>(须是已接手项目的 GitHub 仓库)、idea:<slug>(小写字母数字与连字符,3–40 位)。' +
+ '同一承诺沿用原 id,重复执行不重复建条目。title:当前人话标题,不超过 40 字,不用状态前缀;verdict:unfinished(约定未完成)/ idea(尚未接下的建议)/ done(有依据完成,当前界面隐藏)。无关内容不新建;记录不自动开工。' +
+ 'next:当前进展与下一步,不超过 120 字,unfinished / idea 必填;done 时写完成依据,ref 放支持依据的 https 链接或项目内文件路径。没有专门完成依据字段。停止或合并仍待验收则保持 unfinished;事实未知写待核实。只写有依据的判断,不要编造。',
inputShape: JUDGMENT_FIELDS,
handler: async (args) => {
const sessionId = callerSessionId();
@@ -315,8 +311,8 @@ export function registerBotWorkbenchTools(
name: 'set_workbench_tasks',
category: 'bots',
description:
- `批量写下判断(1–${WORKBENCH_BATCH_MAX} 条),字段与 set_workbench_task 相同。逐条校验,一条不合格不影响其它条;返回每条的结果。`
- + '对话承诺、任务回传、用户纠正或已授权跟进发现相关变化后才写,同一承诺沿用 id;没有变化不造条目。与单条一样保留旧引用,会话 ref 无法确认时不覆盖。检查每条结果,部分失败不代表全部成功,再尝试 get_workbench 读回;成功项可能因会话近期/数量限制不可见,不误报失败或重复写。当前只支持项目内记录。',
+ `批量写下判断(1–${WORKBENCH_BATCH_MAX} 条),字段与 set_workbench_task 相同。逐条校验,一条不合格不影响其它条;返回每条的结果。` +
+ '对话承诺、任务回传、用户纠正或已授权跟进发现相关变化后才写,同一承诺沿用 id;没有变化不造条目。与单条一样保留旧引用,会话 ref 无法确认时不覆盖。检查每条结果,部分失败不代表全部成功,再尝试 get_workbench 读回;成功项可能因会话近期/数量限制不可见,不误报失败或重复写。当前只支持项目内记录。',
inputShape: {
items: z.array(z.object(JUDGMENT_FIELDS)).min(1).max(WORKBENCH_BATCH_MAX).describe('判断列表'),
},
@@ -412,3 +408,141 @@ export function registerBotWorkbenchTools(
},
});
}
+
+const deadline = z.object({
+ kind: z.enum(['date', 'instant']),
+ date: z.string().max(10),
+ timeZone: z.string().max(100),
+ at: z.string().max(80).optional(),
+ sourceId: z.string().max(512).optional(),
+ sourceVersion: z.number().int().nonnegative().optional(),
+ quote: z.string().max(2000).optional(),
+ observedAt: z.string().max(80).optional(),
+});
+const todoPatch = z.object({
+ id: z.string().max(128).optional(),
+ expectedRevision: z.number().int().nonnegative().optional(),
+ key: z.string().min(1).max(512).optional(),
+ origin: z.enum(['assigned', 'discovered']).optional(),
+ title: z.string().min(1).max(300).optional(),
+ progress: z.string().max(4000).optional(),
+ outcome: z.string().min(1).max(4000).optional(),
+ value: z.string().max(4000).optional(),
+ next: z
+ .object({
+ label: z.string().min(1).max(100),
+ instruction: z.string().min(1).max(4000),
+ kind: z.enum(['advance', 'view', 'decide']),
+ })
+ .nullable()
+ .optional(),
+ sources: z
+ .array(
+ z.object({
+ kind: z.enum(['conversation', 'mail', 'feishu', 'github', 'community', 'task']),
+ id: z.string().min(1).max(512),
+ label: z.string().min(1).max(300),
+ ref: z.string().max(2000).optional(),
+ project: z.string().max(4096).optional(),
+ version: z.number().int().nonnegative().optional(),
+ observedAt: z.string().max(80).optional(),
+ }),
+ )
+ .max(100)
+ .optional(),
+ associations: z
+ .array(
+ z.object({
+ kind: z.enum(['task', 'pr']),
+ id: z.string().max(512),
+ label: z.string().max(300),
+ }),
+ )
+ .max(100)
+ .optional(),
+ sourceDeadline: deadline.nullable().optional(),
+ deadlineOverride: z.object({ value: deadline.nullable() }).optional(),
+ deadlineCandidate: z
+ .object({ value: deadline, reason: z.string().max(2000) })
+ .nullable()
+ .optional(),
+ suggestedDate: z.string().max(10).nullable().optional(),
+ resolvedActionRequestId: z.string().min(1).max(128).optional(),
+ operation: z
+ .enum(['complete', 'reopen', 'delete', 'mute', 'later', 'restore', 'confirm-deadline'])
+ .optional(),
+ until: z.string().max(80).optional(),
+ completion: z
+ .object({
+ summary: z.string().min(1).max(4000),
+ ref: z.string().max(2000).optional(),
+ })
+ .optional(),
+});
+function registerTodoTools(
+ registry: XdtHelperToolRegistry,
+ caller: () => string | null,
+ callback: NonNullable<BotWorkbenchCallbacks['todos']>,
+) {
+ const run = async (op: 'list' | 'update' | 'preflight' | 'ingest', input?: unknown) => {
+ const id = caller();
+ if (!id) return missingSession();
+ const result = await callback(id, op, input);
+ return result.ok ? okPayload(result) : errorPayload(result.errorCode, result.message);
+ };
+ registry.register({
+ name: 'list_teammate_todos',
+ category: 'bots',
+ description:
+ '按id/key读取同一事务(含完成/忽略记录),或分页搜索自己的清单,每页25条并返回总数。独立于项目/任务。维护优先精确读;无变化不扫描信息源。',
+ inputShape: {
+ id: z.string().max(128).optional(),
+ key: z.string().max(512).optional(),
+ query: z.string().max(300).optional(),
+ view: z.enum(['open', 'done', 'hidden']).optional(),
+ origin: z.enum(['all', 'assigned', 'discovered']).optional(),
+ offset: z.number().int().nonnegative().optional(),
+ },
+ handler: (input) => run('list', input),
+ });
+ registry.register({
+ name: 'update_teammate_todo',
+ category: 'bots',
+ description:
+ '新建或部分更新同一事务。key跨来源标识同一问题;已存在时用id+expectedRevision,冲突先读再合并,省略字段保留旧值。发现可入单但不自动授权执行/发送。完成必须携带可核验summary/ref;停止/合并未必满足outcome。删除/静音保留抑制记录,只有用户恢复可解除。无项目可用;项目型伙伴只发现职责范围。到期保留来源/时区,模糊日期用candidate,用户覆盖不被新来源改掉;稍后不修改期限。',
+ inputShape: { patch: todoPatch },
+ handler: ({ patch }) => run('update', patch satisfies TodoPatch),
+ });
+ registry.register({
+ name: 'preflight_teammate_todo_events',
+ category: 'bots',
+ description:
+ '现有已授权事件流的便宜增量预检:按职责范围、来源游标、稳定问题key及忽略/完成记录过滤,只有review事件需要取相关正文/模型判断。本工具不连接、扫描或新建定时器;无新事件不调用。',
+ inputShape: {
+ events: z
+ .array(
+ z.object({
+ source: z.string().max(512),
+ sequence: z.number().int().nonnegative(),
+ key: z.string().max(512),
+ project: z.string().max(4096).optional(),
+ }),
+ )
+ .max(100),
+ },
+ handler: ({ events }) => run('preflight', events),
+ });
+ registry.register({
+ name: 'record_teammate_todo_event',
+ category: 'bots',
+ description:
+ '原子保存一条成功处理的增量事件与Todo更新或no-action结果。source+sequence幂等,按来源顺序逐条提交,不跳过失败事件;失败不会推进游标。重复、已完成、已忽略的同一key不会重建。不同来源同一反馈沿用key/id,不能擅自绕过用户拒绝。',
+ inputShape: {
+ source: z.string().max(512),
+ sequence: z.number().int().nonnegative(),
+ patch: todoPatch.optional(),
+ skip: z.enum(['duplicate', 'suppressed', 'outside-scope', 'no-action']).optional(),
+ },
+ handler: (input) => run('ingest', input),
+ });
+}
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index 16084941b7..56c31cfba3 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -92,7 +92,8 @@
"./botTimeline": "./src/botTimeline.ts",
"./remote-desktop-viewer": "./src/remote-desktop/viewerRuntime.js",
"./remote-desktop-mobile": "./src/remote-desktop/mobileHtml.ts",
- "./remote-desktop-scripts": "./src/remote-desktop/viewerScripts.ts"
+ "./remote-desktop-scripts": "./src/remote-desktop/viewerScripts.ts",
+ "./teammate-todo": "./src/teammateTodo.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/maker-shared/src/teammateTodo.test.ts b/packages/maker-shared/src/teammateTodo.test.ts
new file mode 100644
index 0000000000..c0bf8938f9
--- /dev/null
+++ b/packages/maker-shared/src/teammateTodo.test.ts
@@ -0,0 +1,274 @@
+import { describe, expect, it } from 'vitest';
+import {
+ applyTodoPatch,
+ emptyTodoState,
+ effectiveTodoDeadline,
+ preflightTodoEvents,
+ queryTodoItems,
+ todoOverdue,
+ todoVisible,
+ validateTodoDeadline,
+ type TodoPatch,
+} from './teammateTodo';
+const now = new Date('2026-10-10T12:00:00Z');
+const patch: TodoPatch = {
+ key: 'feedback:avatar',
+ title: '修复头像丢失',
+ outcome: '升级后的旧头像仍保留',
+ origin: 'discovered',
+ sources: [{ kind: 'mail', id: 'm1', label: '反馈邮件' }],
+ next: {
+ kind: 'advance',
+ label: '准备修复',
+ instruction: '按已授权范围排查并准备修复',
+ },
+};
+describe('teammate affairs contract', () => {
+ it('works without projects and merges source evidence into the same affair', () => {
+ const s = emptyTodoState(),
+ t = applyTodoPatch(s, patch, 'one', now);
+ applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: 1,
+ sources: [{ kind: 'feishu', id: 'f1', label: '同事反馈' }],
+ associations: [{ kind: 'pr', id: '5729', label: '第一次修复' }],
+ },
+ 'unused',
+ now,
+ );
+ const latest = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: 2,
+ progress: '已合并,仍待升级验收',
+ associations: [{ kind: 'pr', id: '5730', label: '补充修复' }],
+ },
+ 'unused',
+ now,
+ );
+ expect(s.items).toHaveLength(1);
+ expect(latest.sources).toHaveLength(2);
+ expect(latest.associations).toHaveLength(2);
+ expect(latest.status).toBe('open');
+ expect(() =>
+ applyTodoPatch(s, { id: t.id, expectedRevision: 1, title: 'stale' }, 'unused', now),
+ ).toThrow('CONFLICT');
+ });
+ it('requires real completion basis and retains history on reopening', () => {
+ const s = emptyTodoState(),
+ t = applyTodoPatch(s, patch, 'one', now);
+ expect(() =>
+ applyTodoPatch(s, { id: t.id, expectedRevision: 1, operation: 'complete' }, '', now),
+ ).toThrow('COMPLETION_EVIDENCE_REQUIRED');
+ expect(() =>
+ applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: 1,
+ operation: 'complete',
+ completion: { summary: ' ' },
+ },
+ '',
+ now,
+ ),
+ ).toThrow();
+ const done = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: 1,
+ operation: 'complete',
+ completion: {
+ summary: '隔离升级验收通过',
+ ref: 'https://example.test/proof',
+ },
+ },
+ '',
+ now,
+ );
+ const reopened = applyTodoPatch(
+ s,
+ { id: t.id, expectedRevision: done.revision, operation: 'reopen' },
+ '',
+ now,
+ );
+ expect(reopened.history).toEqual(done.history);
+ expect(reopened.status).toBe('open');
+ });
+ it('preserves user date overrides and differentiates candidate / suggestion / deferral', () => {
+ const s = emptyTodoState();
+ let t = applyTodoPatch(
+ s,
+ {
+ ...patch,
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-10',
+ timeZone: 'Asia/Shanghai',
+ sourceVersion: 2,
+ quote: '10月10日前',
+ },
+ deadlineCandidate: {
+ value: {
+ kind: 'date',
+ date: '2026-10-16',
+ timeZone: 'Asia/Shanghai',
+ },
+ reason: '周五前,日期待确认',
+ },
+ suggestedDate: '2026-10-12',
+ },
+ 'one',
+ now,
+ );
+ expect(todoOverdue(t, now)).toBe(false);
+ t = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ deadlineOverride: { value: null },
+ operation: 'later',
+ until: '2026-10-11T12:00:00Z',
+ },
+ '',
+ now,
+ );
+ expect(todoVisible(t, now)).toBe(false);
+ expect(t.sourceDeadline?.date).toBe('2026-10-10');
+ t = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-09',
+ timeZone: 'Asia/Shanghai',
+ sourceVersion: 3,
+ },
+ },
+ '',
+ now,
+ );
+ expect(effectiveTodoDeadline(t)).toBeNull();
+ expect(() =>
+ applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-08',
+ timeZone: 'Asia/Shanghai',
+ sourceVersion: 1,
+ },
+ },
+ '',
+ now,
+ ),
+ ).toThrow('STALE_SOURCE');
+ expect(t.deadlineCandidate?.reason).toBeTruthy();
+ });
+ it('filters duplicate, resolved, ignored and out-of-scope events before model work', () => {
+ const s = emptyTodoState();
+ let t = applyTodoPatch(s, patch, 'one', now);
+ t = applyTodoPatch(s, { id: t.id, expectedRevision: 1, operation: 'mute' }, '', now);
+ expect(
+ preflightTodoEvents(
+ s,
+ [
+ { source: 'mail', sequence: 2, key: patch.key! },
+ { source: 'feishu', sequence: 7, key: patch.key! },
+ { source: 'issues', sequence: 1, key: 'other', project: '/private' },
+ ],
+ ['/cindy'],
+ ).map((x) => x.decision),
+ ).toEqual(['suppressed', 'suppressed', 'outside-scope']);
+ s.cursors.mail = 2;
+ expect(
+ preflightTodoEvents(s, [{ source: 'mail', sequence: 2, key: 'another' }], [])[0].decision,
+ ).toBe('duplicate');
+ expect(t.decision?.kind).toBe('muted');
+ });
+ it('rejects ambiguous or impossible exact dates and invalid zones', () => {
+ for (const date of ['2026-02-30', '9999-99-99', 'bad'])
+ expect(() => validateTodoDeadline({ kind: 'date', date, timeZone: 'UTC' })).toThrow();
+ expect(() =>
+ validateTodoDeadline({
+ kind: 'date',
+ date: '2026-10-10',
+ timeZone: 'Imaginary/City',
+ }),
+ ).toThrow('INVALID_TIME_ZONE');
+ expect(() =>
+ validateTodoDeadline({
+ kind: 'instant',
+ date: '2026-10-10',
+ timeZone: 'UTC',
+ at: '2026-10-10',
+ }),
+ ).toThrow('INVALID_DATE');
+ expect(() =>
+ validateTodoDeadline({
+ kind: 'instant',
+ date: '2026-10-10',
+ timeZone: 'Asia/Shanghai',
+ at: '2026-10-10T23:00:00Z',
+ }),
+ ).toThrow('INVALID_DATE');
+ });
+ it('all 100 affairs are reachable and searchable beyond the first page', () => {
+ const s = emptyTodoState();
+ for (let n = 0; n < 100; n++)
+ applyTodoPatch(s, { ...patch, key: 'k' + n, title: '事项 ' + n }, 'id' + n, now);
+ const ids = new Set();
+ for (let offset = 0; offset < 100; offset += 25)
+ for (const t of queryTodoItems(s.items, { offset }).items) ids.add(t.id);
+ expect(ids.size).toBe(100);
+ expect(queryTodoItems(s.items, { query: '事项 99' }).total).toBe(1);
+ expect(queryTodoItems(s.items, { offset: 100 }).offset).toBe(75);
+ });
+});
+
+it('a source label refresh retains its existing evidence and scope when optional metadata is omitted', () => {
+ const s = emptyTodoState();
+ const t = applyTodoPatch(
+ s,
+ {
+ ...patch,
+ sources: [
+ {
+ kind: 'mail',
+ id: 'm1',
+ label: '报价',
+ ref: 'https://example.test/proof',
+ project: '/cindy',
+ version: 3,
+ },
+ ],
+ },
+ 'one',
+ now,
+ );
+ const latest = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: 1,
+ sources: [{ kind: 'mail', id: 'm1', label: '新报价', version: 4 }],
+ },
+ '',
+ now,
+ );
+ expect(latest.sources[0]).toMatchObject({
+ ref: 'https://example.test/proof',
+ project: '/cindy',
+ label: '新报价',
+ });
+});
diff --git a/packages/maker-shared/src/teammateTodo.ts b/packages/maker-shared/src/teammateTodo.ts
new file mode 100644
index 0000000000..995d32e076
--- /dev/null
+++ b/packages/maker-shared/src/teammateTodo.ts
@@ -0,0 +1,509 @@
+/** Host-owned affairs, independent of Session lifecycle and project visibility. */
+export interface TodoSource {
+ kind: 'conversation' | 'mail' | 'feishu' | 'github' | 'community' | 'task';
+ id: string;
+ label: string;
+ ref?: string;
+ project?: string;
+ version?: number;
+ observedAt?: string;
+}
+export interface TodoDeadline {
+ kind: 'date' | 'instant';
+ date: string;
+ timeZone: string;
+ at?: string;
+ sourceId?: string;
+ sourceVersion?: number;
+ quote?: string;
+ observedAt?: string;
+}
+export interface TodoNext {
+ label: string;
+ instruction: string;
+ kind: 'advance' | 'view' | 'decide';
+}
+export interface TodoCompletion {
+ summary: string;
+ ref?: string;
+ at: string;
+}
+export interface TeammateTodo {
+ id: string;
+ revision: number;
+ key: string;
+ origin: 'assigned' | 'discovered';
+ title: string;
+ progress: string;
+ outcome: string;
+ value: string;
+ next: TodoNext | null;
+ sources: TodoSource[];
+ associations: Array<{ kind: 'task' | 'pr'; id: string; label: string }>;
+ status: 'open' | 'done';
+ createdAt: string;
+ updatedAt: string;
+ sourceDeadline: TodoDeadline | null;
+ deadlineOverride?: { value: TodoDeadline | null };
+ deadlineCandidate: { value: TodoDeadline; reason: string } | null;
+ suggestedDate: string | null;
+ decision: { kind: 'deleted' | 'muted' | 'later'; until?: string } | null;
+ history: TodoCompletion[];
+ action: {
+ requestId: string;
+ revision: number;
+ state: 'received' | 'accepted' | 'failed' | 'unknown';
+ error?: string;
+ } | null;
+ legacyId?: string;
+}
+export interface TodoPatch {
+ id?: string;
+ expectedRevision?: number;
+ key?: string;
+ origin?: TeammateTodo['origin'];
+ title?: string;
+ progress?: string;
+ outcome?: string;
+ value?: string;
+ next?: TodoNext | null;
+ sources?: TodoSource[];
+ associations?: TeammateTodo['associations'];
+ sourceDeadline?: TodoDeadline | null;
+ deadlineOverride?: { value: TodoDeadline | null };
+ deadlineCandidate?: TeammateTodo['deadlineCandidate'];
+ suggestedDate?: string | null;
+ operation?: 'complete' | 'reopen' | 'delete' | 'mute' | 'later' | 'restore' | 'confirm-deadline';
+ until?: string;
+ completion?: { summary: string; ref?: string };
+ resolvedActionRequestId?: string;
+}
+export interface TodoState {
+ version: 1;
+ items: TeammateTodo[];
+ cursors: Record<string, number>;
+ receipts: Record<string, string>;
+}
+export const emptyTodoState = (): TodoState => ({
+ version: 1,
+ items: [],
+ cursors: {},
+ receipts: {},
+});
+export class TodoError extends Error {
+ constructor(
+ public code: string,
+ message = code,
+ ) {
+ super(message);
+ }
+}
+const text = (s: unknown, max: number, required = false): string => {
+ if (typeof s !== 'string' || (required && !s.trim()) || s.length > max)
+ throw new TodoError('INVALID_INPUT');
+ return s.trim();
+};
+const iso = (s: unknown) => {
+ if (
+ typeof s !== 'string' ||
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(s) ||
+ !Number.isFinite(Date.parse(s))
+ )
+ throw new TodoError('INVALID_DATE');
+ return s;
+};
+export function validateTodoDeadline(d: TodoDeadline | null): void {
+ if (d === null) return;
+ if (
+ !d ||
+ !['date', 'instant'].includes(d.kind) ||
+ !/^\d{4}-\d{2}-\d{2}$/.test(d.date) ||
+ !Number.isFinite(Date.parse(d.date)) ||
+ new Date(d.date).toISOString().slice(0, 10) !== d.date
+ )
+ throw new TodoError('INVALID_DATE');
+ if (typeof d.timeZone !== 'string' || !d.timeZone.trim() || d.timeZone.length > 100)
+ throw new TodoError('INVALID_TIME_ZONE');
+ try {
+ new Intl.DateTimeFormat('en', { timeZone: d.timeZone }).format();
+ } catch {
+ throw new TodoError('INVALID_TIME_ZONE');
+ }
+ if (d.kind === 'instant') {
+ iso(d.at);
+ if (todoLocalDate(new Date(d.at!), d.timeZone) !== d.date) throw new TodoError('INVALID_DATE');
+ } else if (d.at !== undefined) throw new TodoError('INVALID_DATE');
+ if (
+ d.sourceVersion !== undefined &&
+ (!Number.isSafeInteger(d.sourceVersion) || d.sourceVersion < 0)
+ )
+ throw new TodoError('INVALID_INPUT');
+ if (d.observedAt !== undefined) iso(d.observedAt);
+ if (d.sourceId !== undefined) text(d.sourceId, 512, true);
+ if (d.quote !== undefined) text(d.quote, 2000);
+}
+export function todoLocalDate(now: Date, zone: string): string {
+ const parts = new Intl.DateTimeFormat('en', {
+ timeZone: zone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).formatToParts(now);
+ return ['year', 'month', 'day'].map((k) => parts.find((p) => p.type === k)!.value).join('-');
+}
+export function effectiveTodoDeadline(t: TeammateTodo): TodoDeadline | null {
+ return t.deadlineOverride ? t.deadlineOverride.value : t.sourceDeadline;
+}
+export function todoOverdue(t: TeammateTodo, now = new Date()): boolean {
+ const d = effectiveTodoDeadline(t);
+ return (
+ !!d &&
+ (d.kind === 'instant'
+ ? Date.parse(d.at!) < now.getTime()
+ : d.date < todoLocalDate(now, d.timeZone))
+ );
+}
+export function todoDateLabel(t: TeammateTodo, locale: string, now = new Date()): string {
+ const d = effectiveTodoDeadline(t);
+ const dateString = d?.date ?? t.deadlineCandidate?.value.date ?? t.suggestedDate;
+ if (!dateString) return '';
+ const date = new Intl.DateTimeFormat(locale, {
+ timeZone: 'UTC',
+ month: 'numeric',
+ day: 'numeric',
+ }).format(new Date(dateString + 'T12:00:00Z'));
+ const day =
+ d && d.date === todoLocalDate(now, d.timeZone)
+ ? new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(0, 'day')
+ : date;
+ return d?.kind === 'instant'
+ ? day +
+ ' ' +
+ new Intl.DateTimeFormat(locale, {
+ timeZone: d.timeZone,
+ hour: '2-digit',
+ minute: '2-digit',
+ }).format(new Date(d.at!))
+ : day;
+}
+export function todoVisible(t: TeammateTodo, now = new Date()): boolean {
+ return (
+ !t.decision ||
+ (t.decision.kind === 'later' &&
+ !!t.decision.until &&
+ Date.parse(t.decision.until) <= now.getTime())
+ );
+}
+/** Deterministic host preflight: repeat events and decisions never wake a model. */
+export function preflightTodoEvents(
+ state: TodoState,
+ events: Array<{
+ source: string;
+ sequence: number;
+ key: string;
+ project?: string;
+ }>,
+ projects: string[],
+) {
+ if (!Array.isArray(events) || events.length > 100) throw new TodoError('INVALID_EVENT');
+ for (const e of events)
+ if (
+ !e ||
+ !Number.isSafeInteger(e.sequence) ||
+ e.sequence < 0 ||
+ typeof e.key !== 'string' ||
+ !e.key ||
+ e.key.length > 512 ||
+ typeof e.source !== 'string' ||
+ !e.source ||
+ e.source.length > 512
+ )
+ throw new TodoError('INVALID_EVENT');
+ return events.map((e) => ({
+ ...e,
+ decision:
+ e.project && !projects.includes(e.project)
+ ? 'outside-scope'
+ : e.sequence <= (Object.hasOwn(state.cursors, e.source) ? state.cursors[e.source] : -1) ||
+ Object.hasOwn(state.receipts, e.source + ':' + e.sequence)
+ ? 'duplicate'
+ : state.items.some((t) => t.key === e.key && !todoVisible(t))
+ ? 'suppressed'
+ : state.items.some((t) => t.key === e.key && t.status === 'done')
+ ? 'resolved'
+ : ('review' as const),
+ }));
+}
+export function applyTodoPatch(
+ state: TodoState,
+ patch: TodoPatch,
+ id: string,
+ now = new Date(),
+): TeammateTodo {
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch))
+ throw new TodoError('INVALID_INPUT');
+ const old = patch.id
+ ? state.items.find((t) => t.id === patch.id)
+ : state.items.find((t) => t.key === patch.key);
+ if (patch.id && !old) throw new TodoError('NOT_FOUND');
+ if (old && patch.expectedRevision !== old.revision) throw new TodoError('CONFLICT');
+ if (!old && patch.expectedRevision !== undefined) throw new TodoError('CONFLICT');
+ if (!old && state.items.length >= 10000) throw new TodoError('CAPACITY_REACHED'); // reject, never evict history
+ const t: TeammateTodo = old
+ ? structuredClone(old)
+ : {
+ id,
+ revision: 0,
+ key: text(patch.key, 512, true),
+ origin: 'assigned',
+ title: '',
+ progress: '',
+ outcome: '',
+ value: '',
+ next: null,
+ sources: [],
+ associations: [],
+ status: 'open',
+ createdAt: now.toISOString(),
+ updatedAt: '',
+ sourceDeadline: null,
+ deadlineCandidate: null,
+ suggestedDate: null,
+ decision: null,
+ history: [],
+ action: null,
+ };
+ for (const field of ['title', 'progress', 'outcome', 'value'] as const)
+ if (patch[field] !== undefined)
+ t[field] = text(
+ patch[field],
+ field === 'title' ? 300 : 4000,
+ field === 'title' || field === 'outcome',
+ );
+ if (!t.title || !t.outcome) throw new TodoError('INVALID_INPUT');
+ if (patch.origin !== undefined) {
+ if (!['assigned', 'discovered'].includes(patch.origin)) throw new TodoError('INVALID_INPUT');
+ t.origin = patch.origin;
+ }
+ if (patch.next !== undefined) {
+ if (patch.next !== null) {
+ text(patch.next.label, 100, true);
+ text(patch.next.instruction, 4000, true);
+ if (!['advance', 'view', 'decide'].includes(patch.next.kind))
+ throw new TodoError('INVALID_INPUT');
+ }
+ if (JSON.stringify(t.next) !== JSON.stringify(patch.next)) t.action = null;
+ t.next = patch.next
+ ? {
+ label: text(patch.next.label, 100, true),
+ instruction: text(patch.next.instruction, 4000, true),
+ kind: patch.next.kind,
+ }
+ : null;
+ }
+ if (patch.sources !== undefined) {
+ if (!Array.isArray(patch.sources) || patch.sources.length > 100)
+ throw new TodoError('INVALID_INPUT');
+ const merged = new Map(t.sources.map((s) => [s.kind + ':' + s.id, s]));
+ for (const s of patch.sources) {
+ if (!s || !['conversation', 'mail', 'feishu', 'github', 'community', 'task'].includes(s.kind))
+ throw new TodoError('INVALID_INPUT');
+ text(s.id, 512, true);
+ text(s.label, 300, true);
+ if (s.ref && (s.ref.length > 2000 || !/^https:\/\/[^\s]+$/.test(s.ref)))
+ throw new TodoError('INVALID_REFERENCE');
+ if (s.version !== undefined && (!Number.isSafeInteger(s.version) || s.version < 0))
+ throw new TodoError('INVALID_INPUT');
+ if (s.project !== undefined) text(s.project, 4096, true);
+ if (s.observedAt !== undefined) iso(s.observedAt);
+ const previous = merged.get(s.kind + ':' + s.id);
+ if (!previous || (s.version ?? 0) >= (previous.version ?? 0))
+ merged.set(s.kind + ':' + s.id, {
+ ...previous,
+ kind: s.kind,
+ id: s.id,
+ label: s.label,
+ ...(s.ref ? { ref: s.ref } : {}),
+ ...(s.project ? { project: s.project } : {}),
+ ...(s.version !== undefined ? { version: s.version } : {}),
+ ...(s.observedAt ? { observedAt: s.observedAt } : {}),
+ });
+ }
+ t.sources = [...merged.values()];
+ }
+ if (patch.associations !== undefined) {
+ if (!Array.isArray(patch.associations) || patch.associations.length > 100)
+ throw new TodoError('INVALID_INPUT');
+ const merged = new Map(t.associations.map((a) => [a.kind + ':' + a.id, a]));
+ for (const a of patch.associations) {
+ if (!['task', 'pr'].includes(a.kind)) throw new TodoError('INVALID_INPUT');
+ text(a.id, 512, true);
+ text(a.label, 300, true);
+ merged.set(a.kind + ':' + a.id, {
+ kind: a.kind,
+ id: a.id,
+ label: a.label,
+ });
+ }
+ t.associations = [...merged.values()];
+ }
+ if (patch.sourceDeadline !== undefined) {
+ validateTodoDeadline(patch.sourceDeadline);
+ if (
+ t.sourceDeadline &&
+ patch.sourceDeadline &&
+ (patch.sourceDeadline.sourceVersion ?? 0) < (t.sourceDeadline.sourceVersion ?? 0)
+ )
+ throw new TodoError('STALE_SOURCE');
+ t.sourceDeadline = patch.sourceDeadline;
+ }
+ if (patch.deadlineOverride !== undefined) {
+ if (!patch.deadlineOverride || typeof patch.deadlineOverride !== 'object')
+ throw new TodoError('INVALID_INPUT');
+ validateTodoDeadline(patch.deadlineOverride.value);
+ t.deadlineOverride = { value: patch.deadlineOverride.value };
+ }
+ if (patch.deadlineCandidate !== undefined) {
+ if (patch.deadlineCandidate) {
+ validateTodoDeadline(patch.deadlineCandidate.value);
+ text(patch.deadlineCandidate.reason, 2000, true);
+ }
+ t.deadlineCandidate = patch.deadlineCandidate;
+ }
+ if (patch.suggestedDate !== undefined) {
+ if (patch.suggestedDate !== null && typeof patch.suggestedDate !== 'string')
+ throw new TodoError('INVALID_DATE');
+ if (patch.suggestedDate)
+ validateTodoDeadline({
+ kind: 'date',
+ date: patch.suggestedDate,
+ timeZone: 'UTC',
+ });
+ t.suggestedDate = patch.suggestedDate;
+ }
+ if (patch.resolvedActionRequestId !== undefined) {
+ if (!old?.action || old.action.requestId !== patch.resolvedActionRequestId)
+ throw new TodoError('STALE_RECEIPT');
+ if (!patch.progress?.trim()) throw new TodoError('RECEIPT_EVIDENCE_REQUIRED');
+ t.action = null;
+ }
+ switch (patch.operation) {
+ case 'complete': {
+ if (!patch.completion) throw new TodoError('COMPLETION_EVIDENCE_REQUIRED');
+ text(patch.completion.summary, 4000, true);
+ if (patch.completion.ref) text(patch.completion.ref, 2000, true);
+ t.history.push({ ...patch.completion, at: now.toISOString() });
+ t.status = 'done';
+ t.decision = null;
+ t.action = null;
+ break;
+ }
+ case 'reopen':
+ t.status = 'open';
+ t.decision = null;
+ t.action = null;
+ break;
+ case 'delete':
+ case 'mute':
+ t.decision = { kind: patch.operation === 'delete' ? 'deleted' : 'muted' };
+ break;
+ case 'later':
+ if (!patch.until || Date.parse(iso(patch.until)) <= now.getTime())
+ throw new TodoError('INVALID_DATE');
+ t.decision = { kind: 'later', until: patch.until };
+ break;
+ case 'restore':
+ t.decision = null;
+ break;
+ case 'confirm-deadline':
+ if (!t.deadlineCandidate) throw new TodoError('INVALID_DATE');
+ t.deadlineOverride = { value: t.deadlineCandidate.value };
+ t.deadlineCandidate = null;
+ break;
+ case undefined:
+ break;
+ default:
+ throw new TodoError('INVALID_INPUT');
+ }
+ t.revision++;
+ t.updatedAt = now.toISOString();
+ const at = state.items.findIndex((x) => x.id === t.id);
+ if (at < 0) state.items.push(t);
+ else state.items[at] = t;
+ return t;
+}
+
+export interface TodoListQuery {
+ query?: string;
+ view?: 'open' | 'done' | 'hidden';
+ origin?: 'all' | 'assigned' | 'discovered';
+ order?: 'due' | 'created';
+ offset?: number;
+ limit?: number;
+}
+export function queryTodoItems(items: TeammateTodo[], q: TodoListQuery = {}, now = new Date()) {
+ if (
+ !q ||
+ typeof q !== 'object' ||
+ Array.isArray(q) ||
+ (q.query !== undefined && typeof q.query !== 'string') ||
+ (q.view !== undefined && !['open', 'done', 'hidden'].includes(q.view)) ||
+ (q.origin !== undefined && !['all', 'assigned', 'discovered'].includes(q.origin)) ||
+ (q.order !== undefined && !['due', 'created'].includes(q.order))
+ )
+ throw new TodoError('INVALID_INPUT');
+ const search = (q.query ?? '').trim().toLocaleLowerCase();
+ if (search.length > 300) throw new TodoError('INVALID_INPUT');
+ const filtered = items
+ .filter(
+ (t) =>
+ (q.view === 'done'
+ ? t.status === 'done' && todoVisible(t, now)
+ : q.view === 'hidden'
+ ? !todoVisible(t, now)
+ : t.status === 'open' && todoVisible(t, now)) &&
+ (!q.origin || q.origin === 'all' || t.origin === q.origin) &&
+ (!search ||
+ [t.title, t.progress, ...t.sources.map((s) => s.label)]
+ .join(' ')
+ .toLocaleLowerCase()
+ .includes(search)),
+ )
+ .sort(
+ (a, b) =>
+ (q.order !== 'created'
+ ? (effectiveTodoDeadline(a)?.date ?? '9999').localeCompare(
+ effectiveTodoDeadline(b)?.date ?? '9999',
+ )
+ : 0) ||
+ a.createdAt.localeCompare(b.createdAt) ||
+ a.id.localeCompare(b.id),
+ );
+ const requestedOffset = Number.isSafeInteger(q.offset) && q.offset! >= 0 ? q.offset! : 0;
+ const limit = Math.min(25, Math.max(1, Number.isSafeInteger(q.limit) ? q.limit! : 25));
+ const offset = Math.min(
+ requestedOffset,
+ Math.max(0, Math.ceil(filtered.length / limit) - 1) * limit,
+ );
+ return {
+ items: filtered.slice(offset, offset + limit),
+ total: filtered.length,
+ offset,
+ limit,
+ completedTotal: items.filter((t) => t.status === 'done' && todoVisible(t, now)).length,
+ };
+}
+
+/** Public transcript copy; the model-only delivery carries the stable affair id separately. */
+export function todoActionText(title: string, step: string, locale = 'en'): string {
+ const prefix = locale.startsWith('zh-TW')
+ ? '繼續'
+ : locale.startsWith('zh')
+ ? '继续'
+ : locale.startsWith('ja')
+ ? '続ける'
+ : locale.startsWith('ko')
+ ? '계속'
+ : 'Continue';
+ return `${prefix} “${title}”: ${step}`;
+}