🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf(agent): read a turn's invariant facts once in the send window (#19690)
Arvin Xu9b99536f011b
diff --git a/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts b/apps/server/src/services/aiAgent/__tests__/runFacts.test.tsnew file mode 100644index 00000000000..daefc1d26b0--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts@@ -0,0 +1,92 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createRunFacts } from '../runFacts';++const { getUserSettings, queryDeviceSystemInfo } = vi.hoisted(() => ({+ getUserSettings: vi.fn(),+ queryDeviceSystemInfo: vi.fn(),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: class {+ constructor(+ _db: unknown,+ readonly userId: string,+ ) {}+ getUserSettings = () => getUserSettings(this.userId);+ },+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { queryDeviceSystemInfo },+}));++const facts = () => createRunFacts({ db: {} as never, userId: 'owner-1', workspaceId: 'ws-1' });++beforeEach(() => {+ vi.clearAllMocks();+ getUserSettings.mockResolvedValue({ market: { accessToken: 'tok' } });+ queryDeviceSystemInfo.mockResolvedValue({ hostname: 'PC', supportedTools: [] });+});++describe('createRunFacts', () => {+ it('asks a routed device for its system info once per turn', async () => {+ const runFacts = facts();++ const [a, b] = await Promise.all([+ runFacts.deviceSystemInfo('dev-1'),+ runFacts.deviceSystemInfo('dev-1'),+ ]);+ await runFacts.deviceSystemInfo('dev-1');++ expect(queryDeviceSystemInfo).toHaveBeenCalledTimes(1);+ expect(a).toBe(b);+ // A personal device must not receive the workspace id.+ expect(queryDeviceSystemInfo).toHaveBeenCalledWith('owner-1', 'dev-1', undefined);+ });++ it('keeps the workspace and personal scopes of the same device apart', async () => {+ const runFacts = facts();++ await runFacts.deviceSystemInfo('dev-1', 'workspace');+ await runFacts.deviceSystemInfo('dev-1', 'personal');++ expect(queryDeviceSystemInfo).toHaveBeenCalledTimes(2);+ expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'owner-1', 'dev-1', 'ws-1');+ expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(2, 'owner-1', 'dev-1', undefined);+ });++ it('remembers an unreachable device rather than asking again', async () => {+ queryDeviceSystemInfo.mockResolvedValue(undefined);+ const runFacts = facts();++ await expect(runFacts.deviceSystemInfo('offline')).resolves.toBeUndefined();+ await expect(runFacts.deviceSystemInfo('offline')).resolves.toBeUndefined();+ expect(queryDeviceSystemInfo).toHaveBeenCalledTimes(1);+ });++ it('reads the settings row once per user, and a visitor separately', async () => {+ const runFacts = facts();++ await runFacts.userSettings();+ await runFacts.userSettings();+ await runFacts.userSettings('visitor-1');++ expect(getUserSettings).toHaveBeenCalledTimes(2);+ expect(getUserSettings).toHaveBeenNthCalledWith(1, 'owner-1');+ expect(getUserSettings).toHaveBeenNthCalledWith(2, 'visitor-1');+ });++ it('keeps a failed settings read a failure, and does not retry it', async () => {+ getUserSettings.mockRejectedValue(new Error('database unavailable'));+ const runFacts = facts();++ // Swallowing this would read as "nothing is set", which `execAgent` turns+ // into memory enabled — the opposite of the conservative default a failed+ // read must keep.+ await expect(runFacts.userSettings()).rejects.toThrow('database unavailable');+ await expect(runFacts.userSettings()).rejects.toThrow('database unavailable');+ expect(getUserSettings).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex d5893be1a51..cbb3a9073d5 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -69,6 +69,7 @@ import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';import { startOperation } from './pipeline/startOperation';import { discoverTools } from './pipeline/toolDiscovery';import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';+import { createRunFacts, type RunFacts } from './runFacts';import { applyShareGateToAgentConfig } from './shareGate';import type { SubAgentRunDeps } from './subAgentRuns';import { execAgentMember, execAgentThreadRun } from './subAgentRuns';@@ -204,17 +205,17 @@ export class AiAgentService {};}- private async getMarketService(): Promise<MarketService> {+ private async getMarketService(runFacts?: RunFacts): Promise<MarketService> {if (this._marketService) return this._marketService;- let accessToken: string | undefined;- try {- const userModel = new UserModel(this.db, this.userId);- const settings = await userModel.getUserSettings();- accessToken = (settings?.market as any)?.accessToken;- } catch {- // non-fatal — MarketService will fall back to trustedClientToken- }+ // The turn's fact reader already holds this row when a run is underway+ // (`execAgent` asks it for the memory / timezone settings too); callers+ // outside a run read it themselves.+ // Non-fatal either way — MarketService falls back to trustedClientToken.+ const settings = await (+ runFacts ? runFacts.userSettings() : new UserModel(this.db, this.userId).getUserSettings()+ ).catch(() => undefined);+ const accessToken = (settings?.market as any)?.accessToken;this._marketService = new MarketService({accessToken,@@ -1028,6 +1029,14 @@ export class AiAgentService {// (`pipeline/*`). Built after the turn rows exist so every stage sees the// persisted anchors; `agentConfig` stays the same mutable object so stage// systemRole appends remain visible to `createOperation` below.+ // One reader for the facts that cannot change within this turn, so the+ // send window asks the routed device and the user's row once each.+ const runFacts = createRunFacts({+ db: this.db,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+const runContext: ExecRunContext = {agentConfig,appContext,@@ -1040,6 +1049,7 @@ export class AiAgentService {prompt,provider,resolvedAgentId,+ runFacts,shareGate,topicId,trigger,@@ -1051,7 +1061,7 @@ export class AiAgentService {{bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),db: this.db,- getMarketService: () => this.getMarketService(),+ getMarketService: () => this.getMarketService(runFacts),messageModel: this.messageModel,resolveDeviceWorkspaceId: (deviceId) => this.resolveDeviceWorkspaceId(deviceId),topicModel: this.topicModel,@@ -1089,8 +1099,7 @@ export class AiAgentService {let enableExpertise = false;let userTimezone: string | undefined;try {- const userModel = new UserModel(this.db, this.userId);- const settings = await userModel.getUserSettings();+ const settings = await runFacts.userSettings();const memorySettings = settings?.memory as { enabled?: boolean } | undefined;globalMemoryEnabled = agentMemoryEnabled ?? memorySettings?.enabled !== false;@@ -1102,10 +1111,7 @@ export class AiAgentService {// `allowReadMemory`), but the timezone has no such gate and must not// leak the creator's own setting into a visitor's turn.if (shareGate) {- const visitorSettings = await new UserModel(- this.db,- shareGate.visitorUserId,- ).getUserSettings();+ const visitorSettings = await runFacts.userSettings(shareGate.visitorUserId);const visitorGeneralSettings = visitorSettings?.general as{ timezone?: string } | undefined;userTimezone = visitorGeneralSettings?.timezone;@@ -1171,7 +1177,7 @@ export class AiAgentService {connectorModel: this.connectorModel,connectorToolModel: this.connectorToolModel,db: this.db,- getMarketService: () => this.getMarketService(),+ getMarketService: () => this.getMarketService(runFacts),messageModel: this.messageModel,pluginModel: this.pluginModel,userId: this.userId,diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 2e9ceb786d0..138fa84d482 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -395,14 +395,10 @@ export const prepareOperation = async (): Promise<Record<string, string>> => {if (!deviceId) return {};try {- // Scope the gateway lookup to the principal that owns the connection:- // workspace devices need workspaceId; personal devices (including a- // workspace run routed to the caller's own machine) must not.- const systemInfo = await deviceGateway.queryDeviceSystemInfo(- deps.userId,- deviceId,- activeDeviceScope === 'workspace' ? deps.workspaceId : undefined,- );+ // Tool discovery already asked this device for the same answer earlier+ // in the send window, so the run's fact reader serves it from there+ // (it also owns the personal / workspace scoping of the lookup).+ const systemInfo = await ctx.runFacts.deviceSystemInfo(deviceId, activeDeviceScope);if (!systemInfo) return {};const device = onlineDevices.find((d) => d.deviceId === deviceId);log('execAgent: fetched device system info for %s', deviceId);diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 2906da368b6..8222e27a387 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -813,11 +813,7 @@ export const discoverTools = async (const supportedDeviceTools = systemInfoDeviceId? (await traceDiscoveryStage('device_system_info', () =>- deviceGateway.queryDeviceSystemInfo(- deps.userId,- systemInfoDeviceId,- activeDeviceScope === 'workspace' ? deps.workspaceId : undefined,- ),+ ctx.runFacts.deviceSystemInfo(systemInfoDeviceId, activeDeviceScope),))?.supportedTools: undefined;diff --git a/apps/server/src/services/aiAgent/runFacts.ts b/apps/server/src/services/aiAgent/runFacts.tsnew file mode 100644index 00000000000..cad1d52f47e--- /dev/null+++ b/apps/server/src/services/aiAgent/runFacts.ts@@ -0,0 +1,92 @@+import type { LobeChatDatabase } from '@lobechat/database';+import debug from 'debug';++import { UserModel } from '@/database/models/user';+import { deviceGateway, type DeviceSystemInfo } from '@/server/services/deviceGateway';++const log = debug('lobe-server:ai-agent-service');++type UserSettings = Awaited<ReturnType<UserModel['getUserSettings']>>;++export interface RunFactsSource {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * Facts that cannot change within one turn, read once and shared by every+ * stage of it. The send window (tool discovery, then operation prep) asked+ * some of them twice: a routed device answered the same system-info RPC over+ * its WebSocket, and the user's settings row was read once for the market+ * access token behind LobeHub skills and again for the memory and timezone+ * settings. Each of those is a round trip between the user pressing send and+ * the operation existing.+ *+ * This only remembers answers, including the unhappy ones: an unreachable+ * device reports no system info and is not asked again, and a settings read+ * that failed keeps failing for the turn rather than passing as an empty row.+ */+export interface RunFacts {+ /** System info of a device routed for this run; one RPC per device and scope. */+ deviceSystemInfo: (+ deviceId: string,+ scope?: 'personal' | 'workspace',+ ) => Promise<DeviceSystemInfo | undefined>;+ /**+ * A user's settings row. Asked for the market access token when resolving+ * LobeHub skills and for the memory / timezone settings of the turn.+ * Defaults to the run's own user; a share-visitor turn asks for the visitor.+ *+ * Rejects when the read fails, so a caller can tell that apart from a row+ * that simply has nothing set; the failure is remembered, not retried.+ */+ userSettings: (userId?: string) => Promise<UserSettings>;+}++/** Remember the promise, not the value, so concurrent callers share one read. */+const memoize = <T>(read: (key: string) => Promise<T>) => {+ const pending = new Map<string, Promise<T>>();+ return (key: string): Promise<T> => {+ const hit = pending.get(key);+ if (hit) return hit;+ const promise = read(key);+ pending.set(key, promise);+ return promise;+ };+};++const KEY_SEPARATOR = String.fromCodePoint(0);++export const createRunFacts = ({ db, userId, workspaceId }: RunFactsSource): RunFacts => {+ const readDeviceSystemInfo = memoize(async (key: string) => {+ const [deviceId, scope] = key.split(KEY_SEPARATOR);+ // Workspace devices need the workspace id to resolve their connection;+ // personal ones (including a workspace run routed to the caller's own+ // machine) must not receive it.+ return deviceGateway.queryDeviceSystemInfo(+ userId,+ deviceId,+ scope === 'workspace' ? workspaceId : undefined,+ );+ });++ // A failed read stays a failure: callers distinguish it from an empty row.+ // `execAgent` leaves memory injection at its conservative default when this+ // rejects, which swallowing here would silently turn into "memory enabled".+ // The rejected promise is remembered too, so one turn does not retry.+ const readUserSettings = memoize(async (targetUserId: string) => {+ try {+ return await new UserModel(db, targetUserId).getUserSettings();+ } catch (error) {+ log('runFacts: failed to read settings for %s: %O', targetUserId, error);+ throw error;+ }+ });++ return {+ deviceSystemInfo: (deviceId, scope) =>+ readDeviceSystemInfo([deviceId, scope ?? 'personal'].join(KEY_SEPARATOR)),+ userSettings: (targetUserId) => readUserSettings(targetUserId ?? userId),+ };+};diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex b28c93b2c53..65712b03963 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -16,6 +16,7 @@ import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';import type { DeviceAccessReason } from './deviceAccessPolicy';+import type { RunFacts } from './runFacts';import type { AgentShareGate } from './shareGate';/**@@ -45,6 +46,11 @@ export interface ExecRunContext {provider: string;/** The actual executing agent row id resolved from id/slug. */resolvedAgentId: string;+ /**+ * Turn-invariant facts (device system info, the user's row), read once and+ * shared by every stage of the send window.+ */+ runFacts: RunFacts;/*** Shared-agent visitor gate for this run, mirrored from* {@link InternalExecAgentParams.shareGate} so every extracted pipeline stage