Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(bots): validate Todo optionals and refresh deferred items

zqchrisa7eb21318b24
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts
index 7f69473c60..19d7668b08 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteResourceTodos.test.ts
@@ -158,3 +158,16 @@ it('projects host-only paths and metadata out of both reads and update responses
expect((await access.list()).items[0].sources[0].project).toBe('/host/private/project');
expect((await access.list()).items[0].next.instruction).toBe('Read /host/private/project');
});
+
+it('projects the next deferral expiry even when the deferred item is absent from the open page', async () => {
+ const access = await env.access();
+ await access.patch({ key: 'visible', title: '可见事务', outcome: '核对完成' });
+ const later = await access.patch({ key: 'later', title: '稍后事务', outcome: '核对完成' });
+ const until = new Date(Date.now() + 60_000).toISOString();
+ await access.patch({ id: later.id, expectedRevision: later.revision, operation: 'later', until });
+ const resource = await remoteResourceRegistry.get(context, { client, ref });
+ const page = resource.blocks?.[0].data as { items: Array<{ id: string }>; nextDeferredAt: string };
+ expect(page.items).toHaveLength(1);
+ expect(page.items[0].id).not.toBe(later.id);
+ expect(page.nextDeferredAt).toBe(until);
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
index 7b2f15494f..d98b31fe0a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
@@ -273,6 +273,20 @@ it('rejects valid JSON with corrupt or overlong text without rewriting the file'
const t = await s.patch(p);
const clean = await s.read();
for (const fields of [
+ { deadlineCandidate: false },
+ { deadlineOverride: false },
+ { suggestedDate: {} },
+ { suggestedDate: 0 },
+ { suggestedDate: '2026-02-30' },
+ { suggestedDate: 'x'.repeat(11) },
+ { suggestedDate: 'not-a-date' },
+ { history: [{ summary: '依据', at: '2026-10-10T00:00:00Z', ref: {} }] },
+ { history: [{ summary: '依据', at: '2026-10-10T00:00:00Z', ref: 'x'.repeat(2001) }] },
+ { sources: [{ ...p.sources[0], project: {} }] },
+ { sources: [{ ...p.sources[0], observedAt: 0 }] },
+ { associations: [{ kind: 'task', id: 't', label: {} }] },
+ { decision: { kind: 'deleted', until: {} } },
+ { next: { label: 'x'.repeat(101), instruction: '继续', kind: 'advance' } },
{ title: {} },
{ outcome: [] },
{ title: 'x'.repeat(301) },
@@ -312,3 +326,28 @@ it('rejects valid JSON with corrupt or overlong text without rewriting the file'
expect(await readFile(file, 'utf8')).toBe(content);
}
});
+
+it('preserves valid suggested dates and local legacy evidence while rejecting invalid optional write fields', async () => {
+ const { file } = await fixture();
+ const store = createBotTodoStore(file, async () => ({}));
+ const t = await store.patch({ ...p, suggestedDate: '2026-10-13' });
+ await store.patch({
+ id: t.id,
+ expectedRevision: t.revision,
+ operation: 'complete',
+ completion: { summary: '已核对文件', ref: '/cindy/notes.md' },
+ });
+ const saved = (await store.read()).items[0];
+ expect(saved.suggestedDate).toBe('2026-10-13');
+ expect(saved.history[0].ref).toBe('/cindy/notes.md');
+ for (const patch of [
+ { deadlineCandidate: false },
+ { suggestedDate: {} },
+ { completion: { summary: '依据', ref: {} }, operation: 'complete' },
+ { sources: [{ ...p.sources[0], ref: false }] },
+ ])
+ await expect(
+ store.patch({ ...patch, id: saved.id, expectedRevision: saved.revision } as any),
+ ).rejects.toThrow();
+ expect((await store.read()).items[0]).toEqual(saved);
+});
diff --git a/apps/desktop/src/main/maker-ipc/botTodoStore.ts b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
index 7e52726684..52880e89da 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
@@ -17,6 +17,10 @@ import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
import type { WorkbenchTaskJudgment } from '../../shared/botWorkbench.js';
import { parseWorkbenchTaskId } from '../../shared/botWorkbench.js';
+function validText(value: unknown, max: number, required = false): boolean {
+ return typeof value === 'string' && value.length <= max && (!required || !!value.trim());
+}
+
function validTimestamp(value: unknown): boolean {
try {
validateTodoTimestamp(value);
@@ -119,6 +123,8 @@ export function createBotTodoStore(
try {
const raw = JSON.parse(await fs.readFile(file, 'utf8')) as TodoState;
if (
+ !raw ||
+ typeof raw !== 'object' ||
raw.version !== 1 ||
!Array.isArray(raw.items) ||
!raw.cursors ||
@@ -156,34 +162,45 @@ export function createBotTodoStore(
t.sources.some(
(s) =>
!s ||
- typeof s.id !== 'string' ||
- !s.id ||
- typeof s.label !== 'string' ||
+ !validText(s.id, 512, true) ||
+ !validText(s.label, 300, true) ||
!['conversation', 'mail', 'feishu', 'github', 'community', 'task'].includes(s.kind) ||
- (s.ref !== undefined && (typeof s.ref !== 'string' || !/^https:\/\//.test(s.ref))),
+ (s.ref !== undefined &&
+ (!validText(s.ref, 2000) || !/^https:\/\/[^\s]+$/.test(s.ref))) ||
+ (s.project !== undefined && !validText(s.project, 4096, true)) ||
+ (s.version !== undefined && (!Number.isSafeInteger(s.version) || s.version < 0)) ||
+ (s.observedAt !== undefined && !validTimestamp(s.observedAt)),
) ||
t.associations.some(
(a) =>
!a ||
!['task', 'pr'].includes(a.kind) ||
- typeof a.id !== 'string' ||
- typeof a.label !== 'string',
+ !validText(a.id, 512, true) ||
+ !validText(a.label, 300, true),
) ||
t.history.some(
- (h) => !h || typeof h.summary !== 'string' || !h.summary || !validTimestamp(h.at),
+ (h) =>
+ !h ||
+ !validText(h.summary, 4000, true) ||
+ !validTimestamp(h.at) ||
+ (h.ref !== undefined && !validText(h.ref, 2000)),
) ||
(t.next !== null &&
(!t.next ||
- typeof t.next.label !== 'string' ||
- typeof t.next.instruction !== 'string' ||
+ !validText(t.next.label, 100, true) ||
+ !validText(t.next.instruction, 4000, true) ||
!['advance', 'view', 'decide'].includes(t.next.kind))) ||
(t.decision !== null &&
(!t.decision ||
!['deleted', 'muted', 'later'].includes(t.decision.kind) ||
- (t.decision.kind === 'later' && !validTimestamp(t.decision.until)))) ||
+ (t.decision.until !== undefined && !validTimestamp(t.decision.until)) ||
+ (t.decision.kind === 'later' && !t.decision.until))) ||
(t.action !== null &&
(!t.action ||
- typeof t.action.requestId !== 'string' ||
+ !validText(t.action.requestId, 80, true) ||
+ !Number.isSafeInteger(t.action.revision) ||
+ t.action.revision < 1 ||
+ (t.action.error !== undefined && !validText(t.action.error, 1000)) ||
!['received', 'accepted', 'failed', 'unknown'].includes(t.action.state)))
)
throw new TodoError('CORRUPT_STORE');
@@ -213,8 +230,27 @@ export function createBotTodoStore(
throw new TodoError('CORRUPT_STORE');
try {
validateTodoDeadline(t.sourceDeadline);
- if (t.deadlineOverride) validateTodoDeadline(t.deadlineOverride.value);
- if (t.deadlineCandidate) {
+ if (t.suggestedDate !== null) {
+ if (!validText(t.suggestedDate, 10)) throw new TodoError('CORRUPT_STORE');
+ if (t.suggestedDate)
+ validateTodoDeadline({ kind: 'date', date: t.suggestedDate, timeZone: 'UTC' });
+ }
+ if (t.deadlineOverride !== undefined) {
+ if (
+ !t.deadlineOverride ||
+ typeof t.deadlineOverride !== 'object' ||
+ Array.isArray(t.deadlineOverride)
+ )
+ throw new TodoError('CORRUPT_STORE');
+ validateTodoDeadline(t.deadlineOverride.value);
+ }
+ if (t.deadlineCandidate !== null) {
+ if (
+ !t.deadlineCandidate ||
+ typeof t.deadlineCandidate !== 'object' ||
+ Array.isArray(t.deadlineCandidate)
+ )
+ throw new TodoError('CORRUPT_STORE');
validateTodoDeadline(t.deadlineCandidate.value);
if (
typeof t.deadlineCandidate.reason !== 'string' ||
diff --git a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
index 48baf866ef..b2fe6d1fb7 100644
--- a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
@@ -16,6 +16,8 @@ import {
import {
effectiveTodoDeadline,
createTodoDueComparator,
+ nextTodoDeferralAt,
+ scheduleTodoDeferralRefresh,
todoDateLabel,
todoOverdue,
todoLocalDate,
@@ -132,6 +134,22 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
unsub?.();
};
}, [botId, refresh]);
+ const nextDeferredAt = nextTodoDeferralAt(items);
+ useEffect(() => {
+ if (!nextDeferredAt) return;
+ return scheduleTodoDeferralRefresh(nextDeferredAt, () => void refresh());
+ }, [nextDeferredAt, refresh]);
+ useEffect(() => {
+ const foreground = () => {
+ if (document.visibilityState === 'visible') void refresh();
+ };
+ document.addEventListener('visibilitychange', foreground);
+ window.addEventListener('focus', foreground);
+ return () => {
+ document.removeEventListener('visibilitychange', foreground);
+ window.removeEventListener('focus', foreground);
+ };
+ }, [refresh]);
const selected = items.find((x) => x.id === detail);
const matches = (x: TeammateTodo) =>
(origin === 'all' || x.origin === origin) &&
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index 1dcbc9f40b..0171f7b609 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -73,6 +73,7 @@ import {
countUnjudgedCandidates,
groupWorkbenchTiles,
workbenchGroupHasFollowUp,
+ workbenchItemNeedsLocalReference,
tierWorkbenchProjectOptions,
type ExternalSessionCandidate,
type WorkbenchPathHints,
@@ -558,7 +559,10 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s
{/* 还没接手项目时,伙伴已有的自动化(例行任务、导入来的自动化)照常列在下面。 */}
{!picking || routineTiles.length > 0 ? (
<TaskGroups
- tiles={picking ? routineTiles : tiles.filter(tile => tile.type !== 'session' && tile.type !== 'item')}
+ tiles={picking ? routineTiles : tiles.filter(tile =>
+ tile.type !== 'session' &&
+ (tile.type !== 'item' || workbenchItemNeedsLocalReference(tile, projectDirs, caseInsensitive))
+ )}
now={now}
language={i18n.language}
showEmpty={false}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
index 8b5f54096e..99f1a17792 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchProjection.test.ts
@@ -12,6 +12,7 @@ import {
tierWorkbenchProjectOptions,
workbenchGroupHasFollowUp,
workbenchTileGroup,
+ workbenchItemNeedsLocalReference,
type WorkbenchProjectOption,
type WorkbenchDelegationInput,
} from '../botWorkbenchProjection';
@@ -570,3 +571,40 @@ describe('project picker filtering and tiers', () => {
expect(cindy).toMatchObject({ name: 'cindy', isGitRepo: true });
});
});
+
+it('retains an entrusted legacy local reference entrance until equivalent migration', () => {
+ const tiles = buildWorkbenchTiles({
+ ...base,
+ projectDirs: [CINDY],
+ sessions: [],
+ judgments: {
+ 'idea:local': {
+ project: CINDY,
+ title: '本地方案',
+ next: '查看文件',
+ verdict: 'idea',
+ ref: CINDY + '/notes.md',
+ updatedAt: new Date(base.now).toISOString(),
+ },
+ 'idea:web': {
+ project: CINDY,
+ title: '网上方案',
+ next: '查看',
+ verdict: 'idea',
+ ref: 'https://example.test/notes',
+ updatedAt: new Date(base.now).toISOString(),
+ },
+ 'idea:outside': {
+ project: CINDY,
+ title: '外部路径',
+ next: '查看',
+ verdict: 'idea',
+ ref: '/private/notes.md',
+ updatedAt: new Date(base.now).toISOString(),
+ },
+ },
+ });
+ const kept = tiles.filter((tile) => workbenchItemNeedsLocalReference(tile, [CINDY], false));
+ expect(kept.map((tile) => tile.id)).toEqual(['idea:local']);
+ expect(workbenchItemNeedsLocalReference(kept[0], [], false)).toBe(false);
+});
diff --git a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
index 4259af3436..e604f16ca6 100644
--- a/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
+++ b/apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts
@@ -27,6 +27,7 @@ import {
isWorkbenchTaskSource,
parseWorkbenchTaskId,
workbenchProjectKey,
+ validateWorkbenchRef,
type WorkbenchDelegationStatus,
type WorkbenchTaskJudgment,
type WorkbenchTaskOrigin,
@@ -728,3 +729,15 @@ export function tierWorkbenchProjectOptions(
const max = input.maxPrimary ?? WORKBENCH_PRIMARY_PROJECTS;
return { primary: primary.slice(0, max), folded: [...primary.slice(max), ...folded].sort(byRecency) };
}
+
+/** Retain the existing safe local-file entrance until its Todo source has an equivalent opener. */
+export function workbenchItemNeedsLocalReference(
+ tile: WorkbenchTile,
+ projectDirs: readonly string[],
+ caseInsensitive: boolean,
+): boolean {
+ return (
+ tile.type === 'item' && !!tile.ref && !/^https:\/\//i.test(tile.ref) &&
+ validateWorkbenchRef(tile.ref, projectDirs, caseInsensitive).ok
+ );
+}
diff --git a/apps/mobile/src/__tests__/CompanionTodos.test.tsx b/apps/mobile/src/__tests__/CompanionTodos.test.tsx
index 16122826a5..dfa09daf8c 100644
--- a/apps/mobile/src/__tests__/CompanionTodos.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionTodos.test.tsx
@@ -2,7 +2,7 @@
import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { applyTodoPatch, emptyTodoState } from '@cindy/maker-shared/teammate-todo';
+import { applyTodoPatch, emptyTodoState, queryTodoItems } from '@cindy/maker-shared/teammate-todo';
const h = vi.hoisted(() => ({
sheet: {} as any,
@@ -12,12 +12,16 @@ const h = vi.hoisted(() => ({
openLink: vi.fn(async () => {}),
onChanged: vi.fn(() => () => {}),
close: vi.fn(),
+ appState: new Set<(state: string) => void>(),
}));
vi.mock('react-native', () => ({
View: ({ children }: any) => createElement('div', null, children),
ScrollView: ({ children }: any) => createElement('div', null, children),
ActivityIndicator: () => null,
Linking: { openURL: vi.fn() },
+ AppState: { addEventListener: (_: string, fn: (state: string) => void) => {
+ h.appState.add(fn); return { remove: () => h.appState.delete(fn) };
+ } },
Pressable: ({ children, onPress, disabled, accessibilityLabel }: any) =>
createElement(
'button',
@@ -142,7 +146,7 @@ beforeEach(() => {
host = document.createElement('div');
root = createRoot(host);
});
-afterEach(() => act(() => root.unmount()));
+afterEach(() => { act(() => root.unmount()); vi.useRealTimers(); });
it('releases dismiss and button busy state on disconnect without replaying an in-flight action', async () => {
let oldResult!: (result: unknown) => void, newResult!: (result: unknown) => void;
@@ -210,3 +214,64 @@ it('does not send a stale operation whose link opens only after disconnect', asy
await render(true);
expect(row().disabled).toBe(false);
});
+
+it.each(['open', 'hidden'] as const)(
+ 'reloads %s at the nearest deferral expiry and cancels the timer when closed',
+ async (view) => {
+ vi.useFakeTimers();
+ const start = new Date('2026-10-10T12:00:00Z');
+ vi.setSystemTime(start);
+ const deferred = {
+ ...todo,
+ decision: { kind: 'later' as const, until: '2026-10-10T12:02:00Z' },
+ };
+ h.get.mockImplementation(async (...args) => ({
+ blocks: [
+ {
+ primitive: 'teammate-todos',
+ data: queryTodoItems([deferred], JSON.parse(args[5]), new Date()),
+ },
+ ],
+ }));
+ await act(async () => root.render(<CompanionTodos {...props} />));
+ await act(async () => vi.advanceTimersByTimeAsync(1));
+ if (view === 'hidden') {
+ await act(async () => button('hidden').click());
+ await act(async () => vi.advanceTimersByTimeAsync(1));
+ }
+ expect(!!host.querySelector('[data-testid="todo-one"]')).toBe(view === 'hidden');
+ const calls = h.get.mock.calls.length;
+ await act(async () => vi.advanceTimersByTimeAsync(120_000));
+ expect(h.get.mock.calls.length).toBe(calls + 1);
+ expect(!!host.querySelector('[data-testid="todo-one"]')).toBe(view === 'open');
+ expect(h.action).not.toHaveBeenCalled();
+ await act(async () => root.render(<CompanionTodos {...props} visible={false} />));
+ expect(h.appState.size).toBe(0);
+ const closedCalls = h.get.mock.calls.length;
+ await act(async () => vi.advanceTimersByTimeAsync(120_000));
+ expect(h.get.mock.calls.length).toBe(closedCalls);
+ },
+);
+
+it('rechecks expired deferrals on foreground without an action or a repeating scan', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-10T12:00:00Z'));
+ const deferred = { ...todo, decision: { kind: 'later' as const, until: '2026-10-10T12:02:00Z' } };
+ h.get.mockImplementation(async (...args) => ({
+ blocks: [
+ {
+ primitive: 'teammate-todos',
+ data: queryTodoItems([deferred], JSON.parse(args[5]), new Date()),
+ },
+ ],
+ }));
+ await act(async () => root.render(<CompanionTodos {...props} />));
+ await act(async () => vi.advanceTimersByTimeAsync(1));
+ expect(host.querySelector('[data-testid="todo-one"]')).toBeNull();
+ const calls = h.get.mock.calls.length;
+ vi.setSystemTime(new Date('2026-10-10T12:05:00Z'));
+ await act(async () => h.appState.forEach((fn) => fn('active')));
+ expect(h.get.mock.calls.length).toBe(calls + 1);
+ expect(row()).toBeDefined();
+ expect(h.action).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/session/CompanionTodos.tsx b/apps/mobile/src/session/CompanionTodos.tsx
index 62dbb947a5..47a37f4dfd 100644
--- a/apps/mobile/src/session/CompanionTodos.tsx
+++ b/apps/mobile/src/session/CompanionTodos.tsx
@@ -2,7 +2,15 @@ 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 {
+ ActivityIndicator,
+ AppState,
+ 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';
@@ -24,6 +32,7 @@ import {
import { CompanionSheet } from './CompanionSheet';
import {
effectiveTodoDeadline,
+ scheduleTodoDeferralRefresh,
todoDateLabel,
todoOverdue,
todoLocalDate,
@@ -44,6 +53,7 @@ interface Page {
items: TeammateTodo[];
total: number;
completedTotal: number;
+ nextDeferredAt?: string | null;
offset: number;
limit: number;
}
@@ -163,6 +173,18 @@ function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId,
epoch.current++;
};
}, [reload]);
+ useEffect(() => {
+ if (!visible || !online || !page.nextDeferredAt) return;
+ // A mounted-list visibility refresh, never a background reminder or action.
+ return scheduleTodoDeferralRefresh(page.nextDeferredAt, () => void reload());
+ }, [visible, online, page.nextDeferredAt, reload]);
+ useEffect(() => {
+ if (!visible || !online) return;
+ const subscription = AppState.addEventListener('change', (state) => {
+ if (state === 'active') void reload();
+ });
+ return () => subscription.remove();
+ }, [visible, online, reload]);
useEffect(
() => () => {
mounted.current = false;
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 3d2589d72d..48e38339cf 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -463,13 +463,13 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
实现使用伙伴目录下独立的 `todos.v1.json`,带稳定 id/key、乐观修订号与跨进程原子写入。旧工作台文件原样保留,旧 PR/issue/idea 条目按稳定 ID 兼容读取,新格式已保存后旧工具的更新仍会在读取时合并;保留用户期限覆盖、忽略决定和来源链接,旧描述更新不会撤销用户重新打开。普通 Session 判断继续属于任务元数据。新存储不静默淘汰完成历史;超容量明确拒绝。损坏文件失败关闭,不能用空列表覆盖。
-`list_teammate_todos`、`update_teammate_todo` 是与任务调用并列的伙伴公共能力,调用者由本机在用伙伴主任务反查。更新是部分合并,旧来源/引用默认保留;已有记录必须带修订号,冲突重新读取。完成必须记录依据,重开保留历史。到期支持日期/确切时刻及来源时区,模糊日期先待确认,用户覆盖/清除不被新来源替换;来源版本仅在相同 sourceId 内比较,双方缺失 ID 时按同一旧版来源处理。到期优先按确切时刻排序,仅日期按来源时区当天结束参与排序,不保存虚构时刻;同一排序时刻沿创建时间/id稳定排序。稍后只暂缓呈现,不延长真实期限。删除/不再提示保留同一问题的抑制记录,跨来源去重也遵守它,恢复不影响整个项目或来源。
+`list_teammate_todos`、`update_teammate_todo` 是与任务调用并列的伙伴公共能力,调用者由本机在用伙伴主任务反查。更新是部分合并,旧来源/引用默认保留;已有记录必须带修订号,冲突重新读取。完成必须记录依据,重开保留历史。到期支持日期/确切时刻及来源时区,模糊日期先待确认,用户覆盖/清除不被新来源替换;来源版本仅在相同 sourceId 内比较,双方缺失 ID 时按同一旧版来源处理。到期优先按确切时刻排序,仅日期按来源时区当天结束参与排序,不保存虚构时刻;同一排序时刻沿创建时间/id稳定排序。稍后只暂缓呈现,不延长真实期限。已打开的列表按最近暂缓期限安排一次只读刷新,回到前台时复核;远程分页返回全清单的最近期限,不受当前页截断。不启动后台提醒、扫描或执行。删除/不再提示保留同一问题的抑制记录,跨来源去重也遵守它,恢复不影响整个项目或来源。
桌面右侧工作台与手机版伙伴 Todo 入口共享同一宿主记录。远程通过已有受信 device-link resource get/invoke 路径和账号/可见伙伴边界,不新增广域 IPC 权限。读取与写入回执只返回可展示的投影,不发送宿主目录、去重键、旧记录内部标识或模型执行指令;来源与关联在手机显示可读名称,来源引用保留 HTTPS 链接。旧客户端有只读文本回退;新客户端专用组件按25条翻页并展示总数,搜索在完整记录中进行;桌面折叠完成区展开后也按25条翻页,不一次挂载全部历史,稳定顺序使用 ID 索引而不在比较器中扫描整个清单。
-具体动作通过既有伙伴输入路径推进,接收/排队与真实开始/完成各自独立;入队成功只显示已收到,既有输入协调器确认实际派发或插话后才显示已接受。未派发的排队项被移除、Stop 或清空时,同条 Todo 记录失败并可重试;重复请求不重复投递,未知回执不能盲重试。重启或切回账号后,生命周期回执按当前账号的伙伴主任务与磁盘 requestId 重建关联;读取清单时核对既有持久队列和消息记录,仍排队/在途则等待,取消墓碑确认未执行则可重试,只有已落库文字而无派发证据则待核实。内存 prepare/enqueue 在途不被当作孤立回执,队列读取失败不推断取消。手机断连解除本地忙态与关闭保护,重连只重新读取、不重发操作,旧连接迟到结果不干扰新请求。邮件等来源正文不自动授予外发或费用授权,原授权流程仍适用。原普通任务组件、归档和引擎状态不变。
+具体动作通过既有伙伴输入路径推进,接收/排队与真实开始/完成各自独立;入队成功只显示已收到,既有输入协调器确认实际派发或插话后才显示已接受。未派发的排队项被移除、Stop 或清空时,同条 Todo 记录失败并可重试;重复请求不重复投递,未知回执不能盲重试。重启或切回账号后,生命周期回执按当前账号的伙伴主任务与磁盘 requestId 重建关联;读取清单时核对既有持久队列和消息记录,仍排队/在途则等待,取消墓碑确认未执行则可重试,只有已落库文字而无派发证据则待核实。内存 prepare/enqueue 在途不被当作孤立回执,队列读取失败不推断取消。手机断连解除本地忙态与关闭保护,重连只重新读取、不重发操作,旧连接迟到结果不干扰新请求。邮件等来源正文不自动授予外发或费用授权,原授权流程仍适用。原普通任务组件、归档和引擎状态不变。旧条目若仍有受信项目内本地引用,等价打开能力迁移完成前保留原详情入口与现有路径校验;不把宿主路径投影到手机。
-共用 `teammate-guide` 要求对话变化、任务结果和已授权跟进维护同条;纯进度询问可读取,无变化不写。`preflight_teammate_todo_events` 先按职责、稳定来源游标、同问题 key 与忽略记录做确定性过滤,`record_teammate_todo_event` 原子提交成功处理结果。仅复用实际可用的连接与现有事件/routine;这些接口不提供全邮箱/飞书扫描器,也不新建定时器。失败不推进游标;无唤醒不承诺后台实时运行,预算沿用既有配置,不拍脑袋设固定模型阈值。
+共用 `teammate-guide` 要求对话变化、任务结果和已授权跟进维护同条;纯进度询问可读取,无变化不写。`preflight_teammate_todo_events` 先按职责、稳定来源游标、同问题 key 与忽略记录做确定性过滤,`record_teammate_todo_event` 原子提交成功处理结果。仅复用实际可用的连接与现有事件/routine;这些接口不提供全邮箱/飞书扫描器,也不新建周期扫描或提醒定时器。失败不推进游标;无唤醒不承诺后台实时运行,预算沿用既有配置,不拍脑袋设固定模型阈值。
以下原项目工具仍供项目素材和普通任务使用,不再作为新 Todo 的存储接口。
diff --git a/packages/maker-shared/src/teammateTodo.test.ts b/packages/maker-shared/src/teammateTodo.test.ts
index 7bb462fcd5..c2a30d7efb 100644
--- a/packages/maker-shared/src/teammateTodo.test.ts
+++ b/packages/maker-shared/src/teammateTodo.test.ts
@@ -1,10 +1,11 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
applyTodoPatch,
emptyTodoState,
effectiveTodoDeadline,
preflightTodoEvents,
queryTodoItems,
+ scheduleTodoDeferralRefresh,
createTodoDueComparator,
todoOverdue,
todoVisible,
@@ -427,3 +428,53 @@ it('normalizes problem keys before lookup and preflight rather than creating dup
expect(s.items).toHaveLength(1);
expect(ignored.key).toBe('quote:1');
});
+
+it('returns the next deferral boundary even outside a page and makes expired entries visible without changing deadlines', () => {
+ const state = emptyTodoState();
+ for (let n = 0; n < 36; n++) applyTodoPatch(state, { ...patch, key: 'k' + n }, 'todo-' + n, now);
+ const later = applyTodoPatch(
+ state,
+ { id: 'todo-35', expectedRevision: 1, operation: 'later', until: '2026-10-10T12:02:00Z' },
+ 'unused',
+ now,
+ );
+ applyTodoPatch(
+ state,
+ { id: 'todo-34', expectedRevision: 1, operation: 'later', until: '2026-10-10T12:03:00Z' },
+ 'unused',
+ now,
+ );
+ const open = queryTodoItems(state.items, { limit: 25 }, now);
+ expect(open.items).toHaveLength(25);
+ expect(open.nextDeferredAt).toBe('2026-10-10T12:02:00Z');
+ expect(queryTodoItems(state.items, { view: 'hidden' }, now).total).toBe(2);
+ const after = new Date('2026-10-10T12:02:00Z');
+ expect(queryTodoItems(state.items, {}, after).total).toBe(35);
+ expect(queryTodoItems(state.items, { view: 'hidden' }, after).total).toBe(1);
+ expect(queryTodoItems(state.items, {}, after).nextDeferredAt).toBe('2026-10-10T12:03:00Z');
+ expect(effectiveTodoDeadline(later)).toEqual(effectiveTodoDeadline(state.items[0]));
+});
+
+it('refreshes once at a long deferral boundary and cancels without polling or executing', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(now);
+ try {
+ const refresh = vi.fn();
+ const until = new Date(now.getTime() + 2_147_483_647 + 5000).toISOString();
+ const cancel = scheduleTodoDeferralRefresh(until, refresh);
+ await vi.advanceTimersByTimeAsync(2_147_483_647);
+ expect(refresh).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(refresh).toHaveBeenCalledOnce();
+ cancel();
+ const cancelled = scheduleTodoDeferralRefresh(
+ new Date(Date.now() + 5000).toISOString(),
+ refresh,
+ );
+ cancelled();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(refresh).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/packages/maker-shared/src/teammateTodo.ts b/packages/maker-shared/src/teammateTodo.ts
index 097899672f..1d27af7d83 100644
--- a/packages/maker-shared/src/teammateTodo.ts
+++ b/packages/maker-shared/src/teammateTodo.ts
@@ -121,6 +121,8 @@ export function validateTodoDeadline(d: TodoDeadline | null): void {
if (
!d ||
!['date', 'instant'].includes(d.kind) ||
+ typeof d.date !== 'string' ||
+ d.date.length !== 10 ||
!/^\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
@@ -358,8 +360,8 @@ export function applyTodoPatch(
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.ref !== undefined) text(s.ref, 2000);
+ if (s.ref && !/^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);
@@ -414,7 +416,13 @@ export function applyTodoPatch(
t.deadlineOverride = { value: patch.deadlineOverride.value };
}
if (patch.deadlineCandidate !== undefined) {
- if (patch.deadlineCandidate) {
+ if (patch.deadlineCandidate !== null) {
+ if (
+ !patch.deadlineCandidate ||
+ typeof patch.deadlineCandidate !== 'object' ||
+ Array.isArray(patch.deadlineCandidate)
+ )
+ throw new TodoError('INVALID_INPUT');
validateTodoDeadline(patch.deadlineCandidate.value);
text(patch.deadlineCandidate.reason, 2000, true);
}
@@ -441,7 +449,7 @@ export function applyTodoPatch(
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);
+ if (patch.completion.ref !== undefined) text(patch.completion.ref, 2000);
t.history.push({ ...patch.completion, at: now.toISOString() });
t.status = 'done';
t.decision = null;
@@ -483,6 +491,37 @@ export function applyTodoPatch(
return t;
}
+/** Earliest visibility boundary; independent of pagination, with no reminder or execution side effect. */
+export function nextTodoDeferralAt(items: TeammateTodo[], now = new Date()): string | null {
+ let next: string | null = null;
+ for (const t of items) {
+ const until = t.decision?.kind === 'later' ? t.decision.until : undefined;
+ if (
+ until &&
+ Date.parse(until) > now.getTime() &&
+ (!next || Date.parse(until) < Date.parse(next))
+ )
+ next = until;
+ }
+ return next;
+}
+
+/** One mounted-view refresh; long waits are chunked locally without reading or running work. */
+export function scheduleTodoDeferralRefresh(until: string, refresh: () => void): () => void {
+ const at = Date.parse(until);
+ if (!Number.isFinite(at)) return () => {};
+ let timer: ReturnType<typeof setTimeout>;
+ const arm = () => {
+ const remaining = at - Date.now();
+ timer =
+ remaining > 2_147_483_647
+ ? setTimeout(arm, 2_147_483_647)
+ : setTimeout(refresh, Math.max(0, remaining));
+ };
+ arm();
+ return () => clearTimeout(timer);
+}
+
export interface TodoListQuery {
query?: string;
view?: 'open' | 'done' | 'hidden';
@@ -537,6 +576,7 @@ export function queryTodoItems(items: TeammateTodo[], q: TodoListQuery = {}, now
total: filtered.length,
offset,
limit,
+ nextDeferredAt: nextTodoDeferralAt(items, now),
completedTotal: items.filter((t) => t.status === 'done' && todoVisible(t, now)).length,
};
}