Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(sandbox): paint instance directory, picker lists and entitlement stale-first from replicas (#20850)

Arvin Xuf4b7b8c12b85
diff --git a/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx b/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx
index d7a3feecb9f..2d4a0a452a5 100644
--- a/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx
@@ -1,6 +1,5 @@
'use client';
-import { environmentKind } from '@lobechat/types';
import { Github } from '@lobehub/icons';
import {
confirmModal,
@@ -27,7 +26,6 @@ import {
} from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';
import { describeError } from '@/features/EnvironmentManager/errorMessage';
@@ -35,6 +33,7 @@ import { settleThenRefresh } from '@/features/EnvironmentManager/settleThenRefre
import { useCanEditEnvironment } from '@/features/EnvironmentManager/useCanEditEnvironment';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { sandboxStorageService } from '@/services/sandboxStorage';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
import OptionRow from './OptionRow';
import SandboxEnvironmentRow from './SandboxEnvironmentRow';
@@ -194,9 +193,6 @@ interface SandboxInstancePickerProps {
value: SandboxSelection;
}
-/** How often a building copy is re-listed while the picker can see it. */
-const BUILD_REFRESH_MS = 4000;
-
/**
* Where a cloud-sandbox run keeps its files, offered the way the local picker
* offers folders: the chip names the slot, the menu lists the places.
@@ -230,42 +226,25 @@ const SandboxInstancePicker = memo<SandboxInstancePickerProps>(
// Fetched while CLOSED whenever a copy is bound, because the chip names
// it by looking it up in this list: gating the list on `open` alone leaves
// the closed chip with nothing to look up.
- const {
- data,
- isLoading: instancesLoading,
- mutate: refreshInstances,
- } = useSWR(
- entitled && (open || boundInstanceId) ? ['sandbox-instances', topicId] : null,
- () => sandboxStorageService.listInstances({ topicId, withSizes: false }),
- // The topic is in the key because occupancy is answered per conversation
- // — "in use by another one" is a different answer here than there. The
- // instances themselves are the same list either way, so the first send,
- // which takes the topic from none to one, must not blank the chip: it
- // would flash a skeleton for a name that never changed. Kept until the
- // refetch lands; a moment of last-known occupancy is not worth that.
- {
- keepPreviousData: true,
- // A building copy settles on a listing, so keep listing while one is
- // building: "Building" has to turn into a usable row on its own.
- refreshInterval: (latest) =>
- (latest?.instances ?? []).some((instance) => instance.status === 'pending')
- ? BUILD_REFRESH_MS
- : 0,
- revalidateOnFocus: false,
- },
- );
- const {
- data: environmentData,
- error: environmentError,
- isLoading: environmentsLoading,
- // Also while closed when a copy is bound: whether that copy is still
- // usable depends on its environment's visibility.
- } = useSWR(entitled && (open || boundInstanceId) ? 'sandbox-environments' : null, () =>
- sandboxStorageService.listEnvironments(),
- );
-
- const instances = data?.instances ?? [];
- const environments = environmentData?.environments ?? [];
+ //
+ // Both lists are replicas: a reload names the chip and fills the menu from
+ // the last answer while the network confirms it. One instance list serves
+ // every conversation (see `sandboxSelectors.pickerInstances`), so the first
+ // send, which takes the topic from none to one, never blanks the chip.
+ const listsEnabled = entitled && Boolean(open || boundInstanceId);
+ const { error: instancesError } = sandboxActions.useFetchPickerInstances(listsEnabled, topicId);
+ // Also while closed when a copy is bound: whether that copy is still
+ // usable depends on its environment's visibility.
+ const { error: environmentError } = sandboxActions.useFetchPickerEnvironments(listsEnabled);
+ const data = useSandboxStore(sandboxSelectors.pickerInstances(topicId));
+ const environmentData = useSandboxStore(sandboxSelectors.pickerEnvironments);
+ const refreshInstances = sandboxActions.mutatePickerInstances;
+ // "Not known yet": nothing painted (persisted or fetched) and no failure.
+ const instancesLoading = listsEnabled && !data && !instancesError;
+ const environmentsLoading = listsEnabled && !environmentData && !environmentError;
+
+ const instances = data ?? [];
+ const environments = environmentData ?? [];
const current = instances.find((instance) => instance.id === boundInstanceId);
// The server's rule, mirrored: only inside a workspace, where private and
// published are two different things. A personal environment is always
@@ -378,7 +357,7 @@ const SandboxInstancePicker = memo<SandboxInstancePickerProps>(
const renderEnvironment = (environment: (typeof environments)[number]) => {
const isCreator = canEdit(environment);
- const kind = environmentKind(environment);
+ const kind = environment.kind;
const row = describeEnvironmentRow({
boundInstanceId,
copies: copiesOf(environment.id),
@@ -423,7 +402,7 @@ const SandboxInstancePicker = memo<SandboxInstancePickerProps>(
);
}
if (currentBlocked) return <Icon icon={LockIcon} size={14} />;
- return environmentKind(currentEnvironment) === 'files' ? (
+ return (currentEnvironment?.kind ?? 'files') === 'files' ? (
<Icon icon={FolderIcon} size={14} />
) : (
<Github size={14} />
@@ -521,7 +500,7 @@ const SandboxInstancePicker = memo<SandboxInstancePickerProps>(
{entitled && (environmentsLoading || instancesLoading) && <EnvironmentSectionSkeleton />}
- {entitled && environmentError && (
+ {entitled && Boolean(environmentError) && (
<Text className={styles.notice}>{t('sandboxStorage.environmentsUnavailable')}</Text>
)}
diff --git a/src/features/ChatInput/ControlBar/useCreateCopy.ts b/src/features/ChatInput/ControlBar/useCreateCopy.ts
index b2a5829949f..5e8d02c4878 100644
--- a/src/features/ChatInput/ControlBar/useCreateCopy.ts
+++ b/src/features/ChatInput/ControlBar/useCreateCopy.ts
@@ -1,19 +1,20 @@
import { useCallback } from 'react';
import { sandboxStorageService } from '@/services/sandboxStorage';
+import type { SandboxPickerInstanceList } from '@/store/sandbox';
import { usePendingIds } from './usePendingIds';
import type { SandboxSelection } from './useSandboxMode';
-type ListedInstances = Awaited<ReturnType<typeof sandboxStorageService.listInstances>>;
-
interface UseCreateCopyOptions {
/** The build could not be started; the copy exists and stays bound. */
onBuildError: (error: unknown) => void;
onChange: (selection: SandboxSelection) => Promise<void>;
- /** The picker's SWR `mutate` for the instance list. */
+ /** The picker's instance-list edit (`sandboxActions.mutatePickerInstances`). */
refreshInstances: (
- update?: (previous: ListedInstances | undefined) => ListedInstances | undefined,
+ update?: (
+ previous: SandboxPickerInstanceList | undefined,
+ ) => SandboxPickerInstanceList | undefined,
options?: { revalidate: boolean },
) => Promise<unknown>;
topicId?: string;
@@ -55,10 +56,7 @@ export const useCreateCopy = ({
instances: [
...previous.instances,
{
- buildError: null,
- buildId: null,
- buildable: true,
- createdAt: created.createdAt,
+ createdAt: new Date(created.createdAt).toISOString(),
environmentId: created.environmentId,
id: created.id,
inUse: false,
@@ -69,7 +67,6 @@ export const useCreateCopy = ({
(instance) => instance.environmentId !== environmentId,
),
name: created.name,
- snapshot: null,
status: 'pending' as const,
workingDirectory: created.workingDirectory,
},
diff --git a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
index abea26c91f2..ce33dde9253 100644
--- a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
@@ -1,13 +1,11 @@
import { isDesktop } from '@lobechat/const';
-import useSWR from 'swr';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
-import { sandboxStorageService } from '@/services/sandboxStorage';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
@@ -61,18 +59,15 @@ const useRunsInSandbox = (agentId: string): boolean => {
export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessResult => {
const labEnabled = useUserStore(labPreferSelectors.enablePersistentSandbox);
const runsInSandbox = useRunsInSandbox(agentId);
- const workspaceId = useActiveWorkspaceId();
const shouldAsk = labEnabled && runsInSandbox;
- // Keyed by workspace, because the server resolves the entitlement from the
- // active one. A single global key with focus revalidation off would hand the
- // previous workspace's answer and quota to the next one until a reload —
- // offering persistence where there is none, or hiding one there is.
- const { data } = useSWR(
- shouldAsk ? ['sandbox-storage-entitlement', workspaceId ?? ''] : null,
- () => sandboxStorageService.getEntitlement(),
- { revalidateOnFocus: false },
- );
+ // A replica partitioned by the cache scope (user + workspace), because the
+ // server resolves the entitlement from the active workspace: one workspace's
+ // answer and quota never reach the next. Persisted, so a reload paints the
+ // chip from the last answer while this one is confirmed; the server still
+ // checks the claim on every sandbox call.
+ sandboxActions.useFetchEntitlement(shouldAsk, { revalidateOnFocus: false });
+ const data = useSandboxStore(sandboxSelectors.entitlement);
if (!shouldAsk) return { quotaBytes: null, status: 'hidden' };
// Until the answer arrives, show nothing rather than flashing an upgrade
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 4cea875960c..98c8e8b5618 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -45,7 +45,6 @@ import {
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import { useBusinessWorkingSidebarTabs } from '@/business/client/features/WorkingSidebarTabs';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
@@ -70,7 +69,6 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
-import { sandboxStorageService } from '@/services/sandboxStorage';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -86,6 +84,7 @@ import {
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';
import Files from './Files';
@@ -399,15 +398,16 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
// Scoped to the bound instance's directory, or the workspace root when the
// run keeps files without one. The empty string IS the root here, which is
// why the tab's gate is the topic rather than a truthy path.
- const { data: sandboxInstances } = useSWR(
- isSandboxExecution && sandboxInstanceId ? ['sandbox-instance-dir', sandboxInstanceId] : null,
- () => sandboxStorageService.getInstance({ id: sandboxInstanceId! }),
- );
- const sandboxDirectory = sandboxInstances?.workingDirectory ?? '';
+ // A replica, so a reload paints the directory (and the Files tab) from the
+ // last answer; `null` is an instance known to be gone.
+ const sandboxDirectoryId = isSandboxExecution ? sandboxInstanceId : undefined;
+ sandboxActions.useFetchInstanceDirectory(sandboxDirectoryId);
+ const sandboxDir = useSandboxStore(sandboxSelectors.instanceDirectory(sandboxDirectoryId));
+ const sandboxDirectory = sandboxDir ?? '';
// The empty string IS the workspace root, so an unresolved instance does not
// read as "no directory yet" — it reads as "the whole workspace", and the
// tree would list every instance's folder for as long as the lookup took.
- const sandboxDirectoryKnown = !sandboxInstanceId || sandboxInstances !== undefined;
+ const sandboxDirectoryKnown = !sandboxInstanceId || sandboxDir !== undefined;
const filesystemEnvironmentAvailable = isLocalExecution || isDeviceMode;
const environmentWorkingDirectory = filesystemEnvironmentAvailable ? workingDirectory : undefined;
diff --git a/src/features/EnvironmentManager/EnvironmentsGate.tsx b/src/features/EnvironmentManager/EnvironmentsGate.tsx
index 795684a0701..2a7e15d2b44 100644
--- a/src/features/EnvironmentManager/EnvironmentsGate.tsx
+++ b/src/features/EnvironmentManager/EnvironmentsGate.tsx
@@ -4,12 +4,10 @@ import { Button, Center, Empty, Flexbox } from '@lobehub/ui';
import { AlertTriangleIcon } from 'lucide-react';
import { memo, type PropsWithChildren } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import { SandboxStorageUpgradeGuide } from '@/business/client/features/SandboxStorageUpsell';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
-import { sandboxStorageService } from '@/services/sandboxStorage';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
/**
* Environments are specifications for a persistent workspace, so the page
@@ -18,17 +16,15 @@ import { sandboxStorageService } from '@/services/sandboxStorage';
* nothing could ever run in.
*
* The entitlement is resolved and signed server-side; asking the server is the
- * only way to see the same answer the sandbox will act on. Same key as the
- * composer's working-directory chip — workspace included, since the server
- * resolves the answer from the active one — so the two never disagree.
+ * only way to see the same answer the sandbox will act on. The same replica
+ * entry as the composer's working-directory chip — partitioned by workspace,
+ * since the server resolves the answer from the active one — so the two never
+ * disagree.
*/
const EnvironmentsGate = memo<PropsWithChildren>(({ children }) => {
const { t } = useTranslation('setting');
- const workspaceId = useActiveWorkspaceId();
- const { data, error, isLoading, mutate } = useSWR(
- ['sandbox-storage-entitlement', workspaceId ?? ''],
- () => sandboxStorageService.getEntitlement(),
- );
+ const { error, revalidate } = sandboxActions.useFetchEntitlement(true);
+ const data = useSandboxStore(sandboxSelectors.entitlement);
// A failed lookup is not an unentitled account, and it is not a slow one
// either: left as a spinner this page is indistinguishable from loading
@@ -44,14 +40,14 @@ const EnvironmentsGate = memo<PropsWithChildren>(({ children }) => {
style={{ maxWidth: 400 }}
title={t('environments.loadFailed.title')}
/>
- <Button onClick={() => void mutate()}>{t('environments.loadFailed.retry')}</Button>
+ <Button onClick={() => void revalidate()}>{t('environments.loadFailed.retry')}</Button>
</Flexbox>
</Center>
);
// Nothing rather than a flash of the upgrade page at a user who turns out to
// be entitled.
- if (isLoading || !data) return <RouteLoading />;
+ if (!data) return <RouteLoading />;
if (!data.entitled) return <SandboxStorageUpgradeGuide />;
return children;
diff --git a/src/features/EnvironmentManager/useCanEditEnvironment.ts b/src/features/EnvironmentManager/useCanEditEnvironment.ts
index 6c43cba2f4a..f4c2f18b329 100644
--- a/src/features/EnvironmentManager/useCanEditEnvironment.ts
+++ b/src/features/EnvironmentManager/useCanEditEnvironment.ts
@@ -22,7 +22,7 @@ export const useCanEditEnvironment = () => {
const currentUserId = useUserStore(userProfileSelectors.userId);
return useCallback(
- (environment: SandboxEnvironment): boolean => {
+ (environment: Pick<SandboxEnvironment, 'userId' | 'workspaceId'>): boolean => {
// Personal environments have no other member to belong to.
if (!environment.workspaceId) return true;
if (!currentUserId) return false;
diff --git a/src/store/sandbox/action.ts b/src/store/sandbox/action.ts
new file mode 100644
index 00000000000..0a940ed5d16
--- /dev/null
+++ b/src/store/sandbox/action.ts
@@ -0,0 +1,91 @@
+import { type ReplicaSyncResult } from '@/libs/replica';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { initialState, type SandboxState } from './initialState';
+import { type InstanceListEdit, SandboxPrivateAction } from './privateAction';
+import { SANDBOX_SCOPE_ENTRY, type SandboxPickerInstanceList } from './projection';
+import { useSandboxStore } from './store';
+
+const n = setNamespace('sandbox');
+
+type Setter = StoreSetter<SandboxState>;
+
+/** How often a building copy is re-listed while the picker can see it. */
+const BUILD_REFRESH_MS = 4000;
+
+interface UseFetchEntitlementOptions {
+ /** Revalidate when the window regains focus. Defaults to `true`. */
+ revalidateOnFocus?: boolean;
+}
+
+export class SandboxActionImpl {
+ readonly #private: SandboxPrivateAction;
+ readonly #set: Setter;
+
+ constructor(set: Setter, _get: () => SandboxState, privateAction: SandboxPrivateAction) {
+ this.#set = set;
+ this.#private = privateAction;
+ }
+
+ /**
+ * The active workspace's sandbox-storage entitlement. Read it with
+ * `sandboxSelectors.entitlement`. The composer and the environments page share
+ * this one entry, so the two never disagree.
+ */
+ useFetchEntitlement = (
+ enabled: boolean,
+ { revalidateOnFocus = true }: UseFetchEntitlementOptions = {},
+ ): ReplicaSyncResult =>
+ this.#private.entitlement.useSync(enabled ? SANDBOX_SCOPE_ENTRY : null, { revalidateOnFocus });
+
+ /** The picker's environments; read them with `sandboxSelectors.pickerEnvironments`. */
+ useFetchPickerEnvironments = (enabled: boolean): ReplicaSyncResult =>
+ this.#private.environments.useSync(enabled ? SANDBOX_SCOPE_ENTRY : null);
+
+ /**
+ * The picker's copies with `topicId`'s occupancy; read them with
+ * `sandboxSelectors.pickerInstances(topicId)`.
+ *
+ * Not refetched on focus: occupancy is re-read each time the menu opens
+ * instead. While a copy is building, the list is polled so "Building" turns
+ * into a usable row on its own.
+ */
+ useFetchPickerInstances = (enabled: boolean, topicId?: string): ReplicaSyncResult =>
+ this.#private.instances.useSync(enabled ? { topicId } : null, {
+ refreshInterval: (latest?: SandboxPickerInstanceList) =>
+ (latest?.instances ?? []).some((instance) => instance.status === 'pending')
+ ? BUILD_REFRESH_MS
+ : 0,
+ revalidateOnFocus: false,
+ });
+
+ /**
+ * Edit the copies on the client (a just-created copy listed as building) and,
+ * unless `revalidate: false`, re-sync them. With no edit it only re-syncs. The
+ * edit stays in memory: only a server answer is persisted.
+ */
+ mutatePickerInstances = async (
+ edit?: InstanceListEdit,
+ { revalidate = true }: { revalidate?: boolean } = {},
+ ): Promise<void> => {
+ if (edit) this.#private.editInstances(edit);
+ if (!edit || revalidate) await this.#private.instances.revalidate(SANDBOX_SCOPE_ENTRY);
+ };
+
+ /** Where a bound instance's files live; read it with `sandboxSelectors.instanceDirectory`. */
+ useFetchInstanceDirectory = (instanceId?: string | null): ReplicaSyncResult =>
+ this.#private.instanceDirectory.useSync(instanceId || null);
+
+ reset = (): void => {
+ this.#set(initialState, false, n('reset'));
+ };
+}
+
+const { getState, setState } = useSandboxStore;
+
+export const sandboxActions = new SandboxActionImpl(
+ setState,
+ getState,
+ new SandboxPrivateAction(setState, getState),
+);
diff --git a/src/store/sandbox/index.ts b/src/store/sandbox/index.ts
new file mode 100644
index 00000000000..5605acd9e45
--- /dev/null
+++ b/src/store/sandbox/index.ts
@@ -0,0 +1,10 @@
+export { sandboxActions } from './action';
+export { type SandboxState } from './initialState';
+export {
+ type SandboxEntitlement,
+ type SandboxPickerEnvironment,
+ type SandboxPickerInstance,
+ type SandboxPickerInstanceList,
+} from './projection';
+export { sandboxSelectors } from './selectors';
+export { useSandboxStore } from './store';
diff --git a/src/store/sandbox/initialState.ts b/src/store/sandbox/initialState.ts
new file mode 100644
index 00000000000..215a30daa92
--- /dev/null
+++ b/src/store/sandbox/initialState.ts
@@ -0,0 +1,34 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type {
+ SandboxEntitlement,
+ SandboxInstanceDirectory,
+ SandboxPickerEnvironment,
+ SandboxPickerInstanceList,
+} from './projection';
+
+export interface SandboxState {
+ /** `sandboxEntitlementMap[SANDBOX_SCOPE_ENTRY]`: the active workspace's answer. */
+ sandboxEntitlementMap: Record<string, SandboxEntitlement>;
+ sandboxEntitlementReplica: ReplicaState<SandboxEntitlement>;
+ /** `sandboxEnvironmentsMap[SANDBOX_SCOPE_ENTRY]`: the picker's environments. */
+ sandboxEnvironmentsMap: Record<string, SandboxPickerEnvironment[]>;
+ sandboxEnvironmentsReplica: ReplicaState<SandboxPickerEnvironment[]>;
+ /** `sandboxInstanceDirectoryMap[instanceId]`: where a bound instance's files live. */
+ sandboxInstanceDirectoryMap: Record<string, SandboxInstanceDirectory>;
+ sandboxInstanceDirectoryReplica: ReplicaState<SandboxInstanceDirectory>;
+ /** `sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]`: the picker's copies. */
+ sandboxInstancesMap: Record<string, SandboxPickerInstanceList>;
+ sandboxInstancesReplica: ReplicaState<SandboxPickerInstanceList>;
+}
+
+export const initialState: SandboxState = {
+ sandboxEntitlementMap: {},
+ sandboxEntitlementReplica: createReplicaState(),
+ sandboxEnvironmentsMap: {},
+ sandboxEnvironmentsReplica: createReplicaState(),
+ sandboxInstanceDirectoryMap: {},
+ sandboxInstanceDirectoryReplica: createReplicaState(),
+ sandboxInstancesMap: {},
+ sandboxInstancesReplica: createReplicaState(),
+};
diff --git a/src/store/sandbox/privateAction.ts b/src/store/sandbox/privateAction.ts
new file mode 100644
index 00000000000..1c718e0bf3c
--- /dev/null
+++ b/src/store/sandbox/privateAction.ts
@@ -0,0 +1,154 @@
+import { createReplicaSlice, recordLens } from '@/libs/replica';
+import { sandboxStorageService } from '@/services/sandboxStorage';
+import type { StoreSetter } from '@/store/types';
+
+import { type SandboxState } from './initialState';
+import {
+ SANDBOX_SCOPE_ENTRY,
+ type SandboxEntitlement,
+ sandboxEntitlementResource,
+ sandboxEnvironmentsResource,
+ type SandboxInstanceDirectory,
+ sandboxInstanceDirectoryResource,
+ sandboxInstancesResource,
+ type SandboxPickerEnvironment,
+ type SandboxPickerInstance,
+ type SandboxPickerInstanceList,
+ toInstanceDirectory,
+ toPickerEnvironment,
+ toPickerInstance,
+ toSandboxEntitlement,
+} from './projection';
+
+type Setter = StoreSetter<SandboxState>;
+
+export type InstanceListEdit = (
+ previous: SandboxPickerInstanceList | undefined,
+) => SandboxPickerInstanceList | undefined;
+
+/** A copy created on this client, and the last listing that started before it. */
+interface LocalCopy {
+ instance: SandboxPickerInstance;
+ since: number;
+}
+
+export class SandboxPrivateAction {
+ readonly #get: () => SandboxState;
+ /** Copies created here that a listing in flight may not know about yet. */
+ readonly #localCopies = new Map<string, LocalCopy>();
+ /** Sequence of `listInstances` calls, so an answer knows when it was asked. */
+ #listSeq = 0;
+ readonly entitlement;
+ readonly environments;
+ readonly instanceDirectory;
+ readonly instances;
+
+ constructor(set: Setter, get: () => SandboxState) {
+ this.#get = get;
+ this.entitlement = createReplicaSlice(sandboxEntitlementResource, {
+ actionPrefix: 'sandboxEntitlement',
+ fetcher: async () => toSandboxEntitlement(await sandboxStorageService.getEntitlement()),
+ get,
+ set,
+ stateKey: 'sandboxEntitlementReplica',
+ view: recordLens<SandboxState, SandboxEntitlement>('sandboxEntitlementMap'),
+ });
+ this.environments = createReplicaSlice(sandboxEnvironmentsResource, {
+ actionPrefix: 'sandboxEnvironments',
+ fetcher: async () => {
+ const { environments } = await sandboxStorageService.listEnvironments();
+ return environments.map(toPickerEnvironment);
+ },
+ get,
+ set,
+ stateKey: 'sandboxEnvironmentsReplica',
+ view: recordLens<SandboxState, SandboxPickerEnvironment[]>('sandboxEnvironmentsMap'),
+ });
+ // The conversation the instance list was last asked for. Every topic shares
+ // one entry and one storage key, so the replica's own guard cannot tell a
+ // superseded topic's late answer from the current one; this does.
+ let askedTopicId: string | null | undefined;
+ this.instances = createReplicaSlice(sandboxInstancesResource, {
+ actionPrefix: 'sandboxInstances',
+ // Names, not sizes: sizes need a live sandbox session to answer.
+ fetcher: async ({ topicId }) => {
+ const asked = topicId ?? null;
+ askedTopicId = asked;
+ const seq = ++this.#listSeq;
+ const { instances } = await sandboxStorageService.listInstances({
+ topicId,
+ withSizes: false,
+ });
+ const answer = {
+ instances: this.#withLocalCopies(instances.map(toPickerInstance), seq),
+ topicId: asked,
+ };
+ // Another conversation was asked for since: keep what the entry holds
+ // rather than let this answer overwrite that conversation's occupancy.
+ if (askedTopicId !== asked) return get().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY] ?? answer;
+
+ return answer;
+ },
+ get,
+ set,
+ stateKey: 'sandboxInstancesReplica',
+ // Only a server answer is persisted: copies merged in from this client
+ // stay in memory until a listing names them.
+ toPersisted: (data) =>
+ this.#localCopies.size === 0
+ ? data
+ : {
+ ...data,
+ instances: data.instances.filter((instance) => !this.#localCopies.has(instance.id)),
+ },
+ view: recordLens<SandboxState, SandboxPickerInstanceList>('sandboxInstancesMap'),
+ });
+ this.instanceDirectory = createReplicaSlice(sandboxInstanceDirectoryResource, {
+ actionPrefix: 'sandboxInstanceDirectory',
+ fetcher: async (id) => toInstanceDirectory(await sandboxStorageService.getInstance({ id })),
+ get,
+ set,
+ stateKey: 'sandboxInstanceDirectoryReplica',
+ // A gone instance is a panel state: never persist it, and evict the
+ // directory persisted earlier so a reload cannot point at it again.
+ toPersisted: (data) => (data.workingDirectory === null ? null : data),
+ view: recordLens<SandboxState, SandboxInstanceDirectory>('sandboxInstanceDirectoryMap'),
+ });
+ }
+
+ /**
+ * Apply a client edit to the copies in memory, remembering any copy it adds.
+ * The copy already exists on the server, so only a listing that started
+ * before the edit can answer without it.
+ */
+ editInstances = (edit: InstanceListEdit) => {
+ const before = new Set(
+ this.#get().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]?.instances.map(({ id }) => id),
+ );
+ this.instances.update(SANDBOX_SCOPE_ENTRY, edit, { persist: false });
+ const after = this.#get().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]?.instances ?? [];
+ for (const instance of after)
+ if (!before.has(instance.id))
+ this.#localCopies.set(instance.id, { instance, since: this.#listSeq });
+ };
+
+ /**
+ * Keep a client-created copy in an answer from a listing that started before
+ * it was made. A listing that started after is authoritative: whether or not
+ * it names the copy, the local record is done.
+ */
+ #withLocalCopies = (instances: SandboxPickerInstance[], seq: number) => {
+ if (this.#localCopies.size === 0) return instances;
+ const listed = new Set(instances.map(({ id }) => id));
+ const merged = [...instances];
+ for (const [id, { instance, since }] of this.#localCopies) {
+ if (listed.has(id) || seq > since) {
+ this.#localCopies.delete(id);
+ continue;
+ }
+ merged.push(instance);
+ }
+
+ return merged;
+ };
+}
diff --git a/src/store/sandbox/projection.ts b/src/store/sandbox/projection.ts
new file mode 100644
index 00000000000..25bb0101c14
--- /dev/null
+++ b/src/store/sandbox/projection.ts
@@ -0,0 +1,178 @@
+import { type EnvironmentKind, environmentKind } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+import type { sandboxStorageService } from '@/services/sandboxStorage';
+
+type RawEnvironment = Awaited<
+ ReturnType<typeof sandboxStorageService.listEnvironments>
+>['environments'][number];
+type RawInstance = Awaited<
+ ReturnType<typeof sandboxStorageService.listInstances>
+>['instances'][number];
+type RawEntitlement = Awaited<ReturnType<typeof sandboxStorageService.getEntitlement>>;
+type RawInstanceDetail = Awaited<ReturnType<typeof sandboxStorageService.getInstance>>;
+
+/**
+ * The cloud-sandbox reads the composer's instance chip, its picker and the
+ * working panel's Files tab paint from. Replicas, so a reload paints the last
+ * confirmed answer on the first frames and the network only confirms it.
+ *
+ * Every value is a slim projection: an environment's configuration carries
+ * `env` and source URLs (a URL can carry a token), and an instance row carries
+ * build logs, so neither reaches storage — only the fields these surfaces read.
+ * Rows are partitioned by the cache scope (user + workspace), which is also the
+ * dimension the server answers the entitlement and both lists from.
+ */
+
+/** The single entry of the scope-wide reads (entitlement and both lists). */
+export const SANDBOX_SCOPE_ENTRY = 'current';
+export type SandboxScopeEntry = typeof SANDBOX_SCOPE_ENTRY;
+
+/**
+ * `{ entitled, quotaBytes }`. Gates the composer's chip and the environments
+ * page; the server still resolves the claim on every sandbox call, so a stale
+ * answer only shapes what is shown until the revalidation lands.
+ */
+export interface SandboxEntitlement {
+ entitled: boolean;
+ quotaBytes: number | null;
+}
+
+export const toSandboxEntitlement = (raw: RawEntitlement): SandboxEntitlement => ({
+ entitled: raw.entitled,
+ quotaBytes: raw.quotaBytes ?? null,
+});
+
+/** What the composer's picker reads of an environment, and nothing more. */
+export interface SandboxPickerEnvironment {
+ id: string;
+ /** Derived from the configuration at the boundary; the configuration is not kept. */
+ kind: EnvironmentKind;
+ name: string;
+ userId: string;
+ visibility: RawEnvironment['visibility'];
+ workspaceId: string | null;
+}
+
+export const toPickerEnvironment = (environment: RawEnvironment): SandboxPickerEnvironment => ({
+ id: environment.id,
+ kind: environmentKind(environment),
+ name: environment.name,
+ userId: environment.userId,
+ visibility: environment.visibility,
+ workspaceId: environment.workspaceId ?? null,
+});
+
+/** A listed copy, as the picker renders it. */
+export interface SandboxPickerInstance {
+ createdAt: string;
+ environmentId: string;
+ id: string;
+ inUse: boolean;
+ inUseByThisTopic: boolean;
+ isDefault: boolean;
+ name: string;
+ status: RawInstance['status'];
+ workingDirectory: string;
+}
+
+/**
+ * The instance list and the conversation its occupancy was answered for.
+ *
+ * One entry for the whole scope rather than one per topic: the copies are the
+ * same list from every conversation, and only `inUseByThisTopic` depends on the
+ * asking topic. Keyed per topic, every conversation visited would persist its
+ * own full copy of the list. The selector reads `inUseByThisTopic` only when
+ * `topicId` is the conversation on screen.
+ */
+export interface SandboxPickerInstanceList {
+ instances: SandboxPickerInstance[];
+ /** The topic `inUseByThisTopic` was answered for; `null` before the first send. */
+ topicId: string | null;
+}
+
+export const toPickerInstance = (
+ instance: Pick<
+ RawInstance,
+ | 'createdAt'
+ | 'environmentId'
+ | 'id'
+ | 'inUse'
+ | 'inUseByThisTopic'
+ | 'isDefault'
+ | 'name'
+ | 'status'
+ | 'workingDirectory'
+ >,
+): SandboxPickerInstance => ({
+ createdAt: new Date(instance.createdAt).toISOString(),
+ environmentId: instance.environmentId,
+ id: instance.id,
+ inUse: instance.inUse,
+ inUseByThisTopic: instance.inUseByThisTopic,
+ isDefault: instance.isDefault,
+ name: instance.name,
+ status: instance.status,
+ workingDirectory: instance.workingDirectory,
+});
+
+/**
+ * Where a bound instance's files live: all the working panel reads of it.
+ * `workingDirectory: null` is the server's "this instance is gone" — a value the
+ * panel settles on, never persisted.
+ */
+export interface SandboxInstanceDirectory {
+ workingDirectory: string | null;
+}
+
+export const toInstanceDirectory = (instance: RawInstanceDetail): SandboxInstanceDirectory => ({
+ workingDirectory: instance ? instance.workingDirectory : null,
+});
+
+export interface SandboxInstancesParams {
+ /** Topic whose occupancy the listing answers; absent before the first send. */
+ topicId?: string;
+}
+
+export const sandboxEntitlementResource = defineReplica<SandboxScopeEntry, SandboxEntitlement>({
+ key: (entry) => entry,
+ name: 'sandboxEntitlement',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export const sandboxEnvironmentsResource = defineReplica<
+ SandboxScopeEntry,
+ SandboxPickerEnvironment[]
+>({
+ key: (entry) => entry,
+ name: 'sandboxPickerEnvironments',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Keyed by the scope alone (see {@link SandboxPickerInstanceList}); the sync key
+ * still carries the topic, so moving to another conversation re-asks the
+ * server for that conversation's occupancy.
+ */
+export const sandboxInstancesResource = defineReplica<
+ SandboxInstancesParams,
+ SandboxPickerInstanceList
+>({
+ key: () => SANDBOX_SCOPE_ENTRY,
+ name: 'sandboxPickerInstances',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Instances a user binds conversations to; old ones fall out of storage only. */
+const MAX_PERSISTED_INSTANCE_DIRECTORIES = 20;
+
+export const sandboxInstanceDirectoryResource = defineReplica<string, SandboxInstanceDirectory>({
+ key: (instanceId) => instanceId,
+ name: 'sandboxInstanceDirectory',
+ persist: { maxEntries: MAX_PERSISTED_INSTANCE_DIRECTORIES },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/sandbox/replica.test.ts b/src/store/sandbox/replica.test.ts
new file mode 100644
index 00000000000..30d94a902ee
--- /dev/null
+++ b/src/store/sandbox/replica.test.ts
@@ -0,0 +1,480 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The cloud-sandbox entitlement, the composer picker's environment and
+ * instance lists and a bound instance's directory are `@lobechat/replica`
+ * resources: a cold start paints the persisted answer while the network
+ * confirms it, only slim projections reach storage, the instance list is one
+ * row however many conversations ask, and scopes stay isolated.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, readReplicaStoredKeys } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { sandboxStorageService } from '@/services/sandboxStorage';
+
+import { sandboxActions } from './action';
+import { initialState } from './initialState';
+import {
+ SANDBOX_SCOPE_ENTRY,
+ sandboxEntitlementResource,
+ sandboxEnvironmentsResource,
+ sandboxInstanceDirectoryResource,
+ sandboxInstancesResource,
+ type SandboxPickerInstance,
+} from './projection';
+import { sandboxSelectors } from './selectors';
+import { useSandboxStore } from './store';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+type ListedEnvironments = Awaited<ReturnType<typeof sandboxStorageService.listEnvironments>>;
+type ListedInstances = Awaited<ReturnType<typeof sandboxStorageService.listInstances>>;
+type InstanceDetail = Awaited<ReturnType<typeof sandboxStorageService.getInstance>>;
+
+const rawEnvironment = {
+ configuration: {
+ env: { API_TOKEN: 'secret-value' },
+ sources: [
+ { kind: 'git', url: 'https://x-access-token:[email protected]/lobehub/lobehub.git' },
+ ],
+ },
+ createdAt: new Date('2026-10-01'),
+ description: null,
+ id: 'env-1',
+ name: 'Lobehub Dev',
+ updatedAt: new Date('2026-10-01'),
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+};
+
+const rawInstance = (overrides: Record<string, unknown> = {}) => ({
+ buildError: 'npm ERR! token=secret-in-log',
+ buildId: null,
+ buildable: true,
+ configurationSnapshot: { env: { API_TOKEN: 'secret-value' } },
+ createdAt: new Date('2026-10-01T00:00:00Z'),
+ environmentId: 'env-1',
+ id: 'inst-1',
+ inUse: false,
+ inUseByThisTopic: false,
+ isDefault: true,
+ name: 'main-checkout',
+ snapshot: null,
+ status: 'ready',
+ workingDirectory: 'lobehub-main',
+ ...overrides,
+});
+
+const listed = (...instances: ReturnType<typeof rawInstance>[]) =>
+ ({ instances, occupancyUnavailable: false }) as unknown as ListedInstances;
+
+const pickerInstance = (overrides: Partial<SandboxPickerInstance> = {}): SandboxPickerInstance => ({
+ createdAt: '2026-10-01T00:00:00.000Z',
+ environmentId: 'env-1',
+ id: 'inst-1',
+ inUse: false,
+ inUseByThisTopic: false,
+ isDefault: true,
+ name: 'main-checkout',
+ status: 'ready',
+ workingDirectory: 'lobehub-main',
+ ...overrides,
+});
+
+const state = () => useSandboxStore.getState();
+
+describe('sandbox replicas', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ const resources = [
+ sandboxEntitlementResource,
+ sandboxEnvironmentsResource,
+ sandboxInstancesResource,
+ sandboxInstanceDirectoryResource,
+ ] as const;
+
+ const stored = async (
+ resource: (typeof resources)[number],
+ queryKey = SANDBOX_SCOPE_ENTRY as string,
+ ) => (await resource.storage!.get({ queryKey, scope }))?.data;
+
+ beforeEach(() => {
+ useScope(`sandbox-user-${randomUUID()}:ws-1`);
+ useSandboxStore.setState({ ...initialState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ resources.flatMap((resource) =>
+ [SANDBOX_SCOPE_ENTRY, 'inst-1', 'inst-gone'].map((queryKey) =>
+ resource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('paints the entitlement, both picker lists and the directory before the network answers', async () => {
+ await sandboxEntitlementResource.storage!.set(
+ { queryKey: SANDBOX_SCOPE_ENTRY, scope },
+ { data: { entitled: true, quotaBytes: 1024 }, updatedAt: 1 },
+ );
+ await sandboxEnvironmentsResource.storage!.set(
+ { queryKey: SANDBOX_SCOPE_ENTRY, scope },
+ {
+ data: [
+ {
+ id: 'env-1',
+ kind: 'code',
+ name: 'Lobehub Dev',
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ },
+ ],
+ updatedAt: 1,
+ },
+ );
+ await sandboxInstancesResource.storage!.set(
+ { queryKey: SANDBOX_SCOPE_ENTRY, scope },
+ { data: { instances: [pickerInstance()], topicId: 'topic-1' }, updatedAt: 1 },
+ );
+ await sandboxInstanceDirectoryResource.storage!.set(
+ { queryKey: 'inst-1', scope },
+ { data: { workingDirectory: 'lobehub-main' }, updatedAt: 1 },
+ );
+ vi.spyOn(sandboxStorageService, 'getEntitlement').mockImplementation(pending);
+ vi.spyOn(sandboxStorageService, 'listEnvironments').mockImplementation(pending);
+ vi.spyOn(sandboxStorageService, 'listInstances').mockImplementation(pending);
+ vi.spyOn(sandboxStorageService, 'getInstance').mockImplementation(pending);
+
+ renderHook(
+ () => {
+ sandboxActions.useFetchEntitlement(true);
+ sandboxActions.useFetchPickerEnvironments(true);
+ sandboxActions.useFetchPickerInstances(true, 'topic-1');
+ sandboxActions.useFetchInstanceDirectory('inst-1');
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(sandboxSelectors.entitlement(state())?.entitled).toBe(true));
+ await waitFor(() =>
+ expect(sandboxSelectors.pickerEnvironments(state())?.[0].name).toBe('Lobehub Dev'),
+ );
+ await waitFor(() =>
+ expect(sandboxSelectors.pickerInstances('topic-1')(state())?.[0].name).toBe('main-checkout'),
+ );
+ await waitFor(() =>
+ expect(sandboxSelectors.instanceDirectory('inst-1')(state())).toBe('lobehub-main'),
+ );
+ });
+
+ it('persists only the slim projections: no configuration, env, source URL or build log', async () => {
+ vi.spyOn(sandboxStorageService, 'listEnvironments').mockResolvedValue({
+ environments: [rawEnvironment],
+ } as unknown as ListedEnvironments);
+ vi.spyOn(sandboxStorageService, 'listInstances').mockResolvedValue(listed(rawInstance()));
+ vi.spyOn(sandboxStorageService, 'getInstance').mockResolvedValue(
+ rawInstance() as unknown as InstanceDetail,
+ );
+
+ renderHook(
+ () => {
+ sandboxActions.useFetchPickerEnvironments(true);
+ sandboxActions.useFetchPickerInstances(true, 'topic-1');
+ sandboxActions.useFetchInstanceDirectory('inst-1');
+ },
+ { wrapper },
+ );
+
+ await waitFor(async () => expect(await stored(sandboxEnvironmentsResource)).toHaveLength(1));
+ await waitFor(async () => expect(await stored(sandboxInstancesResource)).toBeDefined());
+ await waitFor(async () =>
+ expect(await stored(sandboxInstanceDirectoryResource, 'inst-1')).toBeDefined(),
+ );
+
+ expect(await stored(sandboxEnvironmentsResource)).toEqual([
+ {
+ id: 'env-1',
+ kind: 'code',
+ name: 'Lobehub Dev',
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ },
+ ]);
+ expect(await stored(sandboxInstanceDirectoryResource, 'inst-1')).toEqual({
+ workingDirectory: 'lobehub-main',
+ });
+
+ const payload = JSON.stringify([
+ await stored(sandboxEnvironmentsResource),
+ await stored(sandboxInstancesResource),
+ await stored(sandboxInstanceDirectoryResource, 'inst-1'),
+ ]);
+ for (const leaked of ['configuration', 'secret', 'ghp_', 'buildError', 'npm ERR']) {
+ expect(payload).not.toContain(leaked);
+ }
+ });
+
+ // Regression: keyed per topic, every conversation visited persisted its own
+ // full copy of the instance list.
+ it('keeps one persisted instance list however many conversations ask', async () => {
+ const listInstances = vi
+ .spyOn(sandboxStorageService, 'listInstances')
+ .mockImplementation(async ({ topicId } = {}) =>
+ listed(rawInstance({ inUse: true, inUseByThisTopic: topicId === 'topic-1' })),
+ );
+
+ const { rerender } = renderHook(
+ ({ topicId }) => sandboxActions.useFetchPickerInstances(true, topicId),
+ { initialProps: { topicId: 'topic-1' }, wrapper },
+ );
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.topicId).toBe('topic-1'),
+ );
+
+ rerender({ topicId: 'topic-2' });
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.topicId).toBe('topic-2'),
+ );
+
+ expect(listInstances).toHaveBeenCalledWith({ topicId: 'topic-2', withSizes: false });
+ expect(await readReplicaStoredKeys(sandboxInstancesResource)).toEqual([SANDBOX_SCOPE_ENTRY]);
+ });
+
+ // Regression: every topic shares one entry and one storage key, so the
+ // replica's own guard could not tell topic-1's late answer from topic-2's and
+ // let it overwrite topic-2's — the selector then masked topic-2's own copy as
+ // held by another conversation until the next revalidation.
+ it('drops a superseded conversation’s answer that lands after the current one', async () => {
+ let answerTopic1!: () => void;
+ vi.spyOn(sandboxStorageService, 'listInstances').mockImplementation(({ topicId } = {}) => {
+ const answer = listed(rawInstance({ inUse: true, inUseByThisTopic: true }));
+ if (topicId !== 'topic-1') return Promise.resolve(answer);
+ return new Promise((resolve) => {
+ answerTopic1 = () => resolve(answer);
+ });
+ });
+
+ const { rerender } = renderHook(
+ ({ topicId }) => sandboxActions.useFetchPickerInstances(true, topicId),
+ { initialProps: { topicId: 'topic-1' }, wrapper },
+ );
+ await waitFor(() => expect(answerTopic1).toBeTypeOf('function'));
+
+ rerender({ topicId: 'topic-2' });
+ await waitFor(() =>
+ expect(state().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]?.topicId).toBe('topic-2'),
+ );
+
+ await act(async () => {
+ answerTopic1();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(state().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]?.topicId).toBe('topic-2');
+ expect(sandboxSelectors.pickerInstances('topic-2')(state())?.[0].inUseByThisTopic).toBe(true);
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.topicId).toBe('topic-2'),
+ );
+ });
+
+ it('never reads another conversation’s answer as this one holding the copy', () => {
+ useSandboxStore.setState({
+ sandboxInstancesMap: {
+ [SANDBOX_SCOPE_ENTRY]: {
+ instances: [pickerInstance({ inUse: true, inUseByThisTopic: true })],
+ topicId: 'topic-1',
+ },
+ },
+ });
+
+ expect(sandboxSelectors.pickerInstances('topic-1')(state())?.[0].inUseByThisTopic).toBe(true);
+ // Held by topic-1: from topic-2 it is somebody else's run until topic-2's answer lands.
+ expect(sandboxSelectors.pickerInstances('topic-2')(state())?.[0]).toMatchObject({
+ inUse: true,
+ inUseByThisTopic: false,
+ });
+ expect(sandboxSelectors.pickerInstances(undefined)(state())?.[0].inUseByThisTopic).toBe(false);
+ });
+
+ // Regression: a listing already in flight when a copy is created answered
+ // without it, and replacing the whole entry erased the "Building" row (and
+ // the chip bound to it) until the next listing.
+ it('keeps a just-created copy when a listing that started before it lands', async () => {
+ let answerOld!: () => void;
+ const listInstances = vi
+ .spyOn(sandboxStorageService, 'listInstances')
+ .mockResolvedValueOnce(listed(rawInstance()))
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ answerOld = () => resolve(listed(rawInstance()));
+ }),
+ );
+ renderHook(() => sandboxActions.useFetchPickerInstances(true, 'topic-1'), { wrapper });
+ await waitFor(() =>
+ expect(state().sandboxInstancesMap[SANDBOX_SCOPE_ENTRY]?.instances).toHaveLength(1),
+ );
+
+ // A revalidation starts, then the copy is created while it is in flight.
+ const revalidating = sandboxActions.mutatePickerInstances();
+ await waitFor(() => expect(answerOld).toBeTypeOf('function'));
+ await act(() =>
+ sandboxActions.mutatePickerInstances(
+ (previous) =>
+ previous && {
+ ...previous,
+ instances: [
+ ...previous.instances,
+ pickerInstance({ id: 'inst-2', isDefault: false, status: 'pending' }),
+ ],
+ },
+ { revalidate: false },
+ ),
+ );
+
+ await act(async () => {
+ answerOld();
+ await revalidating;
+ });
+
+ const ids = () =>
+ sandboxSelectors
+ .pickerInstances('topic-1')(state())
+ ?.map((i) => i.id);
+ expect(ids()).toEqual(['inst-1', 'inst-2']);
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.instances.map((i) => i.id)).toEqual([
+ 'inst-1',
+ ]),
+ );
+
+ // A listing that started after the creation is authoritative: if it does
+ // not list the copy, the copy is gone.
+ listInstances.mockResolvedValue(listed(rawInstance()));
+ await act(() => sandboxActions.mutatePickerInstances());
+ await waitFor(() => expect(ids()).toEqual(['inst-1']));
+ });
+
+ it('keeps a just-created copy in memory until the server lists it', async () => {
+ const listInstances = vi
+ .spyOn(sandboxStorageService, 'listInstances')
+ .mockResolvedValue(listed(rawInstance()));
+ renderHook(() => sandboxActions.useFetchPickerInstances(true, 'topic-1'), { wrapper });
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.instances).toHaveLength(1),
+ );
+
+ await act(() =>
+ sandboxActions.mutatePickerInstances(
+ (previous) =>
+ previous && {
+ ...previous,
+ instances: [
+ ...previous.instances,
+ pickerInstance({ id: 'inst-2', isDefault: false, status: 'pending' }),
+ ],
+ },
+ { revalidate: false },
+ ),
+ );
+
+ expect(
+ sandboxSelectors
+ .pickerInstances('topic-1')(state())
+ ?.map((i) => i.id),
+ ).toEqual(['inst-1', 'inst-2']);
+ expect((await stored(sandboxInstancesResource))?.instances.map((i) => i.id)).toEqual([
+ 'inst-1',
+ ]);
+
+ listInstances.mockResolvedValue(
+ listed(rawInstance(), rawInstance({ id: 'inst-2', isDefault: false })),
+ );
+ await act(() => sandboxActions.mutatePickerInstances());
+ await waitFor(async () =>
+ expect((await stored(sandboxInstancesResource))?.instances.map((i) => i.id)).toEqual([
+ 'inst-1',
+ 'inst-2',
+ ]),
+ );
+ });
+
+ it('settles on a gone instance without persisting it, and forgets its old directory', async () => {
+ await sandboxInstanceDirectoryResource.storage!.set(
+ { queryKey: 'inst-gone', scope },
+ { data: { workingDirectory: 'old-dir' }, updatedAt: 1 },
+ );
+ vi.spyOn(sandboxStorageService, 'getInstance').mockResolvedValue(null);
+
+ renderHook(() => sandboxActions.useFetchInstanceDirectory('inst-gone'), { wrapper });
+
+ await waitFor(() =>
+ expect(sandboxSelectors.instanceDirectory('inst-gone')(state())).toBeNull(),
+ );
+ await waitFor(async () =>
+ expect(await stored(sandboxInstanceDirectoryResource, 'inst-gone')).toBeUndefined(),
+ );
+ });
+
+ it('drops the previous workspace’s entitlement on a scope switch', async () => {
+ const getEntitlement = vi
+ .spyOn(sandboxStorageService, 'getEntitlement')
+ .mockResolvedValue({ entitled: true, quotaBytes: 1024 });
+ const { rerender } = renderHook(() => sandboxActions.useFetchEntitlement(true), { wrapper });
+ await waitFor(() => expect(sandboxSelectors.entitlement(state())?.entitled).toBe(true));
+
+ useScope(`${scope.split(':')[0]}:ws-2`);
+ getEntitlement.mockImplementation(pending);
+ rerender();
+
+ expect(sandboxSelectors.entitlement(state())).toBeUndefined();
+ });
+
+ it('resets with the other user-data stores', () => {
+ useSandboxStore.setState({
+ sandboxEntitlementMap: { [SANDBOX_SCOPE_ENTRY]: { entitled: true, quotaBytes: null } },
+ });
+
+ sandboxActions.reset();
+
+ expect(sandboxSelectors.entitlement(state())).toBeUndefined();
+ });
+});
diff --git a/src/store/sandbox/selectors.ts b/src/store/sandbox/selectors.ts
new file mode 100644
index 00000000000..6e6d62d2f0e
--- /dev/null
+++ b/src/store/sandbox/selectors.ts
@@ -0,0 +1,53 @@
+import type { SandboxState } from './initialState';
+import {
+ SANDBOX_SCOPE_ENTRY,
+ type SandboxEntitlement,
+ type SandboxPickerEnvironment,
+ type SandboxPickerInstance,
+} from './projection';
+
+/** The active workspace's entitlement, or `undefined` before its first paint. */
+const entitlement = (s: SandboxState): SandboxEntitlement | undefined =>
+ s.sandboxEntitlementMap[SANDBOX_SCOPE_ENTRY];
+
+/** The picker's environments, or `undefined` before their first paint. */
+const pickerEnvironments = (s: SandboxState): SandboxPickerEnvironment[] | undefined =>
+ s.sandboxEnvironmentsMap[SANDBOX_SCOPE_ENTRY];
+
+/**
+ * The picker's copies as `topicId` sees them, or `undefined` before their first
+ * paint.
+ *
+ * The list is shared by every conversation and only "held by this
+ * conversation" depends on which one asked. Until this topic's own answer
+ * lands, a copy held by the conversation that last asked reads as held by
+ * another one: the cautious reading, since the lease is real either way and
+ * the refetch for this topic settles it.
+ */
+const pickerInstances =
+ (topicId?: string) =>
+ (s: SandboxState): SandboxPickerInstance[] | undefined => {
+ const list = s.sandboxInstancesMap[SANDBOX_SCOPE_ENTRY];
+ if (!list) return undefined;
+ if (list.topicId === (topicId ?? null)) return list.instances;
+
+ return list.instances.map((instance) =>
+ instance.inUseByThisTopic ? { ...instance, inUseByThisTopic: false } : instance,
+ );
+ };
+
+/**
+ * A bound instance's directory: a string once known, `null` when the instance
+ * is gone, `undefined` while unknown.
+ */
+const instanceDirectory =
+ (instanceId?: string | null) =>
+ (s: SandboxState): string | null | undefined =>
+ instanceId ? s.sandboxInstanceDirectoryMap[instanceId]?.workingDirectory : undefined;
+
+export const sandboxSelectors = {
+ entitlement,
+ instanceDirectory,
+ pickerEnvironments,
+ pickerInstances,
+};
diff --git a/src/store/sandbox/store.ts b/src/store/sandbox/store.ts
new file mode 100644
index 00000000000..3ce10870d7f
--- /dev/null
+++ b/src/store/sandbox/store.ts
@@ -0,0 +1,15 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { expose } from '../middleware/expose';
+import { initialState, type SandboxState } from './initialState';
+
+const devtools = createDevtools('sandbox');
+
+export const useSandboxStore = createWithEqualityFn<SandboxState>()(
+ devtools(() => initialState),
+ shallow,
+);
+
+expose('sandbox', useSandboxStore);
diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.ts
index b14fa3e5346..d1791dad141 100644
--- a/src/store/utils/userDataStores.test.ts
+++ b/src/store/utils/userDataStores.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const resetGatewayMuxRegistry = vi.hoisted(() => vi.fn());
const storeResets = vi.hoisted(() => [] as Array<() => void>);
const pageReset = vi.hoisted(() => vi.fn());
+const sandboxReset = vi.hoisted(() => vi.fn());
const fakeStore = vi.hoisted(() => () => ({
getState: () => {
const reset = vi.fn();
@@ -28,6 +29,7 @@ vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: fakeStore() }));
vi.mock('@/store/mention', () => ({ useMentionStore: fakeStore() }));
vi.mock('@/store/notebook', () => ({ useNotebookStore: fakeStore() }));
vi.mock('@/store/page', () => ({ pageActions: { reset: pageReset } }));
+vi.mock('@/store/sandbox', () => ({ sandboxActions: { reset: sandboxReset } }));
vi.mock('@/store/session', () => ({ useSessionStore: fakeStore() }));
vi.mock('@/store/task', () => ({ useTaskStore: fakeStore() }));
vi.mock('@/store/tool', () => ({ useToolStore: fakeStore() }));
@@ -40,6 +42,7 @@ describe('stores.reset', () => {
resetGatewayMuxRegistry.mockClear();
storeResets.length = 0;
pageReset.mockClear();
+ sandboxReset.mockClear();
});
it('tears down the gateway mux registry before wiping the user-data stores', async () => {
@@ -52,6 +55,7 @@ describe('stores.reset', () => {
expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);
expect(storeResets).toHaveLength(18);
expect(pageReset).toHaveBeenCalledTimes(1);
+ expect(sandboxReset).toHaveBeenCalledTimes(1);
for (const reset of storeResets) expect(reset).toHaveBeenCalledTimes(1);
expect(order[0]).toBe('mux');
});
diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.ts
index 7eac7d5bbe1..523f49cc8ba 100644
--- a/src/store/utils/userDataStores.ts
+++ b/src/store/utils/userDataStores.ts
@@ -15,6 +15,7 @@ import { useKnowledgeBaseStore } from '@/store/library';
import { useMentionStore } from '@/store/mention';
import { useNotebookStore } from '@/store/notebook';
import { pageActions } from '@/store/page';
+import { sandboxActions } from '@/store/sandbox';
import { useSessionStore } from '@/store/session';
import { useTaskStore } from '@/store/task';
import { useToolStore } from '@/store/tool';
@@ -48,7 +49,7 @@ const resetableStores: ResetableStoreApi[] = [
useVideoStore,
];
-const resetableActions: ResetableStore[] = [agentDocumentActions, pageActions];
+const resetableActions: ResetableStore[] = [agentDocumentActions, pageActions, sandboxActions];
export interface StoreActions extends ResetableStore {}