Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(im): use lightweight activity reads for archive cleanup
xd7fa4b9c27a68
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.tsindex 4d101d0c35..d7e700d601 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts@@ -5,7 +5,11 @@* - 「重新开始」只接受这条连接自己的任务, 渲染端传来的其它任务 id 不会被重启。*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import Database from 'better-sqlite3';+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 { BotImTaskArchiveCleanup } from '../botImConnectionStore';@@ -14,6 +18,8 @@ const h = vi.hoisted(() => ({archived: new Set<string>(),owner: 'owner-a',reclaimable: [] as (readonly BotImTaskArchiveCleanup[])[],+ sql: [] as string[],+ sqlAtArchive: [] as string[],}));vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));@@ -21,11 +27,11 @@ vi.mock('../../../logger', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),}));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,listBotImConnections: () => [...h.records.values()] as BotImConnectionRecord[],archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string, reclaimable: readonly BotImTaskArchiveCleanup[] = []) => {+ h.sqlAtArchive.push(...h.sql);h.reclaimable.push(reclaimable);const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() } };h.records.set(record.id, next);@@ -81,6 +87,7 @@ 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 restartSession = vi.fn<(sessionId: string) => Promise<void>>(async () => {});const knownGroups = vi.fn(async () => [{ chatId: '-1001', chatName: 'Launch crew' }]);@@ -89,9 +96,11 @@ beforeEach(() => {h.records.clear();h.archived.clear();h.reclaimable.length = 0;+ h.sql.length = 0;+ h.sqlAtArchive.length = 0;h.owner = 'owner-a';h.records.set(TELEGRAM.id, TELEGRAM);- __testing.setStore({ listLinks, readActivity });+ __testing.setStore({ listLinks, readActivity, readLastActivityAt });configureBotImLaneRuntime({ isTurnRunning: (id) => id === 's-guest', restartSession });});@@ -107,7 +116,7 @@ describe('botImLaneRuntime', () => {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'));+ readLastActivityAt.mockRejectedValueOnce(new Error('activity unavailable'));await archiveBotImConnectionLane(TELEGRAM.id, 's-group');expect(h.reclaimable).toEqual([[]]);});@@ -122,15 +131,76 @@ 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(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 } });- readActivity.mockImplementationOnce(async () => { h.owner = 'owner-b'; return ACTIVITY['s-topic']; });+ readLastActivityAt.mockImplementationOnce(async () => { h.owner = 'owner-b'; return ACTIVITY['s-topic'].lastActivityAt; });await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-group')).rejects.toThrow(/OWNER_CHANGED/);expect(h.archived.size).toBe(0);- expect(readActivity).toHaveBeenCalledTimes(1);+ expect(readLastActivityAt).toHaveBeenCalledTimes(1);+ 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 () => {+ 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);+ `);+ 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)');+ 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 expected: Record<string, number> = {};+ for (let i = 0; i < 512; i += 1) {+ const sessionId = `old-${i}`;+ cutoffs[sessionId] = 10;+ addSession.run(sessionId);+ addLink.run(sessionId, 'old-bot', `im:telegram:777:g:old-${i}`);+ const kind = i % 5;+ if (kind < 3) {+ addMessage.run(sessionId, ['user', 'assistant', 'error'][kind], 20, null);+ expected[sessionId] = 10;+ } else if (kind === 3) {+ addMessage.run(sessionId, 'user', 10, null);+ }+ // None of these newer rows is visible activity that may release capacity.+ addMessage.run(sessionId, 'assistant', 30, 30);+ addMessage.run(sessionId, 'tool', 40, null);+ addMessage.run(sessionId, 'context_rebuild', 50, 50);+ }+ const legacy = { ...TELEGRAM, id: 'old-connection', botId: 'old-bot', archivedTaskRows: cutoffs };+ h.records.set(legacy.id, legacy);+ vi.mocked(getDbClient).mockReturnValue({ drizzle: drizzle(sqlite) } as unknown as DbClient);+ __testing.setStore(null);+ h.sql.length = 0;++ 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);+ 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([+ { sessionId: 's-group', state: 'failed', lastActivityAt: 5 },+ ]);+ } finally {+ sqlite.close();+ }});// 用户确认的专线归档:既有覆盖只有重启;unit 注入存储验证列表移除与越权拒绝。diff --git a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts b/apps/desktop/src/main/im/shared/botImLaneRuntime.tsindex 4148c9a885..c85059d410 100644--- a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts@@ -61,6 +61,7 @@ export interface BotImLaneActivity {export interface BotImLaneStore {listLinks(botId: string): Promise<BotImLaneLink[]>;readActivity(sessionId: string): Promise<BotImLaneActivity>;+ readLastActivityAt(sessionId: string): Promise<number | null>;}export interface BotImLaneListOptions {@@ -88,6 +89,21 @@ function readOrigin(agentMeta: string | null): BotImLaneActivity['origin'] {}}+/** Keep archive reclamation and list activity on the same visible-message boundary. */+async function readLatestActivity(db: ReturnType<typeof getDbClient>['drizzle'], sessionId: string) {+ const [latest] = await db+ .select({ role: messages.role, createdAt: messages.createdAt })+ .from(messages)+ .where(and(+ eq(messages.sessionId, sessionId),+ isNull(messages.rewindAt),+ inArray(messages.role, ['user', 'assistant', 'error']),+ ))+ .orderBy(desc(messages.createdAt), desc(sql<number>`rowid`))+ .limit(1);+ return latest;+}+const dbLaneStore: BotImLaneStore = {async listLinks(botId) {const rows = await getDbClient()@@ -129,12 +145,7 @@ const dbLaneStore: BotImLaneStore = {.where(and(eq(messages.sessionId, sessionId), eq(messages.role, 'context_rebuild'))).orderBy(desc(messages.createdAt), desc(messageRowid)).limit(1);- const [latest] = await db- .select({ role: messages.role, createdAt: messages.createdAt })- .from(messages)- .where(and(visible, inArray(messages.role, ['user', 'assistant', 'error'])))- .orderBy(desc(messages.createdAt), desc(messageRowid))- .limit(1);+ const latest = await readLatestActivity(db, sessionId);const [lastUser] = await db.select({ agentMeta: messages.agentMeta }).from(messages)@@ -154,6 +165,10 @@ const dbLaneStore: BotImLaneStore = {origin: readOrigin(lastUser?.agentMeta ?? null),};},++ async readLastActivityAt(sessionId) {+ return (await readLatestActivity(getDbClient().drizzle, sessionId))?.createdAt ?? null;+ },};let store: BotImLaneStore = dbLaneStore;@@ -315,14 +330,14 @@ export async function archiveBotImConnectionLane(cutoffs[archivedId] = cutoff;continue;}- let activity: BotImLaneActivity | null = null;+ let lastActivityAt: number | null = null;try {- activity = await store.readActivity(archivedId);+ lastActivityAt = await store.readLastActivityAt(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 (lastActivityAt !== null && lastActivityAt > cutoff) cutoffs[archivedId] = cutoff;}if (Object.keys(cutoffs).length) reclaimable.push({ connection: candidate, cutoffs });}