π€― 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(chat-input): offer a project conversation its own environment (#23477)
Rdmclin25f679b5f33e6
diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.tsindex be79e888da3..a71c9994252 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts@@ -74,3 +74,26 @@ describe('buildNewTopicMetadata β project directory', () => {expect(metadata?.workingDirectoryConfig).toEqual({ path: '/code/lobehub' });});});++// A draft's first send in a project: the composer's placement and whether it+// was picked must both reach `withProjectSandbox`, which decides from them+// whether the project's environment applies.+describe('buildNewTopicMetadata β cloud sandbox placement', () => {+ it('carries a temporary sandbox picked on purpose', () => {+ expect(+ buildNewTopicMetadata({+ appContext: { initialTopicMetadata: { sandboxTemporary: true } } as any,+ }),+ ).toMatchObject({ sandboxTemporary: true });+ });++ it('carries a default environment nobody picked as such', () => {+ expect(+ buildNewTopicMetadata({+ appContext: {+ initialTopicMetadata: { sandboxEnvironmentId: 'env-1', sandboxSeeded: true },+ } as any,+ }),+ ).toMatchObject({ sandboxEnvironmentId: 'env-1', sandboxSeeded: true });+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.ts b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.tsindex 186b4b90b68..5c324e30ed5 100644--- a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.ts@@ -18,6 +18,15 @@ describe('pickSandboxPlacement', () => {).toEqual({ sandboxDrive: 'personal', sandboxWorkingDirectory: 'notes' });});+ // A project conversation decides from these whether its environment applies.+ it('carries whether the placement is a default or a temporary sandbox picked on purpose', () => {+ expect(pickSandboxPlacement({ sandboxEnvironmentId: 'env-1', sandboxSeeded: true })).toEqual({+ sandboxEnvironmentId: 'env-1',+ sandboxSeeded: true,+ });+ expect(pickSandboxPlacement({ sandboxTemporary: true })).toEqual({ sandboxTemporary: true });+ });+it('carries nothing for a conversation that chose nothing', () => {expect(pickSandboxPlacement(undefined)).toEqual({});expect(pickSandboxPlacement({})).toEqual({});diff --git a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.ts b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.tsindex f8e63e31ab7..c6f9ff4ff9b 100644--- a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.ts+++ b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.ts@@ -4,11 +4,23 @@ import type { InitialTopicMetadata } from '@lobechat/types';* The cloud-sandbox placement a first send carries onto the topic it creates β* a folder on one of the workspace's drives and the environment to initialize* it from β without the keys it does not set, so an unset one never lands on the row as an explicit blank.+ *+ * Its creation-time markers ride along: whether the placement is a default+ * nobody picked (`sandboxSeeded`) or a temporary sandbox picked on purpose+ * (`sandboxTemporary`). A project conversation reads them to decide whether+ * its environment applies (see `withProjectSandbox`, which drops them before+ * the row is written); without them a default reads as a pick, and a pick of+ * no environment as nothing picked.*/export const pickSandboxPlacement = (metadata?: Pick<InitialTopicMetadata,- 'sandboxDrive' | 'sandboxEnvironmentId' | 'sandboxInstanceId' | 'sandboxWorkingDirectory'+ | 'sandboxDrive'+ | 'sandboxEnvironmentId'+ | 'sandboxInstanceId'+ | 'sandboxSeeded'+ | 'sandboxTemporary'+ | 'sandboxWorkingDirectory'>,) => ({...(metadata?.sandboxDrive && { sandboxDrive: metadata.sandboxDrive }),@@ -17,4 +29,6 @@ export const pickSandboxPlacement = (...(metadata?.sandboxWorkingDirectory && {sandboxWorkingDirectory: metadata.sandboxWorkingDirectory,}),+ ...(metadata?.sandboxSeeded && { sandboxSeeded: true }),+ ...(metadata?.sandboxTemporary && { sandboxTemporary: true }),});diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxindex 519358d092b..bb945b20ec2 100644--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -25,22 +25,20 @@ import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/Createimport { SANDBOX_STORAGE_PATH } from '@/features/ResourceHome/paths';import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { environmentService } from '@/services/environment';import { refreshProjectFiles } from '@/services/projectFile';import { sandboxStorageService } from '@/services/sandboxStorage';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';import OptionRow from './OptionRow';import SandboxDriveMenu from './SandboxDriveMenu';import {environmentChipState,- pickableEnvironments,+ environmentSettingsPath,repositoriesLabel,repositorySelection,repositorySlug,} from './sandboxEnvironmentOptions';import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';+import { useSandboxEnvironmentList } from './useSandboxEnvironmentList';import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';@@ -96,6 +94,14 @@ interface SandboxDrivePickerProps {*/modeInEnvironmentMenu?: boolean;onChange: (selection: SandboxSelection) => Promise<void>;+ /**+ * The project this conversation belongs to. It runs in the project's own+ * environment, so that is the only one offered, and managed on the+ * project's settings rather than in the workspace's list.+ */+ projectId?: string;+ /** Whether the conversation's agent is workspace-public; it applies published environments only. */+ sharedAgent?: boolean;topicId?: string;/** Where this conversation works today. */value: SandboxSelection;@@ -127,7 +133,15 @@ const folderName = (path: string) => path.split('/').pop() || path;* replaces it.*/const SandboxDrivePicker = memo<SandboxDrivePickerProps>(- ({ entitled, modeInEnvironmentMenu = true, onChange, topicId, value }) => {+ ({+ entitled,+ modeInEnvironmentMenu = true,+ onChange,+ projectId,+ sharedAgent = false,+ topicId,+ value,+ }) => {const { t } = useTranslation(['chat', 'device']);const [open, setOpen] = useState(false);const workspaceId = useActiveWorkspaceId();@@ -142,24 +156,19 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(const repositoryOnly = modeInEnvironmentMenu && !onDrive;const {- data: environmentList,- error: environmentsError,- mutate: refreshEnvironments,- } = useSWR(['sandbox-environment-chip', workspaceId ?? ''], () =>- environmentService.listEnvironments(),- );- const sharedAgent = useAgentStore(- (s) => !!workspaceId && agentSelectors.currentAgentVisibility(s) === 'public',- );- const environments = pickableEnvironments(environmentList?.environments ?? [], sharedAgent);+ environments,+ failed: environmentsFailed,+ loaded: environmentsLoaded,+ refresh: refreshEnvironments,+ } = useSandboxEnvironmentList({ projectId, sharedAgent, workspaceId });const repository = environments.find((item) => item.id === value.environmentId);// Picked once but no longer readable β deleted, or unpublished by its owner// β is said rather than hidden; a list that has not loaded says nothing.const repositoryState = environmentChipState({current: repository,environmentId: value.environmentId,- failed: !!environmentsError,- loaded: !!environmentList,+ failed: environmentsFailed,+ loaded: environmentsLoaded,});// A legacy environment directory's own row, for its name β from the@@ -306,13 +315,15 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(const repositoryMenuProps = {environments,- failed: !!environmentsError,- loaded: !!environmentList,- onAdd: addRepository,+ failed: environmentsFailed,+ loaded: environmentsLoaded,+ // A project has exactly one environment, edited on its settings: there+ // is no second one to add from here.+ onAdd: projectId ? undefined : addRepository,onClose: () => setOpen(false),onManage: () => {setOpen(false);- navigate('/settings/environments');+ navigate(environmentSettingsPath(projectId));},onPick: pickRepository,onRetry: () => void refreshEnvironments(),diff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsxindex 88a3bacdd4b..146337f592e 100644--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx+++ b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx@@ -43,7 +43,8 @@ interface SandboxRepositoryMenuProps {* empty one β rather than one level under a list of places.*/none?: { active: boolean; onPick: () => void };- onAdd: () => void;+ /** Adds an environment and picks it. Absent where there is no other one to add β a project's. */+ onAdd?: () => void;/** Closes the whole work-location menu; a final pick leaves it. */onClose: () => void;onManage: () => void;@@ -136,12 +137,14 @@ const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(</Flexbox>)}- <OptionRow- compact- icon={<Icon icon={PlusIcon} size={16} />}- label={t('sandboxEnvironment.add')}- onClick={onAdd}- />+ {onAdd && (+ <OptionRow+ compact+ icon={<Icon icon={PlusIcon} size={16} />}+ label={t('sandboxEnvironment.add')}+ onClick={onAdd}+ />+ )}</Flexbox>);},diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsxindex 7359ffeb6b5..0aafbd7abf6 100644--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -12,9 +12,15 @@ import { userProfileSelectors } from '@/store/user/selectors';import { useTopicId } from '../hooks/useTopicId';import { rememberSandboxSelection } from './rememberedSandboxDirectory';import SandboxDrivePicker from './SandboxDrivePicker';+import { projectStartEnvironmentId } from './sandboxEnvironmentOptions';import { usePrefersTemporarySandbox } from './temporarySandboxPreference';import { useFollowSandboxModePreference } from './useFollowSandboxModePreference';-import { type SandboxSelection, useSandboxPlacement } from './useSandboxPlacement';+import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';+import {+ isPersistentSelection,+ type SandboxSelection,+ useSandboxPlacement,+} from './useSandboxPlacement';import { useSandboxStorageAccess } from './useSandboxStorageAccess';import { useSeedDefaultSelection, useSeedTemporaryRepository } from './useSeedDefaultSelection';@@ -43,7 +49,19 @@ interface SandboxStorageSectionProps {const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {const { eligible, status } = useSandboxStorageAccess(agentId);const scopeTopicId = useTopicId();- const { selection, setSelection, topicId } = useSandboxPlacement(agentId, scopeTopicId);+ // A project conversation runs in its project's environment.+ const { projectId, selection, setSelection, topicId } = useSandboxPlacement(+ agentId,+ scopeTopicId,+ );+ const workspaceId = useActiveWorkspaceId();+ const sharedAgent = useIsSharedAgent(agentId);+ // Only a run in the sandbox needs the project's environment.+ const { environments: projectEnvironments } = useProjectSandboxEnvironments(+ projectId,+ sharedAgent,+ eligible,+ );// The temporary and persistent sandboxes are picked in the execution// environment menu β when this member can use it. A target the author fixed// leaves that menu read-only, so the choice stays in this one.@@ -55,7 +73,6 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }const modeInEnvironmentMenu =canUseResource && canDisplayExecutionTarget && canSelectExecutionTarget;const userId = useUserStore(userProfileSelectors.userId);- const workspaceId = useActiveWorkspaceId();const prefersTemporary = usePrefersTemporarySandbox({ userId, workspaceId }, agentId);// Only a pick made in that menu counts; a member who cannot make it is not// held to one made before the target was fixed.@@ -68,13 +85,16 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }});// 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.+ // one. A failed save is not, and neither is an environment picked inside a+ // project: it belongs to that project, and the agent's next conversation+ // elsewhere could not use it. A drive folder is usable anywhere.const pick = useCallback(async (next: SandboxSelection) => {await setSelection(next);- rememberSandboxSelection({ userId, workspaceId }, agentId, next);+ if (!projectId || isPersistentSelection(next))+ rememberSandboxSelection({ userId, workspaceId }, agentId, next);},- [agentId, setSelection, userId, workspaceId],+ [agentId, projectId, setSelection, userId, workspaceId],);useSeedDefaultSelection(agentId, {eligible: eligible && !temporary,@@ -87,6 +107,9 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }useSeedTemporaryRepository(agentId, {eligible,hasTopic: !!topicId,+ project: projectId+ ? { environmentId: projectStartEnvironmentId(projectEnvironments) }+ : undefined,temporary: eligible && (temporary || status === 'upgrade'),});@@ -96,6 +119,8 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }<SandboxDrivePickerentitled={status === 'ready'}modeInEnvironmentMenu={modeInEnvironmentMenu}+ projectId={projectId}+ sharedAgent={sharedAgent}topicId={topicId}value={selection}onChange={pick}diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsxindex 47cc4c6919c..66b17c2ac4e 100644--- a/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx@@ -46,6 +46,13 @@ vi.mock('@/services/sandboxStorage', () => ({resolveSessionPlacement: vi.fn(async () => ({})),},}));+// A project's environment lives only in the project's own list.+vi.mock('@/store/projectWorkingDirectory', () => ({+ useProjectDirectoryStore: (selector: (s: object) => unknown) =>+ selector({ useFetchEnvironments: (projectId?: string) => ({ hasData: !!projectId }) }),+ useProjectEnvironments: (projectId?: string) =>+ projectId ? [{ id: 'env-project', name: 'Lobe Write', visibility: 'private' }] : [],+}));vi.mock('@/store/agent', () => ({useAgentStore: (selector: (s: object) => unknown) => selector({}),}));@@ -62,8 +69,10 @@ vi.mock('../SandboxRepositoryMenu', () => ({none ? <div data-testid="repository-menu">{none.active ? 'none-active' : 'none'}</div> : null,}));-const renderPicker = (value: SandboxSelection, props: { modeInEnvironmentMenu?: boolean } = {}) =>- render(<SandboxDrivePicker entitled value={value} onChange={vi.fn()} {...props} />);+const renderPicker = (+ value: SandboxSelection,+ props: { modeInEnvironmentMenu?: boolean; projectId?: string } = {},+) => render(<SandboxDrivePicker entitled value={value} onChange={vi.fn()} {...props} />);// T-14161: the sandbox kind is picked in the execution-environment menu, so// this menu only asks what is left for that kind.@@ -99,6 +108,15 @@ describe('SandboxDrivePicker', () => {expect(screen.getByTestId('repository-menu').textContent).toBe('none');});+ // A project conversation starts in its project's environment, which the+ // workspace's shared list leaves out: the chip read "unavailable".+ it("names a project conversation's own environment on the chip", () => {+ renderPicker({ environmentId: 'env-project' }, { projectId: 'project-1' });++ expect(screen.getByTestId('sandbox-drive-chip').textContent).toContain('Lobe Write');+ expect(screen.queryByText('sandboxEnvironment.missing')).toBeNull();+ });+// A member of a workspace agent whose author fixed the target sees the// execution environment read-only; the placement is still theirs to change.it('keeps temporary and drive side by side when the environment menu is locked', () => {diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsxindex e124452be6c..9b255f43fe8 100644--- a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx@@ -28,6 +28,14 @@ const state = vi.hoisted(() => {topicId: null as string | null,userId: 'user-a' as string | undefined,topics: {} as Record<string, Record<string, unknown>>,+ /** The project each conversation belongs to, when it does. */+ topicProjects: {} as Record<string, string>,+ /** Topics a first send is creating, before the pane moves to them. */+ creating: [] as string[],+ /** The blank project draft a sidebar "+" staged. */+ draft: undefined as { agentId: string; projectId: string } | undefined,+ /** Each project's environments. */+ projectEnvironments: {} as Record<string, { configuration?: unknown; id: string }[]>,updateTopicMetadata: vi.fn(),version: 0,};@@ -47,10 +55,15 @@ vi.mock('@/store/chat', () => ({useVersion();return selector({activeTopicId: state.topicId ?? undefined,+ creatingTopicIds: state.creating,+ pendingNewTopicDirectory: state.draft,refreshTopicDetail: vi.fn(),topicDataMap: {},topicDetailMap: Object.fromEntries(- Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),+ Object.entries(state.topics).map(([id, metadata]) => [+ id,+ { id, metadata, projectId: state.topicProjects[id], sessionId: AGENT },+ ]),),updateTopicMetadata: state.updateTopicMetadata,useFetchTopicDetail: vi.fn(),@@ -93,6 +106,12 @@ vi.mock('../temporarySandboxPreference', () => ({usePrefersTemporarySandbox: () => state.temporary,}));vi.mock('../useFollowSandboxModePreference', () => ({ useFollowSandboxModePreference: () => {} }));+vi.mock('../useSandboxEnvironmentList', () => ({+ useIsSharedAgent: () => false,+ useProjectSandboxEnvironments: (projectId?: string) => ({+ environments: projectId ? (state.projectEnvironments[projectId] ?? []) : [],+ }),+}));vi.mock('@/services/sandboxStorage', () => ({sandboxStorageService: { getEntitlement: vi.fn() },}));@@ -106,12 +125,15 @@ vi.mock('@/store/sandbox', () => ({vi.mock('../SandboxDrivePicker', () => ({default: ({onChange,+ projectId,value,}: {onChange: (s: SandboxSelection) => Promise<void>;+ projectId?: string;value: SandboxSelection;}) => (<div>+ <span data-testid="project">{projectId ?? ''}</span><span data-testid="chip">{value.workingDirectory ??(value.environmentId ? `repo:${value.environmentId}` : 'temporary')}@@ -134,6 +156,18 @@ beforeEach(() => {state.topicId = null;state.userId = 'user-a';state.topics = {};+ state.topicProjects = {};+ state.draft = undefined;+ state.creating = [];+ state.projectEnvironments = {+ 'project-1': [+ {+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobe-write' }] },+ id: 'env-project',+ },+ ],+ 'project-empty': [{ configuration: { sources: [] }, id: 'env-empty' }],+ };state.updateTopicMetadata.mockReset().mockImplementation(async (id, metadata) => {state.topics[id] = { ...state.topics[id], ...metadata };commit();@@ -205,6 +239,19 @@ describe('SandboxStorageSection β T-14158', () => {expect(screen.getByTestId('chip').textContent).toBe('projects/demo');});+ // A drive folder is usable anywhere, so one picked in a project is kept for+ // the agent's next conversation like any other.+ it('remembers a drive folder picked in a project conversation', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ state.topicProjects['topic-1'] = 'project-1';+ send('topic-1');++ await act(async () => fireEvent.click(screen.getByText('pick-folder')));++ 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');@@ -240,6 +287,108 @@ describe('SandboxStorageSection β T-14158', () => {});});+ // A project conversation runs in its project's environment, which the+ // agent's conversations elsewhere cannot use: picking it there must not+ // become where the next one starts.+ it("does not carry a project conversation's environment to the next conversation", async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ state.topicProjects['topic-1'] = 'project-1';+ await send('topic-1');+ expect(screen.getByTestId('project').textContent).toBe('project-1');++ await act(async () => fireEvent.click(screen.getByText('pick-repo')));+ expect(state.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ sandboxEnvironmentId: 'env_repo' }),+ );++ openNewConversation();+ expect(screen.getByTestId('project').textContent).toBe('');+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ });++ // A project's blank draft starts where the server will put it β the+ // project's environment β not on the agent's repository from elsewhere.+ it("starts a project draft on the project's environment", async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ await send('topic-1');+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));++ openNewConversation();+ expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');++ act(() => {+ state.draft = { agentId: AGENT, projectId: 'project-1' };+ commit();+ });+ expect(screen.getByTestId('project').textContent).toBe('project-1');+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');++ // Still a default nobody picked: the server keeps applying the project's.+ send('topic-2');+ expect(state.topics['topic-2']).toMatchObject({+ sandboxEnvironmentId: 'env-project',+ sandboxSeeded: true,+ });+ });++ // The send reads the draft's default after it has minted the topic and+ // dropped the draft, but before this pane moves to the topic. Read as+ // outside the project then, the composer re-seeded the agent's repository+ // from elsewhere, and the conversation started in it.+ it("keeps a project draft's default while its first send creates the topic", async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ await send('topic-1');+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));+ openNewConversation();++ act(() => {+ state.draft = { agentId: AGENT, projectId: 'project-1' };+ commit();+ });+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');++ act(() => {+ state.draft = undefined;+ state.topics['minted-topic'] = {};+ state.topicProjects['minted-topic'] = 'project-1';+ state.creating = ['minted-topic'];+ commit();+ });+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');+ });++ // The draft's default is kept by agent, not by project: the agent's next+ // conversation outside the project must not inherit the project's.+ it("does not carry a project draft's environment to the agent's next conversation", async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ act(() => {+ state.draft = { agentId: AGENT, projectId: 'project-1' };+ commit();+ });+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');++ act(() => {+ state.draft = undefined;+ commit();+ });+ expect(screen.getByTestId('project').textContent).toBe('');+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ });++ it('starts a project draft on no environment when the project checks out no repository', async () => {+ render(<SandboxStorageSection agentId={AGENT} />);+ await send('topic-1');+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));+ openNewConversation();++ act(() => {+ state.draft = { agentId: AGENT, projectId: 'project-empty' };+ commit();+ });+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ });+it('starts the next new conversation without a repository when the last one used none', async () => {render(<SandboxStorageSection agentId={AGENT} />);await send('topic-1');diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.tsindex d2f660ea98f..ee5dce09204 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest';import {environmentChipState,+ environmentSettingsPath,pickableEnvironments,+ projectStartEnvironmentId,repositorySelection,repositorySlug,} from './sandboxEnvironmentOptions';@@ -72,6 +74,16 @@ describe('repositorySlug', () => {});});+describe('environmentSettingsPath', () => {+ it("manages a project conversation's environment on the project's settings", () => {+ expect(environmentSettingsPath('project-1')).toBe('/project/project-1/settings/environments');+ });++ it("manages any other conversation's environments in the workspace's list", () => {+ expect(environmentSettingsPath()).toBe('/settings/environments');+ });+});+describe('repositorySelection', () => {const repo = { id: 'env-repo', name: 'lobehub-biz/agent-mail' };@@ -79,3 +91,21 @@ describe('repositorySelection', () => {expect(repositorySelection(repo)).toEqual({ environmentId: 'env-repo' });});});++describe('projectStartEnvironmentId', () => {+ const git = { sources: [{ kind: 'git' as const, url: 'https://github.com/lobehub/lobe-write' }] };++ it('is the project environment that checks out a repository', () => {+ expect(projectStartEnvironmentId([{ configuration: git, id: 'env-project' }])).toBe(+ 'env-project',+ );+ });++ // The server applies no environment without a repository (see `resolveProjectTopicSandbox`).+ it('is none when the project environment checks out no repository', () => {+ expect(projectStartEnvironmentId([{ configuration: { sources: [] }, id: 'env-project' }])).toBe(+ undefined,+ );+ expect(projectStartEnvironmentId([])).toBeUndefined();+ });+});diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.tsindex 2e7aa2be208..704212b9946 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts@@ -1,5 +1,7 @@import type { EnvironmentConfiguration } from '@lobechat/types';+import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';+import type { SandboxSelection } from './useSandboxPlacement';/**@@ -76,6 +78,28 @@ export const environmentChipState = ({return failed ? { kind: 'loadFailed' } : { kind: 'loading' };};+/**+ * The environment the server applies to a project conversation nobody placed:+ * the project's, when it checks out a repository (see+ * `resolveProjectTopicSandbox`). Undefined while it loads, or when there is none.+ */+export const projectStartEnvironmentId = (+ environments: readonly {+ configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;+ id: string;+ }[],+) =>+ environments.find((environment) =>+ (environment.configuration?.sources ?? []).some((source) => source.kind === 'git'),+ )?.id;++/**+ * Where a conversation's environments are managed: a project's one on the+ * project's settings, anything else in the workspace's list.+ */+export const environmentSettingsPath = (projectId?: string) =>+ projectId ? getProjectSettingsPath(projectId, 'environments') : '/settings/environments';+/*** Where a conversation works once a repository is picked: a fresh temporary* sandbox the repository is cloned into. A repository is only cloned into andiff --git a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.ts b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.tsnew file mode 100644index 00000000000..39551fcf8cd--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.ts@@ -0,0 +1,118 @@+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ useIsSharedAgent,+ useProjectSandboxEnvironments,+ useSandboxEnvironmentList,+} from './useSandboxEnvironmentList';++const state = vi.hoisted(() => ({+ fetchEnvironments: vi.fn(),+ listEnvironments: vi.fn(),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => 'workspace-1',+}));+// The active agent is private; the conversation's own agent is workspace-public.+vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: object) => unknown) =>+ selector({+ activeAgentId: 'agent-private',+ agentMap: {+ 'agent-private': { visibility: 'private' },+ 'agent-public': { visibility: 'public' },+ },+ }),+}));+vi.mock('@/services/environment', () => ({+ environmentService: { listEnvironments: state.listEnvironments },+}));++const PROJECT_ENVIRONMENTS = [+ { id: 'env-project', name: 'Lobe Write', visibility: 'private' },+ { id: 'env-project-public', name: 'Lobe Write (public)', visibility: 'public' },+];++vi.mock('@/store/projectWorkingDirectory', () => ({+ useProjectDirectoryStore: (selector: (s: object) => unknown) =>+ selector({ useFetchEnvironments: state.fetchEnvironments }),+ useProjectEnvironments: (projectId?: string) => (projectId ? PROJECT_ENVIRONMENTS : []),+}));++beforeEach(() => {+ state.listEnvironments.mockReset().mockResolvedValue({+ environments: [{ id: 'env-shared', name: 'lobe-tts', visibility: 'private' }],+ });+ state.fetchEnvironments.mockReset().mockReturnValue({+ error: undefined,+ hasData: true,+ revalidate: vi.fn(),+ });+});++describe('useSandboxEnvironmentList', () => {+ // The workspace's shared list leaves a project's environment out, so a+ // project conversation showed its own environment as unavailable.+ it("offers a project conversation its project's environment, not the shared list", () => {+ const { result } = renderHook(() =>+ useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: false }),+ );++ expect(result.current.environments.map((e) => e.id)).toEqual([+ 'env-project',+ 'env-project-public',+ ]);+ expect(result.current.loaded).toBe(true);+ expect(state.fetchEnvironments).toHaveBeenCalledWith('project-1', true);+ expect(state.listEnvironments).not.toHaveBeenCalled();+ });++ it('offers a workspace-public agent the published project environment only', () => {+ const { result } = renderHook(() =>+ useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: true }),+ );++ expect(result.current.environments.map((e) => e.id)).toEqual(['env-project-public']);+ });++ it("reports the project list's failure rather than an empty list", () => {+ state.fetchEnvironments.mockReturnValue({ error: new Error('offline'), hasData: false });+ const { result } = renderHook(() =>+ useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: false }),+ );++ expect(result.current.failed).toBe(true);+ expect(result.current.loaded).toBe(false);+ });++ it("offers any other conversation the workspace's shared environments", async () => {+ const { result } = renderHook(() =>+ useSandboxEnvironmentList({ sharedAgent: false, workspaceId: 'workspace-1' }),+ );++ await waitFor(() => expect(result.current.loaded).toBe(true));+ expect(result.current.environments.map((e) => e.id)).toEqual(['env-shared']);+ // No project: its list is not fetched.+ expect(state.fetchEnvironments).toHaveBeenCalledWith(undefined, false);+ });+});++describe('useProjectSandboxEnvironments', () => {+ // The composer section renders for runs that never use the sandbox too.+ it('does not fetch while the run does not use the sandbox', () => {+ renderHook(() => useProjectSandboxEnvironments('project-1', false, false));++ expect(state.fetchEnvironments).toHaveBeenCalledWith('project-1', false);+ });+});++describe('useIsSharedAgent', () => {+ // A split or embedded conversation's agent need not be the active one, and+ // the server checks the topic's own agent.+ it("reads the conversation's own agent, not the active one", () => {+ expect(renderHook(() => useIsSharedAgent('agent-public')).result.current).toBe(true);+ expect(renderHook(() => useIsSharedAgent('agent-private')).result.current).toBe(false);+ });+});diff --git a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.tsnew file mode 100644index 00000000000..4cd5346508a--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts@@ -0,0 +1,83 @@+import useSWR from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { environmentService } from '@/services/environment';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';++import { pickableEnvironments } from './sandboxEnvironmentOptions';+import type { SandboxRepositoryOption } from './SandboxRepositoryMenu';++/**+ * Whether the conversation's agent is workspace-public. Such an agent runs on+ * its caller's session and applies published environments only. Read by the+ * conversation's own agent: in split or embedded views it need not be the+ * active one, and the server checks the topic's agent.+ */+export const useIsSharedAgent = (agentId: string) => {+ const workspaceId = useActiveWorkspaceId();+ return useAgentStore(+ (s) => !!workspaceId && agentSelectors.getAgentVisibilityById(agentId)(s) === 'public',+ );+};++export interface SandboxEnvironmentList {+ environments: SandboxRepositoryOption[];+ failed: boolean;+ loaded: boolean;+ refresh: () => Promise<unknown>;+}++/**+ * A project's environments a conversation may start from β every project has+ * exactly one. Fetched only while `enabled` and a project is given.+ */+export const useProjectSandboxEnvironments = (+ projectId: string | undefined,+ sharedAgent: boolean,+ enabled = true,+): SandboxEnvironmentList => {+ const sync = useProjectDirectoryStore((s) => s.useFetchEnvironments)(+ projectId,+ enabled && !!projectId,+ );+ const environments = useProjectEnvironments(projectId);++ return {+ environments: projectId ? pickableEnvironments(environments, sharedAgent) : [],+ failed: !!sync.error,+ loaded: sync.hasData,+ refresh: sync.revalidate,+ };+};++/**+ * The environments a conversation may start from. A project conversation runs+ * in its project's environment β the workspace's shared list leaves it out β+ * so it is offered that one alone. Any other conversation is offered the+ * workspace's shared environments. Only the list in use is fetched.+ */+export const useSandboxEnvironmentList = ({+ projectId,+ sharedAgent,+ workspaceId,+}: {+ projectId?: string;+ sharedAgent: boolean;+ workspaceId?: string | null;+}): SandboxEnvironmentList => {+ const shared = useSWR(projectId ? null : ['sandbox-environment-chip', workspaceId ?? ''], () =>+ environmentService.listEnvironments(),+ );+ const project = useProjectSandboxEnvironments(projectId, sharedAgent);++ if (projectId) return project;++ return {+ environments: pickableEnvironments(shared.data?.environments ?? [], sharedAgent),+ failed: !!shared.error,+ loaded: !!shared.data,+ refresh: () => shared.mutate(),+ };+};diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.tsindex 408d063650f..e1ab91ed5d7 100644--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts@@ -14,7 +14,13 @@ import type { SandboxSelection } from './useSandboxPlacement';const state = vi.hoisted(() => ({driveStatus: 'ready' as 'hidden' | 'loading' | 'ready' | 'upgrade',+ projectId: undefined as string | undefined,+ /** Whether the project's environment list has loaded, and what a refetch brings. */+ projectLoaded: true,+ refreshProject: vi.fn(),+ storeEnvironments: {} as Record<string, unknown[]>,seedPendingSandboxSelection: vi.fn(),+ setPendingSandboxSelection: vi.fn(),selection: {} as Record<string, unknown>,setSelection: vi.fn(),topicId: undefined as string | undefined,@@ -29,6 +35,27 @@ vi.mock('@/store/user', () => ({}));vi.mock('@/store/chat/pendingSandboxSelection', () => ({seedPendingSandboxSelection: state.seedPendingSandboxSelection,+ setPendingSandboxSelection: state.setPendingSandboxSelection,+}));+const PROJECT_ENVIRONMENTS: Record<string, { configuration: unknown; id: string }[]> = {+ 'project-1': [+ {+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobe-write' }] },+ id: 'env-project',+ },+ ],+ 'project-empty': [{ configuration: { sources: [] }, id: 'env-empty' }],+};+vi.mock('./useSandboxEnvironmentList', () => ({+ useIsSharedAgent: () => false,+ useProjectSandboxEnvironments: (projectId?: string) => ({+ environments: projectId && state.projectLoaded ? (PROJECT_ENVIRONMENTS[projectId] ?? []) : [],+ loaded: state.projectLoaded,+ refresh: state.refreshProject,+ }),+}));+vi.mock('@/store/projectWorkingDirectory', () => ({+ useProjectDirectoryStore: { getState: () => ({ environmentsMap: state.storeEnvironments }) },}));vi.mock('./useSandboxStorageAccess', () => ({useSandboxDriveStatus: () => state.driveStatus,@@ -36,6 +63,7 @@ vi.mock('./useSandboxStorageAccess', () => ({vi.mock('./useSandboxPlacement', async (importOriginal) => ({...(await importOriginal<object>()),useSandboxPlacement: () => ({+ projectId: state.projectId,selection: state.selection,setSelection: state.setSelection,topicId: state.topicId,@@ -52,10 +80,15 @@ const renderMode = () =>beforeEach(() => {localStorage.clear();state.driveStatus = 'ready';+ state.projectId = undefined;+ state.projectLoaded = true;+ state.storeEnvironments = {};+ state.refreshProject.mockReset().mockResolvedValue(undefined);state.selection = {};state.topicId = undefined;state.workspaceId = null;state.seedPendingSandboxSelection.mockReset();+ state.setPendingSandboxSelection.mockReset();state.setSelection.mockReset().mockResolvedValue(undefined);});@@ -214,3 +247,87 @@ describe('useSandboxModeSelect', () => {expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(true);});});++// A project conversation leaving the drive starts from its project's+// environment, never the agent's repository from elsewhere β which the chip,+// listing the project's environment only, would call unavailable.+describe('useSandboxModeSelect in a project conversation', () => {+ beforeEach(() => {+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_repo' });+ state.selection = { workingDirectory: 'notes' };+ });++ it("moves an open conversation onto the project's environment and remembers nothing", async () => {+ state.projectId = 'project-1';+ state.topicId = 'topic-1';+ const { result } = renderMode();++ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env-project' });+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_repo' });+ });++ // An open topic keeps what is written now; the server applies the project's+ // environment only when it creates one, so "none" is not written on a guess.+ it("waits for the project's environment before moving an open conversation", async () => {+ state.projectId = 'project-1';+ state.topicId = 'topic-1';+ state.projectLoaded = false;+ state.refreshProject.mockImplementation(async () => {+ state.storeEnvironments['project-1'] = PROJECT_ENVIRONMENTS['project-1'];+ });+ const { result } = renderMode();++ await act(() => result.current.toTemporary());++ expect(state.refreshProject).toHaveBeenCalled();+ expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env-project' });+ });++ it("keeps an open conversation on the drive when the project's environment cannot load", async () => {+ state.projectId = 'project-1';+ state.topicId = 'topic-1';+ state.projectLoaded = false;+ const { result } = renderMode();++ await expect(act(() => result.current.toTemporary())).rejects.toThrow('could not be loaded');++ expect(state.setSelection).not.toHaveBeenCalled();+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);+ });++ it('moves an open conversation onto no environment when the project checks out none', async () => {+ state.projectId = 'project-empty';+ state.topicId = 'topic-1';+ const { result } = renderMode();++ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({});+ });++ // Before a topic exists, a default rather than a pick: the server still+ // applies the project's environment.+ it("gives a project draft the project's environment as a default", async () => {+ state.projectId = 'project-1';+ const { result } = renderMode();++ await act(() => result.current.toTemporary());++ expect(state.seedPendingSandboxSelection).toHaveBeenCalledWith('agent-1', {+ environmentId: 'env-project',+ });+ expect(state.setSelection).not.toHaveBeenCalled();+ });++ it('leaves a project draft to the server when the project checks out none', async () => {+ state.projectId = 'project-empty';+ const { result } = renderMode();++ await act(() => result.current.toTemporary());++ expect(state.setPendingSandboxSelection).toHaveBeenCalledWith('agent-1');+ expect(state.setSelection).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.tsindex 12e16522582..d245eab5775 100644--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts@@ -1,7 +1,11 @@import { useCallback } from 'react';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { seedPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';+import {+ seedPendingSandboxSelection,+ setPendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -11,7 +15,9 @@ import {getRememberedSandboxRepository,rememberSandboxSelection,} from './rememberedSandboxDirectory';+import { pickableEnvironments, projectStartEnvironmentId } from './sandboxEnvironmentOptions';import { setPrefersTemporarySandbox } from './temporarySandboxPreference';+import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';import {isPersistentSelection,type SandboxSelection,@@ -49,8 +55,38 @@ export const useSandboxModeSelect = (const workspaceId = useActiveWorkspaceId();const userId = useUserStore(userProfileSelectors.userId);const driveStatus = useSandboxDriveStatus(enabled);- const { selection, setSelection, topicId: scopeTopicId } = useSandboxPlacement(agentId, topicId);+ const {+ projectId,+ selection,+ setSelection,+ topicId: scopeTopicId,+ } = useSandboxPlacement(agentId, topicId);const onDrive = isPersistentSelection(selection);+ const sharedAgent = useIsSharedAgent(agentId);+ const {+ environments: projectEnvironments,+ loaded: projectEnvironmentsLoaded,+ refresh: refreshProjectEnvironments,+ } = useProjectSandboxEnvironments(projectId, sharedAgent, enabled);+ const projectEnvironmentId = projectStartEnvironmentId(projectEnvironments);++ // A topic that exists keeps whatever is written now: the server applies the+ // project's environment only when it creates one. Until the project's list+ // has loaded, "none" is not known to be right, so it is asked for once more;+ // still unknown, the move fails and the conversation stays on the drive.+ const resolveProjectEnvironmentId = useCallback(async () => {+ if (projectEnvironmentsLoaded || !projectId) return projectEnvironmentId;+ await refreshProjectEnvironments();+ const rows = useProjectDirectoryStore.getState().environmentsMap[projectId];+ if (!rows) throw new Error(`The environment of project ${projectId} could not be loaded`);+ return projectStartEnvironmentId(pickableEnvironments(rows, sharedAgent));+ }, [+ projectEnvironmentId,+ projectEnvironmentsLoaded,+ projectId,+ refreshProjectEnvironments,+ sharedAgent,+ ]);const toTemporary = useCallback(async () => {// Without a drive there is only one sandbox, and nothing to remember.@@ -60,7 +96,18 @@ export const useSandboxModeSelect = (// it where it was, and new conversations must not start elsewhere.// Leaving the drive, the conversation starts from the repository the// agent's last temporary sandbox used, or none.- if (onDrive) {+ if (onDrive && projectId) {+ // A project conversation starts from its project's environment, never the+ // agent's repository from elsewhere, and is not remembered for it. Before+ // a topic exists it is a default, so the server still applies the+ // project's; with none, the server decides.+ if (scopeTopicId) {+ const environmentId = await resolveProjectEnvironmentId();+ await setSelection(environmentId ? { environmentId } : {});+ } else if (projectEnvironmentId)+ seedPendingSandboxSelection(agentId, { environmentId: projectEnvironmentId });+ else setPendingSandboxSelection(agentId);+ } else if (onDrive) {const next =getRememberedSandboxRepository({ userId, workspaceId }, agentId) ??temporarySelection(selection);@@ -70,7 +117,19 @@ export const useSandboxModeSelect = (rememberSandboxSelection({ userId, workspaceId }, agentId, next);}setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);- }, [agentId, driveStatus, onDrive, selection, setSelection, userId, workspaceId]);+ }, [+ agentId,+ driveStatus,+ onDrive,+ projectEnvironmentId,+ projectId,+ resolveProjectEnvironmentId,+ scopeTopicId,+ selection,+ setSelection,+ userId,+ workspaceId,+ ]);const toPersistent = useCallback(async () => {if (!onDrive) {diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.tsindex ae2379fd825..2ced24f6279 100644--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts@@ -11,10 +11,13 @@ interface TopicSandbox {sandboxEnvironmentId?: string;sandboxInstanceId?: string;sandboxWorkingDirectory?: string;+ sessionId?: string;}const state = vi.hoisted(() => ({activeTopicId: undefined as string | undefined,+ creatingTopicIds: [] as string[],+ draft: undefined as { agentId: string; projectId: string } | undefined,refreshTopicDetail: vi.fn(),topics: {} as Record<string, TopicSandbox>,updateTopicMetadata: vi.fn(),@@ -26,12 +29,14 @@ vi.mock('@/store/chat', () => ({useChatStore: (selector: (s: object) => unknown) =>selector({activeTopicId: state.activeTopicId,+ creatingTopicIds: state.creatingTopicIds,+ pendingNewTopicDirectory: state.draft,topicDataMap: {},refreshTopicDetail: state.refreshTopicDetail,topicDetailMap: Object.fromEntries(- Object.entries(state.topics).map(([id, { projectId, ...metadata }]) => [+ Object.entries(state.topics).map(([id, { projectId, sessionId, ...metadata }]) => [id,- { id, metadata, projectId },+ { id, metadata, projectId, sessionId },]),),updateTopicMetadata: state.updateTopicMetadata,@@ -42,6 +47,8 @@ vi.mock('@/store/chat', () => ({beforeEach(() => {// The main column's topic stays globally active while a side pane renders another.state.activeTopicId = 'main-topic';+ state.draft = undefined;+ state.creatingTopicIds = [];state.topics = {'main-topic': { sandboxInstanceId: 'main-instance' },'pane-topic': { sandboxDrive: 'personal', sandboxWorkingDirectory: 'reports' },@@ -150,6 +157,33 @@ describe('useSandboxPlacement', () => {expect(result.current.projectId).toBe('proj_1');});+ // A project sidebar "+" stages a blank draft; it is the project's before a+ // topic exists, and only for the agent it was staged on.+ it("names a project draft's project, for its own agent only", () => {+ state.draft = { agentId: 'agent-1', projectId: 'proj_1' };++ expect(renderHook(() => useSandboxPlacement('agent-1', null)).result.current.projectId).toBe(+ 'proj_1',+ );+ expect(+ renderHook(() => useSandboxPlacement('agent-2', null)).result.current.projectId,+ ).toBeUndefined();+ });++ // A first send drops the draft before the pane moves to the topic it mints;+ // that topic, still being created, keeps naming the project meanwhile.+ it('names the project of the topic a first send is creating, for its own agent only', () => {+ state.topics['minted-topic'] = { projectId: 'proj_1', sessionId: 'agent-1' };+ state.creatingTopicIds = ['minted-topic'];++ expect(renderHook(() => useSandboxPlacement('agent-1', null)).result.current.projectId).toBe(+ 'proj_1',+ );+ expect(+ renderHook(() => useSandboxPlacement('agent-2', null)).result.current.projectId,+ ).toBeUndefined();+ });+it('follows the global active topic when no topic is given', () => {const { result } = renderHook(() => useSandboxPlacement('agent-1'));diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.tsindex 8165ff87cc8..97de75c3f49 100644--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.ts@@ -56,9 +56,22 @@ export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | nulconst topicMetadata = useChatStore((s) =>topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,);- const projectId = useChatStore((s) =>- topicId ? (topicSelectors.getTopicById(topicId)(s)?.projectId ?? undefined) : undefined,- );+ // The project the conversation belongs to: the topic's, or β before a topic+ // exists β the blank draft a project sidebar "+" staged for this agent. A+ // first send mints the topic and drops the draft before this pane moves to+ // it, so for that moment the topic being created names the project: the+ // composer would otherwise read as outside it and re-seed its default just+ // as the send reads it.+ const projectId = useChatStore((s) => {+ if (topicId) return topicSelectors.getTopicById(topicId)(s)?.projectId ?? undefined;+ if (s.pendingNewTopicDirectory?.agentId === agentId)+ return s.pendingNewTopicDirectory.projectId;+ for (const creatingId of s.creatingTopicIds) {+ const creating = topicSelectors.getTopicById(creatingId)(s);+ if (creating?.sessionId === agentId && creating.projectId) return creating.projectId;+ }+ return undefined;+ });// A conversation no loaded list holds β a project conversation opened right// after the project home created it β is read by id, or the chip would show// a temporary sandbox while the topic works in a repository.diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.tsindex 456c1b48c87..353d8fdba81 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts@@ -9,7 +9,7 @@ import {} from '@/store/chat/pendingSandboxSelection';import { rememberSandboxSelection } from './rememberedSandboxDirectory';-import { useSeedDefaultSelection } from './useSeedDefaultSelection';+import { useSeedDefaultSelection, useSeedTemporaryRepository } from './useSeedDefaultSelection';const getEntitlement = vi.hoisted(() => vi.fn());@@ -134,3 +134,39 @@ describe('useSeedDefaultSelection', () => {expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'projects/demo' });});});++describe('useSeedTemporaryRepository β the first-send default', () => {+ const pane = (hasTopic: boolean, environmentId: string) => ({+ eligible: true,+ hasTopic,+ project: { environmentId },+ temporary: true,+ });++ it("registers a project draft's environment for its first send", async () => {+ renderHook(() => useSeedTemporaryRepository(AGENT, pane(false, 'env-project')));+ consumePendingSandboxSelection(AGENT);++ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toEqual({+ environmentId: 'env-project',+ });+ });++ // The entry is the agent's: a split pane already on another project's topic+ // handed its environment to this pane's first send, or cleared it on unmount.+ it("is neither replaced nor cleared by another pane's existing topic", async () => {+ renderHook(() => useSeedTemporaryRepository(AGENT, pane(false, 'env-project')));+ const topicPane = renderHook(() => useSeedTemporaryRepository(AGENT, pane(true, 'env-other')));+ consumePendingSandboxSelection(AGENT);++ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toEqual({+ environmentId: 'env-project',+ });++ consumePendingSandboxSelection(AGENT);+ topicPane.unmount();+ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toEqual({+ environmentId: 'env-project',+ });+ });+});diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.tsindex 6b7f08c63df..cf839de1071 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts@@ -5,6 +5,7 @@ import {getPendingSandboxSelection,isSeededSandboxSelection,seedPendingSandboxSelection,+ setPendingSandboxSelection,setSandboxDefaultSelection,setSandboxTemporaryDefaultSelection,} from '@/store/chat/pendingSandboxSelection';@@ -81,37 +82,60 @@ export const useSeedDefaultSelection = (** 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.+ *+ * A project conversation starts from its project's environment instead β the+ * one the server applies to a default nobody picked β so the chip names what+ * the conversation will run in; the agent's repository from elsewhere is not+ * one this project offers. `project.environmentId` is that environment, or+ * undefined while it loads or when the server would apply none.*/export const useSeedTemporaryRepository = (agentId: string,- { eligible, hasTopic, temporary }: { eligible: boolean; hasTopic: boolean; temporary: boolean },+ {+ eligible,+ hasTopic,+ project,+ temporary,+ }: {+ eligible: boolean;+ hasTopic: boolean;+ /** Set when the conversation belongs to a project. */+ project?: { environmentId?: string };+ temporary: boolean;+ },) => {const workspaceId = useActiveWorkspaceId();const userId = useUserStore(userProfileSelectors.userId);+ const inProject = !!project;+ const projectEnvironmentId = project?.environmentId;// 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.+ // default. Only a conversation not created yet registers one: the entry is+ // the agent's, and a split pane already on a topic β a project's, say β+ // would hand its environment to another pane's first send, or clear it.useEffect(() => {- if (!eligible) return;- const environmentId = getRememberedSandboxRepository(- { userId, workspaceId },- agentId,- )?.environmentId;+ if (!eligible || hasTopic) return;+ const environmentId = inProject+ ? projectEnvironmentId+ : getRememberedSandboxRepository({ userId, workspaceId }, agentId)?.environmentId;setSandboxTemporaryDefaultSelection(agentId, environmentId ? { environmentId } : undefined);return () => setSandboxTemporaryDefaultSelection(agentId);- }, [agentId, eligible, hasTopic, userId, workspaceId]);+ }, [agentId, eligible, hasTopic, inProject, projectEnvironmentId, userId, workspaceId]);useEffect(() => {if (!temporary || hasTopic) return;const pending = getPendingSandboxSelection(agentId);if (pending && !isSeededSandboxSelection(pending)) return;- const environmentId = getRememberedSandboxRepository(- { userId, workspaceId },- agentId,- )?.environmentId;+ const environmentId = inProject+ ? projectEnvironmentId+ : getRememberedSandboxRepository({ userId, workspaceId }, agentId)?.environmentId;if (environmentId) seedPendingSandboxSelection(agentId, { environmentId });- }, [agentId, hasTopic, temporary, userId, workspaceId]);+ // A default environment nothing replaces is stale: the agent's repository+ // from elsewhere in a project, or a project's environment once the agent's+ // next conversation is not that project's. Neither is offered there.+ else if (pending?.environmentId) setPendingSandboxSelection(agentId);+ }, [agentId, hasTopic, inProject, projectEnvironmentId, temporary, userId, workspaceId]);};diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsxindex d585fd055ae..4380ab438df 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx@@ -130,6 +130,8 @@ const chatStore = vi.hoisted(() => ({activeGroupId: undefined as string | undefined,activeThreadId: undefined as string | undefined,activeTopicId: undefined as string | undefined,+ // useSandboxPlacement reads the topics a first send is creating+ creatingTopicIds: [] as string[],openTopicComments: vi.fn(),// useSandboxPlacement reads an unlisted topic by id and reads it back after a pickrefreshTopicDetail: vi.fn(),diff --git a/src/features/Projects/Conversation/useProjectDraftStaging.test.ts b/src/features/Projects/Conversation/useProjectDraftStaging.test.tsindex ee3e1c4f466..04fba2b0986 100644--- a/src/features/Projects/Conversation/useProjectDraftStaging.test.ts+++ b/src/features/Projects/Conversation/useProjectDraftStaging.test.ts@@ -43,6 +43,45 @@ describe('useProjectDraftStaging', () => {expect(pending()).toEqual(switched);});+ // Left behind, the draft outlived its pane: the agent's next blank+ // conversation anywhere sent into this project and offered its environment.+ it('withdraws its draft when the pane leaves it', () => {+ const projectDraft = { agentId: 'agt_a', projectId: 'prj_1' };+ const pane = renderHook(({ draft }) => useProjectDraftStaging(draft, ids), {+ initialProps: { draft: projectDraft as typeof projectDraft | undefined },+ });+ expect(pending()).toEqual(projectDraft);++ pane.rerender({ draft: undefined });+ expect(pending()).toBeUndefined();++ pane.rerender({ draft: projectDraft });+ pane.unmount();+ expect(pending()).toBeUndefined();+ });++ /** @example Review: closing one of two split panes on the same draft cleared the other's staging. */+ it('keeps a draft staged while another live pane holds the same one', () => {+ const projectDraft = { agentId: 'agt_a', projectId: 'prj_1' };+ const first = renderHook(() => useProjectDraftStaging({ ...projectDraft }, ids));+ const second = renderHook(() => useProjectDraftStaging({ ...projectDraft }, ids));++ first.unmount();+ expect(pending()).toEqual(projectDraft);++ second.unmount();+ expect(pending()).toBeUndefined();+ });++ it("leaves another pane's staged draft alone", () => {+ const a = renderHook(() => useProjectDraftStaging(paneA, ids));+ renderHook(() => useProjectDraftStaging(paneB, ids));++ a.unmount();++ expect(pending()).toEqual(paneB);+ });+it('stages nothing without a draft', () => {const { result } = renderHook(() => useProjectDraftStaging(undefined, ids));act(() => result.current());diff --git a/src/features/Projects/Conversation/useProjectDraftStaging.ts b/src/features/Projects/Conversation/useProjectDraftStaging.tsindex 5eacf6f4037..438ca5bede1 100644--- a/src/features/Projects/Conversation/useProjectDraftStaging.ts+++ b/src/features/Projects/Conversation/useProjectDraftStaging.ts@@ -8,6 +8,28 @@ const sameDraft = (a: Draft | undefined, b: Draft | undefined) =>a?.projectWorkingDirectoryId === b?.projectWorkingDirectoryId &&a?.projectId === b?.projectId;+/**+ * The draft each mounted pane holds, by pane. Split view can show one draft in+ * two panes; both hold equal values, so whether the staged draft is still+ * someone's is a question about every live pane, not the one leaving.+ */+const heldDrafts = new Map<object, Draft>();++const hold = (pane: object, draft: Draft | undefined) => {+ if (draft) heldDrafts.set(pane, draft);+ else heldDrafts.delete(pane);+};++/** Clear the staged draft when it is this pane's and no other live pane holds it. */+const withdraw = (pane: object) => {+ const own = heldDrafts.get(pane);+ heldDrafts.delete(pane);+ if (!own) return;+ for (const held of heldDrafts.values()) if (sameDraft(held, own)) return;+ const { pendingNewTopicDirectory, setPendingNewTopicDirectory } = useChatStore.getState();+ if (sameDraft(pendingNewTopicDirectory, own)) setPendingNewTopicDirectory();+};+/*** Keep this pane's blank draft staged for the send.*@@ -17,12 +39,20 @@ const sameDraft = (a: Draft | undefined, b: Draft | undefined) =>* opened in another pane can't make this one send to the wrong agent/device.* A device switch in this pane's composer restages the global value; the pane* follows it while it stays on the same agent and project.+ *+ * Leaving the draft β the pane unmounts or its route no longer names one β+ * withdraws it while it is still the staged one and no other live pane holds+ * the same draft. Left behind, it outlived the draft: the agent's next blank+ * conversation anywhere sent into this project and offered its environment.+ * Another pane's staged draft is left alone.*/export const useProjectDraftStaging = (draft: Draft | undefined,projectDirectoryIds: ReadonlySet<string>,) => {const ownRef = useRef(draft);+ // This pane's identity in `heldDrafts`.+ const paneRef = useRef({});const directoryIdsRef = useRef(projectDirectoryIds);directoryIdsRef.current = projectDirectoryIds;@@ -34,10 +64,17 @@ export const useProjectDraftStaging = (}, []);useEffect(() => {+ if (draft) hold(paneRef.current, draft);+ else withdraw(paneRef.current);ownRef.current = draft;restage();}, [draft?.agentId, draft?.projectWorkingDirectoryId, draft?.projectId, restage]);+ useEffect(() => {+ const pane = paneRef.current;+ return () => withdraw(pane);+ }, []);+useEffect(() =>useChatStore.subscribe(@@ -50,8 +87,10 @@ export const useProjectDraftStaging = (pending.agentId === own.agentId &&!!pending.projectWorkingDirectoryId &&directoryIdsRef.current.has(pending.projectWorkingDirectoryId)- )+ ) {ownRef.current = pending;+ hold(paneRef.current, pending);+ }},),[],diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.tsindex 4220044a846..271a40f6dc4 100644--- a/src/store/agent/selectors/selectors.ts+++ b/src/store/agent/selectors/selectors.ts@@ -66,6 +66,10 @@ const currentAgentCreatedAt = (s: AgentStoreState) => currentAgentData(s)?.creatconst currentAgentVisibility = (s: AgentStoreState) => currentAgentData(s)?.visibility;+/** An agent's visibility by id β for a conversation whose agent is not the active one. */+const getAgentVisibilityById = (agentId: string) => (s: AgentStoreState) =>+ s.agentMap[agentId]?.visibility;+/*** Get complete meta data for the current agent* Used to replace sessionMetaSelectors.currentAgentMeta@@ -407,6 +411,7 @@ export const agentSelectors = {currentAgentDisplayName,currentAgentTitle,currentAgentVisibility,+ getAgentVisibilityById,currentAgentWorkingDirectory,currentEnabledKnowledge,currentKnowledgeIds,diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.tsindex e9b7c783a04..26eebf1a5d5 100644--- a/src/store/projectWorkingDirectory/index.ts+++ b/src/store/projectWorkingDirectory/index.ts@@ -130,7 +130,7 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {/** Fetch orchestration only; read the rows with `useDirectoryTopics`. */useFetchDirectoryTopics: (id?: string) => ProjectListSyncResult;/** Fetch orchestration only; read the rows with `useProjectEnvironments`. */- useFetchEnvironments: (projectId?: string) => ProjectListSyncResult;+ useFetchEnvironments: (projectId?: string, enabled?: boolean) => ProjectListSyncResult;/** Fetch orchestration only; read the rows with `useEnvironmentTopics`. */useFetchEnvironmentTopics: (directoryIds: string[]) => ProjectListSyncResult;/** Fetch orchestration only; read the rows with `useProjectTopics`. */@@ -338,9 +338,9 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<const hasData = useProjectDirectoryStore((state) => state.directoriesMap[key] !== undefined);return { ...sync, hasData };},- useFetchEnvironments: (projectId) => {+ useFetchEnvironments: (projectId, enabled = true) => {const key = projectId ?? ALL_PROJECTS_KEY;- const sync = environments.useSync(key);+ const sync = environments.useSync(key, { enabled });const hasData = useProjectDirectoryStore((state) => state.environmentsMap[key] !== undefined);return { ...sync, hasData };},