🤯 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(followUpAction): move the follow-up chip slots onto @lobechat/replica (#20615)
Arvin Xub0c4295f3a43
diff --git a/src/store/followUpAction/action.ts b/src/store/followUpAction/action.tsindex 823ba9d7148..3921de5214d 100644--- a/src/store/followUpAction/action.ts+++ b/src/store/followUpAction/action.ts@@ -1,10 +1,12 @@import type { FollowUpChip, FollowUpHint, FollowUpModelConfig } from '@lobechat/types';+import { cacheScope, createReplicaSlice, recordLens } from '@/libs/replica';import { aiChatService } from '@/services/aiChat';import { followUpActionService } from '@/services/followUpAction';import { type StoreSetter } from '@/store/types';import { type FollowUpActionSlot } from './initialState';+import { followUpSlotResource } from './projection';import { type FollowUpActionStore } from './store';// LLM `generateObject` for chip extraction routinely takes 8-12s end-to-end.@@ -22,37 +24,6 @@ interface FetchForParams {topicId: string;}-const writeSlot = (- set: Setter,- conversationKey: string,- slot: FollowUpActionSlot,- action: string,-): void => {- set(- (state) => ({- slots: {- ...state.slots,- [conversationKey]: slot,- },- }),- false,- action,- );-};--const removeSlot = (set: Setter, conversationKey: string, action: string): void => {- set(- (state) => {- if (!state.slots[conversationKey]) return state;-- const { [conversationKey]: _, ...rest } = state.slots;- return { slots: rest };- },- false,- action,- );-};-export const createFollowUpActionSlice = (set: Setter,get: () => FollowUpActionStore,@@ -60,16 +31,61 @@ export const createFollowUpActionSlice = () => new FollowUpActionImpl(set, get, _api);export class FollowUpActionImpl {- readonly #set: Setter;readonly #get: () => FollowUpActionStore;+ /** Local-first replica of the per-conversation chip slots (`slots` is its view). */+ readonly #slots;constructor(set: Setter, get: () => FollowUpActionStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;+ this.#slots = createReplicaSlice(followUpSlotResource, {+ actionPrefix: 'followUpAction/slot',+ get,+ set,+ stateKey: 'slotsReplica',+ view: recordLens<FollowUpActionStore, FollowUpActionSlot>('slots'),+ });}+ /** Replace one conversation's slot (in-memory only — slots never persist). */+ #writeSlot = (conversationKey: string, slot: FollowUpActionSlot): void => {+ this.#slots.update(conversationKey, () => slot, { persist: false });+ };++ /** Drop one conversation's slot (and its replica bookkeeping entry). */+ #removeSlot = (conversationKey: string): void => {+ this.#slots.remove(conversationKey);+ };++ /**+ * Drop another identity's slots before this slice inspects the view, and+ * return the scope the caller must still be under when it writes back.+ *+ * Unlike the query-backed replicas, this slice never runs `useSync`, so+ * nothing else calls `ensureScope` on an account / workspace switch. Without+ * it the new identity would read the previous one's slot — and, when that+ * slot is still `loading`, skip its own extraction entirely.+ */+ #ensureActiveScope = (): string => {+ const scope = cacheScope.get();+ const { slots, slotsReplica } = this.#get();++ // Leaving an identity: abort its in-flight extractions first. The reset+ // below drops the only reference to their controllers, so an ownerless+ // request would otherwise run on to completion (or its 20s timeout) while+ // the new identity already starts its own.+ if (slotsReplica.scope !== undefined && slotsReplica.scope !== scope) {+ for (const slot of Object.values(slots)) slot.abortController?.abort();+ }++ this.#slots.ensureScope(scope);+ return scope;+ };+fetchFor = async (conversationKey: string, params: FetchForParams): Promise<void> => {+ // Capture the originating scope: an extraction is an async LLM round trip,+ // and a completion must never land under a different identity.+ const scope = this.#ensureActiveScope();const existing = this.#get().slots[conversationKey];if (existing?.status === 'loading') return;@@ -82,16 +98,11 @@ export class FollowUpActionImpl {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);- writeSlot(- this.#set,- conversationKey,- {- abortController: controller,- chips: [],- status: 'loading',- },- 'fetchFor:start',- );+ this.#writeSlot(conversationKey, {+ abortController: controller,+ chips: [],+ status: 'loading',+ });const result = await followUpActionService.extract({@@ -104,43 +115,52 @@ export class FollowUpActionImpl {);clearTimeout(timeoutId);+ // Scope guard: the identity changed while the extraction was in flight, so+ // this completion has no owner. Writing it would dispatch under the *new*+ // identity's scope and commit one identity's suggestions as the next one's.+ // Drop our own now-ownerless slot too — unless the new identity already+ // started its own extraction for the same key (a different controller).+ if (cacheScope.get() !== scope) {+ if (this.#get().slots[conversationKey]?.abortController === controller) {+ this.#removeSlot(conversationKey);+ }+ return;+ }+// Identity guard: a same-key follow-up turn (next assistant settle) would// otherwise let an in-flight prior result overwrite the new turn's chips// when the network abort race is lost.if (this.#get().slots[conversationKey]?.abortController !== controller) return;if (!result || !result.messageId || result.chips.length === 0) {- writeSlot(this.#set, conversationKey, { ...IDLE_SLOT }, 'fetchFor:fail');+ this.#writeSlot(conversationKey, { ...IDLE_SLOT });return;}- writeSlot(- this.#set,- conversationKey,- {- chips: result.chips,- messageId: result.messageId,- status: 'ready',- tracingId: result.tracingId,- },- 'fetchFor:ready',- );+ this.#writeSlot(conversationKey, {+ chips: result.chips,+ messageId: result.messageId,+ status: 'ready',+ tracingId: result.tracingId,+ });};abort = (conversationKey: string): void => {+ this.#ensureActiveScope();const slot = this.#get().slots[conversationKey];if (!slot) return;this.#maybeRecordDismissal(slot);slot.abortController?.abort();- writeSlot(this.#set, conversationKey, { ...IDLE_SLOT }, 'abort');+ this.#writeSlot(conversationKey, { ...IDLE_SLOT });};clear = (conversationKey: string): void => {+ this.#ensureActiveScope();const slot = this.#get().slots[conversationKey];if (!slot) return;this.#maybeRecordDismissal(slot);slot.abortController?.abort();- removeSlot(this.#set, conversationKey, 'clear');+ this.#removeSlot(conversationKey);};consume = (conversationKey: string, chip: FollowUpChip): void => {@@ -154,6 +174,7 @@ export class FollowUpActionImpl {* doesn't additionally fire a dismissal for the same chips.*/recordChipClick = (conversationKey: string, chipIndex: number): void => {+ this.#ensureActiveScope();const slot = this.#get().slots[conversationKey];if (!slot || slot.status !== 'ready' || !slot.tracingId || slot.feedbackDone) return;@@ -166,7 +187,7 @@ export class FollowUpActionImpl {}).catch((err) => console.warn('[FollowUp] recordFeedback (clicked) failed', err));- writeSlot(this.#set, conversationKey, { ...slot, feedbackDone: true }, 'recordChipClick');+ this.#writeSlot(conversationKey, { ...slot, feedbackDone: true });};/**diff --git a/src/store/followUpAction/initialState.ts b/src/store/followUpAction/initialState.tsindex 830515c9373..bc64805a31c 100644--- a/src/store/followUpAction/initialState.ts+++ b/src/store/followUpAction/initialState.ts@@ -1,5 +1,7 @@import type { FollowUpChip } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export type FollowUpActionStatus = 'idle' | 'loading' | 'ready';/** Per-conversation slot — concurrent surfaces (inbox, popup, thread) own their own slot. */@@ -15,9 +17,13 @@ export interface FollowUpActionSlot {}export interface FollowUpActionState {+ /** The replica view: one slot per conversation key. */slots: Record<string, FollowUpActionSlot>;+ /** Replica bookkeeping for `slots` (see `followUpSlotResource`). */+ slotsReplica: ReplicaState<FollowUpActionSlot>;}export const initialFollowUpActionState: FollowUpActionState = {slots: {},+ slotsReplica: createReplicaState(),};diff --git a/src/store/followUpAction/projection.ts b/src/store/followUpAction/projection.tsnew file mode 100644index 00000000000..b47cc6eb151--- /dev/null+++ b/src/store/followUpAction/projection.ts@@ -0,0 +1,26 @@+import { defineReplica } from '@/libs/replica';++import type { FollowUpActionSlot } from './initialState';++export interface FollowUpSlotParams {+ conversationKey: string;+}++/**+ * The follow-up chip slot of one conversation (`slots[conversationKey]`).+ *+ * Keyed by the conversation so the concurrent surfaces that own a slot (inbox,+ * popup, thread) each keep their own entry, and partitioned by identity scope+ * so an account / workspace switch never paints another identity's suggestions.+ *+ * Memory-only: a slot holds the suggestions for the *latest* assistant turn,+ * is produced by an event-driven LLM extraction (not a GET over a stable key)+ * and carries the live `AbortController` of the in-flight extraction — so it+ * must never be written to, or hydrated from, storage.+ */+export const followUpSlotResource = defineReplica<FollowUpSlotParams, FollowUpActionSlot>({+ key: ({ conversationKey }) => conversationKey,+ name: 'followUpSlot',+ storage: 'memory',+ version: 1,+});diff --git a/src/store/followUpAction/replica.test.ts b/src/store/followUpAction/replica.test.tsnew file mode 100644index 00000000000..333a9d0b61d--- /dev/null+++ b/src/store/followUpAction/replica.test.ts@@ -0,0 +1,165 @@+/**+ * The follow-up chip slots are a replica: `slots` is its view, `slotsReplica`+ * its bookkeeping. The slot is memory-only — it is never written to or+ * hydrated from storage — and a write under a new identity scope drops the+ * previous identity's slots instead of letting them bleed across users /+ * workspaces.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { followUpActionService } from '@/services/followUpAction';++import { followUpSlotResource } from './projection';+import { useFollowUpActionStore } from './store';++vi.mock('@/services/followUpAction', () => ({+ followUpActionService: { extract: vi.fn() },+}));++const KEY_A = 'main_agent-a_topic-a';+const KEY_B = 'main_agent-b_topic-b';+const MSG = 'msg-real';++const params = (topicId: string) => ({+ modelConfig: { model: 'scene-model', provider: 'scene-provider' },+ topicId,+});++const slot = (key: string) => useFollowUpActionStore.getState().slots[key];+const entry = (key: string) => useFollowUpActionStore.getState().slotsReplica.entries[key];++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);+};++describe('followUpAction replica', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useScope('u1:personal');+ useFollowUpActionStore.getState().reset();+ vi.mocked(followUpActionService.extract).mockResolvedValue({+ chips: [{ label: 'a', message: 'a' }],+ messageId: MSG,+ });+ });++ it('is a memory-only resource (a slot carries a live AbortController)', () => {+ expect(followUpSlotResource.persisted).toBe(false);+ expect(followUpSlotResource.storage).toBeUndefined();+ });++ it('keys the view by conversation and keeps the booking entry in step', async () => {+ await useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));++ expect(slot(KEY_A)?.status).toBe('ready');+ expect(slot(KEY_A)?.messageId).toBe(MSG);+ // The view is backed by the replica engine (a local write, not a fetch).+ expect(entry(KEY_A)?.source).toBe('local');+ expect(useFollowUpActionStore.getState().slotsReplica.scope).toBe('u1:personal');++ useFollowUpActionStore.getState().clear(KEY_A);++ expect(slot(KEY_A)).toBeUndefined();+ expect(entry(KEY_A)).toBeUndefined();+ });++ it('writes the loading slot through the engine before the extraction resolves', async () => {+ vi.mocked(followUpActionService.extract).mockImplementation(+ () => new Promise(() => {}) as never,+ );++ void useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));++ expect(slot(KEY_A)?.status).toBe('loading');+ expect(entry(KEY_A)).toBeDefined();+ });++ it('drops the previous identity’s slots when the scope switches', async () => {+ await useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));+ expect(slot(KEY_A)?.status).toBe('ready');++ useScope('u2:personal');+ // Any write under the new identity first drops the old identity's view.+ await useFollowUpActionStore.getState().fetchFor(KEY_B, params('topic-b'));++ expect(slot(KEY_A)).toBeUndefined();+ expect(slot(KEY_B)?.status).toBe('ready');+ expect(useFollowUpActionStore.getState().slotsReplica.scope).toBe('u2:personal');+ });++ it('does not let a new identity reuse the previous identity’s in-flight slot', async () => {+ // Identity A's extraction never settles.+ vi.mocked(followUpActionService.extract).mockImplementation(+ () => new Promise(() => {}) as never,+ );+ void useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));+ expect(slot(KEY_A)?.status).toBe('loading');++ // The identity switches while A's extraction is still in flight.+ useScope('u2:personal');+ vi.mocked(followUpActionService.extract).mockResolvedValue({+ chips: [{ label: 'b', message: 'b' }],+ messageId: MSG,+ });++ // Same conversation key: the new identity must run its own extraction+ // instead of reading A's `loading` slot and skipping its fetch.+ await useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));++ expect(followUpActionService.extract).toHaveBeenCalledTimes(2);+ expect(slot(KEY_A)?.chips).toEqual([{ label: 'b', message: 'b' }]);+ expect(useFollowUpActionStore.getState().slotsReplica.scope).toBe('u2:personal');+ });++ it('aborts the outgoing identity’s in-flight extraction before dropping its slot', async () => {+ let signal: AbortSignal | undefined;+ vi.mocked(followUpActionService.extract).mockImplementation(((_input, outgoing) => {+ signal = outgoing as AbortSignal;+ return new Promise(() => {}) as never;+ }) as never);++ void useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));+ expect(signal?.aborted).toBe(false);++ useScope('u2:personal');+ vi.mocked(followUpActionService.extract).mockResolvedValue({ chips: [], messageId: MSG });+ await useFollowUpActionStore.getState().fetchFor(KEY_B, params('topic-b'));++ // The outgoing request is cancelled instead of running on to completion.+ expect(signal?.aborted).toBe(true);+ });++ it('drops an extraction that lands after the identity switched', async () => {+ const resolvers: Array<(value: unknown) => void> = [];+ vi.mocked(followUpActionService.extract).mockImplementation(+ () => new Promise((resolve) => resolvers.push(resolve)) as never,+ );++ const pending = useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));+ expect(slot(KEY_A)?.status).toBe('loading');++ // The identity switches mid-flight, then A's ownerless result lands.+ useScope('u2:personal');+ resolvers[0]({ chips: [{ label: 'a', message: 'a' }], messageId: MSG });+ await pending;++ // It must not be committed as the new identity's data (nor left on screen+ // as its own slot).+ expect(slot(KEY_A)).toBeUndefined();+ expect(entry(KEY_A)).toBeUndefined();+ });++ it('reset clears the view and the replica bookkeeping together', async () => {+ await useFollowUpActionStore.getState().fetchFor(KEY_A, params('topic-a'));++ useFollowUpActionStore.getState().reset();++ expect(useFollowUpActionStore.getState().slots).toEqual({});+ expect(useFollowUpActionStore.getState().slotsReplica.entries).toEqual({});+ });+});diff --git a/src/store/followUpAction/store.ts b/src/store/followUpAction/store.tsindex 647c13a3b92..5cb20a2279a 100644--- a/src/store/followUpAction/store.ts+++ b/src/store/followUpAction/store.ts@@ -3,6 +3,8 @@ import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';import { type StateCreator } from 'zustand/vanilla';+import { createReplicaState } from '@/libs/replica';+import { createDevtools } from '../middleware/createDevtools';import { expose } from '../middleware/expose';import { type StoreSetter } from '../types';@@ -32,7 +34,9 @@ class FollowUpActionStoreResetAction implements ResetableStore {for (const slot of Object.values(current.slots)) {slot.abortController?.abort();}- this.#set({ slots: {} }, false, 'resetFollowUpActionStore');+ // Reset the view and the replica bookkeeping together: `slots` is the+ // replica's view, so clearing only the view would leave stale entries.+ this.#set({ slots: {}, slotsReplica: createReplicaState() }, false, 'resetFollowUpActionStore');};}