Skip to content

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

✨ feat(project): unify project environments with Settings → Environments and support linking (#23150)

Rdmclin2c7a97a58afbe
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index 83298355e13..957ee5e1903 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -188,6 +188,13 @@ export const projectWorkingDirectoryRouter = router({
data: await ctx.projectModel.attachEnvironment(input.projectId, input.environmentId),
success: true,
})),
+ /** Unlink an environment from the project; the environment itself is kept. */
+ detachEnvironment: write
+ .input(z.object({ projectId: z.string(), environmentId: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.projectModel.detachEnvironment(input.projectId, input.environmentId),
+ success: true,
+ })),
/**
* Link a GitHub repository to the project: the caller's environment for it,
* made when they have none, attached in the same request — the project
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 70df50457b4..9d6cb27708e 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -131,8 +131,14 @@
"environment.add.noExisting": "All of your environments are already in this project.",
"environment.add.noPublished": "No published environments to add. A shared project only uses published environments.",
"environment.add.title": "Add environment",
+ "environment.create": "New environment",
+ "environment.link": "Link environment",
"environment.privateInShared": "Private",
"environment.privateInSharedTooltip": "This project is shared, so its conversations only use published environments. This private environment won't be checked out.",
+ "environment.unlink": "Unlink from project",
+ "environment.unlinkConfirm.desc": "The environment stays in Settings → Environments. This project's folders that use it are kept, but can't run conversations until it is linked again.",
+ "environment.unlinkConfirm.title": "Unlink \"{{name}}\" from this project?",
+ "environment.unlinkFailed": "Couldn't unlink the environment from this project",
"goals.create": "Create goal",
"goals.description": "Define the outcomes this project is pursuing and track them to acceptance.",
"goals.emptyDescription": "Create the first measurable outcome for this project.",
@@ -374,7 +380,7 @@
"settings.editDirectoryDescription": "Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.",
"settings.editDirectoryFailed": "Could not update the folder",
"settings.editDirectoryOtherEnvironment": "This folder already belongs to another environment. Choose a different folder or device.",
- "settings.environmentDescription": "Keep repository sources together in an environment, then add a folder on your device to start working.",
+ "settings.environmentDescription": "Link environments configured in Settings → Environments, then add a folder on your device to start working.",
"settings.environments": "Environments",
"settings.general": "General",
"settings.generalDescription": "Manage the project name, address, and description.",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 8b6416e7063..63a482941a4 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -131,8 +131,14 @@
"environment.add.noExisting": "你的环境都已添加到本项目。",
"environment.add.noPublished": "没有可添加的已发布环境。共享项目只会使用已发布的环境。",
"environment.add.title": "添加环境",
+ "environment.create": "新建环境",
+ "environment.link": "关联环境",
"environment.privateInShared": "仅自己可见",
"environment.privateInSharedTooltip": "这是共享项目,对话只会使用已发布的环境,这个私有环境不会被检出。",
+ "environment.unlink": "取消关联",
+ "environment.unlinkConfirm.desc": "环境本身会保留在「设置 → 环境」中。本项目里用到它的文件夹会保留,但在重新关联前不能运行对话。",
+ "environment.unlinkConfirm.title": "从本项目取消关联「{{name}}」?",
+ "environment.unlinkFailed": "无法从本项目取消关联该环境",
"goals.create": "新建目标",
"goals.description": "定义这个项目正在追求的成果,并持续跟踪到验收。",
"goals.emptyDescription": "为这个项目创建第一个可衡量的成果。",
@@ -374,7 +380,7 @@
"settings.editDirectoryDescription": "选择这个工作目录对应的设备和文件夹。相关话题会一起迁移到新文件夹,并在那里开始新的会话。",
"settings.editDirectoryFailed": "无法修改文件夹",
"settings.editDirectoryOtherEnvironment": "这个文件夹已属于其他环境,请选择别的文件夹或设备。",
- "settings.environmentDescription": "用环境管理仓库来源,再添加设备上的文件夹,开始在项目中工作。",
+ "settings.environmentDescription": "关联在「设置 → 环境」中配置的环境,再添加设备上的文件夹,开始在项目中工作。",
"settings.environments": "环境",
"settings.general": "基础设置",
"settings.generalDescription": "管理项目名称、链接和说明。",
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index 63355f47282..7fe40a787cc 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -997,6 +997,16 @@ describe('ProjectModel', () => {
await expect(model.attachEnvironment(project.id, randomUUID())).rejects.toThrow(
'access denied',
);
+
+ await expect(otherModel.detachEnvironment(project.id, env.id)).rejects.toThrow('access denied');
+ await model.detachEnvironment(project.id, env.id);
+ await model.detachEnvironment(project.id, env.id);
+ expect(await model.listEnvironments(project.id)).toEqual([]);
+ // Unlinking leaves the environment itself for the other places using it.
+ await model.attachEnvironment(project.id, env.id);
+ expect(await model.listEnvironments(project.id)).toEqual([
+ expect.objectContaining({ id: env.id }),
+ ]);
});
it('lists project conversations with or without directories, retaining each agent', async () => {
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 2e52ebbd607..7b0a493295e 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -23,8 +23,8 @@ import { works } from '../schemas/work';
import type { LobeChatDatabase } from '../type';
import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';
import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';
-import { notChannelTopic } from '../utils/topicVisibility';
import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';
+import { notChannelTopic } from '../utils/topicVisibility';
import {
buildWorkspacePayload,
buildWorkspaceWhere,
@@ -1090,6 +1090,25 @@ export class ProjectModel {
return { projectId, environmentId };
}
+ /**
+ * Unlink an environment from a project. The environment itself stays — it is
+ * shared by every project that lists it — and so do the project's folders
+ * and conversations made from it; unlinking twice is a no-op.
+ */
+ async detachEnvironment(projectId: string, environmentId: string) {
+ if (!(await this.findManageableById(projectId)))
+ throw new Error('Project not found or access denied');
+ await this.db
+ .delete(projectEnvironments)
+ .where(
+ and(
+ eq(projectEnvironments.projectId, projectId),
+ eq(projectEnvironments.environmentId, environmentId),
+ ),
+ );
+ return { projectId, environmentId };
+ }
+
/** Enabled environments linked to this project. */
async listEnvironments(projectId: string) {
if (!(await this.findById(projectId))) throw new Error('Project not found or access denied');
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 571a2f987c5..3f1e2b75013 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -28,7 +28,7 @@ export default {
'settings.directoryListDescription':
'Device folders this project works in. Agents read and change files in them on that device.',
'settings.environmentDescription':
- 'Keep repository sources together in an environment, then add a folder on your device to start working.',
+ 'Link environments configured in Settings → Environments, then add a folder on your device to start working.',
'settings.allEnvironments': 'All environments',
'settings.viewDirectories': 'View folders ({{count}})',
'directories.noEnvironment': 'No environment linked',
@@ -315,6 +315,13 @@ export default {
'environment.add.noPublished':
'No published environments to add. A shared project only uses published environments.',
'environment.add.title': 'Add environment',
+ 'environment.create': 'New environment',
+ 'environment.link': 'Link environment',
+ 'environment.unlink': 'Unlink from project',
+ 'environment.unlinkConfirm.desc':
+ "The environment stays in Settings → Environments. This project's folders that use it are kept, but can't run conversations until it is linked again.",
+ 'environment.unlinkConfirm.title': 'Unlink "{{name}}" from this project?',
+ 'environment.unlinkFailed': "Couldn't unlink the environment from this project",
'environment.privateInShared': 'Private',
'environment.privateInSharedTooltip':
"This project is shared, so its conversations only use published environments. This private environment won't be checked out.",
diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsx
index 35d4ecc116a..36a2fe6ec3f 100644
--- a/src/features/EnvironmentManager/EnvironmentItem.tsx
+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx
@@ -8,6 +8,7 @@ import {
cssVar,
cx,
DropdownMenu,
+ type DropdownMenuProps,
Flexbox,
Icon,
Text,
@@ -16,7 +17,7 @@ import {
} from '@lobehub/ui';
import dayjs from 'dayjs';
import { EyeOffIcon, GlobeIcon, MoreHorizontalIcon, Trash2Icon } from 'lucide-react';
-import { memo } from 'react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import UserAvatar from '@/components/UserAvatar';
@@ -108,6 +109,17 @@ const styles = createStaticStyles(({ css }) => ({
interface EnvironmentItemProps {
environment: SandboxEnvironment;
+ /**
+ * What the place listing the row adds to it, before the creator — a project
+ * shows how many of its folders come from the environment.
+ */
+ extra?: ReactNode;
+ /**
+ * The menu, when the place listing the row acts on something other than the
+ * environment itself — a project unlinks it rather than deleting it.
+ * Replaces the environment's own items; an empty list hides the menu.
+ */
+ menuItems?: DropdownMenuProps['items'];
onSelect: () => void;
selected?: boolean;
}
@@ -121,7 +133,8 @@ interface EnvironmentItemProps {
* detail of one environment rather than a way to tell environments apart, so it
* lives in the panel this row opens.
*/
-const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, selected }) => {
+const EnvironmentItem = memo<EnvironmentItemProps>((props) => {
+ const { environment, extra, menuItems, onSelect, selected } = props;
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
const actions = useEnvironmentActions();
@@ -192,6 +205,23 @@ const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, sel
const confirmRemoveEnvironment = useConfirmRemoveEnvironment();
const confirmRemove = () => confirmRemoveEnvironment(environment);
+ // Nothing here acts on an environment you only have the use of, so the menu
+ // goes away rather than offering items that would be refused.
+ const items =
+ menuItems ??
+ (canEdit
+ ? [
+ ...visibilityItems,
+ {
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'remove',
+ label: t('environments.remove'),
+ onClick: confirmRemove,
+ },
+ ]
+ : []);
+
return (
<Flexbox
horizontal
@@ -202,7 +232,9 @@ const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, sel
tabIndex={0}
onClick={onSelect}
onKeyDown={(event) => {
- // Mirror native button keyboard semantics for the div-as-button row.
+ // Mirror native button keyboard semantics for the div-as-button row —
+ // for the row itself only, so a control inside it keeps its own keys.
+ if (event.target !== event.currentTarget) return;
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
onSelect();
@@ -260,6 +292,7 @@ const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, sel
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>
+ {extra && <span onClick={(event) => event.stopPropagation()}>{extra}</span>}
{environment.creator && (
// Who put this here, at a glance — the same answer the device list
// gives with the enroller's avatar.
@@ -269,25 +302,10 @@ const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, sel
</span>
</Tooltip>
)}
- {/* Nothing here acts on an environment you only have the use of, so
- the menu goes away rather than offering items that would be
- refused. */}
- {canEdit && (
+ {items.length > 0 && (
<span onClick={(event) => event.stopPropagation()}>
- <DropdownMenu
- placement={'bottomRight'}
- items={[
- ...visibilityItems,
- {
- danger: true,
- icon: <Icon icon={Trash2Icon} />,
- key: 'remove',
- label: t('environments.remove'),
- onClick: confirmRemove,
- },
- ]}
- >
- <Button icon={MoreHorizontalIcon} />
+ <DropdownMenu items={items} placement={'bottomRight'}>
+ <Button aria-label={tCommon('more')} icon={MoreHorizontalIcon} />
</DropdownMenu>
</span>
)}
diff --git a/src/features/Projects/AddEnvironmentModal.tsx b/src/features/Projects/AddEnvironmentModal.tsx
index ff12c001f93..de76f0eb176 100644
--- a/src/features/Projects/AddEnvironmentModal.tsx
+++ b/src/features/Projects/AddEnvironmentModal.tsx
@@ -69,6 +69,11 @@ const styles = stylex.create({
type Source = 'existing' | 'github';
interface AddEnvironmentContentProps {
+ /**
+ * Where the dialog opens. A project's environment list opens it on the
+ * environments already configured, since making one has its own button there.
+ */
+ defaultSource?: Source;
/** Called with the environment now linked to the project. */
onAdded?: (environmentId: string) => void;
projectId: string;
@@ -85,7 +90,12 @@ interface AddEnvironmentContentProps {
* connected GitHub App can read, or a pasted URL — or an environment the person
* already has, linked as it is.
*/
-const AddEnvironmentContent = ({ onAdded, projectId, publish }: AddEnvironmentContentProps) => {
+const AddEnvironmentContent = ({
+ defaultSource = 'github',
+ onAdded,
+ projectId,
+ publish,
+}: AddEnvironmentContentProps) => {
const { t } = useTranslation(['project', 'common']);
const { close } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
@@ -97,7 +107,7 @@ const AddEnvironmentContent = ({ onAdded, projectId, publish }: AddEnvironmentCo
const owned = useProjectEnvironments();
const reusable = reusableEnvironments(owned, linked, publish);
- const [source, setSource] = useState<Source>('github');
+ const [source, setSource] = useState<Source>(defaultSource);
const [url, setUrl] = useState('');
const [defaultBranch, setDefaultBranch] = useState<string>();
const [existingId, setExistingId] = useState<string>();
diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsx
index d954b81fa89..20cf30392dd 100644
--- a/src/features/Projects/WorkingDirectories/Page.tsx
+++ b/src/features/Projects/WorkingDirectories/Page.tsx
@@ -64,6 +64,7 @@ export function ProjectDirectoriesPage() {
label: t('settings.environments'),
render: () => (
<ProjectWorkingDirectories
+ canManage={canManage}
projectId={detail.project.id}
shared={Boolean(detail.project.workspaceId) && detail.project.visibility === 'public'}
/>
diff --git a/src/features/Projects/WorkingDirectories/index.tsx b/src/features/Projects/WorkingDirectories/index.tsx
index 4eeb665f559..f73cf774088 100644
--- a/src/features/Projects/WorkingDirectories/index.tsx
+++ b/src/features/Projects/WorkingDirectories/index.tsx
@@ -1,20 +1,87 @@
-import { ActionIcon, Block, Button, cssVar, Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';
-import { FolderIcon, PencilIcon, PlusIcon } from 'lucide-react';
+import {
+ Button,
+ Center,
+ confirmModal,
+ DropdownMenu,
+ Empty,
+ Flexbox,
+ Icon,
+ Tag,
+ Text,
+ toast,
+ Tooltip,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import {
+ ContainerIcon,
+ FolderIcon,
+ LinkIcon,
+ MoreHorizontalIcon,
+ PlusIcon,
+ UnlinkIcon,
+} from 'lucide-react';
+import { type ReactNode, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
-import RepositoryAvatar from '@/components/RepositoryAvatar';
+import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';
+import EnvironmentDetailPanel from '@/features/EnvironmentManager/EnvironmentDetailPanel';
+import EnvironmentItem from '@/features/EnvironmentManager/EnvironmentItem';
+import { EnvironmentListSkeleton } from '@/features/EnvironmentManager/Skeleton';
+import { useEnvironments } from '@/features/EnvironmentManager/useEnvironmentData';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
useProjectDirectories,
useProjectDirectoryStore,
useProjectEnvironments,
} from '@/store/projectWorkingDirectory';
+import type { SandboxEnvironment } from '@/store/sandbox';
import { openAddEnvironmentModal } from '../AddEnvironmentModal';
-import { openEnvironmentModal } from './EnvironmentModal';
+import { environmentRepositoryUrl } from '../environmentSource';
+import { hasEditedEnvironment, projectEnvironmentRows } from './projectEnvironmentRows';
+
+/** The frames the environment settings use, so both lists read as one. */
+const styles = stylex.create({
+ detailCol: {
+ alignSelf: 'stretch',
+ minWidth: 0,
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ },
+ listCol: {
+ overflow: 'hidden',
+ minWidth: 0,
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorBgContainer,
+ },
+ unlistedRow: {
+ paddingBlock: '12px',
+ paddingInline: '12px',
+ },
+ unlistedTile: {
+ display: 'flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '48px',
+ height: '48px',
+ borderRadius: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+});
interface ProjectWorkingDirectoriesProps {
+ /** Whether the caller may change which environments the project links. */
+ canManage?: boolean;
projectId: string;
/**
* A workspace-public project: its conversations run a public agent, which
@@ -23,138 +90,255 @@ interface ProjectWorkingDirectoriesProps {
shared?: boolean;
}
-export function ProjectWorkingDirectories({ projectId, shared }: ProjectWorkingDirectoriesProps) {
- const { t } = useTranslation('project');
+/**
+ * The environments a project works with. They are the environments configured
+ * in settings — the same rows, the same detail panel — linked to the project:
+ * linking one, making a new one here or unlinking one never makes a second copy
+ * of a specification, so an edit made on either page is the edit.
+ */
+export function ProjectWorkingDirectories({
+ canManage,
+ projectId,
+ shared,
+}: ProjectWorkingDirectoriesProps) {
+ const { t } = useTranslation(['project', 'common']);
const navigate = useWorkspaceAwareNavigate();
const linkedRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);
+ const detachEnvironment = useProjectDirectoryStore((s) => s.detachEnvironment);
const linked = useProjectEnvironments(projectId);
const directories = useProjectDirectories(projectId);
+ const configured = useEnvironments();
+ const [selectedId, setSelectedId] = useState<string>();
+
const requestError = linkedRequest.error || directoriesRequest.error;
+ const loading =
+ !linkedRequest.hasData ||
+ !directoriesRequest.hasData ||
+ (!configured.settled && !configured.error);
+
+ const { configured: rows, unlisted: unlistedRows } = projectEnvironmentRows(
+ linked,
+ configured.environments ?? [],
+ );
+ // Until the configured list has answered, "not in it" is not an answer yet.
+ const unlisted = configured.settled ? unlistedRows : [];
+ const selected = rows.find((environment) => environment.id === selectedId);
+
+ // The detail panel saves through the settings store; the project's own
+ // projections (directory rows carry the environment's name) follow when a
+ // linked environment's name or visibility changes there.
+ const refreshEnvironments = useProjectDirectoryStore((s) => s.refreshEnvironments);
+ const lastRows = useRef<SandboxEnvironment[]>(undefined);
+ useEffect(() => {
+ const previous = lastRows.current;
+ lastRows.current = rows;
+ if (previous && hasEditedEnvironment(previous, rows)) void refreshEnvironments();
+ }, [rows, refreshEnvironments]);
+
+ const link = () =>
+ openAddEnvironmentModal({
+ defaultSource: 'existing',
+ onAdded: (environmentId) => {
+ setSelectedId(environmentId);
+ // A repository added from GitHub may have made a new environment.
+ void configured.revalidate();
+ },
+ projectId,
+ publish: shared,
+ });
+
+ const create = () =>
+ openCreateEnvironmentModal(
+ shared ? 'public' : undefined,
+ async (created) => {
+ try {
+ await attachEnvironment(projectId, created.id);
+ setSelectedId(created.id);
+ } catch (error) {
+ console.error('Failed to link the new environment to the project', error);
+ toast.error(t('environment.add.failed'));
+ }
+ },
+ t('environment.create'),
+ );
+
+ const unlink = (environment: { id: string; name: string }) =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('environment.unlinkConfirm.desc'),
+ okText: t('environment.unlink'),
+ onOk: async () => {
+ try {
+ await detachEnvironment(projectId, environment.id);
+ setSelectedId((current) => (current === environment.id ? undefined : current));
+ } catch (error) {
+ console.error('Failed to unlink the environment from the project', error);
+ toast.error(t('environment.unlinkFailed'));
+ }
+ },
+ title: t('environment.unlinkConfirm.title', { name: environment.name }),
+ });
+
+ const projectMenu = (environment: { id: string; name: string }) =>
+ canManage
+ ? [
+ {
+ icon: <Icon icon={UnlinkIcon} />,
+ key: 'unlink',
+ label: t('environment.unlink'),
+ onClick: () => unlink(environment),
+ },
+ ]
+ : [];
+
+ /** What the project adds to a row: its folders, and whether it can be used. */
+ const projectFacts = (environment: { id: string; visibility?: string | null }): ReactNode => {
+ const count = directories.filter((d) => d.environmentId === environment.id).length;
+ // The project's conversations never check a private one out.
+ const unusable = shared && environment.visibility !== 'public';
+ return (
+ <Flexbox horizontal align="center" gap={8}>
+ {unusable && (
+ <Tooltip title={t('environment.privateInSharedTooltip')}>
+ <Tag color="warning" size="small">
+ {t('environment.privateInShared')}
+ </Tag>
+ </Tooltip>
+ )}
+ <Button
+ size="small"
+ onClick={() =>
+ navigate(`/project/${projectId}/settings/directories?environment=${environment.id}`)
+ }
+ >
+ {t(count ? 'settings.viewDirectories' : 'settings.configureDirectory', { count })}
+ </Button>
+ </Flexbox>
+ );
+ };
+
+ const actions = canManage && (
+ <Flexbox horizontal align="center" gap={8} style={{ flex: 'none' }}>
+ <Button icon={<Icon icon={LinkIcon} />} onClick={link}>
+ {t('environment.link')}
+ </Button>
+ <Button icon={<Icon icon={PlusIcon} />} type="primary" onClick={create}>
+ {t('environment.create')}
+ </Button>
+ </Flexbox>
+ );
+
+ let content: ReactNode;
+ if (requestError) {
+ content = (
+ <AsyncError
+ error={requestError}
+ onRetry={() => Promise.all([linkedRequest.revalidate(), directoriesRequest.revalidate()])}
+ />
+ );
+ } else if (loading) {
+ content = <EnvironmentListSkeleton />;
+ } else if (!linked.length) {
+ content = (
+ <Flexbox {...stylex.props(styles.listCol)}>
+ <Center paddingBlock={48} width="100%">
+ <Empty
+ action={canManage && <Button onClick={link}>{t('environment.link')}</Button>}
+ description={t('settings.environmentDescription')}
+ descriptionProps={{ fontSize: 13 }}
+ icon={ContainerIcon}
+ style={{ maxWidth: 360 }}
+ title={t('settings.noEnvironments')}
+ />
+ </Center>
+ </Flexbox>
+ );
+ } else {
+ content = (
+ <Flexbox horizontal align="flex-start" gap={16} wrap="wrap">
+ <Flexbox {...stylex.props(styles.listCol)} flex="1 1 320px">
+ {!!configured.error && !configured.settled && (
+ <AsyncError error={configured.error} onRetry={() => configured.revalidate()} />
+ )}
+ <Flexbox gap={2} padding={4}>
+ {rows.map((environment) => (
+ <EnvironmentItem
+ environment={environment}
+ extra={projectFacts(environment)}
+ key={environment.id}
+ menuItems={projectMenu(environment)}
+ selected={environment.id === selectedId}
+ onSelect={() =>
+ setSelectedId((current) =>
+ current === environment.id ? undefined : environment.id,
+ )
+ }
+ />
+ ))}
+ {unlisted.map((environment) => {
+ const repository = environmentRepositoryUrl(environment);
+ return (
+ <Flexbox
+ horizontal
+ align="center"
+ {...stylex.props(styles.unlistedRow)}
+ gap={16}
+ key={environment.id}
+ >
+ <div {...stylex.props(styles.unlistedTile)}>
+ <FolderIcon size={20} />
+ </div>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis fontSize={15} weight={500}>
+ {environment.name}
+ </Text>
+ <Text ellipsis fontSize={12} type="secondary">
+ {repository?.replace('https://github.com/', '') ?? t('settings.noRepository')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={8} style={{ flex: 'none' }}>
+ {projectFacts(environment)}
+ {canManage && (
+ <DropdownMenu items={projectMenu(environment)} placement="bottomRight">
+ <Button
+ aria-label={t('more', { ns: 'common' })}
+ icon={MoreHorizontalIcon}
+ />
+ </DropdownMenu>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ </Flexbox>
+ {selected && (
+ <Flexbox {...stylex.props(styles.detailCol)} flex="2 1 480px">
+ <EnvironmentDetailPanel
+ environment={selected}
+ key={selected.id}
+ onClose={() => setSelectedId(undefined)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ }
+
return (
- <Flexbox gap={20}>
- <Flexbox gap={12}>
- <Flexbox horizontal align="center" gap={12} justify="space-between">
+ <Flexbox gap={16}>
+ <Flexbox gap={8}>
+ <Flexbox horizontal align="center" gap={12} justify="space-between" wrap="wrap">
<Text fontSize={16} weight={600}>
{t('settings.environments')}
</Text>
- <Button
- icon={PlusIcon}
- type="primary"
- onClick={() => openAddEnvironmentModal({ projectId, publish: shared })}
- >
- {t('environment.add.title')}
- </Button>
+ {actions}
</Flexbox>
<Text type="secondary">{t('settings.environmentDescription')}</Text>
</Flexbox>
- {requestError ? (
- <AsyncError
- error={requestError}
- onRetry={() => Promise.all([linkedRequest.revalidate(), directoriesRequest.revalidate()])}
- />
- ) : !linkedRequest.hasData || !directoriesRequest.hasData ? (
- <Text>{t('loading', { ns: 'common' })}</Text>
- ) : !linked.length ? (
- <Text type="secondary">{t('settings.noEnvironments')}</Text>
- ) : (
- <Block padding={0} variant="outlined">
- {linked.map((env, index) => {
- const source = env.configuration.sources?.find((source) => source.kind === 'git');
- const count = directories.filter((d) => d.environmentId === env.id).length;
- // The project's conversations never check a private one out.
- const unusable = shared && env.visibility !== 'public';
- return (
- <Flexbox
- horizontal
- align="center"
- gap={16}
- justify="space-between"
- key={env.id}
- padding={16}
- style={
- index ? { borderTop: `1px solid ${cssVar.colorBorderSecondary}` } : undefined
- }
- >
- <Flexbox horizontal align="center" flex={1} gap={12} style={{ minWidth: 0 }}>
- {source ? (
- <RepositoryAvatar size={36} url={source.url} />
- ) : (
- <Block
- align="center"
- height={36}
- justify="center"
- style={{ borderRadius: '50%', flex: 'none' }}
- variant="filled"
- width={36}
- >
- <FolderIcon size={16} />
- </Block>
- )}
- <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
- <Flexbox horizontal align="center" gap={8}>
- <Text ellipsis weight={500}>
- {env.name}
- </Text>
- {unusable && (
- <Tooltip title={t('environment.privateInSharedTooltip')}>
- <Tag color="warning" size="small">
- {t('environment.privateInShared')}
- </Tag>
- </Tooltip>
- )}
- </Flexbox>
- {source ? (
- <a
- href={source.url}
- rel="noreferrer"
- target="_blank"
- style={{
- color: cssVar.colorTextSecondary,
- overflowWrap: 'anywhere',
- fontSize: 13,
- }}
- >
- {source.url.replace('https://github.com/', '')}
- </a>
- ) : (
- <Text fontSize={13} type="secondary">
- {t('settings.noRepository')}
- </Text>
- )}
- </Flexbox>
- </Flexbox>
- <Flexbox horizontal align="center" flex="none" gap={12}>
- <Button
- size="small"
- onClick={() =>
- navigate(`/project/${projectId}/settings/directories?environment=${env.id}`)
- }
- >
- {t(count ? 'settings.viewDirectories' : 'settings.configureDirectory', {
- count,
- })}
- </Button>
- <ActionIcon
- aria-label={t('directories.editEnvironment')}
- icon={PencilIcon}
- size="small"
- title={t('directories.editEnvironment')}
- onClick={() =>
- openEnvironmentModal({
- id: env.id,
- name: env.name,
- repositoryUrl: source?.url,
- onSaved: () => {},
- })
- }
- />
- </Flexbox>
- </Flexbox>
- );
- })}
- </Block>
- )}
+ {content}
</Flexbox>
);
}
diff --git a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.ts b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.ts
new file mode 100644
index 00000000000..2f23d17fa4b
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+
+import type { SandboxEnvironment } from '@/store/sandbox';
+
+import { hasEditedEnvironment, projectEnvironmentRows } from './projectEnvironmentRows';
+
+const configured = (id: string, name = id): SandboxEnvironment => ({
+ createdAt: '2026-10-01T00:00:00.000Z',
+ creator: null,
+ description: null,
+ id,
+ kind: 'code',
+ name,
+ userId: 'user-1',
+ visibility: 'private',
+ workspaceId: null,
+});
+
+describe('projectEnvironmentRows', () => {
+ it("shows a linked environment as the configured row, in the project's order", () => {
+ const result = projectEnvironmentRows(
+ [{ id: 'b' }, { id: 'a' }],
+ [configured('a', 'Renamed in settings'), configured('b'), configured('c')],
+ );
+
+ expect(result.configured.map((row) => row.id)).toEqual(['b', 'a']);
+ // The configured row wins, so an edit made in settings shows here too.
+ expect(result.configured[1].name).toBe('Renamed in settings');
+ expect(result.unlisted).toEqual([]);
+ });
+
+ it('keeps a linked environment the configured list does not hold apart', () => {
+ const result = projectEnvironmentRows(
+ [{ id: 'a' }, { id: 'gone', name: 'Theirs' }],
+ [configured('a')],
+ );
+
+ expect(result.configured.map((row) => row.id)).toEqual(['a']);
+ expect(result.unlisted).toEqual([{ id: 'gone', name: 'Theirs' }]);
+ });
+});
+
+describe('hasEditedEnvironment', () => {
+ it('reports a rename or a visibility change of a row listed both times', () => {
+ expect(
+ hasEditedEnvironment([configured('a', 'Old: name')], [configured('a', 'New: name')]),
+ ).toBe(true);
+ expect(
+ hasEditedEnvironment([configured('a')], [{ ...configured('a'), visibility: 'public' }]),
+ ).toBe(true);
+ });
+
+ it('ignores linking, unlinking and unchanged rows', () => {
+ expect(hasEditedEnvironment([configured('a')], [configured('a'), configured('b')])).toBe(false);
+ expect(hasEditedEnvironment([configured('a'), configured('b')], [configured('a')])).toBe(false);
+ expect(hasEditedEnvironment([configured('a')], [configured('a')])).toBe(false);
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.ts b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.ts
new file mode 100644
index 00000000000..22a14e59a15
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.ts
@@ -0,0 +1,42 @@
+import type { SandboxEnvironment } from '@/store/sandbox';
+
+/**
+ * A project's environments, as the rows the environment settings list them
+ * with. The project holds only the link; the row — repository, creator, when it
+ * was made — is the configured environment itself, so both pages show the same
+ * thing and an edit made on either shows up on both.
+ *
+ * A linked environment the caller's configured list does not hold (a
+ * colleague's private one linked to a shared project) is returned separately,
+ * since there is no row to show for it beyond the link.
+ */
+export const projectEnvironmentRows = <TLinked extends { id: string }>(
+ linked: TLinked[],
+ configured: SandboxEnvironment[],
+): { configured: SandboxEnvironment[]; unlisted: TLinked[] } => {
+ const byId = new Map(configured.map((environment) => [environment.id, environment]));
+ const rows: SandboxEnvironment[] = [];
+ const unlisted: TLinked[] = [];
+ for (const environment of linked) {
+ const row = byId.get(environment.id);
+ if (row) rows.push(row);
+ else unlisted.push(environment);
+ }
+ return { configured: rows, unlisted };
+};
+
+/**
+ * Whether an environment listed both times changed in a way the project's own
+ * projections denormalize (its name) or depend on (its visibility). Linking or
+ * unlinking is not an edit: those refresh the project on their own.
+ */
+export const hasEditedEnvironment = (
+ previous: Pick<SandboxEnvironment, 'id' | 'name' | 'visibility'>[],
+ next: Pick<SandboxEnvironment, 'id' | 'name' | 'visibility'>[],
+): boolean => {
+ const before = new Map(previous.map((environment) => [environment.id, environment]));
+ return next.some((environment) => {
+ const old = before.get(environment.id);
+ return !!old && (old.name !== environment.name || old.visibility !== environment.visibility);
+ });
+};
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
index eaeeb9769b8..5c551fdf3f8 100644
--- a/src/services/projectWorkingDirectory.ts
+++ b/src/services/projectWorkingDirectory.ts
@@ -16,6 +16,8 @@ class ProjectWorkingDirectoryService {
lambdaClient.projectWorkingDirectory.saveEnvironment.mutate(input);
attachEnvironment = (projectId: string, environmentId: string) =>
lambdaClient.projectWorkingDirectory.attachEnvironment.mutate({ projectId, environmentId });
+ detachEnvironment = (projectId: string, environmentId: string) =>
+ lambdaClient.projectWorkingDirectory.detachEnvironment.mutate({ projectId, environmentId });
attachRepository = (input: Parameters<Client['attachRepository']['mutate']>[0]) =>
lambdaClient.projectWorkingDirectory.attachRepository.mutate(input);
bind = (input: BindProjectDirectoryInput) =>
diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.ts
index 8f64eef94c0..ab74b7db85b 100644
--- a/src/store/projectWorkingDirectory/index.test.ts
+++ b/src/store/projectWorkingDirectory/index.test.ts
@@ -84,6 +84,38 @@ describe('projectWorkingDirectory store', () => {
});
});
+ describe('detachEnvironment', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("unlinks through the service and refreshes only that project's environments", async () => {
+ vi.mocked(mutate).mockClear();
+ const detach = vi
+ .spyOn(projectWorkingDirectoryService, 'detachEnvironment')
+ .mockResolvedValue({ data: {}, success: true } as never);
+
+ await useProjectDirectoryStore.getState().detachEnvironment('project-1', 'env-1');
+
+ expect(detach).toHaveBeenCalledWith('project-1', 'env-1');
+ expect(invalidates('projectEnvironments', 'project-1')).toBe(true);
+ // Its folders in the project are no longer runnable.
+ expect(invalidates('projectDirectories', 'project-1')).toBe(true);
+ expect(invalidates('projectDirectories', 'all')).toBe(true);
+ // The environment itself is untouched, so the scope-wide list stays as it is.
+ expect(invalidates('projectEnvironments', 'all')).toBe(false);
+ });
+ });
+
+ describe('refreshEnvironments', () => {
+ it('refreshes every environment and directory projection', async () => {
+ vi.mocked(mutate).mockClear();
+
+ await useProjectDirectoryStore.getState().refreshEnvironments();
+
+ expect(invalidates('projectEnvironments', 'project-1')).toBe(true);
+ expect(invalidates('projectDirectories', 'all')).toBe(true);
+ });
+ });
+
describe('useFetchProjectTopics polling', () => {
afterEach(() => {
vi.restoreAllMocks();
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
index 37fa42cb13c..c3da2749fc3 100644
--- a/src/store/projectWorkingDirectory/index.ts
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -103,8 +103,16 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {
createProjectTopic: (
...args: ServiceParams<'createProjectTopic'>
) => Promise<ServiceData<'createProjectTopic'>>;
+ /** Unlink an environment from a project; the environment itself is kept. */
+ detachEnvironment: (...args: ServiceParams<'detachEnvironment'>) => Promise<void>;
/** Move a directory conversation to its project's directory on another device. */
moveTopic: (...args: ServiceParams<'moveTopic'>) => Promise<ServiceData<'moveTopic'>>;
+ /**
+ * Refetch every environment and directory projection after an environment
+ * was edited elsewhere (the shared settings panel): directory rows carry its
+ * name denormalized.
+ */
+ refreshEnvironments: () => Promise<void>;
/** Refetch a project's conversations after a change made elsewhere, e.g. a new main agent. */
refreshProjectTopics: (projectId: string) => Promise<void>;
/** Repoint a directory at another device location; its conversations follow it. */
@@ -231,6 +239,9 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
]);
return result.data;
},
+ refreshEnvironments: async () => {
+ await Promise.all([environments.revalidate(), directories.revalidate()]);
+ },
refreshProjectTopics: async (projectId) => {
// Directory and environment rows carry the same topics with their agent
// denormalized, so every projection that lists them is stale too.
@@ -277,10 +288,22 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
await projectWorkingDirectoryService.attachEnvironment(projectId, environmentId);
await Promise.all([
environments.revalidate(projectId),
+ // Relinking makes the project's folders made from it runnable again.
+ directories.revalidate(ALL_PROJECTS_KEY),
+ directories.revalidate(projectId),
// The scope-wide list gained the environment instanced by the attach.
environments.revalidate(ALL_PROJECTS_KEY),
]);
},
+ detachEnvironment: async (projectId, environmentId) => {
+ await projectWorkingDirectoryService.detachEnvironment(projectId, environmentId);
+ await Promise.all([
+ environments.revalidate(projectId),
+ // The project's folders made from it lose their runnable environment.
+ directories.revalidate(ALL_PROJECTS_KEY),
+ directories.revalidate(projectId),
+ ]);
+ },
attachRepository: async (input) => {
const result = await projectWorkingDirectoryService.attachRepository(input);
await Promise.all([