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(environment): move the environments page onto the sandbox environments replica (#22875)

Arvin Xu3f9db6a5817b
diff --git a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx
index e1e70e6cc03..2d8a2b1f4de 100644
--- a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx
+++ b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx
@@ -30,6 +30,7 @@ import UserAvatar from '@/components/UserAvatar';
import EnvironmentForm, { type EnvironmentFormSection } from './EnvironmentForm';
import PanelSection from './PanelSection';
import { repositoryPath } from './repository';
+import { EnvironmentDefinitionSkeleton } from './Skeleton';
import TabPane from './TabPane';
import { useCanEditEnvironment } from './useCanEditEnvironment';
import { type SandboxEnvironment, useEnvironmentActions } from './useEnvironmentData';
@@ -88,7 +89,7 @@ interface EnvironmentDetailPanelProps {
* comparing six.
*
* Read by id from the list rather than handed a snapshot: the form writes
- * through to the same SWR entry, so a copy taken at open time would go stale
+ * through to the same replica entry, so a copy taken at open time would go stale
* the moment someone saved.
*/
const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment, onClose }) => {
@@ -100,6 +101,10 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,
const [picked, setTab] = useState<DetailTab>();
// An editor works in the definition; a reader only has the summary.
const tab: DetailTab = canEdit ? (picked === 'variables' ? 'variables' : 'settings') : 'overview';
+ // A row restored from storage has no configuration until the server answers:
+ // it carries `env`, so it is never stored. The definition waits for it rather
+ // than reading as empty β€” an editor saving over `{}` would erase it.
+ const configurationPending = environment.configuration === undefined;
const configuration = environment.configuration ?? {};
const repository = repositoryPath(configuration);
@@ -199,7 +204,9 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,
sections and meets the next one's icon exactly, so any space
between them would show as a break in the line. */}
<Flexbox>
- {tab === 'overview' && (
+ {configurationPending && <EnvironmentDefinitionSkeleton />}
+
+ {!configurationPending && tab === 'overview' && (
<TabPane desc={t('environments.detail.initializerDesc')}>
<PanelSection icon={FolderGit2Icon} title={t('environments.form.sources')}>
<Text fontSize={13}>{repository ?? t('environments.detail.noRepository')}</Text>
@@ -214,7 +221,7 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,
{/* Every field saves itself, so nothing is lost by unmounting the
form on a tab switch and each tab mounts only what it shows. */}
- {canEdit && (tab === 'variables' || tab === 'settings') && (
+ {!configurationPending && canEdit && (tab === 'variables' || tab === 'settings') && (
<EnvironmentForm
environment={environment}
section={tab}
diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsx
index 31f6dced47c..35d4ecc116a 100644
--- a/src/features/EnvironmentManager/EnvironmentItem.tsx
+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx
@@ -127,7 +127,10 @@ const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, sel
const actions = useEnvironmentActions();
const canEdit = useCanEditEnvironment()(environment);
- const repository = repositoryPath(environment.configuration);
+ // A row restored from storage carries only its plain `owner/name`.
+ const repository = environment.configuration
+ ? repositoryPath(environment.configuration)
+ : environment.repository;
const creator =
environment.creator?.fullName ||
environment.creator?.username ||
diff --git a/src/features/EnvironmentManager/Skeleton.tsx b/src/features/EnvironmentManager/Skeleton.tsx
index ea6f96402b3..ce9f1c817ca 100644
--- a/src/features/EnvironmentManager/Skeleton.tsx
+++ b/src/features/EnvironmentManager/Skeleton.tsx
@@ -34,6 +34,19 @@ export const EnvironmentListSkeleton = () => (
</Flexbox>
);
+/**
+ * The detail panel's definition while only the stored row is known: the row
+ * keeps no configuration, so its sections wait for the server's answer.
+ */
+export const EnvironmentDefinitionSkeleton = () => (
+ <Flexbox aria-busy data-testid={'environment-definition-skeleton'} gap={12} paddingBlock={8}>
+ <SkeletonBar height={16} width={'40%'} />
+ <SkeletonBar height={32} width={'100%'} />
+ <SkeletonBar height={16} width={'30%'} />
+ <SkeletonBar height={32} width={'100%'} />
+ </Flexbox>
+);
+
/**
* `EnvironmentManager` before its chunk loads: the heading row (pool tabs, or
* the section name, then refresh + create) above the list frame. `leading`
diff --git a/src/features/EnvironmentManager/index.tsx b/src/features/EnvironmentManager/index.tsx
index f8fddf8d351..3eda8c012b7 100644
--- a/src/features/EnvironmentManager/index.tsx
+++ b/src/features/EnvironmentManager/index.tsx
@@ -12,7 +12,7 @@ import {
Text,
} from '@lobehub/ui';
import { ContainerIcon, PlusIcon, RefreshCwIcon } from 'lucide-react';
-import { memo, type ReactNode, useEffect, useState } from 'react';
+import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
@@ -92,30 +92,17 @@ interface EnvironmentManagerProps {
const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility }) => {
const { t } = useTranslation('setting');
- const { data, error, isValidating, mutate } = useEnvironments(visibility);
+ // `settled`: a list to paint β€” the stored one on a reload, confirmed behind
+ // it, a tab switch included. A stored empty list waits for the server.
+ const { environments, error, revalidate, settled } = useEnvironments(visibility);
const [selectedId, setSelectedId] = useState<string>();
// Whether a refresh the user asked for is still running.
const [refreshing, setRefreshing] = useState(false);
- /**
- * Whether the first fetch of THIS mount has come back.
- *
- * A pool visited earlier is still in SWR's cache, so switching back to it
- * rendered last time's answer instantly and revalidated behind the scenes β€”
- * no skeleton, no sign anything was happening, and a list that may already
- * have been wrong. Switching tabs is the question being asked again, so it
- * waits for the new answer. Only the first fetch after a mount gates; later
- * background revalidations must not throw away a list the reader is using.
- */
- const [ready, setReady] = useState(false);
-
- useEffect(() => {
- if (!isValidating) setReady(true);
- }, [isValidating]);
- const environments = data?.environments ?? [];
+ const list = environments ?? [];
const selected = selectedId
- ? environments.find((environment) => environment.id === selectedId)
+ ? list.find((environment) => environment.id === selectedId)
: undefined;
const select = (id: string) => {
@@ -127,14 +114,14 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })
const onEnvironmentCreated = (created: CreatedEnvironment) => setSelectedId(created.id);
/**
- * The spinner is driven by this call rather than by SWR's `isValidating`,
- * which is true of every fetch the page makes β€” read off that flag the button
- * would spin on a tab switch and on any background revalidation.
+ * The spinner is driven by this call rather than by `isValidating`, which is
+ * true of every fetch the page makes β€” read off that flag the button would
+ * spin on a tab switch and on any background revalidation.
*/
const refresh = async () => {
setRefreshing(true);
try {
- await mutate();
+ await revalidate();
} finally {
setRefreshing(false);
}
@@ -167,16 +154,15 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })
</Flexbox>
);
- const list = (
+ const content = (
<AsyncBoundary
- // Both gated on the same signal, because the boundary reads `data` as
- // "has anything settled": handing it the cache while saying the fetch is
- // still running would show that cache, which is the thing being avoided.
- data={ready ? data : undefined}
+ // A failed background refresh keeps the list it has: the boundary shows
+ // the error only while nothing has settled.
+ data={settled ? environments : undefined}
error={error}
errorVariant={'block'}
- isEmpty={environments.length === 0}
- isLoading={!ready}
+ isEmpty={settled && list.length === 0}
+ isLoading={!settled && !error}
loading={<EnvironmentListSkeleton />}
empty={
// Inside the same frame the rows land in, sized to the skeleton's
@@ -209,7 +195,7 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })
<Flexbox horizontal align={'flex-start'} gap={16} wrap={'wrap'}>
<Flexbox className={styles.listCol} flex={'1 1 320px'}>
<Flexbox className={styles.listScroll} gap={2} padding={4}>
- {environments.map((environment) => (
+ {list.map((environment) => (
<EnvironmentItem
environment={environment}
key={environment.id}
@@ -252,7 +238,7 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })
)}
{actions}
</Flexbox>
- {list}
+ {content}
</Flexbox>
);
});
diff --git a/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.ts b/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.ts
deleted file mode 100644
index e3fb377abaa..00000000000
--- a/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { environmentService } from '@/services/environment';
-
-import { useEnvironmentActions } from './useEnvironmentData';
-
-const swr = vi.hoisted(() => ({ mutate: vi.fn() }));
-
-vi.mock('swr', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- useSWRConfig: () => ({ mutate: swr.mutate }),
-}));
-
-vi.mock('@/services/environment', () => ({
- environmentService: { setEnvironmentVisibility: vi.fn() },
-}));
-
-describe('useEnvironmentActions.setEnvironmentVisibility', () => {
- beforeEach(() => {
- swr.mutate.mockReset().mockResolvedValue(undefined);
- vi.mocked(environmentService.setEnvironmentVisibility).mockResolvedValue({} as any);
- });
-
- it('should refresh every environment list, since publishing moves a row between them', async () => {
- const { result } = renderHook(() => useEnvironmentActions());
-
- await act(async () => {
- await result.current.setEnvironmentVisibility({ id: 'env-1', visibility: 'private' });
- });
-
- expect(environmentService.setEnvironmentVisibility).toHaveBeenCalledWith({
- id: 'env-1',
- visibility: 'private',
- });
- const [matchesKey] = swr.mutate.mock.calls[0];
- expect(matchesKey(['sandbox-environments', 'public'])).toBe(true);
- expect(matchesKey(['sandbox-environments', 'private'])).toBe(true);
- expect(matchesKey(['sandbox-drive-files'])).toBe(false);
- });
-});
diff --git a/src/features/EnvironmentManager/useEnvironmentData.test.ts b/src/features/EnvironmentManager/useEnvironmentData.test.ts
new file mode 100644
index 00000000000..faabed466ac
--- /dev/null
+++ b/src/features/EnvironmentManager/useEnvironmentData.test.ts
@@ -0,0 +1,128 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The environments page's list hook paints the last list from the sandbox
+ * environments replica on a reload, while the network confirms it. A restored
+ * empty list is not an answer: it stays unsettled until the server says.
+ */
+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 } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { environmentService } from '@/services/environment';
+import { initialState } from '@/store/sandbox/initialState';
+import { sandboxEnvironmentsResource } from '@/store/sandbox/projection';
+import { useSandboxStore } from '@/store/sandbox/store';
+
+import { useEnvironments } from './useEnvironmentData';
+
+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,
+ );
+
+type Listed = Awaited<ReturnType<typeof environmentService.listEnvironments>>;
+
+const storedRow = {
+ createdAt: '2026-10-01T00:00:00.000Z',
+ creator: { avatar: null, fullName: 'Ada', id: 'user-1', username: 'ada' },
+ description: 'Main repo',
+ id: 'env-1',
+ kind: 'code',
+ name: 'Lobehub Dev',
+ repository: 'lobehub/lobehub',
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+};
+
+describe('useEnvironments', () => {
+ let scope = '';
+ let answer: (value: Listed) => void;
+
+ beforeEach(() => {
+ scope = `env-page-${randomUUID()}:ws-1`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ useSandboxStore.setState({ ...initialState });
+ // Held until the test answers it: what the hook has first can only come from storage.
+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(
+ () => new Promise<Listed>((resolve) => (answer = resolve)),
+ );
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ ['all', 'public', 'private'].map((queryKey) =>
+ sandboxEnvironmentsResource.storage!.remove({ queryKey, scope }),
+ ),
+ );
+ vi.restoreAllMocks();
+ });
+
+ const seed = (data: unknown[]) =>
+ sandboxEnvironmentsResource.storage!.set(
+ { queryKey: 'private', scope },
+ { data: data as never, updatedAt: 1 },
+ );
+
+ it('has the stored list on a reload before the network answers, then the server answer', async () => {
+ await seed([storedRow]);
+
+ const { result } = renderHook(() => useEnvironments('private'), { wrapper });
+
+ await waitFor(() =>
+ expect(result.current).toMatchObject({
+ environments: [expect.objectContaining({ name: 'Lobehub Dev' })],
+ settled: true,
+ }),
+ );
+
+ await act(async () =>
+ answer({
+ environments: [
+ {
+ ...storedRow,
+ configuration: { sources: [] },
+ createdAt: new Date(storedRow.createdAt),
+ name: 'Lobehub Renamed',
+ updatedAt: new Date(storedRow.createdAt),
+ },
+ ],
+ } as unknown as Listed),
+ );
+
+ await waitFor(() =>
+ expect(result.current.environments?.map(({ name }) => name)).toEqual(['Lobehub Renamed']),
+ );
+ });
+
+ it('keeps an empty stored list unsettled until the server confirms it', async () => {
+ await seed([]);
+
+ const { result } = renderHook(() => useEnvironments('private'), { wrapper });
+
+ await waitFor(() => expect(result.current).toMatchObject({ environments: [] }));
+ expect(result.current.settled).toBe(false);
+
+ await act(async () => answer({ environments: [] } as unknown as Listed));
+
+ await waitFor(() => expect(result.current.settled).toBe(true));
+ expect(result.current.environments).toEqual([]);
+ });
+});
diff --git a/src/features/EnvironmentManager/useEnvironmentData.ts b/src/features/EnvironmentManager/useEnvironmentData.ts
index 1acb896f539..9ad631a5627 100644
--- a/src/features/EnvironmentManager/useEnvironmentData.ts
+++ b/src/features/EnvironmentManager/useEnvironmentData.ts
@@ -1,90 +1,40 @@
import type { EnvironmentVisibility } from '@lobechat/types';
-import { useSWRConfig } from 'swr';
-import { useClientDataSWR } from '@/libs/swr';
-import {
- environmentService,
- type NewEnvironmentSpecification,
- type SandboxEnvironmentSpecification,
-} from '@/services/environment';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
-const ENVIRONMENTS_KEY = 'sandbox-environments';
+export type { CreatedEnvironment, SandboxEnvironment } from '@/store/sandbox';
/**
- * Specifications. Answered from the database alone, so this settles fast and is
- * safe to render the page on.
+ * Specifications, one pool at a time: `public` / `private` on the workspace
+ * page's two tabs, every environment on the personal page.
*
- * Keyed by pool, so the workspace page's two tabs do not overwrite each other's
- * cache β€” and so switching back to one shows what it held rather than a
- * skeleton. A mutation refreshes every pool, because publishing moves a row
- * from one to the other.
+ * Read from the sandbox store's environments replica, which the composer's
+ * picker shares, so a reload paints the last list from storage and the network
+ * only confirms it. A restored row has no `configuration` (it carries `env`).
*
- * `useClientDataSWR` rather than plain SWR, because it adds the active
- * workspace to the key. Without that dimension a list fetched in one workspace
- * keeps being served after switching to another β€” the same trap the device list
- * documents, and a worse one here, where the answer is which environments exist
- * for whom.
+ * `settled` says whether there is a list to paint. An empty list restored from
+ * storage is not an answer β€” it may be stale β€” so it stays unsettled (the
+ * skeleton, not "no environments") until the server says.
+ *
+ * Partitioned by the cache scope (user + workspace): a list fetched in one
+ * workspace is never served in another.
*/
-export const useEnvironments = (visibility?: EnvironmentVisibility) =>
- useClientDataSWR<Awaited<ReturnType<typeof environmentService.listEnvironments>>>(
- [ENVIRONMENTS_KEY, visibility ?? 'all'],
- () => environmentService.listEnvironments(visibility ? { visibility } : undefined),
- );
-
-/** A new environment as `createEnvironment` returns it: the definition alone. */
-export type CreatedEnvironment = Awaited<ReturnType<typeof environmentService.createEnvironment>>;
+export const useEnvironments = (visibility?: EnvironmentVisibility) => {
+ const { error, revalidate } = sandboxActions.useFetchEnvironments(visibility);
+ const environments = useSandboxStore(sandboxSelectors.environments(visibility));
+ const confirmed = useSandboxStore(sandboxSelectors.isEnvironmentsConfirmed(visibility));
+ const settled = environments !== undefined && (environments.length > 0 || confirmed);
-export type SandboxEnvironment = NonNullable<
- ReturnType<typeof useEnvironments>['data']
->['environments'][number];
+ return { environments, error, revalidate, settled };
+};
/**
- * Mutations, each refreshing exactly the lists it can have changed.
+ * Mutations, each landing on the replica as soon as the server agrees, then
+ * refreshing every pool β€” publishing moves a row from one pool to the other.
*/
-export const useEnvironmentActions = () => {
- const { mutate: globalMutate } = useSWRConfig();
-
- // Every pool and every workspace, not the one this caller happens to be
- // looking at: publishing an environment takes it out of one tab and puts it
- // in the other, so refreshing only the current key leaves the other tab
- // showing a row that moved. The workspace id the key carries is part of what
- // is matched loosely here, for the same reason.
- const refreshEnvironments = () =>
- globalMutate((key) => Array.isArray(key) && key[0] === ENVIRONMENTS_KEY);
-
- return {
- createEnvironment: async (params: {
- configuration?: NewEnvironmentSpecification;
- description?: string;
- name: string;
- visibility?: EnvironmentVisibility;
- }) => {
- // Returned, not discarded: the caller opens the environment it made.
- // Nothing is built β€” a conversation applies it to its working directory.
- const created = await environmentService.createEnvironment(params);
- await refreshEnvironments();
-
- return created;
- },
-
- setEnvironmentVisibility: async (params: { id: string; visibility: EnvironmentVisibility }) => {
- await environmentService.setEnvironmentVisibility(params);
- await refreshEnvironments();
- },
-
- removeEnvironment: async (id: string) => {
- await environmentService.removeEnvironment({ id });
- await refreshEnvironments();
- },
-
- updateEnvironment: async (params: {
- configuration?: SandboxEnvironmentSpecification;
- description?: string;
- id: string;
- name?: string;
- }) => {
- await environmentService.updateEnvironment(params);
- await refreshEnvironments();
- },
- };
-};
+export const useEnvironmentActions = () => ({
+ createEnvironment: sandboxActions.createEnvironment,
+ removeEnvironment: sandboxActions.removeEnvironment,
+ setEnvironmentVisibility: sandboxActions.setEnvironmentVisibility,
+ updateEnvironment: sandboxActions.updateEnvironment,
+});
diff --git a/src/store/sandbox/action.ts b/src/store/sandbox/action.ts
index 0a940ed5d16..2002c79fb37 100644
--- a/src/store/sandbox/action.ts
+++ b/src/store/sandbox/action.ts
@@ -1,10 +1,22 @@
+import type { EnvironmentVisibility } from '@lobechat/types';
+
import { type ReplicaSyncResult } from '@/libs/replica';
+import {
+ environmentService,
+ type NewEnvironmentSpecification,
+ type SandboxEnvironmentSpecification,
+} from '@/services/environment';
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 {
+ SANDBOX_SCOPE_ENTRY,
+ type SandboxEnvironment,
+ type SandboxPickerInstanceList,
+ toEnvironmentPool,
+} from './projection';
import { useSandboxStore } from './store';
const n = setNamespace('sandbox');
@@ -14,6 +26,15 @@ type Setter = StoreSetter<SandboxState>;
/** How often a building copy is re-listed while the picker can see it. */
const BUILD_REFRESH_MS = 4000;
+/**
+ * Readers of one pool mounted together (the page, the picker, the folder
+ * dialog) share one request. Explicit refreshes and writes bypass it.
+ */
+const ENVIRONMENTS_DEDUPE_MS = 10_000;
+
+/** A new environment as `createEnvironment` returns it: the definition alone. */
+export type CreatedEnvironment = Awaited<ReturnType<typeof environmentService.createEnvironment>>;
+
interface UseFetchEntitlementOptions {
/** Revalidate when the window regains focus. Defaults to `true`. */
revalidateOnFocus?: boolean;
@@ -21,9 +42,11 @@ interface UseFetchEntitlementOptions {
export class SandboxActionImpl {
readonly #private: SandboxPrivateAction;
+ readonly #get: () => SandboxState;
readonly #set: Setter;
- constructor(set: Setter, _get: () => SandboxState, privateAction: SandboxPrivateAction) {
+ constructor(set: Setter, get: () => SandboxState, privateAction: SandboxPrivateAction) {
+ this.#get = get;
this.#set = set;
this.#private = privateAction;
}
@@ -39,9 +62,101 @@ export class SandboxActionImpl {
): ReplicaSyncResult =>
this.#private.entitlement.useSync(enabled ? SANDBOX_SCOPE_ENTRY : null, { revalidateOnFocus });
+ /**
+ * One pool of environments; read it with `sandboxSelectors.environments`.
+ * `visibility` omitted is every environment the caller can see.
+ */
+ useFetchEnvironments = (visibility?: EnvironmentVisibility): ReplicaSyncResult =>
+ this.#private.environments.useSync(toEnvironmentPool(visibility), {
+ dedupingInterval: ENVIRONMENTS_DEDUPE_MS,
+ });
+
/** The picker's environments; read them with `sandboxSelectors.pickerEnvironments`. */
useFetchPickerEnvironments = (enabled: boolean): ReplicaSyncResult =>
- this.#private.environments.useSync(enabled ? SANDBOX_SCOPE_ENTRY : null);
+ this.#private.environments.useSync(enabled ? 'all' : null, {
+ dedupingInterval: ENVIRONMENTS_DEDUPE_MS,
+ });
+
+ /**
+ * Re-sync every mounted pool. Every pool, not the one a caller is looking
+ * at: publishing moves an environment from one pool to the other.
+ */
+ refreshEnvironments = async (): Promise<void> => {
+ await this.#private.environments.revalidate();
+ };
+
+ /** Returns the definition, so the caller can open what it made. */
+ createEnvironment = async (params: {
+ configuration?: NewEnvironmentSpecification;
+ description?: string;
+ name: string;
+ visibility?: EnvironmentVisibility;
+ }): Promise<CreatedEnvironment> => {
+ const created = await environmentService.createEnvironment(params);
+ await this.refreshEnvironments();
+
+ return created;
+ };
+
+ updateEnvironment = async (params: {
+ configuration?: SandboxEnvironmentSpecification;
+ description?: string;
+ id: string;
+ name?: string;
+ }): Promise<void> => {
+ await environmentService.updateEnvironment(params);
+ const { description, id, name } = params;
+ // The facts a row shows land at once, in every pool and in storage; the
+ // configuration comes back with the refresh, the way it is stored.
+ this.#private.environments.updateEntity<SandboxEnvironment>(id, (environment) => ({
+ ...environment,
+ ...(name === undefined ? {} : { name }),
+ ...(description === undefined ? {} : { description }),
+ }));
+ await this.refreshEnvironments();
+ };
+
+ /**
+ * Gone from every pool and from storage as soon as the server agrees, so a
+ * reload before the refresh lands cannot restore it.
+ */
+ removeEnvironment = async (id: string): Promise<void> => {
+ await environmentService.removeEnvironment({ id });
+ this.#private.environments.removeEntity(id);
+ await this.refreshEnvironments();
+ };
+
+ /**
+ * Moves the row from one pool to the other as soon as the server agrees: out
+ * of the pool it left, into the pool it joined when that pool is loaded.
+ */
+ setEnvironmentVisibility = async ({
+ id,
+ visibility,
+ }: {
+ id: string;
+ visibility: EnvironmentVisibility;
+ }): Promise<void> => {
+ await environmentService.setEnvironmentVisibility({ id, visibility });
+ const slice = this.#private.environments;
+ const left: EnvironmentVisibility = visibility === 'public' ? 'private' : 'public';
+ const pools = this.#get().sandboxEnvironmentsMap;
+ const current = [pools.all, pools[left], pools[visibility]]
+ .flatMap((list) => list ?? [])
+ .find((environment) => environment.id === id);
+
+ slice.updateEntity<SandboxEnvironment>(id, (environment) => ({ ...environment, visibility }));
+ slice.update(left, (list) => list?.filter((environment) => environment.id !== id));
+ if (current)
+ slice.update(visibility, (list) =>
+ list && !list.some((environment) => environment.id === id)
+ ? [...list, { ...current, visibility }].sort((a, b) =>
+ a.createdAt.localeCompare(b.createdAt),
+ )
+ : list,
+ );
+ await this.refreshEnvironments();
+ };
/**
* The picker's copies with `topicId`'s occupancy; read them with
diff --git a/src/store/sandbox/environments.test.ts b/src/store/sandbox/environments.test.ts
new file mode 100644
index 00000000000..722e5dbe424
--- /dev/null
+++ b/src/store/sandbox/environments.test.ts
@@ -0,0 +1,319 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The environments page's pools (`all` / `public` / `private`) are one
+ * `local-replica` resource shared with the composer's picker: a reload paints
+ * the stored rows while the network confirms them, configuration never reaches
+ * storage, writes land on the replica and its storage, and scopes stay apart.
+ */
+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 } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { environmentService } from '@/services/environment';
+
+import { sandboxActions } from './action';
+import { initialState } from './initialState';
+import { type SandboxEnvironment, sandboxEnvironmentsResource } 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: { 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 Listed = Awaited<ReturnType<typeof environmentService.listEnvironments>>;
+
+const raw = (overrides: Record<string, unknown> = {}) => ({
+ configuration: {
+ bootstrapCommand: 'pnpm install',
+ env: { API_TOKEN: 'secret-value' },
+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub.git' }],
+ },
+ createdAt: new Date('2026-10-01T00:00:00Z'),
+ creator: { avatar: null, fullName: 'Ada', id: 'user-1', username: 'ada' },
+ description: 'Main repo',
+ id: 'env-1',
+ name: 'Lobehub Dev',
+ updatedAt: new Date('2026-10-01T00:00:00Z'),
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ ...overrides,
+});
+
+const listed = (...environments: ReturnType<typeof raw>[]) =>
+ ({ environments }) as unknown as Listed;
+
+const storedRow = (overrides: Partial<SandboxEnvironment> = {}): SandboxEnvironment => ({
+ createdAt: '2026-10-01T00:00:00.000Z',
+ creator: { avatar: null, fullName: 'Ada', id: 'user-1', username: 'ada' },
+ description: 'Main repo',
+ id: 'env-1',
+ kind: 'code',
+ name: 'Lobehub Dev',
+ repository: 'lobehub/lobehub',
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ ...overrides,
+});
+
+const POOLS = ['all', 'public', 'private'] as const;
+const state = () => useSandboxStore.getState();
+
+describe('sandbox environments replica', () => {
+ 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 seed = (pool: (typeof POOLS)[number], data: SandboxEnvironment[], at = scope) =>
+ sandboxEnvironmentsResource.storage!.set({ queryKey: pool, scope: at }, { data, updatedAt: 1 });
+
+ const stored = async (pool: (typeof POOLS)[number]) =>
+ (await sandboxEnvironmentsResource.storage!.get({ queryKey: pool, scope }))?.data;
+
+ beforeEach(() => {
+ useScope(`env-user-${randomUUID()}:ws-1`);
+ useSandboxStore.setState({ ...initialState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ POOLS.map((queryKey) =>
+ sandboxEnvironmentsResource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('paints a pool from storage before the network answers, then takes the server answer', async () => {
+ await seed('private', [storedRow()]);
+ let answer!: (value: Listed) => void;
+ const listEnvironments = vi
+ .spyOn(environmentService, 'listEnvironments')
+ .mockImplementation(() => new Promise<Listed>((resolve) => (answer = resolve)));
+
+ renderHook(() => sandboxActions.useFetchEnvironments('private'), { wrapper });
+
+ await waitFor(() =>
+ expect(sandboxSelectors.environments('private')(state())?.[0].name).toBe('Lobehub Dev'),
+ );
+ // Restored, not confirmed: no configuration and no server answer yet.
+ expect(sandboxSelectors.environments('private')(state())?.[0].configuration).toBeUndefined();
+ expect(sandboxSelectors.isEnvironmentsConfirmed('private')(state())).toBe(false);
+ expect(listEnvironments).toHaveBeenCalledWith({ visibility: 'private' });
+
+ await act(async () => answer(listed(raw({ name: 'Renamed' }))));
+
+ await waitFor(() =>
+ expect(sandboxSelectors.environments('private')(state())?.[0].name).toBe('Renamed'),
+ );
+ expect(sandboxSelectors.isEnvironmentsConfirmed('private')(state())).toBe(true);
+ expect(sandboxSelectors.environments('private')(state())?.[0].configuration).toMatchObject({
+ bootstrapCommand: 'pnpm install',
+ });
+ });
+
+ it('keeps configuration (env, source URLs) out of storage', async () => {
+ vi.spyOn(environmentService, 'listEnvironments').mockResolvedValue(
+ listed(
+ raw(),
+ raw({
+ configuration: {
+ sources: [{ kind: 'git', url: 'https://x-access-token:[email protected]/a/b.git' }],
+ },
+ id: 'env-2',
+ }),
+ ),
+ );
+
+ renderHook(() => sandboxActions.useFetchEnvironments(), { wrapper });
+
+ await waitFor(async () => expect(await stored('all')).toHaveLength(2));
+ const rows = (await stored('all'))!;
+ expect(rows[0]).toEqual(storedRow());
+ // A URL carrying a token is not a plain `owner/name`, so nothing of it is kept.
+ expect(rows[1].repository).toBeUndefined();
+ const payload = JSON.stringify(rows);
+ for (const leaked of ['configuration', 'secret', 'ghp_', 'pnpm install', 'API_TOKEN']) {
+ expect(payload).not.toContain(leaked);
+ }
+ });
+
+ it('treats an empty list restored from storage as unconfirmed until the server answers', async () => {
+ await seed('public', []);
+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(pending);
+
+ renderHook(() => sandboxActions.useFetchEnvironments('public'), { wrapper });
+
+ await waitFor(() => expect(sandboxSelectors.environments('public')(state())).toEqual([]));
+ expect(sandboxSelectors.isEnvironmentsConfirmed('public')(state())).toBe(false);
+ });
+
+ it('keeps the last list when a background refresh fails', async () => {
+ vi.spyOn(environmentService, 'listEnvironments')
+ .mockResolvedValueOnce(listed(raw()))
+ .mockRejectedValue(new Error('network down'));
+
+ const { result } = renderHook(() => sandboxActions.useFetchEnvironments('private'), {
+ wrapper,
+ });
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toHaveLength(1));
+
+ await act(async () => {
+ await result.current.revalidate().catch(() => {});
+ });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(sandboxSelectors.environments('private')(state())?.[0].name).toBe('Lobehub Dev');
+ });
+
+ it('serves the page and the picker from one request', async () => {
+ const listEnvironments = vi
+ .spyOn(environmentService, 'listEnvironments')
+ .mockResolvedValue(listed(raw()));
+
+ renderHook(
+ () => {
+ sandboxActions.useFetchEnvironments();
+ sandboxActions.useFetchPickerEnvironments(true);
+ sandboxActions.useFetchEnvironments();
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(sandboxSelectors.pickerEnvironments(state())).toHaveLength(1));
+ expect(sandboxSelectors.environments()(state())).toBe(
+ sandboxSelectors.pickerEnvironments(state()),
+ );
+ expect(listEnvironments).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not show the previous identity its environments', async () => {
+ const previous = scope;
+ await seed('all', [storedRow({ name: 'Previous user env' })], previous);
+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(pending);
+
+ const { rerender } = renderHook(() => sandboxActions.useFetchEnvironments(), { wrapper });
+ await waitFor(() =>
+ expect(sandboxSelectors.environments()(state())?.[0].name).toBe('Previous user env'),
+ );
+
+ useScope(`env-user-${randomUUID()}:ws-2`);
+ rerender();
+
+ await waitFor(() => expect(sandboxSelectors.environments()(state())).toBeUndefined());
+ });
+
+ it('drops a removed environment from every pool and from storage, so a reload cannot restore it', async () => {
+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(async (params) =>
+ // The server still lists it until the delete lands.
+ listed(raw({ visibility: params?.visibility ?? 'private' })),
+ );
+ vi.spyOn(environmentService, 'removeEnvironment').mockResolvedValue(undefined as never);
+
+ const { unmount } = renderHook(
+ () => {
+ sandboxActions.useFetchEnvironments();
+ sandboxActions.useFetchEnvironments('private');
+ },
+ { wrapper },
+ );
+ await waitFor(async () => expect(await stored('private')).toHaveLength(1));
+ await waitFor(async () => expect(await stored('all')).toHaveLength(1));
+
+ // The refresh after the delete has not answered yet.
+ vi.mocked(environmentService.listEnvironments).mockImplementation(pending);
+ await act(async () => {
+ void sandboxActions.removeEnvironment('env-1');
+ });
+
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toEqual([]));
+ expect(sandboxSelectors.environments()(state())).toEqual([]);
+ await waitFor(async () => expect(await stored('private')).toEqual([]));
+ await waitFor(async () => expect(await stored('all')).toEqual([]));
+
+ // Reload: a fresh store hydrates the stored pool without the removed row.
+ unmount();
+ useSandboxStore.setState({ ...initialState });
+ renderHook(() => sandboxActions.useFetchEnvironments('private'), { wrapper });
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toEqual([]));
+ });
+
+ it('moves a published environment from the private pool into the public one', async () => {
+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(async (params) =>
+ params?.visibility === 'public' ? listed() : listed(raw()),
+ );
+ vi.spyOn(environmentService, 'setEnvironmentVisibility').mockResolvedValue({} as never);
+
+ renderHook(
+ () => {
+ sandboxActions.useFetchEnvironments('private');
+ sandboxActions.useFetchEnvironments('public');
+ },
+ { wrapper },
+ );
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toHaveLength(1));
+ await waitFor(() => expect(sandboxSelectors.environments('public')(state())).toEqual([]));
+
+ // The refresh after the write has not answered yet: the move is already there.
+ vi.mocked(environmentService.listEnvironments).mockImplementation(pending);
+ await act(async () => {
+ void sandboxActions.setEnvironmentVisibility({ id: 'env-1', visibility: 'public' });
+ });
+
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toEqual([]));
+ expect(sandboxSelectors.environments('public')(state())?.[0]).toMatchObject({
+ id: 'env-1',
+ visibility: 'public',
+ });
+ await waitFor(async () => expect(await stored('private')).toEqual([]));
+ });
+
+ it('writes an edited name through to every pool and storage', async () => {
+ vi.spyOn(environmentService, 'listEnvironments').mockResolvedValue(listed(raw()));
+ vi.spyOn(environmentService, 'updateEnvironment').mockResolvedValue({} as never);
+
+ renderHook(() => sandboxActions.useFetchEnvironments('private'), { wrapper });
+ await waitFor(() => expect(sandboxSelectors.environments('private')(state())).toHaveLength(1));
+
+ vi.mocked(environmentService.listEnvironments).mockImplementation(pending);
+ await act(async () => {
+ void sandboxActions.updateEnvironment({ id: 'env-1', name: 'Renamed' });
+ });
+
+ await waitFor(() =>
+ expect(sandboxSelectors.environments('private')(state())?.[0].name).toBe('Renamed'),
+ );
+ await waitFor(async () => expect((await stored('private'))?.[0].name).toBe('Renamed'));
+ });
+});
diff --git a/src/store/sandbox/index.ts b/src/store/sandbox/index.ts
index 5605acd9e45..bd27cbfb43c 100644
--- a/src/store/sandbox/index.ts
+++ b/src/store/sandbox/index.ts
@@ -1,7 +1,8 @@
-export { sandboxActions } from './action';
+export { type CreatedEnvironment, sandboxActions } from './action';
export { type SandboxState } from './initialState';
export {
type SandboxEntitlement,
+ type SandboxEnvironment,
type SandboxPickerEnvironment,
type SandboxPickerInstance,
type SandboxPickerInstanceList,
diff --git a/src/store/sandbox/initialState.ts b/src/store/sandbox/initialState.ts
index 215a30daa92..82930af7b11 100644
--- a/src/store/sandbox/initialState.ts
+++ b/src/store/sandbox/initialState.ts
@@ -2,8 +2,8 @@ import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type {
SandboxEntitlement,
+ SandboxEnvironment,
SandboxInstanceDirectory,
- SandboxPickerEnvironment,
SandboxPickerInstanceList,
} from './projection';
@@ -11,9 +11,9 @@ 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[]>;
+ /** `sandboxEnvironmentsMap[pool]`: one pool's environments (`all` / `public` / `private`). */
+ sandboxEnvironmentsMap: Record<string, SandboxEnvironment[]>;
+ sandboxEnvironmentsReplica: ReplicaState<SandboxEnvironment[]>;
/** `sandboxInstanceDirectoryMap[instanceId]`: where a bound instance's files live. */
sandboxInstanceDirectoryMap: Record<string, SandboxInstanceDirectory>;
sandboxInstanceDirectoryReplica: ReplicaState<SandboxInstanceDirectory>;
diff --git a/src/store/sandbox/privateAction.ts b/src/store/sandbox/privateAction.ts
index 36e2d4a4289..8554bfeabe9 100644
--- a/src/store/sandbox/privateAction.ts
+++ b/src/store/sandbox/privateAction.ts
@@ -8,17 +8,19 @@ import {
SANDBOX_SCOPE_ENTRY,
type SandboxEntitlement,
sandboxEntitlementResource,
+ type SandboxEnvironment,
+ sandboxEnvironmentEntity,
sandboxEnvironmentsResource,
type SandboxInstanceDirectory,
sandboxInstanceDirectoryResource,
sandboxInstancesResource,
- type SandboxPickerEnvironment,
type SandboxPickerInstance,
type SandboxPickerInstanceList,
toInstanceDirectory,
- toPickerEnvironment,
+ toPersistedEnvironments,
toPickerInstance,
toSandboxEntitlement,
+ toSandboxEnvironment,
} from './projection';
type Setter = StoreSetter<SandboxState>;
@@ -56,14 +58,19 @@ export class SandboxPrivateAction {
});
this.environments = createReplicaSlice(sandboxEnvironmentsResource, {
actionPrefix: 'sandboxEnvironments',
- fetcher: async () => {
- const { environments } = await environmentService.listEnvironments();
- return environments.map(toPickerEnvironment);
+ entity: sandboxEnvironmentEntity,
+ fetcher: async (pool) => {
+ const { environments } = await environmentService.listEnvironments(
+ pool === 'all' ? undefined : { visibility: pool },
+ );
+ return environments.map(toSandboxEnvironment);
},
get,
set,
stateKey: 'sandboxEnvironmentsReplica',
- view: recordLens<SandboxState, SandboxPickerEnvironment[]>('sandboxEnvironmentsMap'),
+ // Configuration (env, source URLs) stays in memory: see SandboxEnvironment.
+ toPersisted: toPersistedEnvironments,
+ view: recordLens<SandboxState, SandboxEnvironment[]>('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
diff --git a/src/store/sandbox/projection.ts b/src/store/sandbox/projection.ts
index 3c0262283cc..0010c1d6a7b 100644
--- a/src/store/sandbox/projection.ts
+++ b/src/store/sandbox/projection.ts
@@ -1,6 +1,6 @@
-import type { EnvironmentKind } from '@lobechat/types';
+import type { EnvironmentKind, EnvironmentVisibility } from '@lobechat/types';
-import { defineReplica } from '@/libs/replica';
+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';
import type { environmentService } from '@/services/environment';
import type { sandboxStorageService } from '@/services/sandboxStorage';
@@ -14,18 +14,20 @@ type RawEntitlement = Awaited<ReturnType<typeof sandboxStorageService.getEntitle
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.
+ * The cloud-sandbox reads the composer's instance chip, its picker, the
+ * environments page 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.
+ * Every persisted 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). */
+/** The single entry of the scope-wide reads (entitlement and the instance list). */
export const SANDBOX_SCOPE_ENTRY = 'current';
export type SandboxScopeEntry = typeof SANDBOX_SCOPE_ENTRY;
@@ -44,28 +46,87 @@ export const toSandboxEntitlement = (raw: RawEntitlement): SandboxEntitlement =>
quotaBytes: raw.quotaBytes ?? null,
});
-/** What the composer's picker reads of an environment, and nothing more. */
-export interface SandboxPickerEnvironment {
+/**
+ * Which pool of environments a list answers: `all` on the personal page and in
+ * the composer's picker, `public` / `private` on the workspace page's two tabs.
+ * The server answers each pool with its own query, so each is its own entry.
+ */
+export type SandboxEnvironmentPool = EnvironmentVisibility | 'all';
+
+export const toEnvironmentPool = (visibility?: EnvironmentVisibility): SandboxEnvironmentPool =>
+ visibility ?? 'all';
+
+/** A GitHub checkout URL as `owner/name`, or nothing for any other URL. */
+const GITHUB_REPOSITORY = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/;
+
+const githubRepository = (configuration: RawEnvironment['configuration']): string | undefined => {
+ const sources = (configuration as { sources?: { kind?: string; url?: string }[] } | null)
+ ?.sources;
+ const url = sources?.find((source) => source.kind === 'git')?.url;
+
+ return url ? GITHUB_REPOSITORY.exec(url)?.[1] : undefined;
+};
+
+/**
+ * One environment as the environments page and the composer's picker read it.
+ *
+ * `configuration` lives in memory only: it carries `env` (credentials) and
+ * source URLs (a URL can carry a token), so it never reaches storage. A row
+ * restored from storage has none; `repository` is the one fact of it a row
+ * shows, kept only when it is a plain GitHub `owner/name`.
+ */
+export interface SandboxEnvironment {
+ /** Absent on a row restored from storage, until the server answers again. */
+ configuration?: RawEnvironment['configuration'];
+ createdAt: string;
+ creator: {
+ avatar: string | null;
+ fullName: string | null;
+ id: string | null;
+ username: string | null;
+ } | null;
+ description: string | null;
id: string;
- /** Derived from the configuration at the boundary; the configuration is not kept. */
+ /** Every environment is a code environment now; kept for the picker's shape. */
kind: EnvironmentKind;
name: string;
+ repository?: string;
userId: string;
visibility: RawEnvironment['visibility'];
workspaceId: string | null;
}
-export const toPickerEnvironment = (environment: RawEnvironment): SandboxPickerEnvironment => ({
+export const toSandboxEnvironment = (environment: RawEnvironment): SandboxEnvironment => ({
+ configuration: environment.configuration,
+ createdAt: new Date(environment.createdAt).toISOString(),
+ creator: environment.creator
+ ? {
+ avatar: environment.creator.avatar ?? null,
+ fullName: environment.creator.fullName ?? null,
+ id: environment.creator.id,
+ username: environment.creator.username ?? null,
+ }
+ : null,
+ description: environment.description ?? null,
id: environment.id,
- // Every environment is a code environment now; the field stays so the
- // picker's shape does not change under the persisted replica rows.
kind: 'code',
name: environment.name,
+ repository: githubRepository(environment.configuration),
userId: environment.userId,
visibility: environment.visibility,
workspaceId: environment.workspaceId ?? null,
});
+/** What reaches storage of a list: every row without its configuration. */
+export const toPersistedEnvironments = (environments: SandboxEnvironment[]): SandboxEnvironment[] =>
+ environments.map(({ configuration: _configuration, ...row }) => row);
+
+/** What the composer's picker reads of an environment, and nothing more. */
+export type SandboxPickerEnvironment = Pick<
+ SandboxEnvironment,
+ 'id' | 'kind' | 'name' | 'userId' | 'visibility' | 'workspaceId'
+>;
+
/** A listed copy, as the picker renders it. */
export interface SandboxPickerInstance {
createdAt: string;
@@ -144,12 +205,23 @@ export const sandboxEntitlementResource = defineReplica<SandboxScopeEntry, Sandb
version: 1,
});
+/** Environment rows are addressed by the environment id, in every pool. */
+export const sandboxEnvironmentEntity: ReplicaEntityAdapter<
+ SandboxEnvironment[],
+ SandboxEnvironment
+> = arrayEntity<SandboxEnvironment>((environment) => environment.id);
+
+/**
+ * Every pool's environments. The environments page and the composer's picker
+ * read the same `all` entry, so the personal page and the picker share one
+ * request and one stored row.
+ */
export const sandboxEnvironmentsResource = defineReplica<
- SandboxScopeEntry,
- SandboxPickerEnvironment[]
+ SandboxEnvironmentPool,
+ SandboxEnvironment[]
>({
- key: (entry) => entry,
- name: 'sandboxPickerEnvironments',
+ key: (pool) => pool,
+ name: 'sandboxEnvironments',
storage: 'indexedDB',
version: 1,
});
diff --git a/src/store/sandbox/replica.test.ts b/src/store/sandbox/replica.test.ts
index 828cd585f99..83fb7c4053c 100644
--- a/src/store/sandbox/replica.test.ts
+++ b/src/store/sandbox/replica.test.ts
@@ -139,7 +139,7 @@ describe('sandbox replicas', () => {
await Promise.all(
[...scopes].flatMap((value) =>
resources.flatMap((resource) =>
- [SANDBOX_SCOPE_ENTRY, 'inst-1', 'inst-gone'].map((queryKey) =>
+ [SANDBOX_SCOPE_ENTRY, 'all', 'inst-1', 'inst-gone'].map((queryKey) =>
resource.storage!.remove({ queryKey, scope: value }),
),
),
@@ -155,10 +155,13 @@ describe('sandbox replicas', () => {
{ data: { entitled: true, quotaBytes: 1024 }, updatedAt: 1 },
);
await sandboxEnvironmentsResource.storage!.set(
- { queryKey: SANDBOX_SCOPE_ENTRY, scope },
+ { queryKey: 'all', scope },
{
data: [
{
+ createdAt: '2026-10-01T00:00:00.000Z',
+ creator: null,
+ description: null,
id: 'env-1',
kind: 'code',
name: 'Lobehub Dev',
@@ -223,14 +226,19 @@ describe('sandbox replicas', () => {
{ wrapper },
);
- await waitFor(async () => expect(await stored(sandboxEnvironmentsResource)).toHaveLength(1));
+ await waitFor(async () =>
+ expect(await stored(sandboxEnvironmentsResource, 'all')).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([
+ expect(await stored(sandboxEnvironmentsResource, 'all')).toEqual([
{
+ createdAt: '2026-10-01T00:00:00.000Z',
+ creator: null,
+ description: null,
id: 'env-1',
kind: 'code',
name: 'Lobehub Dev',
@@ -244,7 +252,7 @@ describe('sandbox replicas', () => {
});
const payload = JSON.stringify([
- await stored(sandboxEnvironmentsResource),
+ await stored(sandboxEnvironmentsResource, 'all'),
await stored(sandboxInstancesResource),
await stored(sandboxInstanceDirectoryResource, 'inst-1'),
]);
diff --git a/src/store/sandbox/selectors.ts b/src/store/sandbox/selectors.ts
index 6e6d62d2f0e..d6e724dccc9 100644
--- a/src/store/sandbox/selectors.ts
+++ b/src/store/sandbox/selectors.ts
@@ -1,18 +1,44 @@
+import type { EnvironmentVisibility } from '@lobechat/types';
+
import type { SandboxState } from './initialState';
import {
SANDBOX_SCOPE_ENTRY,
type SandboxEntitlement,
+ type SandboxEnvironment,
type SandboxPickerEnvironment,
type SandboxPickerInstance,
+ toEnvironmentPool,
} from './projection';
/** The active workspace's entitlement, or `undefined` before its first paint. */
const entitlement = (s: SandboxState): SandboxEntitlement | undefined =>
s.sandboxEntitlementMap[SANDBOX_SCOPE_ENTRY];
+/**
+ * One pool's environments (`visibility` omitted: every environment), or
+ * `undefined` before their first paint.
+ */
+const environments =
+ (visibility?: EnvironmentVisibility) =>
+ (s: SandboxState): SandboxEnvironment[] | undefined =>
+ s.sandboxEnvironmentsMap[toEnvironmentPool(visibility)];
+
+/**
+ * Whether the server has answered this pool since the page loaded. A list
+ * restored from storage may be empty or out of date, so until then "no
+ * environments" and "this one is gone" are not answers yet.
+ */
+const isEnvironmentsConfirmed =
+ (visibility?: EnvironmentVisibility) =>
+ (s: SandboxState): boolean => {
+ const source = s.sandboxEnvironmentsReplica.entries[toEnvironmentPool(visibility)]?.source;
+
+ return source === 'server' || source === 'local';
+ };
+
/** The picker's environments, or `undefined` before their first paint. */
const pickerEnvironments = (s: SandboxState): SandboxPickerEnvironment[] | undefined =>
- s.sandboxEnvironmentsMap[SANDBOX_SCOPE_ENTRY];
+ s.sandboxEnvironmentsMap.all;
/**
* The picker's copies as `topicId` sees them, or `undefined` before their first
@@ -47,7 +73,9 @@ const instanceDirectory =
export const sandboxSelectors = {
entitlement,
+ environments,
instanceDirectory,
+ isEnvironmentsConfirmed,
pickerEnvironments,
pickerInstances,
};