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): recover durable Todo receipts and mobile controls

zqchris376486a406d4
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts
index 6e148ec586..6ae98c3a97 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoAccess.test.ts
@@ -4,14 +4,16 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const env = vi.hoisted(() => ({
owner: 'owner-one',
+ generation: 1,
root: '',
active: true,
pending: false,
projects: ['/cindy'],
notify: vi.fn(),
+ cancel: vi.fn(async () => true),
}));
vi.mock('../../appSessionState.js', () => ({
- activeOwnerScopeKey: () => env.owner,
+ activeOwnerScopeKey: () => `${env.owner}:${env.generation}`,
ownerScopedUserDataPath: () => env.root,
isAppSessionBoundaryPending: () => env.pending,
}));
@@ -47,16 +49,29 @@ vi.mock('../botWorkbenchTools.js', () => ({
? { ok: true, botId: 'bot-one' }
: { ok: false, errorCode: 'NOT_A_BOT_SESSION' },
}));
-import { configureBotTodoDispatch, todoAccess, todoForCaller } from '../botTodoAccess';
+vi.mock('../../localDb/agentInputQueueSnapshots.js', () => ({
+ saveCancelledInputDelivery: env.cancel,
+}));
+import {
+ configureBotTodoDispatch,
+ todoAccess,
+ todoForCaller,
+ settleBotTodoForSession,
+} from '../botTodoAccess';
+import { createBotTodoStore } from '../botTodoStore';
+import { botProfileDir } from '../botProfileFolder';
import { createBotTodoDispatch } from '../botTodoDispatch';
let root = '';
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'todo-owner-'));
env.root = root;
env.owner = 'owner-one';
+ env.generation = 1;
env.active = true;
env.pending = false;
env.notify.mockClear();
+ env.cancel.mockReset().mockResolvedValue(true);
+ configureBotTodoDispatch(async () => ({ ok: true }));
});
afterEach(async () => rm(root, { recursive: true, force: true }));
const patch = {
@@ -143,7 +158,8 @@ describe('Todo public access', () => {
const send = vi.fn(async () => ({ ok: true, queued: true }));
const bridge = createBotTodoDispatch(send);
configureBotTodoDispatch(bridge.dispatch);
- const access = await todoAccess('bot-one'), todo = await access.patch(patch);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
const queued = await access.act(todo.id, todo.revision, 'queued-one');
expect(queued?.action?.state).toBe('received');
await bridge.settle('different-session', 'queued-one', false);
@@ -160,14 +176,100 @@ describe('Todo public access', () => {
expect(send).toHaveBeenCalledTimes(2);
});
it('rejects an old-owner queue receipt without writing to either account', async () => {
- const bridge = createBotTodoDispatch(async () => ({ ok: true, queued: true }));
+ const bridge = createBotTodoDispatch(
+ async () => ({ ok: true, queued: true }),
+ settleBotTodoForSession,
+ );
configureBotTodoDispatch(bridge.dispatch);
- const access = await todoAccess('bot-one'), todo = await access.patch(patch);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
await access.act(todo.id, todo.revision, 'old-owner');
env.owner = 'owner-two';
- await expect(bridge.settle('canonical-one', 'old-owner', false)).rejects.toMatchObject({ code: 'OWNER_SCOPE_CHANGED' });
+ env.root = path.join(root, 'other-owner');
+ await expect(bridge.settle('canonical-one', 'old-owner', false)).rejects.toMatchObject({
+ code: 'OWNER_SCOPE_CHANGED',
+ });
env.owner = 'owner-one';
+ env.root = root;
+ env.generation++;
+ const restoredAccess = await todoAccess('bot-one');
+ expect((await restoredAccess.list()).items[0].action?.state).toBe('received');
+ await bridge.settle('canonical-one', 'old-owner', false);
+ expect((await restoredAccess.list()).items[0].action?.state).toBe('failed');
+ });
+ it('rebuilds queued associations from disk after losing the dispatch bridge', async () => {
+ const old = createBotTodoDispatch(async () => ({ ok: true, queued: true }));
+ configureBotTodoDispatch(old.dispatch);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
+ await access.act(todo.id, todo.revision, 'restart-one');
+ const restored = createBotTodoDispatch(
+ async () => ({ ok: true, queued: true }),
+ settleBotTodoForSession,
+ );
+ configureBotTodoDispatch(restored.dispatch);
+ await restored.settle('another-session', 'restart-one', false);
expect((await access.list()).items[0].action?.state).toBe('received');
+ await restored.settle('canonical-one', 'restart-one', false);
+ expect((await access.list()).items[0].action?.state).toBe('failed');
+ expect(env.cancel).toHaveBeenCalledWith('canonical-one', 'restart-one');
+ await access.act(todo.id, todo.revision, 'restart-two');
+ // Lose a second bridge while queued; actual dispatch can still resolve the same Todo.
+ const again = createBotTodoDispatch(async () => ({ ok: true }), settleBotTodoForSession);
+ await again.settle('canonical-one', 'restart-two', true);
+ await again.settle('canonical-one', 'restart-two', false);
+ expect((await access.list()).items[0].action?.state).toBe('accepted');
+ expect((await access.list()).items[0].status).toBe('open');
+ });
+ it('reconciles orphaned prepare receipts without replaying ambiguous persisted input', async () => {
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
+ const disk = createBotTodoStore(
+ path.join(botProfileDir(env.root, 'bot-one'), 'todos.v1.json'),
+ async () => ({}),
+ );
+ // Process loss after prepare but before enqueue leaves only the durable Todo receipt.
+ await disk.prepareAction(todo.id, todo.revision, 'orphan');
+ const inspect = vi.fn(async (_session: string, ids: string[]) =>
+ ids.map((requestId) => ({ requestId, state: 'cancelled' as const })),
+ );
+ const send = vi.fn(async () => ({ ok: true, queued: true }));
+ configureBotTodoDispatch(send, inspect);
+ expect((await access.list()).items[0].action?.state).toBe('failed');
+ await access.act(todo.id, todo.revision, 'after-orphan');
+ expect(send).toHaveBeenCalledOnce();
+ configureBotTodoDispatch(send, async (_session, ids) =>
+ ids.map((requestId) => ({ requestId, state: 'pending' })),
+ );
+ expect((await access.list()).items[0].action?.state).toBe('received');
+ configureBotTodoDispatch(send, async (_session, ids) =>
+ ids.map((requestId) => ({ requestId, state: 'unknown' })),
+ );
+ expect((await access.list()).items[0].action?.state).toBe('unknown');
+ await access.act(todo.id, todo.revision, 'no-blind-replay');
+ expect(send).toHaveBeenCalledOnce();
+ });
+ it('does not reconcile an in-process prepare while enqueue is still in flight', async () => {
+ let finish!: (r: { ok: boolean; queued: boolean }) => void;
+ const send = vi.fn(
+ () =>
+ new Promise<{ ok: boolean; queued: boolean }>((r) => {
+ finish = r;
+ }),
+ );
+ const inspect = vi.fn(async (_session: string, ids: string[]) =>
+ ids.map((requestId) => ({ requestId, state: 'cancelled' as const })),
+ );
+ configureBotTodoDispatch(send, inspect);
+ const access = await todoAccess('bot-one'),
+ todo = await access.patch(patch);
+ const first = access.act(todo.id, todo.revision, 'preparing');
+ await vi.waitFor(() => expect(send).toHaveBeenCalledOnce());
+ await access.act(todo.id, todo.revision, 'preparing');
+ expect((await access.list()).items[0].action?.state).toBe('received');
+ expect(inspect).not.toHaveBeenCalled();
+ finish({ ok: true, queued: true });
+ await first;
});
});
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 2cbd7046d9..7b2f15494f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTodoStore.test.ts
@@ -277,9 +277,29 @@ it('rejects valid JSON with corrupt or overlong text without rewriting the file'
{ outcome: [] },
{ title: 'x'.repeat(301) },
{ progress: 'x'.repeat(4001) },
- { deadlineCandidate: { value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' }, reason: {} } },
- { deadlineCandidate: { value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' }, reason: 'x'.repeat(2001) } },
- { deadlineCandidate: { value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' }, reason: ' ' } },
+ { createdAt: 0 },
+ { updatedAt: [] },
+ { createdAt: {} },
+ { updatedAt: '2026-10-10' },
+ { createdAt: '2026-10-10T00:00:00.' + '0'.repeat(65) + 'Z' },
+ {
+ deadlineCandidate: {
+ value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' },
+ reason: {},
+ },
+ },
+ {
+ deadlineCandidate: {
+ value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' },
+ reason: 'x'.repeat(2001),
+ },
+ },
+ {
+ deadlineCandidate: {
+ value: { kind: 'date', date: '2026-10-13', timeZone: 'Asia/Shanghai' },
+ reason: ' ',
+ },
+ },
]) {
const corrupt = structuredClone(clean);
Object.assign(corrupt.items[0], fields);
diff --git a/apps/desktop/src/main/maker-ipc/botTodoAccess.ts b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
index c7aea05cb6..b3ed9c79d4 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoAccess.ts
@@ -13,6 +13,7 @@ import {
ownerScopedUserDataPath,
} from '../appSessionState.js';
import { getDbClient } from '../localDb/client/current.js';
+import { saveCancelledInputDelivery } from '../localDb/agentInputQueueSnapshots.js';
import { botProfiles } from '../localDb/schema.js';
import { botProfileDir } from './botProfileFolder.js';
import { broadcastBotWorkbenchChanged, readBotWorkbenchState } from './botWorkbenchService.js';
@@ -33,6 +34,8 @@ export interface BotTodoAccess {
requestId: string,
locale?: string,
): Promise<TeammateTodo | null>;
+ /** Host lifecycle only; not exposed as a model or Remote Resource action. */
+ settle(requestId: string, dispatched: boolean): Promise<void>;
}
export type TodoDispatchResult = { ok: boolean; queued?: boolean; error?: string };
export type TodoDispatchInput = {
@@ -41,12 +44,19 @@ export type TodoDispatchInput = {
displayText: string;
requestId: string;
assertCurrent: () => void;
+ canRecover: () => boolean;
onSettled: (result: { ok: boolean; error?: string }) => Promise<void>;
};
type Dispatch = (p: TodoDispatchInput) => Promise<TodoDispatchResult>;
let dispatch: Dispatch | null = null;
-export function configureBotTodoDispatch(value: Dispatch) {
+type RecoveryReceipt = { requestId: string; state: 'pending' | 'cancelled' | 'unknown' };
+type InspectReceipts = (sessionId: string, requestIds: string[]) => Promise<RecoveryReceipt[]>;
+let inspectReceipts: InspectReceipts | null = null;
+// Only closes the prepare -> enqueue race within this process. Recovery uses durable records.
+const preparing = new Map<string, number>();
+export function configureBotTodoDispatch(value: Dispatch, inspect?: InspectReceipts) {
dispatch = value;
+ inspectReceipts = inspect ?? null;
}
export async function todoAccess(botId: string): Promise<BotTodoAccess> {
const owner = activeOwnerScopeKey(),
@@ -78,11 +88,57 @@ export async function todoAccess(botId: string): Promise<BotTodoAccess> {
broadcastBotWorkbenchChanged(botId);
broadcastBotRemoteResourceChanged(botId);
};
+ const attemptKey = (requestId: string) => JSON.stringify([root, botId, requestId]);
+ const recoverReceived = async () => {
+ const state = await store.read();
+ const received = state.items.filter(
+ (t) => t.action?.state === 'received' && !preparing.has(attemptKey(t.action.requestId)),
+ );
+ if (!bot.sessionId || !inspectReceipts || !received.length) return state;
+ const receipts = await inspectReceipts(
+ bot.sessionId,
+ received.map((t) => t.action!.requestId),
+ );
+ assertCurrent();
+ const byRequest = new Map(receipts.map((r) => [r.requestId, r]));
+ let saved = false;
+ for (const t of received) {
+ const receipt = byRequest.get(t.action!.requestId);
+ if (!receipt || receipt.state === 'pending' || preparing.has(attemptKey(receipt.requestId)))
+ continue;
+ const result = await store.settleAction(t.id, receipt.requestId, {
+ ok: false,
+ uncertain: receipt.state === 'unknown',
+ error: receipt.state === 'cancelled' ? 'CANCELLED' : 'DELIVERY_UNCONFIRMED',
+ });
+ saved ||= result !== null;
+ }
+ if (saved) changed();
+ return saved ? store.read() : state;
+ };
+ const settle = async (requestId: string, dispatched: boolean) => {
+ const t = (await store.read()).items.find(
+ (t) => t.action?.requestId === requestId && t.action.state === 'received',
+ );
+ if (!t || !bot.sessionId) return;
+ // A cancellation tombstone fences a stale restored queue before exposing Retry.
+ const cancelled = !dispatched && (await saveCancelledInputDelivery(bot.sessionId, requestId));
+ assertCurrent();
+ if (
+ await store.settleAction(t.id, requestId, {
+ ok: dispatched,
+ uncertain: !dispatched && !cancelled,
+ ...(!dispatched ? { error: cancelled ? 'CANCELLED' : 'DELIVERY_UNCONFIRMED' } : {}),
+ })
+ )
+ changed();
+ };
return {
list: async () => {
- const state = await store.read();
+ const state = await recoverReceived();
return { items: state.items, version: 1 as const };
},
+ settle,
patch: async (p: TodoPatch) => {
const state = await readLegacy();
for (const s of p.sources ?? [])
@@ -105,10 +161,13 @@ export async function todoAccess(botId: string): Promise<BotTodoAccess> {
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;
+ await recoverReceived();
+ const key = attemptKey(requestId);
+ preparing.set(key, (preparing.get(key) ?? 0) + 1);
try {
+ const prepared = await store.prepareAction(id, revision, requestId);
+ changed();
+ if (!prepared.dispatch) return prepared.todo;
assertCurrent();
const t = prepared.todo;
const result = await dispatch({
@@ -129,10 +188,10 @@ export async function todoAccess(botId: string): Promise<BotTodoAccess> {
'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,
+ canRecover: () => !isAppSessionBoundaryPending() && ownerScopedUserDataPath() === root,
onSettled: async (result) => {
assertCurrent();
- await store.settleAction(id, requestId, result);
- changed();
+ await settle(requestId, result.ok);
},
});
// Enqueue success is only receipt. Coordinator dispatch/discard settles it later.
@@ -150,10 +209,31 @@ export async function todoAccess(botId: string): Promise<BotTodoAccess> {
});
changed();
throw error;
+ } finally {
+ const count = (preparing.get(key) ?? 1) - 1;
+ if (count) preparing.set(key, count);
+ else preparing.delete(key);
}
},
};
}
+/** Rebuild the association from this owner's canonical profile and persisted request ID. */
+export async function settleBotTodoForSession(
+ sessionId: string,
+ requestId: string,
+ dispatched: boolean,
+): Promise<void> {
+ const owner = activeOwnerScopeKey();
+ if (isAppSessionBoundaryPending()) throw new TodoError('OWNER_SCOPE_CHANGED');
+ const [bot] = await getDbClient()
+ .drizzle.select({ id: botProfiles.id, sessionId: botProfiles.canonicalSessionId })
+ .from(botProfiles)
+ .where(eq(botProfiles.canonicalSessionId, sessionId))
+ .limit(1);
+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())
+ throw new TodoError('OWNER_SCOPE_CHANGED');
+ if (bot?.sessionId === sessionId) await (await todoAccess(bot.id)).settle(requestId, dispatched);
+}
export async function todoForCaller(callerSessionId: string): Promise<BotTodoAccess> {
const owner = activeOwnerScopeKey();
const caller = await resolveWorkbenchCaller(callerSessionId);
diff --git a/apps/desktop/src/main/maker-ipc/botTodoDispatch.ts b/apps/desktop/src/main/maker-ipc/botTodoDispatch.ts
index 5b9a7c3b1a..91638f0109 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoDispatch.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoDispatch.ts
@@ -3,6 +3,7 @@ import type { TodoDispatchInput, TodoDispatchResult } from './botTodoAccess.js';
/** Consume the existing coordinator's dispatch/discard receipts; enqueue is not dispatch. */
export function createBotTodoDispatch(
send: (input: TodoDispatchInput) => Promise<TodoDispatchResult>,
+ restored?: (sessionId: string, requestId: string, dispatched: boolean) => Promise<void>,
) {
const pending = new Map<string, TodoDispatchInput>();
const key = (sessionId: string, requestId: string) => sessionId + '\0' + requestId;
@@ -22,10 +23,22 @@ export function createBotTodoDispatch(
async settle(sessionId: string, requestId: string, dispatched: boolean): Promise<void> {
const id = key(sessionId, requestId);
const input = pending.get(id);
- if (!input || input.sessionId !== sessionId) return;
- pending.delete(id);
- input.assertCurrent();
+ if (!input) {
+ await restored?.(sessionId, requestId, dispatched);
+ return;
+ }
+ try {
+ input.assertCurrent();
+ } catch (error) {
+ // A switched-back owner has a new generation. Rebuild from its current profile,
+ // never run the old closure or write a different owner's home.
+ if (!restored || !input.canRecover()) throw error;
+ await restored(sessionId, requestId, dispatched);
+ if (pending.get(id) === input) pending.delete(id);
+ return;
+ }
await input.onSettled({ ok: dispatched, ...(!dispatched ? { error: 'CANCELLED' } : {}) });
+ if (pending.get(id) === input) pending.delete(id);
},
};
}
diff --git a/apps/desktop/src/main/maker-ipc/botTodoStore.ts b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
index 7b4efea57b..7e52726684 100644
--- a/apps/desktop/src/main/maker-ipc/botTodoStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botTodoStore.ts
@@ -8,6 +8,7 @@ import {
normalizeTodoKey,
todoVisible,
validateTodoDeadline,
+ validateTodoTimestamp,
type TodoPatch,
type TodoState,
type TeammateTodo,
@@ -16,6 +17,15 @@ import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
import type { WorkbenchTaskJudgment } from '../../shared/botWorkbench.js';
import { parseWorkbenchTaskId } from '../../shared/botWorkbench.js';
+function validTimestamp(value: unknown): boolean {
+ try {
+ validateTodoTimestamp(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
export interface TodoIngestInput {
source: string;
sequence: number;
@@ -160,11 +170,7 @@ export function createBotTodoStore(
typeof a.label !== 'string',
) ||
t.history.some(
- (h) =>
- !h ||
- typeof h.summary !== 'string' ||
- !h.summary ||
- !Number.isFinite(Date.parse(h.at)),
+ (h) => !h || typeof h.summary !== 'string' || !h.summary || !validTimestamp(h.at),
) ||
(t.next !== null &&
(!t.next ||
@@ -174,7 +180,7 @@ export function createBotTodoStore(
(t.decision !== null &&
(!t.decision ||
!['deleted', 'muted', 'later'].includes(t.decision.kind) ||
- (t.decision.kind === 'later' && !Number.isFinite(Date.parse(t.decision.until!))))) ||
+ (t.decision.kind === 'later' && !validTimestamp(t.decision.until)))) ||
(t.action !== null &&
(!t.action ||
typeof t.action.requestId !== 'string' ||
@@ -201,8 +207,8 @@ export function createBotTodoStore(
typeof t.value !== 'string' ||
t.value.length > 4000 ||
!['assigned', 'discovered'].includes(t.origin) ||
- !Number.isFinite(Date.parse(t.createdAt)) ||
- !Number.isFinite(Date.parse(t.updatedAt))
+ !validTimestamp(t.createdAt) ||
+ !validTimestamp(t.updatedAt)
)
throw new TodoError('CORRUPT_STORE');
try {
@@ -214,7 +220,8 @@ export function createBotTodoStore(
typeof t.deadlineCandidate.reason !== 'string' ||
!t.deadlineCandidate.reason.trim() ||
t.deadlineCandidate.reason.length > 2000
- ) throw new TodoError('CORRUPT_STORE');
+ )
+ throw new TodoError('CORRUPT_STORE');
}
} catch {
throw new TodoError('CORRUPT_STORE');
@@ -351,7 +358,8 @@ export function createBotTodoStore(
) =>
mutate((s) => {
const t = s.items.find((t) => t.id === id);
- if (!t?.action || t.action.requestId !== requestId) return null;
+ if (!t?.action || t.action.requestId !== requestId || t.action.state !== 'received')
+ return null;
t.action = {
...t.action,
state: result.ok ? 'accepted' : result.uncertain ? 'unknown' : 'failed',
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 96aa2ae63e..084167d8bc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,4 +1,4 @@
-import { configureBotTodoDispatch } from './botTodoAccess.js';
+import { configureBotTodoDispatch, settleBotTodoForSession } from './botTodoAccess.js';
import { createBotTodoDispatch } from './botTodoDispatch.js';
import { assertBotTaskCoordination, classifySessionMessagePurpose, coordinationInput } from './botTaskCoordination.js';
import type { BotTaskCoordination, SessionMessagePurpose } from '../../shared/botTaskCoordination.js';
@@ -9890,13 +9890,72 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
- const todoDispatch = createBotTodoDispatch(async ({sessionId,message,displayText,requestId,assertCurrent}) => {
+ const todoDispatch = createBotTodoDispatch(
+ async ({ sessionId, message, displayText, requestId, assertCurrent }) => {
+ assertCurrent();
+ const result = await sendToSessionInternal({
+ targetSessionId: sessionId,
+ message,
+ persistedContent: displayText,
+ clientId: requestId,
+ onAccepted: assertCurrent,
+ forceQueue: true,
+ autoReviewUserText: { kind: 'delegated-continuation' },
+ });
+ if (result.ok && result.wakeKind === 'queued')
+ await awaitAgentInputQueueSnapshotPersistence(sessionId);
+ assertCurrent();
+ return {
+ ok: result.ok,
+ queued: result.ok && result.wakeKind === 'queued',
+ ...(!result.ok ? { error: result.message } : {}),
+ };
+ },
+ settleBotTodoForSession,
+ );
+ configureBotTodoDispatch(todoDispatch.dispatch, async (sessionId, requestIds) => {
+ const owner = getCurrentDbClientSnapshot();
+ const assertCurrent = () => {
+ if (
+ !owner ||
+ getCurrentDbClientSnapshot()?.clientEpoch !== owner.clientEpoch ||
+ isAppSessionBoundaryPending()
+ )
+ throw new Error('OWNER_SCOPE_CHANGED');
+ };
+ assertCurrent();
+ await inputCoordinator.ensureQueueRestored(sessionId);
assertCurrent();
- const result = await sendToSessionInternal({targetSessionId:sessionId,message,persistedContent:displayText,clientId:requestId,onAccepted:assertCurrent,
- autoReviewUserText:{kind:'delegated-continuation'}});
- assertCurrent();return {ok:result.ok, queued:result.ok && result.wakeKind === 'queued', ...(!result.ok ? {error:result.message} : {})};
+ if (!inputCoordinator.isQueueRestored(sessionId)) throw new Error('QUEUE_UNAVAILABLE');
+ const recovered: Array<{ requestId: string; state: 'pending' | 'cancelled' | 'unknown' }> = [];
+ for (let offset = 0; offset < requestIds.length; offset += 200) {
+ const receipts = await readInputDeliveryReceipts(
+ sessionId,
+ requestIds.slice(offset, offset + 200),
+ );
+ assertCurrent();
+ for (const receipt of receipts) {
+ const pending =
+ receipt.state === 'pending' ||
+ inputCoordinator.hasQueuedItemWhere(
+ sessionId,
+ (item) => item.clientId === receipt.clientId,
+ { includeRecovery: true },
+ );
+ // Persisted user text proves receipt, not vendor dispatch. Never replay that uncertainty.
+ const cancelled =
+ !pending &&
+ receipt.state !== 'accepted' &&
+ (await saveCancelledInputDelivery(sessionId, receipt.clientId));
+ assertCurrent();
+ recovered.push({
+ requestId: receipt.clientId,
+ state: pending ? 'pending' : cancelled ? 'cancelled' : 'unknown',
+ });
+ }
+ }
+ return recovered;
});
- configureBotTodoDispatch(todoDispatch.dispatch);
const settleTodoDispatch = (sessionId: string, clientId: string, dispatched: boolean) =>
todoDispatch.settle(sessionId, clientId, dispatched).catch(() => {
log.warn('Todo input receipt could not be saved');
@@ -16927,6 +16986,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await gitSnapshotCoordinator?.onTurnStart(sessionId);
},
onUndispatchedUserTurn: (sessionId, item, disposition) => {
+ void settleTodoDispatch(sessionId, item.clientId, false);
welcomeDispatchReceipts.settle(sessionId, item.clientId, false);
// 目标轮落库了却没能 dispatch(取消 / 失败): 记账该立刻还回去, 而不是等超时。
publishUiTurnUndispatched(sessionId, item.clientId);
diff --git a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
index e91293b9da..48baf866ef 100644
--- a/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotTodoList.tsx
@@ -15,6 +15,7 @@ import {
} from '@/contexts/dataOwnerGeneration';
import {
effectiveTodoDeadline,
+ createTodoDueComparator,
todoDateLabel,
todoOverdue,
todoLocalDate,
@@ -92,16 +93,14 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
api = useRef(transport);
api.current = transport;
const current = () => mounted.current && isDataOwnerGenerationCurrent(scope.current);
- const sorted = (rows: TeammateTodo[], kind: string) =>
- [...rows].sort((a, b) =>
+ const sorted = (rows: TeammateTodo[], kind: string) => {
+ const compareDue = createTodoDueComparator();
+ return [...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)
+ ? compareDue(a, b) || 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 {
@@ -508,7 +507,9 @@ export function TodoPanel({ transport, botId }: { transport: TodoTransport; botI
value={order}
onChange={(e) => {
setOrder(e.target.value);
- initialOrder.current = new Map(sorted(items, e.target.value).map((x, rank) => [x.id, rank]));
+ initialOrder.current = new Map(
+ sorted(items, e.target.value).map((x, rank) => [x.id, rank]),
+ );
setPage(0);
setDonePage(0);
}}
diff --git a/apps/mobile/src/__tests__/CompanionTodos.test.tsx b/apps/mobile/src/__tests__/CompanionTodos.test.tsx
new file mode 100644
index 0000000000..5a6a7d7483
--- /dev/null
+++ b/apps/mobile/src/__tests__/CompanionTodos.test.tsx
@@ -0,0 +1,198 @@
+// @vitest-environment jsdom
+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';
+
+const h = vi.hoisted(() => ({
+ sheet: {} as any,
+ get: vi.fn(),
+ action: vi.fn(),
+ invoke: vi.fn(),
+ openLink: vi.fn(async () => {}),
+ onChanged: vi.fn(() => () => {}),
+ close: vi.fn(),
+}));
+vi.mock('react-native', () => ({
+ View: ({ children }: any) => createElement('div', null, children),
+ ScrollView: ({ children }: any) => createElement('div', null, children),
+ ActivityIndicator: () => null,
+ Linking: { openURL: vi.fn() },
+ Pressable: ({ children, onPress, disabled, accessibilityLabel }: any) =>
+ createElement(
+ 'button',
+ { onClick: onPress, disabled, 'aria-label': accessibilityLabel },
+ children,
+ ),
+ StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 },
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (s: string) => s.replace('devices.teammateTodo.', ''),
+ i18n: { language: 'en' },
+ }),
+}));
+vi.mock('@/auth/AuthContext', () => ({
+ useAuth: () => ({ accountGeneration: 1 }),
+}));
+vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({
+ invoke: h.invoke,
+ openLink: h.openLink,
+ onRemoteResourceChanged: h.onChanged,
+ }),
+}));
+vi.mock('@/device-link/remoteResources', () => ({
+ getRemoteResource: h.get,
+ invokeRemoteResourceAction: h.action,
+}));
+vi.mock('@/components/AppText', () => ({
+ Text: ({ children }: any) => createElement('span', null, children),
+ TextInput: ({ value, onChangeText, accessibilityLabel }: any) =>
+ createElement('input', {
+ value,
+ onChange: (e: any) => onChangeText(e.target.value),
+ 'aria-label': accessibilityLabel,
+ }),
+}));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return {
+ ...tokens,
+ useTheme: () => ({ colors: tokens.lightColors }),
+ useThemedStyles: (fn: any) => fn(tokens.lightColors),
+ };
+});
+vi.mock('lucide-react-native', () => ({
+ Plus: () => null,
+ ChevronDown: () => null,
+ ChevronRight: () => null,
+}));
+vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-request' }));
+vi.mock('@/session/TodoDateInput', () => ({ TodoDateInput: () => null }));
+vi.mock('@/session/CompanionSheet', () => ({
+ CompanionSheet: (props: any) => {
+ h.sheet = props;
+ return props.children;
+ },
+}));
+vi.mock('@/session/CompanionTodoRow', () => ({
+ CompanionTodoRow: ({ item, busy, onAction }: any) =>
+ createElement(
+ 'button',
+ { 'data-testid': item.id, disabled: busy, onClick: onAction },
+ item.title,
+ ),
+}));
+import { CompanionTodos } from '@/session/CompanionTodos';
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root, host: HTMLDivElement;
+const todo = applyTodoPatch(
+ emptyTodoState(),
+ {
+ key: 'quote',
+ title: 'Compare quote',
+ outcome: 'Review the prepared comparison',
+ next: {
+ kind: 'advance',
+ label: 'Compare',
+ instruction: 'Prepare only, do not send',
+ },
+ },
+ 'todo-one',
+);
+const props = {
+ visible: true,
+ online: true,
+ deviceId: 'host',
+ deviceName: 'Computer',
+ botId: 'teammate',
+ onClose: h.close,
+};
+const flush = async () =>
+ act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ });
+async function render(online = true) {
+ await act(async () => root.render(<CompanionTodos {...props} online={online} />));
+ await flush();
+}
+const row = () => host.querySelector<HTMLButtonElement>('[data-testid="todo-one"]')!;
+const button = (label: string) =>
+ Array.from(host.querySelectorAll<HTMLButtonElement>('button')).find(
+ (b) => b.textContent === label,
+ )!;
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.get.mockResolvedValue({
+ blocks: [
+ {
+ primitive: 'teammate-todos',
+ data: {
+ items: [todo],
+ total: 1,
+ completedTotal: 1,
+ offset: 0,
+ limit: 25,
+ },
+ },
+ ],
+ });
+ h.action.mockResolvedValue({});
+ host = document.createElement('div');
+ root = createRoot(host);
+});
+afterEach(() => act(() => root.unmount()));
+
+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;
+ h.action
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ oldResult = resolve;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ newResult = resolve;
+ }),
+ );
+ await render();
+ await act(async () => row().click());
+ expect(h.action).toHaveBeenCalledOnce();
+ expect(row().disabled).toBe(true);
+ expect(h.sheet.preventDismiss).toBe(true);
+ await render(false);
+ expect(h.sheet.preventDismiss).toBe(false);
+ await render(true);
+ expect(row().disabled).toBe(false);
+ expect(h.action).toHaveBeenCalledOnce();
+ await act(async () => row().click());
+ expect(row().disabled).toBe(true);
+ // A late success from the previous connection must not unlock or close the new request.
+ await act(async () => oldResult({}));
+ expect(row().disabled).toBe(true);
+ expect(h.sheet.preventDismiss).toBe(true);
+ await act(async () => newResult({}));
+ expect(row().disabled).toBe(false);
+ expect(h.sheet.preventDismiss).toBe(false);
+});
+
+it('routes Open from completed directly to open, and labels the hidden-list action by its destination', async () => {
+ await render();
+ expect(button('hidden')).toBeDefined();
+ await act(async () => button('done · 1').click());
+ await flush();
+ expect(JSON.parse(h.get.mock.calls.at(-1)![5]).view).toBe('done');
+ await act(async () => button('open').click());
+ await flush();
+ expect(JSON.parse(h.get.mock.calls.at(-1)![5]).view).toBe('open');
+ await act(async () => button('hidden').click());
+ await flush();
+ expect(JSON.parse(h.get.mock.calls.at(-1)![5]).view).toBe('hidden');
+ await act(async () => button('open').click());
+ await flush();
+ expect(JSON.parse(h.get.mock.calls.at(-1)![5]).view).toBe('open');
+});
diff --git a/apps/mobile/src/session/CompanionTodos.tsx b/apps/mobile/src/session/CompanionTodos.tsx
index 879deddbce..0791444402 100644
--- a/apps/mobile/src/session/CompanionTodos.tsx
+++ b/apps/mobile/src/session/CompanionTodos.tsx
@@ -84,11 +84,20 @@ function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId,
const [form, setForm] = useState<Record<string, string>>({});
const [showActions, setShowActions] = useState(false);
const pending = useRef(false);
+ const operationEpoch = useRef(0);
const formRevision = useRef<number | undefined>(undefined);
const epoch = useRef(0),
binding = useRef(''),
mounted = useRef(true);
binding.current = `${deviceId}:${botId}:${visible}:${online}`;
+ useEffect(() => {
+ // A lost link invalidates this panel's UI request, not the host's operation.
+ // Do not replay it on reconnect; reload the host record instead.
+ operationEpoch.current++;
+ pending.current = false;
+ setBusy(false);
+ setLoading(false);
+ }, [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 () => {
@@ -185,6 +194,9 @@ function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId,
pending.current = true;
setBusy(true);
const scope = binding.current;
+ const operation = ++operationEpoch.current;
+ const current = () =>
+ mounted.current && scope === binding.current && operation === operationEpoch.current;
try {
await openLink(deviceId);
await invokeRemoteResourceAction(
@@ -193,18 +205,19 @@ function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId,
{ collectionId: 'teammates', resourceRef: ref, actionId, input },
i18n.language,
);
- if (mounted.current && scope === binding.current) {
+ if (current()) {
setEditing(false);
setDetail(null);
setShowActions(false);
await reload();
}
} catch (e) {
- if (mounted.current && scope === binding.current)
- setError(String(e).includes('CONFLICT') ? 'conflict' : 'error');
+ if (current()) setError(String(e).includes('CONFLICT') ? 'conflict' : 'error');
} finally {
- pending.current = false;
- if (mounted.current && scope === binding.current) setBusy(false);
+ if (operation === operationEpoch.current) {
+ pending.current = false;
+ if (mounted.current) setBusy(false);
+ }
}
};
const update = (item: TeammateTodo, patch: TodoPatch) =>
@@ -574,11 +587,11 @@ function CompanionTodosContent({ visible, onClose, deviceId, deviceName, botId,
</View>
<View style={styles.toolbar}>
{button(
- tr(filter.view === 'hidden' ? 'hidden' : 'open'),
+ tr(filter.view === 'open' ? 'hidden' : 'open'),
() => {
setFilter({
...filter,
- view: filter.view === 'hidden' ? 'open' : 'hidden',
+ view: filter.view === 'open' ? 'hidden' : 'open',
});
setOffset(0);
},
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index b7546b08ee..3d2589d72d 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -463,11 +463,11 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
实现使用伙伴目录下独立的 `todos.v1.json`,带稳定 id/key、乐观修订号与跨进程原子写入。旧工作台文件原样保留,旧 PR/issue/idea 条目按稳定 ID 兼容读取,新格式已保存后旧工具的更新仍会在读取时合并;保留用户期限覆盖、忽略决定和来源链接,旧描述更新不会撤销用户重新打开。普通 Session 判断继续属于任务元数据。新存储不静默淘汰完成历史;超容量明确拒绝。损坏文件失败关闭,不能用空列表覆盖。
-`list_teammate_todos`、`update_teammate_todo` 是与任务调用并列的伙伴公共能力,调用者由本机在用伙伴主任务反查。更新是部分合并,旧来源/引用默认保留;已有记录必须带修订号,冲突重新读取。完成必须记录依据,重开保留历史。到期支持日期/确切时刻及来源时区,模糊日期先待确认,用户覆盖/清除不被新来源替换;稍后只暂缓呈现,不延长真实期限。删除/不再提示保留同一问题的抑制记录,跨来源去重也遵守它,恢复不影响整个项目或来源。
+`list_teammate_todos`、`update_teammate_todo` 是与任务调用并列的伙伴公共能力,调用者由本机在用伙伴主任务反查。更新是部分合并,旧来源/引用默认保留;已有记录必须带修订号,冲突重新读取。完成必须记录依据,重开保留历史。到期支持日期/确切时刻及来源时区,模糊日期先待确认,用户覆盖/清除不被新来源替换;来源版本仅在相同 sourceId 内比较,双方缺失 ID 时按同一旧版来源处理。到期优先按确切时刻排序,仅日期按来源时区当天结束参与排序,不保存虚构时刻;同一排序时刻沿创建时间/id稳定排序。稍后只暂缓呈现,不延长真实期限。删除/不再提示保留同一问题的抑制记录,跨来源去重也遵守它,恢复不影响整个项目或来源。
桌面右侧工作台与手机版伙伴 Todo 入口共享同一宿主记录。远程通过已有受信 device-link resource get/invoke 路径和账号/可见伙伴边界,不新增广域 IPC 权限。读取与写入回执只返回可展示的投影,不发送宿主目录、去重键、旧记录内部标识或模型执行指令;来源与关联在手机显示可读名称,来源引用保留 HTTPS 链接。旧客户端有只读文本回退;新客户端专用组件按25条翻页并展示总数,搜索在完整记录中进行;桌面折叠完成区展开后也按25条翻页,不一次挂载全部历史,稳定顺序使用 ID 索引而不在比较器中扫描整个清单。
-具体动作通过既有伙伴输入路径推进,接收/排队与真实开始/完成各自独立;入队成功只显示已收到,既有输入协调器确认实际派发或插话后才显示已接受。未派发的排队项被移除、Stop 或清空时,同条 Todo 记录失败并可重试;重复请求不重复投递,未知回执不能盲重试。邮件等来源正文不自动授予外发或费用授权,原授权流程仍适用。原普通任务组件、归档和引擎状态不变。
+具体动作通过既有伙伴输入路径推进,接收/排队与真实开始/完成各自独立;入队成功只显示已收到,既有输入协调器确认实际派发或插话后才显示已接受。未派发的排队项被移除、Stop 或清空时,同条 Todo 记录失败并可重试;重复请求不重复投递,未知回执不能盲重试。重启或切回账号后,生命周期回执按当前账号的伙伴主任务与磁盘 requestId 重建关联;读取清单时核对既有持久队列和消息记录,仍排队/在途则等待,取消墓碑确认未执行则可重试,只有已落库文字而无派发证据则待核实。内存 prepare/enqueue 在途不被当作孤立回执,队列读取失败不推断取消。手机断连解除本地忙态与关闭保护,重连只重新读取、不重发操作,旧连接迟到结果不干扰新请求。邮件等来源正文不自动授予外发或费用授权,原授权流程仍适用。原普通任务组件、归档和引擎状态不变。
共用 `teammate-guide` 要求对话变化、任务结果和已授权跟进维护同条;纯进度询问可读取,无变化不写。`preflight_teammate_todo_events` 先按职责、稳定来源游标、同问题 key 与忽略记录做确定性过滤,`record_teammate_todo_event` 原子提交成功处理结果。仅复用实际可用的连接与现有事件/routine;这些接口不提供全邮箱/飞书扫描器,也不新建定时器。失败不推进游标;无唤醒不承诺后台实时运行,预算沿用既有配置,不拍脑袋设固定模型阈值。
diff --git a/packages/maker-shared/src/teammateTodo.test.ts b/packages/maker-shared/src/teammateTodo.test.ts
index d1f5d6e628..7bb462fcd5 100644
--- a/packages/maker-shared/src/teammateTodo.test.ts
+++ b/packages/maker-shared/src/teammateTodo.test.ts
@@ -5,6 +5,7 @@ import {
effectiveTodoDeadline,
preflightTodoEvents,
queryTodoItems,
+ createTodoDueComparator,
todoOverdue,
todoVisible,
validateTodoDeadline,
@@ -236,6 +237,148 @@ describe('teammate affairs contract', () => {
});
});
+it('orders source versions only within their source, including the legacy stream', () => {
+ const s = emptyTodoState();
+ let t = applyTodoPatch(
+ s,
+ {
+ ...patch,
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-10',
+ timeZone: 'UTC',
+ sourceId: 'mail:A',
+ sourceVersion: 100,
+ },
+ },
+ 'one',
+ now,
+ );
+ t = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ deadlineOverride: {
+ value: { kind: 'date', date: '2026-10-20', timeZone: 'UTC' },
+ },
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-11',
+ timeZone: 'UTC',
+ sourceId: 'issue:B',
+ sourceVersion: 1,
+ },
+ },
+ '',
+ now,
+ );
+ expect(t.sourceDeadline?.sourceId).toBe('issue:B');
+ expect(effectiveTodoDeadline(t)?.date).toBe('2026-10-20');
+ expect(() =>
+ applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ sourceDeadline: { ...t.sourceDeadline!, sourceVersion: 0 },
+ },
+ '',
+ now,
+ ),
+ ).toThrow('STALE_SOURCE');
+ t = applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ sourceDeadline: {
+ kind: 'date',
+ date: '2026-10-12',
+ timeZone: 'UTC',
+ sourceVersion: 2,
+ },
+ },
+ '',
+ now,
+ );
+ expect(() =>
+ applyTodoPatch(
+ s,
+ {
+ id: t.id,
+ expectedRevision: t.revision,
+ sourceDeadline: { ...t.sourceDeadline!, sourceVersion: 1 },
+ },
+ '',
+ now,
+ ),
+ ).toThrow('STALE_SOURCE');
+});
+
+it('orders exact instants and source-local date ends, retaining creation/ID tie breakers', () => {
+ const s = emptyTodoState();
+ const add = (id: string, deadline: NonNullable<TodoPatch['sourceDeadline']>, created = now) =>
+ applyTodoPatch(s, { ...patch, key: id, sourceDeadline: deadline }, id, created);
+ add(
+ 'late',
+ {
+ kind: 'instant',
+ date: '2026-10-10',
+ timeZone: 'UTC',
+ at: '2026-10-10T17:00:00Z',
+ },
+ new Date('2026-10-01'),
+ );
+ add('early', {
+ kind: 'instant',
+ date: '2026-10-10',
+ timeZone: 'UTC',
+ at: '2026-10-10T09:00:00Z',
+ });
+ add('date-shanghai', {
+ kind: 'date',
+ date: '2026-10-10',
+ timeZone: 'Asia/Shanghai',
+ });
+ add('date-utc', { kind: 'date', date: '2026-10-10', timeZone: 'UTC' });
+ add('next-local-date', {
+ kind: 'instant',
+ date: '2026-10-11',
+ timeZone: 'Asia/Shanghai',
+ at: '2026-10-11T01:00:00+08:00',
+ });
+ expect(queryTodoItems(s.items).items.map((t) => t.id)).toEqual([
+ 'early',
+ 'date-shanghai',
+ 'late',
+ 'next-local-date',
+ 'date-utc',
+ ]);
+ expect(queryTodoItems(s.items, { order: 'created' }).items[0].id).toBe('late');
+ const compare = createTodoDueComparator();
+ const dst = add('dst-date', {
+ kind: 'date',
+ date: '2026-11-01',
+ timeZone: 'America/New_York',
+ });
+ const before = add('dst-before', {
+ kind: 'instant',
+ date: '2026-11-01',
+ timeZone: 'America/New_York',
+ at: '2026-11-02T04:30:00Z',
+ });
+ const after = add('dst-after', {
+ kind: 'instant',
+ date: '2026-11-02',
+ timeZone: 'America/New_York',
+ at: '2026-11-02T05:30:00Z',
+ });
+ expect(compare(before, dst)).toBeLessThan(0);
+ expect(compare(dst, after)).toBeLessThan(0);
+ expect(dst.sourceDeadline?.at).toBeUndefined();
+});
+
it('a source label refresh retains its existing evidence and scope when optional metadata is omitted', () => {
const s = emptyTodoState();
const t = applyTodoPatch(
diff --git a/packages/maker-shared/src/teammateTodo.ts b/packages/maker-shared/src/teammateTodo.ts
index adf3dfe841..097899672f 100644
--- a/packages/maker-shared/src/teammateTodo.ts
+++ b/packages/maker-shared/src/teammateTodo.ts
@@ -105,15 +105,17 @@ const text = (s: unknown, max: number, required = false): string => {
throw new TodoError('INVALID_INPUT');
return s.trim();
};
-const iso = (s: unknown) => {
+export function validateTodoTimestamp(s: unknown): string {
if (
typeof s !== 'string' ||
+ s.length > 64 ||
!/^\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;
-};
+}
+const iso = validateTodoTimestamp;
export function validateTodoDeadline(d: TodoDeadline | null): void {
if (d === null) return;
if (
@@ -156,6 +158,45 @@ export function todoLocalDate(now: Date, zone: string): string {
export function effectiveTodoDeadline(t: TeammateTodo): TodoDeadline | null {
return t.deadlineOverride ? t.deadlineOverride.value : t.sourceDeadline;
}
+/** Date-only items sort at the end of their source-local day, without inventing a stored time. */
+export function createTodoDueComparator() {
+ const values = new Map<string, number>();
+ const value = (t: TeammateTodo) => {
+ const d = effectiveTodoDeadline(t);
+ if (!d) return Infinity;
+ if (d.kind === 'instant') return Date.parse(d.at!);
+ const key = d.date + '\0' + d.timeZone;
+ const cached = values.get(key);
+ if (cached !== undefined) return cached;
+ // Locate the next local calendar day, including DST transitions and midnight gaps.
+ const target = Number(d.date.replaceAll('-', ''));
+ const nominal = Date.parse(d.date + 'T00:00:00Z') + 86_400_000;
+ const format = new Intl.DateTimeFormat('en', {
+ timeZone: d.timeZone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ });
+ let lo = nominal - 36 * 3_600_000,
+ hi = nominal + 36 * 3_600_000;
+ while (lo < hi) {
+ const mid = Math.floor((lo + hi) / 2),
+ parts = format.formatToParts(new Date(mid));
+ const date = Number(
+ ['year', 'month', 'day'].map((k) => parts.find((p) => p.type === k)!.value).join(''),
+ );
+ if (date > target) hi = mid;
+ else lo = mid + 1;
+ }
+ values.set(key, lo - 1);
+ return lo - 1;
+ };
+ return (a: TeammateTodo, b: TeammateTodo) => {
+ const left = value(a),
+ right = value(b);
+ return left === right ? 0 : left - right;
+ };
+}
export function todoOverdue(t: TeammateTodo, now = new Date()): boolean {
const d = effectiveTodoDeadline(t);
return (
@@ -359,6 +400,8 @@ export function applyTodoPatch(
if (
t.sourceDeadline &&
patch.sourceDeadline &&
+ // Versions are ordered only within one source. Two missing IDs are the legacy stream.
+ t.sourceDeadline.sourceId === patch.sourceDeadline.sourceId &&
(patch.sourceDeadline.sourceVersion ?? 0) < (t.sourceDeadline.sourceVersion ?? 0)
)
throw new TodoError('STALE_SOURCE');
@@ -461,6 +504,7 @@ export function queryTodoItems(items: TeammateTodo[], q: TodoListQuery = {}, now
throw new TodoError('INVALID_INPUT');
const search = (q.query ?? '').trim().toLocaleLowerCase();
if (search.length > 300) throw new TodoError('INVALID_INPUT');
+ const compareDue = createTodoDueComparator();
const filtered = items
.filter(
(t) =>
@@ -478,11 +522,7 @@ export function queryTodoItems(items: TeammateTodo[], q: TodoListQuery = {}, now
)
.sort(
(a, b) =>
- (q.order !== 'created'
- ? (effectiveTodoDeadline(a)?.date ?? '9999').localeCompare(
- effectiveTodoDeadline(b)?.date ?? '9999',
- )
- : 0) ||
+ (q.order !== 'created' ? compareDue(a, b) : 0) ||
a.createdAt.localeCompare(b.createdAt) ||
a.id.localeCompare(b.id),
);