Skip to content

🤯 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.

⚡️ perf(agent-signal,app): exp backoff retry of listing signal receipts (#14542)

Nekob47e32436ea2
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
index b70ee53d5fe..1db448ce715 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
@@ -104,4 +104,103 @@ describe('useAgentSignalReceipts', () => {
topicId: 'topic-1',
});
});
+
+ it('backs off receipt refreshes when no new receipts are available', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(0));
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValue({
+ cursor: undefined,
+ receipts: [],
+ });
+
+ renderHook(
+ () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
+ { wrapper },
+ );
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(6000);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(3);
+ });
+
+ it('stops refreshing receipts after five minutes in the current topic scope', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(0));
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValue({
+ cursor: undefined,
+ receipts: [],
+ });
+
+ renderHook(
+ () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
+ { wrapper },
+ );
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ });
+ const callsAtTimeout = vi.mocked(agentSignalService.listReceipts).mock.calls.length;
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(callsAtTimeout);
+ });
+
+ it('restarts the polling window when new work starts in the same topic scope', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(0));
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValue({
+ cursor: undefined,
+ receipts: [],
+ });
+
+ const { rerender } = renderHook(
+ ({ pollingSignal }) =>
+ useAgentSignalReceipts({
+ agentId: 'agent-1',
+ enabled: true,
+ pollingSignal,
+ topicId: 'topic-1',
+ }),
+ { initialProps: { pollingSignal: 'assistant-1' }, wrapper },
+ );
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ });
+ const callsAtTimeout = vi.mocked(agentSignalService.listReceipts).mock.calls.length;
+
+ vi.setSystemTime(new Date(5 * 60_000));
+ rerender({ pollingSignal: 'assistant-2' });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(callsAtTimeout + 1);
+ });
});
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
index 5f18a46f679..71d3bf24cbf 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
@@ -4,7 +4,13 @@ import useSWR from 'swr';
import { agentSignalService } from '@/services/agentSignal';
/** Poll cadence for the active conversation's Agent Signal receipt surface. */
-const AGENT_SIGNAL_RECEIPT_REFRESH_INTERVAL_MS = 3000;
+const AGENT_SIGNAL_RECEIPT_INITIAL_REFRESH_INTERVAL_MS = 3000;
+
+/** Upper bound for one backoff sleep so the receipt surface still catches late async work. */
+const AGENT_SIGNAL_RECEIPT_MAX_REFRESH_INTERVAL_MS = 60_000;
+
+/** Maximum time to wait for async Agent Signal receipts in the current agent/topic scope. */
+const AGENT_SIGNAL_RECEIPT_POLLING_TIMEOUT_MS = 5 * 60_000;
export type AgentSignalReceiptView = Awaited<
ReturnType<typeof agentSignalService.listReceipts>
@@ -13,13 +19,17 @@ export type AgentSignalReceiptView = Awaited<
export const useAgentSignalReceipts = (input: {
agentId?: string | null;
enabled?: boolean;
+ pollingSignal?: string | null;
topicId?: string | null;
}) => {
// TODO: Migrate Agent Signal receipt visibility to a dedicated product capability flag.
const shouldFetch = input.enabled === true && Boolean(input.agentId && input.topicId);
const scopeKey = shouldFetch ? `${input.agentId}:${input.topicId}` : undefined;
+ const pollingKey = shouldFetch ? `${scopeKey}:${input.pollingSignal ?? ''}` : undefined;
+ const pollingKeyRef = useRef<string | undefined>(undefined);
const scopeKeyRef = useRef<string | undefined>(undefined);
const latestCreatedAtRef = useRef<number | undefined>(undefined);
+ const pollingRef = useRef<{ emptyRefreshes: number; startedAt?: number }>({ emptyRefreshes: 0 });
const receiptsRef = useRef<AgentSignalReceiptView[]>([]);
if (scopeKeyRef.current !== scopeKey) {
@@ -28,6 +38,14 @@ export const useAgentSignalReceipts = (input: {
receiptsRef.current = [];
}
+ if (pollingKeyRef.current !== pollingKey) {
+ pollingKeyRef.current = pollingKey;
+ pollingRef.current = {
+ emptyRefreshes: 0,
+ ...(shouldFetch ? { startedAt: Date.now() } : {}),
+ };
+ }
+
const { data, isLoading } = useSWR(
shouldFetch ? ['agentSignalReceipts', input.agentId, input.topicId] : null,
async () => {
@@ -49,6 +67,8 @@ export const useAgentSignalReceipts = (input: {
receiptsRef.current = nextReceipts;
latestCreatedAtRef.current =
latestCreatedAt === undefined ? latestCreatedAtRef.current : latestCreatedAt;
+ pollingRef.current.emptyRefreshes =
+ result.receipts.length === 0 ? pollingRef.current.emptyRefreshes + 1 : 0;
return {
...result,
@@ -56,7 +76,22 @@ export const useAgentSignalReceipts = (input: {
};
},
{
- refreshInterval: shouldFetch ? AGENT_SIGNAL_RECEIPT_REFRESH_INTERVAL_MS : 0,
+ refreshInterval: () => {
+ if (!shouldFetch || pollingRef.current.startedAt === undefined) return 0;
+
+ const elapsedMs = Date.now() - pollingRef.current.startedAt;
+ const remainingMs = AGENT_SIGNAL_RECEIPT_POLLING_TIMEOUT_MS - elapsedMs;
+
+ if (remainingMs <= 0) return 0;
+
+ const emptyRefreshBackoffStep = Math.max(pollingRef.current.emptyRefreshes - 1, 0);
+ const nextIntervalMs = Math.min(
+ AGENT_SIGNAL_RECEIPT_INITIAL_REFRESH_INTERVAL_MS * 2 ** emptyRefreshBackoffStep,
+ AGENT_SIGNAL_RECEIPT_MAX_REFRESH_INTERVAL_MS,
+ );
+
+ return Math.min(nextIntervalMs, remainingMs);
+ },
refreshWhenHidden: false,
revalidateOnFocus: false,
},
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index f0b97651bae..44cff2a54d0 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -67,6 +67,8 @@ const ChatList = memo<ChatListProps>(
const activeAgentId = useChatStore((s) => s.activeAgentId);
const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
useFetchMessages(context, skipFetch);
+ const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);
+ const latestMessageId = displayMessageIds.at(-1);
// Skip fetching notebook and memories for share pages (they require authentication)
const isSharePage = !!context.topicShareId;
@@ -75,6 +77,7 @@ const ChatList = memo<ChatListProps>(
const { receiptsByAnchor, unanchoredReceipts } = useAgentSignalReceipts({
agentId: canShowAgentSignalReceipts ? activeAgentId : undefined,
enabled: canShowAgentSignalReceipts,
+ pollingSignal: latestMessageId,
topicId: canShowAgentSignalReceipts ? context.topicId : undefined,
});
@@ -85,8 +88,6 @@ const ChatList = memo<ChatListProps>(
// Use selectors for data
- const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);
-
const defaultItemContent = useCallback(
(index: number, id: string) => {
const isLatestItem = displayMessageIds.length === index + 1;