π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(sandbox): new conversations keep the last folder / repository of each cloud sandbox (#23122)
Rdmclin2cb0aaadad0df
diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsxindex a6617434988..7359ffeb6b5 100644--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -1,6 +1,6 @@'use client';-import { memo } from 'react';+import { memo, useCallback } from 'react';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import SafeBoundary from '@/components/ErrorBoundary';@@ -10,12 +10,13 @@ import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { useTopicId } from '../hooks/useTopicId';+import { rememberSandboxSelection } from './rememberedSandboxDirectory';import SandboxDrivePicker from './SandboxDrivePicker';import { usePrefersTemporarySandbox } from './temporarySandboxPreference';import { useFollowSandboxModePreference } from './useFollowSandboxModePreference';-import { useSandboxPlacement } from './useSandboxPlacement';+import { type SandboxSelection, useSandboxPlacement } from './useSandboxPlacement';import { useSandboxStorageAccess } from './useSandboxStorageAccess';-import { useSeedDefaultSelection } from './useSeedDefaultSelection';+import { useSeedDefaultSelection, useSeedTemporaryRepository } from './useSeedDefaultSelection';interface SandboxStorageSectionProps {agentId: string;@@ -29,9 +30,11 @@ interface SandboxStorageSectionProps {** Nothing chosen means a temporary sandbox, cleaned up with the session; a* folder on the drive keeps its files, and a repository starts from a checkout.- * A plan with a drive starts each new conversation on its default folder rather- * than nothing β unless the execution-environment menu moved the agent to the- * temporary cloud sandbox, which new conversations then keep.+ * A plan with a drive starts each new conversation in the folder the agent's+ * last conversation was put in, or on its default folder rather than nothing β+ * unless the execution-environment menu moved the agent to the+ * temporary cloud sandbox, which new conversations then keep, initialized from+ * the repository the last temporary sandbox used (or none).** A plan without a drive still gets the chip: the temporary sandbox is* everyone's, and the way to a plan is a row in the same menu rather than a@@ -63,11 +66,29 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }scopeKey: `${userId ?? ''}:${workspaceId ?? ''}:${agentId}`,temporary: prefersTemporary,});+ // Every pick that lands is remembered for the next conversation: the folder+ // for the persistent sandbox, the repository (or none) for the temporary+ // one. A failed save is not.+ const pick = useCallback(+ async (next: SandboxSelection) => {+ await setSelection(next);+ rememberSandboxSelection({ userId, workspaceId }, agentId, next);+ },+ [agentId, setSelection, userId, workspaceId],+ );useSeedDefaultSelection(agentId, {eligible: eligible && !temporary,entitled: status === 'ready' && !temporary,hasTopic: !!topicId,});+ // Where new conversations start in the temporary sandbox β picked in the+ // environment menu, or the only one a plan without a drive has β they start+ // from the repository the last one used.+ useSeedTemporaryRepository(agentId, {+ eligible,+ hasTopic: !!topicId,+ temporary: eligible && (temporary || status === 'upgrade'),+ });if (status === 'hidden') return null;@@ -77,7 +98,7 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }modeInEnvironmentMenu={modeInEnvironmentMenu}topicId={topicId}value={selection}- onChange={setSelection}+ onChange={pick}/>);});diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsxnew file mode 100644index 00000000000..e124452be6c--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx@@ -0,0 +1,253 @@+import { act, fireEvent, render, screen } from '@testing-library/react';+import { useSyncExternalStore } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ consumePendingSandboxSelection,+ toSandboxTopicMetadata,+} from '@/store/chat/pendingSandboxSelection';++import SandboxStorageSection from '../SandboxStorageSection';+import type { SandboxSelection } from '../useSandboxPlacement';++const AGENT = 'agent-remember';++const state = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ return {+ listeners,+ // Bumped on every change so subscribed components re-render, as the real+ // store would make them.+ notify: () => {+ for (const listener of listeners) listener();+ },+ // The execution-environment menu: usable, and the agent moved to the+ // temporary sandbox there.+ inMenu: false,+ temporary: false,+ topicId: null as string | null,+ userId: 'user-a' as string | undefined,+ topics: {} as Record<string, Record<string, unknown>>,+ updateTopicMetadata: vi.fn(),+ version: 0,+ };+});++const useVersion = () =>+ useSyncExternalStore(+ (listener) => {+ state.listeners.add(listener);+ return () => state.listeners.delete(listener);+ },+ () => state.version,+ );++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: object) => unknown) => {+ useVersion();+ return selector({+ activeTopicId: state.topicId ?? undefined,+ refreshTopicDetail: vi.fn(),+ topicDataMap: {},+ topicDetailMap: Object.fromEntries(+ Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),+ ),+ updateTopicMetadata: state.updateTopicMetadata,+ useFetchTopicDetail: vi.fn(),+ });+ },+}));++vi.mock('../../hooks/useTopicId', () => ({+ useTopicId: () => {+ useVersion();+ return state.topicId;+ },+}));+vi.mock('../useSandboxStorageAccess', () => ({+ useSandboxStorageAccess: () => ({ eligible: true, status: 'ready' }),+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: object) => unknown) => {+ useVersion();+ return selector({ user: { id: state.userId } });+ },+}));+// The execution-environment menu and its temporary/persistent preference are+// covered by their own tests; here the member cannot use that menu, so the+// folder chip is the only place the sandbox is chosen.+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({+ useChatInputResourceAccess: () => ({ canConfigureResource: true, canUseResource: state.inMenu }),+}));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ canDisplayExecutionTarget: state.inMenu,+ canSelectExecutionTarget: state.inMenu,+ }),+}));+vi.mock('../temporarySandboxPreference', () => ({+ usePrefersTemporarySandbox: () => state.temporary,+}));+vi.mock('../useFollowSandboxModePreference', () => ({ useFollowSandboxModePreference: () => {} }));+vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { getEntitlement: vi.fn() },+}));+vi.mock('@/store/sandbox', () => ({+ sandboxSelectors: { entitlement: () => ({ entitled: true }) },+ useSandboxStore: { getState: () => ({}) },+}));++// The picker's menu is covered by its own tests; here it only names the+// current folder and makes the picks a person would.+vi.mock('../SandboxDrivePicker', () => ({+ default: ({+ onChange,+ value,+ }: {+ onChange: (s: SandboxSelection) => Promise<void>;+ value: SandboxSelection;+ }) => (+ <div>+ <span data-testid="chip">+ {value.workingDirectory ??+ (value.environmentId ? `repo:${value.environmentId}` : 'temporary')}+ </span>+ <button onClick={() => onChange({ environmentId: 'env_repo' }).catch(() => {})}>+ pick-repo+ </button>+ {/* The real picker catches a failed save and says so. */}+ <button onClick={() => onChange({ workingDirectory: 'projects/demo' }).catch(() => {})}>+ pick-folder+ </button>+ <button onClick={() => onChange({}).catch(() => {})}>pick-temporary</button>+ </div>+ ),+}));++beforeEach(() => {+ state.inMenu = false;+ state.temporary = false;+ state.topicId = null;+ state.userId = 'user-a';+ state.topics = {};+ state.updateTopicMetadata.mockReset().mockImplementation(async (id, metadata) => {+ state.topics[id] = { ...state.topics[id], ...metadata };+ commit();+ });+});++afterEach(() => {+ consumePendingSandboxSelection(AGENT);+ localStorage.clear();+});++const commit = () => {+ state.version += 1;+ state.notify();+};++/** The first send: the pending pick becomes the new topic's metadata. */+const send = (topicId: string) =>+ act(() => {+ state.topics[topicId] = { ...toSandboxTopicMetadata(consumePendingSandboxSelection(AGENT)) };+ state.topicId = topicId;+ commit();+ });++/** "New topic" in the sidebar. */+const openNewConversation = () =>+ act(() => {+ state.topicId = null;+ commit();+ });++describe('SandboxStorageSection β T-14158', () => {+ it('starts the next new conversation in the folder picked in the last one', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ // A first conversation starts at the drive's root.+ expect(screen.getByTestId('chip').textContent).toBe('.');++ send('topic-1');+ await act(async () => fireEvent.click(screen.getByText('pick-folder')));+ expect(state.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ sandboxWorkingDirectory: 'projects/demo' }),+ );+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo');++ // "New topic": previously this went back to the root every time.+ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo');++ // And the conversation it creates is born there, still marked as a default+ // nobody picked for it, so a project conversation can take its checkout.+ send('topic-2');+ expect(state.topics['topic-2']).toMatchObject({+ sandboxSeeded: true,+ sandboxWorkingDirectory: 'projects/demo',+ });+ });++ // Using the temporary sandbox once does not erase the persistent sandbox's+ // folder: the next conversation on the drive still starts there.+ it('keeps the folder after a temporary sandbox is used once', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ await act(async () => fireEvent.click(screen.getByText('pick-folder')));+ await send('topic-1');++ await act(async () => fireEvent.click(screen.getByText('pick-temporary')));++ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo');+ });++ it('does not remember a pick that failed to save', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ send('topic-1');+ state.updateTopicMetadata.mockRejectedValueOnce(new Error('offline'));++ await act(async () => {+ fireEvent.click(screen.getByText('pick-folder'));+ });++ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('.');+ });++ describe('in the temporary sandbox', () => {+ beforeEach(() => {+ state.inMenu = true;+ state.temporary = true;+ });++ it('starts the next new conversation from the repository the last one used', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ await send('topic-1');++ await act(async () => fireEvent.click(screen.getByText('pick-repo')));++ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');+ await send('topic-2');+ expect(state.topics['topic-2']).toMatchObject({+ sandboxEnvironmentId: 'env_repo',+ sandboxSeeded: true,+ });+ });++ it('starts the next new conversation without a repository when the last one used none', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ await send('topic-1');+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));+ await act(async () => fireEvent.click(screen.getByText('pick-temporary')));++ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ });+ });+});diff --git a/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.ts b/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.tsindex 289a509e9c3..45c3f55eafb 100644--- a/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.ts+++ b/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.ts@@ -16,4 +16,15 @@ describe('resolveDefaultSandboxSelection', () => {workingDirectory: '.',});});++ // T-14158: a new conversation used to fall back to the drive's root every+ // time, losing the folder the last one was put in.+ it('starts in the folder the last conversation was put in', () => {+ expect(resolveDefaultSandboxSelection(null, { workingDirectory: 'projects/demo' })).toEqual({+ workingDirectory: 'projects/demo',+ });+ expect(+ resolveDefaultSandboxSelection('ws_1', { drive: 'public', workingDirectory: 'team' }),+ ).toEqual({ drive: 'public', workingDirectory: 'team' });+ });});diff --git a/src/features/ChatInput/ControlBar/defaultSandboxSelection.ts b/src/features/ChatInput/ControlBar/defaultSandboxSelection.tsindex c0c6d631ab1..bc1cc514365 100644--- a/src/features/ChatInput/ControlBar/defaultSandboxSelection.ts+++ b/src/features/ChatInput/ControlBar/defaultSandboxSelection.ts@@ -1,11 +1,13 @@import { SANDBOX_DRIVE_ROOT } from '@lobechat/builtin-tool-cloud-sandbox';+import type { RememberedSandboxDirectory } from './rememberedSandboxDirectory';import type { SandboxSelection } from './useSandboxPlacement';/*** Where a new conversation's cloud sandbox works when the person has not- * picked anything, for an account whose plan includes a drive: the root of a- * drive that is theirs alone.+ * picked anything, for an account whose plan includes a drive: the folder the+ * agent's last conversation was put in, when one is remembered; otherwise the+ * root of a drive that is theirs alone.** - personal account β the root of their own drive;* - workspace β the root of the member's personal drive, for every agent. The@@ -13,7 +15,12 @@ import type { SandboxSelection } from './useSandboxPlacement';* anyone may work in, so a shared agent starts on the member's own drive too;* moving to a folder on the public drive is an explicit pick.*/-export const resolveDefaultSandboxSelection = (workspaceId?: string | null): SandboxSelection =>- workspaceId- ? { drive: 'personal', workingDirectory: SANDBOX_DRIVE_ROOT }- : { workingDirectory: SANDBOX_DRIVE_ROOT };+export const resolveDefaultSandboxSelection = (+ workspaceId?: string | null,+ remembered?: RememberedSandboxDirectory,+): SandboxSelection =>+ remembered?.workingDirectory+ ? { ...remembered }+ : workspaceId+ ? { drive: 'personal', workingDirectory: SANDBOX_DRIVE_ROOT }+ : { workingDirectory: SANDBOX_DRIVE_ROOT };diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.tsnew file mode 100644index 00000000000..45bc15a95b6--- /dev/null+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ getRememberedSandboxDirectory,+ getRememberedSandboxRepository,+ rememberedSandboxDirectoryKey,+ rememberSandboxSelection,+} from './rememberedSandboxDirectory';++const ME = { userId: 'user-a' };+const MY_WS = { userId: 'user-a', workspaceId: 'ws_1' };++afterEach(() => {+ localStorage.clear();+});++describe('rememberedSandboxDirectory', () => {+ it('remembers a folder picked on the drive', () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'projects/demo' });++ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({+ workingDirectory: 'projects/demo',+ });+ });++ it('keeps the drive of a workspace pick', () => {+ rememberSandboxSelection(MY_WS, 'agent-1', { drive: 'public', workingDirectory: 'team' });++ expect(getRememberedSandboxDirectory(MY_WS, 'agent-1')).toEqual({+ drive: 'public',+ workingDirectory: 'team',+ });+ });++ it('keeps each workspace and agent apart', () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'mine' });++ expect(getRememberedSandboxDirectory(MY_WS, 'agent-1')).toBeUndefined();+ expect(getRememberedSandboxDirectory(ME, 'agent-2')).toBeUndefined();+ });++ // Storage outlives a logout; the next member on the same browser shares the+ // workspace and the agent but not the first member's personal folders.+ it("never hands one member's folder to another on the same browser", () => {+ rememberSandboxSelection(MY_WS, 'agent-1', { drive: 'personal', workingDirectory: 'mine' });++ expect(+ getRememberedSandboxDirectory({ userId: 'user-b', workspaceId: 'ws_1' }, 'agent-1'),+ ).toBeUndefined();+ });++ it('reads and writes nothing before the user is known', () => {+ rememberSandboxSelection({ workspaceId: 'ws_1' }, 'agent-1', { workingDirectory: 'x' });++ expect(localStorage.length).toBe(0);+ expect(getRememberedSandboxDirectory({ workspaceId: 'ws_1' }, 'agent-1')).toBeUndefined();+ });++ // The persistent sandbox remembers its folder and the temporary one its+ // repository, each on its own: using one never erases the other.+ it('remembers the temporary sandbox repository apart from the folder', () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });++ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });+ });++ it('remembers a temporary sandbox that used no repository', () => {+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });+ rememberSandboxSelection(ME, 'agent-1', {});++ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({});+ });++ it('remembers nothing for the temporary sandbox until one is used', () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });++ expect(getRememberedSandboxRepository(ME, 'agent-1')).toBeUndefined();+ });++ it('changes nothing for a legacy environment directory', () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });+ rememberSandboxSelection(ME, 'agent-1', { instanceId: 'inst_1' });++ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });+ });++ it('ignores a corrupted entry', () => {+ const key = rememberedSandboxDirectoryKey(ME, 'agent-1')!;+ localStorage.setItem(key, '{not json');+ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toBeUndefined();++ localStorage.setItem(key, JSON.stringify({ drive: 'other', workingDirectory: 'x' }));+ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toBeUndefined();+ });+});diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.tsnew file mode 100644index 00000000000..4a68e5e9338--- /dev/null+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts@@ -0,0 +1,135 @@+import type { SandboxSelection } from './useSandboxPlacement';++/** Prefix of every entry; each user + workspace + agent has a key of its own. */+export const REMEMBERED_SANDBOX_DIRECTORY_PREFIX = 'lobechat-sandbox-last-directory';++/**+ * Prefix of the temporary sandbox's memory, kept apart from the folder: the+ * persistent sandbox remembers which folder of the drive, the temporary one+ * which repository it was initialized from β or that it used none.+ */+export const REMEMBERED_SANDBOX_REPOSITORY_PREFIX = 'lobechat-sandbox-last-repository';++/** The folder part of a selection: which drive, and where on it. */+export type RememberedSandboxDirectory = Pick<SandboxSelection, 'drive' | 'workingDirectory'>;++/** Whose memory this is: the signed-in user, in the active workspace (if any). */+export interface RememberScope {+ userId?: string | null;+ workspaceId?: string | null;+}++// Scoped to the signed-in user first: storage outlives a logout, and a shared+// agent has the same workspace and agent ids for every member, while a+// personal-drive folder is one member's own β the next person on the same+// browser must not inherit it. The drive is per account, so a folder picked in+// one workspace means nothing in another; the agent is part of the key because+// each agent's conversations tend to live in their own folder. Without a known+// user nothing is read or written.+const scopedKey = (prefix: string, { userId, workspaceId }: RememberScope, agentId: string) =>+ userId ? `${prefix}:${userId}:${workspaceId || 'personal'}:${agentId}` : undefined;++export const rememberedSandboxDirectoryKey = (scope: RememberScope, agentId: string) =>+ scopedKey(REMEMBERED_SANDBOX_DIRECTORY_PREFIX, scope, agentId);++export const rememberedSandboxRepositoryKey = (scope: RememberScope, agentId: string) =>+ scopedKey(REMEMBERED_SANDBOX_REPOSITORY_PREFIX, scope, agentId);++const readEntry = (key: string): unknown => {+ try {+ const raw = localStorage.getItem(key);+ return raw ? JSON.parse(raw) : undefined;+ } catch {+ return undefined;+ }+};++const isValid = (value: unknown): value is RememberedSandboxDirectory => {+ if (!value || typeof value !== 'object') return false;+ const { drive, workingDirectory } = value as RememberedSandboxDirectory;+ if (typeof workingDirectory !== 'string' || !workingDirectory) return false;+ return drive === undefined || drive === 'personal' || drive === 'public';+};++/** The folder this agent's last conversation was pointed at, if any. */+export const getRememberedSandboxDirectory = (+ scope: RememberScope,+ agentId: string,+): RememberedSandboxDirectory | undefined => {+ const key = rememberedSandboxDirectoryKey(scope, agentId);+ if (!key) return undefined;++ const value = readEntry(key);+ if (!isValid(value)) return undefined;++ return value.drive+ ? { drive: value.drive, workingDirectory: value.workingDirectory }+ : { workingDirectory: value.workingDirectory };+};++/**+ * What the agent's last temporary sandbox was initialized from: `{ environmentId }`+ * for a repository, `{}` for none picked on purpose, `undefined` when nothing+ * is remembered yet.+ */+export const getRememberedSandboxRepository = (+ scope: RememberScope,+ agentId: string,+): Pick<SandboxSelection, 'environmentId'> | undefined => {+ const key = rememberedSandboxRepositoryKey(scope, agentId);+ if (!key) return undefined;++ const value = readEntry(key) as { environmentId?: unknown } | undefined;+ if (!value || typeof value !== 'object') return undefined;+ if (value.environmentId === undefined) return {};+ return typeof value.environmentId === 'string' && value.environmentId+ ? { environmentId: value.environmentId }+ : undefined;+};++/**+ * Remember a pick so the next conversation starts where this one was put:+ *+ * - a folder on the drive β the persistent sandbox β is remembered as its+ * folder;+ * - the temporary sandbox is remembered as the repository it starts from, or+ * as none; the folder memory stays, for the next time the persistent+ * sandbox is used;+ * - a legacy environment directory says nothing about either and changes+ * nothing.+ *+ * Storage unavailable (private mode, quota) is ignored: the next conversation+ * starts at the plan's default, as it did before anything was remembered.+ */+export const rememberSandboxSelection = (+ scope: RememberScope,+ agentId: string,+ selection: SandboxSelection,+): void => {+ const key = rememberedSandboxDirectoryKey(scope, agentId);+ if (!key) return;++ const repositoryKey = rememberedSandboxRepositoryKey(scope, agentId)!;+ if (selection.instanceId) return;++ try {+ if (selection.workingDirectory) {+ localStorage.setItem(+ key,+ JSON.stringify(+ selection.drive+ ? { drive: selection.drive, workingDirectory: selection.workingDirectory }+ : { workingDirectory: selection.workingDirectory },+ ),+ );+ return;+ }++ localStorage.setItem(+ repositoryKey,+ JSON.stringify(selection.environmentId ? { environmentId: selection.environmentId } : {}),+ );+ } catch {+ // Storage unavailable: nothing is remembered, as described above.+ }+};diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.tsindex 9018e4577de..408d063650f 100644--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts@@ -1,6 +1,10 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ getRememberedSandboxRepository,+ rememberSandboxSelection,+} from './rememberedSandboxDirectory';import {prefersTemporarySandbox,TEMPORARY_SANDBOX_PREFERENCE_KEY,@@ -46,7 +50,7 @@ const renderMode = () =>);beforeEach(() => {- localStorage.removeItem(TEMPORARY_SANDBOX_PREFERENCE_KEY);+ localStorage.clear();state.driveStatus = 'ready';state.selection = {};state.topicId = undefined;@@ -124,6 +128,46 @@ describe('useSandboxModeSelect', () => {});});+ // T-14158: switching back to the persistent sandbox starts in the folder the+ // agent's last conversation used, like a new conversation does.+ it('gives a conversation back the remembered folder', async () => {+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'projects/demo' });++ const { result } = renderMode();+ await act(() => result.current.toPersistent());++ expect(state.seedPendingSandboxSelection).toHaveBeenCalledWith('agent-1', {+ workingDirectory: 'projects/demo',+ });+ });++ // Leaving the drive, a conversation starts from the repository the agent's+ // last temporary sandbox used.+ it('moves a conversation off the drive onto the remembered repository', async () => {+ state.topicId = 'topic-1';+ state.selection = { workingDirectory: 'notes' } satisfies SandboxSelection;+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_repo' });++ const { result } = renderMode();+ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env_repo' });+ });++ it('remembers the repository a conversation leaves the drive with', async () => {+ state.topicId = 'topic-1';+ state.selection = {+ environmentId: 'env_old',+ workingDirectory: 'notes',+ } satisfies SandboxSelection;++ const { result } = renderMode();+ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env_old' });+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_old' });+ });+it('remembers nothing without a drive service', async () => {state.driveStatus = 'hidden';diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.tsindex f8f59895512..12e16522582 100644--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts@@ -6,6 +6,11 @@ import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';+import {+ getRememberedSandboxDirectory,+ getRememberedSandboxRepository,+ rememberSandboxSelection,+} from './rememberedSandboxDirectory';import { setPrefersTemporarySandbox } from './temporarySandboxPreference';import {isPersistentSelection,@@ -53,17 +58,34 @@ export const useSandboxModeSelect = (// Remembered only once the conversation has moved: a failed write leaves// it where it was, and new conversations must not start elsewhere.- if (onDrive) await setSelection(temporarySelection(selection));+ // Leaving the drive, the conversation starts from the repository the+ // agent's last temporary sandbox used, or none.+ if (onDrive) {+ const next =+ getRememberedSandboxRepository({ userId, workspaceId }, agentId) ??+ temporarySelection(selection);+ await setSelection(next);+ // What the conversation now runs on is what the next temporary sandbox+ // starts from, as a pick in the chip would be.+ rememberSandboxSelection({ userId, workspaceId }, agentId, next);+ }setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);}, [agentId, driveStatus, onDrive, selection, setSelection, userId, workspaceId]);const toPersistent = useCallback(async () => {if (!onDrive) {- const next = resolveDefaultSandboxSelection(workspaceId);+ // Back on the drive in the folder the agent's last conversation used,+ // the same default a new conversation gets.+ const next = resolveDefaultSandboxSelection(+ workspaceId,+ getRememberedSandboxDirectory({ userId, workspaceId }, agentId),+ );// A conversation not started yet gets the default as a default, not as a// pick: a project conversation is then still given its repository checkout.- if (scopeTopicId) await setSelection(next);- else seedPendingSandboxSelection(agentId, next);+ if (scopeTopicId) {+ await setSelection(next);+ rememberSandboxSelection({ userId, workspaceId }, agentId, next);+ } else seedPendingSandboxSelection(agentId, next);}// After the move, as above: a failed write keeps the old preference too.setPrefersTemporarySandbox({ userId, workspaceId }, agentId, false);diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.tsindex a41b9e4ad81..ae2379fd825 100644--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts@@ -120,6 +120,18 @@ describe('useSandboxPlacement', () => {expect(state.refreshTopicDetail).toHaveBeenCalledWith('fresh-topic', true);});+ // The write has landed when the read-back runs; its failure must not make+ // the pick look failed (and so go unremembered for the next conversation).+ it('resolves a pick whose save landed even if the read-back fails', async () => {+ state.refreshTopicDetail.mockRejectedValueOnce(new Error('offline'));+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'fresh-topic'));++ await expect(+ act(() => result.current.setSelection({ workingDirectory: 'reports' })),+ ).resolves.toBeUndefined();+ expect(state.updateTopicMetadata).toHaveBeenCalled();+ });+it('leaves a listed topic to the list it is in', async () => {const { result } = renderHook(() => useSandboxPlacement('agent-1', 'pane-topic'));diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.tsindex 2ae160237d3..8165ff87cc8 100644--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.ts@@ -1,3 +1,4 @@+import debug from 'debug';import { useCallback, useSyncExternalStore } from 'react';import { useChatStore } from '@/store/chat';@@ -8,6 +9,8 @@ import {} from '@/store/chat/pendingSandboxSelection';import { topicSelectors } from '@/store/chat/selectors';+const log = debug('lobe-client:sandbox:placement');+/*** Where a conversation's cloud sandbox works, and what it starts from. Nothing* chosen is a temporary sandbox; choosing a folder IS the choice to keep files:@@ -101,7 +104,15 @@ export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | nul});// Written straight to the server when no list holds the topic; read it// back so the pick shows rather than looking ignored until a reload.- if (isUnlisted) await refreshTopicDetail(topicId, true);+ // The save itself has landed by now; a failed read-back only delays+ // the chip showing it, and must not make the pick look failed.+ if (isUnlisted) {+ try {+ await refreshTopicDetail(topicId, true);+ } catch (error) {+ log('Failed to read back topic %s after a sandbox pick: %O', topicId, error);+ }+ }},[agentId, isUnlisted, refreshTopicDetail, topicId, updateTopicMetadata],);diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.tsindex 2fc22852ae4..456c1b48c87 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts@@ -8,6 +8,7 @@ import {setPendingSandboxSelection,} from '@/store/chat/pendingSandboxSelection';+import { rememberSandboxSelection } from './rememberedSandboxDirectory';import { useSeedDefaultSelection } from './useSeedDefaultSelection';const getEntitlement = vi.hoisted(() => vi.fn());@@ -16,6 +17,12 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({useActiveWorkspaceId: () => null,}));+const user = vi.hoisted(() => ({ id: 'user-a' as string | undefined }));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: object) => unknown) => selector({ user: { id: user.id } }),+}));+vi.mock('@/services/sandboxStorage', () => ({sandboxStorageService: { getEntitlement },}));@@ -30,6 +37,8 @@ const AGENT = 'agent-seed';afterEach(() => {consumePendingSandboxSelection(AGENT);getEntitlement.mockReset();+ localStorage.clear();+ user.id = 'user-a';});describe('useSeedDefaultSelection', () => {@@ -76,4 +85,52 @@ describe('useSeedDefaultSelection', () => {workingDirectory: '.',});});++ // T-14158: every new conversation went back to the drive's root.+ it('starts the next conversation in the folder the last one was put in', () => {+ const { rerender } = renderHook(+ ({ hasTopic }) =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: true, hasTopic }),+ { initialProps: { hasTopic: false } },+ );+ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: '.' });++ // The first send consumes the slot; the person then moves the conversation.+ consumePendingSandboxSelection(AGENT);+ rerender({ hasTopic: true });+ rememberSandboxSelection({ userId: 'user-a' }, AGENT, { workingDirectory: 'projects/demo' });++ // A new conversation opens.+ rerender({ hasTopic: false });+ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'projects/demo' });+ });++ it('registers the remembered folder for a send made before the entitlement loads', async () => {+ getEntitlement.mockResolvedValue({ entitled: true });+ rememberSandboxSelection({ userId: 'user-a' }, AGENT, { workingDirectory: 'projects/demo' });++ renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: false, hasTopic: false }),+ );++ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toEqual({+ workingDirectory: 'projects/demo',+ });+ });++ // On a cold boot the persisted entitlement can be ready before the user id;+ // the root seeded meanwhile must give way once the remembered folder is readable.+ it('replaces the provisional root once the user id arrives', () => {+ rememberSandboxSelection({ userId: 'user-a' }, AGENT, { workingDirectory: 'projects/demo' });+ user.id = undefined;+ const { rerender } = renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: true, hasTopic: false }),+ );+ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: '.' });++ user.id = 'user-a';+ rerender();++ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'projects/demo' });+ });});diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.tsindex 4246839b7a7..6b7f08c63df 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts@@ -3,15 +3,24 @@ import { useEffect } from 'react';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import {getPendingSandboxSelection,+ isSeededSandboxSelection,seedPendingSandboxSelection,setSandboxDefaultSelection,+ setSandboxTemporaryDefaultSelection,} from '@/store/chat/pendingSandboxSelection';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';+import {+ getRememberedSandboxDirectory,+ getRememberedSandboxRepository,+} from './rememberedSandboxDirectory';/*** Give a conversation that does not exist yet the plan's default place to- * work: an account with a drive keeps its files unless it says otherwise. Only+ * work: an account with a drive keeps its files unless it says otherwise, in the+ * folder the agent's last conversation was put in when there is one. Only* fills an empty slot β a pick, including the temporary sandbox, stays β and* only before the topic exists, so a conversation already running never moves.* Sending consumes the slot, and the next new conversation is seeded again.@@ -27,19 +36,82 @@ export const useSeedDefaultSelection = ({ eligible, entitled, hasTopic }: { eligible: boolean; entitled: boolean; hasTopic: boolean },) => {const workspaceId = useActiveWorkspaceId();+ const userId = useUserStore(userProfileSelectors.userId);// Cleared on unmount as well: once the run moves off the sandbox, nothing- // should hand a sandbox folder to a conversation on a machine.+ // should hand a sandbox folder to a conversation on a machine. Registered+ // again whenever a new conversation opens, so it carries the folder picked+ // in the conversation before.useEffect(() => {if (!eligible) return;- setSandboxDefaultSelection(agentId, resolveDefaultSandboxSelection(workspaceId));+ setSandboxDefaultSelection(+ agentId,+ resolveDefaultSandboxSelection(+ workspaceId,+ getRememberedSandboxDirectory({ userId, workspaceId }, agentId),+ ),+ );return () => setSandboxDefaultSelection(agentId);- }, [agentId, eligible, workspaceId]);+ }, [agentId, eligible, hasTopic, userId, workspaceId]);++ useEffect(() => {+ if (!entitled || hasTopic) return;+ // A pick stays; a default filled in earlier is provisional and is filled in+ // again β the user id can arrive after the entitlement on a cold boot, and+ // the remembered folder only becomes readable then.+ const pending = getPendingSandboxSelection(agentId);+ if (pending && !isSeededSandboxSelection(pending)) return;++ seedPendingSandboxSelection(+ agentId,+ resolveDefaultSandboxSelection(+ workspaceId,+ getRememberedSandboxDirectory({ userId, workspaceId }, agentId),+ ),+ );+ }, [agentId, entitled, hasTopic, userId, workspaceId]);+};++/**+ * The temporary sandbox's counterpart: a conversation that does not exist yet,+ * for an agent whose new conversations start in the temporary sandbox, starts+ * from the repository the agent's last temporary sandbox used β or from none,+ * which is the temporary sandbox's own default and needs nothing filled in.+ *+ * Filled in as a default rather than a pick, the same as the folder: a pick+ * stays, and a project conversation is still given its project's checkout.+ */+export const useSeedTemporaryRepository = (+ agentId: string,+ { eligible, hasTopic, temporary }: { eligible: boolean; hasTopic: boolean; temporary: boolean },+) => {+ const workspaceId = useActiveWorkspaceId();+ const userId = useUserStore(userProfileSelectors.userId);++ // Registered as soon as the run is known to use the sandbox β before the+ // entitlement β so a first send that turns out to have no drive still+ // starts from the remembered repository. Cleared on unmount, like the drive+ // default.+ useEffect(() => {+ if (!eligible) return;+ const environmentId = getRememberedSandboxRepository(+ { userId, workspaceId },+ agentId,+ )?.environmentId;+ setSandboxTemporaryDefaultSelection(agentId, environmentId ? { environmentId } : undefined);+ return () => setSandboxTemporaryDefaultSelection(agentId);+ }, [agentId, eligible, hasTopic, userId, workspaceId]);useEffect(() => {- if (!entitled || hasTopic || getPendingSandboxSelection(agentId)) return;+ if (!temporary || hasTopic) return;+ const pending = getPendingSandboxSelection(agentId);+ if (pending && !isSeededSandboxSelection(pending)) return;- seedPendingSandboxSelection(agentId, resolveDefaultSandboxSelection(workspaceId));- }, [agentId, entitled, hasTopic, workspaceId]);+ const environmentId = getRememberedSandboxRepository(+ { userId, workspaceId },+ agentId,+ )?.environmentId;+ if (environmentId) seedPendingSandboxSelection(agentId, { environmentId });+ }, [agentId, hasTopic, temporary, userId, workspaceId]);};diff --git a/src/store/chat/pendingSandboxSelection.test.ts b/src/store/chat/pendingSandboxSelection.test.tsindex 9384e914f0b..50a2f325085 100644--- a/src/store/chat/pendingSandboxSelection.test.ts+++ b/src/store/chat/pendingSandboxSelection.test.ts@@ -7,6 +7,7 @@ import {seedPendingSandboxSelection,setPendingSandboxSelection,setSandboxDefaultSelection,+ setSandboxTemporaryDefaultSelection,subscribePendingSandboxSelection,toSandboxTopicMetadata,} from './pendingSandboxSelection';@@ -171,4 +172,38 @@ describe('pendingSandboxSelection', () => {setSandboxDefaultSelection('agent-offline');});});++ // A plan without a drive learns so only from the entitlement; a first send+ // made before then still starts from the remembered repository.+ describe('temporary-sandbox default', () => {+ it('is carried by a first send once the plan turns out to have no drive', async () => {+ mocks.cachedEntitlement = undefined;+ mocks.getEntitlement.mockResolvedValueOnce({ entitled: false });+ setSandboxDefaultSelection('agent-nodrive', { workingDirectory: '.' });+ setSandboxTemporaryDefaultSelection('agent-nodrive', { environmentId: 'env_repo' });++ await expect(resolvePendingSandboxSelection('agent-nodrive')).resolves.toEqual({+ environmentId: 'env_repo',+ });++ consumePendingSandboxSelection('agent-nodrive');+ setSandboxDefaultSelection('agent-nodrive');+ setSandboxTemporaryDefaultSelection('agent-nodrive');+ });++ it('gives way to the drive default when the plan has a drive', async () => {+ mocks.cachedEntitlement = { entitled: true };+ setSandboxDefaultSelection('agent-drive', { workingDirectory: 'notes' });+ setSandboxTemporaryDefaultSelection('agent-drive', { environmentId: 'env_repo' });++ await expect(resolvePendingSandboxSelection('agent-drive')).resolves.toEqual({+ workingDirectory: 'notes',+ });++ mocks.cachedEntitlement = undefined;+ consumePendingSandboxSelection('agent-drive');+ setSandboxDefaultSelection('agent-drive');+ setSandboxTemporaryDefaultSelection('agent-drive');+ });+ });});diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.tsindex 78198a71410..969ddc121ba 100644--- a/src/store/chat/pendingSandboxSelection.ts+++ b/src/store/chat/pendingSandboxSelection.ts@@ -93,6 +93,24 @@ export const setSandboxDefaultSelection = (agentId: string, selection?: SandboxSelse defaults.delete(agentId);};+/**+ * Where an agent's next conversation starts when it runs in the temporary+ * sandbox β the repository its last temporary sandbox used. Registered beside+ * the drive default so a first send made before the entitlement is known+ * still carries it once the plan turns out to have no drive.+ */+const temporaryDefaults = new Map<string, SandboxSelection>();++/** Register an agent's temporary-sandbox default; `undefined` clears it. */+export const setSandboxTemporaryDefaultSelection = (+ agentId: string,+ selection?: SandboxSelection,+): void => {+ if (selection) seeded.add(selection);+ if (selection) temporaryDefaults.set(agentId, selection);+ else temporaryDefaults.delete(agentId);+};+/*** Whether the active workspace's plan includes a drive. A cached yes is taken* as is; a cached no is confirmed with the server first, because the cache is@@ -115,8 +133,9 @@ const isDriveEntitled = async (): Promise<boolean> => {/*** The selection the first send carries: the pick, if one was made; otherwise- * the registered default, once the plan is confirmed to include a drive. The- * default then becomes the pick, so every later reader of this send sees it.+ * the registered drive default, once the plan is confirmed to include a drive;+ * otherwise the registered temporary-sandbox default. That default then+ * becomes the pick, so every later reader of this send sees it.*/export const resolvePendingSandboxSelection = async (agentId: string,@@ -124,8 +143,9 @@ export const resolvePendingSandboxSelection = async (const picked = map.get(agentId);if (picked) return picked;- const fallback = defaults.get(agentId);- if (!fallback || !(await isDriveEntitled())) return undefined;+ const drive = defaults.get(agentId);+ const fallback = drive && (await isDriveEntitled()) ? drive : temporaryDefaults.get(agentId);+ if (!fallback) return map.get(agentId);// A pick made while the entitlement was in flight wins over the default.if (!map.has(agentId)) setPendingSandboxSelection(agentId, fallback);