π€― 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
β»οΈ refactor(brief): move the unresolved brief feed onto @lobechat/replica (#20613)
Arvin Xu076ef9b213a8
diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxindex 0827761cbd9..3db3d42345c 100644--- a/src/features/Home/HomeModeContent.tsx+++ b/src/features/Home/HomeModeContent.tsx@@ -504,9 +504,9 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges[inboxTopics.running, myId],);const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);- const briefsSWR = useFetchBriefs(isLogin, cacheScope);- const briefs = useBriefStore(briefListSelectors.briefs(cacheScope));- const briefsInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));+ const briefsSWR = useFetchBriefs(isLogin);+ const briefs = useBriefStore(briefListSelectors.briefs);+ const briefsInit = useBriefStore(briefListSelectors.isBriefsInit);const needsYouCount = useMemo(() => splitBriefs(briefs).needsYou.length, [briefs]);const topicRecents = recentsSWR.data ?? [];diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex 1c46af6ad75..d537787dd36 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -138,14 +138,16 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const isLogin = useUserStore(authSelectors.isLogin);const myId = useUserStore(userProfileSelectors.userId);- // Briefs are per-user AND per-workspace rows, so the feed is read through the- // active cache scope β a list left over from the previous workspace holds ids- // this one cannot resolve, and every action on it would fail silently.+ // Briefs are per-user AND per-workspace rows: a list left over from the+ // previous workspace holds ids this one cannot resolve, and every action on it+ // would fail silently. The `briefList` replica partitions by identity scope+ // and clears its view on a scope switch, so the selectors only ever surface+ // the active scope's feed.const cacheScope = useCacheScope();const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);- const briefsSWR = useFetchBriefs(isLogin, cacheScope);- const briefs = useBriefStore(briefListSelectors.briefs(cacheScope));- const isBriefsInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));+ const briefsSWR = useFetchBriefs(isLogin);+ const briefs = useBriefStore(briefListSelectors.briefs);+ const isBriefsInit = useBriefStore(briefListSelectors.isBriefsInit);// The news digest is day-scoped: it fetches only briefs *created* on the// viewed local day (today by default), resolved or not, with βΉ βΊ paging intodiff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.tsindex 2a72909ff30..d25ef63a8e8 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts@@ -54,17 +54,13 @@ vi.mock('swr', () => ({default: mockUseSWR,}));-// The brief feed is read through the active cache scope β a list fetched for-// another user/workspace is treated as not-loaded (see `briefListSelectors`).-vi.mock('@/libs/swr/useCacheScope', () => ({- useCacheScope: () => 'user-1:personal',-}));-+// The brief feed is a replica now: the hook only needs the feed to hold a+// value for the scope (`briefListMap` has an entry) to leave its skeleton β+// see `briefListSelectors.isBriefsInit`.vi.mock('@/store/brief', () => ({useBriefStore: (selector: (state: any) => unknown) =>selector({- briefsScope: 'user-1:personal',- isBriefsInit: true,+ briefListMap: { unresolved: [] },useFetchBriefs: mockUseFetchBriefs,}),}));diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.tsindex 35dfbf14ea5..60cdcc20ad4 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts@@ -12,7 +12,6 @@ import { useTranslation } from 'react-i18next';import useSWR from 'swr';import { taskTemplateKeys } from '@/libs/swr/keys';-import { useCacheScope } from '@/libs/swr/useCacheScope';import { taskTemplateService } from '@/services/taskTemplate';import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';@@ -164,11 +163,10 @@ export function useDailyBriefRecommendationsUI(const locale = i18n.resolvedLanguage || i18n.language;const isLogin = useUserStore(authSelectors.isLogin);- const cacheScope = useCacheScope();const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);- useFetchBriefs(isLogin, cacheScope);+ useFetchBriefs(isLogin);- const isInit = useBriefStore(briefListSelectors.isBriefsInit(cacheScope));+ const isInit = useBriefStore(briefListSelectors.isBriefsInit);const interestKeys = useResolvedInterestKeys();const [refreshSeed, setRefreshSeed] = useSessionStorageState<string>(REFRESH_SEED_STORAGE_KEY, {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex a067116f375..bde6f9bd2e7 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -409,13 +409,10 @@ export const workKeys = {};// ---- brief --------------------------------------------------------------+// The unresolved brief feed no longer has an SWR key: it moved onto+// `@lobechat/replica` (`briefList`, partitioned by identity scope). Only the+// day-scoped news digest still reads through SWR.export const briefKeys = {- /**- * Unresolved brief feed, keyed by login + identity scope. Briefs are per-user- * AND per-workspace rows, so an entry fetched in one scope must never be- * served in another β its ids are unreachable there.- */- list: def('brief:list', (isLogin: boolean, scope: string) => ['brief:list', isLogin, scope]),/*** Day-scoped news digest (`insight` + `result`, resolved included), keyed by* the viewer's local day (`YYYY-MM-DD`) on top of the identity scope.diff --git a/src/store/brief/slices/list/action.test.ts b/src/store/brief/slices/list/action.test.tsindex c95aa5ede7d..4d8b5a064a0 100644--- a/src/store/brief/slices/list/action.test.ts+++ b/src/store/brief/slices/list/action.test.ts@@ -1,14 +1,31 @@-// @vitest-environment node-import type { ScopedMutator } from 'swr/_internal';+/**+ * @vitest-environment happy-dom+ *+ * The unresolved brief feed is a replica: the inbox paints the persisted rows+ * on the first frame, a mutation shows at once and rolls back when the server+ * rejects, and the view is cleared when the identity scope changes.+ */+import { randomUUID } from 'node:crypto';++import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { setScopedMutate } from '@/libs/swr';-import { briefKeys } from '@/libs/swr/keys';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';import { briefService } from '@/services/brief';-import type { BriefStore } from '@/store/brief/store';+import { useBriefStore } from '@/store/brief';import type { BriefItem } from '@/store/brief/types';-import { BriefListActionImpl } from './action';+import { initialBriefListState } from './initialState';+import { briefListResource } from './projection';+import { briefListSelectors } from './selectors';++const LIST_PARAMS = {} as Record<string, never>;+/** The persisted row of the feed under test (one entry, keyed `unresolved`). */+const STORAGE_KEY = { queryKey: briefListResource.storageKey(LIST_PARAMS) };const createBrief = (id: string): BriefItem => ({actions: null,@@ -31,89 +48,144 @@ const createBrief = (id: string): BriefItem => ({userId: 'user-1',});-describe('BriefListActionImpl', () => {- const cache = new Map<string, BriefItem[]>();+const deferred = <T>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ reject = rejectPromise;+ resolve = resolvePromise;+ });+ return { promise, reject, resolve };+};++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++let scope = '';+const useScope = (next: string) => {+ scope = next;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+};++/** The feed as the inbox reads it. */+const feed = () => briefListSelectors.briefs(useBriefStore.getState());++/** Drive the real sync path and wait until the head page has landed. */+const load = async (briefs: BriefItem[]) => {+ vi.spyOn(briefService, 'listUnresolved').mockResolvedValue({ data: briefs } as never);+ renderHook(() => useBriefStore((s) => s.useFetchBriefs)(true), { wrapper });+ await waitFor(() => expect(feed()).toBeDefined());+ return briefs;+};++beforeEach(() => {+ useScope(`brief-user-${randomUUID()}:personal`);+ act(() => useBriefStore.setState({ ...initialBriefListState }));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('brief list replica', () => {+ it('paints the persisted feed before the network answers', async () => {+ await briefListResource.storage!.set(+ { ...STORAGE_KEY, scope },+ { data: [createBrief('cached')], updatedAt: 1 },+ );+ vi.spyOn(briefService, 'listUnresolved').mockImplementation(() => new Promise(() => {}));++ const { result } = renderHook(() => useBriefStore((s) => s.useFetchBriefs)(true), { wrapper });- beforeEach(() => {- vi.clearAllMocks();- cache.clear();- setScopedMutate((async (key, data) => {- if (Array.isArray(data)) cache.set(JSON.stringify(key), data);- return data;- }) as ScopedMutator);+ await waitFor(() => expect(feed().map((brief) => brief.id)).toEqual(['cached']));+ expect(briefListSelectors.isBriefsInit(useBriefStore.getState())).toBe(true);+ expect(result.current.isValidating).toBe(true);});- afterEach(() => {- vi.restoreAllMocks();+ it('does not fetch while logged out', () => {+ const listUnresolved = vi.spyOn(briefService, 'listUnresolved');+ renderHook(() => useBriefStore((s) => s.useFetchBriefs)(false), { wrapper });+ expect(listUnresolved).not.toHaveBeenCalled();});- const SCOPE = 'user-1:workspace-1';+ it('marks a brief read optimistically and rolls back when the server rejects', async () => {+ await load([createBrief('b1')]);+ const request = deferred<void>();+ vi.spyOn(briefService, 'markRead').mockReturnValue(request.promise as never);- it('should remove resolved briefs from the SWR snapshot used on route remount', async () => {- const resolvedBrief = createBrief('brief-resolved');- const remainingBrief = createBrief('brief-remaining');- const initialBriefs = [resolvedBrief, remainingBrief];- const cacheKey = JSON.stringify(briefKeys.list(true, SCOPE));- cache.set(cacheKey, initialBriefs);+ const pending = useBriefStore.getState().markBriefRead('b1');+ expect(feed()[0].readAt).toBeTruthy();- const state = { briefs: initialBriefs, briefsScope: SCOPE, isBriefsInit: true };- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));- const action = new BriefListActionImpl(set as never, () => state as BriefStore);- vi.spyOn(briefService, 'resolveManyAsRead').mockResolvedValue({- data: [resolvedBrief.id],- } as never);+ request.reject(new Error('failed'));+ await expect(pending).rejects.toThrow('failed');+ expect(feed()[0].readAt).toBeNull();+ });- await action.resolveBriefsAsRead(initialBriefs.map((brief) => brief.id));+ it('writes a confirmed resolve through to the persisted row', async () => {+ await load([createBrief('b1')]);+ vi.spyOn(briefService, 'resolve').mockResolvedValue(undefined as never);- expect(state.briefs).toEqual([remainingBrief]);- expect(cache.get(cacheKey)).toEqual([remainingBrief]);+ await act(() => useBriefStore.getState().resolveBrief('b1', 'approve'));- state.briefs = cache.get(cacheKey) ?? [];- expect(state.briefs).not.toContainEqual(expect.objectContaining({ id: resolvedBrief.id }));- });+ expect(feed()[0]).toMatchObject({ resolvedAction: 'approve' });+ expect(feed()[0].resolvedAt).toBeTruthy();- // The write-back must land on the entry the list came from. Keying it off the- // live scope instead would, on a mid-flight workspace switch, seed the new- // workspace's bucket and cache key with the previous workspace's briefs.- it('should abandon the write when the workspace changed while the request was in flight', async () => {- const brief = createBrief('brief-1');- const nextScopeBrief = createBrief('brief-from-next-workspace');- const state = { briefs: [brief], briefsScope: SCOPE, isBriefsInit: true };- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));- const action = new BriefListActionImpl(set as never, () => state as BriefStore);- vi.spyOn(briefService, 'resolveManyAsRead').mockImplementation(async () => {- // The switch lands before the response does.- Object.assign(state, { briefs: [nextScopeBrief], briefsScope: 'user-1:workspace-2' });- return { data: [brief.id] } as never;+ await waitFor(async () => {+ const row = await briefListResource.storage!.get({ ...STORAGE_KEY, scope });+ expect(row?.data[0]).toMatchObject({ resolvedAction: 'approve' });});+ });- await action.resolveBriefsAsRead([brief.id]);+ it('drops the briefs resolved as read from the feed', async () => {+ await load([createBrief('b1'), createBrief('b2')]);+ vi.spyOn(briefService, 'resolveManyAsRead').mockResolvedValue({ data: ['b1'] } as never);- expect(state.briefs).toEqual([nextScopeBrief]);- expect(cache.size).toBe(0);+ await act(() => useBriefStore.getState().resolveBriefsAsRead(['b1']));++ expect(feed().map((brief) => brief.id)).toEqual(['b2']);});- it('should not write an unstamped brief list into any scope entry', async () => {- const brief = createBrief('brief-1');- const state = { briefs: [brief], briefsScope: undefined, isBriefsInit: true };- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));- const action = new BriefListActionImpl(set as never, () => state as BriefStore);- vi.spyOn(briefService, 'resolveManyAsRead').mockResolvedValue({ data: [brief.id] } as never);+ it('removes a deleted brief and restores it when the server rejects', async () => {+ await load([createBrief('b1'), createBrief('b2')]);+ const request = deferred<void>();+ vi.spyOn(briefService, 'delete').mockReturnValue(request.promise as never);- await action.resolveBriefsAsRead([brief.id]);+ const pending = useBriefStore.getState().deleteBrief('b1');+ expect(feed().map((brief) => brief.id)).toEqual(['b2']);- expect(set).not.toHaveBeenCalled();- expect(cache.size).toBe(0);+ request.reject(new Error('failed'));+ await expect(pending).rejects.toThrow('failed');+ expect(feed().map((brief) => brief.id)).toEqual(['b1', 'b2']);});- it('should skip the store write when deleting a brief the list no longer holds', async () => {- const state = { briefs: [createBrief('brief-1')], briefsScope: SCOPE, isBriefsInit: true };- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));- const action = new BriefListActionImpl(set as never, () => state as BriefStore);- vi.spyOn(briefService, 'delete').mockResolvedValue(undefined as never);+ it('clears the previous scopeβs feed on a scope switch, before any answer lands', async () => {+ vi.spyOn(briefService, 'listUnresolved').mockResolvedValue({+ data: [createBrief('b1'), createBrief('b2')],+ } as never);+ const { rerender } = renderHook(() => useBriefStore((s) => s.useFetchBriefs)(true), {+ wrapper,+ });+ await waitFor(() => expect(feed()).toBeDefined());+ expect(feed().length).toBeGreaterThan(0);- await action.deleteBrief('brief-from-another-workspace');+ // A different identity: the previous scope's rows are unreachable here, so+ // they must leave the view even while the new scope's fetch is in flight.+ useScope(`brief-user-${randomUUID()}:personal`);+ vi.spyOn(briefService, 'listUnresolved').mockImplementation(() => new Promise(() => {}));+ rerender();- expect(set).not.toHaveBeenCalled();+ await waitFor(() => expect(briefListSelectors.hasBriefs(useBriefStore.getState())).toBe(false));});});diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.tsindex 4eed6fb0a6a..401bd5f4fc3 100644--- a/src/store/brief/slices/list/action.ts+++ b/src/store/brief/slices/list/action.ts@@ -1,11 +1,14 @@import dayjs from 'dayjs';-import isEqual from 'fast-deep-equal';-import { useEffect } from 'react';import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';+import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaSyncResult,+} from '@/libs/replica';+import { mutate, useClientDataSWR } from '@/libs/swr';import { briefKeys, goalKeys } from '@/libs/swr/keys';-import { getCacheScope } from '@/libs/swr/useCacheScope';import { briefService } from '@/services/brief';import { taskService } from '@/services/task';import { type BriefStore } from '@/store/brief/store';@@ -13,6 +16,8 @@ import { type BriefItem } from '@/store/brief/types';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';+import { BRIEF_LIST_KEY, briefEntity, briefListResource } from './projection';+const n = setNamespace('briefList');export interface NewsDay {@@ -28,6 +33,17 @@ export interface NewsDay {news: BriefItem[];}+/** Sync flags of the unresolved feed, plus the aliases the inbox reads. */+export interface BriefListSyncResult extends ReplicaSyncResult {+ /** A request is in flight and the feed has no value for this scope yet. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;+}++/** The feed has one entry per scope (the replica partitions by identity), so its params are constant. */+const LIST_PARAMS = {} as Record<string, never>;+type Setter = StoreSetter<BriefStore>;export const createBriefListSlice = (set: Setter, get: () => BriefStore, _api?: unknown) =>@@ -35,79 +51,75 @@ export const createBriefListSlice = (set: Setter, get: () => BriefStore, _api?:export class BriefListActionImpl {readonly #get: () => BriefStore;- readonly #set: Setter;+ readonly #briefList;+ readonly #briefs;constructor(set: Setter, get: () => BriefStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;+ this.#briefList = createReplicaSlice(briefListResource, {+ actionPrefix: n('list'),+ entity: briefEntity,+ fetcher: () => briefService.listUnresolved(),+ get,+ // The server row keeps `actions` as a json column (`unknown`); the card+ // narrows it to `BriefAction[]`, so the view adopts the client `BriefItem`.+ merge: (response) => response.data as unknown as BriefItem[],+ set,+ stateKey: 'briefListReplica',+ view: recordLens<BriefStore, BriefItem[]>('briefListMap'),+ });+ // Every brief mutation runs through the entity link: the optimistic overlay+ // applies right away, a failed write rolls back to the confirmed base, and a+ // confirmed write reaches the persisted row too β so a reload never hydrates+ // a value the server has already moved past.+ this.#briefs = linkReplicaEntity<BriefItem>([this.#briefList]);}- internal_updateBrief = (id: string, data: Partial<BriefItem>) => {- const briefs = this.#get().briefs;- const index = briefs.findIndex((b) => b.id === id);- if (index === -1) return;+ #syncResult = (sync: ReplicaSyncResult): BriefListSyncResult => ({+ ...sync,+ isLoading: sync.isValidating && this.#get().briefListMap[BRIEF_LIST_KEY] === undefined,+ mutate: sync.revalidate,+ });- const updated = [...briefs];- updated[index] = { ...briefs[index], ...data };- this.#set({ briefs: updated }, false, n('internal_updateBrief'));+ /** Show the read state at once; the server confirms in the background. */+ markBriefRead = async (id: string) => {+ await this.#briefs.optimistic(+ id,+ (brief) => ({ ...brief, readAt: new Date().toISOString() }),+ () => briefService.markRead(id),+ );};deleteBrief = async (id: string) => {- await briefService.delete(id);-- const previous = this.#get().briefs;- const briefs = previous.filter((b) => b.id !== id);- // Nothing removed β the brief was already gone, or the list has since been- // replaced by another scope's (a workspace switch while the request was in- // flight). Either way, writing an identical list only churns subscribers.- if (briefs.length === previous.length) return;-- this.#set({ briefs }, false, n('deleteBrief'));- };-- markBriefRead = async (id: string) => {- await briefService.markRead(id);- this.internal_updateBrief(id, { readAt: new Date().toISOString() });+ await this.#briefs.optimistic(id, 'remove', () => briefService.delete(id));};/**- * "Mark all read" resolves news briefs with the neutral `read` action and drops- * them from both Zustand and its backing SWR snapshot. Route remounts hydrate- * Zustand from SWR before revalidation, so the cache write prevents stale briefs- * from reappearing after navigation.+ * "Mark all read" resolves news briefs with the neutral `read` action and+ * drops them from the unresolved feed. The removal is written to the store+ * and its persisted row, so a route remount hydrates the already-cleared list+ * instead of resurrecting the briefs.*/resolveBriefsAsRead = async (ids: string[]) => {if (ids.length === 0) return;- // Capture the scope these ids belong to *before* awaiting. Unlike the- // id-keyed mutations above, this one rewrites the whole list and patches an- // SWR entry, so a workspace switch mid-request would splice the previous- // partition's briefs into the next one's bucket and cache key β the exact- // leak this slice exists to prevent.- const scope = this.#get().briefsScope;-const result = await briefService.resolveManyAsRead(ids);- const resolvedIds = new Set(result.data);- if (resolvedIds.size === 0) return;-- const state = this.#get();- // Unstamped, or the scope moved while the request was in flight: the switch- // already cleared the bucket, so there is nothing of ours left to patch.- if (scope === undefined || state.briefsScope !== scope) return;-- const briefs = state.briefs.filter((b) => !resolvedIds.has(b.id));- this.#set({ briefs }, false, n('resolveBriefsAsRead'));- void mutate(briefKeys.list(true, scope), briefs, { revalidate: false });+ for (const id of result.data) this.#briefs.remove(id);};resolveBrief = async (id: string, action?: string, comment?: string) => {- const goal = this.#get().briefs.find((brief) => brief.id === id)?.metadata?.goal;- await briefService.resolve(id, { action, comment });- this.internal_updateBrief(id, {- resolvedAction: action,- resolvedAt: new Date().toISOString(),- });+ const goal = this.#get().briefListMap[BRIEF_LIST_KEY]?.find((brief) => brief.id === id)+ ?.metadata?.goal;+ await this.#briefs.optimistic(+ id,+ (brief) => ({+ ...brief,+ resolvedAction: action ?? null,+ resolvedAt: new Date().toISOString(),+ }),+ () => briefService.resolve(id, { action, comment }),+ );// A goal brief answered the goal itself: the island and the goal views// asking the same question have to drop it too.if (goal)@@ -161,54 +173,12 @@ export class BriefListActionImpl {);/**- * `scope` is the identity partition (`${userId}:${workspaceId}`) the caller is- * rendering. Briefs are per-user AND per-workspace rows, so carrying a list- * across a scope change hands the user cards whose ids the server can no- * longer resolve β every action on them 404s, and the tRPC client only logs- * non-401 failures, so the surface just stops responding. Dropping the bucket- * the moment the scope changes is what keeps that from happening.+ * The unresolved feed of the active scope. Read the rows with+ * `briefListSelectors.briefs`; the replica hydrates the persisted copy on the+ * first frame and converges on the server's head page in the background.*/- useFetchBriefs = (isLogin: boolean | undefined, scope: string): SWRResponse<BriefItem[]> => {- // Effect (not render-time set) because this writes another store; the- // scope-aware selectors already keep the foreign list off screen in the- // frame before it runs.- useEffect(() => {- const { briefsScope } = this.#get();- if (briefsScope === undefined || briefsScope === scope) return;-- this.#set(- { briefs: [], briefsScope: undefined, isBriefsInit: false },- false,- n('useFetchBriefs/scopeChanged'),- );- }, [scope]);-- return useClientDataSWRWithSync<BriefItem[]>(- isLogin === true ? briefKeys.list(isLogin, scope) : null,- async () => {- const result = await briefService.listUnresolved();- return result.data as BriefItem[];- },- {- onData: (data) => {- // A response in flight across a scope switch answers for the previous- // partition β writing it back would re-seed exactly the unreachable- // list this hook exists to clear.- if (getCacheScope() !== scope) return;-- const state = this.#get();- if (state.isBriefsInit && state.briefsScope === scope && isEqual(state.briefs, data))- return;-- this.#set(- { briefs: data, briefsScope: scope, isBriefsInit: true },- false,- n('useFetchBriefs/onData'),- );- },- },- );- };+ useFetchBriefs = (isLogin: boolean | undefined): BriefListSyncResult =>+ this.#syncResult(this.#briefList.useSync(LIST_PARAMS, { enabled: isLogin === true }));}export type BriefListAction = Pick<BriefListActionImpl, keyof BriefListActionImpl>;diff --git a/src/store/brief/slices/list/initialState.ts b/src/store/brief/slices/list/initialState.tsindex 88370f9db96..3f681a54d1b 100644--- a/src/store/brief/slices/list/initialState.ts+++ b/src/store/brief/slices/list/initialState.ts@@ -1,21 +1,14 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type BriefItem } from '@/store/brief/types';export interface BriefListState {- briefs: BriefItem[];- /**- * Cache scope (`${userId}:${workspaceId}`) the current `briefs` were fetched- * for. Briefs are per-user AND per-workspace rows, so a list carried across a- * workspace switch is not merely stale β every id in it is unreachable in the- * new scope, and acting on one 404s. Readers compare against the live scope- * and treat a mismatch as "not loaded yet" rather than rendering rows the- * server will refuse.- */- briefsScope?: string;- isBriefsInit: boolean;+ /** The unresolved feed β the view of the `briefList` replica (`briefListMap[BRIEF_LIST_KEY]`). */+ briefListMap: Record<string, BriefItem[]>;+ /** Replica bookkeeping for `briefListMap`. */+ briefListReplica: ReplicaState<BriefItem[]>;}export const initialBriefListState: BriefListState = {- briefs: [],- briefsScope: undefined,- isBriefsInit: false,+ briefListMap: {},+ briefListReplica: createReplicaState(),};diff --git a/src/store/brief/slices/list/projection.ts b/src/store/brief/slices/list/projection.tsnew file mode 100644index 00000000000..97c85efe192--- /dev/null+++ b/src/store/brief/slices/list/projection.ts@@ -0,0 +1,38 @@+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';+import type { briefService } from '@/services/brief';+import type { BriefItem } from '@/store/brief/types';++type BriefListResponse = Awaited<ReturnType<typeof briefService.listUnresolved>>;++/**+ * The unresolved feed holds every open brief of the active identity scope, so+ * the list needs exactly one entry per scope. Briefs are per-user AND+ * per-workspace rows: a list carried across a scope change holds ids the new+ * scope cannot resolve, and every action on it fails silently (the tRPC client+ * only logs non-401 failures). Partitioning by the replica's identity scope β+ * instead of a per-scope key β is what keeps that list off screen: the replica+ * clears the view before paint on a scope switch, and the feed paints its+ * skeleton until the new scope's head page lands.+ */+export const BRIEF_LIST_KEY = 'unresolved';++/**+ * The unresolved brief feed of the active scope. Persisted to IndexedDB so a+ * reload / revisit paints the last confirmed list on the first frame, then+ * converges on the server's head page in the background.+ */+export const briefListResource = defineReplica<+ Record<string, never>,+ BriefItem[],+ BriefListResponse+>({+ key: () => BRIEF_LIST_KEY,+ name: 'briefList',+ storage: 'indexedDB',+ version: 1,+});++/** Briefs are addressed by `briefs.id` β the row's own id. */+export const briefEntity: ReplicaEntityAdapter<BriefItem[], BriefItem> = arrayEntity<BriefItem>(+ (brief) => brief.id,+);diff --git a/src/store/brief/slices/list/selectors.test.ts b/src/store/brief/slices/list/selectors.test.tsindex 1a9338fb3c3..d7b99eb92fd 100644--- a/src/store/brief/slices/list/selectors.test.ts+++ b/src/store/brief/slices/list/selectors.test.ts@@ -1,79 +1,58 @@import { describe, expect, it } from 'vitest';import { type BriefStore } from '@/store/brief/store';+import { type BriefItem } from '@/store/brief/types';import { initialBriefListState } from './initialState';+import { BRIEF_LIST_KEY } from './projection';import { briefListSelectors } from './selectors';-const SCOPE = 'user-1:workspace-1';-const OTHER_SCOPE = 'user-1:workspace-2';-const createState = (overrides: Partial<BriefStore> = {}) =>({...initialBriefListState,...overrides,}) as BriefStore;+const feed = (briefs: BriefItem[]) => ({ [BRIEF_LIST_KEY]: briefs });+describe('briefListSelectors', () => {describe('briefs', () => {it('should return empty array by default', () => {- const state = createState();- expect(briefListSelectors.briefs(SCOPE)(state)).toEqual([]);+ expect(briefListSelectors.briefs(createState())).toEqual([]);});- it('should return briefs fetched for the active scope', () => {- const briefs = [{ id: 'brief-1', title: 'Test' }] as any;- const state = createState({ briefs, briefsScope: SCOPE });- expect(briefListSelectors.briefs(SCOPE)(state)).toBe(briefs);+ it('should return the loaded feed', () => {+ const briefs = [{ id: 'brief-1' }] as unknown as BriefItem[];+ const state = createState({ briefListMap: feed(briefs) });+ expect(briefListSelectors.briefs(state)).toBe(briefs);});- // The reported bug: after a workspace switch the previous scope's briefs- // stayed on screen, and every action on them 404'd silently.- it('should hide briefs fetched for another scope', () => {- const briefs = [{ id: 'brief-1', title: 'Test' }] as any;- const state = createState({ briefs, briefsScope: OTHER_SCOPE, isBriefsInit: true });- expect(briefListSelectors.briefs(SCOPE)(state)).toEqual([]);- });-- it('should keep a stable identity across scope misses so subscribers do not churn', () => {- const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: OTHER_SCOPE });- expect(briefListSelectors.briefs(SCOPE)(state)).toBe(briefListSelectors.briefs(SCOPE)(state));+ // An identity scope with no value yet must not churn `shallow`-compared+ // subscribers (and must not look like an empty feed).+ it('should keep a stable identity for an unloaded feed', () => {+ const state = createState();+ expect(briefListSelectors.briefs(state)).toBe(briefListSelectors.briefs(state));});});describe('hasBriefs', () => {it('should return false when empty', () => {- const state = createState();- expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(false);+ expect(briefListSelectors.hasBriefs(createState())).toBe(false);});it('should return true when has briefs', () => {- const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: SCOPE });- expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(true);- });-- it('should return false when the briefs belong to another scope', () => {- const state = createState({ briefs: [{ id: 'brief-1' }] as any, briefsScope: OTHER_SCOPE });- expect(briefListSelectors.hasBriefs(SCOPE)(state)).toBe(false);+ const state = createState({ briefListMap: feed([{ id: 'brief-1' } as BriefItem]) });+ expect(briefListSelectors.hasBriefs(state)).toBe(true);});});describe('isBriefsInit', () => {- it('should return false by default', () => {- const state = createState();- expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(false);- });-- it('should return true when initialized for the active scope', () => {- const state = createState({ briefsScope: SCOPE, isBriefsInit: true });- expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(true);+ it('should return false while the feed has no value for the active scope', () => {+ expect(briefListSelectors.isBriefsInit(createState())).toBe(false);});- // Reporting "loaded" for a foreign scope is what suppressed the skeleton and- // let the unreachable cards render.- it('should report not-initialized when the loaded scope differs', () => {- const state = createState({ briefsScope: OTHER_SCOPE, isBriefsInit: true });- expect(briefListSelectors.isBriefsInit(SCOPE)(state)).toBe(false);+ it('should report loaded once the feed has a value, even an empty one', () => {+ expect(briefListSelectors.isBriefsInit(createState({ briefListMap: feed([]) }))).toBe(true);});});});diff --git a/src/store/brief/slices/list/selectors.ts b/src/store/brief/slices/list/selectors.tsindex e9546621c40..4c1b1a563e6 100644--- a/src/store/brief/slices/list/selectors.ts+++ b/src/store/brief/slices/list/selectors.ts@@ -1,26 +1,24 @@import { type BriefStore } from '@/store/brief/store';import { type BriefItem } from '@/store/brief/types';-/** Stable identity so a scope miss never churns `shallow`-compared subscribers. */+import { BRIEF_LIST_KEY } from './projection';++/** Stable identity so an unloaded feed never churns `shallow`-compared subscribers. */const EMPTY_BRIEFS: BriefItem[] = [];/**- * Briefs are per-user AND per-workspace rows. A list left over from another- * scope is not merely stale β every id in it is unreachable now, so acting on- * one 404s while the UI shows nothing (the tRPC client only logs non-401- * failures). Selectors therefore report a scope miss as "not loaded yet", which- * makes the surface paint its skeleton instead of unreachable cards.+ * The unresolved feed of the active identity scope. Briefs are per-user AND+ * per-workspace rows, and a list left over from another scope holds ids that+ * are unreachable here. The replica clears its view on a scope switch (before+ * paint), so a miss means "not loaded yet" β the surface then paints its+ * skeleton instead of unreachable cards.*/-const isScopeCurrent = (s: BriefStore, scope: string) => s.briefsScope === scope;--const briefs = (scope: string) => (s: BriefStore) =>- isScopeCurrent(s, scope) ? s.briefs : EMPTY_BRIEFS;+const briefs = (s: BriefStore): BriefItem[] => s.briefListMap[BRIEF_LIST_KEY] ?? EMPTY_BRIEFS;-const hasBriefs = (scope: string) => (s: BriefStore) =>- isScopeCurrent(s, scope) && s.briefs.length > 0;+const hasBriefs = (s: BriefStore): boolean => briefs(s).length > 0;-const isBriefsInit = (scope: string) => (s: BriefStore) =>- isScopeCurrent(s, scope) && s.isBriefsInit;+/** Whether the feed has a confirmed value (hydrated from storage or fetched) for the active scope. */+const isBriefsInit = (s: BriefStore): boolean => s.briefListMap[BRIEF_LIST_KEY] !== undefined;export const briefListSelectors = {briefs,