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.

♻️ refactor(chat): move Agent Signal receipts, the document chat topic and topic share info onto @lobechat/replica (#22849)

Arvin Xu7a62aa1639ec
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
index c342714f46b..6c83fa1d4df 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
@@ -18,6 +18,7 @@ import { useStableNavigate } from '@/hooks/useStableNavigate';
import { mutate } from '@/libs/swr';
import { userMemoryKeys } from '@/libs/swr/keys';
import { agentSignalService } from '@/services/agentSignal';
+import { agentSignalActions } from '@/store/agentSignal';
import { useChatStore } from '@/store/chat';
import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';
@@ -220,6 +221,10 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(
onRollbackStatusChange(receipt.id, status);
if (ROLLBACK_SUCCESS_STATUSES.has(status)) {
+ agentSignalActions.markReceiptRolledBack(
+ { agentId: receipt.agentId, topicId: receipt.topicId },
+ receipt.id,
+ );
// Drop the cached detail so an open Portal / memory page shows the memory is gone.
if (target?.type === 'memory' && target.memoryLayer && target.id) {
void mutate(userMemoryKeys.memoryDetail(target.memoryLayer, target.id));
@@ -265,7 +270,9 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(
}, [
canRollback,
onRollbackStatusChange,
+ receipt.agentId,
receipt.id,
+ receipt.topicId,
rollbackAgentDocumentId,
rollbackDocumentId,
rollbackHistoryId,
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.reload.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.reload.test.ts
new file mode 100644
index 00000000000..b6c294a4867
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.reload.test.ts
@@ -0,0 +1,208 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Agent Signal receipts survive a reload: the receipt chips of a topic paint
+ * from the local copy before the network answers, then follow the server.
+ * Each "reload" re-imports the module graph (fresh stores, fresh SWR cache)
+ * over the same IndexedDB.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { UIChatMessage } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const receipt = (id: string, createdAt: number, overrides: Record<string, unknown> = {}) => ({
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-1',
+ createdAt,
+ detail: 'Saved this for future replies',
+ id,
+ kind: 'memory' as const,
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied' as const,
+ title: `Memory ${id}`,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ ...overrides,
+});
+
+const displayMessages = [
+ { content: '', createdAt: 1, id: 'assistant-1', role: 'assistant', updatedAt: 1 },
+] as UIChatMessage[];
+
+const pending = () => new Promise<never>(() => {});
+
+/** A fresh module graph: what a page reload starts from (IndexedDB survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ const [{ useAgentSignalReceipts }, { agentSignalService }] = await Promise.all([
+ import('./useAgentSignalReceipts'),
+ import('@/services/agentSignal'),
+ ]);
+ const listReceipts = vi.spyOn(agentSignalService, 'listReceipts');
+ /** The main conversation and a floating panel on the same topic (one SWR cache). */
+ const renderTwo = () =>
+ renderHook(
+ () => {
+ const input = { agentId: 'agent-1', displayMessages, enabled: true, topicId: 'topic-1' };
+ useAgentSignalReceipts(input);
+ return useAgentSignalReceipts(input);
+ },
+ { wrapper },
+ );
+ const render = (topicId = 'topic-1') =>
+ renderHook(
+ () =>
+ useAgentSignalReceipts({
+ agentId: 'agent-1',
+ displayMessages,
+ enabled: true,
+ topicId,
+ }),
+ { wrapper },
+ );
+ return { listReceipts, render, renderTwo };
+};
+
+const titles = (result: { current: { receiptsByAnchor: Map<string, { title: string }[]> } }) =>
+ (result.current.receiptsByAnchor.get('assistant-1') ?? []).map((r) => r.title);
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+// Re-importing the module graph per reload is slow on a cold transform cache.
+describe('useAgentSignalReceipts across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `receipts-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('paints the previous session’s receipts before the network answers, then follows the server', async () => {
+ const first = await reload();
+ first.listReceipts.mockResolvedValue({ cursor: undefined, receipts: [receipt('a', 2)] });
+ const { result } = first.render();
+ await waitFor(() => expect(titles(result)).toEqual(['Memory a']));
+ await settle();
+
+ const second = await reload();
+ let answer!: (value: Awaited<ReturnType<typeof second.listReceipts>>) => void;
+ second.listReceipts.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const reloaded = second.render();
+
+ // Painted from the local copy while the request is still in flight…
+ await waitFor(() => expect(titles(reloaded.result)).toEqual(['Memory a']));
+ // …and the first read after a reload is a full head, not an increment.
+ expect(second.listReceipts).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ limit: 20,
+ topicId: 'topic-1',
+ });
+
+ await act(async () => {
+ answer({ cursor: undefined, receipts: [receipt('b', 3), receipt('a', 2)] });
+ });
+ await waitFor(() => expect(titles(reloaded.result)).toEqual(['Memory b', 'Memory a']));
+ });
+
+ it('keeps the receipts on screen when the refresh fails', async () => {
+ const first = await reload();
+ first.listReceipts.mockResolvedValue({ cursor: undefined, receipts: [receipt('a', 2)] });
+ first.render();
+ await settle();
+
+ const second = await reload();
+ second.listReceipts.mockRejectedValue(new Error('offline'));
+ const { result } = second.render();
+
+ await waitFor(() => expect(second.listReceipts).toHaveBeenCalled());
+ await settle();
+ expect(titles(result)).toEqual(['Memory a']);
+ });
+
+ it('does not show another identity’s receipts', async () => {
+ const first = await reload();
+ first.listReceipts.mockResolvedValue({ cursor: undefined, receipts: [receipt('a', 2)] });
+ first.render();
+ await settle();
+
+ scope.current = `receipts-user-${randomUUID()}:personal`;
+ const second = await reload();
+ second.listReceipts.mockImplementation(pending);
+ const { result } = second.render();
+ await settle();
+
+ expect(titles(result)).toEqual([]);
+ });
+
+ it('asks the server once for two views of the same topic', async () => {
+ const first = await reload();
+ first.listReceipts.mockResolvedValue({ cursor: undefined, receipts: [receipt('a', 2)] });
+ first.renderTwo();
+ await settle();
+
+ expect(first.listReceipts).toHaveBeenCalledTimes(1);
+ });
+
+ it('remembers an undone receipt across a reload', async () => {
+ const first = await reload();
+ first.listReceipts.mockResolvedValue({
+ cursor: undefined,
+ receipts: [receipt('a', 2, { metadata: { rollbackStatus: 'available' } })],
+ });
+ const { result } = first.render();
+ await waitFor(() => expect(titles(result)).toEqual(['Memory a']));
+
+ const { agentSignalActions } = await import('@/store/agentSignal');
+ act(() => {
+ agentSignalActions.markReceiptRolledBack({ agentId: 'agent-1', topicId: 'topic-1' }, 'a');
+ });
+ await settle();
+
+ const second = await reload();
+ second.listReceipts.mockImplementation(pending);
+ const reloaded = second.render();
+
+ await waitFor(() =>
+ expect(
+ reloaded.result.current.receiptsByAnchor.get('assistant-1')?.[0]?.metadata?.rollbackStatus,
+ ).toBe('rolled_back'),
+ );
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
index 0a00a9ce806..32d414128ab 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
@@ -5,7 +5,10 @@ import { createElement } from 'react';
import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheScope } from '@/libs/replica';
import { agentSignalService } from '@/services/agentSignal';
+import { useAgentSignalStore } from '@/store/agentSignal';
+import { initialState } from '@/store/agentSignal/initialState';
import { useAgentSignalReceipts } from './useAgentSignalReceipts';
@@ -26,6 +29,12 @@ const { receipt } = vi.hoisted(() => ({
},
}));
+// Poll timing only: persistence is covered by `src/store/agentSignal/replica.test.ts`.
+vi.mock('@/libs/swr', async () => {
+ const swr = await import('swr');
+ return { mutate: swr.mutate, useClientDataSWR: swr.default };
+});
+
vi.mock('@/services/agentSignal', () => ({
agentSignalService: {
listReceipts: vi.fn().mockResolvedValue({
@@ -50,6 +59,12 @@ describe('useAgentSignalReceipts', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
+ useAgentSignalStore.setState({ ...initialState });
+ const scope = crypto.randomUUID();
+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ vi.spyOn(cacheScope, 'canHydrate').mockReturnValue(false);
});
const renderReceiptsHook = (input: Parameters<typeof useAgentSignalReceipts>[0]) =>
@@ -292,8 +307,9 @@ describe('useAgentSignalReceipts', () => {
topicId: 'topic-1',
});
+ // Let the first request settle (it also writes the replica) before timing polls.
await act(async () => {
- await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(0);
});
expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(1);
@@ -325,8 +341,9 @@ describe('useAgentSignalReceipts', () => {
topicId: 'topic-1',
});
+ // Let the first request settle (it also writes the replica) before timing polls.
await act(async () => {
- await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(0);
});
expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(1);
@@ -361,8 +378,9 @@ describe('useAgentSignalReceipts', () => {
topicId: 'topic-1',
});
+ // Let the first request settle (it also writes the replica) before timing polls.
await act(async () => {
- await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(0);
});
await act(async () => {
@@ -396,8 +414,9 @@ describe('useAgentSignalReceipts', () => {
{ initialProps: { pollingSignal: 'assistant-1' }, wrapper },
);
+ // Let the first request settle (it also writes the replica) before timing polls.
await act(async () => {
- await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(0);
});
await act(async () => {
@@ -413,4 +432,85 @@ describe('useAgentSignalReceipts', () => {
});
expect(agentSignalService.listReceipts).toHaveBeenCalledTimes(callsAtTimeout + 1);
});
+
+ it('reads the full head again when a topic is reopened', async () => {
+ vi.useFakeTimers();
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValue({
+ cursor: undefined,
+ receipts: [receipt],
+ });
+
+ const { rerender } = renderHook(
+ ({ topicId }) =>
+ useAgentSignalReceipts({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: true,
+ topicId,
+ }),
+ { initialProps: { topicId: 'topic-1' }, wrapper },
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ rerender({ topicId: 'topic-2' });
+ // Past the dedupe window, so reopening topic-1 requests at once.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2500);
+ });
+
+ vi.mocked(agentSignalService.listReceipts).mockClear();
+ rerender({ topicId: 'topic-1' });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+
+ // An Undo made elsewhere changes an older receipt, which a `sinceCreatedAt`
+ // read would never return.
+ expect(vi.mocked(agentSignalService.listReceipts).mock.calls[0]?.[0]).toEqual({
+ agentId: 'agent-1',
+ limit: 20,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('keeps reconciling the full head when the reopen read fails', async () => {
+ vi.useFakeTimers();
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValue({
+ cursor: undefined,
+ receipts: [receipt],
+ });
+
+ const { rerender } = renderHook(
+ ({ topicId }) =>
+ useAgentSignalReceipts({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: true,
+ topicId,
+ }),
+ { initialProps: { topicId: 'topic-1' }, wrapper },
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ rerender({ topicId: 'topic-2' });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2500);
+ });
+
+ vi.mocked(agentSignalService.listReceipts).mockClear();
+ vi.mocked(agentSignalService.listReceipts).mockRejectedValueOnce(new Error('offline'));
+ rerender({ topicId: 'topic-1' });
+ // The reopen read fails, then SWR's error retry (2.5–7.5 s) runs.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(20_000);
+ });
+
+ const calls = vi.mocked(agentSignalService.listReceipts).mock.calls.map(([input]) => input);
+ expect(calls.length).toBeGreaterThanOrEqual(2);
+ // The retry is a full head too, so an Undo made elsewhere still reaches this view.
+ expect(calls[1]).toEqual({ agentId: 'agent-1', limit: 20, topicId: 'topic-1' });
+ });
});
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
index 07b8c2aa5bd..fb227ead9e9 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
@@ -1,12 +1,18 @@
import type { UIChatMessage } from '@lobechat/types';
import { useMemo, useRef } from 'react';
-import useSWR from 'swr';
-import { agentSignalKeys } from '@/libs/swr/keys';
-import { agentSignalService } from '@/services/agentSignal';
+import {
+ agentSignalActions,
+ type AgentSignalReceiptsParams,
+ type AgentSignalReceiptView,
+ agentSignalSelectors,
+ useAgentSignalStore,
+} from '@/store/agentSignal';
import { collectSteerChains } from '../../store/slices/data/steerChains';
+export type { AgentSignalReceiptView } from '@/store/agentSignal';
+
/** Poll cadence for the active conversation's Agent Signal receipt surface. */
const AGENT_SIGNAL_RECEIPT_INITIAL_REFRESH_INTERVAL_MS = 3000;
@@ -16,9 +22,7 @@ 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>
->['receipts'][number];
+const EMPTY_RECEIPTS: AgentSignalReceiptView[] = [];
export const useAgentSignalReceipts = (input: {
agentId?: string | null;
@@ -29,80 +33,51 @@ export const useAgentSignalReceipts = (input: {
}) => {
// 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 params = useMemo<AgentSignalReceiptsParams | null>(
+ () => (shouldFetch ? { agentId: input.agentId!, topicId: input.topicId! } : null),
+ [shouldFetch, input.agentId, input.topicId],
+ );
+ const scopeKey = params ? `${params.agentId}:${params.topicId}` : undefined;
+ const pollingKey = scopeKey ? `${scopeKey}:${input.pollingSignal ?? ''}` : 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[]>([]);
+ const pollingKeyRef = useRef<string | undefined>(undefined);
+ const pollingRef = useRef<{ params: AgentSignalReceiptsParams | null; startedAt?: number }>({
+ params: null,
+ });
+ // Opening a topic (again) reconciles its whole head; polls stay incremental.
if (scopeKeyRef.current !== scopeKey) {
scopeKeyRef.current = scopeKey;
- latestCreatedAtRef.current = undefined;
- receiptsRef.current = [];
+ if (params) agentSignalActions.requestFullReceiptHead(params);
}
if (pollingKeyRef.current !== pollingKey) {
pollingKeyRef.current = pollingKey;
- pollingRef.current = {
- emptyRefreshes: 0,
- ...(shouldFetch ? { startedAt: Date.now() } : {}),
- };
+ pollingRef.current = { params, ...(params ? { startedAt: Date.now() } : {}) };
+ if (params) agentSignalActions.resetReceiptPolling(params);
}
- const { data, isLoading } = useSWR(
- shouldFetch ? agentSignalKeys.receipts(input.agentId!, input.topicId!) : null,
- async () => {
- const result = await agentSignalService.listReceipts({
- agentId: input.agentId!,
- limit: 20,
- ...(latestCreatedAtRef.current === undefined
- ? {}
- : { sinceCreatedAt: latestCreatedAtRef.current }),
- topicId: input.topicId!,
- });
-
- const nextReceipts =
- latestCreatedAtRef.current === undefined
- ? result.receipts
- : mergeReceiptRefresh(receiptsRef.current, result.receipts);
- const latestCreatedAt = nextReceipts[0]?.createdAt;
-
- receiptsRef.current = nextReceipts;
- latestCreatedAtRef.current =
- latestCreatedAt === undefined ? latestCreatedAtRef.current : latestCreatedAt;
- pollingRef.current.emptyRefreshes =
- result.receipts.length === 0 ? pollingRef.current.emptyRefreshes + 1 : 0;
-
- return {
- ...result,
- receipts: nextReceipts,
- };
- },
- {
- refreshInterval: () => {
- if (!shouldFetch || pollingRef.current.startedAt === undefined) return 0;
+ agentSignalActions.useFetchReceipts(params, {
+ refreshInterval: () => {
+ const { params: polled, startedAt } = pollingRef.current;
+ if (!polled || startedAt === undefined) return 0;
- const elapsedMs = Date.now() - pollingRef.current.startedAt;
- const remainingMs = AGENT_SIGNAL_RECEIPT_POLLING_TIMEOUT_MS - elapsedMs;
+ const elapsedMs = Date.now() - startedAt;
+ const remainingMs = AGENT_SIGNAL_RECEIPT_POLLING_TIMEOUT_MS - elapsedMs;
- if (remainingMs <= 0) return 0;
+ 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,
- );
+ const emptyRefreshBackoffStep = Math.max(agentSignalActions.getEmptyRefreshes(polled) - 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,
+ return Math.min(nextIntervalMs, remainingMs);
},
- );
+ });
- const receipts = data?.receipts ?? [];
+ const receipts = useAgentSignalStore(agentSignalSelectors.getReceipts(params)) ?? EMPTY_RECEIPTS;
const receiptsByAnchor = useMemo(
() =>
@@ -113,10 +88,7 @@ export const useAgentSignalReceipts = (input: {
[input.displayMessages, receipts],
);
- return {
- isLoading,
- receiptsByAnchor,
- };
+ return { receiptsByAnchor };
};
interface GroupAgentSignalReceiptsByEffectiveAnchorInput {
@@ -196,18 +168,3 @@ const groupAgentSignalReceiptsByEffectiveAnchor = ({
return receiptsByAnchor;
};
-
-const mergeReceiptRefresh = (
- currentReceipts: AgentSignalReceiptView[],
- newReceipts: AgentSignalReceiptView[],
-) => {
- if (newReceipts.length === 0) return currentReceipts;
-
- const mergedById = new Map(currentReceipts.map((receipt) => [receipt.id, receipt]));
-
- for (const receipt of newReceipts) {
- mergedById.set(receipt.id, receipt);
- }
-
- return [...mergedById.values()].sort((a, b) => b.createdAt - a.createdAt).slice(0, 20);
-};
diff --git a/src/features/FloatingChatPanel/useDocumentChatTopic.reload.test.ts b/src/features/FloatingChatPanel/useDocumentChatTopic.reload.test.ts
new file mode 100644
index 00000000000..311b5950bab
--- /dev/null
+++ b/src/features/FloatingChatPanel/useDocumentChatTopic.reload.test.ts
@@ -0,0 +1,137 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The document page's floating chat panel resolves its topic from the local
+ * copy after a reload, before `getOrCreateChatTopic` answers. Each "reload"
+ * re-imports the module graph (fresh stores, fresh SWR cache) over the same
+ * IndexedDB.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const PARAMS = { agentId: 'agent-1', documentId: 'docs_1' };
+
+const pending = () => new Promise<never>(() => {});
+
+/** A fresh module graph: what a page reload starts from (IndexedDB survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ const [{ useDocumentChatTopic }, { agentDocumentService }] = await Promise.all([
+ import('./useDocumentChatTopic'),
+ import('@/services/agentDocument'),
+ ]);
+ const getOrCreate = vi.spyOn(agentDocumentService, 'getOrCreateChatTopic');
+ const render = (params: { agentId?: string; documentId?: string } = PARAMS) =>
+ renderHook(
+ () => useDocumentChatTopic({ agentId: params.agentId, documentId: params.documentId }),
+ { wrapper },
+ );
+ return { getOrCreate, render };
+};
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+// Re-importing the module graph per reload is slow on a cold transform cache.
+describe('useDocumentChatTopic across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `doc-topic-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('resolves the previous session’s topic before the server answers, then follows it', async () => {
+ const first = await reload();
+ first.getOrCreate.mockResolvedValue({ topicId: 'tpc_doc' });
+ const { result } = first.render();
+ await waitFor(() => expect(result.current.topicId).toBe('tpc_doc'));
+ await settle();
+
+ const second = await reload();
+ let answer!: (value: { topicId: string }) => void;
+ second.getOrCreate.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const reloaded = second.render();
+
+ await waitFor(() => expect(reloaded.result.current.topicId).toBe('tpc_doc'));
+ expect(second.getOrCreate).toHaveBeenCalledWith(PARAMS);
+
+ // The topic was deleted elsewhere and get-or-create provisioned a new one.
+ await act(async () => {
+ answer({ topicId: 'tpc_new' });
+ });
+ await waitFor(() => expect(reloaded.result.current.topicId).toBe('tpc_new'));
+ });
+
+ it('keeps each document’s topic apart', async () => {
+ const first = await reload();
+ first.getOrCreate.mockResolvedValue({ topicId: 'tpc_doc' });
+ first.render();
+ await settle();
+
+ const second = await reload();
+ second.getOrCreate.mockImplementation(pending);
+ const other = second.render({ agentId: 'agent-2', documentId: 'docs_1' });
+ await settle();
+
+ expect(other.result.current.topicId).toBeUndefined();
+ });
+
+ it('does not resolve another identity’s topic', async () => {
+ const first = await reload();
+ first.getOrCreate.mockResolvedValue({ topicId: 'tpc_doc' });
+ first.render();
+ await settle();
+
+ scope.current = `doc-topic-user-${randomUUID()}:personal`;
+ const second = await reload();
+ second.getOrCreate.mockImplementation(pending);
+ const { result } = second.render();
+ await settle();
+
+ expect(result.current.topicId).toBeUndefined();
+ });
+
+ it('does not call get-or-create before ownership is proven', async () => {
+ const first = await reload();
+ first.render({ agentId: undefined, documentId: undefined });
+ await settle();
+
+ expect(first.getOrCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/FloatingChatPanel/useDocumentChatTopic.ts b/src/features/FloatingChatPanel/useDocumentChatTopic.ts
index 725acbbcdd5..763f6f0bea4 100644
--- a/src/features/FloatingChatPanel/useDocumentChatTopic.ts
+++ b/src/features/FloatingChatPanel/useDocumentChatTopic.ts
@@ -1,20 +1,25 @@
import debug from 'debug';
-import { useEffect } from 'react';
+import { useEffect, useMemo } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
+import {
+ agentDocumentActions,
+ agentDocumentSelectors,
+ useAgentDocumentStore,
+} from '@/store/agentDocument';
const log = debug('lobe-chat:useDocumentChatTopic');
/**
* Resolve the doc-anchored chat topic for an `(agentId, documentId)` pair.
*
- * Backed by `agentDocument.getOrCreateChatTopic`, which is idempotent and
- * marks the topic with `trigger='document'` so it is filtered out of the
- * regular chat sidebar. The first call provisions the topic + the
- * `topic_documents` association; subsequent calls return the same topic id.
+ * Backed by the `agentDocumentChatTopic` replica over
+ * `agentDocument.getOrCreateChatTopic`, which is idempotent and marks the topic
+ * with `trigger='document'` so it is filtered out of the regular chat sidebar.
+ * The first call provisions the topic + the `topic_documents` association;
+ * subsequent calls return the same topic id. The resolved id is persisted, so a
+ * reload paints the panel's conversation before the server confirms it.
*
- * Returns `topicId: undefined` until the request resolves; callers should gate
+ * Returns `topicId: undefined` until an id is known; callers should gate
* rendering on a non-undefined value to avoid mounting a chat panel without a
* topic anchor.
*/
@@ -24,13 +29,14 @@ export const useDocumentChatTopic = (params: {
}) => {
const { agentId, documentId } = params;
const enabled = !!agentId && !!documentId;
- const { data, error, isLoading } = useClientDataSWR(
- enabled ? agentDocumentSWRKeys.documentChatTopic(agentId, documentId) : null,
- () =>
- agentDocumentService.getOrCreateChatTopic({
- agentId: agentId!,
- documentId: documentId!,
- }),
+ const replicaParams = useMemo(
+ () => (agentId && documentId ? { agentId, documentId } : null),
+ [agentId, documentId],
+ );
+ const { error, isHydrated, isValidating } =
+ agentDocumentActions.useFetchDocumentChatTopic(replicaParams);
+ const topicId = useAgentDocumentStore(
+ agentDocumentSelectors.getDocumentChatTopicId(replicaParams),
);
useEffect(() => {
@@ -49,8 +55,12 @@ export const useDocumentChatTopic = (params: {
});
return;
}
- if (data?.topicId) log('resolved topicId=%s for (%s, %s)', data.topicId, agentId, documentId);
- }, [enabled, agentId, documentId, data?.topicId, error]);
+ if (topicId) log('resolved topicId=%s for (%s, %s)', topicId, agentId, documentId);
+ }, [enabled, agentId, documentId, topicId, error]);
- return { error, isLoading, topicId: data?.topicId };
+ return {
+ error,
+ isLoading: enabled && !topicId && !error && (!isHydrated || isValidating),
+ topicId,
+ };
};
diff --git a/src/features/SharePopover/useTopicShare.reload.test.ts b/src/features/SharePopover/useTopicShare.reload.test.ts
new file mode 100644
index 00000000000..7f36e00da21
--- /dev/null
+++ b/src/features/SharePopover/useTopicShare.reload.test.ts
@@ -0,0 +1,198 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The topic Share popover paints the previous session's share record before
+ * the network answers. Each "reload" re-imports the module graph (fresh
+ * stores, fresh SWR cache) over the same IndexedDB.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const TOPIC_ID = 'topic-share-1';
+const record = (visibility: 'link' | 'private') => ({
+ id: 'share-1',
+ topicId: TOPIC_ID,
+ userId: 'user-1',
+ visibility,
+});
+
+const pending = () => new Promise<never>(() => {});
+
+/** A fresh module graph: what a page reload starts from (IndexedDB survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ const [{ useTopicShare }, { topicService }] = await Promise.all([
+ import('./useTopicShare'),
+ import('@/services/topic'),
+ ]);
+ const getShareInfo = vi.spyOn(topicService, 'getShareInfo');
+ const enableSharing = vi.spyOn(topicService, 'enableSharing');
+ const render = () => renderHook(() => useTopicShare(TOPIC_ID, true), { wrapper });
+ /** Two popovers in one app (one SWR cache), e.g. the header and the topic menu. */
+ const renderTwo = () =>
+ renderHook(
+ () => {
+ useTopicShare(TOPIC_ID, true);
+ return useTopicShare(TOPIC_ID, true);
+ },
+ { wrapper },
+ );
+ return { enableSharing, getShareInfo, render, renderTwo };
+};
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+// Re-importing the module graph per reload is slow on a cold transform cache.
+describe('useTopicShare across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `share-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('paints the previous session’s share record before the network answers', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(record('link') as never);
+ const { result } = first.render();
+ await waitFor(() => expect(result.current.visibility).toBe('link'));
+ await settle();
+
+ const second = await reload();
+ second.getShareInfo.mockImplementation(pending);
+ const reloaded = second.render();
+
+ await waitFor(() => expect(reloaded.result.current.isLoading).toBe(false));
+ expect(reloaded.result.current.visibility).toBe('link');
+ expect(reloaded.result.current.shareInfo?.id).toBe('share-1');
+ });
+
+ it('keeps a visibility change across a reload', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(null as never);
+ first.enableSharing.mockResolvedValue(record('link') as never);
+ const { result } = first.render();
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ await act(async () => {
+ await result.current.setVisibility('link');
+ });
+ expect(result.current.visibility).toBe('link');
+ await settle();
+
+ const second = await reload();
+ second.getShareInfo.mockImplementation(pending);
+ const reloaded = second.render();
+
+ await waitFor(() => expect(reloaded.result.current.visibility).toBe('link'));
+ });
+
+ it('waits for the server instead of painting a remembered "no share record" as private', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(null as never);
+ const { result } = first.render();
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ await settle();
+
+ const second = await reload();
+ second.getShareInfo.mockImplementation(pending);
+ const reloaded = second.render();
+ await settle();
+
+ expect(reloaded.result.current.isLoading).toBe(true);
+ });
+
+ it('keeps the record on screen, without an error, when the refresh fails', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(record('link') as never);
+ first.render();
+ await settle();
+
+ const second = await reload();
+ second.getShareInfo.mockRejectedValue(new Error('offline'));
+ const { result } = second.render();
+ await waitFor(() => expect(second.getShareInfo).toHaveBeenCalled());
+ await settle();
+
+ expect(result.current.visibility).toBe('link');
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('asks the server once for popovers mounted together', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(record('private') as never);
+ first.renderTwo();
+ await settle();
+
+ expect(first.getShareInfo).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not adopt a share change into the identity switched to while it was in flight', async () => {
+ const first = await reload();
+ first.getShareInfo.mockResolvedValue(null as never);
+ let answer!: (value: ReturnType<typeof record>) => void;
+ first.enableSharing.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve as never;
+ }) as never,
+ );
+ const { rerender, result } = first.render();
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ let change!: Promise<unknown>;
+ act(() => {
+ change = result.current.setVisibility('link');
+ });
+
+ // The user switches workspace while the request is in flight; the new
+ // identity's own read has not answered yet.
+ first.getShareInfo.mockImplementation(pending);
+ scope.current = `share-user-${randomUUID()}:ws-2`;
+ rerender();
+ await act(async () => {
+ answer(record('link'));
+ await change;
+ });
+ await settle();
+
+ const second = await reload();
+ second.getShareInfo.mockImplementation(pending);
+ const reloaded = second.render();
+ await settle();
+
+ // Nothing was persisted for the new identity: it waits for its own server answer.
+ expect(reloaded.result.current.isLoading).toBe(true);
+ });
+});
diff --git a/src/features/SharePopover/useTopicShare.ts b/src/features/SharePopover/useTopicShare.ts
index ed07a46ea99..2ab62a074ae 100644
--- a/src/features/SharePopover/useTopicShare.ts
+++ b/src/features/SharePopover/useTopicShare.ts
@@ -1,48 +1,40 @@
import { useCallback } from 'react';
-import useSWR from 'swr';
-import { shareKeys } from '@/libs/swr/keys';
-import { topicService } from '@/services/topic';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import type { TopicShareVisibility } from '@/store/chat/slices/topic/projection';
-export type ShareVisibility = 'private' | 'link';
+export type ShareVisibility = TopicShareVisibility;
/**
- * Share record of a topic. A topic without a record is private: the record is
- * created on the first visibility change rather than when the share UI opens,
- * so opening it never waits on a write.
+ * Share record of a topic, from the topic share replica. A topic without a
+ * record is private: the record is created on the first visibility change
+ * rather than when the share UI opens, so opening it never waits on a write.
+ * A persisted record paints at once while the server confirms it.
*/
export const useTopicShare = (topicId: string | undefined, enabled: boolean) => {
- const { data, error, isLoading, mutate } = useSWR(
- topicId && enabled ? shareKeys.topicInfo(topicId) : null,
- () => topicService.getShareInfo(topicId!),
- { revalidateOnFocus: false },
- );
+ const { error, revalidate } = useChatStore((s) => s.useFetchTopicShare)(topicId, enabled);
+ const entry = useChatStore(topicSelectors.getTopicShare(enabled ? topicId : undefined));
+ const setTopicShareVisibility = useChatStore((s) => s.setTopicShareVisibility);
/** Resolves to the share id after the change. */
const setVisibility = useCallback(
async (visibility: ShareVisibility) => {
if (!topicId) return;
-
- let record = data
- ? await topicService.updateShareVisibility(topicId, visibility)
- : await topicService.enableSharing(topicId, visibility);
- // A stale cache can miss a record created elsewhere; create then keeps
- // the existing visibility, so apply the requested one on top.
- if (record && record.visibility !== visibility)
- record = await topicService.updateShareVisibility(topicId, visibility);
-
- await mutate();
- return record?.id ?? data?.id;
+ return setTopicShareVisibility(topicId, visibility);
},
- [data, mutate, topicId],
+ [setTopicShareVisibility, topicId],
);
+ const shareInfo = entry?.share ?? undefined;
+
return {
- error,
- isLoading,
- retry: mutate,
+ // A failed refresh keeps the record on screen; only a first load surfaces it.
+ error: entry ? undefined : error,
+ isLoading: !!topicId && enabled && !entry && !error,
+ retry: revalidate,
setVisibility,
- shareInfo: data,
- visibility: (data?.visibility as ShareVisibility) || 'private',
+ shareInfo,
+ visibility: (shareInfo?.visibility as ShareVisibility) || 'private',
};
};
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index 3f617849a6f..3eb91b4a6ef 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -16,7 +16,6 @@ const LEGACY_SWR_KEYS = [
'acceptanceCollaborationKeys.conversation',
'agentConfigKeys.search',
'agentHomeKeys.topics',
- 'agentSignalKeys.receipts',
'apiKeyKeys.list',
'authKeys.oidcClientMetadata',
'authKeys.oidcInteraction',
@@ -117,7 +116,6 @@ const LEGACY_SWR_KEYS = [
'shareKeys.file',
'shareKeys.pageDocument',
'shareKeys.topic',
- 'shareKeys.topicInfo',
'shareKeys.visitorTopics',
'taskLabelKeys.list',
'threadKeys.list',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 723b70fb107..cc07296787b 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -17,15 +17,9 @@
*
* Each factory also exposes `.root` (the namespace string) for `mutate`
* matchers that compare `key[0]`.
- *
- * Document / page / agent-document keys are defined in
- * `@/services/document/swrKeys` (already a factory, widely imported) and
- * re-exported here so the whole set is reachable from one place.
*/
import { type ConversationContext } from '@lobechat/types';
-import { agentDocumentSWRKeys } from '@/services/document/swrKeys';
-
type KeyFactory<A extends unknown[]> = ((...args: A) => readonly unknown[]) & { root: string };
/** Define a key factory carrying its namespace root (for `mutate` matchers). */
@@ -511,7 +505,7 @@ export const fileKeys = {
// =========================================================================
// UI-layer keys (features / routes / components). Prefixes below stay
// memory-only unless explicitly listed in `CACHE_TIERS`. Names avoid colliding
-// with cached prefixes — e.g. share/topicInfo is `share:` not `topic:`, portal
+// with cached prefixes — e.g. share/topic is `share:` not `topic:`, portal
// header is `portal:` not `document:`.
// =========================================================================
@@ -623,7 +617,6 @@ export const shareKeys = {
documentId,
]),
topic: def('share:topic', (id: string) => ['share:topic', id]),
- topicInfo: def('share:topicInfo', (topicId: string) => ['share:topicInfo', topicId]),
/** The visitor's own topics under an agent share (server-scoped by senderId). */
visitorTopics: def('share:visitorTopics', (shareId: string) => ['share:visitorTopics', shareId]),
};
@@ -726,17 +719,10 @@ export const onboardingKeys = {
understandingTopic: def('onboarding:understandingTopic', () => ['onboarding:understandingTopic']),
};
-// ---- agent home / profile / signal (kept off the `agent:` idb tier) -----
+// ---- agent home / profile (kept off the `agent:` idb tier) -----
export const agentHomeKeys = {
topics: def('agentHome:topics', (agentId: string) => ['agentHome:topics', agentId]),
};
-export const agentSignalKeys = {
- receipts: def('agentSignal:receipts', (agentId: string, topicId: string) => [
- 'agentSignal:receipts',
- agentId,
- topicId,
- ]),
-};
// ---- bot wake records (one bot's judged messages; never persisted) ----
export const botWakeKeys = {
@@ -844,9 +830,7 @@ export const taskLabelKeys = {
export const swrKeys = {
agent: agentConfigKeys,
- agentDocument: agentDocumentSWRKeys,
agentHome: agentHomeKeys,
- agentSignal: agentSignalKeys,
auth: authKeys,
canvas: canvasKeys,
changelog: changelogKeys,
diff --git a/src/routes/(main)/agent/docs/documentListLoader.ts b/src/routes/(main)/agent/docs/documentListLoader.ts
index 995a152f55e..df7899eaddd 100644
--- a/src/routes/(main)/agent/docs/documentListLoader.ts
+++ b/src/routes/(main)/agent/docs/documentListLoader.ts
@@ -2,17 +2,27 @@ import type { LoaderFunctionArgs } from 'react-router';
import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
import { agentDocumentActions } from '@/store/agentDocument';
+import { getIdFromIdentifier } from '@/utils/identifier';
/**
* Route loader for the agent documents surface (`/agent/:aid/docs/*`).
*
* Route loaders run before React commits the route: the only point where the
* persisted document list (an async IndexedDB read) can land before the docs
- * sidebar paints its loading spinner.
+ * sidebar paints its loading spinner. On a document route it also seeds that
+ * document's chat topic id, so the floating chat panel opens on its
+ * conversation without waiting for the get-or-create round-trip.
*/
export const agentDocumentListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
+ const documentId = params.docId ? getIdFromIdentifier(params.docId, 'docs') : undefined;
+
await settleWithin(
- agentDocumentActions.preHydrateDocumentList(params.aid),
+ Promise.all([
+ agentDocumentActions.preHydrateDocumentList(params.aid),
+ params.aid && documentId
+ ? agentDocumentActions.preHydrateDocumentChatTopic({ agentId: params.aid, documentId })
+ : false,
+ ]),
PRE_PAINT_HYDRATE_TIMEOUT,
);
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index f6445e14a0b..123041f24f1 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -8,8 +8,6 @@ import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';
-export { agentDocumentSWRKeys } from '@/services/document/swrKeys';
-
const revalidateAgentDocuments = async (agentId: string) => {
await invalidateDocumentMutation({ agentId, cause: 'agent-document' });
};
diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.ts
deleted file mode 100644
index 3a01c1c6a52..00000000000
--- a/src/services/document/swrKeys.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// Domain-namespaced SWR key roots. See the central registry in `@/libs/swr/keys`.
-// The agent's document list and the read-only reader are replicas
-// (`@/store/agentDocument`), so they have no SWR key here.
-export const agentDocumentSWRKeys = {
- documentChatTopic: (agentId: string, documentId: string) =>
- ['agent:documentChatTopic', agentId, documentId] as const,
-};
diff --git a/src/store/agentDocument/action.ts b/src/store/agentDocument/action.ts
index 6f3ad674759..3b4beca0602 100644
--- a/src/store/agentDocument/action.ts
+++ b/src/store/agentDocument/action.ts
@@ -79,6 +79,30 @@ export class AgentDocumentActionImpl {
return this.#private.reader.hydrate(params, scope);
};
+ /**
+ * Seed the document's persisted chat topic id before the page mounts, so the
+ * floating chat panel opens on its conversation without waiting for the
+ * get-or-create round-trip. Resolves `true` when a persisted id landed.
+ */
+ preHydrateDocumentChatTopic = (params?: AgentDocumentReaderParams | null): Promise<boolean> => {
+ if (!params?.agentId || !params.documentId) return Promise.resolve(false);
+
+ const scope = cacheScope.get();
+ this.#private.chatTopic.ensureScope(scope);
+ return this.#private.chatTopic.hydrate(params, scope);
+ };
+
+ /**
+ * Fetch orchestration for the document's chat topic (get-or-create, so it
+ * runs only once the caller has proven the agent owns the document). Read the
+ * id with `agentDocumentSelectors.getDocumentChatTopicId`.
+ */
+ useFetchDocumentChatTopic = (params?: AgentDocumentReaderParams | null): ReplicaSyncResult =>
+ this.#private.chatTopic.useSync(params?.agentId && params.documentId ? params : null, {
+ dedupingInterval: 10_000,
+ revalidateOnFocus: false,
+ });
+
/** Fetch orchestration for the read-only reader; read it with `getReaderDocument`. */
useFetchReaderDocument = (params?: AgentDocumentReaderParams | null): ReplicaSyncResult =>
this.#private.reader.useSync(params?.agentId && params.documentId ? params : null, {
diff --git a/src/store/agentDocument/initialState.ts b/src/store/agentDocument/initialState.ts
index 6d8153e5b2c..8705a1f9fc2 100644
--- a/src/store/agentDocument/initialState.ts
+++ b/src/store/agentDocument/initialState.ts
@@ -1,9 +1,13 @@
import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type { AgentDocumentListItem } from '@/services/agentDocument';
-import type { AgentDocumentReaderDetail } from './projection';
+import type { AgentDocumentChatTopic, AgentDocumentReaderDetail } from './projection';
export interface AgentDocumentState {
+ /** Doc-anchored chat topics (`agentDocumentChatTopicMap[agentDocumentReaderKey(params)]`). */
+ agentDocumentChatTopicMap: Record<string, AgentDocumentChatTopic>;
+ /** Replica bookkeeping for `agentDocumentChatTopicMap`. */
+ agentDocumentChatTopicReplica: ReplicaState<AgentDocumentChatTopic>;
/** Full document list per agent (`agentDocumentListMap[agentId]`). */
agentDocumentListMap: Record<string, AgentDocumentListItem[]>;
/** Replica bookkeeping for `agentDocumentListMap`. */
@@ -15,6 +19,8 @@ export interface AgentDocumentState {
}
export const initialState: AgentDocumentState = {
+ agentDocumentChatTopicMap: {},
+ agentDocumentChatTopicReplica: createReplicaState(),
agentDocumentListMap: {},
agentDocumentListReplica: createReplicaState(),
agentDocumentReaderMap: {},
diff --git a/src/store/agentDocument/privateAction.ts b/src/store/agentDocument/privateAction.ts
index a23fb402537..f1335cbe771 100644
--- a/src/store/agentDocument/privateAction.ts
+++ b/src/store/agentDocument/privateAction.ts
@@ -5,6 +5,8 @@ import { isTrpcErrorCode } from '@/utils/trpcError';
import { type AgentDocumentState } from './initialState';
import {
+ type AgentDocumentChatTopic,
+ agentDocumentChatTopicResource,
agentDocumentListResource,
type AgentDocumentReaderDetail,
agentDocumentReaderResource,
@@ -16,10 +18,22 @@ type Setter = StoreSetter<AgentDocumentState>;
const READER_ACCESS_LOST = ['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED'] as const;
export class AgentDocumentPrivateAction {
+ readonly chatTopic;
readonly list;
readonly reader;
constructor(set: Setter, get: () => AgentDocumentState) {
+ this.chatTopic = createReplicaSlice(agentDocumentChatTopicResource, {
+ actionPrefix: 'agentDocumentChatTopic',
+ fetcher: async (params) => {
+ const { topicId } = await agentDocumentService.getOrCreateChatTopic(params);
+ return { topicId };
+ },
+ get,
+ set,
+ stateKey: 'agentDocumentChatTopicReplica',
+ view: recordLens<AgentDocumentState, AgentDocumentChatTopic>('agentDocumentChatTopicMap'),
+ });
this.list = createReplicaSlice(agentDocumentListResource, {
actionPrefix: 'agentDocumentList',
fetcher: (agentId) => agentDocumentService.listDocuments({ agentId }),
diff --git a/src/store/agentDocument/projection.ts b/src/store/agentDocument/projection.ts
index c990a0d307f..35db2f2b7e5 100644
--- a/src/store/agentDocument/projection.ts
+++ b/src/store/agentDocument/projection.ts
@@ -5,6 +5,8 @@ import type { AgentDocumentListItem } from '@/services/agentDocument';
const MAX_PERSISTED_AGENT_DOCUMENT_LISTS = 30;
/** Reader documents whose body survives a reload, most recently used first. */
const MAX_PERSISTED_READER_DOCUMENTS = 20;
+/** Document chat topic ids that survive a reload, most recently used first. */
+const MAX_PERSISTED_DOCUMENT_CHAT_TOPICS = 50;
/**
* One agent's full document list (documents, web clips and skill bundles),
@@ -81,3 +83,26 @@ export const agentDocumentReaderResource = defineReplica<
storage: 'indexedDB',
version: 1,
});
+
+/** The doc-anchored chat topic of an agent document; only its id is kept. */
+export interface AgentDocumentChatTopic {
+ topicId: string;
+}
+
+/**
+ * The floating chat panel's topic for one agent + document
+ * (`agentDocumentChatTopicMap[agentDocumentReaderKey(params)]`). The read is
+ * `getOrCreateChatTopic`, which provisions the topic on the first call and is
+ * idempotent after that, so only the resolved id is stored: a reload mounts the
+ * panel on it at once while the server confirms it.
+ */
+export const agentDocumentChatTopicResource = defineReplica<
+ AgentDocumentReaderParams,
+ AgentDocumentChatTopic
+>({
+ key: agentDocumentReaderKey,
+ name: 'agentDocumentChatTopic',
+ persist: { maxEntries: MAX_PERSISTED_DOCUMENT_CHAT_TOPICS },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/agentDocument/replica.test.ts b/src/store/agentDocument/replica.test.ts
index 05453ac3b30..98a000ad826 100644
--- a/src/store/agentDocument/replica.test.ts
+++ b/src/store/agentDocument/replica.test.ts
@@ -22,6 +22,7 @@ import { type AgentDocumentListItem, agentDocumentService } from '@/services/age
import { agentDocumentActions } from './action';
import { initialState } from './initialState';
import {
+ agentDocumentChatTopicResource,
agentDocumentListResource,
type AgentDocumentReaderParams,
agentDocumentReaderResource,
@@ -66,6 +67,7 @@ const reader = () =>
const LIST_KEY = agentDocumentListResource.storageKey(AGENT_ID);
const READER_KEY = agentDocumentReaderResource.storageKey(READER);
+const CHAT_TOPIC_KEY = agentDocumentChatTopicResource.storageKey(READER);
describe('agent document replicas', () => {
const scopes = new Set<string>();
@@ -95,6 +97,7 @@ describe('agent document replicas', () => {
[...scopes].flatMap((value) => [
agentDocumentListResource.storage!.remove({ queryKey: LIST_KEY, scope: value }),
agentDocumentReaderResource.storage!.remove({ queryKey: READER_KEY, scope: value }),
+ agentDocumentChatTopicResource.storage!.remove({ queryKey: CHAT_TOPIC_KEY, scope: value }),
]),
);
scopes.clear();
@@ -102,6 +105,32 @@ describe('agent document replicas', () => {
vi.clearAllMocks();
});
+ describe('document chat topic', () => {
+ const topicId = () =>
+ agentDocumentSelectors.getDocumentChatTopicId(READER)(useAgentDocumentStore.getState());
+
+ it('seeds the persisted topic id before the page mounts, for the docs route loader', async () => {
+ await agentDocumentChatTopicResource.storage!.set(
+ { queryKey: CHAT_TOPIC_KEY, scope },
+ { data: { topicId: 'tpc_doc' }, updatedAt: 1 },
+ );
+ const getOrCreate = vi.spyOn(agentDocumentService, 'getOrCreateChatTopic');
+
+ await expect(agentDocumentActions.preHydrateDocumentChatTopic(READER)).resolves.toBe(true);
+
+ expect(topicId()).toBe('tpc_doc');
+ // Seeding never provisions a topic: get-or-create waits for the ownership-gated sync.
+ expect(getOrCreate).not.toHaveBeenCalled();
+ });
+
+ it('leaves the topic unresolved when nothing is persisted or no document is routed', async () => {
+ await expect(agentDocumentActions.preHydrateDocumentChatTopic(READER)).resolves.toBe(false);
+ await expect(agentDocumentActions.preHydrateDocumentChatTopic(null)).resolves.toBe(false);
+
+ expect(topicId()).toBeUndefined();
+ });
+ });
+
describe('document list', () => {
const renderSync = () =>
renderHook(() => agentDocumentActions.useFetchDocumentList(AGENT_ID), { wrapper });
diff --git a/src/store/agentDocument/selectors.ts b/src/store/agentDocument/selectors.ts
index d2631d59918..4efbf0ae945 100644
--- a/src/store/agentDocument/selectors.ts
+++ b/src/store/agentDocument/selectors.ts
@@ -31,7 +31,16 @@ const getReaderDocument =
(s: AgentDocumentState): AgentDocumentReaderDetail | undefined =>
params ? s.agentDocumentReaderMap[agentDocumentReaderKey(params)] : undefined;
+/** The document's chat topic id, or `undefined` before its first paint. */
+const getDocumentChatTopicId =
+ (params?: AgentDocumentReaderParams | null) =>
+ (s: AgentDocumentState): string | undefined =>
+ params?.agentId && params.documentId
+ ? s.agentDocumentChatTopicMap[agentDocumentReaderKey(params)]?.topicId
+ : undefined;
+
export const agentDocumentSelectors = {
+ getDocumentChatTopicId,
getDocumentList,
getReaderDocument,
isDocumentListConfirmed,
diff --git a/src/store/agentSignal/action.ts b/src/store/agentSignal/action.ts
new file mode 100644
index 00000000000..5f99ddecbdd
--- /dev/null
+++ b/src/store/agentSignal/action.ts
@@ -0,0 +1,89 @@
+import { type ReplicaSyncResult } from '@/libs/replica';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type AgentSignalState, initialState } from './initialState';
+import { AgentSignalPrivateAction } from './privateAction';
+import { agentSignalReceiptsKey, type AgentSignalReceiptsParams } from './projection';
+import { useAgentSignalStore } from './store';
+
+const n = setNamespace('agentSignal');
+
+type Setter = StoreSetter<AgentSignalState>;
+
+/**
+ * Collapse mounts of the same topic (main chat + a floating panel) into one
+ * request. SWR dedupes poll ticks too, so this stays below the shortest poll.
+ */
+const RECEIPTS_DEDUPING_INTERVAL = 2000;
+
+interface UseFetchReceiptsOptions {
+ /** Poll cadence, decided per tick (see `useAgentSignalReceipts`). */
+ refreshInterval?: () => number;
+}
+
+export class AgentSignalActionImpl {
+ readonly #private: AgentSignalPrivateAction;
+ readonly #set: Setter;
+
+ constructor(set: Setter, _get: () => AgentSignalState, privateAction: AgentSignalPrivateAction) {
+ this.#set = set;
+ this.#private = privateAction;
+ }
+
+ /**
+ * Fetch orchestration for one topic's receipts. Read them with
+ * `agentSignalSelectors.getReceipts`, not from the return value.
+ */
+ useFetchReceipts = (
+ params: AgentSignalReceiptsParams | null,
+ { refreshInterval }: UseFetchReceiptsOptions = {},
+ ): ReplicaSyncResult =>
+ this.#private.receipts.useSync(params, {
+ dedupingInterval: RECEIPTS_DEDUPING_INTERVAL,
+ refreshInterval,
+ refreshWhenHidden: false,
+ revalidateOnFocus: false,
+ });
+
+ /** Polls in a row that brought no new receipt for this topic. */
+ getEmptyRefreshes = (params: AgentSignalReceiptsParams): number =>
+ this.#private.emptyRefreshes.get(agentSignalReceiptsKey(params)) ?? 0;
+
+ /** Make the topic's next read a full head, when the topic is opened (again). */
+ requestFullReceiptHead = (params: AgentSignalReceiptsParams): void => {
+ this.#private.fullHeadPending.add(agentSignalReceiptsKey(params));
+ };
+
+ /** Restart the polling backoff, when new work starts in the topic. */
+ resetReceiptPolling = (params: AgentSignalReceiptsParams): void => {
+ this.#private.emptyRefreshes.delete(agentSignalReceiptsKey(params));
+ };
+
+ /**
+ * Record a server-confirmed rollback on the receipt, persisted, so a reload
+ * does not paint the receipt as still undoable. Incremental polls only fetch
+ * receipts newer than the head, so they would never carry this change.
+ */
+ markReceiptRolledBack = (params: AgentSignalReceiptsParams, receiptId: string): void => {
+ this.#private.receipts.update(agentSignalReceiptsKey(params), (receipts) =>
+ receipts?.map((receipt) =>
+ receipt.id === receiptId
+ ? { ...receipt, metadata: { ...receipt.metadata, rollbackStatus: 'rolled_back' } }
+ : receipt,
+ ),
+ );
+ };
+
+ reset = (): void => {
+ this.#set(initialState, false, n('reset'));
+ };
+}
+
+const { getState, setState } = useAgentSignalStore;
+
+export const agentSignalActions = new AgentSignalActionImpl(
+ setState,
+ getState,
+ new AgentSignalPrivateAction(setState, getState),
+);
diff --git a/src/store/agentSignal/index.ts b/src/store/agentSignal/index.ts
new file mode 100644
index 00000000000..134064e6702
--- /dev/null
+++ b/src/store/agentSignal/index.ts
@@ -0,0 +1,5 @@
+export { agentSignalActions } from './action';
+export { type AgentSignalState } from './initialState';
+export { type AgentSignalReceiptsParams, type AgentSignalReceiptView } from './projection';
+export { agentSignalSelectors } from './selectors';
+export { useAgentSignalStore } from './store';
diff --git a/src/store/agentSignal/initialState.ts b/src/store/agentSignal/initialState.ts
new file mode 100644
index 00000000000..8152c362032
--- /dev/null
+++ b/src/store/agentSignal/initialState.ts
@@ -0,0 +1,15 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { AgentSignalReceiptView } from './projection';
+
+export interface AgentSignalState {
+ /** Receipts per agent topic (`agentSignalReceiptsMap[agentSignalReceiptsKey(params)]`). */
+ agentSignalReceiptsMap: Record<string, AgentSignalReceiptView[]>;
+ /** Replica bookkeeping for `agentSignalReceiptsMap`. */
+ agentSignalReceiptsReplica: ReplicaState<AgentSignalReceiptView[]>;
+}
+
+export const initialState: AgentSignalState = {
+ agentSignalReceiptsMap: {},
+ agentSignalReceiptsReplica: createReplicaState(),
+};
diff --git a/src/store/agentSignal/privateAction.ts b/src/store/agentSignal/privateAction.ts
new file mode 100644
index 00000000000..0e61afe80e4
--- /dev/null
+++ b/src/store/agentSignal/privateAction.ts
@@ -0,0 +1,71 @@
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { agentSignalService } from '@/services/agentSignal';
+import type { StoreSetter } from '@/store/types';
+
+import { type AgentSignalState } from './initialState';
+import {
+ AGENT_SIGNAL_RECEIPT_LIMIT,
+ agentSignalReceiptsKey,
+ agentSignalReceiptsResource,
+ type AgentSignalReceiptView,
+ mergeReceiptRefresh,
+} from './projection';
+
+type Setter = StoreSetter<AgentSignalState>;
+
+export class AgentSignalPrivateAction {
+ readonly receipts;
+ /**
+ * Consecutive polls per entry that brought no new receipt — polling backoff
+ * bookkeeping only, never data, so it is not scoped to an identity.
+ */
+ readonly emptyRefreshes = new Map<string, number>();
+ /**
+ * Entries whose next read must be a full head: a topic opened again. An
+ * incremental read only returns receipts newer than the head, so it never
+ * carries a change to an older one (an Undo from another tab or device).
+ */
+ readonly fullHeadPending = new Set<string>();
+
+ constructor(set: Setter, get: () => AgentSignalState) {
+ this.receipts = createReplicaSlice(agentSignalReceiptsResource, {
+ actionPrefix: 'agentSignalReceipts',
+ fetcher: async (params) => {
+ const key = agentSignalReceiptsKey(params);
+ // Only a list the server answered this session may be extended
+ // incrementally, and only while its topic stays open: a persisted one
+ // can miss receipts and status changes made since, so the first read
+ // after a reload or a revisit fetches the full head.
+ const isConfirmed = get().agentSignalReceiptsReplica.entries[key]?.source === 'server';
+ const isFullHead = this.fullHeadPending.has(key) || !isConfirmed;
+ const sinceCreatedAt = isFullHead
+ ? undefined
+ : get().agentSignalReceiptsMap[key]?.[0]?.createdAt;
+
+ const result = await agentSignalService.listReceipts({
+ ...params,
+ limit: AGENT_SIGNAL_RECEIPT_LIMIT,
+ ...(sinceCreatedAt === undefined ? {} : { sinceCreatedAt }),
+ });
+ // Only a full head that answered settles the reopen: a failed one
+ // leaves the intent for the retry.
+ if (isFullHead) this.fullHeadPending.delete(key);
+
+ this.emptyRefreshes.set(
+ key,
+ result.receipts.length === 0 ? (this.emptyRefreshes.get(key) ?? 0) + 1 : 0,
+ );
+
+ if (sinceCreatedAt === undefined) return result.receipts;
+ // Merge into what is on screen now: a rollback may have patched a row
+ // while the request was in flight.
+ const current: AgentSignalReceiptView[] = get().agentSignalReceiptsMap[key] ?? [];
+ return mergeReceiptRefresh(current, result.receipts);
+ },
+ get,
+ set,
+ stateKey: 'agentSignalReceiptsReplica',
+ view: recordLens<AgentSignalState, AgentSignalReceiptView[]>('agentSignalReceiptsMap'),
+ });
+ }
+}
diff --git a/src/store/agentSignal/projection.ts b/src/store/agentSignal/projection.ts
new file mode 100644
index 00000000000..9af8f6a5871
--- /dev/null
+++ b/src/store/agentSignal/projection.ts
@@ -0,0 +1,53 @@
+import { defineReplica } from '@/libs/replica';
+import type { agentSignalService } from '@/services/agentSignal';
+
+export type AgentSignalReceiptView = Awaited<
+ ReturnType<typeof agentSignalService.listReceipts>
+>['receipts'][number];
+
+/** Receipts one request returns, and the most a topic's entry keeps. */
+export const AGENT_SIGNAL_RECEIPT_LIMIT = 20;
+/** Topics whose receipts survive a reload, most recently used first. */
+const MAX_PERSISTED_RECEIPT_TOPICS = 30;
+
+export interface AgentSignalReceiptsParams {
+ agentId: string;
+ topicId: string;
+}
+
+export const agentSignalReceiptsKey = ({ agentId, topicId }: AgentSignalReceiptsParams) =>
+ `${agentId}/${topicId}`;
+
+/**
+ * The latest Agent Signal receipts of one agent's topic, newest first
+ * (`agentSignalReceiptsMap[agentSignalReceiptsKey(params)]`). The persisted copy
+ * paints the receipt chips on a cold start; the network then confirms it.
+ */
+export const agentSignalReceiptsResource = defineReplica<
+ AgentSignalReceiptsParams,
+ AgentSignalReceiptView[]
+>({
+ key: agentSignalReceiptsKey,
+ name: 'agentSignalReceipts',
+ persist: { maxEntries: MAX_PERSISTED_RECEIPT_TOPICS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Fold an incremental (`sinceCreatedAt`) page into the receipts on screen. */
+export const mergeReceiptRefresh = (
+ currentReceipts: AgentSignalReceiptView[],
+ newReceipts: AgentSignalReceiptView[],
+) => {
+ if (newReceipts.length === 0) return currentReceipts;
+
+ const mergedById = new Map(currentReceipts.map((receipt) => [receipt.id, receipt]));
+
+ for (const receipt of newReceipts) {
+ mergedById.set(receipt.id, receipt);
+ }
+
+ return [...mergedById.values()]
+ .sort((a, b) => b.createdAt - a.createdAt)
+ .slice(0, AGENT_SIGNAL_RECEIPT_LIMIT);
+};
diff --git a/src/store/agentSignal/selectors.ts b/src/store/agentSignal/selectors.ts
new file mode 100644
index 00000000000..4f0a55e215f
--- /dev/null
+++ b/src/store/agentSignal/selectors.ts
@@ -0,0 +1,16 @@
+import type { AgentSignalState } from './initialState';
+import {
+ agentSignalReceiptsKey,
+ type AgentSignalReceiptsParams,
+ type AgentSignalReceiptView,
+} from './projection';
+
+/** One topic's receipts, or `undefined` before their first paint. */
+const getReceipts =
+ (params?: AgentSignalReceiptsParams | null) =>
+ (s: AgentSignalState): AgentSignalReceiptView[] | undefined =>
+ params ? s.agentSignalReceiptsMap[agentSignalReceiptsKey(params)] : undefined;
+
+export const agentSignalSelectors = {
+ getReceipts,
+};
diff --git a/src/store/agentSignal/store.ts b/src/store/agentSignal/store.ts
new file mode 100644
index 00000000000..7d102b99319
--- /dev/null
+++ b/src/store/agentSignal/store.ts
@@ -0,0 +1,15 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { expose } from '../middleware/expose';
+import { type AgentSignalState, initialState } from './initialState';
+
+const devtools = createDevtools('agentSignal');
+
+export const useAgentSignalStore = createWithEqualityFn<AgentSignalState>()(
+ devtools(() => initialState),
+ shallow,
+);
+
+expose('agentSignal', useAgentSignalStore);
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index be117bfcaf1..c329f74c420 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -1,6 +1,8 @@
import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';
import { type ChatTopic, type TopicQuerySortBy } from '@/types/topic';
+import type { TopicShareEntry } from './projection';
+
/** The project (and directory, when there is one) a blank conversation was opened in. */
export type PendingNewTopicDirectory =
| { agentId: string; projectId?: undefined; projectWorkingDirectoryId: string }
@@ -126,6 +128,10 @@ export interface ChatTopicState {
topicLoadingIds: string[];
topicRenamingId?: string;
topicSearchKeywords: string;
+ /** Share records behind the Share popover (`topicShareMap[topicId]`). */
+ topicShareMap: Record<string, TopicShareEntry>;
+ /** Local-first bookkeeping for `topicShareMap`. */
+ topicShareReplica: ReplicaState<TopicShareEntry>;
}
export const initialTopicState: ChatTopicState = {
@@ -141,6 +147,8 @@ export const initialTopicState: ChatTopicState = {
topicDetailMap: {},
topicDetailReplica: createReplicaState<ChatTopic>(),
topicListReplica: createReplicaState<TopicData>(),
+ topicShareMap: {},
+ topicShareReplica: createReplicaState<TopicShareEntry>(),
topicLoadingIdCounts: {},
topicLoadingIds: [],
topicEffortUpdatingIds: [],
diff --git a/src/store/chat/slices/topic/projection.ts b/src/store/chat/slices/topic/projection.ts
index e7935616352..2e3a2ff813c 100644
--- a/src/store/chat/slices/topic/projection.ts
+++ b/src/store/chat/slices/topic/projection.ts
@@ -163,6 +163,39 @@ export const topicDetailResource = defineReplica<string, ChatTopic, ChatTopic |
version: 1,
});
+export type TopicShareVisibility = 'private' | 'link';
+
+/** A topic's share record as the owner sees it (`topic.getShareInfo`). */
+export interface TopicShareInfo {
+ id: string;
+ topicId: string;
+ userId: string;
+ visibility: TopicShareVisibility;
+}
+
+/**
+ * The value of one share entry. A topic without a record is private — the
+ * record is created on the first visibility change — so `share: null` is a
+ * settled answer, distinct from "nothing loaded yet" (no entry).
+ */
+export interface TopicShareEntry {
+ share: TopicShareInfo | null;
+}
+
+/**
+ * The share record behind the topic Share popover, by topic id
+ * (`topicShareMap[topicId]`). Only an existing record is persisted: "no record"
+ * reads as private, and a stale copy of that could hide a link published from
+ * another device, so a reload waits for the server instead.
+ */
+export const topicShareResource = defineReplica<string, TopicShareEntry>({
+ key: (topicId) => topicId,
+ name: 'topicShareInfo',
+ persist: { maxEntries: 50 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
/** Apply a topic dispatch to one container bucket (counts and `hasMore` included). */
export const applyTopicDispatchToBucket = (
bucket: TopicData | undefined,
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index d6c39f20712..08b9acc70a3 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -27,6 +27,7 @@ import { type ChatStoreState } from '../../initialState';
import { topicMapKey } from '../../utils/topicMapKey';
import { operationSelectors } from '../operation/selectors';
import { type TopicData } from './initialState';
+import type { TopicShareEntry } from './projection';
// Helper selector: get current topic data based on session context
const currentTopicData = (s: ChatStoreState): TopicData | undefined => {
@@ -544,6 +545,12 @@ const agentTopicsViewIsLoadingMore = (s: ChatStoreState): boolean =>
const agentTopicsViewLoadMoreError = (s: ChatStoreState): unknown =>
agentTopicsViewData(s)?.loadMoreError;
+/** The topic's share entry (`share: null` = no record), or `undefined` before its first paint. */
+const getTopicShare =
+ (topicId?: string | null) =>
+ (s: ChatStoreState): TopicShareEntry | undefined =>
+ topicId ? s.topicShareMap[topicId] : undefined;
+
export const topicSelectors = {
activeTopicHeteroPin,
activeTopicModel,
@@ -570,6 +577,7 @@ export const topicSelectors = {
getTopicModelById,
getTopicReasoningConfigForModel,
getTopicReasoningPinById,
+ getTopicShare,
getTopicWorkingDirectory,
getTopicsByAgentId,
groupedTopicsForSidebar,
diff --git a/src/store/chat/slices/topic/topicShare.ts b/src/store/chat/slices/topic/topicShare.ts
new file mode 100644
index 00000000000..738f0591ea2
--- /dev/null
+++ b/src/store/chat/slices/topic/topicShare.ts
@@ -0,0 +1,101 @@
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { topicService } from '@/services/topic';
+import type { ChatStore } from '@/store/chat';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ type TopicShareEntry,
+ type TopicShareInfo,
+ topicShareResource,
+ type TopicShareVisibility,
+} from './projection';
+
+/** Keep the fields the popover reads; write results carry the whole row. */
+const toShareInfo = (record: {
+ id: string;
+ topicId: string;
+ userId: string;
+ visibility: string;
+}): TopicShareInfo => ({
+ id: record.id,
+ topicId: record.topicId,
+ userId: record.userId,
+ visibility: record.visibility as TopicShareVisibility,
+});
+
+type Setter = StoreSetter<ChatStore>;
+
+const createTopicShareSlice = (set: Setter, get: () => ChatStore) =>
+ createReplicaSlice(topicShareResource, {
+ actionPrefix: setNamespace('t')('topicShare'),
+ fetcher: async (topicId): Promise<TopicShareEntry> => {
+ const record = await topicService.getShareInfo(topicId);
+ return { share: record ? toShareInfo(record) : null };
+ },
+ get,
+ set,
+ stateKey: 'topicShareReplica',
+ // "No record" is never persisted, and evicts a record persisted earlier.
+ toPersisted: (data) => (data.share ? data : null),
+ view: recordLens<ChatStore, TopicShareEntry>('topicShareMap'),
+ });
+
+/** The share record behind the topic Share popover → `topicShareMap[topicId]`. */
+export class ChatTopicShareActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #share;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#get = get;
+ this.#share = createTopicShareSlice(set, get);
+ }
+
+ /**
+ * The topic's share record for the Share popover; read it with
+ * `topicSelectors.getTopicShare`. An absent id (or no share permission)
+ * disables the read.
+ */
+ useFetchTopicShare = (topicId?: string | null, enabled = true): ReplicaSyncResult =>
+ this.#share.useSync(enabled && topicId ? topicId : null, {
+ dedupingInterval: 10_000,
+ revalidateOnFocus: false,
+ });
+
+ /**
+ * Change a topic's share visibility and land the server's record on the
+ * replica (persisted). Resolves to the share id after the change.
+ */
+ setTopicShareVisibility = async (
+ topicId: string,
+ visibility: TopicShareVisibility,
+ ): Promise<string | undefined> => {
+ // The record belongs to the identity that started the change; never adopt
+ // (and persist) it into another account's or workspace's scope.
+ const scope = this.#share.resource.scope.get();
+ const current = this.#get().topicShareMap[topicId]?.share;
+
+ let record = current
+ ? await topicService.updateShareVisibility(topicId, visibility)
+ : await topicService.enableSharing(topicId, visibility);
+ // A stale copy can miss a record created elsewhere; create then keeps the
+ // existing visibility, so apply the requested one on top.
+ if (record && record.visibility !== visibility)
+ record = await topicService.updateShareVisibility(topicId, visibility);
+
+ const isSameScope = this.#share.resource.scope.get() === scope;
+
+ if (record) {
+ const share = toShareInfo(record);
+ if (isSameScope) this.#share.update(topicId, () => ({ share }));
+ return share.id;
+ }
+ if (!isSameScope) return current?.id;
+
+ await this.#share.fetch(topicId, { fresh: true });
+ return this.#get().topicShareMap[topicId]?.share?.id ?? current?.id;
+ };
+}
+
+export type ChatTopicShareAction = Pick<ChatTopicShareActionImpl, keyof ChatTopicShareActionImpl>;
diff --git a/src/store/chat/store.ts b/src/store/chat/store.ts
index ebdc76820a4..8d47f90a651 100644
--- a/src/store/chat/store.ts
+++ b/src/store/chat/store.ts
@@ -30,6 +30,7 @@ import { ChatThreadActionImpl } from './slices/thread/action';
import { type ChatTopicAction } from './slices/topic/action';
import { ChatTopicActionImpl } from './slices/topic/action';
import { subscribeJustArchivedTopic } from './slices/topic/justArchived';
+import { type ChatTopicShareAction, ChatTopicShareActionImpl } from './slices/topic/topicShare';
import { type ChatTranslateAction } from './slices/translate/action';
import { ChatTranslateActionImpl } from './slices/translate/action';
import { type VoiceMessageAction } from './slices/voiceMessage/action';
@@ -40,6 +41,7 @@ export type ChatStoreAction = ChatMessageAction &
ChatThreadAction &
ChatAgentRunAction &
ChatTopicAction &
+ ChatTopicShareAction &
ChatTranslateAction &
ChatPluginAction &
ChatBuiltinToolAction &
@@ -80,6 +82,7 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (
new ChatThreadActionImpl(...params),
chatAgentRun(...params),
new ChatTopicActionImpl(...params),
+ new ChatTopicShareActionImpl(...params),
new ChatTranslateActionImpl(...params),
chatToolSlice(...params),
chatPlugin(...params),