🤯 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(web): stop redundant client polling (#23745)
YuTengjingdce3ec5a52ba
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex b0efbdf1068..7b0557dbd73 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -311,8 +311,7 @@ export default class GatewayConnectionCtr extends ControllerModule {hostname: string;platform: string;}> {- // Signed in, report the stable id the gateway registers — not the pre-connect- // fallback — so the renderer's "this device" matches the pins it writes.+ // Report the gateway's stable id, not the pre-connect fallback, so "this device" matches pins.const stableId = await this.service.resolveCurrentDeviceId().catch(() => undefined);const info = { ...this.service.getDeviceInfo(), ...(stableId && { deviceId: stableId }) };try {@@ -328,6 +327,7 @@ export default class GatewayConnectionCtr extends ControllerModule {deviceId: info.deviceId,headers,serverUrl,+ userId: this.remoteServerConfigCtr.getDesktopBootstrapIdentity().userId,});}} catch (error) {diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex ac70ef40709..450cc11c11e 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -342,6 +342,7 @@ const mockMcpCtr = {const mockRemoteServerConfigCtr = {getAccessToken: vi.fn().mockResolvedValue('mock-access-token'),+ getDesktopBootstrapIdentity: () => ({ userId: 'user-a' }),getRemoteServerConfig: vi.fn().mockResolvedValue({active: true,remoteServerUrl: 'https://server.example.com',@@ -2857,7 +2858,6 @@ describe('GatewayConnectionCtr', () => {},}),);-const info = await ctr.getDeviceInfo();expect(info.deviceId).toBe('my-device');diff --git a/apps/desktop/src/main/services/__tests__/deviceArchitectureBackfill.test.ts b/apps/desktop/src/main/services/__tests__/deviceArchitectureBackfill.test.tsindex 289a76d1464..e962fb44559 100644--- a/apps/desktop/src/main/services/__tests__/deviceArchitectureBackfill.test.ts+++ b/apps/desktop/src/main/services/__tests__/deviceArchitectureBackfill.test.ts@@ -1,6 +1,10 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { backfillDeviceArchitecture } from '../deviceArchitectureBackfill';+import {+ backfillDeviceArchitecture,+ resetDeviceArchitectureBackfill,+ UNLISTED_DEVICE_RETRY_MS,+} from '../deviceArchitectureBackfill';const options = {architecture: 'arm64',@@ -16,7 +20,11 @@ const localDevice = {scope: 'personal',};-afterEach(() => vi.unstubAllGlobals());+afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ resetDeviceArchitectureBackfill();+});describe('backfillDeviceArchitecture', () => {it('repairs a missing local architecture without overwriting metadata or settings', async () => {@@ -71,4 +79,65 @@ describe('backfillDeviceArchitecture', () => {await expect(backfillDeviceArchitecture(options)).resolves.toBeUndefined();expect(fetchMock).toHaveBeenCalledTimes(4);});++ // Regression: every device-info read (each window focus, each local run)+ // downloaded the whole device list again, long after the backfill was done.+ it('stops reading the device list once the architecture is known', async () => {+ const fetchMock = vi+ .fn()+ .mockImplementation(async () =>+ Response.json({ result: { data: { json: [{ ...localDevice, architecture: 'arm64' }] } } }),+ );+ vi.stubGlobal('fetch', fetchMock);+ for (let read = 0; read < 5; read++) await backfillDeviceArchitecture(options);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('stops reading the device list after a successful backfill', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(Response.json({ result: { data: { json: [localDevice] } } }))+ .mockResolvedValueOnce(Response.json({ result: { data: { json: {} } } }));+ vi.stubGlobal('fetch', fetchMock);+ await backfillDeviceArchitecture(options);+ await backfillDeviceArchitecture(options);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('shares one read between concurrent calls', async () => {+ const fetchMock = vi+ .fn()+ .mockImplementation(async () =>+ Response.json({ result: { data: { json: [{ ...localDevice, architecture: 'arm64' }] } } }),+ );+ vi.stubGlobal('fetch', fetchMock);+ await Promise.all([backfillDeviceArchitecture(options), backfillDeviceArchitecture(options)]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('looks up a device the registry does not list yet again only after a while', async () => {+ vi.useFakeTimers();+ const fetchMock = vi+ .fn()+ .mockImplementation(async () => Response.json({ result: { data: { json: [] } } }));+ vi.stubGlobal('fetch', fetchMock);+ await backfillDeviceArchitecture(options);+ await backfillDeviceArchitecture(options);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(UNLISTED_DEVICE_RETRY_MS);+ await backfillDeviceArchitecture(options);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('checks again for another signed-in account on the same device', async () => {+ const fetchMock = vi+ .fn()+ .mockImplementation(async () =>+ Response.json({ result: { data: { json: [{ ...localDevice, architecture: 'arm64' }] } } }),+ );+ vi.stubGlobal('fetch', fetchMock);+ await backfillDeviceArchitecture({ ...options, userId: 'user-a' });+ await backfillDeviceArchitecture({ ...options, userId: 'user-b' });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });});diff --git a/apps/desktop/src/main/services/deviceArchitectureBackfill.ts b/apps/desktop/src/main/services/deviceArchitectureBackfill.tsindex 30bff95985c..e6dc68255e2 100644--- a/apps/desktop/src/main/services/deviceArchitectureBackfill.ts+++ b/apps/desktop/src/main/services/deviceArchitectureBackfill.ts@@ -3,14 +3,34 @@ interface DeviceArchitectureBackfillOptions {deviceId: string;headers: Record<string, string>;serverUrl: string;+ /** Signed-in user, so another account on this machine is checked again. */+ userId?: string;}-export const backfillDeviceArchitecture = async ({- architecture,- deviceId,- headers,- serverUrl,-}: DeviceArchitectureBackfillOptions): Promise<void> => {+/** How long a device the registry does not list yet waits before it is looked up again. */+export const UNLISTED_DEVICE_RETRY_MS = 10 * 60_000;++/**+ * Devices whose registry row already carries an architecture. The backfill runs+ * on every local device-info read (each window focus, each local run), and each+ * check downloads the whole device list, so a device is checked once per+ * process, not on every read, after the server confirms it.+ */+const settled = new Set<string>();+const unlistedAt = new Map<string, number>();+const inFlight = new Map<string, Promise<void>>();++/** Test hook: forget what earlier calls learned. */+export const resetDeviceArchitectureBackfill = () => {+ settled.clear();+ unlistedAt.clear();+ inFlight.clear();+};++const run = async (+ key: string,+ { architecture, deviceId, headers, serverUrl }: DeviceArchitectureBackfillOptions,+): Promise<void> => {const response = await fetch(`${serverUrl}/trpc/lambda/device.listDevices`, {headers,signal: AbortSignal.timeout(5000),@@ -24,7 +44,15 @@ export const backfillDeviceArchitecture = async ({const device = devices.find((item) => item.deviceId === deviceId && item.scope === 'personal' && item.registered,);- if (!device || device.architecture) return;+ // Not registered yet: the gateway may register it later, so look again, but not on every read.+ if (!device) {+ unlistedAt.set(key, Date.now());+ return;+ }+ if (device.architecture) {+ settled.add(key);+ return;+ }const updated = await fetch(`${serverUrl}/trpc/lambda/device.updateDeviceInfo`, {body: JSON.stringify({@@ -35,4 +63,21 @@ export const backfillDeviceArchitecture = async ({signal: AbortSignal.timeout(5000),});if (!updated.ok) throw new Error(`Device architecture backfill failed: HTTP ${updated.status}`);+ settled.add(key);+};++export const backfillDeviceArchitecture = (+ options: DeviceArchitectureBackfillOptions,+): Promise<void> => {+ const key = [options.serverUrl, options.userId ?? '', options.deviceId].join('\n');+ if (settled.has(key)) return Promise.resolve();+ const unlisted = unlistedAt.get(key);+ if (unlisted !== undefined && Date.now() - unlisted < UNLISTED_DEVICE_RETRY_MS)+ return Promise.resolve();+ const running = inFlight.get(key);+ if (running) return running;++ const pending = run(key, options).finally(() => inFlight.delete(key));+ inFlight.set(key, pending);+ return pending;};diff --git a/apps/server/src/routers/lambda/__tests__/message.interventionSnapshot.test.ts b/apps/server/src/routers/lambda/__tests__/message.interventionSnapshot.test.tsnew file mode 100644index 00000000000..17c4a0a6d5a--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/message.interventionSnapshot.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ assertCanViewMessageTargets,+ assertCanViewTopicTargets,+} from '../_helpers/conversationResourceGuard';++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ cloudWorkspaceAuth: (opts: any) => opts.next({ ctx: opts.ctx }),+}));+vi.mock('../_helpers/conversationResourceGuard', () => ({+ assertCanUseConversationTargets: vi.fn(),+ assertCanUseCreateMessageTargets: vi.fn(),+ assertCanUseMessageTargets: vi.fn(),+ assertCanUseTopicTargets: vi.fn(),+ assertCanViewMessageTargets: vi.fn(),+ assertCanViewTopicTargets: vi.fn(),+}));++const { getInterventionSnapshot } = vi.hoisted(() => ({ getInterventionSnapshot: vi.fn() }));+vi.mock('@/database/models/message', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ MessageModel: vi.fn(function () {+ return { getInterventionSnapshot };+ }),+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++const { messageRouter } = await import('../message');++beforeEach(() => {+ vi.clearAllMocks();+});++describe('message.getInterventionSnapshot', () => {+ it('checks the topic and the cards, then returns the model snapshot', async () => {+ const snapshot = { revision: '3|t|h', statuses: { card: 'pending' } };+ getInterventionSnapshot.mockResolvedValue(snapshot);+ const caller = messageRouter.createCaller({ userId: 'owner', serverDB: {} } as any);++ const result = await caller.getInterventionSnapshot({ messageIds: ['card'], topicId: 'topic' });++ expect(result).toEqual(snapshot);+ expect(getInterventionSnapshot).toHaveBeenCalledWith({ ids: ['card'], topicId: 'topic' });+ expect(assertCanViewTopicTargets).toHaveBeenCalledWith(expect.anything(), ['topic']);+ expect(assertCanViewMessageTargets).toHaveBeenCalledWith(expect.anything(), ['card']);+ });++ it('reads nothing when the caller cannot view the topic', async () => {+ vi.mocked(assertCanViewTopicTargets).mockRejectedValueOnce(new Error('FORBIDDEN'));+ const caller = messageRouter.createCaller({ userId: 'owner', serverDB: {} } as any);++ await expect(+ caller.getInterventionSnapshot({ messageIds: ['card'], topicId: 'someone-else' }),+ ).rejects.toThrow('FORBIDDEN');+ expect(getInterventionSnapshot).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex c4f79e63bb2..cbcfe6ee7f1 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -423,6 +423,28 @@ export const messageRouter = router({return ctx.messageService.getToolResultPayloads(input.messageIds);}),+ /**+ * Change probe for a topic waiting on approval cards, for the client poll+ * that waits for an answer from another device. A topic's full message page+ * can be megabytes; this answers "did anything change?" in a few bytes: each+ * card's intervention status (`null` when deleted or not visible) and a+ * revision that moves on any message or card-argument change. The client+ * re-reads the page only when a card settled or the revision moved.+ */+ getInterventionSnapshot: messageProcedure+ .input(z.object({ messageIds: z.array(z.string()).min(1).max(50), topicId: z.string() }))+ .query(async ({ input, ctx }) => {+ await Promise.all([+ assertCanViewTopicTargets(guardCtx(ctx), [input.topicId]),+ assertCanViewMessageTargets(guardCtx(ctx), input.messageIds),+ ]);++ return ctx.messageModel.getInterventionSnapshot({+ ids: input.messageIds,+ topicId: input.topicId,+ });+ }),+/*** Where a message came from, for answering it: its conversation and, for a* message another agent sent, that agent and its conversationdiff --git a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.tsindex 958bdfeb464..b5e825c44bb 100644--- a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts+++ b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts@@ -443,6 +443,55 @@ describe('MessageModel.listMessagePluginsByIds', () => {});});+describe('MessageModel.getInterventionSnapshot', () => {+ const snapshot = (ids: string[]) =>+ messageModel.getInterventionSnapshot({ ids, topicId: 'plugin-topic' });++ it('returns each card status and null for a card outside the topic or owner', async () => {+ await seedToolMessage({ id: 'snap-pending', intervention: { status: 'pending' } });+ await seedToolMessage({ id: 'snap-plain' });+ await seedToolMessage({ id: 'snap-other-topic', topicId: 'plugin-topic-2' });+ await seedToolMessage({ id: 'snap-theirs', ownerId: otherUserId });++ const { statuses } = await snapshot([+ 'snap-pending',+ 'snap-plain',+ 'snap-other-topic',+ 'snap-theirs',+ 'snap-missing',+ ]);++ expect(statuses).toEqual({+ 'snap-missing': null,+ 'snap-other-topic': null,+ 'snap-pending': 'pending',+ 'snap-plain': null,+ 'snap-theirs': null,+ });+ });++ it('moves the revision when a message is added or a card argument is edited', async () => {+ await seedToolMessage({+ arguments: '{"q":1}',+ id: 'snap-card',+ intervention: { status: 'pending' },+ });+ const initial = (await snapshot(['snap-card'])).revision;+ expect((await snapshot(['snap-card'])).revision).toBe(initial);++ // Plugin rows do not bump the message updatedAt, so the arguments must count.+ await serverDB+ .update(messagePlugins)+ .set({ arguments: '{"q":2}' })+ .where(eq(messagePlugins.id, 'snap-card'));+ const edited = (await snapshot(['snap-card'])).revision;+ expect(edited).not.toBe(initial);++ await seedAssistantMessage('snap-new-row');+ expect((await snapshot(['snap-card'])).revision).not.toBe(edited);+ });+});+describe('MessageModel.findToolMessageIdByToolCallId', () => {it('resolves the message id for a tool call id', async () => {await seedToolMessage({ id: 'plug-tc-a', toolCallId: 'call-1', topicId: 'plugin-topic' });diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.tsindex 361f9c7a231..5035710ec00 100644--- a/packages/database/src/models/message/index.ts+++ b/packages/database/src/models/message/index.ts@@ -89,6 +89,7 @@ export class MessageModel {listToolCallsInTopics: MessagePluginStore['listToolCallsInTopics'];listMessagePluginsForOperation: MessagePluginStore['listMessagePluginsForOperation'];listMessagePluginsByIds: MessagePluginStore['listMessagePluginsByIds'];+ getInterventionSnapshot: MessagePluginStore['getInterventionSnapshot'];findToolMessageIdByToolCallId: MessagePluginStore['findToolMessageIdByToolCallId'];updateToolMessage: MessageToolMutations['updateToolMessage'];@@ -208,6 +209,7 @@ export class MessageModel {this.listToolCallsInTopics = plugins.listToolCallsInTopics;this.listMessagePluginsForOperation = plugins.listMessagePluginsForOperation;this.listMessagePluginsByIds = plugins.listMessagePluginsByIds;+ this.getInterventionSnapshot = plugins.getInterventionSnapshot;this.findToolMessageIdByToolCallId = plugins.findToolMessageIdByToolCallId;this.updateToolMessage = tools.updateToolMessage;this.updateToolArguments = tools.updateToolArguments;diff --git a/packages/database/src/models/message/plugin.ts b/packages/database/src/models/message/plugin.tsindex 32fb0ef76d3..f9a1777646f 100644--- a/packages/database/src/models/message/plugin.ts+++ b/packages/database/src/models/message/plugin.ts@@ -17,6 +17,8 @@ export class HumanApprovalAlreadyResolvedError extends Error {}}+type InterventionStatus = NonNullable<MessagePluginItem['intervention']>['status'];+/** One row of `listToolCallIndexByTopic`. */export interface ToolCallIndexItem extends Pick<MessagePluginItem,@@ -527,6 +529,59 @@ export class MessagePluginStore extends MessageScope {}));};+ /**+ * Cheap change probe for a topic that is waiting on approval cards: each+ * card's intervention status plus a revision that moves whenever the topic+ * gains, loses or edits a message, or a card's arguments change (plugin rows+ * do not bump the parent message's `updatedAt`). Lets a waiting client skip+ * re-reading the whole transcript page while nothing changed.+ */+ getInterventionSnapshot = async (params: {+ ids: string[];+ topicId: string;+ }): Promise<{+ revision: string;+ statuses: Record<string, InterventionStatus | null>;+ }> => {+ const [cards, [topicRow]] = await Promise.all([+ params.ids.length === 0+ ? Promise.resolve([])+ : this.db+ .select({+ argsHash: sql<string>`md5(coalesce(${messagePlugins.arguments}, ''))`,+ id: messagePlugins.id,+ status: sql<InterventionStatus | null>`${messagePlugins.intervention}->>'status'`,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(+ and(+ inArray(messagePlugins.id, params.ids),+ eq(messages.topicId, params.topicId),+ this.ownership(),+ this.pluginsOwnership(),+ notShareVisitorMessage(),+ ),+ ),+ this.db+ .select({+ count: sql<number>`count(*)::int`,+ updatedAt: sql<string | null>`max(${messages.updatedAt})::text`,+ })+ .from(messages)+ .where(and(eq(messages.topicId, params.topicId), this.ownership())),+ ]);++ const byId = new Map(cards.map((card) => [card.id, card]));+ const statuses = Object.fromEntries(params.ids.map((id) => [id, byId.get(id)?.status ?? null]));+ const argsHashes = params.ids.map((id) => byId.get(id)?.argsHash ?? '-').join(',');++ return {+ revision: `${topicRow?.count ?? 0}|${topicRow?.updatedAt ?? ''}|${argsHashes}`,+ statuses,+ };+ };+/*** Resolve the tool result message id for a toolCallId — the stable identifier* the model emitted for the call. Lets server-side services push async statediff --git a/src/features/Acceptance/hooks.test.ts b/src/features/Acceptance/hooks.test.tsindex 1e8ffc7929b..02817b6992a 100644--- a/src/features/Acceptance/hooks.test.ts+++ b/src/features/Acceptance/hooks.test.ts@@ -86,9 +86,10 @@ describe('Verify data hooks', () => {});});- it('polls fastest before an acceptance exists, then keeps it live until it settles', () => {- expect(getAcceptanceBySubjectRefreshInterval(undefined)).toBe(2000);- expect(getAcceptanceBySubjectRefreshInterval(null)).toBe(2000);+ it('checks for a missing acceptance slowly, then keeps one live until it settles', () => {+ // Regression: a missing acceptance was polled every 2s for as long as the page stayed open.+ expect(getAcceptanceBySubjectRefreshInterval(undefined)).toBe(10_000);+ expect(getAcceptanceBySubjectRefreshInterval(null)).toBe(10_000);// A task page left open through a goal loop would otherwise keep rendering// whatever state it first saw, all the way through delivery.expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'verifying' })).toBe(5000);@@ -96,4 +97,32 @@ describe('Verify data hooks', () => {expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'accepted' })).toBe(0);expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'closed' })).toBe(0);});++ // Regression: the task page mounts the state row and the acceptance section on the same+ // subject, and each polled it on its own timer; a reader opened seconds later (the result+ // portal) kept a second chain.+ it('shares one poll between readers of the same subject, even mounted seconds apart', async () => {+ vi.useFakeTimers();+ try {+ const getAcceptanceBySubject = vi+ .spyOn(verifyService, 'getAcceptanceBySubject')+ .mockResolvedValue({ id: 'a1', status: 'verifying' } as never);+ const wrapper = createSWRWrapper(new Map());+ renderHook(() => useAcceptanceBySubject('task', 'T-shared'), { wrapper });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ renderHook(() => useAcceptanceBySubject('task', 'T-shared'), { wrapper });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100);+ });+ const calls = getAcceptanceBySubject.mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(50_000);+ });+ expect(getAcceptanceBySubject.mock.calls.length - calls).toBeLessThanOrEqual(11);+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex d5099e7f661..a98ea0d106e 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -32,8 +32,22 @@ const VERIFY_REPORT_SWR_CONFIG = {*/const TERMINAL_ACCEPTANCE_STATUSES = new Set(['accepted', 'closed']);+/**+ * Most subjects never get an acceptance, so a missing one is checked every 10s rather than+ * every 2s, which kept every open task page reading it around the clock.+ */+export const ACCEPTANCE_ABSENT_REFRESH_MS = 10_000;++/**+ * Readers on one task page (state row, acceptance section, result portal) poll the same subject+ * on their own timers, and may mount seconds apart; `useClientDataSWR` dedupes nothing by+ * default. Just under the 5s live interval, so every reader shares one read per interval, and a+ * read left by the slower absent poll delays the first live one by less than one interval.+ */+export const ACCEPTANCE_POLL_DEDUPE_MS = 4500;+export const getAcceptanceBySubjectRefreshInterval = (acceptance: unknown) => {- if (!acceptance) return 2000;+ if (!acceptance) return ACCEPTANCE_ABSENT_REFRESH_MS;const status = (acceptance as { status?: string }).status;return status && TERMINAL_ACCEPTANCE_STATUSES.has(status) ? 0 : 5000;};@@ -120,7 +134,7 @@ export interface AcceptanceBySubjectSync {* The optional acceptance aggregate attached to a task/topic/document subject,* read from the verify store's replica of `acceptanceBySubjectMap`. A subject* can mount before its first Verify Run creates the aggregate, so the sync- * polls fastest until one exists and then keeps it live until it settles.+ * checks for one and then keeps it live until it settles.*/export const useAcceptanceBySubject = (subjectType: CreatableAcceptanceSubjectType,@@ -131,10 +145,11 @@ export const useAcceptanceBySubject = (const data = useVerifyStore((s) => (key ? s.acceptanceBySubjectMap[key] : undefined));const sync = useFetchAcceptanceBySubject(subjectType, subjectId, {+ dedupingInterval: ACCEPTANCE_POLL_DEDUPE_MS,refreshInterval: getAcceptanceBySubjectRefreshInterval(data),});- // A subject without an acceptance polls every 2s. Once a request for this key+ // A subject without an acceptance polls every 10s. Once a request for this key// has settled, "no acceptance" is a known answer: later polls must not flip the// caller back to its loading placeholder (that swapped the task's Acceptance// trigger for a spinner on every tick and made the section jump).diff --git a/src/features/Channels/useChannelEvents.test.ts b/src/features/Channels/useChannelEvents.test.tsnew file mode 100644index 00000000000..825f27d1eb5--- /dev/null+++ b/src/features/Channels/useChannelEvents.test.ts@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { channelActions } from '@/store/channel';++import { queueChannelRefresh } from './useChannelEvents';++vi.mock('@/store/channel', () => ({+ channelActions: { refreshDetail: vi.fn(async () => {}), refreshList: vi.fn(async () => {}) },+}));++const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++describe('queueChannelRefresh', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // Regression: one `channel_changed` reached the sidebar, the main conversation and the+ // thread panel, and each refreshed the list itself: three list reads per notify.+ it('merges the refreshes every subscriber asks for in the same tick', async () => {+ const main = { channelId: 'channel', threadId: null };+ const thread = { channelId: 'channel', threadId: 'thread' };+ queueChannelRefresh();+ queueChannelRefresh(main);+ queueChannelRefresh({ ...main, before: undefined });+ queueChannelRefresh(thread);+ await flush();++ expect(channelActions.refreshList).toHaveBeenCalledTimes(1);+ expect(vi.mocked(channelActions.refreshDetail).mock.calls).toEqual([[main], [thread]]);+ });++ it('refreshes again for an event in a later tick', async () => {+ queueChannelRefresh();+ await flush();+ queueChannelRefresh();+ await flush();++ expect(channelActions.refreshList).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/Channels/useChannelEvents.ts b/src/features/Channels/useChannelEvents.tsindex 1f8576bfa70..af1ef0a463d 100644--- a/src/features/Channels/useChannelEvents.ts+++ b/src/features/Channels/useChannelEvents.ts@@ -10,6 +10,32 @@ import {} from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';import { useServerConfigStore } from '@/store/serverConfig';+/**+ * One gateway event reaches every mounted subscriber (sidebar, main conversation, thread+ * panel) in the same tick, and each used to refresh the list on its own: one notify cost three+ * list reads plus the details. Requests made in the same tick are merged into one refresh per+ * view; a reconnect refreshes the same way.+ */+let queuedList = false;+const queuedDetails = new Map<string, ChannelViewParams>();+export const queueChannelRefresh = (detail?: ChannelViewParams) => {+ if (detail) {+ const { before, channelId, threadId } = detail;+ queuedDetails.set(JSON.stringify([channelId, threadId ?? null, before ?? null]), detail);+ }+ if (queuedList) return;+ queuedList = true;+ queueMicrotask(() => {+ const details = [...queuedDetails.values()];+ queuedList = false;+ queuedDetails.clear();+ void Promise.allSettled([+ channelActions.refreshList(),+ ...details.map((params) => channelActions.refreshDetail(params)),+ ]);+ });+};+/** Public invalidations share the authenticated user socket, never an Agent's private stream. */export const useChannelEvents = (params?: ChannelViewParams) => {const gatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);@@ -22,12 +48,8 @@ export const useChannelEvents = (params?: ChannelViewParams) => {const identity = { gatewayUrl };if (isGatewayMuxUnavailable(identity)) return;const mux = getGatewayMux(identity);- const refresh = () => {- void Promise.allSettled([- channelActions.refreshList(),- ...(channelId ? [channelActions.refreshDetail({ channelId, threadId, before })] : []),- ]);- };+ const refresh = () =>+ queueChannelRefresh(channelId ? { before, channelId, threadId } : undefined);const remove = [mux.on('channel_changed', (event) => {if (!channelId || event.channelId === channelId) refresh();diff --git a/src/features/DeviceManager/DeviceActivity/RunningUsers.test.ts b/src/features/DeviceManager/DeviceActivity/RunningUsers.test.tsnew file mode 100644index 00000000000..475c3793f1f--- /dev/null+++ b/src/features/DeviceManager/DeviceActivity/RunningUsers.test.ts@@ -0,0 +1,46 @@+import { act, renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceService } from '@/services/device';++import { useDeviceRunningSummary } from './RunningUsers';++vi.mock('@/services/device', () => ({+ deviceService: { getRunningSummary: vi.fn(async () => []) },+}));++const tick = (ms: number) =>+ act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+const calls = () => vi.mocked(deviceService.getRunningSummary).mock.calls.length;++describe('useDeviceRunningSummary', () => {+ let wrapper: (props: PropsWithChildren) => ReturnType<typeof createElement>;+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ const cache = new Map();+ wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, {+ children,+ value: { isOnline: () => true, isVisible: () => true, provider: () => cache },+ });+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ // Regression: each device card polled on its own timer, so N cards made N requests every 15s.+ it('serves every mounted card from one poll', async () => {+ for (let card = 0; card < 3; card++) {+ renderHook(() => useDeviceRunningSummary(), { wrapper });+ await tick(2000);+ }+ const before = calls();+ await tick(60_000);+ expect(calls() - before).toBeLessThanOrEqual(5);+ });+});diff --git a/src/features/DeviceManager/DeviceActivity/RunningUsers.tsx b/src/features/DeviceManager/DeviceActivity/RunningUsers.tsxindex 6b1ff9a65fa..64a77da6e55 100644--- a/src/features/DeviceManager/DeviceActivity/RunningUsers.tsx+++ b/src/features/DeviceManager/DeviceActivity/RunningUsers.tsx@@ -59,9 +59,14 @@ RunUserAvatar.displayName = 'RunUserAvatar';/*** Running-topic counts for every device in the list, from one request. Keyed* per workspace by `useClientDataSWR`, like the device list itself.+ *+ * Every device card mounts its own reader, each on its own timer, and+ * `useClientDataSWR` dedupes nothing by default: N cards meant N requests every+ * 15s. The dedupe window lets one read serve them all.*/export const useDeviceRunningSummary = () =>useClientDataSWR(['device/runningSummary'], () => deviceService.getRunningSummary(), {+ dedupingInterval: REFRESH_INTERVAL_MS - 1000,focusThrottleInterval: 1000,refreshInterval: REFRESH_INTERVAL_MS,});diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex e5e4f3fc3af..e2808f414cb 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -202,6 +202,10 @@ export class MessageService {return lambdaClient.message.getToolResultPayload.query({ messageId });};+ /** Status per pending card id (`null` when gone) plus a revision of the topic, for the approval poll. */+ getInterventionSnapshot = async (topicId: string, messageIds: string[]) =>+ lambdaClient.message.getInterventionSnapshot.query({ messageIds, topicId });+/*** Bulk form, for surfaces that need every omitted row at once (export).*diff --git a/src/store/channel/action.polling.test.ts b/src/store/channel/action.polling.test.tsindex 6f40db036d7..320eeee5fe3 100644--- a/src/store/channel/action.polling.test.ts+++ b/src/store/channel/action.polling.test.ts@@ -208,6 +208,63 @@ describe('Channel in-progress refresh without gateway notifications', () => {expect(channelService.detail).toHaveBeenCalledTimes(calls);});+ // Regression: the page header and the conversation both mount this view, each on its own+ // timer, and every extra mount doubled the fast poll.+ it('shares one fast poll between views mounted on the same channel', async () => {+ response = detail({ messages: [message('pending')] });+ const cache = new Map();+ const shared = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, {+ children,+ value: {+ dedupingInterval: 0,+ isOnline: () => true,+ isVisible: () => true,+ provider: () => cache,+ },+ });+ renderHook(() => channelActions.useFetchDetail(params), { wrapper: shared });+ await tick(1000);+ renderHook(() => channelActions.useFetchDetail(params), { wrapper: shared });+ await tick(0);+ const calls = vi.mocked(channelService.detail).mock.calls.length;+ await tick(10 * CHANNEL_ACTIVE_REFRESH_MS);+ expect(vi.mocked(channelService.detail).mock.calls.length - calls).toBeLessThanOrEqual(11);+ });++ // Regression: SWR keeps the dedupe window of a key's first mount, so views mounted while idle+ // (no window) each kept their own 3s poll once the channel turned active.+ it('shares one fast poll between staggered idle views once the channel turns active', async () => {+ const cache = new Map();+ const shared = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, {+ children,+ value: {+ dedupingInterval: 0,+ isOnline: () => true,+ isVisible: () => true,+ provider: () => cache,+ },+ });+ renderHook(() => channelActions.useFetchDetail(params), { wrapper: shared });+ await tick(1500);+ // The conversation browsed an older page, then returns to the latest one.+ const conversation = renderHook(+ ({ view }: { view: typeof params | null }) => channelActions.useFetchDetail(view),+ { initialProps: { view: null as typeof params | null }, wrapper: shared },+ );+ await tick(700);+ conversation.rerender({ view: params });+ await tick(0);++ // The channel turns active on a regular poll.+ response = detail({ messages: [message('pending')] });+ await tick(60_000);+ const calls = vi.mocked(channelService.detail).mock.calls.length;+ await tick(10 * CHANNEL_ACTIVE_REFRESH_MS);+ expect(vi.mocked(channelService.detail).mock.calls.length - calls).toBeLessThanOrEqual(11);+ });+it('does not fetch a disabled view', async () => {renderHook(() => channelActions.useFetchDetail(null), { wrapper });await tick(5000);diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex baac76e94d7..f808d15b42a 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -39,6 +39,23 @@ import { initialState, useChannelStore } from './store';export const CHANNEL_ACTIVE_REFRESH_MS = 3000;export const CHANNEL_IDLE_REFRESH_MS = 60_000;+/**+ * Several mounted views poll the same list or detail (sidebar + agent manager, page header ++ * conversation), each on its own timer. `useClientDataSWR` dedupes nothing by default, so every+ * extra mount multiplied the fast poll; one read per window serves all of them.+ *+ * The window stays the same in both states: SWR keeps the dedupe window a key had when it was+ * first mounted, so views that mounted idle with no window kept separate fast polls once the+ * channel turned active. A window shorter than one fast interval delays at most the first fast+ * poll after an idle read, by under one interval.+ */+const CHANNEL_POLL_DEDUPE_MS = CHANNEL_ACTIVE_REFRESH_MS - 500;++const pollDedupe = (pending: boolean) => ({+ dedupingInterval: CHANNEL_POLL_DEDUPE_MS,+ refreshInterval: pending ? CHANNEL_ACTIVE_REFRESH_MS : CHANNEL_IDLE_REFRESH_MS,+});+type ChannelSendInput = Parameters<typeof channelService.send>[0];/** What the composer hands over; the outbox adds the request key, time and status. */@@ -56,18 +73,13 @@ class ChannelActionImpl {/** Pass `false` where the list is only needed behind a user choice, so nothing polls before. */useFetchList = (enabled = true) => {const pending = useChannelStore(channelSelectors.listHasPendingWork);- return this.#private.list.useSync(- {},- { enabled, refreshInterval: pending ? CHANNEL_ACTIVE_REFRESH_MS : CHANNEL_IDLE_REFRESH_MS },- );+ return this.#private.list.useSync({}, { enabled, ...pollDedupe(pending) });};useFetchDetail = (params: ChannelViewParams | null) => {// Subscribe to the replica, not just SWR's last response: sending a message// updates this view imperatively and must shorten an already scheduled idle poll.const pending = useChannelStore(channelSelectors.hasPendingWork(params));- return this.#private.detail.useSync(params, {- refreshInterval: pending ? CHANNEL_ACTIVE_REFRESH_MS : CHANNEL_IDLE_REFRESH_MS,- });+ return this.#private.detail.useSync(params, pollDedupe(pending));};refreshList = () => this.#private.list.fetch({}, { fresh: true });refreshDetail = (params: ChannelViewParams) =>diff --git a/src/store/chat/slices/message/actions/transcript.approvalBackoff.test.ts b/src/store/chat/slices/message/actions/transcript.approvalBackoff.test.tsnew file mode 100644index 00000000000..8d552340e51--- /dev/null+++ b/src/store/chat/slices/message/actions/transcript.approvalBackoff.test.ts@@ -0,0 +1,316 @@+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createReplicaState } from '@/libs/replica';+import { messageService } from '@/services/message';+import { clearMessageListClientCacheState } from '@/services/message/cache';+import { topicService } from '@/services/topic';+import { useChatStore } from '@/store/chat';+import {+ backoffPollInterval,+ hasPendingInterventions,+ INTERVENTION_FAST_POLL_WINDOW,+ INTERVENTION_MAX_REFRESH_INTERVAL,+ INTERVENTION_REFRESH_INTERVAL,+} from '@/store/chat/utils/interventionSync';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { resetInterventionSnapshotSupport } from './transcript';++vi.mock('@/services/message', () => {+ const getMessages = vi.fn();+ return {+ messageService: {+ getEarlierMessages: vi.fn(),+ getInterventionSnapshot: vi.fn(),+ getMessages,+ getMessageListPage: vi.fn(async (params: unknown) => ({+ messages: await getMessages(params),+ olderCursor: null,+ })),+ },+ };+});+vi.mock('@/services/topic', () => ({ topicService: { getTopicDetail: vi.fn() } }));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => undefined,+ useActiveWorkspaceId: () => undefined,+}));++const context = { agentId: 'sync-agent', threadId: null, topicId: 'sync-topic' };+const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+};++const key = messageMapKey(context);+/** A conversation whose loaded transcript holds one unanswered approval. */+const seedPending = () =>+ useChatStore.setState({+ dbMessagesMap: { [key]: [pending] },+ messagePagingMap: {},+ messageReplica: createReplicaState(),+ messagesMap: {},+ });++/**+ * Separate file: a card that stays pending keeps its key in the transcript's+ * module-level pending set, which would leak into the other polling tests.+ */+describe('pending approval poll backoff', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ clearMessageListClientCacheState();+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: {} });+ vi.mocked(messageService.getMessages).mockResolvedValue([pending]);+ vi.mocked(messageService.getMessageListPage).mockImplementation(async (params) => ({+ messages: await messageService.getMessages(params),+ olderCursor: null,+ }));+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(null);+ resetInterventionSnapshotSupport();+ // A failing probe: every tick re-reads the page.+ vi.mocked(messageService.getInterventionSnapshot).mockRejectedValue(new Error('timeout'));+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ const mountPolling = async () => {+ seedPending();+ const cache = new Map();+ const view = renderHook(+ () => {+ const hasPending = useChatStore((state) =>+ hasPendingInterventions(state.dbMessagesMap[key] ?? []),+ );+ useChatStore.getState().useFetchMessages(context, {+ refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,+ syncInterventions: true,+ });+ },+ {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ },+ );+ await act(async () => {+ await Promise.resolve();+ });+ return view;+ };++ it('backs off a card that stays pending past the fast window', async () => {+ // Regression: an unanswered card can stay `pending` for days, and an open+ // tab re-read the whole transcript every 2s for as long as it stayed open.+ const view = await mountPolling();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_FAST_POLL_WINDOW + 8 * 60_000);+ });+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ });+ const perHalfHour = vi.mocked(messageService.getMessages).mock.calls.length - requests;+ // At the ceiling: one read every five minutes instead of one every 2s.+ expect(perHalfHour).toBeLessThanOrEqual(7);+ expect(perHalfHour).toBeGreaterThanOrEqual(5);+ view.unmount();+ });++ it('keeps the base interval within the fast window', async () => {+ const view = await mountPolling();+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(+ vi.mocked(messageService.getMessages).mock.calls.length - requests,+ ).toBeGreaterThanOrEqual(28);+ view.unmount();+ });++ it('restores the base interval when another card is raised', async () => {+ const view = await mountPolling();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_FAST_POLL_WINDOW + 4 * 60_000);+ });+ // The first card was answered and the run raised the next one.+ const next = { ...pending, id: 'question-2', tool_call_id: 'call-2' };+ vi.mocked(messageService.getMessages).mockResolvedValue([next]);+ await act(async () => {+ useChatStore.setState({ dbMessagesMap: { [key]: [next] } });+ await vi.advanceTimersByTimeAsync(30_000);+ });+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(+ vi.mocked(messageService.getMessages).mock.calls.length - requests,+ ).toBeGreaterThanOrEqual(28);+ view.unmount();+ });+});++const snapshot = (status: 'approved' | 'pending', revision = 'r1') => ({+ revision,+ statuses: { question: status } as Record<string, 'approved' | 'pending'>,+});++describe('pending approval status poll', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ clearMessageListClientCacheState();+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: {} });+ vi.mocked(messageService.getMessages).mockResolvedValue([pending]);+ vi.mocked(messageService.getMessageListPage).mockImplementation(async (params) => ({+ messages: await messageService.getMessages(params),+ olderCursor: null,+ }));+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(null);+ resetInterventionSnapshotSupport();+ vi.mocked(messageService.getInterventionSnapshot).mockResolvedValue(snapshot('pending'));+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ const mount = async () => {+ seedPending();+ const cache = new Map();+ const view = renderHook(+ () => useChatStore.getState().useFetchMessages(context, { syncInterventions: true }),+ {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ },+ );+ await act(async () => {+ await Promise.resolve();+ });+ return view;+ };++ // Regression: each tick re-read the whole message page, megabytes for a long+ // topic, only to learn the card was still pending.+ it('asks only for the card status while it stays pending', async () => {+ const view = await mount();+ // The first probe of the chain re-reads once to set its baseline.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL * 2);+ });+ const reads = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(vi.mocked(messageService.getMessages).mock.calls.length).toBe(reads);+ expect(messageService.getInterventionSnapshot).toHaveBeenCalledWith(context.topicId, [+ 'question',+ ]);+ expect(+ vi.mocked(messageService.getInterventionSnapshot).mock.calls.length,+ ).toBeGreaterThanOrEqual(28);+ view.unmount();+ });++ it('re-reads the page once another device answered the card', async () => {+ const view = await mount();+ const reads = vi.mocked(messageService.getMessages).mock.calls.length;+ vi.mocked(messageService.getInterventionSnapshot).mockResolvedValue(snapshot('approved'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL);+ });+ expect(vi.mocked(messageService.getMessages).mock.calls.length).toBeGreaterThan(reads);+ view.unmount();+ });++ // Regression: the first probe only recorded its revision, so an argument+ // edit landing between the page read and that probe was never shown.+ it('re-reads the page on the first probe of a chain', async () => {+ const view = await mount();+ const reads = vi.mocked(messageService.getMessages).mock.calls.length;+ vi.mocked(messageService.getInterventionSnapshot).mockResolvedValue(snapshot('pending', 'r2'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL + 100);+ });+ expect(vi.mocked(messageService.getMessages).mock.calls.length).toBeGreaterThan(reads);+ view.unmount();+ });++ it('re-reads the page when the topic changed while the card stays pending', async () => {+ const view = await mount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL * 2);+ });+ const reads = vi.mocked(messageService.getMessages).mock.calls.length;+ // Another device edited the card's arguments or added a row.+ vi.mocked(messageService.getInterventionSnapshot).mockResolvedValue(snapshot('pending', 'r2'));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL);+ });+ expect(vi.mocked(messageService.getMessages).mock.calls.length).toBeGreaterThan(reads);+ view.unmount();+ });++ it('stops asking a server that has no snapshot probe', async () => {+ vi.mocked(messageService.getInterventionSnapshot).mockRejectedValue(+ new Error('No procedure found on path "message.getInterventionSnapshot"'),+ );+ const view = await mount();+ const reads = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000);+ });+ expect(messageService.getInterventionSnapshot).toHaveBeenCalledTimes(1);+ // Falls back to re-reading the page, as before the probe existed.+ expect(vi.mocked(messageService.getMessages).mock.calls.length - reads).toBeGreaterThanOrEqual(+ 8,+ );+ view.unmount();+ });++ it('polls a newly raised card at once instead of waiting out the backoff', async () => {+ const view = await mount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_FAST_POLL_WINDOW + 4 * 60_000);+ });+ // Sitting in a backed-off wait; the run raises a second card over the stream.+ const second = { ...pending, id: 'question-2', tool_call_id: 'call-2' };+ const probes = vi.mocked(messageService.getInterventionSnapshot).mock.calls.length;+ await act(async () => {+ useChatStore.setState({ dbMessagesMap: { [key]: [pending, second] } });+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL + 100);+ });+ expect(vi.mocked(messageService.getInterventionSnapshot).mock.calls.length).toBeGreaterThan(+ probes,+ );+ view.unmount();+ });+});++describe('backoffPollInterval', () => {+ it('keeps the base interval inside the fast window, then doubles each minute up to the ceiling', () => {+ const base = INTERVENTION_REFRESH_INTERVAL;+ expect(backoffPollInterval(base, 0)).toBe(base);+ expect(backoffPollInterval(base, INTERVENTION_FAST_POLL_WINDOW - 1)).toBe(base);+ expect(backoffPollInterval(base, INTERVENTION_FAST_POLL_WINDOW)).toBe(base * 2);+ expect(backoffPollInterval(base, INTERVENTION_FAST_POLL_WINDOW + 60_000)).toBe(base * 4);+ expect(backoffPollInterval(base, INTERVENTION_FAST_POLL_WINDOW + 60 * 60_000)).toBe(+ INTERVENTION_MAX_REFRESH_INTERVAL,+ );+ expect(backoffPollInterval(0, INTERVENTION_FAST_POLL_WINDOW * 10)).toBe(0);+ });+});diff --git a/src/store/chat/slices/message/actions/transcript.ts b/src/store/chat/slices/message/actions/transcript.tsindex 5a9fa8dea55..851ba47106c 100644--- a/src/store/chat/slices/message/actions/transcript.ts+++ b/src/store/chat/slices/message/actions/transcript.ts@@ -3,6 +3,7 @@ import debug from 'debug';import { useEffect, useRef } from 'react';import { type StoreApi, useStore } from 'zustand';+import { messageService } from '@/services/message';import {getMessageListCacheIdentity,getMessageListFetchPolicy,@@ -14,14 +15,31 @@ import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { topicSelectors } from '@/store/chat/slices/topic/selectors';import { type ChatStore } from '@/store/chat/store';import {+ backoffPollInterval,hasPendingInterventions,INTERVENTION_REFRESH_INTERVAL,+ pendingInterventionIds,} from '@/store/chat/utils/interventionSync';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type StoreSetter } from '@/store/types';import { getMessageTranscript } from '../transcript';+/** Matches the `getInterventionSnapshot` input cap in the lambda router. */+const INTERVENTION_STATUS_BATCH_SIZE = 50;++/** Set once the server proved it lacks the snapshot probe (an older deployment). */+let snapshotUnsupported = false;++/** tRPC's answer for a procedure the server does not have. */+const isMissingProcedure = (error: unknown) =>+ error instanceof Error && /no procedure found/i.test(error.message);++/** Test hook: forget a previous server's missing probe. */+export const resetInterventionSnapshotSupport = () => {+ snapshotUnsupported = false;+};+const log = debug('lobe-store:message-transcript');/** Fetch flags of a transcript sync. The rows live in `dbMessagesMap`. */@@ -242,6 +260,7 @@ export class MessageTranscriptActionImpl {// card that arrived over the stream) was deduped for the whole 30s list// window and another device's answer showed up that late. Each tick// re-reads the interval: the pending set changes without a render.+ const bucket = messageMapKey(context);const revalidateRef = useRef(result.revalidate);revalidateRef.current = result.revalidate;const validatingRef = useRef(result.isValidating);@@ -254,25 +273,117 @@ export class MessageTranscriptActionImpl {: refreshInterval;let timer: ReturnType<typeof setTimeout> | undefined;let cancelled = false;+ /** A tick is reading; its `finally` schedules the next one. */+ let inFlight = false;+ /** Start of the current uninterrupted polling run; drives the backoff. */+ let pollingSince: number | undefined;+ /** Cards pending when `pollingSince` was set; a newly raised card restarts the fast window. */+ let pollingFor: string | undefined;+ /** Snapshot revision seen by the previous status poll. */+ let lastRevision: string | undefined;+ const pendingCardIds = () => pendingInterventionIds(this.#get().dbMessagesMap[bucket] ?? []);const next = () => {// A read still in flight when the effect re-ran must not restart this chain.- if (cancelled) return;- const interval = intervalOf();- if (interval > 0) timer = setTimeout(tick, interval);+ if (cancelled || inFlight) return;+ clearTimeout(timer);+ const base = intervalOf();+ if (base <= 0) return;+ // Read from the store, not a subscription: a re-render here would+ // reorder this hook against the sync it drives.+ const pendingCards = pendingCardIds().join(',');+ if (pollingSince === undefined || pollingFor !== pendingCards) {+ pollingSince = Date.now();+ pollingFor = pendingCards;+ }+ timer = setTimeout(tick, backoffPollInterval(base, Date.now() - pollingSince));+ };+ /**+ * Whether this tick must re-read the transcript. While cards wait for an+ * answer, ask only for a snapshot of them: the full page can be+ * megabytes, and an unanswered card can stay pending for days, so an open+ * tab used to re-read it every tick all that time. The page is re-read+ * once a card settled, the topic changed (revision moved), or the probe+ * failed.+ */+ const needsRead = async () => {+ const ids = pendingCardIds();+ if (+ !syncContinuation ||+ !context.topicId ||+ snapshotUnsupported ||+ ids.length === 0 ||+ ids.length > INTERVENTION_STATUS_BATCH_SIZE+ )+ return true;+ try {+ const { revision, statuses } = await messageService.getInterventionSnapshot(+ context.topicId,+ ids,+ );+ // The first probe of a chain has no baseline: a card edited between+ // the page read and this probe would otherwise never be re-read, so+ // it re-reads once.+ const changed = lastRevision !== revision;+ lastRevision = revision;+ return changed || ids.some((id) => statuses[id] !== 'pending');+ } catch (error) {+ // A server without the probe answers every tick with the same error;+ // stop asking for the rest of the session.+ if (isMissingProcedure(error)) snapshotUnsupported = true;+ log('[poll] snapshot read failed | key=%s | %O', bucket, error);+ return true;+ }};const tick = () => {+ if (cancelled || inFlight) return;const visible = typeof document === 'undefined' || document.visibilityState !== 'hidden';const online = typeof navigator === 'undefined' || navigator.onLine !== false;if (visible && online && !validatingRef.current) {- void Promise.resolve(revalidateRef.current()).finally(next);+ inFlight = true;+ void needsRead()+ .then((read) => (read && !cancelled ? revalidateRef.current() : undefined))+ .finally(() => {+ inFlight = false;+ next();+ });return;}next();};+ // A card raised while the chain sits in a long backed-off wait must not+ // wait that long: restart at the base interval as soon as it appears.+ let knownRows = this.#get().dbMessagesMap[bucket];+ let knownIds = new Set(pendingCardIds());+ const unsubscribe = this.#api.subscribe((state) => {+ const rows = state.dbMessagesMap[bucket];+ if (rows === knownRows) return;+ knownRows = rows;+ const ids = pendingInterventionIds(rows ?? []);+ const raised = ids.some((id) => !knownIds.has(id));+ knownIds = new Set(ids);+ if (raised) next();+ });+ // Returning to the window answers "was it answered elsewhere?" at once,+ // even while SWR throttles focus revalidation.+ const onReturn = () => {+ if (document.visibilityState === 'hidden' || !pendingInterventions.has(syncKey)) return;+ clearTimeout(timer);+ tick();+ };+ const hasDom = typeof window !== 'undefined' && typeof document !== 'undefined';+ if (hasDom) {+ window.addEventListener('focus', onReturn);+ document.addEventListener('visibilitychange', onReturn);+ }next();return () => {cancelled = true;clearTimeout(timer);+ unsubscribe();+ if (hasDom) {+ window.removeEventListener('focus', onReturn);+ document.removeEventListener('visibilitychange', onReturn);+ }};}, [shouldFetch, syncContinuation, syncKey, refreshInterval]);@@ -282,7 +393,6 @@ export class MessageTranscriptActionImpl {this.#api,operationSelectors.isAgentRuntimeRunningByContext(context),);- const bucket = messageMapKey(context);const wasStreamingRef = useRef({ bucket, running: isStreaming });useEffect(() => {if (diff --git a/src/store/chat/utils/interventionSync.ts b/src/store/chat/utils/interventionSync.tsindex 21349e146f7..379fb346a15 100644--- a/src/store/chat/utils/interventionSync.ts+++ b/src/store/chat/utils/interventionSync.ts@@ -2,6 +2,26 @@ import type { ChatTopic, UIChatMessage } from '@lobechat/types';export const INTERVENTION_REFRESH_INTERVAL = 2000;+/** How long a pending card polls at the base interval before backing off. */+export const INTERVENTION_FAST_POLL_WINDOW = 5 * 60_000;+/** Ceiling of the backed-off poll interval. */+export const INTERVENTION_MAX_REFRESH_INTERVAL = 5 * 60_000;++/**+ * Poll interval after `elapsed` ms of continuous polling. An answer from+ * another device normally lands within minutes, so the first window keeps the+ * base interval; after that the interval doubles every minute up to the+ * ceiling. A question nobody answers keeps its run parked in+ * `waiting_for_human` for days, and without this backoff an open tab polled+ * every 2 s all that time.+ * Focus revalidation still refreshes immediately when the user returns.+ */+export const backoffPollInterval = (base: number, elapsed: number) => {+ if (base <= 0 || elapsed < INTERVENTION_FAST_POLL_WINDOW) return base;+ const doublings = 1 + Math.floor((elapsed - INTERVENTION_FAST_POLL_WINDOW) / 60_000);+ return Math.max(base, Math.min(base * 2 ** doublings, INTERVENTION_MAX_REFRESH_INTERVAL));+};+/** A missing operation marker can still mean the continuation is starting. */export const isInterventionRunActive = (topic: ChatTopic | null) =>!!topic?.metadata?.runningOperation ||@@ -20,6 +40,17 @@ export const hasPendingInterventions = (messages: UIChatMessage[]) =>intervention(message)?.status === 'pending',);+/** Ids of the persisted cards still waiting for an answer. */+export const pendingInterventionIds = (messages: UIChatMessage[]) =>+ messages+ .filter(+ (message) =>+ message.role === 'tool' &&+ !message.id.startsWith('tmp_') &&+ intervention(message)?.status === 'pending',+ )+ .map((message) => message.id);+const isTerminal = (status: string | undefined) =>status === 'approved' || status === 'rejected' || status === 'aborted';diff --git a/src/store/verify/action.ts b/src/store/verify/action.tsindex a8bc1a99542..5e3b6dcaacd 100644--- a/src/store/verify/action.ts+++ b/src/store/verify/action.ts@@ -495,9 +495,10 @@ export class ActionImpl {useFetchAcceptanceBySubject = (subjectType: CreatableAcceptanceSubjectType,subjectId?: string | null,- options: { enabled?: boolean; refreshInterval?: number } = {},+ options: { dedupingInterval?: number; enabled?: boolean; refreshInterval?: number } = {},): ReplicaSyncResult =>this.#bySubject.useSync(subjectId ? { subjectId, subjectType } : null, {+ ...(options.dedupingInterval !== undefined && { dedupingInterval: options.dedupingInterval }),enabled: options.enabled ?? true,refreshInterval: options.refreshInterval,revalidateOnFocus: true,