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: 让已清空消息的投递回执收口并补齐错误恢复测试

Dashde73ea0ff8ae
diff --git a/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
index fa0682abf9..33e3264ab1 100644
--- a/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
@@ -74,14 +74,15 @@ describe('agent input queue snapshot durability boundary', () => {
const sqlite = new Database(':memory:');
sqlite.exec(`
CREATE TABLE agent_input_queue_snapshots (session_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER);
- CREATE TABLE messages (session_id TEXT, client_id TEXT, role TEXT, rewind_at INTEGER);
+ CREATE TABLE messages (session_id TEXT, client_id TEXT, role TEXT, rewind_at INTEGER, created_at INTEGER DEFAULT 1);
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, cleared_at INTEGER);
`);
const sid = `receipt-malformed-${allMalformed}`;
const good = allMalformed ? [] : [queued('pending', 'valid'), queued('accepted', 'history')];
const payload = JSON.stringify([...good, null, 'legacy row', { clientId: 'bad' }, { clientId: 'removed' }]);
sqlite.prepare('INSERT INTO agent_input_queue_snapshots VALUES (?, ?, ?)').run(sid, payload, 1);
- sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?)').run(sid, 'history', 'user', null);
- sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?)').run(sid, 'removed', 'message_tombstone', 1);
+ sqlite.prepare('INSERT INTO messages (session_id, client_id, role, rewind_at) VALUES (?, ?, ?, ?)').run(sid, 'history', 'user', null);
+ sqlite.prepare('INSERT INTO messages (session_id, client_id, role, rewind_at) VALUES (?, ?, ?, ?)').run(sid, 'removed', 'message_tombstone', 1);
mocks.getDbClient.mockReturnValue({ drizzle: drizzle(sqlite) });
try {
expect((await loadAgentInputQueueSnapshot(sid)).map((item) => item.clientId)).toEqual(good.map((item) => item.clientId));
@@ -96,6 +97,30 @@ describe('agent input queue snapshot durability boundary', () => {
expect(sqlite.prepare('SELECT payload FROM agent_input_queue_snapshots').get()).toEqual({ payload });
} finally { sqlite.close(); }
});
+ it('reports cleared history as removed while preserving later messages and pending inputs', async () => {
+ const sqlite = new Database(':memory:');
+ sqlite.exec(`
+ CREATE TABLE agent_input_queue_snapshots (session_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER);
+ CREATE TABLE messages (session_id TEXT, client_id TEXT, role TEXT, rewind_at INTEGER, created_at INTEGER);
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, cleared_at INTEGER);
+ INSERT INTO sessions VALUES ('clear-receipts', NULL);
+ INSERT INTO sessions VALUES ('other-task', 999);
+ INSERT INTO messages VALUES ('clear-receipts', 'before', 'user', NULL, 99);
+ INSERT INTO messages VALUES ('clear-receipts', 'at', 'user', NULL, 100);
+ INSERT INTO messages VALUES ('clear-receipts', 'after', 'user', NULL, 101);
+ `);
+ sqlite.prepare('INSERT INTO agent_input_queue_snapshots VALUES (?, ?, ?)')
+ .run('clear-receipts', JSON.stringify([queued('pending', 'pending')]), 1);
+ mocks.getDbClient.mockReturnValue({ drizzle: drizzle(sqlite) });
+ try {
+ const ids = ['before', 'at', 'after', 'pending', 'unknown'];
+ const states = async () => (await readInputDeliveryReceipts('clear-receipts', ids)).map(row => row.state);
+ expect(await states()).toEqual(['accepted', 'accepted', 'accepted', 'pending', 'unknown']);
+ sqlite.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?').run(100, 'clear-receipts');
+ expect(await states()).toEqual(['removed', 'removed', 'accepted', 'pending', 'unknown']);
+ expect(await states()).toEqual(['removed', 'removed', 'accepted', 'pending', 'unknown']);
+ } finally { sqlite.close(); }
+ });
it.each(['settled', 'pending', 'receipt-retry'] as const)('does not let %s cancellation replace a failed snapshot boundary', async (timing) => {
const sid = `snapshot-cancel-${timing}`;
const failure = new Error('snapshot failed');
diff --git a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
index f4f86fed96..d5d5f3565e 100644
--- a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
+++ b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
@@ -11,12 +11,12 @@
* (宁可让上层保留可重试的输入,不把未持久化误报成成功)。
*/
-import { and, eq, inArray } from 'drizzle-orm';
+import { and, eq, inArray, sql } from 'drizzle-orm';
import { randomUUID } from 'node:crypto';
import type { InputDeliveryReceipt } from '@cindy/device-link';
import { getDbClient, getCurrentDbClientSnapshot, type CurrentDbClientSnapshot } from './client/current';
-import { agentInputQueueSnapshots, messages } from './schema';
+import { agentInputQueueSnapshots, messages, sessions } from './schema';
import { createLogger } from '../logger';
import {
sanitizeQueuedMessageForPersistence,
@@ -180,6 +180,11 @@ export async function readInputDeliveryReceipts(
const pending = new Set(raw.filter(isRestorableQueuedMessage).map((item) => item.clientId));
const rows = await owner.client.drizzle.select({
clientId: messages.clientId, role: messages.role, rewindAt: messages.rewindAt,
+ // /clear hides history without deleting rows. Read the boundary with the row
+ // so even old controllers without a saved boundary receive terminal evidence.
+ cleared: sql<number>`coalesce(${messages.createdAt} <= (
+ select ${sessions.clearedAt} from ${sessions} where ${sessions.id} = ${sessionId}
+ ), 0)`,
}).from(messages).where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, clientIds)));
assertQueueOwner(owner);
const persisted = new Map(rows.map((row) => [row.clientId, row]));
@@ -188,7 +193,7 @@ export async function readInputDeliveryReceipts(
return {
clientId,
state: row
- ? row.role === 'message_tombstone' || row.rewindAt !== null ? 'removed' : 'accepted'
+ ? row.role === 'message_tombstone' || row.rewindAt !== null || row.cleared === 1 ? 'removed' : 'accepted'
: pending.has(clientId) ? 'pending' : 'unknown',
};
});
diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.ts
index 65c7922e59..79441f476f 100644
--- a/apps/mobile/src/__tests__/durableOutbox.test.ts
+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts
@@ -196,7 +196,7 @@ describe("durable mobile outbox ownership", () => {
new Error('[NOT_FOUND] Message 不存在'),
])('waits for host receipts when pending history is missing (%s)', async (error) => {
const { store, deps, runner } = await setup();
- await store.add({ ...message(), state: 'host-owned', retrySafe: true });
+ await store.add({ ...message(), state: 'host-owned', retrySafe: true, error: '[NOT_FOUND] Message 不存在' });
deps.projection.mockResolvedValue(projection('id-1', 'pending'));
deps.history.mockRejectedValue(error);
await runner.run();
@@ -227,6 +227,20 @@ describe("durable mobile outbox ownership", () => {
expect(deps.cleanup).not.toHaveBeenCalled();
});
+ it('settles cleared legacy records without a saved boundary from the host receipt', async () => {
+ const { store, deps, runner } = await setup();
+ await store.add({ ...message(), state: 'host-owned', retrySafe: true });
+ deps.projection.mockResolvedValue({ ...projection('id-1', 'removed'), clearBoundaryMs: 123 });
+ await runner.run();
+ runner.wake();
+ await runner.run();
+ expect(store.getSnapshot()).toEqual([]);
+ expect(deps.projection).toHaveBeenCalledOnce();
+ expect(deps.history).not.toHaveBeenCalled();
+ expect(deps.enqueue).not.toHaveBeenCalled();
+ expect(deps.cleanup).toHaveBeenCalledWith(expect.anything(), false);
+ });
+
it('still reports other history lookup failures', async () => {
const { store, deps, runner } = await setup();
await store.add({ ...message(), state: 'host-owned', retrySafe: true });
@@ -752,6 +766,8 @@ describe("app-owned delivery and reconciliation", () => {
expect(deps.enqueue).toHaveBeenCalledTimes(1);
expect(deps.enqueue.mock.calls[0]?.[0].prepared?.clientId).toBe("id-1");
expect(store.getSnapshot()[0]?.state).toBe("host-owned");
+ expect(store.getSnapshot()[0]?.clearBoundaryMs).toBeNull();
+ expect(deps.enqueue.mock.calls[0]?.[0].clearBoundaryMs).toBeNull();
runner.wake();
deps.projection.mockResolvedValue(projection("id-1", "accepted"));
deps.history.mockResolvedValue(true);
diff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.ts
index 7ebe4e892d..6b6304dfbe 100644
--- a/apps/mobile/src/session/durableOutboxDelivery.ts
+++ b/apps/mobile/src/session/durableOutboxDelivery.ts
@@ -274,7 +274,8 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
},
retrySafe: projection.inputDeliveryVersion === 1,
enqueueStarted: record.enqueueStarted ?? (record.sendAtMs === undefined ? false : undefined),
- clearBoundaryMs: projection.clearBoundaryMs ?? record.clearBoundaryMs,
+ clearBoundaryMs: projection.clearBoundaryMs !== undefined
+ ? projection.clearBoundaryMs : record.clearBoundaryMs,
sendAtMs: record.sendAtMs ?? Date.now(),
});
}