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): reclaim stale archives across connections

xdb17cfa6519d4
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 bdcfd181e3..7c6d493ee5 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts
@@ -171,11 +171,12 @@ describe('bot im connection store', () => {
expect(listBotImConnections()).toHaveLength(3);
const obsolete = Object.fromEntries(Object.keys(document.connections[first.id].archivedTaskRows)
.slice(0, limit === 'count' ? 1 : count / 2).map((id) => [id, 1]));
- await archiveBotImTaskRow(first, 'new-session', obsolete);
+ await archiveBotImTaskRow(second, 'new-session', [{ connection: first, cutoffs: obsolete }]);
const archives = readBotImConnection(first.id)?.archivedTaskRows;
- expect(archives?.['new-session']).toEqual(expect.any(Number));
for (const id of Object.keys(obsolete)) expect(archives?.[id]).toBeUndefined();
- expect(readBotImConnection(second.id)?.archivedTaskRows).toEqual(document.connections[second.id].archivedTaskRows);
+ expect(readBotImConnection(second.id)?.archivedTaskRows).toEqual({
+ ...document.connections[second.id].archivedTaskRows, 'new-session': expect.any(Number),
+ });
});
it('serializes concurrent archives at the owner-wide limit', async () => {
@@ -195,12 +196,23 @@ describe('bot im connection store', () => {
document.connections[record.id].archivedTaskRows = { obsolete: 1, rearchived: 2, dormant: 1 };
fs.writeFileSync(file(), JSON.stringify(document));
// The runtime observed cutoff=1 before another writer rearchived this row.
- await archiveBotImTaskRow(record, 'new-session', { obsolete: 1, rearchived: 1 });
+ await archiveBotImTaskRow(record, 'new-session', [{ connection: record, cutoffs: { obsolete: 1, rearchived: 1 } }]);
expect(readBotImConnection(record.id)?.archivedTaskRows).toEqual({
rearchived: 2, dormant: 1, 'new-session': expect.any(Number),
});
});
+ it('preserves another connection whose binding changed during reclamation lookup', async () => {
+ const first = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });
+ const second = await addBotImConnectionRecord({ botId: 'bot-b', channel: 'telegram' }, { id: () => 'bbbbbbbbbbbb' });
+ await archiveBotImTaskRow(first, 'old-session');
+ const observed = readBotImConnection(first.id)!;
+ await updateBotImConnectionRecord(first.id, { botContextId: 'new-binding' });
+ await archiveBotImTaskRow(second, 'new-session', [{ connection: observed, cutoffs: observed.archivedTaskRows! }]);
+ expect(readBotImConnection(first.id)?.archivedTaskRows).toEqual(observed.archivedTaskRows);
+ expect(readBotImConnection(second.id)?.archivedTaskRows?.['new-session']).toEqual(expect.any(Number));
+ });
+
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__');
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 7fbfa77bcf..4d101d0c35 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts
@@ -7,12 +7,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { BotImConnectionRecord } from '../../../../shared/botImConnection';
+import type { BotImTaskArchiveCleanup } from '../botImConnectionStore';
const h = vi.hoisted(() => ({
records: new Map<string, unknown>(),
archived: new Set<string>(),
owner: 'owner-a',
- reclaimable: [] as Record<string, number>[],
+ reclaimable: [] as (readonly BotImTaskArchiveCleanup[])[],
}));
vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));
@@ -23,7 +24,8 @@ vi.mock('../../../localDb/client/current', () => ({ getDbClient: vi.fn() }));
vi.mock('../../../localDb/schema', () => ({ botSessionLinks: {}, messages: {}, sessions: {} }));
vi.mock('../botImConnectionStore', () => ({
readBotImConnection: (id: string) => h.records.get(id) ?? null,
- archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: Record<string, number> = {}) => {
+ listBotImConnections: () => [...h.records.values()] as BotImConnectionRecord[],
+ archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: readonly BotImTaskArchiveCleanup[] = []) => {
h.reclaimable.push(reclaimable);
const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() } };
h.records.set(record.id, next);
@@ -99,7 +101,7 @@ describe('botImLaneRuntime', () => {
it('identifies only unlinked or superseded cutoffs for reclamation', async () => {
h.records.set(TELEGRAM.id, { ...TELEGRAM, archivedTaskRows: { 's-main': 200, 's-topic': 1, removed: 1 } });
await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
- expect(h.reclaimable).toEqual([{ 's-topic': 1, removed: 1 }]);
+ expect(h.reclaimable).toEqual([[{ connection: expect.objectContaining({ id: TELEGRAM.id }), cutoffs: { 's-topic': 1, removed: 1 } }]]);
expect(restartSession).not.toHaveBeenCalled();
});
@@ -107,7 +109,20 @@ describe('botImLaneRuntime', () => {
h.records.set(TELEGRAM.id, { ...TELEGRAM, archivedTaskRows: { 's-topic': 1 } });
readActivity.mockRejectedValueOnce(new Error('activity unavailable'));
await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
- expect(h.reclaimable).toEqual([{}]);
+ expect(h.reclaimable).toEqual([[]]);
+ });
+
+ it.each(['empty', 'active', 'unavailable'] as const)('checks another connection with %s routes before applying the shared archive budget', async (routes) => {
+ const cutoffs = Object.fromEntries(Array.from({ length: 512 }, (_, i) => [`obsolete-${i}`, 1]));
+ const legacy = { ...TELEGRAM, id: 'old-connection', botId: 'old-bot', archivedTaskRows: cutoffs };
+ h.records.set(legacy.id, legacy);
+ if (routes === 'unavailable') listLinks.mockResolvedValueOnce(LINKS).mockRejectedValueOnce(new Error('routes unavailable'));
+ if (routes === 'active') listLinks.mockResolvedValueOnce(LINKS).mockResolvedValueOnce(
+ Object.keys(cutoffs).map((sessionId, i) => ({ sessionId, role: 'channel', routeKey: `im:telegram:777:g:-${1000 + i}` })),
+ );
+ await archiveBotImConnectionLane(TELEGRAM.id, 's-group');
+ expect(h.reclaimable).toEqual([routes === 'unavailable' ? [] : [{ connection: legacy, cutoffs }]]);
+ expect(restartSession).not.toHaveBeenCalled();
});
it('rejects an account change during reclamation lookup before any archive write', async () => {
diff --git a/apps/desktop/src/main/im/shared/botImConnectionStore.ts b/apps/desktop/src/main/im/shared/botImConnectionStore.ts
index 82ee3f4aa5..73245eb088 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionStore.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionStore.ts
@@ -191,11 +191,16 @@ function assertArchiveCapacity(connections: BotImConnectionDocument['connections
}
}
+export interface BotImTaskArchiveCleanup {
+ connection: BotImConnectionRecord;
+ cutoffs: Readonly<Record<string, number>>;
+}
+
/** Archive a row in one connection, without touching its session or route link. */
export async function archiveBotImTaskRow(
expected: BotImConnectionRecord,
sessionId: string,
- reclaimable: Readonly<Record<string, number>> = {},
+ reclaimable: readonly BotImTaskArchiveCleanup[] = [],
): Promise<BotImConnectionRecord | null> {
const owner = activeOwnerScopeKey();
let next: BotImConnectionRecord | null = null;
@@ -203,16 +208,23 @@ 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;
- const archivedTaskRows = { ...existing.archivedTaskRows };
- for (const [id, observedCutoff] of Object.entries(reclaimable)) {
- // A newer archive made while activity was being read must survive.
- if (archivedTaskRows[id] === observedCutoff) delete archivedTaskRows[id];
+ 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 };
+ 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];
+ }
+ connections[connection.id] = { ...source, archivedTaskRows };
}
+ const target = connections[expected.id];
const merged = {
- ...existing,
- archivedTaskRows: { ...archivedTaskRows, [sessionId]: Date.now() },
+ ...target,
+ archivedTaskRows: { ...target.archivedTaskRows, [sessionId]: Date.now() },
};
- const connections = { ...current.value.connections, [expected.id]: merged };
+ connections[expected.id] = merged;
assertArchiveCapacity(connections);
next = { id: expected.id, ...merged };
return { connections };
diff --git a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
index f47e60a1f6..4148c9a885 100644
--- a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts
@@ -29,7 +29,7 @@ import type {
BotImConnectionRecord,
BotImLaneKind,
} from '../../../shared/botImConnection';
-import { archiveBotImTaskRow, readBotImConnection } from './botImConnectionStore';
+import { archiveBotImTaskRow, listBotImConnections, readBotImConnection, type BotImTaskArchiveCleanup } from './botImConnectionStore';
import { companionConnectionRouteKeyPrefix } from './imBotBindingRoute';
const log = createLogger('im:bot-lanes');
@@ -294,22 +294,37 @@ export async function archiveBotImConnectionLane(
const link = links.find((item) => item.sessionId === sessionId);
assertCurrent();
if (!link) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');
- const linkedIds = new Set(links.map((item) => item.sessionId));
- const reclaimable: Record<string, number> = Object.create(null);
- for (const [id, cutoff] of Object.entries(record.archivedTaskRows ?? {})) {
- if (id === sessionId) continue;
- if (!linkedIds.has(id)) {
- reclaimable[id] = cutoff;
- continue;
- }
- let activity: BotImLaneActivity | null = null;
+ 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.
+ for (const candidate of [record, ...listBotImConnections().filter((item) => item.id !== id)]) {
+ if (!candidate.archivedTaskRows) continue;
+ let candidateLinks: ScopedLink[];
try {
- activity = await store.readActivity(id);
+ candidateLinks = candidate.id === id ? links : await listScopedLinks(candidate);
} catch {
- // Missing activity evidence must not reveal a still-archived row.
+ assertCurrent();
+ continue; // A failed route lookup is not evidence that its rows are gone.
}
assertCurrent();
- if (activity && activity.lastActivityAt !== null && activity.lastActivityAt > cutoff) reclaimable[id] = cutoff;
+ const linkedIds = new Set(candidateLinks.map((item) => item.sessionId));
+ const cutoffs: Record<string, number> = Object.create(null);
+ for (const [archivedId, cutoff] of Object.entries(candidate.archivedTaskRows)) {
+ if (candidate.id === id && archivedId === sessionId) continue;
+ if (!linkedIds.has(archivedId)) {
+ cutoffs[archivedId] = cutoff;
+ continue;
+ }
+ let activity: BotImLaneActivity | null = null;
+ try {
+ activity = await store.readActivity(archivedId);
+ } catch {
+ // Missing activity evidence must not reveal a still-archived row.
+ }
+ assertCurrent();
+ if (activity && activity.lastActivityAt !== null && activity.lastActivityAt > cutoff) cutoffs[archivedId] = cutoff;
+ }
+ if (Object.keys(cutoffs).length) reclaimable.push({ connection: candidate, cutoffs });
}
assertCurrent();
const current = requireRecord(id);