Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): bound and reclaim task archive metadata
xd6b484ce34aa1
diff --git a/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts b/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.tsindex 6a3c3e1214..1f4bceac7e 100644--- a/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts+++ b/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts@@ -71,7 +71,8 @@ const txMock = vi.fn(async () => ({}));let sqlite: Database.Database;let client: DbClient;-let commitRewindAtMessage: typeof import('../maker-orchestration/rewind').commitRewindAtMessage;+// Load the production module once during collection, outside per-case setup.+const { commitRewindAtMessage } = await import('../maker-orchestration/rewind');function insertSession(over: { clearedAt?: number | null } = {}): void {client.drizzle@@ -172,9 +173,6 @@ beforeEach(async () => {isGitRepo: false,isInsideWorktree: false,});- if (!commitRewindAtMessage) {- ({ commitRewindAtMessage } = await import('../maker-orchestration/rewind'));- }});afterEach(() => {diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.tsindex 4e97d69adc..bdcfd181e3 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts@@ -148,4 +148,66 @@ describe('bot im connection store', () => {h.owner = 'owner-b';expect(listBotImConnections()).toEqual([]);});++ // PR #6899 review: accumulated archive markers must not consume the shared+ // connection settings budget. Exercise the real file writer, not a mock.+ it.each(['count', 'bytes'] as const)('reserves connection settings space when archive %s capacity is reached', async (limit) => {+ const first = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });+ const second = await addBotImConnectionRecord({ botId: 'bot-b', channel: 'telegram' }, { id: () => 'bbbbbbbbbbbb' });+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));+ const count = limit === 'count' ? 512 : 330;+ for (const [index, id] of [first.id, second.id].entries()) {+ document.connections[id].archivedTaskRows = Object.fromEntries(Array.from({ length: count / 2 }, (_, i) => [+ `s-${index}-${i}${limit === 'bytes' ? '-'.repeat(185) : ''}`, 1,+ ]));+ }+ fs.writeFileSync(file(), JSON.stringify(document, null, 2));+ const before = fs.readFileSync(file(), 'utf8');+ await expect(archiveBotImTaskRow(first, 'new-session')).rejects.toThrow(/ARCHIVE_CAPACITY_REACHED/);+ expect(fs.readFileSync(file(), 'utf8')).toBe(before);+ await addBotImConnectionRecord({ botId: 'bot-c', channel: 'telegram' }, { id: () => 'cccccccccccc' });+ await setBotImConnectionGroupActivation(second.id, '-1001', 'always');+ expect(readBotImConnection(second.id)?.groupActivation).toEqual({ '-1001': 'always' });+ 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);+ 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);+ });++ it('serializes concurrent archives at the owner-wide limit', async () => {+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));+ document.connections[record.id].archivedTaskRows = Object.fromEntries(Array.from({ length: 511 }, (_, i) => [`existing-${i}`, 1]));+ fs.writeFileSync(file(), JSON.stringify(document));+ const results = await Promise.allSettled([archiveBotImTaskRow(record, 'new-a'), archiveBotImTaskRow(record, 'new-b')]);+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1);+ expect(Object.keys(readBotImConnection(record.id)?.archivedTaskRows ?? {})).toHaveLength(512);+ });++ it('reclaims only observed obsolete cutoffs and preserves a concurrent rearchive', async () => {+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });+ const document = JSON.parse(fs.readFileSync(file(), 'utf8'));+ 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 });+ expect(readBotImConnection(record.id)?.archivedTaskRows).toEqual({+ rearchived: 2, dormant: 1, 'new-session': 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__');+ await archiveBotImTaskRow(record, 'constructor');+ 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));+ });});diff --git a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.tsindex 27f6918ee6..7fbfa77bcf 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts@@ -12,6 +12,7 @@ const h = vi.hoisted(() => ({records: new Map<string, unknown>(),archived: new Set<string>(),owner: 'owner-a',+ reclaimable: [] as Record<string, number>[],}));vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));@@ -22,7 +23,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) => {+ archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: Record<string, number> = {}) => {+ h.reclaimable.push(reclaimable);const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() } };h.records.set(record.id, next);h.archived.add(sessionId);@@ -84,6 +86,7 @@ beforeEach(() => {vi.clearAllMocks();h.records.clear();h.archived.clear();+ h.reclaimable.length = 0;h.owner = 'owner-a';h.records.set(TELEGRAM.id, TELEGRAM);__testing.setStore({ listLinks, readActivity });@@ -91,6 +94,30 @@ beforeEach(() => {});describe('botImLaneRuntime', () => {+ // 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 () => {+ 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(restartSession).not.toHaveBeenCalled();+ });++ it('does not reclaim a cutoff when activity lookup fails', async () => {+ 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([{}]);+ });++ 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 } });+ readActivity.mockImplementationOnce(async () => { h.owner = 'owner-b'; return ACTIVITY['s-topic']; });+ await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-group')).rejects.toThrow(/OWNER_CHANGED/);+ expect(h.archived.size).toBe(0);+ expect(readActivity).toHaveBeenCalledTimes(1);+ });+// 用户确认的专线归档:既有覆盖只有重启;unit 注入存储验证列表移除与越权拒绝。it('archives only the selected connection row and preserves all session links', async () => {const payload = await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');diff --git a/apps/desktop/src/main/im/shared/botImConnectionStore.ts b/apps/desktop/src/main/im/shared/botImConnectionStore.tsindex ace094556a..82ee3f4aa5 100644--- a/apps/desktop/src/main/im/shared/botImConnectionStore.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionStore.ts@@ -176,10 +176,26 @@ export async function updateBotImConnectionRecord(return next;}+// Reserve most of the 256 KiB connection file for bindings/group preferences.+// This is an owner-wide budget, so adding connections cannot multiply it.+const MAX_ARCHIVED_TASK_ROWS = 512;+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 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) {+ throw new Error('ARCHIVE_CAPACITY_REACHED');+ }+}+/** 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>> = {},): Promise<BotImConnectionRecord | null> {const owner = activeOwnerScopeKey();let next: BotImConnectionRecord | null = null;@@ -187,12 +203,19 @@ 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 merged = {...existing,- archivedTaskRows: { ...existing.archivedTaskRows, [sessionId]: Date.now() },+ archivedTaskRows: { ...archivedTaskRows, [sessionId]: Date.now() },};+ const connections = { ...current.value.connections, [expected.id]: merged };+ assertArchiveCapacity(connections);next = { id: expected.id, ...merged };- return { connections: { ...current.value.connections, [expected.id]: merged } };+ return { connections };}, { preserveDefaults: true });if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) throw new Error('OWNER_CHANGED');return next;diff --git a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts b/apps/desktop/src/main/im/shared/botImLaneRuntime.tsindex 51ed6a9756..f47e60a1f6 100644--- a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts@@ -290,14 +290,33 @@ export async function archiveBotImConnectionLane(};assertCurrent();const record = requireRecord(id);- const link = (await listScopedLinks(record)).find((item) => item.sessionId === sessionId);+ const links = await listScopedLinks(record);+ 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;+ try {+ activity = await store.readActivity(id);+ } catch {+ // Missing activity evidence must not reveal a still-archived row.+ }+ assertCurrent();+ if (activity && activity.lastActivityAt !== null && activity.lastActivityAt > cutoff) reclaimable[id] = cutoff;+ }assertCurrent();const current = requireRecord(id);if (current.botId !== record.botId || current.botContextId !== record.botContextId || current.channel !== record.channel) {throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');}- if (!link) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');- if (!await archiveBotImTaskRow(record, sessionId)) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');+ if (!await archiveBotImTaskRow(record, sessionId, reclaimable)) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');assertCurrent();const payload = await listBotImConnectionLanes(id, options);assertCurrent();