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(agentGroup): move the group list and detail onto @lobechat/replica (#20588)

Arvin Xu67c9c9d7291c
diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
index 998081d83b3..4dfc85587d0 100644
--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
@@ -146,7 +146,7 @@ export class GroupAgentBuilderExecutionRuntime {
title: args.title,
});
- state.internal_dispatchChatGroup({ payload: group, type: 'addGroup' });
+ state.internal_addGroup(group);
if (args.supervisor) {
const {
diff --git a/packages/replica/README.md b/packages/replica/README.md
index ce517e5cf4c..a144fd42253 100644
--- a/packages/replica/README.md
+++ b/packages/replica/README.md
@@ -101,4 +101,4 @@ Message-like resources page backward by cursor, with windows whose length change
| `slice.update(key, fn, { persist: false })` + `slice.persist(key)` | Stream into memory, then persist the confirmed value once. |
| `splitPagedLens({ itemsField, metaField, derive })` | Keep raw rows where readers expect them, paging bookkeeping beside them, and derived fields (a parsed display list) in the same commit. |
-`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, …) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in.
+`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, …) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in. On a cold start with no network (offline / slow), `onHydrated` runs the same "success" handling off the persisted value the hydrate paints, since there is no response for `onSuccess` to run on.
diff --git a/packages/replica/src/core/engine.persistence.test.ts b/packages/replica/src/core/engine.persistence.test.ts
index 450ac87f3a7..2048db6c8fb 100644
--- a/packages/replica/src/core/engine.persistence.test.ts
+++ b/packages/replica/src/core/engine.persistence.test.ts
@@ -219,6 +219,31 @@ describe('removeEntity keeps its guard until the persisted patch lands', () => {
});
});
+describe('removeEntity in a scope left behind', () => {
+ it("drops the entity from that scope's rows without touching the active view", async () => {
+ resetScope();
+ const storage = createStorage();
+ const first = setupList(storage);
+ first.engine.replace({ id: 'b' }, [item('1'), item('2')]);
+ await flush();
+
+ // The UI moved to another scope, which shows its own `b`.
+ scopeState.current = 'u2';
+ const { engine, host } = setupList(storage);
+ engine.replace({ id: 'b' }, [item('1'), item('9')]);
+ await flush();
+
+ // A late "gone" for entity 1, answered for the scope left behind.
+ engine.removeEntity('1', { scope: SCOPE });
+ await flush();
+
+ // That scope's persisted row loses it; the scope on screen keeps its own.
+ expect(storage.rows.get(`${SCOPE}|b?{}`)?.data).toEqual([item('2')]);
+ expect(host.view().b).toEqual([item('1'), item('9')]);
+ resetScope();
+ });
+});
+
describe('redundant persist writes', () => {
const rowWrites = (storage: ReturnType<typeof createStorage>, queryKey: string) =>
storage.writes.filter((key) => key === queryKey).length;
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index 95e3d801de2..22cdf070aa7 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -16,8 +16,8 @@ import {
} from './paging';
import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';
import { replicaReducer } from './reducer';
-import { createTombstones } from './tombstones';
-import type { ReplicaResource, ReplicaState } from './types';
+import { createTombstones, DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from './tombstones';
+import type { ReplicaResource, ReplicaSource, ReplicaState } from './types';
import { readReplicaRowStrict, ReplicaWriteQueue } from './writeQueue';
/** Reserved storage key of the per-scope index of persisted rows. */
@@ -166,7 +166,28 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
* again once the scope becomes trusted.
*/
const purgedEntries = createTombstones();
- const markRemoved = (scope: string, key: string) => removedEntries.add(scope, key);
+ /**
+ * Bumped on every removal of a scope+key. A network response whose request
+ * started before the entry was removed (deleted, access revoked, pruned by an
+ * authoritative parent list) must not `replace` it back: the slice records
+ * the generation a request starts under and drops a response that crossed a
+ * removal. Bounded like the tombstones; an evicted key reads 0, which only
+ * ever drops a response (the next revalidate refetches), never admits one.
+ */
+ const removalGenerations = new Map<string, number>();
+ const removalId = (scope: string, key: string) => `${scope}\u0000${key}`;
+ const removalGeneration = (scope: string, key: string) =>
+ removalGenerations.get(removalId(scope, key)) ?? 0;
+ const markRemoved = (scope: string, key: string) => {
+ removedEntries.add(scope, key);
+ const id = removalId(scope, key);
+ const next = (removalGenerations.get(id) ?? 0) + 1;
+ // Re-insert so the map's insertion order is least-recently-removed first.
+ removalGenerations.delete(id);
+ removalGenerations.set(id, next);
+ if (removalGenerations.size > DEFAULT_REMOVAL_TOMBSTONE_LIMIT)
+ removalGenerations.delete(removalGenerations.keys().next().value as string);
+ };
const clearRemoved = (scope: string, key: string) => {
removedEntries.clear(scope, key);
purgedEntries.clear(scope, key);
@@ -583,23 +604,36 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return port.read(key);
};
- const dispatch = (action: ReplicaAction<TData>): boolean => {
+ const dispatch = (action: ReplicaAction<TData>): boolean => runActions([action]);
+
+ /**
+ * Fold one or more actions into a single host commit. A caller that seeds
+ * many keys (a list refresh) must not clone the view and notify subscribers
+ * once per key; every action is still reduced in order, and the accumulated
+ * writes are applied as ONE host update. A batch is dropped whole when any
+ * action belongs to another identity (see {@link dispatch}).
+ */
+ function runActions(actions: ReplicaAction<TData>[]): boolean {
+ if (actions.length === 0) return false;
const activeScope = resource.scope.get();
// An action captured under another identity is stale — drop it.
- if (action.scope !== activeScope) return false;
-
- // Every removal path (explicit `remove`, a missing response, an entity that
- // takes its whole value with it) arms the hydration guard for this key.
- if (action.type === 'remove') markRemoved(action.scope, action.key);
- // A replacement that reaches the active scope supersedes an earlier removal,
- // so the key may hydrate again. A response captured under another scope is
- // dropped below and must NOT clear its guard: the removal still stands for
- // its own scope, whose row delete may be pending or may have failed.
- if (action.type === 'replace') clearRemoved(action.scope, action.key);
+ if (actions.some((action) => action.scope !== activeScope)) return false;
+
+ for (const action of actions) {
+ // Every removal path (explicit `remove`, a missing response, an entity that
+ // takes its whole value with it) arms the hydration guard for this key.
+ if (action.type === 'remove') markRemoved(action.scope, action.key);
+ // A replacement that reaches the active scope supersedes an earlier
+ // removal, so the key may hydrate again. A response captured under another
+ // scope is dropped above and must NOT clear its guard: the removal still
+ // stands for its own scope, whose row delete may be pending or may have failed.
+ if (action.type === 'replace') clearRemoved(action.scope, action.key);
+ }
const initial = getSlot();
let slot = initial;
const writes: ReplicaViewWrite<TData>[] = [];
+ const effects: ReplicaEffect<TData>[] = [];
const read = (key: string) => readThrough(writes, key);
if (slot.scope !== undefined && slot.scope !== activeScope) {
// Memory moves to another identity; what we knew of its rows can go.
@@ -609,15 +643,23 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
slot = reset.state;
}
- const transition = replicaReducer(slot, action, read);
- if (transition.state === slot && transition.writes.length === 0 && slot === initial)
- return false;
+ let changed = false;
+ for (const action of actions) {
+ const transition = replicaReducer(slot, action, read);
+ writes.push(...transition.writes);
+ effects.push(...transition.effects);
+ // The reducer returns the entry's state unchanged for a no-op.
+ if (transition.state !== slot) {
+ slot = transition.state;
+ changed = true;
+ }
+ }
- writes.push(...transition.writes);
- port.commit(writes, transition.state, `${prefix}/${action.type}`);
- runEffects(transition.effects);
+ if (!changed && writes.length === 0 && slot === initial) return false;
+ port.commit(writes, slot, `${prefix}/${actions.length > 1 ? 'batch' : actions[0].type}`);
+ runEffects(effects);
return true;
- };
+ }
/**
* Drop memory owned by another identity as soon as a new scope is active —
@@ -796,12 +838,49 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return applied;
};
- /** Confirmed local write: patches the view (and the base under any overlay). */
+ /**
+ * Confirmed local write: patches the view (and the base under any overlay).
+ * Pass `source: 'seed'` for a provisional row (a list row standing in for a
+ * detail): it is hydratable and never persisted, so the authoritative value it
+ * stands in for is preserved (see `ReplicaSource`).
+ */
const update = (
key: string,
apply: (data: TData | undefined) => TData | undefined,
- { persist = true }: { persist?: boolean } = {},
- ) => dispatch({ apply, key, persist, scope: resource.scope.get(), type: 'update' });
+ {
+ persist = true,
+ seedTag,
+ source,
+ }: { persist?: boolean; seedTag?: string; source?: ReplicaSource } = {},
+ ) =>
+ dispatch({ apply, key, persist, scope: resource.scope.get(), seedTag, source, type: 'update' });
+
+ /**
+ * Confirmed local write to several keys as ONE host update — same per-key
+ * semantics as {@link update}, but a whole list seeds in a single commit
+ * instead of one per row (no repeated view cloning or subscriber churn).
+ */
+ const updateMany = (
+ entries: { apply: (data: TData | undefined) => TData | undefined; key: string }[],
+ {
+ persist = true,
+ seedTag,
+ source,
+ }: { persist?: boolean; seedTag?: string; source?: ReplicaSource } = {},
+ ) => {
+ const scope = resource.scope.get();
+ return runActions(
+ entries.map(({ apply, key }) => ({
+ apply,
+ key,
+ persist,
+ scope,
+ seedTag,
+ source,
+ type: 'update' as const,
+ })),
+ );
+ };
/**
* Purge a removal that belongs to a scope which is no longer active.
@@ -1106,13 +1185,18 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const patchStoredEntityRows = async <TItem>(
id: string,
fn: (item: TItem) => TItem | undefined,
+ scope: string = resource.scope.get(),
): Promise<boolean> => {
if (!writeQueue) return true;
if (!resource.scope.canPersist()) return false;
- const scope = resource.scope.get();
+ // A scope left behind is patched on purpose: nothing of it is loaded, and an
+ // identity switch while reading its index does not make its rows foreign.
+ const offScope = scope !== resource.scope.get();
const slot = getSlot();
+ // Rows memory holds are patched through memory — but only in the active
+ // scope; a view still showing a scope left behind is not what it persists.
const loaded = new Set(
- slot.scope === scope
+ !offScope && slot.scope === scope
? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)
: [],
);
@@ -1126,7 +1210,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return false;
}
// Identity changed while reading the index: those rows are not ours to touch.
- if (resource.scope.get() !== scope) return false;
+ if (!offScope && resource.scope.get() !== scope) return false;
const patches: Promise<boolean>[] = [];
for (const queryKey of keys) {
if (loaded.has(queryKey)) continue;
@@ -1256,8 +1340,8 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
* a value hydrated afterwards — even by a read already in flight — comes
* back without the entity (see `removedEntities`).
*/
- const removeEntity = (id: string, options?: { persist?: boolean }) => {
- const scope = resource.scope.get();
+ const removeEntity = (id: string, options?: { persist?: boolean; scope?: string }) => {
+ const scope = options?.scope ?? resource.scope.get();
const guard: { releasedAt?: number } = {};
const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();
removedEntities.set(scope, guards);
@@ -1268,7 +1352,12 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
guard.releasedAt = ++guardClock;
pruneEntityGuards(scope);
};
- const patch = applyEntity(id, () => undefined, options);
+ // A scope left behind has nothing on screen: only its persisted rows drop
+ // the entity, and the guard keeps a later hydrate there from reading it back.
+ const patch =
+ scope === resource.scope.get()
+ ? applyEntity(id, () => undefined, options)
+ : patchStoredEntityRows(id, () => undefined, scope);
// Without a storage patch (`persist: false`) only reads already in flight
// can hold the entity; with one, reads that start before it lands can too.
// A patch that did not land (untrusted scope, unreadable index or row, a
@@ -1304,6 +1393,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
beginOptimistic,
clear,
clearGeneration,
+ removalGeneration,
collapse,
dispatch,
ensureScope,
@@ -1325,6 +1415,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
revalidate,
update,
updateEntity,
+ updateMany,
};
};
diff --git a/packages/replica/src/core/entity.ts b/packages/replica/src/core/entity.ts
index d5b0dea7a7d..89e37fff422 100644
--- a/packages/replica/src/core/entity.ts
+++ b/packages/replica/src/core/entity.ts
@@ -14,7 +14,7 @@ export interface ReplicaEntityTarget {
* Explicit entity removal that also guards later hydrates. Optional for
* custom targets; `linkReplicaEntity` falls back to `updateEntity`.
*/
- removeEntity?: (id: string, options?: { persist?: boolean }) => void;
+ removeEntity?: (id: string, options?: { persist?: boolean; scope?: string }) => void;
revalidate: (key?: string) => Promise<unknown>;
updateEntity: <TItem>(
id: string,
@@ -48,12 +48,14 @@ export const linkReplicaEntity = <TItem>(targets: ReplicaEntityTarget[]) => {
/**
* Confirmed removal everywhere (list rows dropped, single-entity values
* removed). A value hydrated later — even one whose read was already in
- * flight — comes back without the entity.
+ * flight — comes back without the entity. With `scope` set to a scope left
+ * behind, only that scope's persisted rows lose the entity; the view on
+ * screen belongs to another scope and is left alone.
*/
- const remove = (id: string, options?: { persist?: boolean }): void => {
+ const remove = (id: string, options?: { persist?: boolean; scope?: string }): void => {
for (const target of targets) {
if (target.removeEntity) target.removeEntity(id, options);
- else target.updateEntity<TItem>(id, () => undefined, options);
+ else if (!options?.scope) target.updateEntity<TItem>(id, () => undefined, options);
}
};
diff --git a/packages/replica/src/core/reducer.test.ts b/packages/replica/src/core/reducer.test.ts
index 7ce75dccc45..3e7a0da9b3b 100644
--- a/packages/replica/src/core/reducer.test.ts
+++ b/packages/replica/src/core/reducer.test.ts
@@ -38,6 +38,8 @@ const createHarness = (initialView: Record<string, List> = {}) => {
const S = 'user-1:personal';
const append = (item: string) => (list: List) => [...list, item];
+/** A seed write merges into its input, as a replayed seed must (see `seedPatches`). */
+const seedWith = (item: string) => (list: List | undefined) => [...(list ?? []), item];
describe('replicaReducer', () => {
describe('hydrate vs replace ordering', () => {
@@ -149,6 +151,135 @@ describe('replicaReducer', () => {
expect(h.view.k).toBe(before);
expect(h.state.entries.k.source).toBe('server');
});
+
+ it('hydrates over a provisional seed (a list row standing in for a detail)', () => {
+ const h = createHarness();
+ // The seed makes the object resolvable before its own detail is known.
+ h.run({
+ apply: seedWith('seed'),
+ key: 'k',
+ persist: false,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ expect(h.view.k).toEqual(['seed']);
+ expect(h.state.entries.k.source).toBe('seed');
+
+ // The persisted detail hydrates instead of being blocked, and the seed's
+ // own (fresher) fields are merged back over it.
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['persisted', 'seed']);
+ expect(h.state.entries.k.source).toBe('storage');
+ expect(h.effects).toEqual([]);
+ });
+
+ it('keeps a confirmed local write authoritative over a late hydrate', () => {
+ const h = createHarness();
+ h.run({ apply: () => ['local'], key: 'k', persist: true, scope: S, type: 'update' });
+ expect(h.state.entries.k.source).toBe('local');
+
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['local']);
+ });
+
+ // A confirmed write made over a seed (e.g. a rename while the detail is still
+ // reading storage) must survive the late hydrate that replaces the seed:
+ // it is replayed onto the hydrated value, which then persists.
+ it('replays a confirmed write made over a seed onto the late hydrate', () => {
+ const h = createHarness();
+ h.run({
+ apply: seedWith('seed'),
+ key: 'k',
+ persist: false,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ h.run({ apply: append('confirmed'), key: 'k', persist: true, scope: S, type: 'update' });
+ // Still provisional: persisting the seed would clobber the stored detail.
+ expect(h.effects).toEqual([]);
+
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['persisted', 'seed', 'confirmed']);
+ expect(h.state.entries.k.source).toBe('local');
+ expect(h.effects).toEqual([
+ { data: ['persisted', 'seed', 'confirmed'], key: 'k', scope: S, type: 'persist' },
+ ]);
+
+ // Now authoritative: another late hydrate cannot clobber it either.
+ h.run({ data: ['stale'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['persisted', 'seed', 'confirmed']);
+ });
+
+ it('replays the latest seed and later writes, but persists neither seeds nor in-memory writes', () => {
+ const h = createHarness();
+ h.run({
+ apply: seedWith('seed'),
+ key: 'k',
+ persist: false,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ h.run({
+ apply: append('reseeded'),
+ key: 'k',
+ persist: false,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ h.run({ apply: append('memory'), key: 'k', persist: false, scope: S, type: 'update' });
+
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ // The re-seed supersedes the first seed (same source); the in-memory
+ // write still replays after it.
+ expect(h.view.k).toEqual(['persisted', 'reseeded', 'memory']);
+ expect(h.effects).toEqual([]);
+ });
+
+ // Repeated refreshes of one source must not grow the remembered history:
+ // a later seed of the same tag supersedes the earlier one since the last
+ // confirmed write, while other tags and confirmed writes keep their order.
+ it('coalesces repeated seeds of one tag, keeping their order around confirmed writes', () => {
+ const h = createHarness();
+ const seed = (item: string, seedTag: string) =>
+ h.run({
+ apply: seedWith(item),
+ key: 'k',
+ persist: false,
+ scope: S,
+ seedTag,
+ source: 'seed',
+ type: 'update',
+ });
+ for (let i = 0; i < 50; i++) seed(`list-${i}`, 'list');
+ seed('session', 'session');
+ seed('list-last', 'list');
+ h.run({ apply: append('confirmed'), key: 'k', persist: true, scope: S, type: 'update' });
+ seed('list-after', 'list');
+
+ expect(h.state.entries.k.seedPatches).toHaveLength(4);
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['persisted', 'session', 'list-last', 'confirmed', 'list-after']);
+ });
+
+ it('does not hydrate over a seed that carries an in-flight overlay', () => {
+ const h = createHarness();
+ h.run({
+ apply: seedWith('seed'),
+ key: 'k',
+ persist: false,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+
+ h.run({ data: ['persisted'], key: 'k', scope: S, type: 'hydrate' });
+ expect(h.view.k).toEqual(['seed', 'opt']);
+ });
});
describe('scope isolation', () => {
@@ -285,6 +416,24 @@ describe('replicaReducer', () => {
expect(h.effects).toEqual([]);
});
+ it('a seed never persists, even when its write asks to', () => {
+ const h = createHarness();
+ h.run({
+ apply: () => ['seed'],
+ key: 'k',
+ persist: true,
+ scope: S,
+ source: 'seed',
+ type: 'update',
+ });
+ // A later write on top of the seed keeps it provisional.
+ h.run({ apply: append('patched'), key: 'k', persist: true, scope: S, type: 'update' });
+
+ expect(h.view.k).toEqual(['seed', 'patched']);
+ expect(h.state.entries.k.source).toBe('seed');
+ expect(h.effects).toEqual([]);
+ });
+
it('remove drops the entry and its persisted row', () => {
const h = createHarness({ k: ['a'] });
h.run({ key: 'k', scope: S, type: 'remove' });
diff --git a/packages/replica/src/core/reducer.ts b/packages/replica/src/core/reducer.ts
index 48d0215ff0e..16c1e7f6497 100644
--- a/packages/replica/src/core/reducer.ts
+++ b/packages/replica/src/core/reducer.ts
@@ -1,4 +1,10 @@
-import type { ReplicaEntryMeta, ReplicaPendingMutation, ReplicaState } from './types';
+import type {
+ ReplicaEntryMeta,
+ ReplicaPendingMutation,
+ ReplicaSeedPatch,
+ ReplicaSource,
+ ReplicaState,
+} from './types';
/**
* Pure transition core of a replica. It never touches the store
@@ -40,6 +46,14 @@ export type ReplicaAction<T> =
key: string;
persist: boolean;
scope: string;
+ /** Marks a provisional write (`'seed'`); defaults to the entry's own source. */
+ source?: ReplicaSource;
+ /**
+ * Seed writes of one source (a list refresh, a session refresh). A later
+ * seed write supersedes an earlier one of the same tag since the last
+ * confirmed write, so a remembered seed history stays bounded.
+ */
+ seedTag?: string;
type: 'update';
}
| {
@@ -84,6 +98,27 @@ const noop = <T>(state: ReplicaState<T>): ReplicaTransition<T> => ({
writes: [],
});
+/**
+ * Drop the seed patches a new seed write of `tag` supersedes: those of the same
+ * tag after the last confirmed patch. Repeated refreshes of one source then keep
+ * one patch instead of one per refresh, while the order relative to confirmed
+ * writes (and to other sources' seeds) is preserved.
+ */
+const coalesceSeedPatches = <T>(
+ patches: ReplicaSeedPatch<T>[],
+ isSeedWrite: boolean,
+ tag: string | undefined,
+): ReplicaSeedPatch<T>[] => {
+ if (!isSeedWrite) return patches;
+ let lastConfirmed = -1;
+ patches.forEach((patch, index) => {
+ if (!patch.seed) lastConfirmed = index;
+ });
+ return patches.filter(
+ (patch, index) => index <= lastConfirmed || !patch.seed || patch.tag !== tag,
+ );
+};
+
export const replicaReducer = <T>(
state: ReplicaState<T>,
action: ReplicaAction<T>,
@@ -117,32 +152,50 @@ export const replicaReducer = <T>(
switch (action.type) {
case 'hydrate': {
+ // A removed key never reaches here: the engine's removal tombstones drop a
+ // storage read that resolves after a removal (see `hydrate` in engine.ts).
// Hydrate only fills an empty slot: a server-confirmed value, an
// optimistic write or any local write always wins over storage. A caller
// that knows the slot answers a *different* query (a navigation) may ask
// to repaint it from that query's persisted page instead — the overlays it
// drops belong to the query being left. An overlay whose query is unknown
// still wins: we cannot prove it is not this query's.
- if (entry) {
+ //
+ // A provisional `seed` is the other exception — it is a list row standing
+ // in for a detail, not authoritative state, so the persisted value
+ // replaces it. Otherwise a seeded entry would block the persisted detail
+ // forever.
+ const provisionalSeed = !!entry && entry.source === 'seed' && entry.pending.length === 0;
+ if (entry && !provisionalSeed) {
if (
!action.overwrite ||
entry.query === action.query ||
entry.pending.some((mutation) => mutation.query === undefined)
)
return noop(state);
- } else if (view !== undefined) {
+ } else if (!entry && view !== undefined) {
return noop(state);
}
+ // The writes made over the seed are replayed onto the stored value, so
+ // storage cannot clobber them: the seed's own (fresher) fields — a list
+ // row's renamed title — and any confirmed edit made before storage
+ // answered. Only a confirmed edit makes the result a local value (and
+ // persists it); seed writes stay in-memory.
+ const patches = (provisionalSeed && entry.seedPatches) || [];
+ const data = patches.reduce((value, patch) => patch.apply(value) ?? value, action.data);
+ const confirmedPatches = patches.filter((patch) => !patch.seed);
return {
- effects: [],
+ effects: confirmedPatches.some((patch) => patch.persist)
+ ? [{ data, key: action.key, query: action.query, scope, type: 'persist' }]
+ : [],
state: withEntry({
params: action.params,
pending: [],
query: action.query,
- source: 'storage',
- updatedAt: action.updatedAt ?? now,
+ source: confirmedPatches.length ? 'local' : 'storage',
+ updatedAt: confirmedPatches.length ? now : (action.updatedAt ?? now),
}),
- writes: [{ data: action.data, key: action.key }],
+ writes: [{ data, key: action.key }],
};
}
@@ -182,16 +235,40 @@ export const replicaReducer = <T>(
const pending = entry?.pending ?? [];
const nextBase = pending.length ? action.apply(entry!.base) : nextView;
if (nextView === view && nextBase === confirmed) return noop(state);
+ // A provisional seed is never authoritative, so it must not persist: it
+ // only stands in for a value another source owns, and persisting it would
+ // overwrite that value's persisted row. A `seed` also only ever marks a
+ // fresh slot — a value already in memory (written outside the binding) is
+ // authoritative and is never downgraded to a seed.
+ const source: ReplicaSource =
+ entry?.source ?? (view === undefined ? (action.source ?? 'local') : 'local');
+ const persist = action.persist && source !== 'seed';
+ // Every write while the entry is a seed is remembered so a hydrate that
+ // replaces the seed replays it (see `hydrate`): a confirmed write keeps
+ // the seed provisional, and a seed write carries fresher fields.
+ const isSeedWrite = action.source === 'seed';
+ const seedPatches =
+ source === 'seed'
+ ? [
+ ...coalesceSeedPatches(entry?.seedPatches ?? [], isSeedWrite, action.seedTag),
+ {
+ apply: action.apply,
+ persist: !isSeedWrite && action.persist,
+ ...(isSeedWrite && { seed: true, tag: action.seedTag }),
+ },
+ ]
+ : entry?.seedPatches;
return {
effects:
- action.persist && nextBase !== undefined
+ persist && nextBase !== undefined
? [{ data: nextBase, key: action.key, query: entry?.query, scope, type: 'persist' }]
: [],
state: withEntry({
...entry,
base: pending.length ? nextBase : undefined,
pending,
- source: entry?.source ?? 'local',
+ seedPatches,
+ source,
updatedAt: now,
}),
writes: nextView === view ? [] : [{ data: nextView, key: action.key }],
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index 023a126254b..2edd473decb 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -49,8 +49,12 @@ export interface ReplicaStorage<T> {
* - `storage`: hydrated from the persisted projection (may be stale)
* - `server`: confirmed by a network response
* - `local`: written locally before any hydrate/replace landed
+ * - `seed`: a provisional local row (e.g. a list row standing in for a detail so
+ * an object stays resolvable). Unlike `local` it is *not* authoritative: a
+ * persisted `storage` value may replace it on hydrate, and it never persists —
+ * so it cannot overwrite the detail it is only standing in for.
*/
-export type ReplicaSource = 'local' | 'server' | 'storage';
+export type ReplicaSource = 'local' | 'seed' | 'server' | 'storage';
/**
* Identity partition of the persisted projection (user + workspace by default).
@@ -94,10 +98,34 @@ export interface ReplicaEntryMeta<T> {
pending: ReplicaPendingMutation<T>[];
/** Stable query identity beyond the key (filters, page size). */
query?: string;
+ /**
+ * Every write made while the entry is still a `seed`, in order — the seed
+ * writes themselves and the confirmed writes made over them. A hydrate that
+ * replaces the seed replays them onto the stored value: the seed's fresher
+ * fields (a list row's renamed title) and a confirmed edit made before
+ * storage answered both survive, instead of storage painting older values.
+ */
+ seedPatches?: ReplicaSeedPatch<T>[];
source: ReplicaSource;
updatedAt: number;
}
+export interface ReplicaSeedPatch<T> {
+ /**
+ * Replayed onto the stored value, so a seed write must merge the fields it
+ * owns into its input rather than ignore it (its first run sees `undefined`).
+ */
+ apply: (data: T | undefined) => T | undefined;
+ persist: boolean;
+ /** A provisional seed write: replayed, but never makes the result confirmed. */
+ seed?: boolean;
+ /**
+ * Source of a seed write. A later seed of the same tag supersedes this one
+ * (since the last confirmed write), so it must carry every field this one set.
+ */
+ tag?: string;
+}
+
/** Bookkeeping slot a replica keeps inside its domain store. */
export interface ReplicaState<T> {
entries: Record<string, ReplicaEntryMeta<T>>;
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index 7327613a50f..58aebde33bb 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -11,6 +11,7 @@ import { createStore } from 'zustand/vanilla';
import { testDriver as driver } from '../../tests/testDriver';
import { defineReplica } from '../core/defineReplica';
import { REPLICA_INDEX_KEY } from '../core/engine';
+import { singleEntity } from '../core/entityAdapters';
import { createReplicaState } from '../core/reducer';
import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';
import { createReplicaSlice, recordLens } from './createReplicaSlice';
@@ -154,6 +155,33 @@ describe('createReplicaSlice', () => {
expect(failing.store.getState().lists.b).toBeUndefined();
});
+ it('runs onHydrated with the hydrated value, and skips it when nothing was stored', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });
+ let resolveFetch!: (value: string[]) => void;
+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));
+ const { slice, store } = setup({ fetcher, storage });
+ const seen: string[][] = [];
+ renderHook(() => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));
+ expect(seen).toEqual([['cached']]);
+
+ await act(async () => resolveFetch(['server']));
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));
+ // The network response stays `onSuccess`'s job; onHydrated does not fire for it.
+ expect(seen).toEqual([['cached']]);
+
+ // An empty slot has no persisted value, so nothing is replayed.
+ const empty = setup();
+ const missed = vi.fn();
+ renderHook(() => empty.slice.useSync({ id: 'b' }, { onHydrated: missed }), { wrapper });
+ await waitFor(() => expect(empty.store.getState().lists.b).toEqual(['server']));
+ expect(missed).not.toHaveBeenCalled();
+ });
+
it('drops the prior persisted projection when `toPersisted` reports a confirmed absence', async () => {
const storage = createMemoryStorage();
storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });
@@ -456,6 +484,48 @@ describe('createReplicaSlice', () => {
expect(store.getState().lists.a).toBeUndefined();
});
+ it('runs the caller success side effects when the response changes nothing', () => {
+ // `replace` reports false both for a rejected response and for one with
+ // nothing to write (an unchanged revalidation, or `undefined` for an id the
+ // server no longer has). Callers rely on onSuccess in the latter cases —
+ // e.g. removing a cached detail the server answered with nothing.
+ const requests: { onSuccess: (data: string[] | undefined) => void }[] = [];
+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {
+ if (key !== null && options?.onSuccess) requests.push({ onSuccess: options.onSuccess });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'noopSuccessSideEffects',
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: { a: ['same'] },
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ scopeState.current = 'user-1:personal';
+ const onSuccess = vi.fn();
+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });
+ const request = requests.find((entry) => entry)!;
+
+ act(() => request.onSuccess(['same']));
+ act(() => request.onSuccess(['same']));
+ act(() => request.onSuccess(undefined));
+
+ expect(onSuccess).toHaveBeenCalledTimes(3);
+ expect(onSuccess).toHaveBeenLastCalledWith(undefined);
+ });
+
it("drops a settled request's success side effects once the store has left its scope", () => {
// A response can settle after an identity/workspace switch. The engine
// refuses the off-scope `replace`, but the caller's callbacks carry the
@@ -573,6 +643,29 @@ describe('createReplicaSlice', () => {
await waitFor(() => expect(memory.rows.get('user-1:personal|a')).toBeUndefined());
});
+ // The guard lives in the engine, per scope — not in the bookkeeping slot a
+ // scope reset wipes — so an A → B → A round trip cannot lift it.
+ it('keeps the removal guard across a scope round trip', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ // The persisted-row delete is still pending: the stale row stays on disk.
+ storage.storage.remove = async () => {};
+ const { slice, store } = setup({ storage });
+
+ act(() => slice.remove('a'));
+
+ scopeState.current = 'user-2:personal';
+ act(() => slice.ensureScope('user-2:personal'));
+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');
+ scopeState.current = 'user-1:personal';
+ act(() => slice.ensureScope('user-1:personal'));
+
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
it('purges the captured scope row for a removal that lands after a scope switch', async () => {
const storage = createMemoryStorage();
storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
@@ -730,6 +823,141 @@ describe('createReplicaSlice', () => {
await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual([]));
});
+ // The removal deletes the entry, but a storage read that started before it
+ // can still resolve afterwards; the replica must not let that stale read
+ // resurrect the removed entry (the server already confirmed it gone).
+ it('does not let a hydrate that resolves after a removal resurrect the entry', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });
+ const realGet = storage.storage.get.bind(storage.storage);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ let readStarted = false;
+ vi.spyOn(storage.storage, 'get').mockImplementation(async (key) => {
+ if (key.queryKey === 'a') {
+ // A storage read is a snapshot: capture the row now, resolve later.
+ const snapshot = await realGet(key);
+ readStarted = true;
+ await readGate;
+ return snapshot;
+ }
+ return realGet(key);
+ });
+
+ // A network that never answers, so only the hydrate is at play.
+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });
+
+ let hydrated = false;
+ const session = renderHook(
+ () => slice.useSync({ id: 'a' }, { onHydrated: () => (hydrated = true) }),
+ { wrapper },
+ );
+ await waitFor(() => expect(readStarted).toBe(true));
+
+ // The key is removed (a server-confirmed absence) before the read lands.
+ act(() => slice.remove('a'));
+
+ releaseRead();
+ await act(async () => {});
+
+ expect(hydrated).toBe(false);
+ expect(store.getState().lists.a).toBeUndefined();
+ expect(store.getState().listsReplica.entries.a).toBeUndefined();
+ session.unmount();
+ });
+
+ // a → b → a: a's hydration query already settled and is not re-run, so its
+ // side effects must be replayed off the cached value when `a` is active again
+ // — or they stay pointed at `b` until (or, offline, without) a response.
+ it('replays onHydrated when a hydrated key becomes active again', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['cached-a'], updatedAt: 1 });
+ storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });
+ // Offline: the network never answers, so only hydration can run effects.
+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });
+ const seen: string[][] = [];
+
+ const session = renderHook(
+ ({ id }: { id: string }) =>
+ slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),
+ { initialProps: { id: 'a' }, wrapper },
+ );
+ await waitFor(() => expect(session.result.current.isHydrated).toBe(true));
+ // The first activation runs it once, from the hydrate itself.
+ expect(seen).toEqual([['cached-a']]);
+
+ session.rerender({ id: 'b' });
+ await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b']]));
+
+ session.rerender({ id: 'a' });
+ await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b'], ['cached-a']]));
+ expect(store.getState().lists.a).toEqual(['cached-a']);
+
+ // A plain re-render of the same key does not replay again.
+ session.rerender({ id: 'a' });
+ await act(async () => {});
+ expect(seen).toHaveLength(3);
+ session.unmount();
+ });
+
+ // Scope A → B → A with the same key: B's activation cleared the view and
+ // A's `once` hydration result is reused, so the slice must read A's
+ // partition again — offline, nothing else would bring the row back.
+ it('rehydrates an entry after returning to a prior scope', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['cached-a1'], updatedAt: 1 });
+ storage.rows.set('user-2:personal|a', { data: ['cached-a2'], updatedAt: 1 });
+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });
+ const seen: string[][] = [];
+
+ const session = renderHook(
+ () => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }),
+ { wrapper },
+ );
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));
+
+ scopeState.current = 'user-2:personal';
+ session.rerender();
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a2']));
+
+ scopeState.current = 'user-1:personal';
+ session.rerender();
+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));
+ // Its side effects follow the row back too.
+ await waitFor(() => expect(seen.at(-1)).toEqual(['cached-a1']));
+ session.unmount();
+ });
+
+ // A lookup that missed storage settles `true` as well; reactivating its key
+ // must not replay `onHydrated` off a value that never came from storage
+ // (a provisional seed written into the view).
+ it('does not replay onHydrated for a reactivated key whose lookup missed storage', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });
+ const { slice } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });
+ const seen: string[][] = [];
+
+ const session = renderHook(
+ ({ id }: { id: string }) =>
+ slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),
+ { initialProps: { id: 'a' }, wrapper },
+ );
+ await waitFor(() => expect(session.result.current.isHydrated).toBe(true));
+ expect(seen).toEqual([]);
+
+ session.rerender({ id: 'b' });
+ await waitFor(() => expect(seen).toEqual([['cached-b']]));
+
+ // A seed lands in `a`'s view while the hook shows `b`.
+ act(() => {
+ slice.update('a', () => ['seed-a'], { persist: false, source: 'seed' });
+ });
+ session.rerender({ id: 'a' });
+ await act(async () => {});
+ expect(seen).toEqual([['cached-b']]);
+ session.unmount();
+ });
+
it('a version bump ignores rows written by the previous version', async () => {
// One backing map shared by every version, keyed by the namespace the
// factory receives — like IndexedDB rows of two app releases.
@@ -1454,6 +1682,196 @@ describe('createReplicaSlice', () => {
});
});
+ describe('late scoped responses', () => {
+ it('does not replay a response that lands after a scope switch', () => {
+ // A driver that settles each request through its own callback, so the
+ // test chooses the moment the response arrives.
+ let settle!: (data: string[]) => void;
+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {
+ if (key !== null) settle = options.onSuccess;
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'lateScopeResponse',
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ const onSuccess = vi.fn();
+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));
+
+ // The identity switches while the request is in flight; the response
+ // belongs to the previous scope and `replace` rejects it.
+ scopeState.current = 'user-2:personal';
+ act(() => settle(['late-user-1']));
+
+ expect(store.getState().lists.a).toBeUndefined();
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ // An entity removed while its entry's request is in flight (deleted, pruned
+ // by an authoritative parent list) must not be recreated by that response.
+ // `slice.remove` drops the head-query marker, but an entity removal goes
+ // straight through the engine, so the request generation must catch it.
+ it('drops a response whose request started before the entity was removed', () => {
+ interface Item {
+ id: string;
+ title: string;
+ }
+ interface ItemState {
+ items: Record<string, Item>;
+ itemsReplica: ReplicaState<Item>;
+ }
+ let settle!: (data: Item) => void;
+ const useQuery = vi.fn((key: any, fetcher: () => unknown, options: any) => {
+ if (key !== null) {
+ settle = options.onSuccess;
+ void fetcher();
+ }
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const resource = defineReplica<{ id: string }, Item>({
+ fetcher: () => new Promise<Item>(() => {}),
+ key: ({ id }) => id,
+ name: 'removedEntityInFlight',
+ scope,
+ version: 1,
+ });
+ const store = createStore<ItemState>()(() => ({
+ items: {},
+ itemsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<ItemState, { id: string }, Item>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ entity: singleEntity<Item>((item) => item.id),
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'itemsReplica',
+ view: recordLens('items'),
+ });
+ act(() => slice.replace({ id: 'a' }, { id: 'a', title: 'first' }));
+
+ const onSuccess = vi.fn();
+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));
+ act(() => slice.removeEntity('a'));
+ expect(store.getState().items.a).toBeUndefined();
+
+ act(() => settle({ id: 'a', title: 'stale' }));
+ expect(store.getState().items.a).toBeUndefined();
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ // a → b while a's request is in flight: a's late response still fills its
+ // own cache entry, but its success side effects act on the CURRENT view, so
+ // they must not re-adopt `a` while the hook shows `b`.
+ it('does not replay a response for a key the hook has moved past', () => {
+ let settle!: (data: string[]) => void;
+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {
+ if (key !== null) settle = options.onSuccess;
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async ({ id }) => [id],
+ key: ({ id }) => id,
+ name: 'lateKeyResponse',
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ const onSuccess = vi.fn();
+ const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {
+ initialProps: { id: 'a' },
+ });
+ const settleA = settle;
+
+ rerender({ id: 'b' });
+ const settleB = settle;
+ act(() => settleA(['late-a']));
+
+ expect(store.getState().lists.a).toEqual(['late-a']);
+ expect(onSuccess).not.toHaveBeenCalled();
+
+ act(() => settleB(['b']));
+ expect(onSuccess).toHaveBeenCalledTimes(1);
+ expect(onSuccess).toHaveBeenCalledWith(['b']);
+ });
+ });
+
+ describe('updateMany', () => {
+ it('applies many keys as one commit and clones the record once', () => {
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'batchedSeed',
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const lens = recordLens<TestState, string[]>('lists');
+ const setMany = vi.spyOn(lens, 'setMany');
+ const set = vi.spyOn(lens, 'set');
+ let commits = 0;
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: {
+ revalidate: vi.fn(),
+ useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+ },
+ get: store.getState,
+ set: (partial) => {
+ commits += 1;
+ store.setState(partial);
+ },
+ stateKey: 'listsReplica',
+ view: lens,
+ });
+
+ act(() => {
+ slice.updateMany([
+ { apply: () => ['a'], key: 'a' },
+ { apply: () => ['b'], key: 'b' },
+ { apply: () => ['c'], key: 'c' },
+ ]);
+ });
+
+ expect(store.getState().lists).toEqual({ a: ['a'], b: ['b'], c: ['c'] });
+ // One host commit for the whole batch, and one clone of the record.
+ expect(commits).toBe(1);
+ expect(setMany).toHaveBeenCalledTimes(1);
+ expect(set).not.toHaveBeenCalled();
+
+ // An empty batch commits nothing.
+ expect(slice.updateMany([])).toBe(false);
+ expect(commits).toBe(1);
+ });
+ });
+
describe('optimistic', () => {
it('commits and persists the confirmed value on success', async () => {
const { slice, store, storage } = setup();
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index d71092e51c4..596f2e19e29 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -1,4 +1,4 @@
-import { useLayoutEffect } from 'react';
+import { useEffect, useLayoutEffect, useRef } from 'react';
import { stableQueryKey } from '../core/defineReplica';
import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';
@@ -11,6 +11,14 @@ import type { ReplicaSyncDriver, ReplicaSyncSchedule } from './driver';
/** Zustand `setState`, with the devtools action label. */
type Setter<TStore> = (partial: Partial<TStore>, replace?: false, action?: any) => void;
+/**
+ * One `key` write in a batched lens update (see {@link ReplicaLens.setMany}).
+ */
+export interface ReplicaViewSet<TData> {
+ data: TData | undefined;
+ key: string;
+}
+
/**
* Where the materialized value lives in the domain store. Selectors keep
* reading this location; the slice is the only writer.
@@ -21,6 +29,12 @@ export interface ReplicaLens<TStore, TData> {
/** Enumerate loaded keys (needed for entity propagation). */
keys?: (state: TStore) => string[];
set: (state: TStore, key: string, data: TData | undefined) => Partial<TStore>;
+ /**
+ * Apply several key writes in one pass — one clone of the backing field
+ * instead of one per key. Optional: the slice falls back to repeated `set`
+ * when a lens does not implement it.
+ */
+ setMany?: (state: TStore, entries: ReplicaViewSet<TData>[]) => Partial<TStore>;
}
export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> extends Omit<
@@ -56,7 +70,10 @@ export interface ReplicaSyncErrorContext {
scope: string;
}
-export interface ReplicaSyncOptions<TFetched = unknown> extends ReplicaSyncSchedule {
+export interface ReplicaSyncOptions<
+ TFetched = unknown,
+ TData = unknown,
+> extends ReplicaSyncSchedule {
enabled?: boolean;
/**
* Side effects of a failed fetch (error side-maps); the store view is left as is.
@@ -65,6 +82,13 @@ export interface ReplicaSyncOptions<TFetched = unknown> extends ReplicaSyncSched
* active once the callback runs.
*/
onError?: (error: unknown, context: ReplicaSyncErrorContext) => void;
+ /**
+ * Side effects of a hydrated persisted value, run after it is folded into the
+ * replica. A cold start with no network (offline / slow) has no response for
+ * `onSuccess` to run on, so the same "success" handling must also run off the
+ * persisted value it paints.
+ */
+ onHydrated?: (data: TData) => void;
/**
* Side effects of a response, run after it is folded into the replica
* (e.g. adopting an active id, or settling a "not found" state).
@@ -102,14 +126,45 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
...options
}: CreateReplicaSliceOptions<TStore, TParams, TData, TFetched>,
) => {
+ /**
+ * Apply every view write as ONE host update, so subscribers never observe a
+ * view out of step with its bookkeeping. Consecutive key writes go through
+ * the lens' `setMany` when it has one, so seeding N rows clones the backing
+ * field once instead of N times.
+ */
const applyWrites = (state: TStore, writes: ReplicaViewWrite<TData>[]) => {
let patch: Partial<TStore> = {};
let current = state;
+ let pending: ReplicaViewSet<TData>[] = [];
+
+ const flush = () => {
+ if (pending.length === 0) return;
+ const entries = pending;
+ pending = [];
+ if (view.setMany && entries.length > 1) {
+ const next = view.setMany(current, entries);
+ patch = { ...patch, ...next };
+ current = { ...current, ...next };
+ return;
+ }
+ for (const entry of entries) {
+ const next = view.set(current, entry.key, entry.data);
+ patch = { ...patch, ...next };
+ current = { ...current, ...next };
+ }
+ };
+
for (const write of writes) {
- const next = 'type' in write ? view.clear(current) : view.set(current, write.key, write.data);
- patch = { ...patch, ...next };
- current = { ...current, ...next };
+ if ('type' in write) {
+ flush();
+ const next = view.clear(current);
+ patch = { ...patch, ...next };
+ current = { ...current, ...next };
+ } else {
+ pending.push({ data: write.data, key: write.key });
+ }
}
+ flush();
return patch;
};
@@ -129,7 +184,8 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
},
revalidate,
});
- const { clearGeneration, ensureScope, fetcher, hydrate, replace, retain } = engine;
+ const { clearGeneration, ensureScope, fetcher, hydrate, removalGeneration, replace, retain } =
+ engine;
/**
* Row key of the head query each entry last asked for. One entry backs a
@@ -141,6 +197,16 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
*/
const headQuery = new Map<string, string>();
+ /**
+ * Entries (`scope` + key) whose one-shot hydration actually painted a
+ * persisted row. The hydration query settles `true` on a cache miss too, so
+ * a reactivated key may only replay `onHydrated` when its row really came from
+ * storage — not off a provisional seed or another source that happens to sit
+ * in the view.
+ */
+ const hydratedEntries = new Set<string>();
+ const hydratedEntryId = (scope: string, key: string) => `${scope}\u0000${key}`;
+
/**
* `clear()` generation each in-flight head request started under, by sync
* key. A response to a request that started before a `clear()` of its scope
@@ -148,7 +214,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
* at a time (a newer request supersedes the older one), so the latest start
* is the one that settles.
*/
- const requestGeneration = new Map<string, number>();
+ const requestGeneration = new Map<string, { clear: number; removal: number }>();
/**
* Hydrates the persisted row once per scope/key/query, then lets the driver
@@ -156,7 +222,13 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
*/
const useSync = (
params: TParams | null | undefined,
- { enabled = true, onError, onSuccess, ...schedule }: ReplicaSyncOptions<TFetched> = {},
+ {
+ enabled = true,
+ onError,
+ onHydrated,
+ onSuccess,
+ ...schedule
+ }: ReplicaSyncOptions<TFetched, TData> = {},
): ReplicaSyncResult => {
const scope = resource.scope.use();
const key = params ? resource.key(params) : undefined;
@@ -179,17 +251,73 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
if (active && key !== undefined && queryKey !== undefined) return retain(key, queryKey);
}, [active, key, queryKey]);
+ // The entry this hook currently asks for. A hydrate that resolves after the
+ // hook moved to another key still fills its own cache entry (harmless), but
+ // it must not replay `onHydrated`: those side effects act on the *current*
+ // view, so they would re-adopt a superseded object (e.g. navigate g1 → g2
+ // while g1's storage read is slow, then g1's hydrate resets the active group
+ // back to g1's supervisor).
+ const activeKey = useRef<string | undefined>(undefined);
+ // The entry (scope + key) whose hydration side effects already ran in its
+ // current activation. Reset on every key or scope change, so an entry that
+ // comes back (g1 → g2 → g1, or scope A → B → A with the same key) gets them
+ // replayed even though its `once` hydration is not re-run.
+ const hydratedKey = useRef<string | undefined>(undefined);
+ useLayoutEffect(() => {
+ activeKey.current = active ? key : undefined;
+ hydratedKey.current = undefined;
+ }, [active, key, scope]);
+
const hydration = driver.useQuery<boolean>(
active && resource.persisted && resource.persistKey(key!)
? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!))
: null,
async () => {
- await hydrate(params!, scope);
+ const didHydrate = await hydrate(params!, scope);
+ if (didHydrate) hydratedEntries.add(hydratedEntryId(scope, key!));
+ // A superseded key (the hook moved on) runs no side effects at all.
+ if (activeKey.current !== key) return true;
+ hydratedKey.current = hydratedEntryId(scope, key!);
+ // A persisted row is a successful value with no network response: replay
+ // the success side effects off it, so an offline / slow first paint still
+ // adopts the roster and settles the flags the response path would.
+ if (didHydrate) {
+ const hydrated = view.get(get(), key!);
+ if (hydrated !== undefined) onHydrated?.(hydrated);
+ }
return true;
},
{ once: true },
);
+ // Reactivating a key whose hydration already settled: the driver reuses the
+ // `once` result and the fetcher above does not run, so replay the side
+ // effects off the value in memory. Without it, returning to g1 offline
+ // leaves them acting on g2 until a response lands (or forever, offline).
+ useEffect(() => {
+ if (!active || key === undefined || hydration.data !== true) return;
+ const entry = hydratedEntryId(scope, key);
+ if (hydratedKey.current === entry) return;
+ hydratedKey.current = entry;
+ const current = view.get(get(), key);
+ if (current !== undefined) {
+ // A lookup that missed storage hydrated nothing to replay.
+ if (hydratedEntries.has(entry)) onHydrated?.(current);
+ return;
+ }
+ // Back on a scope whose view `ensureScope` cleared (A → B → A): the cached
+ // `once` result means the fetcher will not read storage again, so read it
+ // here — otherwise a row still in A's partition stays off screen while
+ // the network is slow or offline.
+ void hydrate(params!, scope).then((didHydrate) => {
+ if (!didHydrate) return;
+ hydratedEntries.add(entry);
+ if (activeKey.current !== key || resource.scope.get() !== scope) return;
+ const hydrated = view.get(get(), key);
+ if (hydrated !== undefined) onHydrated?.(hydrated);
+ });
+ }, [active, key, scope, hydration.data]);
+
const syncKey =
active && fetcher
? (resource.syncKey?.(params!) ??
@@ -198,12 +326,20 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
const requestId = () => `${scope}\u0000${stableQueryKey(syncKey)}`;
/** Whether the request settling now still belongs to the entry's active query. */
const isActiveQuery = () => queryKey !== undefined && headQuery.get(key!) === queryKey;
- /** Whether the settling request started after the latest `clear()` of its scope. */
+ /**
+ * Whether the settling request started after the latest `clear()` of its
+ * scope and after the latest removal of its entry (a deleted / pruned entry
+ * must not be recreated by a response that was already in flight).
+ */
const isSinceClear = () => {
const id = requestId();
const started = requestGeneration.get(id);
requestGeneration.delete(id);
- return started === undefined || started === clearGeneration(scope);
+ return (
+ started === undefined ||
+ (started.clear === clearGeneration(scope) &&
+ started.removal === removalGeneration(scope, key!))
+ );
};
/**
* Whether the entry is still on the scope the request was captured under.
@@ -220,7 +356,10 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
const sync = driver.useQuery<TFetched>(
syncKey,
() => {
- requestGeneration.set(requestId(), clearGeneration(scope));
+ requestGeneration.set(requestId(), {
+ clear: clearGeneration(scope),
+ removal: removalGeneration(scope, key!),
+ });
return fetcher!(params!, undefined);
},
{
@@ -247,6 +386,10 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
// one captured under a scope the store has since left.
if (!isSinceClear() || !isActiveQuery() || !isActiveScope()) return;
replace(params!, data, scope);
+ // The same holds for a key the hook has moved past (g1 → g2 while
+ // g1's request is in flight): the response still fills g1's own
+ // entry, but its side effects would re-adopt g1 over the g2 view.
+ if (activeKey.current !== key) return;
onSuccess?.(data);
},
},
@@ -303,6 +446,16 @@ export const recordLens = <TStore, TData>(
else next[key] = data;
return { [field]: next } as Partial<TStore>;
},
+ setMany: (state, entries) => {
+ // One clone of the record, then every key — a list refresh seeds N groups
+ // in a single copy instead of N.
+ const next = { ...(state[field] as Record<string, TData> | undefined) };
+ for (const { key, data } of entries) {
+ if (data === undefined) delete next[key];
+ else next[key] = data;
+ }
+ return { [field]: next } as Partial<TStore>;
+ },
});
/**
diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts
index cb1359d8154..96622190414 100644
--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts
+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { groupKeys } from '@/libs/swr/keys';
+import type * as ReplicaModule from '@/libs/replica';
import { refreshCachesAfterOwnershipChange } from './refreshAfterOwnershipChange';
@@ -8,12 +8,22 @@ const mocks = vi.hoisted(() => ({
globalMutate: vi.fn(),
refreshAgentConfig: vi.fn(),
refreshAgentList: vi.fn(),
+ revalidateReplica: vi.fn(),
}));
// The regression this guards: the accept path once passed these detail keys to
// a hook-BOUND `mutate` (which treats a key as replacement data for its own
-// cache). The refresh must go through the GLOBAL mutator from `@/libs/swr`.
+// cache). Agent config still goes through the agent store; the group detail now
+// lives behind a replica resource, so it is revalidated through that resource's
+// scoped sync query instead of a global SWR key.
vi.mock('@/libs/swr', () => ({ mutate: (...args: unknown[]) => mocks.globalMutate(...args) }));
+vi.mock('@/libs/replica', async (importOriginal) => {
+ const actual = await importOriginal<typeof ReplicaModule>();
+ return {
+ ...actual,
+ revalidateReplica: (...args: unknown[]) => mocks.revalidateReplica(...args),
+ };
+});
vi.mock('@/store/agent', () => ({
getAgentStoreState: () => ({ internal_refreshAgentConfig: mocks.refreshAgentConfig }),
}));
@@ -31,14 +41,16 @@ describe('refreshCachesAfterOwnershipChange', () => {
expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-1');
expect(mocks.globalMutate).not.toHaveBeenCalled();
+ expect(mocks.revalidateReplica).not.toHaveBeenCalled();
expect(mocks.refreshAgentList).toHaveBeenCalled();
});
- it('revalidates the group detail cache via the global mutator', async () => {
+ it('revalidates the group detail replica for the handed-over group', async () => {
await refreshCachesAfterOwnershipChange('agentGroup', 'group-1');
- expect(mocks.globalMutate).toHaveBeenCalledTimes(1);
- expect(mocks.globalMutate).toHaveBeenCalledWith(groupKeys.detail('group-1'));
+ expect(mocks.revalidateReplica).toHaveBeenCalledTimes(1);
+ expect(mocks.revalidateReplica.mock.calls[0][1]).toBe('group-1');
+ expect(mocks.revalidateReplica.mock.calls[0][0]?.name).toBe('agentGroupDetail');
expect(mocks.refreshAgentList).toHaveBeenCalled();
});
});
diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts
index 9c90563e2d7..cc847d32099 100644
--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts
+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts
@@ -1,6 +1,6 @@
-import { mutate } from '@/libs/swr';
-import { groupKeys } from '@/libs/swr/keys';
+import { revalidateReplica } from '@/libs/replica';
import { getAgentStoreState } from '@/store/agent';
+import { agentGroupDetailResource } from '@/store/agentGroup/projection';
import { useHomeStore } from '@/store/home';
/**
@@ -10,9 +10,10 @@ import { useHomeStore } from '@/store/home';
* config/detail cache refreshes too, or it keeps rendering the previous owner
* and owner-gated controls until a focus revalidation.
*
- * Deliberately uses the GLOBAL SWR mutator: these caches live under other SWR
- * keys, which a hook-bound `mutate` cannot reach — it would instead REPLACE
- * its own cache's data with the key array.
+ * The agent and group caches now live behind their stores' replica resources,
+ * so they are revalidated through `revalidateReplica` rather than the global
+ * SWR mutator — the replica sync query key is derived from the resource
+ * (name + version + scope), not from the old `group:*` / `agent:*` keys.
*/
export const refreshCachesAfterOwnershipChange = async (
resourceType: string,
@@ -21,7 +22,7 @@ export const refreshCachesAfterOwnershipChange = async (
await Promise.all([
resourceType === 'agent'
? getAgentStoreState().internal_refreshAgentConfig(resourceId)
- : mutate(groupKeys.detail(resourceId)),
+ : revalidateReplica(agentGroupDetailResource, resourceId),
useHomeStore.getState().refreshAgentList(),
]);
};
diff --git a/src/hooks/useInitGroupConfig.ts b/src/hooks/useInitGroupConfig.ts
index 988f08cbc34..79cf900ac88 100644
--- a/src/hooks/useInitGroupConfig.ts
+++ b/src/hooks/useInitGroupConfig.ts
@@ -1,25 +1,29 @@
import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
export const useInitGroupConfig = () => {
- const [useFetchGroupDetail, activeGroupId] = useAgentGroupStore((s) => [
+ const [useFetchGroupDetail, activeGroupId, group] = useAgentGroupStore((s) => [
s.useFetchGroupDetail,
s.activeGroupId,
+ s.activeGroupId ? agentGroupSelectors.getGroupById(s.activeGroupId)(s) : undefined,
]);
const isLogin = useUserStore(authSelectors.isLogin);
// Only fetch group detail if we have a valid group ID and user is logged in
const shouldFetch = Boolean(isLogin && activeGroupId);
- const { isValidating, data, ...rest } = useFetchGroupDetail(shouldFetch, activeGroupId || '');
+ // Fetch orchestration only — the group itself is read from `groupMap`.
+ const { error, isHydrated, isValidating } = useFetchGroupDetail(shouldFetch, activeGroupId || '');
return {
- ...rest,
- data,
- error: rest.error || (!shouldFetch ? undefined : rest.error),
- isLoading: (rest.isLoading && isLogin) || !shouldFetch,
+ data: group,
+ error: shouldFetch ? error : undefined,
+ // Nothing painted yet (neither the persisted row nor the network): the
+ // surface still has to render its skeleton.
+ isLoading: shouldFetch ? !group && !isHydrated : true,
// isRevalidating: has cached data, updating in background
- isRevalidating: isValidating && !!data,
+ isRevalidating: isValidating && !!group,
};
};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 11ada9b726f..594947a057a 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -232,8 +232,6 @@ export const agentBuilderKeys = {
// ---- group --------------------------------------------------------------
export const groupKeys = {
- detail: def('group:detail', (groupId: string) => ['group:detail', groupId]),
- list: def('group:list', (isLogin: boolean) => ['group:list', isLogin]),
/** Agent picker for the "add member" modal. */
queryAgents: def('group:queryAgents', () => ['group:queryAgents']),
/** Agent picker for the "create group" modal. */
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index d849788e037..707b09c826d 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -483,7 +483,6 @@ export const CACHE_TIERS = {
'message:', // chat messages (conversation + legacy stores)
'topic:', // topic lists / agent view / search
'agent:', // sidebar agent list + agent documents
- 'group:detail', // group detail (group list stays in localStorage)
'task:', // task lists + detail
'document:', // editor document content
'page:', // page detail / list / meta
@@ -498,7 +497,6 @@ export const CACHE_TIERS = {
'fetchRecentTopics',
'fetchRecentResources',
'fetchRecentPages',
- 'group:list',
'agentBuilder:suggestions', // builder opening-suggestion chips (skip LLM regen on revisit)
'taskTemplate:', // home task-template recommendations
'modelConfig:', // small remote model config shells used by home starter chips
diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.ts
index 39ea88e4484..7349a81ce49 100644
--- a/src/libs/swr/useClientDataSWRWithSync.ts
+++ b/src/libs/swr/useClientDataSWRWithSync.ts
@@ -38,12 +38,12 @@ interface UseClientDataSWRWithSyncOptions<T> extends SWRConfiguration<T> {
* @example
* ```ts
* useClientDataSWRWithSync(
- * isLogin ? groupKeys.list(scope) : null,
- * () => groupService.getGroups(),
+ * isLogin ? sessionKeys.list(scope) : null,
+ * () => sessionService.getGroupedSessions(),
* {
* onData: (data) => {
* // Auto sync to store, whether cached or fresh data
- * set({ groups: data, isInit: true });
+ * set({ sessions: data.sessions, isInit: true });
* },
* skipSync: state.isInit, // Optional: skip after initialized
* }
diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.ts
index 9da8f2ed225..45b4b780425 100644
--- a/src/store/agentGroup/action.ts
+++ b/src/store/agentGroup/action.ts
@@ -1,11 +1,17 @@
import { type AgentGroupDetail } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
-import { produce } from 'immer';
import { type StateCreator } from 'zustand/vanilla';
import { type ChatGroupItem } from '@/database/schemas/chatGroup';
-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
-import { groupKeys } from '@/libs/swr/keys';
+import {
+ cacheScope,
+ createReplicaSlice,
+ linkReplicaEntity,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
import { chatGroupService } from '@/services/chatGroup';
import { getAgentStoreState } from '@/store/agent';
import { type ChatGroupStore } from '@/store/agentGroup/store';
@@ -15,15 +21,23 @@ import { flattenActions } from '@/store/utils/flattenActions';
import { type ResetableStore } from '@/store/utils/resetableStore';
import { setNamespace } from '@/utils/storeDebug';
-import { type ChatGroupState, initialChatGroupState } from './initialState';
-import { type ChatGroupDispatchPayloads, type ChatGroupReducer } from './reducers';
-import { chatGroupReducers } from './reducers';
+import { initialChatGroupState } from './initialState';
+import {
+ AGENT_GROUP_LIST_KEY,
+ agentGroupDetailEntity,
+ agentGroupDetailResource,
+ agentGroupListResource,
+ agentGroupsEntity,
+} from './projection';
import { ChatGroupCurdAction } from './slices/curd';
import { ChatGroupLifecycleAction } from './slices/lifecycle';
import { ChatGroupMemberAction } from './slices/member';
const n = setNamespace('chatGroup');
+/** The group list is one entry per scope, so every sync shares these params. */
+const LIST_PARAMS = {} as Record<string, never>;
+
/**
* Convert ChatGroupItem to AgentGroupDetail by adding empty agents array if not present
*/
@@ -33,39 +47,190 @@ const toAgentGroupDetail = (group: ChatGroupItem): AgentGroupDetail =>
agents: [],
}) as AgentGroupDetail;
+/**
+ * Where a seed row comes from. A `list` row is the server's group list row; a
+ * `session` row is synthesized from a session and only its real fields count.
+ */
+export type GroupSeedSource = 'list' | 'session';
+
+/**
+ * The fields a session-derived group row actually carries. The rest of that row
+ * is placeholders (`workspaceId: null`, `visibility: 'public'`, `userId: ''`, …)
+ * that must never overwrite a real detail — e.g. turn a workspace group personal.
+ */
+const SESSION_GROUP_FIELDS = [
+ 'createdAt',
+ 'description',
+ 'groupId',
+ 'pinned',
+ 'title',
+ 'updatedAt',
+] as const satisfies readonly (keyof ChatGroupItem)[];
+
+const pickSessionFields = (group: ChatGroupItem): Partial<ChatGroupItem> => {
+ const picked: Partial<ChatGroupItem> = {};
+ for (const field of SESSION_GROUP_FIELDS) {
+ if (group[field] !== undefined) (picked as Record<string, unknown>)[field] = group[field];
+ }
+ return picked;
+};
+
+/**
+ * Fold a list row into a group detail: the row's metadata (title, avatar, …)
+ * wins, while a loaded roster (`agents`) and an authoritative `config` are kept.
+ *
+ * Every list seed goes through this merge, and the detail replica replays it
+ * when the persisted detail hydrates over the seed — so a fresher list row's
+ * metadata is not regressed to the persisted detail's, and the persisted roster
+ * and config are not dropped for the row's empty ones.
+ */
+const mergeListRow = (
+ existing: AgentGroupDetail | undefined,
+ group: ChatGroupItem,
+ source: GroupSeedSource = 'list',
+): AgentGroupDetail =>
+ existing
+ ? ({
+ ...existing,
+ ...(source === 'session' ? pickSessionFields(group) : group),
+ agents: existing.agents,
+ config: existing.config || group.config,
+ } as AgentGroupDetail)
+ : toAgentGroupDetail(group);
+
+/**
+ * The group list keeps its long-standing flat `groups` field as the replica
+ * view, so every selector keeps reading what it did. The init flag gates it:
+ * before the first hydrate/replace the view must read `undefined`, otherwise
+ * the empty default would block hydration from storage.
+ */
+const groupsLens: ReplicaLens<ChatGroupStore, ChatGroupItem[]> = {
+ clear: () => ({ groups: [], groupsInit: false }),
+ get: (state) => (state.groupsInit ? state.groups : undefined),
+ keys: (state) => (state.groupsInit ? [AGENT_GROUP_LIST_KEY] : []),
+ set: (_state, _key, data) =>
+ data === undefined ? { groups: [], groupsInit: false } : { groups: data, groupsInit: true },
+};
+
+/** `groupMap` is a plain `Record<groupId, detail>`, so the stock record lens fits. */
+const groupDetailLens = recordLens<ChatGroupStore, AgentGroupDetail>('groupMap');
+
type Setter = StoreSetter<ChatGroupStore>;
+
class ChatGroupInternalAction implements ResetableStore {
- readonly #get: () => ChatGroupState;
+ readonly #get: () => ChatGroupStore;
readonly #set: Setter;
-
- constructor(set: Setter, get: () => ChatGroupState, _api?: unknown) {
+ /** One group's detail behind `groupMap[groupId]` — the roster and config. */
+ readonly #groupDetail;
+ /** The group list behind `groups` (one entry per scope). */
+ readonly #groupList;
+ /** One group lives in the list row and in `groupMap`: write to both at once. */
+ readonly #groupRows;
+ /**
+ * Ids the last authoritative list `replace` dropped. A group can live in the
+ * persisted list without ever being seeded into `groupMap` (a reload hydrates
+ * the list only), so the detail reconcile prunes these as well — see
+ * {@link #reconcileGroupMap}.
+ */
+ #droppedGroupIds: string[] = [];
+ /** Bumped by every `loadGroups`; a late reconcile only runs for the latest. */
+ #listLoadSeq = 0;
+
+ constructor(set: Setter, get: () => ChatGroupStore, _api?: unknown) {
// keep signature aligned with StateCreator params: (set, get, api)
void _api;
this.#set = set;
this.#get = get;
+ this.#groupList = createReplicaSlice(agentGroupListResource, {
+ actionPrefix: 'agentGroupList',
+ entity: agentGroupsEntity,
+ fetcher: () => chatGroupService.getGroups(),
+ get,
+ // The list is the authoritative parent of every detail, so remember the
+ // rows a `replace` drops: a group that only ever hydrated from the
+ // persisted list never reached `groupMap`, and its detail must still be
+ // pruned (see `#reconcileGroupMap`). Returning `incoming` keeps the
+ // default "the response is the value".
+ merge: (incoming, confirmed) => {
+ const nextIds = new Set(incoming.map((group) => group.id));
+ this.#droppedGroupIds = (confirmed ?? [])
+ .map((group) => group.id)
+ .filter((id) => !nextIds.has(id));
+ return incoming;
+ },
+ set,
+ stateKey: 'agentGroupListReplica',
+ view: groupsLens,
+ });
+ this.#groupDetail = createReplicaSlice(agentGroupDetailResource, {
+ actionPrefix: 'agentGroupDetail',
+ entity: agentGroupDetailEntity,
+ fetcher: async ({ groupId }) => {
+ const scope = this.#captureScope();
+ const groupDetail = await chatGroupService.getGroupDetail(groupId);
+ // `null` is a terminal "gone / no access" answer. Record it here, per
+ // key, rather than only in the hook's success callback: that callback
+ // is skipped once the hook moved to another group (or the driver drops
+ // it), and the stale detail would then be kept and replayed offline.
+ if (!groupDetail) this.#settleGroupGone(groupId, scope);
+ return groupDetail;
+ },
+ get,
+ // The endpoint returns the complete, authoritative detail. `null` (gone /
+ // no access) is settled by the fetcher (see `#settleGroupGone`), not a
+ // value to paint. An unchanged detail keeps its reference so the group
+ // pages do not re-render.
+ merge: (incoming, confirmed) =>
+ !incoming || isEqual(incoming, confirmed) ? undefined : incoming,
+ set,
+ stateKey: 'agentGroupDetailReplica',
+ view: groupDetailLens,
+ });
+ this.#groupRows = linkReplicaEntity<ChatGroupItem>([this.#groupList, this.#groupDetail]);
}
reset: ResetableStore['reset'] = () => {
this.#set(initialChatGroupState, false, n('reset'));
};
- internal_dispatchChatGroup = <T extends keyof ChatGroupDispatchPayloads>(payload: {
- payload: ChatGroupDispatchPayloads[T];
- type: T;
- }) => {
- this.#set(
- produce((draft: ChatGroupState) => {
- const reducer = chatGroupReducers[payload.type] as ChatGroupReducer | undefined;
- if (reducer) return reducer(draft, payload);
- }),
- false,
- payload,
- );
+ /**
+ * The cache scope (`${userId}:${workspaceId}`) a request starts under. The
+ * full scope is what partitions the persisted replica rows, so it — not just
+ * the workspace id — is what an imperative response must be validated
+ * against: two users in personal mode share a `null` workspace, and a
+ * response started for one must never land in the other's partition.
+ */
+ #captureScope = (): string => cacheScope.get();
+
+ /** Whether the identity a request started under is still the active one. */
+ #isStillInScope = (scope: string): boolean => cacheScope.get() === scope;
+
+ #removeStaleGroup = (groupId: string) => {
+ const loaded = this.#get().groupMap[groupId] !== undefined;
+ this.#groupRows.remove(groupId);
+ // The entity removal only dispatches for a loaded detail. Remove the key
+ // itself otherwise, so a detail request already in flight for it is
+ // invalidated too (and cannot recreate the group once it answers).
+ if (!loaded) this.#groupDetail.remove(groupId);
};
- private removeStaleGroup = (groupId: string) => {
- this.internal_dispatchChatGroup({ payload: groupId, type: 'deleteGroup' });
+ /**
+ * A detail request answered "gone / no access" for `groupId` under `scope`.
+ * In the active scope the group leaves every view (and storage) and settles
+ * as not found. A scope left behind keeps its view untouched — it is not on
+ * screen — but its persisted detail and its persisted list row both drop the
+ * group, so switching back cannot hydrate it into the sidebar (indefinitely,
+ * offline, until `getGroups()` answers).
+ */
+ #settleGroupGone = (groupId: string, scope: string) => {
+ if (!this.#isStillInScope(scope)) {
+ this.#groupDetail.remove(groupId, scope);
+ this.#groupRows.remove(groupId, { scope });
+ return;
+ }
+ this.#removeStaleGroup(groupId);
+ this.#markGroupNotFound(groupId);
};
// A successful fetch that resolves to nothing means the group doesn't exist
@@ -95,28 +260,29 @@ class ChatGroupInternalAction implements ResetableStore {
);
};
- internal_fetchGroupDetail = async (groupId: string) => {
- const groupDetail = await chatGroupService.getGroupDetail(groupId);
- if (!groupDetail) {
- this.removeStaleGroup(groupId);
- this.#markGroupNotFound(groupId);
- return;
- }
- this.#clearGroupNotFound(groupId);
-
- // Update groupMap with full group detail including supervisorAgentId and agents
- this.internal_dispatchChatGroup({
- payload: { id: groupDetail.id, value: groupDetail },
- type: 'updateGroup',
- });
-
- // Sync group agents to agentStore for builtin agent resolution
+ /**
+ * Push a fetched group's roster into the agent store, so builtin agent
+ * resolution (e.g. the supervisor slug) and the model switcher find it, and
+ * adopt the supervisor as the active agent for correct model resolution.
+ */
+ #syncGroupAgents = (groupDetail: AgentGroupDetail, { onlyIfNewer = false } = {}) => {
const agentStore = getAgentStoreState();
for (const agent of groupDetail.agents) {
+ // A background sync must not overwrite a newer local agent, but an
+ // explicit refresh (right after a write) always takes the server value.
+ const current = agentStore.agentMap[agent.id];
+ if (
+ onlyIfNewer &&
+ current &&
+ !(new Date(agent.updatedAt) > new Date(current.updatedAt || 0))
+ ) {
+ continue;
+ }
+
+ // AgentGroupMember extends AgentItem which shares fields with LobeAgentConfig
agentStore.internal_dispatchAgentMap(agent.id, agent as any);
}
- // Set activeAgentId to supervisor for correct model resolution
if (groupDetail.supervisorAgentId) {
agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
useChatStore.setState(
@@ -127,59 +293,203 @@ class ChatGroupInternalAction implements ResetableStore {
}
};
- internal_updateGroupMaps = (groups: ChatGroupItem[]) => {
- // Build a candidate map from incoming groups
- const incomingMap = groups.reduce(
- (map, group) => {
- map[group.id] = group;
- return map;
- },
- {} as Record<string, ChatGroupItem>,
- );
+ /**
+ * The side effects of a group detail that resolved successfully, whether it
+ * came from the network or from the persisted replica: adopt the roster and
+ * supervisor, and settle the not-found state (`null` is the settled "gone /
+ * no access" state). Running it off the hydrated value too is what lets a
+ * cold start with a slow / failed / offline network paint a usable group page
+ * instead of an empty roster behind the 404 guard.
+ */
+ #applyGroupDetail = (groupId: string, groupDetail: AgentGroupDetail | null | undefined) => {
+ if (!groupDetail) {
+ this.#removeStaleGroup(groupId);
+ this.#markGroupNotFound(groupId);
+ return;
+ }
+ this.#clearGroupNotFound(groupId);
+ this.#syncGroupAgents(groupDetail, { onlyIfNewer: true });
+ };
- // Merge with existing map, preserving existing config and agents if present
- const mergedMap = produce(this.#get().groupMap, (draft) => {
- for (const id of Object.keys(incomingMap)) {
- const incoming = incomingMap[id];
- const existing = draft[id];
- if (existing) {
- draft[id] = {
- ...existing,
- ...incoming,
-
- // Preserve existing agents data
- agents: existing.agents,
-
- // Keep existing config (authoritative) if present; do not overwrite
- config: existing.config || incoming.config,
- } as AgentGroupDetail;
- } else {
- draft[id] = toAgentGroupDetail(incoming);
- }
- }
+ internal_fetchGroupDetail = async (groupId: string) => {
+ const scope = this.#captureScope();
+ // The removal generation the request starts under: a group pruned or
+ // removed while the request is in flight must not be recreated by it (the
+ // same guard `useSync` applies to its own responses).
+ const removal = this.#groupDetail.removalGeneration(scope, groupId);
+ const groupDetail = await chatGroupService.getGroupDetail(groupId);
+ // A terminal "gone / no access" is settled in the scope the request started
+ // under — even after a switch, that scope's persisted detail is purged so
+ // switching back cannot hydrate the deleted / revoked group.
+ if (!groupDetail) {
+ this.#settleGroupGone(groupId, scope);
+ return;
+ }
+ // The request may resolve after a logout / account switch; its response
+ // belongs to the scope it started under, not the one active now.
+ if (!this.#isStillInScope(scope)) return;
+ // Removed while in flight: the response is older than the removal.
+ if (this.#groupDetail.removalGeneration(scope, groupId) !== removal) return;
+ this.#clearGroupNotFound(groupId);
+
+ // Confirmed server detail: it paints the group page on the next visit too.
+ // The captured scope makes the write itself admit only its own identity.
+ this.#groupDetail.replace({ groupId }, groupDetail, scope);
+ this.#syncGroupAgents(groupDetail);
+ };
+
+ /**
+ * Add a freshly created group to every view that holds group rows. The detail
+ * entry is only a `seed` (the create response carries no roster): it keeps the
+ * new group resolvable until {@link internal_fetchGroupDetail} confirms it.
+ */
+ internal_addGroup = (group: ChatGroupItem) => {
+ this.#groupList.update(AGENT_GROUP_LIST_KEY, (items) => [...(items ?? []), group], {
+ persist: false,
+ });
+ this.#groupDetail.update(group.id, (existing) => mergeListRow(existing, group), {
+ persist: false,
+ seedTag: 'list',
+ source: 'seed',
});
+ };
- this.#set(
- {
- groupMap: mergedMap,
- groupsInit: true,
- },
- false,
- n('internal_updateGroupMaps/chatGroup'),
+ /** Patch one group row in every view that holds it (list row + detail map). */
+ internal_updateGroupRow = (id: string, value: Partial<ChatGroupItem>) => {
+ this.#groupRows.update(id, (group) => ({ ...group, ...value }));
+ };
+
+ /**
+ * Merge a group list payload into `groupMap`. A group that is already loaded
+ * keeps its roster (`agents`) and its authoritative `config`; a group that is
+ * only known from the list gets an empty roster until its detail fetch lands.
+ *
+ * The write is a `seed`, not authoritative detail: it is in-memory only, and
+ * the detail replica may still hydrate the persisted full detail over it (see
+ * `packages/replica/src/core/reducer.ts`). A plain local entry would have
+ * blocked that hydrate, stranding the group page on default config and no
+ * members whenever the network was slow, failed or offline.
+ *
+ * This only merges; it never prunes. It is also called with a partial set
+ * (the group sessions the session list carries), so a caller that holds the
+ * complete group list prunes through {@link #reconcileGroupMap} instead.
+ *
+ * The seeds are applied as ONE batched replica write: doing it per row would
+ * clone `groupMap` and notify subscribers once per group.
+ */
+ internal_updateGroupMaps = (groups: ChatGroupItem[], source: GroupSeedSource = 'list') => {
+ this.#groupDetail.updateMany(
+ groups.map((group) => ({
+ apply: (existing) => mergeListRow(existing, group, source),
+ key: group.id,
+ })),
+ // One tag per source: a refresh supersedes that source's earlier seed.
+ { persist: false, seedTag: source, source: 'seed' },
);
};
+ /**
+ * Fold the complete, authoritative group list into `groupMap`: every detail
+ * the list no longer carries (the group was deleted, or the caller lost
+ * access) is pruned from memory and from the persisted replica, then the
+ * returned rows are merged in. Without the prune a removed group keeps
+ * resolving its metadata and permissions (e.g. the supervisor fallback) even
+ * though `getGroups()` stopped listing it.
+ *
+ * The candidates are not just `groupMap`: after a reload the persisted list
+ * hydrates groups without seeding `groupMap`, so a group the authoritative
+ * response drops would otherwise keep its persisted detail and paint on a
+ * later slow / offline visit. `#droppedGroupIds` carries those ids from the
+ * list replace. A stale candidate is harmless — only ids *absent from the
+ * authoritative list* are ever removed.
+ */
+ #reconcileGroupMap = (groups: ChatGroupItem[]) => {
+ const listedIds = new Set(groups.map((group) => group.id));
+ const candidates = new Set([...Object.keys(this.#get().groupMap), ...this.#droppedGroupIds]);
+ this.#droppedGroupIds = [];
+
+ for (const groupId of candidates) {
+ if (!listedIds.has(groupId)) this.#removeStaleGroup(groupId);
+ }
+ this.internal_updateGroupMaps(groups);
+ };
+
+ /**
+ * Refresh the group list. The persisted projection paints as soon as it is
+ * read, while the network confirms it in parallel, instead of blanking the
+ * list first; the rows then seed `groupMap`.
+ *
+ * The request is started before the hydration read is awaited: the two are
+ * independent, and a caller such as `sendAsGroup` awaits `loadGroups()` before
+ * it navigates, so serializing them only delays both. Hydration still paints
+ * the persisted list as soon as it resolves; a bounded wait for it before the
+ * replace keeps that paint ahead of the network's without letting a stalled
+ * storage read block the response.
+ *
+ * The scope is captured before the first await and threaded through the
+ * writes, so a response that resolves after an identity switch is dropped
+ * instead of being written (and persisted) into the next scope's partition.
+ */
loadGroups = async () => {
+ const scope = this.#captureScope();
+ // Drop the previous identity's list before anything else. After a workspace
+ // switch the store stays mounted with `groupsInit` still true, so without
+ // this the old workspace's groups linger through a slow / failed request and
+ // the new scope's persisted list is never read — which in turn leaves the
+ // detail reconcile blind to the persisted-only ids a response omits.
+ this.#groupList.ensureScope(scope);
+ const load = ++this.#listLoadSeq;
+ const hydration = this.#get().groupsInit
+ ? undefined
+ : this.#groupList.hydrate(LIST_PARAMS, scope).finally(() => (hydrated = true));
+ let hydrated = !hydration;
+ // The persisted list ids, read alongside the hydrate. If the hydrate misses
+ // the bound below, the list `replace` cannot see which ids the response
+ // dropped (see `#droppedGroupIds`), so those are pruned from this snapshot.
+ const persistedIds = hydration ? this.#readPersistedGroupIds(scope) : undefined;
const groups = await chatGroupService.getGroups();
- this.internal_dispatchChatGroup({ payload: groups, type: 'loadGroups' });
+ // Let a hydrate that is about to land paint first, but never let a stalled
+ // storage read hold back an authoritative response that already arrived:
+ // creation flows await `loadGroups()` before they navigate. A hydrate that
+ // lands after the replace is a no-op (it only fills an empty slot).
+ if (hydration) await settleWithin(hydration, PRE_PAINT_HYDRATE_TIMEOUT);
+ if (!this.#isStillInScope(scope)) return;
+
+ this.#groupList.replace(LIST_PARAMS, groups, scope);
+ this.#reconcileGroupMap(groups);
+
+ if (!hydrated && persistedIds) {
+ const listedIds = new Set(groups.map((group) => group.id));
+ void persistedIds.then((ids) => {
+ // A newer list load (or an identity switch) owns the reconcile now.
+ if (load !== this.#listLoadSeq || !this.#isStillInScope(scope)) return;
+ const current = new Set(this.#get().groups.map((group) => group.id));
+ for (const id of ids) {
+ if (!listedIds.has(id) && !current.has(id)) this.#removeStaleGroup(id);
+ }
+ });
+ }
+ };
+
+ /** Ids of the persisted group list in `scope` (empty when unreadable). */
+ #readPersistedGroupIds = async (scope: string): Promise<string[]> => {
+ try {
+ const row = await agentGroupListResource.storage?.get({
+ queryKey: agentGroupListResource.storageKey(LIST_PARAMS),
+ scope,
+ });
+ return (row?.data ?? []).map((group) => group.id);
+ } catch {
+ return [];
+ }
};
refreshGroupDetail = async (groupId: string) => {
- await mutate(groupKeys.detail(groupId));
+ await this.#groupDetail.revalidate(groupId);
};
refreshGroups = async () => {
- await mutate(groupKeys.list(true));
+ await this.#groupList.revalidate(AGENT_GROUP_LIST_KEY);
};
toggleGroupSetting = (open: boolean) => {
@@ -190,113 +500,28 @@ class ChatGroupInternalAction implements ResetableStore {
this.#set({ activeThreadAgentId: agentId }, false, 'toggleThread');
};
- useFetchGroupDetail = (enabled: boolean, groupId: string) =>
- useClientDataSWRWithSync<AgentGroupDetail | null>(
- enabled && groupId ? groupKeys.detail(groupId) : null,
- async () => {
- const groupDetail = await chatGroupService.getGroupDetail(groupId);
- // Resolve to null instead of throwing: "gone / no access" is a settled
- // terminal state (rendered as a 404 card), not a retryable error.
- if (!groupDetail) {
- this.removeStaleGroup(groupId);
- return null;
- }
- return groupDetail;
- },
- {
- onData: (groupDetail) => {
- if (!groupDetail) {
- this.#markGroupNotFound(groupId);
- return;
- }
- this.#clearGroupNotFound(groupId);
-
- // Update groupMap with detailed group info including agents
- const currentGroup = this.#get().groupMap[groupDetail.id];
- if (isEqual(currentGroup, groupDetail)) return;
-
- const nextGroupMap = {
- ...this.#get().groupMap,
- [groupDetail.id]: groupDetail,
- };
-
- this.#set(
- {
- groupMap: nextGroupMap,
- },
- false,
- n('useFetchGroupDetail/onData', { groupId: groupDetail.id }),
- );
-
- // Sync group agents to agentStore for builtin agent resolution (e.g., supervisor slug)
- // Use smart merge: only overwrite if server data is newer to prevent race conditions
- const agentStore = getAgentStoreState();
- for (const agent of groupDetail.agents) {
- const currentAgentInStore = agentStore.agentMap[agent.id];
-
- // Only overwrite if:
- // 1. Agent doesn't exist in store
- // 2. Server data is newer than store data (based on updatedAt)
- if (
- !currentAgentInStore ||
- new Date(agent.updatedAt) > new Date(currentAgentInStore.updatedAt || 0)
- ) {
- // AgentGroupMember extends AgentItem which shares fields with LobeAgentConfig
- agentStore.internal_dispatchAgentMap(agent.id, agent as any);
- }
- }
-
- // Set activeAgentId to supervisor for correct model resolution in sendMessage
- if (groupDetail.supervisorAgentId) {
- agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
- useChatStore.setState(
- { activeAgentId: groupDetail.supervisorAgentId },
- false,
- 'syncActiveAgentIdFromAgentGroup',
- );
- }
- },
- },
- );
+ /**
+ * Fetch orchestration only; read the group through `groupMap` /
+ * `agentGroupSelectors`. A response of `null` is the settled "gone / no
+ * access" state. The detail also hydrates from the persisted replica with no
+ * response, so the same side effects run off the hydrated value as well.
+ */
+ useFetchGroupDetail = (enabled: boolean, groupId: string): ReplicaSyncResult =>
+ this.#groupDetail.useSync(groupId ? { groupId } : null, {
+ enabled,
+ onHydrated: (groupDetail) => this.#applyGroupDetail(groupId, groupDetail),
+ onSuccess: (groupDetail) => this.#applyGroupDetail(groupId, groupDetail),
+ });
- // SWR Hooks for data fetching
- // This is not used for now, as we are combining group in the session lambda's response
- useFetchGroups = (enabled: boolean, isLogin: boolean) =>
- useClientDataSWRWithSync<ChatGroupItem[]>(
- enabled ? groupKeys.list(isLogin) : null,
- async () => chatGroupService.getGroups(),
- {
- fallbackData: [],
- onData: (groups) => {
- // Update both groups list and groupMap
- const currentMap = this.#get().groupMap;
- const nextGroupMap = groups.reduce(
- (map, group) => {
- // Preserve existing agents data if available
- const existing = currentMap[group.id];
- map[group.id] = existing
- ? ({ ...existing, ...group } as AgentGroupDetail)
- : toAgentGroupDetail(group);
- return map;
- },
- {} as Record<string, AgentGroupDetail>,
- );
-
- if (this.#get().groupsInit && isEqual(currentMap, nextGroupMap)) {
- return;
- }
-
- this.#set(
- {
- groupMap: nextGroupMap,
- groupsInit: true,
- },
- false,
- n('useFetchGroups/onData'),
- );
- },
- },
- );
+ /**
+ * Fetch orchestration only; the authoritative list reconciles `groupMap`
+ * through its `onSuccess`.
+ */
+ useFetchGroups = (enabled: boolean, isLogin: boolean): ReplicaSyncResult =>
+ this.#groupList.useSync(LIST_PARAMS, {
+ enabled: enabled && isLogin,
+ onSuccess: (groups) => this.#reconcileGroupMap(groups),
+ });
}
type PublicActions<T> = { [K in keyof T]: T[K] };
diff --git a/src/store/agentGroup/index.ts b/src/store/agentGroup/index.ts
index 98b4c633cb9..e1fa735aa04 100644
--- a/src/store/agentGroup/index.ts
+++ b/src/store/agentGroup/index.ts
@@ -1,5 +1,4 @@
export * from './action';
export * from './initialState';
-export * from './reducers';
export * from './selectors';
export { getChatGroupStoreState, useAgentGroupStore } from './store';
diff --git a/src/store/agentGroup/initialState.ts b/src/store/agentGroup/initialState.ts
index f19e6f8ee1f..0fe40ae94e9 100644
--- a/src/store/agentGroup/initialState.ts
+++ b/src/store/agentGroup/initialState.ts
@@ -2,6 +2,7 @@ import { type AgentGroupDetail } from '@lobechat/types';
import { type ParsedQuery } from 'query-string';
import { type ChatGroupItem } from '@/database/schemas/chatGroup';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
export interface QueryRouter {
push: (url: string, options?: { query?: ParsedQuery; replace?: boolean }) => void;
@@ -10,6 +11,11 @@ export interface QueryRouter {
export interface ChatGroupState {
activeGroupId?: string;
activeThreadAgentId: string;
+ /** Replica bookkeeping for `groupMap`. */
+ agentGroupDetailReplica: ReplicaState<AgentGroupDetail>;
+ /** Replica bookkeeping for `groups`. */
+ agentGroupListReplica: ReplicaState<ChatGroupItem[]>;
+ /** Detailed groups by id. Replica view of `agentGroupDetailReplica`. */
groupMap: Record<string, AgentGroupDetail>;
/**
* Groups whose detail fetch succeeded but resolved to nothing — the group
@@ -19,7 +25,13 @@ export interface ChatGroupState {
* a later fetch succeeds.
*/
groupNotFoundMap: Record<string, boolean>;
+ /** Group metadata rows of the active scope. Replica view of `agentGroupListReplica`. */
groups: ChatGroupItem[];
+ /**
+ * Whether the group list has been filled (from storage or the server). Gates
+ * the list replica lens: an un-loaded list must read `undefined`, otherwise
+ * hydration would treat the empty default as a real value.
+ */
groupsInit: boolean;
router?: QueryRouter;
showGroupSetting: boolean;
@@ -35,6 +47,8 @@ export interface ChatGroupState {
export const initialChatGroupState: ChatGroupState = {
activeThreadAgentId: '',
+ agentGroupDetailReplica: createReplicaState(),
+ agentGroupListReplica: createReplicaState(),
groupMap: {},
groupNotFoundMap: {},
groups: [],
diff --git a/src/store/agentGroup/projection.ts b/src/store/agentGroup/projection.ts
new file mode 100644
index 00000000000..08f52ebfc61
--- /dev/null
+++ b/src/store/agentGroup/projection.ts
@@ -0,0 +1,66 @@
+import type { AgentGroupDetail } from '@lobechat/types';
+
+import type { ChatGroupItem } from '@/database/schemas/chatGroup';
+import {
+ arrayEntity,
+ defineReplica,
+ type ReplicaEntityAdapter,
+ singleEntity,
+} from '@/libs/replica';
+
+/** The group list is one entry per scope, so every sync shares these params. */
+export const AGENT_GROUP_LIST_KEY = 'all';
+
+export interface AgentGroupDetailParams {
+ groupId: string;
+}
+
+/**
+ * Group metadata rows of the active scope (`groups`), from `group.getGroups`.
+ * Seeds `groupMap` with the groups whose detail has not been fetched yet, so
+ * `getGroupById` / `getGroupMeta` can resolve a group the viewer has access to
+ * before its detail page mounts.
+ */
+export const agentGroupListResource = defineReplica<Record<string, never>, ChatGroupItem[]>({
+ key: () => AGENT_GROUP_LIST_KEY,
+ name: 'agentGroupList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One group's detail, keyed by group id (`groupMap[groupId]`): the roster, the
+ * config and the supervisor. The fetch resolves `null` when the group is gone
+ * or the viewer lost access — a settled 404, not a retryable error — which the
+ * sync hook turns into `groupNotFoundMap`.
+ */
+export const agentGroupDetailResource = defineReplica<
+ AgentGroupDetailParams,
+ AgentGroupDetail,
+ AgentGroupDetail | null
+>({
+ key: ({ groupId }) => groupId,
+ name: 'agentGroupDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A group is addressed by `id` in both the list row and the detail map. */
+export const agentGroupsEntity: ReplicaEntityAdapter<ChatGroupItem[], ChatGroupItem> =
+ arrayEntity<ChatGroupItem>((group) => group.id);
+
+/**
+ * The same group also lives in `groupMap[groupId]` as an `AgentGroupDetail`.
+ * A list row carries no roster, so spreading one onto a loaded detail keeps
+ * `agents` (and any other detail-only field) intact.
+ */
+export const agentGroupDetailEntity = singleEntity<AgentGroupDetail, ChatGroupItem>(
+ (group) => group.id,
+ {
+ // `AgentGroupDetail` is the slimmer shared type while the store rows are the
+ // database `ChatGroupItem` (which also carries the soft-delete columns), so
+ // the detail is handed to the entity mapper as the row shape it came from.
+ get: (detail) => detail as unknown as ChatGroupItem,
+ set: (detail, group) => ({ ...detail, ...group }),
+ },
+);
diff --git a/src/store/agentGroup/reducers.ts b/src/store/agentGroup/reducers.ts
deleted file mode 100644
index 9453e302199..00000000000
--- a/src/store/agentGroup/reducers.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { type AgentGroupDetail } from '@lobechat/types';
-import { produce } from 'immer';
-
-import { type ChatGroupItem } from '@/database/schemas/chatGroup';
-
-import { type ChatGroupState } from './initialState';
-
-/**
- * Convert ChatGroupItem to AgentGroupDetail by adding empty agents array
- */
-const toAgentGroupDetail = (group: ChatGroupItem): AgentGroupDetail =>
- ({
- ...group,
- agents: [],
- }) as AgentGroupDetail;
-
-export type ChatGroupReducer = (state: ChatGroupState, payload: any) => ChatGroupState;
-
-export const chatGroupReducers = {
- // Add a new group to the list
- addGroup: (state: ChatGroupState, { payload }: { payload: ChatGroupItem }) =>
- produce(state, (draft: ChatGroupState) => {
- draft.groups.push(payload);
- draft.groupMap[payload.id] = toAgentGroupDetail(payload);
- }),
-
- // Delete a group from the list
- deleteGroup: (state: ChatGroupState, { payload: id }: { payload: string }) =>
- produce(state, (draft: ChatGroupState) => {
- draft.groups = draft.groups.filter((group: ChatGroupItem) => group.id !== id);
- delete draft.groupMap[id];
- }),
-
- // Load groups into the state
- loadGroups: (state: ChatGroupState, { payload }: { payload: ChatGroupItem[] }) =>
- produce(state, (draft: ChatGroupState) => {
- draft.groups = payload;
- // Rebuild groupMap to maintain consistency, preserving existing agents data
- const currentMap = state.groupMap;
- draft.groupMap = payload.reduce(
- (map, group) => {
- const existing = currentMap[group.id];
- map[group.id] = existing
- ? ({ ...existing, ...group } as AgentGroupDetail)
- : toAgentGroupDetail(group);
- return map;
- },
- {} as Record<string, AgentGroupDetail>,
- );
- }),
-
- // Update a group in the map
- updateGroup: (
- state: ChatGroupState,
- { payload }: { payload: { id: string; value: Partial<ChatGroupItem> } },
- ) =>
- produce(state, (draft: ChatGroupState) => {
- if (draft.groupMap[payload.id]) {
- Object.assign(draft.groupMap[payload.id], payload.value);
- // Also update in groups array to maintain consistency
- const groupIndex = draft.groups.findIndex(
- (group: ChatGroupItem) => group.id === payload.id,
- );
- if (groupIndex !== -1) {
- Object.assign(draft.groups[groupIndex], payload.value);
- }
- }
- }),
-};
-
-export type ChatGroupDispatchPayloads = {
- addGroup: ChatGroupItem;
- deleteGroup: string;
- loadGroups: ChatGroupItem[];
- updateGroup: { id: string; value: Partial<ChatGroupItem> };
-};
diff --git a/src/store/agentGroup/replica.test.ts b/src/store/agentGroup/replica.test.ts
new file mode 100644
index 00000000000..f2e7daf9e28
--- /dev/null
+++ b/src/store/agentGroup/replica.test.ts
@@ -0,0 +1,1088 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The agent group store is two `@lobechat/replica` resources: the group list
+ * (`groups`) and the per-group detail (`groupMap`). The persisted projection
+ * paints while the network confirms it, a gone group is dropped from every view
+ * that holds it (and from storage), and one group row is patched everywhere it
+ * appears in a single fan-out.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ChatGroupItem } from '@/database/schemas/chatGroup';
+import { cacheScope, createReplicaState } from '@/libs/replica';
+import { chatGroupService } from '@/services/chatGroup';
+
+import { initialChatGroupState } from './initialState';
+import { agentGroupDetailResource, agentGroupListResource } from './projection';
+import { useAgentGroupStore } from './store';
+
+vi.mock('@/services/chatGroup', () => ({
+ chatGroupService: {
+ getGroupDetail: vi.fn(),
+ getGroups: vi.fn(),
+ updateGroup: vi.fn(),
+ },
+}));
+
+/** Shared agent-store probe, so the detail side effects can be asserted. */
+const agentStoreMock = vi.hoisted(() => ({
+ agentMap: {} as Record<string, any>,
+ internal_dispatchAgentMap: vi.fn(),
+ setActiveAgentId: vi.fn(),
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: vi.fn(() => agentStoreMock),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { setState: vi.fn() },
+}));
+
+const getGroupDetail = chatGroupService.getGroupDetail as unknown as ReturnType<typeof vi.fn>;
+const getGroups = chatGroupService.getGroups as unknown as ReturnType<typeof vi.fn>;
+
+const groupRow = (id: string, title = `Group ${id}`): ChatGroupItem =>
+ ({
+ accessedAt: new Date(),
+ avatar: null,
+ backgroundColor: null,
+ clientId: null,
+ config: null,
+ content: null,
+ createdAt: new Date(),
+ deletedAt: null,
+ description: null,
+ editorData: null,
+ groupId: null,
+ id,
+ isDeleted: null,
+ marketIdentifier: null,
+ pinned: false,
+ title,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ visibility: 'public',
+ workspaceId: null,
+ }) as ChatGroupItem;
+
+const groupDetail = (id: string, title = `Group ${id}`) =>
+ ({ ...groupRow(id, title), agents: [], supervisorAgentId: `${id}-supervisor` }) as any;
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const LIST_STORAGE_KEY = agentGroupListResource.storageKey({});
+const detailStorageKey = (groupId: string) => agentGroupDetailResource.storageKey({ groupId });
+
+describe('agentGroup store replica', () => {
+ const scopes = new Set<string>();
+
+ const createScope = (prefix = 'agent-group-user') => {
+ const scope = `${prefix}:${randomUUID()}:personal`;
+ scopes.add(scope);
+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ return scope;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ agentStoreMock.agentMap = {};
+ useAgentGroupStore.setState({ ...initialChatGroupState });
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((scope) => [
+ agentGroupListResource.storage!.remove({ queryKey: LIST_STORAGE_KEY, scope }),
+ agentGroupDetailResource.storage!.remove({ queryKey: detailStorageKey('g1'), scope }),
+ agentGroupDetailResource.storage!.remove({ queryKey: detailStorageKey('g2'), scope }),
+ ]),
+ );
+ cleanup();
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted group list before the network answers', async () => {
+ const scope = createScope();
+ await agentGroupListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [groupRow('cached', 'Cached group')], updatedAt: 1 },
+ );
+ getGroups.mockImplementation(pending);
+
+ void useAgentGroupStore.getState().loadGroups();
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['cached']),
+ );
+ expect(useAgentGroupStore.getState().groupsInit).toBe(true);
+ });
+
+ // The network request must not wait behind the hydration read: `sendAsGroup`
+ // awaits `loadGroups()` before it navigates, so serializing the two delays both.
+ it('starts the list request before the hydration read resolves', async () => {
+ const scope = createScope();
+ await agentGroupListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [groupRow('cached')], updatedAt: 1 },
+ );
+ getGroups.mockResolvedValue([groupRow('g1')]);
+
+ // Hold the hydration read open so the request's start can be observed.
+ const storage = agentGroupListResource.storage!;
+ const original = storage.get.bind(storage);
+ let releaseHydration!: () => void;
+ const gate = new Promise<void>((resolve) => (releaseHydration = resolve));
+ const getSpy = vi.spyOn(storage, 'get').mockImplementation(async (key: any) => {
+ await gate;
+ return original(key);
+ });
+
+ const inflight = useAgentGroupStore.getState().loadGroups();
+
+ // The request is already in flight while hydration is still pending.
+ await vi.waitFor(() => expect(getGroups).toHaveBeenCalled());
+ expect(useAgentGroupStore.getState().groupsInit).toBe(false);
+
+ releaseHydration();
+ await inflight;
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+ getSpy.mockRestore();
+ });
+
+ // A stalled IndexedDB read must not hold back an authoritative response that
+ // already arrived: creation flows await `loadGroups()` before navigating.
+ it('applies the list response even when the hydration read stalls', async () => {
+ createScope();
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ const storage = agentGroupListResource.storage!;
+ const getSpy = vi.spyOn(storage, 'get').mockImplementation(pending);
+
+ await useAgentGroupStore.getState().loadGroups();
+
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Group g1');
+ getSpy.mockRestore();
+ });
+
+ // The list hydrate misses the bound, so the `replace` cannot see which ids the
+ // response dropped. A persisted detail of a dropped group must still be pruned,
+ // or a later slow / offline visit paints the deleted group.
+ it('prunes a dropped group detail even when the list hydrate misses the bound', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1'), groupRow('g2')]);
+ getGroupDetail.mockImplementation(async (groupId: string) => groupDetail(groupId));
+
+ // An earlier visit persisted both the list and g2's detail.
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g2');
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope })
+ )?.data?.map((group) => group.id),
+ ).toEqual(['g1', 'g2']),
+ );
+ await vi.waitFor(async () =>
+ expect(
+ (await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }))
+ ?.data,
+ ).toBeDefined(),
+ );
+
+ // Reload: memory is gone, storage stays.
+ useAgentGroupStore.setState({ ...initialChatGroupState });
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ const storage = agentGroupListResource.storage!;
+ const realGet = storage.get.bind(storage);
+ const getSpy = vi.spyOn(storage, 'get').mockImplementation(async (key: any) => {
+ const row = await realGet(key);
+ // A slow list read: well past the pre-paint bound.
+ if (key.queryKey === LIST_STORAGE_KEY) await new Promise((r) => setTimeout(r, 150));
+ return row;
+ });
+
+ await useAgentGroupStore.getState().loadGroups();
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+
+ getSpy.mockRestore();
+ await vi.waitFor(
+ async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }),
+ ).toBeUndefined(),
+ { timeout: 2000 },
+ );
+ });
+
+ // Session rows are synthesized: their placeholders (`workspaceId: null`,
+ // `visibility: 'public'`) must not be replayed over a real persisted detail.
+ it('keeps a persisted detail’s real fields over a session seed', async () => {
+ const scope = createScope();
+ const roster = [{ id: 'a1', isSupervisor: false, title: 'Member' }];
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ {
+ data: {
+ ...groupDetail('g1', 'Persisted'),
+ agents: roster,
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ } as any,
+ updatedAt: 1,
+ },
+ );
+
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps(
+ [{ ...groupRow('g1', 'Session title'), visibility: 'public', workspaceId: null } as any],
+ 'session',
+ );
+ getGroupDetail.mockImplementation(pending);
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual(roster),
+ );
+ const detail = useAgentGroupStore.getState().groupMap.g1 as any;
+ expect(detail.title).toBe('Session title');
+ expect(detail.workspaceId).toBe('ws-1');
+ expect(detail.visibility).toBe('private');
+ session.unmount();
+ });
+
+ // g1 answers "gone" only after the page moved on to g2. The success callback
+ // is skipped for a superseded key, so the terminal answer must still drop g1
+ // (memory + storage) and settle it as not found.
+ it('records a terminal absence that lands after navigating to another group', async () => {
+ const scope = createScope();
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ { data: groupDetail('g1', 'One'), updatedAt: 1 },
+ );
+ let answerG1!: (detail: null) => void;
+ getGroupDetail.mockImplementation((id: string) =>
+ id === 'g1'
+ ? new Promise((resolve) => (answerG1 = resolve))
+ : Promise.resolve(groupDetail(id)),
+ );
+
+ const session = renderHook(
+ ({ id }: { id: string }) => useAgentGroupStore.getState().useFetchGroupDetail(true, id),
+ { initialProps: { id: 'g1' } },
+ );
+ await vi.waitFor(() => expect(useAgentGroupStore.getState().groupMap.g1).toBeDefined());
+ await vi.waitFor(() => expect(answerG1).toBeDefined());
+
+ session.rerender({ id: 'g2' });
+ await vi.waitFor(() => expect(useAgentGroupStore.getState().groupMap.g2).toBeDefined());
+
+ answerG1(null);
+ await vi.waitFor(() => expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined());
+ expect(useAgentGroupStore.getState().groupNotFoundMap.g1).toBe(true);
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }),
+ ).toBeUndefined(),
+ );
+ session.unmount();
+ });
+
+ // The authoritative list drops g1 while g1's detail request is still in
+ // flight: that older response must not recreate (and re-persist) the group.
+ it('does not let an in-flight detail response recreate a group the list pruned', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ getGroupDetail.mockResolvedValue(groupDetail('g1', 'One'));
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeDefined();
+
+ let answerG1!: (detail: unknown) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (answerG1 = resolve)));
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+ await vi.waitFor(() => expect(answerG1).toBeDefined());
+
+ // The list no longer carries g1 (deleted / access revoked).
+ getGroups.mockResolvedValue([]);
+ await useAgentGroupStore.getState().loadGroups();
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+
+ answerG1(groupDetail('g1', 'Stale'));
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }),
+ ).toBeUndefined(),
+ );
+ session.unmount();
+ });
+
+ // The imperative refresh writes through `replace` directly, so it needs the
+ // same removal guard: a group the list pruned mid-flight stays gone.
+ it('does not let an in-flight imperative detail fetch recreate a pruned group', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ getGroupDetail.mockResolvedValue(groupDetail('g1', 'One'));
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeDefined();
+
+ let answer!: (detail: unknown) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const refresh = useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ await vi.waitFor(() => expect(answer).toBeDefined());
+
+ getGroups.mockResolvedValue([]);
+ await useAgentGroupStore.getState().loadGroups();
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+
+ agentStoreMock.setActiveAgentId.mockClear();
+ answer(groupDetail('g1', 'Stale'));
+ await refresh;
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ expect(agentStoreMock.setActiveAgentId).not.toHaveBeenCalled();
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ // An imperative refresh answers "gone" only after an account switch: the
+ // persisted detail must still be purged in the scope the request started in.
+ it('purges a late terminal absence in the scope the refresh started in', async () => {
+ const scope = createScope();
+ getGroupDetail.mockResolvedValue(groupDetail('g1', 'One'));
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ await vi.waitFor(async () =>
+ expect(
+ (await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }))
+ ?.data,
+ ).toBeDefined(),
+ );
+
+ let answer!: (detail: null) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const refresh = useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ await vi.waitFor(() => expect(answer).toBeDefined());
+
+ createScope('agent-group-other-user');
+ answer(null);
+ await refresh;
+
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ // The same late "gone" must also leave that scope's persisted list, or
+ // switching back hydrates the deleted group into the sidebar.
+ it('drops a late terminal absence from the original scope’s persisted list', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1', 'One'), groupRow('g2', 'Two')]);
+ await useAgentGroupStore.getState().loadGroups();
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope })
+ )?.data?.map((group) => group.id),
+ ).toEqual(['g1', 'g2']),
+ );
+
+ let answer!: (detail: null) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const refresh = useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ await vi.waitFor(() => expect(answer).toBeDefined());
+
+ createScope('agent-group-other-user');
+ answer(null);
+ await refresh;
+
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope })
+ )?.data?.map((group) => group.id),
+ ).toEqual(['g2']),
+ );
+ });
+
+ it('replaces the list with the server response, persists it and seeds groupMap', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1', 'Server group')]);
+
+ await useAgentGroupStore.getState().loadGroups();
+
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+ expect(useAgentGroupStore.getState().groupsInit).toBe(true);
+ // The list row also makes the group resolvable before its detail page mounts.
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Server group');
+
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope })
+ )?.data?.map((group) => group.id),
+ ).toEqual(['g1']),
+ );
+ });
+
+ it('never hydrates another identity’s persisted list', async () => {
+ const scope = createScope();
+ await agentGroupListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope },
+ { data: [groupRow('mine')], updatedAt: 1 },
+ );
+ createScope('agent-group-other-user');
+ getGroups.mockImplementation(pending);
+
+ void useAgentGroupStore.getState().loadGroups();
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(useAgentGroupStore.getState().groups).toEqual([]);
+ expect(useAgentGroupStore.getState().groupsInit).toBe(false);
+ });
+
+ it('keeps a loaded roster and its authoritative config when the list is merged in', async () => {
+ createScope();
+ const detail = {
+ ...groupDetail('g1', 'Loaded title'),
+ agents: [{ id: 'a1', title: 'Member' }],
+ config: { systemPrompt: 'authoritative' },
+ };
+ useAgentGroupStore.setState({
+ agentGroupDetailReplica: createReplicaState(),
+ groupMap: { g1: detail as any },
+ });
+
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps([{ ...groupRow('g1', 'List title'), config: null } as any]);
+
+ const merged = useAgentGroupStore.getState().groupMap.g1;
+ expect(merged.title).toBe('List title');
+ // The roster is detail-only data the list row cannot carry.
+ expect(merged.agents).toEqual([{ id: 'a1', title: 'Member' }]);
+ expect(merged.config).toEqual({ systemPrompt: 'authoritative' });
+ });
+
+ it('persists a fetched group detail so the group page paints it on the next visit', async () => {
+ const scope = createScope();
+ getGroupDetail.mockResolvedValue(groupDetail('g1', 'Server detail'));
+
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Server detail');
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupDetailResource.storage!.get({
+ queryKey: detailStorageKey('g1'),
+ scope,
+ })
+ )?.data?.title,
+ ).toBe('Server detail'),
+ );
+
+ // A fresh page load (memory gone, network slow) paints the persisted detail.
+ useAgentGroupStore.setState({ ...initialChatGroupState });
+ getGroupDetail.mockImplementation(pending);
+
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Server detail'),
+ );
+ await vi.waitFor(() => expect(session.result.current.isHydrated).toBe(true));
+ // Background loading must not hide the hydrated group.
+ expect(session.result.current.isValidating).toBe(true);
+ session.unmount();
+ });
+
+ it('drops a gone group from both views and storage, and marks it not found', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ getGroupDetail.mockResolvedValue(groupDetail('g1'));
+
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeDefined();
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupDetailResource.storage!.get({
+ queryKey: detailStorageKey('g1'),
+ scope,
+ })
+ )?.data,
+ ).toBeDefined(),
+ );
+
+ getGroupDetail.mockResolvedValue(null);
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ expect(useAgentGroupStore.getState().groups.some((group) => group.id === 'g1')).toBe(false);
+ expect(useAgentGroupStore.getState().groupNotFoundMap.g1).toBe(true);
+
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g1'), scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ it('patches one group row in the list and the detail map in one fan-out', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1', 'Before')]);
+ getGroupDetail.mockResolvedValue(groupDetail('g1', 'Before'));
+
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+
+ useAgentGroupStore.getState().internal_updateGroupRow('g1', { title: 'After' });
+
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('After');
+ expect(useAgentGroupStore.getState().groups[0].title).toBe('After');
+ // The detail's roster survives a metadata-only patch.
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual([]);
+
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupDetailResource.storage!.get({
+ queryKey: detailStorageKey('g1'),
+ scope,
+ })
+ )?.data?.title,
+ ).toBe('After'),
+ );
+ });
+
+ // P1 #1: the list seeds `groupMap` with a roster-less row. That seed must not
+ // block the persisted full detail from hydrating, or a slow / failed / offline
+ // detail fetch strands the group page on default config and no members.
+ it('hydrates the persisted detail over a list seed when the network never answers', async () => {
+ const scope = createScope();
+ const roster = [{ id: 'a1', isSupervisor: false, title: 'Member' }];
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ {
+ data: {
+ ...groupDetail('g1', 'Persisted detail'),
+ agents: roster,
+ config: { systemPrompt: 'authoritative' },
+ } as any,
+ updatedAt: 1,
+ },
+ );
+
+ // The list lands first: `groupMap` only knows the roster-less list row.
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps([{ ...groupRow('g1', 'List row'), config: null } as any]);
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('List row');
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual([]);
+
+ // The group page mounts while the network hangs (offline / slow).
+ getGroupDetail.mockImplementation(pending);
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual(roster),
+ );
+ expect(useAgentGroupStore.getState().groupMap.g1?.config).toEqual({
+ systemPrompt: 'authoritative',
+ });
+ // The list row is fresher than the persisted detail: its metadata (the
+ // renamed title) survives the hydrate instead of regressing to storage's.
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('List row');
+ session.unmount();
+ });
+
+ it('never persists a list seed over the authoritative detail row', async () => {
+ const scope = createScope();
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ {
+ data: {
+ ...groupDetail('g1', 'Persisted detail'),
+ agents: [{ id: 'a1', isSupervisor: false, title: 'Member' }],
+ } as any,
+ updatedAt: 1,
+ },
+ );
+
+ // Only the list seed is in memory (the detail was not loaded this session).
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps([{ ...groupRow('g1', 'List row'), config: null } as any]);
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual([]);
+
+ // A metadata patch against the seed asks to persist, but a seed never does.
+ useAgentGroupStore.getState().internal_updateGroupRow('g1', { title: 'Renamed' });
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Renamed');
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const row = await agentGroupDetailResource.storage!.get({
+ queryKey: detailStorageKey('g1'),
+ scope,
+ });
+ expect(row?.data?.title).toBe('Persisted detail');
+ expect((row?.data as any)?.agents).toEqual([
+ { id: 'a1', isSupervisor: false, title: 'Member' },
+ ]);
+ });
+
+ // P1 #2: two users in personal mode both have a `null` workspace, so the guard
+ // must compare the full cache scope (`${userId}:${workspaceId}`) — otherwise a
+ // response started for user A lands in user B's partition.
+ it('drops a group detail response that lands after an account switch', async () => {
+ createScope('agent-group-user-a');
+ let resolveDetail!: (value: unknown) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (resolveDetail = resolve)));
+
+ const inflight = useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ // Switch to another user, also personal (both have a null workspace).
+ const scopeB = createScope('agent-group-user-b');
+
+ resolveDetail(groupDetail('g1', 'User A group'));
+ await inflight;
+
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(
+ await agentGroupDetailResource.storage!.get({
+ queryKey: detailStorageKey('g1'),
+ scope: scopeB,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('drops a group list response that lands after an account switch', async () => {
+ createScope('agent-group-user-a');
+ let resolveGroups!: (value: unknown) => void;
+ getGroups.mockImplementation(() => new Promise((resolve) => (resolveGroups = resolve)));
+
+ const inflight = useAgentGroupStore.getState().loadGroups();
+ // `loadGroups` hydrates before it fetches, so wait for the request to be in flight.
+ await vi.waitFor(() => expect(getGroups).toHaveBeenCalled());
+ const scopeB = createScope('agent-group-user-b');
+
+ resolveGroups([groupRow('g1', 'User A group')]);
+ await inflight;
+
+ expect(useAgentGroupStore.getState().groups).toEqual([]);
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope: scopeB }),
+ ).toBeUndefined();
+ });
+
+ // P1: the group list is the authoritative, complete set. A group it no longer
+ // returns was deleted or is no longer visible, so its detail must be dropped
+ // from `groupMap` (and the persisted replica) — otherwise selectors such as
+ // the supervisor fallback keep resolving a group the server does not list.
+ it('prunes a detail the authoritative list no longer carries, from memory and storage', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1'), groupRow('g2')]);
+ getGroupDetail.mockImplementation(async (groupId: string) => groupDetail(groupId));
+
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g1');
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g2');
+ expect(useAgentGroupStore.getState().groupMap.g2).toBeDefined();
+ await vi.waitFor(async () =>
+ expect(
+ (await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }))
+ ?.data,
+ ).toBeDefined(),
+ );
+
+ // `g2` is gone from the next authoritative list.
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ await useAgentGroupStore.getState().loadGroups();
+
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+ expect(useAgentGroupStore.getState().groupMap.g2).toBeUndefined();
+ // The group that is still listed keeps its detail.
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeDefined();
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ // P1: a group can live in the persisted list without ever being seeded into
+ // `groupMap`. After a reload the list hydrates it, the authoritative response
+ // drops it — and its persisted detail must go too, or a later direct visit
+ // paints a deleted / unauthorized group from storage while the network is slow.
+ it('prunes a persisted detail the authoritative list drops, with no groupMap entry', async () => {
+ const scope = createScope();
+ getGroups.mockResolvedValue([groupRow('g1'), groupRow('g2')]);
+ getGroupDetail.mockImplementation(async (groupId: string) => groupDetail(groupId));
+
+ // An earlier visit persisted both the list and g2's detail.
+ await useAgentGroupStore.getState().loadGroups();
+ await useAgentGroupStore.getState().internal_fetchGroupDetail('g2');
+ await vi.waitFor(async () =>
+ expect(
+ (
+ await agentGroupListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope })
+ )?.data?.map((group) => group.id),
+ ).toEqual(['g1', 'g2']),
+ );
+ await vi.waitFor(async () =>
+ expect(
+ (await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }))
+ ?.data,
+ ).toBeDefined(),
+ );
+
+ // Reload: memory is gone, storage stays — `groupMap` is empty again, so the
+ // list is the only thing that still knows about g2 before the network answers.
+ useAgentGroupStore.setState({ ...initialChatGroupState });
+ expect(useAgentGroupStore.getState().groupMap.g2).toBeUndefined();
+
+ getGroups.mockResolvedValue([groupRow('g1')]);
+ await useAgentGroupStore.getState().loadGroups();
+
+ // g2 never entered `groupMap` this session, yet its persisted detail is gone.
+ expect(useAgentGroupStore.getState().groupMap.g2).toBeUndefined();
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+ await vi.waitFor(async () =>
+ expect(
+ await agentGroupDetailResource.storage!.get({ queryKey: detailStorageKey('g2'), scope }),
+ ).toBeUndefined(),
+ );
+ });
+
+ // P1: a persisted detail hydrates with no network response. Its success side
+ // effects must run off the hydrated value too, or an offline / slow first
+ // paint resolves tools / models through an empty (or previously active) agent
+ // and stays behind the 404 guard.
+ it('replays the group-detail side effects for a hydrated value', async () => {
+ const scope = createScope();
+ const roster = [
+ { id: 'a1', isSupervisor: false, title: 'Member', updatedAt: new Date('2030-01-01') },
+ ];
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ {
+ data: {
+ ...groupDetail('g1', 'Persisted detail'),
+ agents: roster,
+ supervisorAgentId: 'sup-1',
+ } as any,
+ updatedAt: 1,
+ },
+ );
+
+ // A stale not-found flag left by an earlier (failed) visit.
+ useAgentGroupStore.setState({ groupNotFoundMap: { g1: true } });
+
+ getGroupDetail.mockImplementation(pending);
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Persisted detail'),
+ );
+ // … roster copied into the agent store …
+ await vi.waitFor(() =>
+ expect(agentStoreMock.internal_dispatchAgentMap).toHaveBeenCalledWith(
+ 'a1',
+ expect.objectContaining({ id: 'a1' }),
+ ),
+ );
+ // … supervisor adopted as the active agent …
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenCalledWith('sup-1');
+ // … and the stale 404 cleared, all with no network response.
+ expect(useAgentGroupStore.getState().groupNotFoundMap.g1).toBeUndefined();
+
+ await vi.waitFor(() => expect(session.result.current.isHydrated).toBe(true));
+ session.unmount();
+ });
+
+ // P1: the generic `useSync` hook must not replay a response's success side
+ // effects when the scoped write was rejected. A detail fetch started under
+ // user A that resolves after the switch to user B must not copy A's roster
+ // into the current agent store nor adopt A's supervisor as the active agent.
+ it('does not adopt a detail response that lands after an account switch', async () => {
+ createScope('agent-group-user-a');
+ let resolveDetail!: (value: unknown) => void;
+ getGroupDetail.mockImplementation(() => new Promise((resolve) => (resolveDetail = resolve)));
+
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+ await vi.waitFor(() => expect(getGroupDetail).toHaveBeenCalled());
+
+ // The identity switches while the request is still in flight.
+ createScope('agent-group-user-b');
+ resolveDetail({
+ ...groupDetail('g1', 'User A group'),
+ agents: [{ id: 'a1', isSupervisor: false, title: 'A member' }],
+ supervisorAgentId: 'a-supervisor',
+ });
+
+ await vi.waitFor(() => expect(session.result.current.isHydrated).toBe(true));
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ expect(agentStoreMock.internal_dispatchAgentMap).not.toHaveBeenCalled();
+ expect(agentStoreMock.setActiveAgentId).not.toHaveBeenCalled();
+ session.unmount();
+ });
+
+ // P2: a list / session refresh seeds every group at once. One batched replica
+ // write means one store commit (one subscriber notification), not one per row.
+ it('seeds many groups in a single store commit', () => {
+ createScope();
+ let notifications = 0;
+ const unsubscribe = useAgentGroupStore.subscribe(() => {
+ notifications += 1;
+ });
+
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps([
+ { ...groupRow('g1', 'One'), config: null } as any,
+ { ...groupRow('g2', 'Two'), config: null } as any,
+ { ...groupRow('g3', 'Three'), config: null } as any,
+ ]);
+ unsubscribe();
+
+ expect(notifications).toBe(1);
+ expect(Object.keys(useAgentGroupStore.getState().groupMap).sort()).toEqual(['g1', 'g2', 'g3']);
+ expect(useAgentGroupStore.getState().groupMap.g2?.title).toBe('Two');
+ });
+
+ // P1: a server-confirmed absence (deleted / no access) must win over a detail
+ // hydrate that was already reading storage. Otherwise the stale read restores
+ // the group, `onHydrated` clears the 404 and adopts the old roster, and the
+ // gone group stays on screen with no further network call to correct it.
+ it('does not resurrect a group the server confirmed gone while its hydrate was in flight', async () => {
+ const scope = createScope();
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ { data: groupDetail('g1', 'Persisted detail'), updatedAt: 1 },
+ );
+ // The list already seeded the group, so the page has something to hydrate.
+ useAgentGroupStore.getState().internal_updateGroupMaps([groupRow('g1', 'List row')]);
+
+ // Park the detail hydrate: read the row now (a storage snapshot), resolve late.
+ const storage = agentGroupDetailResource.storage!;
+ const realGet = storage.get.bind(storage);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ let readStarted = false;
+ vi.spyOn(storage, 'get').mockImplementation(async (key) => {
+ if (key.queryKey === detailStorageKey('g1') && key.scope === scope) {
+ const snapshot = await realGet(key);
+ readStarted = true;
+ await readGate;
+ return snapshot;
+ }
+ return realGet(key);
+ });
+
+ // The server answers first: the group is gone.
+ getGroupDetail.mockResolvedValue(null);
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+
+ await vi.waitFor(() => expect(readStarted).toBe(true));
+ await vi.waitFor(() => expect(useAgentGroupStore.getState().groupNotFoundMap.g1).toBe(true));
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+
+ // The stale read finally lands; the group must stay gone.
+ releaseRead();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(useAgentGroupStore.getState().groupMap.g1).toBeUndefined();
+ expect(useAgentGroupStore.getState().groupNotFoundMap.g1).toBe(true);
+ expect(agentStoreMock.setActiveAgentId).not.toHaveBeenCalled();
+ session.unmount();
+ });
+
+ // P1: switching to another group while `g1`'s storage read is slow must not let
+ // `g1`'s hydrate replay its side effects. Filling g1's cache entry is harmless,
+ // but `onHydrated` acts on the current view and would reset the active agent and
+ // chat model back to g1's supervisor.
+ it('does not adopt a superseded group when its hydrate lands after navigation', async () => {
+ const scope = createScope();
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ { data: groupDetail('g1', 'One'), updatedAt: 1 },
+ );
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g2'), scope },
+ { data: groupDetail('g2', 'Two'), updatedAt: 1 },
+ );
+
+ const storage = agentGroupDetailResource.storage!;
+ const realGet = storage.get.bind(storage);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ let readStarted = false;
+ vi.spyOn(storage, 'get').mockImplementation(async (key) => {
+ if (key.queryKey === detailStorageKey('g1') && key.scope === scope) {
+ const snapshot = await realGet(key);
+ readStarted = true;
+ await readGate;
+ return snapshot;
+ }
+ return realGet(key);
+ });
+
+ getGroupDetail.mockImplementation(pending);
+
+ const session = renderHook(
+ ({ id }: { id: string }) => useAgentGroupStore.getState().useFetchGroupDetail(true, id),
+ { initialProps: { id: 'g1' } },
+ );
+ await vi.waitFor(() => expect(readStarted).toBe(true));
+
+ // Navigate to g2 while g1's hydrate is still parked.
+ session.rerender({ id: 'g2' });
+ await vi.waitFor(() =>
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenCalledWith('g2-supervisor'),
+ );
+
+ // g1's slow hydrate lands now — it must not re-adopt g1's supervisor.
+ releaseRead();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(agentStoreMock.setActiveAgentId).not.toHaveBeenCalledWith('g1-supervisor');
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenLastCalledWith('g2-supervisor');
+ session.unmount();
+ });
+
+ // P1: g1 → g2 → g1 offline. g1's hydration already ran and is not re-run, so
+ // its side effects must be replayed off the cached detail when g1 is active
+ // again — otherwise the agent / chat stores stay on g2's supervisor.
+ it('re-adopts a cached group when navigating back to it with no network', async () => {
+ const scope = createScope();
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ { data: groupDetail('g1', 'One'), updatedAt: 1 },
+ );
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g2'), scope },
+ { data: groupDetail('g2', 'Two'), updatedAt: 1 },
+ );
+ getGroupDetail.mockImplementation(pending);
+
+ const session = renderHook(
+ ({ id }: { id: string }) => useAgentGroupStore.getState().useFetchGroupDetail(true, id),
+ { initialProps: { id: 'g1' } },
+ );
+ await vi.waitFor(() =>
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenLastCalledWith('g1-supervisor'),
+ );
+
+ session.rerender({ id: 'g2' });
+ await vi.waitFor(() =>
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenLastCalledWith('g2-supervisor'),
+ );
+
+ session.rerender({ id: 'g1' });
+ await vi.waitFor(() =>
+ expect(agentStoreMock.setActiveAgentId).toHaveBeenLastCalledWith('g1-supervisor'),
+ );
+ session.unmount();
+ });
+
+ // P2: a rename confirmed by the API while the detail is still a list seed
+ // (its storage read not landed yet) must survive the late hydrate, and the
+ // hydrated detail must persist with the rename and keep its stored roster.
+ it('keeps a confirmed rename made over a seed when the detail hydrates late', async () => {
+ const scope = createScope();
+ const roster = [{ id: 'a1', isSupervisor: false, title: 'Member' }];
+ await agentGroupDetailResource.storage!.set(
+ { queryKey: detailStorageKey('g1'), scope },
+ { data: { ...groupDetail('g1', 'Persisted detail'), agents: roster } as any, updatedAt: 1 },
+ );
+
+ const storage = agentGroupDetailResource.storage!;
+ const realGet = storage.get.bind(storage);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ let readStarted = false;
+ vi.spyOn(storage, 'get').mockImplementation(async (key) => {
+ if (key.queryKey === detailStorageKey('g1') && key.scope === scope) {
+ const snapshot = await realGet(key);
+ readStarted = true;
+ await readGate;
+ return snapshot;
+ }
+ return realGet(key);
+ });
+
+ useAgentGroupStore
+ .getState()
+ .internal_updateGroupMaps([{ ...groupRow('g1', 'List row'), config: null } as any]);
+ getGroupDetail.mockImplementation(pending);
+ const session = renderHook(() => useAgentGroupStore.getState().useFetchGroupDetail(true, 'g1'));
+ await vi.waitFor(() => expect(readStarted).toBe(true));
+
+ // The API confirmed the rename; the detail is still the list seed.
+ useAgentGroupStore.getState().internal_updateGroupRow('g1', { title: 'Renamed' });
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Renamed');
+
+ releaseRead();
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groupMap.g1?.agents).toEqual(roster),
+ );
+ expect(useAgentGroupStore.getState().groupMap.g1?.title).toBe('Renamed');
+ await vi.waitFor(async () =>
+ expect((await realGet({ queryKey: detailStorageKey('g1'), scope }))?.data).toMatchObject({
+ agents: roster,
+ title: 'Renamed',
+ }),
+ );
+ session.unmount();
+ });
+
+ // P1: after a workspace switch the store stays mounted with `groupsInit` still
+ // true. `loadGroups` must reset the view to the new scope and read its persisted
+ // list rather than leaving the previous workspace's groups on screen until the
+ // (possibly slow) response lands.
+ it('resets to the new scope and hydrates its list when the workspace switches', async () => {
+ createScope('agent-group-user-a');
+ getGroups.mockResolvedValue([groupRow('g1', 'A group')]);
+ await useAgentGroupStore.getState().loadGroups();
+ expect(useAgentGroupStore.getState().groupsInit).toBe(true);
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['g1']);
+
+ // The new scope persists a list of its own.
+ const scopeB = createScope('agent-group-user-b');
+ await agentGroupListResource.storage!.set(
+ { queryKey: LIST_STORAGE_KEY, scope: scopeB },
+ { data: [groupRow('b1', 'B group')], updatedAt: 1 },
+ );
+
+ // The network is slow, so the new scope's persisted list must paint meanwhile.
+ let resolveGroups!: (value: unknown) => void;
+ getGroups.mockImplementation(() => new Promise((resolve) => (resolveGroups = resolve)));
+
+ const inflight = useAgentGroupStore.getState().loadGroups();
+
+ await vi.waitFor(() =>
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['b1']),
+ );
+
+ resolveGroups([groupRow('b1', 'B group')]);
+ await inflight;
+ expect(useAgentGroupStore.getState().groups.map((group) => group.id)).toEqual(['b1']);
+ });
+});
diff --git a/src/store/agentGroup/slices/curd.test.ts b/src/store/agentGroup/slices/curd.test.ts
index 2fd4f145e16..fd3cec41780 100644
--- a/src/store/agentGroup/slices/curd.test.ts
+++ b/src/store/agentGroup/slices/curd.test.ts
@@ -4,10 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
import type { ChatGroupItem } from '@/database/schemas/chatGroup';
+import { replicaKeys } from '@/libs/replica';
import type * as SwrModule from '@/libs/swr';
-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
+import { mutate } from '@/libs/swr';
import { chatGroupService } from '@/services/chatGroup';
+import { initialChatGroupState } from '../initialState';
+import { agentGroupDetailResource } from '../projection';
import { useAgentGroupStore } from '../store';
// Mock dependencies
@@ -23,15 +26,9 @@ vi.mock('@/libs/swr', async (importOriginal) => {
return {
...actual,
mutate: vi.fn().mockResolvedValue(undefined),
- useClientDataSWRWithSync: vi.fn(() => ({ data: undefined, isValidating: false })),
};
});
-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- getActiveWorkspaceId: vi.fn(() => null),
- useActiveWorkspaceId: vi.fn(() => null),
-}));
-
// Helper to create mock AgentGroupDetail
const createMockGroup = (overrides: Partial<AgentGroupDetail>): AgentGroupDetail => ({
agents: [],
@@ -68,12 +65,35 @@ const createMockChatGroup = (overrides: Partial<ChatGroupItem> = {}): ChatGroupI
...overrides,
});
+/**
+ * `refreshGroupDetail` revalidates the replica sync query of one group. The
+ * query key is derived from the resource (name + version + scope) and the entry
+ * params, so assert the match predicate itself rather than a literal key tuple.
+ */
+const expectDetailRevalidated = (groupId: string) => {
+ const match = vi.mocked(mutate).mock.calls.at(-1)?.[0] as ((key: unknown) => boolean) | undefined;
+ expect(typeof match).toBe('function');
+
+ const keyOf = (id: string) =>
+ replicaKeys.sync(
+ agentGroupDetailResource.name,
+ agentGroupDetailResource.version,
+ agentGroupDetailResource.scope.get(),
+ id,
+ { groupId: id },
+ );
+
+ expect(match!(keyOf(groupId))).toBe(true);
+ expect(match!(keyOf(`${groupId}-other`))).toBe(false);
+};
+
describe('ChatGroupCurdSlice', () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset store state
act(() => {
useAgentGroupStore.setState({
+ ...initialChatGroupState,
activeGroupId: 'group-1',
groupMap: {
'group-1': createMockGroup({ id: 'group-1', title: 'Test Group' }),
@@ -101,6 +121,8 @@ describe('ChatGroupCurdSlice', () => {
expect(chatGroupService.updateGroup).toHaveBeenCalledWith('group-1', {
title: 'Updated Title',
});
+ expect(result.current.groupMap['group-1'].title).toBe('Updated Title');
+ expect(result.current.groups[0].title).toBe('Updated Title');
});
it('should refresh group detail after update', async () => {
@@ -112,48 +134,7 @@ describe('ChatGroupCurdSlice', () => {
await result.current.updateGroup('group-1', { description: 'New description' });
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
- });
- });
-
- describe('refreshGroups', () => {
- it('should invalidate the group list', async () => {
- const { result } = renderHook(() => useAgentGroupStore());
-
- await act(async () => {
- await result.current.refreshGroups();
- });
-
- expect(mutate).toHaveBeenCalledWith(['group:list', true]);
- });
- });
-
- describe('useFetchGroupDetail', () => {
- it('should remove stale local group data and mark not-found when detail revalidation reports not found', async () => {
- vi.mocked(chatGroupService.getGroupDetail).mockResolvedValue(null as any);
-
- const { result } = renderHook(() => useAgentGroupStore());
-
- act(() => {
- result.current.useFetchGroupDetail(true, 'group-1');
- });
-
- const swrCall = vi.mocked(useClientDataSWRWithSync).mock.calls.at(-1);
- const fetcher = swrCall?.[1] as (() => Promise<unknown>) | undefined;
- const swrOptions = swrCall?.[2];
- const onData = swrOptions?.onData as ((data: unknown) => void) | undefined;
-
- // "Gone / no access" resolves to null (settled 404 state) instead of throwing.
- await act(async () => {
- await expect(fetcher?.()).resolves.toBeNull();
- });
- act(() => {
- onData?.(null);
- });
-
- expect(result.current.groupMap['group-1']).toBeUndefined();
- expect(result.current.groups.some((group) => group.id === 'group-1')).toBe(false);
- expect(result.current.groupNotFoundMap['group-1']).toBe(true);
+ expectDetailRevalidated('group-1');
});
});
@@ -173,6 +154,9 @@ describe('ChatGroupCurdSlice', () => {
allowDM: false,
}),
});
+ expect(result.current.groupMap['group-1'].config).toEqual(
+ expect.objectContaining({ allowDM: false }),
+ );
});
it('should not update if no current group', async () => {
@@ -201,7 +185,7 @@ describe('ChatGroupCurdSlice', () => {
await result.current.updateGroupConfig({ revealDM: true });
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
});
});
@@ -247,7 +231,7 @@ describe('ChatGroupCurdSlice', () => {
await result.current.updateGroupMeta({ title: 'Updated' });
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
});
it('keeps an explicit metadata update bound to its original group', async () => {
@@ -285,7 +269,7 @@ describe('ChatGroupCurdSlice', () => {
expect(chatGroupService.updateGroup).toHaveBeenCalledExactlyOnceWith('group-1', {
title: 'Group One Draft',
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
expect(result.current.groupMap['group-1']?.title).toBe('Group One Draft');
expect(result.current.groupMap['group-2']?.title).toBe('Group Two');
});
diff --git a/src/store/agentGroup/slices/curd.ts b/src/store/agentGroup/slices/curd.ts
index d5dbc238f27..f7fdc89d010 100644
--- a/src/store/agentGroup/slices/curd.ts
+++ b/src/store/agentGroup/slices/curd.ts
@@ -11,10 +11,7 @@ import { agentGroupSelectors } from '../selectors';
type Setter = StoreSetter<ChatGroupStore>;
type ChatGroupStoreWithInternal = ChatGroupStore & {
- internal_dispatchChatGroup: (payload: {
- payload: { id: string; value: Partial<ChatGroupItem> };
- type: 'updateGroup';
- }) => void;
+ internal_updateGroupRow: (id: string, value: Partial<ChatGroupItem>) => void;
refreshGroupDetail: (groupId: string) => Promise<void>;
};
@@ -83,7 +80,7 @@ export class ChatGroupCurdAction {
updateGroup = async (id: string, value: Partial<ChatGroupItem>) => {
await chatGroupService.updateGroup(id, value);
- this.#get().internal_dispatchChatGroup({ payload: { id, value }, type: 'updateGroup' });
+ this.#get().internal_updateGroupRow(id, value);
await this.#get().refreshGroupDetail(id);
};
@@ -103,12 +100,9 @@ export class ChatGroupCurdAction {
// Update the database first
await chatGroupService.updateGroup(group.id, { config: mergedConfig });
- // Immediately update the local store to ensure configuration is available
- // Note: reducer expects payload: { id, value }
- this.#get().internal_dispatchChatGroup({
- payload: { id: group.id, value: { config: mergedConfig } },
- type: 'updateGroup',
- });
+ // Immediately patch every copy of the group, so the configuration is
+ // available before the refreshed detail lands.
+ this.#get().internal_updateGroupRow(group.id, { config: mergedConfig });
// Refresh groups to ensure consistency
await this.#get().refreshGroupDetail(group.id);
@@ -129,7 +123,7 @@ export class ChatGroupCurdAction {
await chatGroupService.updateGroup(id, meta);
// Keep local store in sync immediately
- this.#get().internal_dispatchChatGroup({ payload: { id, value: meta }, type: 'updateGroup' });
+ this.#get().internal_updateGroupRow(id, meta);
await this.#get().refreshGroupDetail(id);
};
}
diff --git a/src/store/agentGroup/slices/lifecycle.ts b/src/store/agentGroup/slices/lifecycle.ts
index 93fcc7bae1a..8be05a176c6 100644
--- a/src/store/agentGroup/slices/lifecycle.ts
+++ b/src/store/agentGroup/slices/lifecycle.ts
@@ -41,7 +41,7 @@ export class ChatGroupLifecycleAction {
});
}
- this.#get().internal_dispatchChatGroup({ payload: group, type: 'addGroup' });
+ this.#get().internal_addGroup(group);
// Fetch full group detail to get supervisorAgentId and agents for tools injection
await this.#get().internal_fetchGroupDetail(group.id);
diff --git a/src/store/agentGroup/slices/member.test.ts b/src/store/agentGroup/slices/member.test.ts
index 22077ceeb80..743f6ecacb3 100644
--- a/src/store/agentGroup/slices/member.test.ts
+++ b/src/store/agentGroup/slices/member.test.ts
@@ -1,10 +1,13 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { replicaKeys } from '@/libs/replica';
import type * as SwrModule from '@/libs/swr';
import { mutate } from '@/libs/swr';
import { chatGroupService } from '@/services/chatGroup';
+import { initialChatGroupState } from '../initialState';
+import { agentGroupDetailResource } from '../projection';
import { useAgentGroupStore } from '../store';
// Mock dependencies
@@ -21,16 +24,33 @@ vi.mock('@/libs/swr', async (importOriginal) => {
return { ...actual, mutate: vi.fn().mockResolvedValue(undefined) };
});
+/**
+ * A member write refreshes the group's detail through the replica: assert the
+ * sync query match predicate instead of the retired `group:detail` SWR tuple.
+ */
+const expectDetailRevalidated = (groupId: string) => {
+ const match = vi.mocked(mutate).mock.calls.at(-1)?.[0] as ((key: unknown) => boolean) | undefined;
+ expect(typeof match).toBe('function');
+
+ const keyOf = (id: string) =>
+ replicaKeys.sync(
+ agentGroupDetailResource.name,
+ agentGroupDetailResource.version,
+ agentGroupDetailResource.scope.get(),
+ id,
+ { groupId: id },
+ );
+
+ expect(match!(keyOf(groupId))).toBe(true);
+ expect(match!(keyOf(`${groupId}-other`))).toBe(false);
+};
+
describe('ChatGroupMemberSlice', () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset store state
act(() => {
- useAgentGroupStore.setState({
- groupMap: {},
- groups: [],
- groupsInit: false,
- });
+ useAgentGroupStore.setState({ ...initialChatGroupState });
});
});
@@ -63,7 +83,7 @@ describe('ChatGroupMemberSlice', () => {
await result.current.addAgentsToGroup('group-1', ['agent-1']);
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
});
});
@@ -95,7 +115,7 @@ describe('ChatGroupMemberSlice', () => {
await result.current.removeAgentFromGroup('group-1', 'agent-1');
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
});
});
@@ -130,7 +150,7 @@ describe('ChatGroupMemberSlice', () => {
await result.current.reorderGroupMembers('group-1', ['agent-1', 'agent-2']);
});
- expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);
+ expectDetailRevalidated('group-1');
});
});
});
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index 222181b9a8c..15a040e433f 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -252,7 +252,9 @@ export class SessionActionImpl {
workspaceId: null,
}));
- chatGroupStore.internal_updateGroupMaps(chatGroups);
+ // Session rows are synthesized: only their real fields may seed a
+ // group detail (see `GroupSeedSource`).
+ chatGroupStore.internal_updateGroupMaps(chatGroups, 'session');
}
this.#set(