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(im): preserve archive activity boundaries and normalize IPC errors

xdd9bb658d16ee
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
index b459fe0837..b76844810f 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
@@ -96,6 +96,8 @@ import {
__testing,
} from '../botImConnectionRuntime';
import { addBotImConnectionRecord, listBotImConnections, secretKeyPrefixFor } from '../botImConnectionStore';
+import * as connectionStore from '../botImConnectionStore';
+import { __testing as laneTesting } from '../botImLaneRuntime';
import { withBotProfileLocks } from '../../../maker-ipc/botProfileLock';
import { readWechatChannelSettings, writeWechatCompanionBinding, writeWechatWorkingDir } from '../../wechat/channelSettings';
import {
@@ -296,6 +298,62 @@ describe('bot im connection runtime', () => {
expect(h.archiveCalls).toEqual([]);
});
+ // PR #6959: the real IPC handler must encode storage failures without leaking
+ // filesystem paths, while retaining domain/owner errors. Existing coverage
+ // only rejects synchronous invalid inputs. Unit: inject failure at archive
+ // persistence after real connection/link ownership checks, without Electron.
+ it.each([
+ { failure: new Error('ARCHIVE_CAPACITY_REACHED'), code: 'PRECONDITION_FAILED', message: 'ARCHIVE_CAPACITY_REACHED' },
+ { failure: new Error('OWNER_CHANGED'), code: 'PRECONDITION_FAILED', message: 'OWNER_CHANGED' },
+ { failure: new Error("EACCES: permission denied, open '/private/owners/secret/bot-im-connections.json'"), code: 'INTERNAL', message: 'LANE_ARCHIVE_FAILED' },
+ { failure: new Error('EPERM: operation not permitted, rename C:\\Users\\private-owner\\bot-im-connections.json'), code: 'INTERNAL', message: 'LANE_ARCHIVE_FAILED' },
+ ])('normalizes archive persistence failure to $code ($message)', async ({ failure, code, message }) => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-mia', channel: 'telegram' });
+ await connectionStore.updateBotImConnectionRecord(record.id, { botContextId: '777' });
+ laneTesting.setStore({
+ listLinks: async () => [{ sessionId: 'session-1', role: 'canonical', routeKey: null }],
+ readActivity: vi.fn(),
+ readArchiveActivity: vi.fn(async () => ({ messageId: null, hasNewActivity: false })),
+ });
+ const archive = vi.spyOn(connectionStore, 'archiveBotImTaskRow').mockRejectedValueOnce(failure);
+ registerBotImConnectionIpc();
+ const handler = h.ipcHandlers.get('botImConnection:archive-lane')!;
+ await expect(handler({}, { id: record.id, sessionId: 'session-1' })).rejects.toMatchObject({
+ code, message: `[${code}] ${message}`,
+ });
+ expect(archive).toHaveBeenCalledOnce();
+ expect(listBotImConnections()[0]?.archivedTaskRows).toBeUndefined();
+ });
+
+ it('preserves the archive IPC not-found error', async () => {
+ registerBotImConnectionIpc();
+ const handler = h.ipcHandlers.get('botImConnection:archive-lane')!;
+ await expect(handler({}, { id: 'a1b2c3d4e5f6', sessionId: 'session-1' })).rejects.toMatchObject({
+ code: 'NOT_FOUND', message: '[NOT_FOUND] CONNECTION_NOT_FOUND',
+ });
+ });
+
+ it('preserves the archive IPC owner-change rejection before persistence', async () => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-mia', channel: 'telegram' });
+ await connectionStore.updateBotImConnectionRecord(record.id, { botContextId: '777' });
+ laneTesting.setStore({
+ listLinks: async () => {
+ h.ownerKey = 'owner-b';
+ return [{ sessionId: 'session-1', role: 'canonical', routeKey: null }];
+ },
+ readActivity: vi.fn(),
+ readArchiveActivity: vi.fn(async () => ({ messageId: null, hasNewActivity: false })),
+ });
+ const archive = vi.spyOn(connectionStore, 'archiveBotImTaskRow');
+ registerBotImConnectionIpc();
+ const handler = h.ipcHandlers.get('botImConnection:archive-lane')!;
+ await expect(handler({}, { id: record.id, sessionId: 'session-1' })).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] OWNER_CHANGED',
+ });
+ expect(archive).not.toHaveBeenCalled();
+ expect(listBotImConnections()[0]?.archivedTaskRows).toBeUndefined();
+ });
+
beforeEach(() => {
h.root = fs.mkdtempSync(path.join(os.tmpdir(), 'bot-im-runtime-'));
h.secrets.clear();
@@ -405,6 +463,8 @@ describe('bot im connection runtime', () => {
});
afterEach(async () => {
+ vi.restoreAllMocks();
+ laneTesting.setStore(null);
await stopBotImConnections();
fs.rmSync(h.root, { recursive: true, force: true });
});
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts
index 7c6d493ee5..565ef4126e 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts
@@ -36,6 +36,7 @@ describe('bot im connection store', () => {
});
afterEach(() => {
+ vi.restoreAllMocks();
fs.rmSync(h.root, { recursive: true, force: true });
});
@@ -213,13 +214,140 @@ describe('bot im connection store', () => {
expect(readBotImConnection(second.id)?.archivedTaskRows?.['new-session']).toEqual(expect.any(Number));
});
+ // Codex review: timestamp-only CAS cannot distinguish two archives in one ms.
+ // Real file entry points must retain a newer marker and atomically pair its anchor;
+ // previous tests only varied timestamps. Unit tier uses an isolated temporary file.
+ it('preserves a same-millisecond rearchive while reclaiming an older observation', async () => {
+ const at = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(at);
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ await archiveBotImTaskRow(record, 'rearchived', [], { messageId: 'message', generation: '111111111111' });
+ const observed = readBotImConnection(record.id)!;
+ await archiveBotImTaskRow(observed, 'rearchived', [], { messageId: 'message', generation: '222222222222' });
+ await archiveBotImTaskRow(readBotImConnection(record.id)!, 'new-session', [
+ { connection: observed, cutoffs: observed.archivedTaskRows! },
+ ], { messageId: null, generation: '333333333333' });
+ expect(readBotImConnection(record.id)?.archivedTaskRows).toEqual({ rearchived: at, 'new-session': at });
+ expect(readBotImConnection(record.id)?.archivedTaskActivity).toEqual({
+ rearchived: { messageId: 'message', generation: '222222222222' },
+ 'new-session': { messageId: null, generation: '333333333333' },
+ });
+ });
+
+ it.each(['cutoff', 'generation', 'messageId'] as const)('does not overwrite a newer target with a stale %s observation', async (changed) => {
+ const at = Date.now();
+ const now = vi.spyOn(Date, 'now').mockReturnValue(at);
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const activity = { messageId: 'first', generation: '111111111111' };
+ await archiveBotImTaskRow(record, 'target', [], activity);
+ const observed = readBotImConnection(record.id)!;
+ if (changed === 'cutoff') now.mockReturnValue(at + 1);
+ const winningActivity = {
+ messageId: changed === 'messageId' ? 'second' : activity.messageId,
+ generation: changed === 'generation' ? '222222222222' : activity.generation,
+ };
+ const winner = await archiveBotImTaskRow(observed, 'target', [], winningActivity);
+ expect(winner?.archivedTaskActivity?.target).toEqual(winningActivity);
+ const before = fs.readFileSync(file(), 'utf8');
+ now.mockReturnValue(at + 2);
+ const late = await archiveBotImTaskRow(observed, 'target', [], { messageId: 'stale', generation: '333333333333' });
+ expect(late).toEqual(winner);
+ expect(fs.readFileSync(file(), 'utf8')).toBe(before);
+ });
+
+ it('normalizes only valid activity anchors with a corresponding numeric cutoff', async () => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));
+ const activity = { messageId: 'message', generation: '111111111111' };
+ const anchors = {
+ valid: activity, empty: { ...activity, messageId: '' }, spaces: { ...activity, messageId: ' ' },
+ long: { ...activity, messageId: 'x'.repeat(257) }, wrongType: { ...activity, messageId: 1 },
+ badGeneration: { ...activity, generation: 'not-a-nonce' }, missing: { messageId: 'message' },
+ nullMessage: { ...activity, messageId: null }, orphan: activity, badCutoff: activity,
+ };
+ document.connections[record.id].archivedTaskRows = { ...Object.fromEntries(Object.keys(anchors)
+ .filter((id) => id !== 'orphan').map((id) => [id, 100])), badCutoff: 'invalid' };
+ document.connections[record.id].archivedTaskActivity = anchors;
+ fs.writeFileSync(file(), JSON.stringify(document));
+ expect(readBotImConnection(record.id)?.archivedTaskActivity).toEqual({
+ valid: activity, nullMessage: { ...activity, messageId: null },
+ });
+ await setBotImConnectionGroupActivation(record.id, '-1001', 'always');
+ expect(JSON.parse(fs.readFileSync(file(), 'utf8')).connections[record.id].archivedTaskActivity)
+ .toEqual(readBotImConnection(record.id)?.archivedTaskActivity);
+ });
+
+ it('cleans activity anchors with matching cutoffs and clears them for legacy archive writes', async () => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const activity = { messageId: null, generation: '111111111111' };
+ await archiveBotImTaskRow(record, 'obsolete', [], activity);
+ await archiveBotImTaskRow(readBotImConnection(record.id)!, 'dormant', [], activity);
+ const observed = readBotImConnection(record.id)!;
+ await archiveBotImTaskRow(observed, 'new-session', [
+ { connection: observed, cutoffs: { obsolete: observed.archivedTaskRows!.obsolete } },
+ ], activity);
+ const cleaned = readBotImConnection(record.id)!;
+ expect(Object.keys(cleaned.archivedTaskRows!).sort()).toEqual(['dormant', 'new-session']);
+ expect(Object.keys(cleaned.archivedTaskActivity!).sort()).toEqual(['dormant', 'new-session']);
+ await archiveBotImTaskRow(cleaned, 'dormant');
+ expect(readBotImConnection(record.id)?.archivedTaskRows?.dormant).toEqual(expect.any(Number));
+ expect(readBotImConnection(record.id)?.archivedTaskActivity).toEqual({ 'new-session': activity });
+ });
+
+ it('includes activity anchors in the byte budget and rolls back both maps on rejection', async () => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));
+ const ids = Array.from({ length: 200 }, (_, i) => `existing-${i}`);
+ const activity = { messageId: 'x'.repeat(256), generation: '111111111111' };
+ document.connections[record.id].archivedTaskRows = Object.fromEntries(ids.map((id) => [id, 1]));
+ document.connections[record.id].archivedTaskActivity = Object.fromEntries(ids.map((id) => [id, activity]));
+ fs.writeFileSync(file(), JSON.stringify(document, null, 2));
+ const observed = readBotImConnection(record.id)!;
+ const before = fs.readFileSync(file(), 'utf8');
+ expect(Buffer.byteLength(before)).toBeGreaterThan(64 * 1024);
+ expect(Buffer.byteLength(JSON.stringify(observed.archivedTaskRows))).toBeLessThan(64 * 1024);
+ await expect(archiveBotImTaskRow(observed, 'new-session', [], activity)).rejects.toThrow('ARCHIVE_CAPACITY_REACHED');
+ expect(fs.readFileSync(file(), 'utf8')).toBe(before);
+ await archiveBotImTaskRow(observed, 'new-session', [
+ { connection: observed, cutoffs: Object.fromEntries(ids.slice(0, 80).map((id) => [id, 1])) },
+ ], activity);
+ const cleaned = readBotImConnection(record.id)!;
+ expect(Object.keys(cleaned.archivedTaskRows!)).toHaveLength(121);
+ expect(Object.keys(cleaned.archivedTaskActivity!)).toHaveLength(121);
+ expect(cleaned.archivedTaskActivity?.[ids[0]]).toBeUndefined();
+ expect(cleaned.archivedTaskActivity?.['new-session']).toEqual(activity);
+ });
+
it('keeps valid prototype-named task ids as ordinary archive entries', async () => {
const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
- await archiveBotImTaskRow(record, '__proto__');
- await archiveBotImTaskRow(record, 'constructor');
+ const activity = { messageId: null, generation: '111111111111' };
+ await archiveBotImTaskRow(record, '__proto__', [], activity);
+ await archiveBotImTaskRow(record, 'constructor', [], activity);
const archived = readBotImConnection(record.id)?.archivedTaskRows;
expect(Object.hasOwn(archived ?? {}, '__proto__')).toBe(true);
expect(archived?.['__proto__']).toEqual(expect.any(Number));
expect(archived?.constructor).toEqual(expect.any(Number));
+ expect(readBotImConnection(record.id)?.archivedTaskActivity?.['__proto__']).toEqual(activity);
+ expect(readBotImConnection(record.id)?.archivedTaskActivity?.constructor).toEqual(activity);
+ });
+
+ it('does not treat inherited activity fields as anchors for legacy prototype-named rows', async () => {
+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));
+ const activity = { messageId: 'message', generation: '111111111111' };
+ document.connections[record.id].archivedTaskRows = Object.fromEntries([
+ ['constructor', 1], ['__proto__', 1], ['other', 1],
+ ]);
+ document.connections[record.id].archivedTaskActivity = { other: activity };
+ fs.writeFileSync(file(), JSON.stringify(document));
+ const observed = readBotImConnection(record.id)!;
+ await archiveBotImTaskRow(observed, 'new-session', [{ connection: observed, cutoffs: { constructor: 1 } }], activity);
+ const cleaned = readBotImConnection(record.id)!;
+ expect(Object.hasOwn(cleaned.archivedTaskRows!, 'constructor')).toBe(false);
+ expect(Object.hasOwn(cleaned.archivedTaskRows!, '__proto__')).toBe(true);
+ expect(Object.hasOwn(cleaned.archivedTaskActivity!, '__proto__')).toBe(false);
+ await archiveBotImTaskRow(observed, '__proto__', [], activity);
+ expect(readBotImConnection(record.id)?.archivedTaskActivity?.['__proto__']).toEqual(activity);
+ expect(readBotImConnection(record.id)?.archivedTaskActivity?.other).toEqual(activity);
});
});
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts
index d7e700d601..0249a8d04f 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts
@@ -10,7 +10,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import type { DbClient } from '../../../localDb/client/DbClient';
import { getDbClient } from '../../../localDb/client/current';
-import type { BotImConnectionRecord } from '../../../../shared/botImConnection';
+import type { BotImConnectionRecord, BotImTaskArchiveActivity } from '../../../../shared/botImConnection';
import type { BotImTaskArchiveCleanup } from '../botImConnectionStore';
const h = vi.hoisted(() => ({
@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({
reclaimable: [] as (readonly BotImTaskArchiveCleanup[])[],
sql: [] as string[],
sqlAtArchive: [] as string[],
+ beforeArchive: null as (() => void) | null,
}));
vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));
@@ -30,10 +31,11 @@ vi.mock('../../../localDb/client/current', () => ({ getDbClient: vi.fn() }));
vi.mock('../botImConnectionStore', () => ({
readBotImConnection: (id: string) => h.records.get(id) ?? null,
listBotImConnections: () => [...h.records.values()] as BotImConnectionRecord[],
- archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: readonly BotImTaskArchiveCleanup[] = []) => {
+ archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: readonly BotImTaskArchiveCleanup[] = [], archiveActivity?: BotImTaskArchiveActivity) => {
h.sqlAtArchive.push(...h.sql);
h.reclaimable.push(reclaimable);
- const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() } };
+ h.beforeArchive?.();
+ const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() }, archivedTaskActivity: archiveActivity ? { ...record.archivedTaskActivity, [sessionId]: archiveActivity } : record.archivedTaskActivity };
h.records.set(record.id, next);
h.archived.add(sessionId);
return next;
@@ -87,7 +89,10 @@ const ACTIVITY: Record<string, BotImLaneActivity> = {
const listLinks = vi.fn(async (botId: string) => (botId === TELEGRAM.botId ? LINKS : []));
const readActivity = vi.fn(async (sessionId: string) => ACTIVITY[sessionId] ?? activity());
-const readLastActivityAt = vi.fn(async (sessionId: string) => (ACTIVITY[sessionId] ?? activity()).lastActivityAt);
+const readArchiveActivity = vi.fn(async (sessionId: string, archive?: number | BotImTaskArchiveActivity) => ({
+ messageId: `message-${sessionId}`,
+ hasNewActivity: typeof archive === 'number' && ((ACTIVITY[sessionId] ?? activity()).lastActivityAt ?? 0) > archive,
+}));
const restartSession = vi.fn<(sessionId: string) => Promise<void>>(async () => {});
const knownGroups = vi.fn(async () => [{ chatId: '-1001', chatName: 'Launch crew' }]);
@@ -99,12 +104,106 @@ beforeEach(() => {
h.sql.length = 0;
h.sqlAtArchive.length = 0;
h.owner = 'owner-a';
+ h.beforeArchive = null;
h.records.set(TELEGRAM.id, TELEGRAM);
- __testing.setStore({ listLinks, readActivity, readLastActivityAt });
+ __testing.setStore({ listLinks, readActivity, readArchiveActivity });
configureBotImLaneRuntime({ isTurnRunning: (id) => id === 's-guest', restartSession });
});
+async function withActivityDatabase(run: (db: Database.Database) => Promise<void>): Promise<void> {
+ const db = new Database(':memory:');
+ const now = vi.spyOn(Date, 'now').mockReturnValue(500);
+ try {
+ db.exec(`
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, status TEXT, cleared_at INTEGER);
+ CREATE TABLE bot_session_links (session_id TEXT, bot_id TEXT, role TEXT, route_key TEXT, archived_at INTEGER);
+ CREATE TABLE messages (id TEXT PRIMARY KEY, session_id TEXT, role TEXT, created_at INTEGER, rewind_at INTEGER, agent_meta TEXT);
+ INSERT INTO sessions VALUES ('s-group', 'bot', 'active', NULL), ('s-topic', 'bot', 'active', NULL);
+ INSERT INTO bot_session_links VALUES ('s-group', 'bot-a', 'channel', 'im:telegram:777:g:-1001', NULL),
+ ('s-topic', 'bot-a', 'channel', 'im:telegram:777:g:-1001:t:42', NULL);
+ INSERT INTO messages VALUES ('old', 's-group', 'user', 500, NULL, NULL);
+ `);
+ vi.mocked(getDbClient).mockReturnValue({ drizzle: drizzle(db) } as unknown as DbClient);
+ __testing.setStore(null);
+ await run(db);
+ } finally {
+ now.mockRestore();
+ db.close();
+ }
+}
+
describe('botImLaneRuntime', () => {
+ // Timestamps cannot distinguish writes in the same millisecond or after a
+ // clock adjustment. Exercise the real SQL and both display/reclamation paths.
+ it.each([
+ ['user', 500], ['assistant', 500], ['error', 500],
+ ['user', 100], ['assistant', 100], ['error', 100],
+ ] as const)('restores and reclaims an archive for a new %s message at %i', async (role, at) => {
+ await withActivityDatabase(async (db) => {
+ expect((await archiveBotImConnectionLane(TELEGRAM.id, 's-group')).lanes.map((lane) => lane.sessionId)).toEqual(['s-topic']);
+ db.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, NULL, NULL)').run('new', 's-group', role, at);
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.some((lane) => lane.sessionId === 's-group')).toBe(true);
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');
+ expect(h.reclaimable.at(-1)).toEqual([{ connection: expect.objectContaining({ id: TELEGRAM.id }), cutoffs: { 's-group': 500 } }]);
+ expect(restartSession).not.toHaveBeenCalled();
+ expect(db.prepare('SELECT count(*) AS n FROM bot_session_links').get()).toEqual({ n: 2 });
+ });
+ });
+
+ it('captures insertion order after an earlier clock rollback and ignores invisible activity', async () => {
+ await withActivityDatabase(async (db) => {
+ db.exec("INSERT INTO messages VALUES ('earlier-rollback', 's-group', 'assistant', 100, NULL, NULL)");
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
+ expect((h.records.get(TELEGRAM.id) as BotImConnectionRecord).archivedTaskActivity?.['s-group'].messageId).toBe('earlier-rollback');
+ db.exec(`INSERT INTO messages VALUES ('tool', 's-group', 'tool', 600, NULL, NULL),
+ ('rebuild', 's-group', 'context_rebuild', 600, 600, NULL),
+ ('rewound', 's-group', 'assistant', 600, 600, NULL);
+ UPDATE messages SET rewind_at = 600 WHERE id = 'earlier-rollback';`);
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.map((lane) => lane.sessionId)).toEqual(['s-topic']);
+ db.exec("INSERT INTO messages VALUES ('next', 's-group', 'error', 1, NULL, NULL)");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.some((lane) => lane.sessionId === 's-group')).toBe(true);
+ });
+ });
+
+ it('keeps stable anchors through pruning and VACUUM and restores after the anchor is removed', async () => {
+ await withActivityDatabase(async (db) => {
+ db.exec("INSERT INTO messages VALUES ('anchor', 's-group', 'assistant', 500, NULL, NULL)");
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
+ db.exec("DELETE FROM messages WHERE id = 'old'; VACUUM;");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.map((lane) => lane.sessionId)).toEqual(['s-topic']);
+ db.exec("DELETE FROM messages WHERE id = 'anchor'; VACUUM;");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.map((lane) => lane.sessionId)).toEqual(['s-topic']);
+ db.exec("INSERT INTO messages VALUES ('new-after-pruning', 's-group', 'user', 1, NULL, NULL)");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.some((lane) => lane.sessionId === 's-group')).toBe(true);
+ });
+ });
+
+ it('restores remaining visible history when pruning invalidates its archived anchor', async () => {
+ await withActivityDatabase(async (db) => {
+ db.exec("INSERT INTO messages VALUES ('anchor', 's-group', 'assistant', 500, NULL, NULL)");
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
+ db.exec("DELETE FROM messages WHERE id = 'anchor'");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.some((lane) => lane.sessionId === 's-group')).toBe(true);
+ });
+ });
+
+ it('restores an archived empty lane on its first visible message', async () => {
+ await withActivityDatabase(async (db) => {
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.map((lane) => lane.sessionId)).toEqual(['s-group']);
+ db.exec("INSERT INTO messages VALUES ('first', 's-topic', 'user', 1, NULL, NULL)");
+ expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes.some((lane) => lane.sessionId === 's-topic')).toBe(true);
+ });
+ });
+
+ it('does not hide a message arriving between the archive snapshot and file commit', async () => {
+ await withActivityDatabase(async (db) => {
+ h.beforeArchive = () => db.exec("INSERT INTO messages VALUES ('during-save', 's-group', 'user', 100, NULL, NULL)");
+ const payload = await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
+ expect(payload.lanes.some((lane) => lane.sessionId === 's-group')).toBe(true);
+ });
+ });
+
// Only route/activity evidence may release archive capacity; dormant records
// must stay hidden and a later concurrent archive is checked by the store.
it('identifies only unlinked or superseded cutoffs for reclamation', async () => {
@@ -116,7 +215,7 @@ describe('botImLaneRuntime', () => {
it('does not reclaim a cutoff when activity lookup fails', async () => {
h.records.set(TELEGRAM.id, { ...TELEGRAM, archivedTaskRows: { 's-topic': 1 } });
- readLastActivityAt.mockRejectedValueOnce(new Error('activity unavailable'));
+ readArchiveActivity.mockImplementationOnce(async () => ({ messageId: 'group-message', hasNewActivity: false })).mockRejectedValueOnce(new Error('activity unavailable'));
await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
expect(h.reclaimable).toEqual([[]]);
});
@@ -131,39 +230,40 @@ describe('botImLaneRuntime', () => {
);
await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
expect(h.reclaimable).toEqual([routes === 'unavailable' ? [] : [{ connection: legacy, cutoffs }]]);
- expect(readLastActivityAt).toHaveBeenCalledTimes(routes === 'active' ? 512 : 0);
+ expect(readArchiveActivity.mock.calls.filter(([, archive]) => archive !== undefined)).toHaveLength(routes === 'active' ? 513 : 1);
expect(readActivity.mock.calls.every(([sessionId]) => !sessionId.startsWith('obsolete-'))).toBe(true);
expect(restartSession).not.toHaveBeenCalled();
});
it('rejects an account change during reclamation lookup before any archive write', async () => {
h.records.set(TELEGRAM.id, { ...TELEGRAM, archivedTaskRows: { 's-topic': 1, 's-main': 1 } });
- readLastActivityAt.mockImplementationOnce(async () => { h.owner = 'owner-b'; return ACTIVITY['s-topic'].lastActivityAt; });
+ readArchiveActivity.mockImplementationOnce(async () => ({ messageId: 'group-message', hasNewActivity: false })).mockImplementationOnce(async () => { h.owner = 'owner-b'; return { messageId: 'topic-message', hasNewActivity: true }; });
await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-group')).rejects.toThrow(/OWNER_CHANGED/);
expect(h.archived.size).toBe(0);
- expect(readLastActivityAt).toHaveBeenCalledTimes(1);
+ expect(readArchiveActivity).toHaveBeenCalledTimes(2);
expect(readActivity).not.toHaveBeenCalled();
});
// The real archive entry must not read list details for every old cutoff.
// In-memory SQLite keeps the query budget and visibility boundary observable.
- it('reclaims 512 linked markers with one activity query each and preserves cutoff visibility', async () => {
+ it.each(['legacy', 'anchored'] as const)('reclaims 512 %s linked markers with one activity query each and preserves cutoff visibility', async (format) => {
const sqlite = new Database(':memory:', { verbose: (statement) => h.sql.push(String(statement)) });
try {
sqlite.exec(`
CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, status TEXT, cleared_at INTEGER);
CREATE TABLE bot_session_links (session_id TEXT, bot_id TEXT, role TEXT, route_key TEXT, archived_at INTEGER);
- CREATE TABLE messages (session_id TEXT, role TEXT, created_at INTEGER, rewind_at INTEGER, agent_meta TEXT);
+ CREATE TABLE messages (id TEXT PRIMARY KEY, session_id TEXT, role TEXT, created_at INTEGER, rewind_at INTEGER, agent_meta TEXT);
`);
const addSession = sqlite.prepare("INSERT INTO sessions VALUES (?, 'bot', 'active', NULL)");
const addLink = sqlite.prepare("INSERT INTO bot_session_links VALUES (?, ?, 'channel', ?, NULL)");
- const addMessage = sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, NULL)');
+ const addMessage = sqlite.prepare('INSERT INTO messages VALUES (lower(hex(randomblob(16))), ?, ?, ?, ?, NULL)');
addSession.run('s-group');
addLink.run('s-group', TELEGRAM.botId, 'im:telegram:777:g:-1001');
// Same-millisecond ordering must still determine the refreshed list state.
addMessage.run('s-group', 'assistant', 5, null);
addMessage.run('s-group', 'error', 5, null);
const cutoffs: Record<string, number> = {};
+ const anchors: Record<string, BotImTaskArchiveActivity> = {};
const expected: Record<string, number> = {};
for (let i = 0; i < 512; i += 1) {
const sessionId = `old-${i}`;
@@ -171,10 +271,15 @@ describe('botImLaneRuntime', () => {
addSession.run(sessionId);
addLink.run(sessionId, 'old-bot', `im:telegram:777:g:old-${i}`);
const kind = i % 5;
+ if (format === 'anchored') {
+ const id = `anchor-${i}`;
+ sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, ?, NULL)').run(id, sessionId, 'user', 10, kind === 4 ? 10 : null);
+ anchors[sessionId] = { messageId: id, generation: '111111111111' };
+ }
if (kind < 3) {
addMessage.run(sessionId, ['user', 'assistant', 'error'][kind], 20, null);
expected[sessionId] = 10;
- } else if (kind === 3) {
+ } else if (kind === 3 && format === 'legacy') {
addMessage.run(sessionId, 'user', 10, null);
}
// None of these newer rows is visible activity that may release capacity.
@@ -182,7 +287,9 @@ describe('botImLaneRuntime', () => {
addMessage.run(sessionId, 'tool', 40, null);
addMessage.run(sessionId, 'context_rebuild', 50, 50);
}
- const legacy = { ...TELEGRAM, id: 'old-connection', botId: 'old-bot', archivedTaskRows: cutoffs };
+ const legacy = { ...TELEGRAM, id: 'old-connection', botId: 'old-bot', archivedTaskRows: cutoffs,
+ ...(format === 'anchored' ? { archivedTaskActivity: anchors } : {}),
+ };
h.records.set(legacy.id, legacy);
vi.mocked(getDbClient).mockReturnValue({ drizzle: drizzle(sqlite) } as unknown as DbClient);
__testing.setStore(null);
@@ -191,8 +298,8 @@ describe('botImLaneRuntime', () => {
await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
expect(h.reclaimable).toEqual([[{ connection: legacy, cutoffs: expected }]]);
const queries = h.sqlAtArchive.filter((statement) => /^select\b/i.test(statement));
- // Two scoped-link lookups plus at most one activity SELECT per old marker.
- expect(queries.length).toBeLessThanOrEqual(514);
+ // Two scoped-link lookups, one target snapshot and one SELECT per old marker.
+ expect(queries.length).toBeLessThanOrEqual(515);
expect(queries.some((statement) => /count\(|agent_meta|cleared_at|context_rebuild/i.test(statement))).toBe(false);
h.records.set(TELEGRAM.id, TELEGRAM);
expect((await listBotImConnectionLanes(TELEGRAM.id)).lanes).toMatchObject([
@@ -220,9 +327,7 @@ describe('botImLaneRuntime', () => {
// 列表归档不改变 session:后续消息仍在原任务上,既有用例不覆盖归档后的活动。
it('shows the same session again after new activity without creating or restarting it', async () => {
await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');
- readActivity.mockImplementationOnce(async () => ACTIVITY['s-main']);
- readActivity.mockImplementationOnce(async () => ACTIVITY['s-group']);
- readActivity.mockImplementationOnce(async () => activity({ lastActivityAt: Date.now() + 1 }));
+ readArchiveActivity.mockResolvedValueOnce({ messageId: 'new-message', hasNewActivity: true });
const payload = await listBotImConnectionLanes(TELEGRAM.id);
expect(payload.lanes.some((lane) => lane.sessionId === 's-topic')).toBe(true);
expect(await listLinks(TELEGRAM.botId)).toEqual(LINKS);
diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
index 4d22caccff..13e0e437cc 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
@@ -26,6 +26,7 @@ import { botProfiles } from '../../localDb/schema';
import { withBotProfileLocks } from '../../maker-ipc/botProfileLock';
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer';
import { throwIpcError } from '../../utils/ipcValidate';
+import { isIpcError } from '../../../shared/ipc-errors';
import { ownerScopedImSecrets } from '../ownerScopedStorage';
import { readWechatChannelSettings, writeWechatCompanionBinding } from '../wechat/channelSettings';
import {
@@ -791,7 +792,14 @@ export function registerBotImConnectionIpc(): void {
if (typeof p.sessionId !== 'string' || !/^[A-Za-z0-9_.:-]{1,200}$/.test(p.sessionId)) {
throwIpcError('INVALID_PARAMS', 'sessionId is invalid');
}
- return archiveBotImConnectionLane(p.id, p.sessionId, laneOptions);
+ return archiveBotImConnectionLane(p.id, p.sessionId, laneOptions).catch((error: unknown) => {
+ if (isIpcError(error)) throw error;
+ if (error instanceof Error && (error.message === 'ARCHIVE_CAPACITY_REACHED' || error.message === 'OWNER_CHANGED')) {
+ throwIpcError('PRECONDITION_FAILED', error.message);
+ }
+ // Storage errors can include owner-specific absolute paths; keep them in main.
+ throwIpcError('INTERNAL', 'LANE_ARCHIVE_FAILED');
+ });
});
}
diff --git a/apps/desktop/src/main/im/shared/botImConnectionStore.ts b/apps/desktop/src/main/im/shared/botImConnectionStore.ts
index 73245eb088..345ea08dc6 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionStore.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionStore.ts
@@ -19,6 +19,7 @@ import {
type BotImChannel,
type BotImConnectionRecord,
type BotImFeishuService,
+ type BotImTaskArchiveActivity,
} from '../../../shared/botImConnection.js';
const log = desktopMakerLogger.child('bot-im-connection-store');
@@ -61,6 +62,7 @@ function normalizeRecord(id: string, raw: unknown): Omit<BotImConnectionRecord,
: null;
const groupActivation = normalizeGroupActivation(r.groupActivation);
const archivedTaskRows = normalizeArchivedTaskRows(r.archivedTaskRows);
+ const archivedTaskActivity = normalizeArchivedTaskActivity(r.archivedTaskActivity, archivedTaskRows);
return {
botId: r.botId,
channel: r.channel,
@@ -69,6 +71,7 @@ function normalizeRecord(id: string, raw: unknown): Omit<BotImConnectionRecord,
botContextId,
...(groupActivation ? { groupActivation } : {}),
...(archivedTaskRows ? { archivedTaskRows } : {}),
+ ...(archivedTaskActivity ? { archivedTaskActivity } : {}),
};
}
@@ -81,6 +84,35 @@ function normalizeArchivedTaskRows(raw: unknown): Record<string, number> | undef
return Object.keys(rows).length ? rows : undefined;
}
+function normalizeArchivedTaskActivity(
+ raw: unknown,
+ cutoffs: Record<string, number> | undefined,
+): Record<string, BotImTaskArchiveActivity> | undefined {
+ if (!cutoffs || !raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+ const entries: [string, BotImTaskArchiveActivity][] = [];
+ for (const [id, value] of Object.entries(raw)) {
+ if (!Object.hasOwn(cutoffs, id) || !value || typeof value !== 'object' || Array.isArray(value)) continue;
+ const activity = value as Record<string, unknown>;
+ if (typeof activity.generation !== 'string' || !ID_PATTERN.test(activity.generation)) continue;
+ if (activity.messageId !== null && (typeof activity.messageId !== 'string'
+ || !activity.messageId.trim() || activity.messageId.length > 256)) continue;
+ entries.push([id, { messageId: activity.messageId as string | null, generation: activity.generation }]);
+ }
+ return entries.length ? Object.fromEntries(entries) : undefined;
+}
+
+function archivedCutoff(record: Pick<BotImConnectionRecord, 'archivedTaskRows'>, id: string): number | undefined {
+ return record.archivedTaskRows && Object.hasOwn(record.archivedTaskRows, id) ? record.archivedTaskRows[id] : undefined;
+}
+
+function archivedActivity(record: Pick<BotImConnectionRecord, 'archivedTaskActivity'>, id: string): BotImTaskArchiveActivity | undefined {
+ return record.archivedTaskActivity && Object.hasOwn(record.archivedTaskActivity, id) ? record.archivedTaskActivity[id] : undefined;
+}
+
+function sameArchiveActivity(left: BotImTaskArchiveActivity | undefined, right: BotImTaskArchiveActivity | undefined): boolean {
+ return left?.messageId === right?.messageId && left?.generation === right?.generation;
+}
+
/** 只认 chatId → 'always'; 'mention' 是缺省, 不落盘。未知值整条丢弃。 */
function normalizeGroupActivation(raw: unknown): Record<string, 'always'> | undefined {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
@@ -183,7 +215,9 @@ const MAX_ARCHIVED_TASK_BYTES = 64 * 1024;
function assertArchiveCapacity(connections: BotImConnectionDocument['connections']): void {
const count = Object.values(connections).reduce((sum, record) => sum + Object.keys(record.archivedTaskRows ?? {}).length, 0);
- const withoutArchives = Object.fromEntries(Object.entries(connections).map(([id, record]) => [id, { ...record, archivedTaskRows: undefined }]));
+ const withoutArchives = Object.fromEntries(Object.entries(connections).map(([id, record]) => [id, {
+ ...record, archivedTaskRows: undefined, archivedTaskActivity: undefined,
+ }]));
const archiveBytes = Buffer.byteLength(JSON.stringify({ connections }, null, 2), 'utf8')
- Buffer.byteLength(JSON.stringify({ connections: withoutArchives }, null, 2), 'utf8');
if (count > MAX_ARCHIVED_TASK_ROWS || archiveBytes > MAX_ARCHIVED_TASK_BYTES) {
@@ -201,6 +235,7 @@ export async function archiveBotImTaskRow(
expected: BotImConnectionRecord,
sessionId: string,
reclaimable: readonly BotImTaskArchiveCleanup[] = [],
+ activity?: BotImTaskArchiveActivity,
): Promise<BotImConnectionRecord | null> {
const owner = activeOwnerScopeKey();
let next: BotImConnectionRecord | null = null;
@@ -208,21 +243,40 @@ export async function archiveBotImTaskRow(
if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) throw new Error('OWNER_CHANGED');
const existing = current.value.connections[expected.id];
if (!existing || existing.botId !== expected.botId || existing.channel !== expected.channel || existing.botContextId !== expected.botContextId) return current.value;
+ if (activity && (archivedCutoff(existing, sessionId) !== archivedCutoff(expected, sessionId)
+ || !sameArchiveActivity(archivedActivity(existing, sessionId), archivedActivity(expected, sessionId)))) {
+ // A newer archive already won while this request was reading activity.
+ next = { id: expected.id, ...existing };
+ return current.value;
+ }
const connections = { ...current.value.connections };
for (const { connection, cutoffs } of reclaimable) {
const source = connections[connection.id];
if (!source || source.botId !== connection.botId || source.channel !== connection.channel || source.botContextId !== connection.botContextId) continue;
const archivedTaskRows = { ...source.archivedTaskRows };
+ const archivedTaskActivity = { ...source.archivedTaskActivity };
for (const [id, observedCutoff] of Object.entries(cutoffs)) {
// A newer archive made while activity was being read must survive.
- if (archivedTaskRows[id] === observedCutoff) delete archivedTaskRows[id];
+ if (archivedCutoff(source, id) === observedCutoff
+ && sameArchiveActivity(archivedActivity(source, id), archivedActivity(connection, id))) {
+ delete archivedTaskRows[id];
+ delete archivedTaskActivity[id];
+ }
}
- connections[connection.id] = { ...source, archivedTaskRows };
+ connections[connection.id] = {
+ ...source, archivedTaskRows,
+ archivedTaskActivity: Object.keys(archivedTaskActivity).length ? archivedTaskActivity : undefined,
+ };
}
const target = connections[expected.id];
+ const archivedTaskActivity = activity
+ ? { ...target.archivedTaskActivity, [sessionId]: activity }
+ : { ...target.archivedTaskActivity };
+ if (!activity) delete archivedTaskActivity[sessionId];
const merged = {
...target,
archivedTaskRows: { ...target.archivedTaskRows, [sessionId]: Date.now() },
+ archivedTaskActivity: Object.keys(archivedTaskActivity).length ? archivedTaskActivity : undefined,
};
connections[expected.id] = merged;
assertArchiveCapacity(connections);
diff --git a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
index c85059d410..15f8b5c66e 100644
--- a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
@@ -16,6 +16,7 @@
* 换一个干净的原生会话。这里只负责校验这条任务确实属于这条连接。
*/
+import { randomBytes } from 'node:crypto';
import { and, count, desc, eq, gt, inArray, isNull, sql } from 'drizzle-orm';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';
@@ -28,6 +29,7 @@ import type {
BotImConnectionLanesPayload,
BotImConnectionRecord,
BotImLaneKind,
+ BotImTaskArchiveActivity,
} from '../../../shared/botImConnection';
import { archiveBotImTaskRow, listBotImConnections, readBotImConnection, type BotImTaskArchiveCleanup } from './botImConnectionStore';
import { companionConnectionRouteKeyPrefix } from './imBotBindingRoute';
@@ -61,7 +63,10 @@ export interface BotImLaneActivity {
export interface BotImLaneStore {
listLinks(botId: string): Promise<BotImLaneLink[]>;
readActivity(sessionId: string): Promise<BotImLaneActivity>;
- readLastActivityAt(sessionId: string): Promise<number | null>;
+ readArchiveActivity(sessionId: string, archive?: number | BotImTaskArchiveActivity): Promise<{
+ messageId: string | null;
+ hasNewActivity: boolean;
+ }>;
}
export interface BotImLaneListOptions {
@@ -166,8 +171,27 @@ const dbLaneStore: BotImLaneStore = {
};
},
- async readLastActivityAt(sessionId) {
- return (await readLatestActivity(getDbClient().drizzle, sessionId))?.createdAt ?? null;
+ async readArchiveActivity(sessionId, archive) {
+ const db = getDbClient().drizzle;
+ if (typeof archive === 'number') {
+ // Older clients stored only a timestamp. Keep that format readable.
+ const latest = await readLatestActivity(db, sessionId);
+ return { messageId: null, hasNewActivity: latest !== undefined && latest.createdAt > archive };
+ }
+ // Persist a stable message identity, never SQLite's mutable hidden rowid.
+ // Resolve its current position in the same query, including rewound rows.
+ // If history pruning removed the anchor, any visible message restores the
+ // row: an invalid display boundary must not hide future activity forever.
+ const afterAnchor = archive?.messageId === undefined || archive.messageId === null
+ ? undefined
+ : sql`rowid > coalesce((select rowid from messages where id = ${archive.messageId} and session_id = ${sessionId}), 0)`;
+ const [latest] = await db.select({ id: messages.id }).from(messages).where(and(
+ eq(messages.sessionId, sessionId),
+ isNull(messages.rewindAt),
+ inArray(messages.role, ['user', 'assistant', 'error']),
+ afterAnchor,
+ )).orderBy(desc(sql<number>`rowid`)).limit(1);
+ return { messageId: latest?.id ?? null, hasNewActivity: latest !== undefined };
},
};
@@ -217,6 +241,12 @@ function requireRecord(id: string): BotImConnectionRecord {
return record;
}
+function archiveBoundary(record: BotImConnectionRecord, sessionId: string, cutoff: number): number | BotImTaskArchiveActivity {
+ return record.archivedTaskActivity && Object.hasOwn(record.archivedTaskActivity, sessionId)
+ ? record.archivedTaskActivity[sessionId]
+ : cutoff;
+}
+
export async function listBotImConnectionLanes(
id: string,
options: BotImLaneListOptions = {},
@@ -234,8 +264,13 @@ export async function listBotImConnectionLanes(
log.warn(`bot im connection ${id}: known groups unavailable: ${String(err)}`);
}
}
- const lanes = await Promise.all(
- links.map(async (link): Promise<BotImConnectionLane> => {
+ const rows = await Promise.all(
+ links.map(async (link): Promise<BotImConnectionLane | null> => {
+ const archivedAt = record.archivedTaskRows?.[link.sessionId];
+ if (typeof archivedAt === 'number') {
+ const activity = await store.readArchiveActivity(link.sessionId, archiveBoundary(record, link.sessionId, archivedAt));
+ if (!activity.hasNewActivity) return null;
+ }
const activity = await store.readActivity(link.sessionId);
const running = deps?.isTurnRunning(link.sessionId) === true;
const name =
@@ -256,15 +291,13 @@ export async function listBotImConnectionLanes(
};
}),
);
+ const lanes = rows.filter((lane): lane is BotImConnectionLane => lane !== null);
// 主人私聊在最前, 其余按最近活动倒序。
lanes.sort((a, b) => {
if (a.kind === 'owner-dm' || b.kind === 'owner-dm') return a.kind === 'owner-dm' ? -1 : 1;
return (b.lastActivityAt ?? 0) - (a.lastActivityAt ?? 0);
});
- return { connectionId: id, lanes: lanes.filter((lane) => {
- const archivedAt = record.archivedTaskRows?.[lane.sessionId];
- return typeof archivedAt !== 'number' || (lane.lastActivityAt !== null && lane.lastActivityAt > archivedAt);
- }) };
+ return { connectionId: id, lanes };
}
/**
@@ -309,6 +342,11 @@ export async function archiveBotImConnectionLane(
const link = links.find((item) => item.sessionId === sessionId);
assertCurrent();
if (!link) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');
+ // Fix the boundary before waiting on reclamation or the settings-file lock.
+ // A message arriving during those awaits must be able to restore the row.
+ const activity = await store.readArchiveActivity(sessionId);
+ assertCurrent();
+ const archiveActivity = { messageId: activity.messageId, generation: randomBytes(6).toString('hex') };
const reclaimable: BotImTaskArchiveCleanup[] = [];
// Capacity is shared by the owner. An empty old connection must not strand
// obsolete markers that block archiving in every other connection.
@@ -330,14 +368,14 @@ export async function archiveBotImConnectionLane(
cutoffs[archivedId] = cutoff;
continue;
}
- let lastActivityAt: number | null = null;
+ let hasNewActivity = false;
try {
- lastActivityAt = await store.readLastActivityAt(archivedId);
+ hasNewActivity = (await store.readArchiveActivity(archivedId, archiveBoundary(candidate, archivedId, cutoff))).hasNewActivity;
} catch {
// Missing activity evidence must not reveal a still-archived row.
}
assertCurrent();
- if (lastActivityAt !== null && lastActivityAt > cutoff) cutoffs[archivedId] = cutoff;
+ if (hasNewActivity) cutoffs[archivedId] = cutoff;
}
if (Object.keys(cutoffs).length) reclaimable.push({ connection: candidate, cutoffs });
}
@@ -346,7 +384,7 @@ export async function archiveBotImConnectionLane(
if (current.botId !== record.botId || current.botContextId !== record.botContextId || current.channel !== record.channel) {
throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');
}
- if (!await archiveBotImTaskRow(record, sessionId, reclaimable)) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');
+ if (!await archiveBotImTaskRow(record, sessionId, reclaimable, archiveActivity)) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');
assertCurrent();
const payload = await listBotImConnectionLanes(id, options);
assertCurrent();
diff --git a/apps/desktop/src/shared/botImConnection.ts b/apps/desktop/src/shared/botImConnection.ts
index c25af1ca71..f670d651b5 100644
--- a/apps/desktop/src/shared/botImConnection.ts
+++ b/apps/desktop/src/shared/botImConnection.ts
@@ -60,6 +60,12 @@ export type BotImConnectionStatus =
| { kind: 'offline'; appId: string }
| { kind: 'error'; reason: string; code?: string };
+/** Message identity and archive generation supplement legacy timestamp cutoffs. */
+export interface BotImTaskArchiveActivity {
+ messageId: string | null;
+ generation: string;
+}
+
/** 落盘记录: 不含凭证, 凭证按连接 id 前缀存在本机安全存储里。 */
export interface BotImConnectionRecord {
id: string;
@@ -78,6 +84,8 @@ export interface BotImConnectionRecord {
groupActivation?: Record<string, 'always'>;
/** List-only archive cutoffs. Never changes the referenced session or its routing. */
archivedTaskRows?: Record<string, number>;
+ /** Optional anchors for the same archived rows; older clients retain numeric cutoffs. */
+ archivedTaskActivity?: Record<string, BotImTaskArchiveActivity>;
}
export type BotImGroupActivationMode = 'mention' | 'always';