🤯 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
✨ feat(project): one work-location picker for project conversations and a unified add-environment flow (#22834)
Arvin Xu3742ce866e68
diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex d0871f30375..da956f4fec3 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -128,6 +128,15 @@"directories.untitled": "Untitled topic","disabled.action": "Enable in Labs","disabled.title": "Project workspaces are an Alpha experiment",+ "environment.add.action": "Add",+ "environment.add.existing": "Add an existing one",+ "environment.add.failed": "Couldn't add the environment to this project",+ "environment.add.github": "New from GitHub",+ "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.privateInShared": "Private",+ "environment.privateInSharedTooltip": "This project is shared, so its conversations only use published environments. This private environment won't be checked out.","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.",@@ -223,18 +232,19 @@"overview.activeTasks": "In progress","overview.agentSelect": "Choose an agent","overview.composerPlaceholder": "Tell the project what to move forward next…",- "overview.context.repository.add": "Add a repository",- "overview.context.repository.addAction": "Add",- "overview.context.repository.addTitle": "Add a repository to this project",- "overview.context.repository.attachFailed": "Couldn't add the repository to this project",+ "overview.context.location.devices": "Devices",+ "overview.context.location.directories": "Project folders",+ "overview.context.location.directoryUnavailable": "Couldn't reach this folder. Check that the device is online and the folder still exists.",+ "overview.context.location.environments": "Code environments",+ "overview.context.location.noDirectories": "No project folders on this device yet.",+ "overview.context.location.noDirectoryTooltip": "This device has no project folder yet, so the conversation starts in the device's default directory.",+ "overview.context.location.noEnvironments": "No code environments yet.",+ "overview.context.location.title": "Work location","overview.context.repository.publishHint": "This agent is shared with the workspace and only uses published environments, so the repository is added as one that workspace members can see.",- "overview.context.repository.tooltip": "New conversations work in this repository, cloned before the first command.",- "overview.context.settings": "Repositories and environments","overview.context.target.device": "A connected device","overview.context.target.noneTooltip": "This agent has nowhere to run yet. Switch to the cloud sandbox so it can work on the code.","overview.context.target.sandboxTooltip": "Runs in the cloud sandbox, so none of your devices need to be online.","overview.context.target.switchFailed": "Couldn't change where this agent runs",- "overview.context.target.useSandbox": "Use the cloud sandbox","overview.contextTitle": "Project context","overview.createTask": "Create task","overview.createTaskFailed": "Could not create the task",@@ -379,8 +389,6 @@"settings.removeDirectoryConfirmDescription": "{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.","settings.removeDirectoryConfirmTitle": "Remove {{name}} from this project?","settings.removeDirectoryFailed": "Could not remove the folder. If a topic is running here, wait for it to finish and try again.",- "settings.reuseEnvironment": "Add an existing environment to this project",- "settings.reuseEnvironmentDescription": "Already created an environment? Select it to link its repository configuration to this project, then add a working directory for this project.","settings.saveFailed": "Could not save the change","settings.saved": "Saved","settings.slugDescription": "Used in the project URL. Changing it updates the address; leave blank to use the project ID.",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex 53bd65e01d8..4b53bbc8d4a 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -128,6 +128,15 @@"directories.untitled": "未命名话题","disabled.action": "前往实验室开启","disabled.title": "项目工作空间目前处于 Alpha 阶段",+ "environment.add.action": "添加",+ "environment.add.existing": "添加已有环境",+ "environment.add.failed": "无法将环境添加到本项目",+ "environment.add.github": "从 GitHub 新建",+ "environment.add.noExisting": "你的环境都已添加到本项目。",+ "environment.add.noPublished": "没有可添加的已发布环境。共享项目只会使用已发布的环境。",+ "environment.add.title": "添加环境",+ "environment.privateInShared": "仅自己可见",+ "environment.privateInSharedTooltip": "这是共享项目,对话只会使用已发布的环境,这个私有环境不会被检出。","goals.create": "新建目标","goals.description": "定义这个项目正在追求的成果,并持续跟踪到验收。","goals.emptyDescription": "为这个项目创建第一个可衡量的成果。",@@ -223,18 +232,19 @@"overview.activeTasks": "正在推进","overview.agentSelect": "选择 Agent","overview.composerPlaceholder": "告诉项目接下来要推进什么…",- "overview.context.repository.add": "添加代码仓库",- "overview.context.repository.addAction": "添加",- "overview.context.repository.addTitle": "为项目添加代码仓库",- "overview.context.repository.attachFailed": "没能把代码仓库加到这个项目里",+ "overview.context.location.devices": "设备",+ "overview.context.location.directories": "项目工作目录",+ "overview.context.location.directoryUnavailable": "无法访问这个工作目录,请确认设备在线且目录仍然存在。",+ "overview.context.location.environments": "代码环境",+ "overview.context.location.noDirectories": "这台设备上还没有项目工作目录。",+ "overview.context.location.noDirectoryTooltip": "这台设备上还没有项目工作目录,对话会在设备的默认目录中开始。",+ "overview.context.location.noEnvironments": "还没有代码环境。",+ "overview.context.location.title": "工作位置","overview.context.repository.publishHint": "这个助手已共享给工作区,只能使用已发布的环境,因此仓库会以工作区成员可见的环境添加。",- "overview.context.repository.tooltip": "新对话在这个仓库里进行,首条命令前自动克隆。",- "overview.context.settings": "仓库与环境设置","overview.context.target.device": "已连接设备","overview.context.target.noneTooltip": "这个助手还没有可运行的位置。切换到云端沙箱后,它就能直接处理代码。","overview.context.target.sandboxTooltip": "在云端沙箱里运行,不需要你的设备在线。","overview.context.target.switchFailed": "没能切换运行位置",- "overview.context.target.useSandbox": "改用云端沙箱","overview.contextTitle": "项目上下文","overview.createTask": "创建任务","overview.createTaskFailed": "创建任务失败",@@ -379,8 +389,6 @@"settings.removeDirectoryConfirmDescription": "{{device}} 上的 {{path}} 将不再是本项目的工作目录。设备上的文件不会改动,相关话题仍保留在项目中,但不再关联此文件夹。","settings.removeDirectoryConfirmTitle": "从项目中移除「{{name}}」?","settings.removeDirectoryFailed": "无法移除文件夹。如果有话题正在此处运行,请等待结束后重试。",- "settings.reuseEnvironment": "将已有环境添加到本项目",- "settings.reuseEnvironmentDescription": "如果之前已创建过环境,可从列表选择,将它的仓库配置关联到本项目,再为本项目添加工作目录。","settings.saveFailed": "保存失败","settings.saved": "已保存","settings.slugDescription": "用于项目链接。修改后地址会更新,留空则使用项目 ID。",diff --git a/packages/database/src/models/__tests__/project.repository.test.ts b/packages/database/src/models/__tests__/project.repository.test.tsindex b7dfd241f4b..c3d1146f2ea 100644--- a/packages/database/src/models/__tests__/project.repository.test.ts+++ b/packages/database/src/models/__tests__/project.repository.test.ts@@ -2,13 +2,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { ProjectRepository } from '../../repositories/project';-import { environments, projectEnvironments, users } from '../../schemas';+import { environments, projectEnvironments, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { EnvironmentModel } from '../environment';import type { CreateProjectInput } from '../project';import { ProjectModel } from '../project';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'project-repository-user';+const workspaceId = 'project-repository-workspace';let projectIdentifierSequence = 0;// Creating a project spans the project and the environment aggregates, so the@@ -32,6 +34,7 @@ describe('a project created from a GitHub repository', () => {afterEach(async () => {await serverDB.delete(projectEnvironments);await serverDB.delete(environments);+ await serverDB.delete(workspaces);await serverDB.delete(users);});@@ -66,6 +69,41 @@ describe('a project created from a GitHub repository', () => {]);});+ it('publishes the repository of a shared workspace project instead of reusing a private one', async () => {+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Repository Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ const repository = { name: 'lobehub/lobehub', url: 'https://github.com/lobehub/lobehub' };+ // The creator already checks the repository out privately.+ const own = await new EnvironmentModel(serverDB, userId, workspaceId).ensureForRepository({+ name: repository.name,+ repositoryUrl: repository.url,+ });+ const workspaceRepo = new ProjectRepository(serverDB, userId, workspaceId);+ const workspaceModel = new ProjectModel(serverDB, userId, workspaceId);++ const shared = await createProject(workspaceRepo, {+ name: 'Shared',+ repository,+ visibility: 'public',+ });+ const privateProject = await createProject(workspaceRepo, {+ name: 'Private',+ repository,+ visibility: 'private',+ });++ const [sharedEnvironment] = await workspaceModel.listEnvironments(shared.id);+ expect(sharedEnvironment).toEqual(expect.objectContaining({ visibility: 'public' }));+ expect(sharedEnvironment.id).not.toBe(own.id);+ expect(await workspaceModel.listEnvironments(privateProject.id)).toEqual([+ expect.objectContaining({ id: own.id, visibility: 'private' }),+ ]);+ });+it('names the unique index a taken slug violates, so the router can map it', async () => {await createProject(repo, { name: 'Taken', slug: 'taken' });const error = await createProject(repo, { name: 'Taken again', slug: 'taken' }).catch(diff --git a/packages/database/src/repositories/project/index.ts b/packages/database/src/repositories/project/index.tsindex 53d8611c996..31f6f5b7bf5 100644--- a/packages/database/src/repositories/project/index.ts+++ b/packages/database/src/repositories/project/index.ts@@ -65,7 +65,13 @@ export class ProjectRepository {// The environment belongs to another aggregate too, and a repository the// environment cannot accept must not leave a half-made project behind, so// it is created in the same transaction.+ //+ // A workspace-public main agent applies published environments only, so+ // its repository is published too; reusing the creator's private one+ // would link a repository the project's conversations never check out.if (repository) {+ const publish =+ !!this.workspaceId && (mainAgent as { visibility?: string }).visibility === 'public';const environment = await new EnvironmentModel(db,this.userId,@@ -74,6 +80,7 @@ export class ProjectRepository {defaultBranch: repository.defaultBranch,name: repository.name,repositoryUrl: repository.url,+ ...(publish && { visibility: 'public' as const }),});await db.insert(projectEnvironments).values({addedByUserId: this.userId,diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex b5c6485de92..3d617331157 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -1,7 +1,5 @@export default {'directories.currentFolder': 'Current folder',- 'settings.reuseEnvironmentDescription':- 'Already created an environment? Select it to link its repository configuration to this project, then add a working directory for this project.','settings.startDirectoryConversation': 'New topic here','settings.editDirectory': 'Edit folder','settings.editDirectoryBusy':@@ -18,7 +16,6 @@ export default {'settings.removeDirectoryFailed':'Could not remove the folder. If a topic is running here, wait for it to finish and try again.','settings.configureDirectory': 'Add a working directory',- 'settings.reuseEnvironment': 'Add an existing environment to this project','settings.addDirectoryFailed': 'Could not add working directory','settings.identifier': 'Project identifier','settings.identifierDescription':@@ -302,24 +299,37 @@ export default {'rename.nameLabel': 'Project name','rename.success': 'Project renamed','rename.title': 'Rename project',+ 'environment.add.action': 'Add',+ 'environment.add.existing': 'Add an existing one',+ 'environment.add.failed': "Couldn't add the environment to this project",+ 'environment.add.github': 'New from GitHub',+ '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.privateInShared': 'Private',+ 'environment.privateInSharedTooltip':+ "This project is shared, so its conversations only use published environments. This private environment won't be checked out.",+ 'overview.context.location.devices': 'Devices',+ 'overview.context.location.directories': 'Project folders',+ 'overview.context.location.directoryUnavailable':+ "Couldn't reach this folder. Check that the device is online and the folder still exists.",+ 'overview.context.location.noDirectories': 'No project folders on this device yet.',+ 'overview.context.location.noDirectoryTooltip':+ "This device has no project folder yet, so the conversation starts in the device's default directory.",+ 'overview.context.location.environments': 'Code environments',+ 'overview.context.location.noEnvironments': 'No code environments yet.',+ 'overview.context.location.title': 'Work location','overview.openTasks': 'Open task workspace','overview.composerPlaceholder': 'Tell the project what to move forward next…',- 'overview.context.repository.add': 'Add a repository',- 'overview.context.repository.addAction': 'Add',- 'overview.context.repository.addTitle': 'Add a repository to this project',- 'overview.context.repository.attachFailed': "Couldn't add the repository to this project",'overview.context.repository.publishHint':'This agent is shared with the workspace and only uses published environments, so the repository is added as one that workspace members can see.',- 'overview.context.repository.tooltip':- 'New conversations work in this repository, cloned before the first command.',- 'overview.context.settings': 'Repositories and environments','overview.context.target.device': 'A connected device','overview.context.target.noneTooltip':'This agent has nowhere to run yet. Switch to the cloud sandbox so it can work on the code.','overview.context.target.sandboxTooltip':'Runs in the cloud sandbox, so none of your devices need to be online.','overview.context.target.switchFailed': "Couldn't change where this agent runs",- 'overview.context.target.useSandbox': 'Use the cloud sandbox','overview.sendHint': '⌘ ↵ to send','overview.startConversation': 'Start moving','overview.tasksEmpty': 'No tasks belong to this project yet.',diff --git a/src/components/RepositoryAvatar/githubOwner.test.ts b/src/components/RepositoryAvatar/githubOwner.test.tsnew file mode 100644index 00000000000..453ee616e0d--- /dev/null+++ b/src/components/RepositoryAvatar/githubOwner.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { githubOwner } from './index';++describe('githubOwner', () => {+ it('reads the owner of every form an environment names its repository in', () => {+ expect(githubOwner('https://github.com/lobehub-biz/agent-mail')).toBe('lobehub-biz');+ expect(githubOwner('[email protected]:lobehub/lobehub.git')).toBe('lobehub');+ expect(githubOwner('lobehub/lobe-tts')).toBe('lobehub');+ });++ it('names no owner for anything else', () => {+ expect(githubOwner(undefined)).toBeUndefined();+ expect(githubOwner('https://gitlab.com/a/b')).toBeUndefined();+ expect(githubOwner('agent-mail')).toBeUndefined();+ });+});diff --git a/src/components/RepositoryAvatar/index.tsx b/src/components/RepositoryAvatar/index.tsxnew file mode 100644index 00000000000..b51194b4860--- /dev/null+++ b/src/components/RepositoryAvatar/index.tsx@@ -0,0 +1,54 @@+'use client';++import { Github } from '@lobehub/icons';+import { Avatar, Center } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ fallback: {+ flex: 'none',+ borderRadius: '50%',+ color: cssVar.colorTextSecondary,+ backgroundColor: cssVar.colorFillTertiary,+ },+});++interface RepositoryAvatarProps {+ size?: number;+ /** The repository an environment checks out: its GitHub URL, or `owner/name`. */+ url?: string;+}++/**+ * A repository told apart at a glance: its owner's round GitHub avatar, the+ * GitHub mark when the URL names no GitHub owner.+ */+/** The owner of `https://github.com/owner/name`, `[email protected]:owner/name` or `owner/name`. */+export const githubOwner = (url?: string) =>+ url+ ? /^(?:https:\/\/github\.com\/|git@github\.com:)?([\w.-]+)\/[\w.-]+/.exec(url.trim())?.[1]+ : undefined;++const RepositoryAvatar = ({ size = 16, url }: RepositoryAvatarProps) => {+ const owner = githubOwner(url);++ if (!owner)+ return (+ <Center height={size} width={size} {...stylex.props(styles.fallback)}>+ <Github size={Math.round(size * 0.65)} />+ </Center>+ );++ return (+ <Avatar+ avatar={`https://github.com/${owner}.png?size=${size * 2}`}+ shape={'circle'}+ size={size}+ style={{ flex: 'none' }}+ title={owner}+ />+ );+};++export default RepositoryAvatar;diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxindex 90639f685e6..ea2c41ef064 100644--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -20,6 +20,7 @@ import useSWR from 'swr';import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import RepositoryAvatar from '@/components/RepositoryAvatar';import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';import { SANDBOX_STORAGE_PATH } from '@/features/ResourceHome/paths';import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';@@ -36,6 +37,7 @@ import {environmentChipState,pickableEnvironments,repositorySelection,+ repositorySlug,} from './sandboxEnvironmentOptions';import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';@@ -252,7 +254,7 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(const chipIcon = fallback ? (<Icon icon={TriangleAlertIcon} size={14} />) : onRepository ? (- <Github size={14} />+ <RepositoryAvatar size={14} url={repository && repositorySlug(repository)} />) : persistent ? (<Icon icon={currentIcon} size={14} />) : (@@ -379,8 +381,21 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(arrowcompactactive={onRepository}- icon={<Github size={16} />}- label={t('sandboxEnvironment.title')}+ hint={onRepository && repository ? repositorySlug(repository) : undefined}+ icon={+ onRepository && repository ? (+ <RepositoryAvatar size={16} url={repositorySlug(repository)} />+ ) : (+ <Github size={16} />+ )+ }+ label={+ // The repository the conversation works in, by name; the+ // generic title only while none is picked.+ onRepository && repositoryState.kind === 'picked'+ ? repositoryState.name+ : t('sandboxEnvironment.title')+ }onClick={() => {}}/></div>diff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsxindex 65f954eb8f1..e373ba6dfe3 100644--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx+++ b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx@@ -1,7 +1,6 @@'use client';import type { EnvironmentConfiguration } from '@lobechat/types';-import { Github } from '@lobehub/icons';import { Button, Flexbox, Icon, Text } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';@@ -9,6 +8,8 @@ import { PlusIcon, SettingsIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import RepositoryAvatar from '@/components/RepositoryAvatar';+import OptionRow from './OptionRow';import { repositorySlug } from './sandboxEnvironmentOptions';import SubmenuHeader from './SubmenuHeader';@@ -71,7 +72,7 @@ const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(active={environment.id === selectedId}desc={environment.description || undefined}hint={repositorySlug(environment)}- icon={<Github size={16} />}+ icon={<RepositoryAvatar size={16} url={repositorySlug(environment)} />}key={environment.id}label={environment.name}onClick={() => {diff --git a/src/features/Projects/AddEnvironmentModal.tsx b/src/features/Projects/AddEnvironmentModal.tsxnew file mode 100644index 00000000000..ff12c001f93--- /dev/null+++ b/src/features/Projects/AddEnvironmentModal.tsx@@ -0,0 +1,254 @@+'use client';++import {+ Button,+ createModal,+ cssVar as lobeCssVar,+ Flexbox,+ Input,+ ModalFooter,+ Segmented,+ Text,+ toast,+ useModalContext,+} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { t as translate } from 'i18next';+import { CheckIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import RepositoryAvatar from '@/components/RepositoryAvatar';+import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';+import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';++import { parseGithubRepository } from './CreateFromGithub/githubRepository';+import RepositoryList from './CreateFromGithub/RepositoryList';+import { environmentRepositoryUrl, reusableEnvironments } from './environmentSource';++const styles = stylex.create({+ list: {+ overflowY: 'auto',+ maxHeight: '300px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+ row: {+ cursor: 'pointer',+ display: 'flex',+ gap: '12px',+ alignItems: 'center',+ width: '100%',+ paddingBlock: '8px',+ paddingInline: '12px',+ borderBlockStartWidth: 0,+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: { 'default': 'solid', ':last-child': 'none' },+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderInlineWidth: 0,+ font: 'inherit',+ color: 'inherit',+ textAlign: 'start',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ },+ selected: {+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillSecondary },+ },+ check: {+ flex: 'none',+ color: cssVar.colorPrimary,+ },+});++type Source = 'existing' | 'github';++interface AddEnvironmentContentProps {+ /** Called with the environment now linked to the project. */+ onAdded?: (environmentId: string) => void;+ projectId: string;+ /**+ * The project's conversations run a workspace-public agent, which applies+ * published environments only: a new repository is published, and only+ * published environments are offered for reuse.+ */+ publish?: boolean;+}++/**+ * The one way to give a project an environment: a GitHub repository — one the+ * 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 { t } = useTranslation(['project', 'common']);+ const { close } = useModalContext();+ const navigate = useWorkspaceAwareNavigate();+ const attachRepository = useProjectDirectoryStore((s) => s.attachRepository);+ const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);+ const available = useProjectDirectoryStore((s) => s.useFetchEnvironments)();+ useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);+ const linked = useProjectEnvironments(projectId);+ const owned = useProjectEnvironments();+ const reusable = reusableEnvironments(owned, linked, publish);++ const [source, setSource] = useState<Source>('github');+ const [url, setUrl] = useState('');+ const [defaultBranch, setDefaultBranch] = useState<string>();+ const [existingId, setExistingId] = useState<string>();+ const [adding, setAdding] = useState(false);++ const repository = parseGithubRepository(url);+ const urlInvalid = Boolean(url.trim()) && !repository;+ const existing = reusable.find((environment) => environment.id === existingId);+ const ready = source === 'github' ? !!repository : !!existing;++ const add = async () => {+ if (!ready || adding) return;+ setAdding(true);+ try {+ let environmentId: string;+ if (source === 'github') {+ const environment = await attachRepository({+ projectId,+ repository: { defaultBranch, name: repository!.fullName, url: repository!.url },+ ...(publish && { visibility: 'public' as const }),+ });+ environmentId = environment.id;+ } else {+ await attachEnvironment(projectId, existing!.id);+ environmentId = existing!.id;+ }+ close();+ onAdded?.(environmentId);+ } catch (error) {+ console.error('Failed to add an environment to the project', error);+ toast.error(t('environment.add.failed'));+ } finally {+ setAdding(false);+ }+ };++ return (+ <>+ <Flexbox gap={16} padding={16}>+ <Segmented+ block+ value={source}+ options={[+ { label: t('environment.add.github'), value: 'github' },+ { label: t('environment.add.existing'), value: 'existing' },+ ]}+ onChange={(value) => setSource(value as Source)}+ />+ {source === 'github' ? (+ <>+ <RepositoryList+ selected={repository?.fullName}+ onConnect={() => {+ close();+ navigate(GITHUB_RETURN_TO);+ }}+ onSelect={(picked) => {+ setUrl(picked.htmlUrl);+ setDefaultBranch(picked.defaultBranch);+ }}+ />+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('createFromGithub.urlLabel')}+ </Text>+ <Input+ aria-invalid={urlInvalid}+ placeholder={t('createFromGithub.urlPlaceholder')}+ style={urlInvalid ? { borderColor: lobeCssVar.colorError } : undefined}+ value={url}+ onPressEnter={add}+ onChange={(event) => {+ setUrl(event.target.value);+ // A typed URL names no branch; the repository's default applies.+ setDefaultBranch(undefined);+ }}+ />+ {urlInvalid && (+ <Text fontSize={12} type={'danger'}>+ {t('createFromGithub.urlInvalid')}+ </Text>+ )}+ </Flexbox>+ {publish && (+ <Text fontSize={12} type={'secondary'}>+ {t('overview.context.repository.publishHint')}+ </Text>+ )}+ </>+ ) : available.error && !available.hasData ? (+ <AsyncError error={available.error} onRetry={() => available.revalidate()} />+ ) : !available.hasData ? (+ <Text type={'secondary'}>{t('loading', { ns: 'common' })}</Text>+ ) : reusable.length === 0 ? (+ <Flexbox align={'center'} gap={12} paddingBlock={24}>+ <Text type={'secondary'}>+ {t(publish ? 'environment.add.noPublished' : 'environment.add.noExisting')}+ </Text>+ <Button onClick={() => setSource('github')}>{t('environment.add.github')}</Button>+ </Flexbox>+ ) : (+ <div {...stylex.props(styles.list)} role={'listbox'}>+ {reusable.map((environment) => {+ const selected = environment.id === existingId;+ return (+ <button+ aria-selected={selected}+ key={environment.id}+ role={'option'}+ type={'button'}+ {...stylex.props(styles.row, selected && styles.selected)}+ onClick={() => setExistingId(environment.id)}+ >+ <RepositoryAvatar size={28} url={environmentRepositoryUrl(environment)} />+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {environment.name}+ </Text>+ {/* A name that already is the slug needs no second copy of it. */}+ {repositorySlug(environment) !== environment.name && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {repositorySlug(environment) ?? t('settings.noRepository')}+ </Text>+ )}+ </Flexbox>+ {selected && (+ <span {...stylex.props(styles.check)}>+ <CheckIcon size={16} />+ </span>+ )}+ </button>+ );+ })}+ </div>+ )}+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>+ <Button disabled={!ready} loading={adding} type={'primary'} onClick={add}>+ {t('environment.add.action')}+ </Button>+ </ModalFooter>+ </>+ );+};++export const openAddEnvironmentModal = (props: AddEnvironmentContentProps) =>+ createModal({+ content: <AddEnvironmentContent {...props} />,+ footer: null,+ styles: { content: { padding: 0 } },+ title: translate('environment.add.title', { ns: 'project' }),+ width: 560,+ });diff --git a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsxindex 07c52eb492e..89c3656f61d 100644--- a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx+++ b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx@@ -17,10 +17,20 @@ import { deviceService } from '@/services/device';import { deviceSelectors, useDeviceStore } from '@/store/device';import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';+interface AddDirectoryOptions {+ /** The machine to add it on, when the caller already knows it. */+ deviceId?: string;+ /** Called with the folder once it is part of the project. */+ /** Called with the folder once it is part of the project, and the device it was saved on. */+ onAdded?: (directory: { deviceId: string; id: string }) => void;+}+function AddDirectoryContent({projectId,environmentId: initialEnvironmentId,-}: {+ deviceId: initialDeviceId,+ onAdded,+}: AddDirectoryOptions & {projectId: string;environmentId?: string;}) {@@ -30,7 +40,7 @@ function AddDirectoryContent({const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);const environments = useProjectEnvironments(projectId);const [environmentId, setEnvironment] = useState(initialEnvironmentId ?? '');- const [deviceId, setDevice] = useState('');+ const [deviceId, setDevice] = useState(initialDeviceId ?? '');const [path, setPath] = useState('');const [pending, setPending] = useState(false);const [error, setError] = useState<unknown>();@@ -42,7 +52,7 @@ function AddDirectoryContent({try {const stat = await deviceService.statPath(deviceId, path);if (!stat?.exists || !stat.isDirectory) throw new Error(t('settings.directoryUnavailable'));- await bind({+ const added = await bind({projectId,environmentId,deviceId,@@ -50,6 +60,8 @@ function AddDirectoryContent({name: path.split(/[\\/]/).findLast(Boolean) || path,});close();+ // The device picked here, not the one the caller suggested: the person may have changed it.+ onAdded?.({ deviceId, id: added.id });} catch (error) {console.error('Failed to add work location', error);setError(error);@@ -127,10 +139,16 @@ function AddDirectoryContent({</Flexbox>);}-export const openAddDirectoryModal = (projectId: string, environmentId?: string) =>+export const openAddDirectoryModal = (+ projectId: string,+ environmentId?: string,+ options: AddDirectoryOptions = {},+) =>createModal({title: t('settings.addDirectory', { ns: 'project' }),- content: <AddDirectoryContent environmentId={environmentId} projectId={projectId} />,+ content: (+ <AddDirectoryContent {...options} environmentId={environmentId} projectId={projectId} />+ ),footer: null,width: 520,});diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsxindex a3a89be48ff..d954b81fa89 100644--- a/src/features/Projects/WorkingDirectories/Page.tsx+++ b/src/features/Projects/WorkingDirectories/Page.tsx@@ -62,7 +62,12 @@ export function ProjectDirectoriesPage() {{key: 'environments',label: t('settings.environments'),- render: () => <ProjectWorkingDirectories projectId={detail.project.id} />,+ render: () => (+ <ProjectWorkingDirectories+ projectId={detail.project.id}+ shared={Boolean(detail.project.workspaceId) && detail.project.visibility === 'public'}+ />+ ),},{key: 'directories',diff --git a/src/features/Projects/WorkingDirectories/index.tsx b/src/features/Projects/WorkingDirectories/index.tsxindex 088176047d7..4eeb665f559 100644--- a/src/features/Projects/WorkingDirectories/index.tsx+++ b/src/features/Projects/WorkingDirectories/index.tsx@@ -1,10 +1,9 @@-import { ActionIcon, Block, Button, cssVar, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';-import { GithubIcon } from '@lobehub/ui/icons';-import { ChevronDownIcon, FolderIcon, PencilIcon, PlusIcon } from 'lucide-react';-import { useState } from 'react';+import { ActionIcon, Block, Button, cssVar, Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';+import { FolderIcon, PencilIcon, PlusIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';+import RepositoryAvatar from '@/components/RepositoryAvatar';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import {useProjectDirectories,@@ -12,38 +11,26 @@ import {useProjectEnvironments,} from '@/store/projectWorkingDirectory';+import { openAddEnvironmentModal } from '../AddEnvironmentModal';import { openEnvironmentModal } from './EnvironmentModal';-export function ProjectWorkingDirectories({ projectId }: { projectId: string }) {+interface ProjectWorkingDirectoriesProps {+ projectId: string;+ /**+ * A workspace-public project: its conversations run a public agent, which+ * applies published environments only.+ */+ shared?: boolean;+}++export function ProjectWorkingDirectories({ projectId, shared }: ProjectWorkingDirectoriesProps) {const { t } = useTranslation('project');const navigate = useWorkspaceAwareNavigate();const linkedRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);- const availableRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)();const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);const linked = useProjectEnvironments(projectId);- const available = useProjectEnvironments();const directories = useProjectDirectories(projectId);- const attach = useProjectDirectoryStore((s) => s.attachEnvironment);- const [pending, setPending] = useState(false);- const [error, setError] = useState<unknown>();- const [failedEnvironmentId, setFailedEnvironmentId] = useState<string>();- const link = async (id: string) => {- setFailedEnvironmentId(id);- setPending(true);- setError(undefined);- try {- await attach(projectId, id);- setFailedEnvironmentId(undefined);- } catch (error) {- console.error('Failed to associate environment', error);- setError(error);- } finally {- setPending(false);- }- };- const unlinked = available.filter((env) => !linked.some((item) => item.id === env.id));- const requestError =- error || linkedRequest.error || availableRequest.error || directoriesRequest.error;+ const requestError = linkedRequest.error || directoriesRequest.error;return (<Flexbox gap={20}><Flexbox gap={12}>@@ -51,49 +38,20 @@ export function ProjectWorkingDirectories({ projectId }: { projectId: string })<Text fontSize={16} weight={600}>{t('settings.environments')}</Text>- <Flexbox horizontal gap={8}>- {!!unlinked.length && (- <DropdownMenu- items={unlinked.map((env) => ({- key: env.id,- label: env.name,- onClick: () => void link(env.id),- }))}- >- <Button disabled={pending} icon={ChevronDownIcon}>- {t('settings.reuseEnvironment')}- </Button>- </DropdownMenu>- )}- <Button- disabled={pending}- icon={PlusIcon}- type="primary"- onClick={() => openEnvironmentModal({ onSaved: (env) => link(env.id) })}- >- {t('directories.newEnvironment')}- </Button>- </Flexbox>+ <Button+ icon={PlusIcon}+ type="primary"+ onClick={() => openAddEnvironmentModal({ projectId, publish: shared })}+ >+ {t('environment.add.title')}+ </Button></Flexbox><Text type="secondary">{t('settings.environmentDescription')}</Text>- {!!unlinked.length && (- <Text fontSize={13} type="secondary">- {t('settings.reuseEnvironmentDescription')}- </Text>- )}</Flexbox>{requestError ? (<AsyncErrorerror={requestError}- onRetry={() =>- failedEnvironmentId- ? link(failedEnvironmentId)- : Promise.all([- linkedRequest.revalidate(),- availableRequest.revalidate(),- directoriesRequest.revalidate(),- ])- }+ onRetry={() => Promise.all([linkedRequest.revalidate(), directoriesRequest.revalidate()])}/>) : !linkedRequest.hasData || !directoriesRequest.hasData ? (<Text>{t('loading', { ns: 'common' })}</Text>@@ -104,6 +62,8 @@ export function ProjectWorkingDirectories({ projectId }: { projectId: string }){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 (<Flexboxhorizontal@@ -116,10 +76,34 @@ export function ProjectWorkingDirectories({ projectId }: { projectId: string })index ? { borderTop: `1px solid ${cssVar.colorBorderSecondary}` } : undefined}>- <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>- <Text weight={500}>{env.name}</Text>- <Flexbox horizontal align="center" gap={6}>- <Icon icon={source ? GithubIcon : FolderIcon} size={14} />+ <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 ? (<ahref={source.url}diff --git a/src/features/Projects/Workspace/AddRepositoryModal.tsx b/src/features/Projects/Workspace/AddRepositoryModal.tsxdeleted file mode 100644index a76a834f6bd..00000000000--- a/src/features/Projects/Workspace/AddRepositoryModal.tsx+++ /dev/null@@ -1,130 +0,0 @@-'use client';--import {- Button,- createModal,- cssVar,- Flexbox,- Input,- ModalFooter,- Text,- toast,- useModalContext,-} from '@lobehub/ui';-import { t as translate } from 'i18next';-import { useState } from 'react';-import { useTranslation } from 'react-i18next';--import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';-import { parseGithubRepository } from '@/features/Projects/CreateFromGithub/githubRepository';-import RepositoryList from '@/features/Projects/CreateFromGithub/RepositoryList';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';--interface AddRepositoryContentProps {- onAdded: (environmentId: string) => void;- projectId: string;- /**- * Add it as a published environment: the composer's agent is workspace-public- * and applies nothing else, so a private one would be linked and never used.- */- publish?: boolean;-}--/**- * A repository for the project: one the connected GitHub App can read, or a- * pasted URL — the same two ways a project is created from GitHub, so the- * dialog works whether or not GitHub is connected. The environment that checks- * it out is the caller's own, reused when they already have one for it.- */-const AddRepositoryContent = ({ onAdded, projectId, publish }: AddRepositoryContentProps) => {- const { t } = useTranslation(['project', 'common']);- const { close } = useModalContext();- const navigate = useWorkspaceAwareNavigate();- const attachRepository = useProjectDirectoryStore((s) => s.attachRepository);- const [url, setUrl] = useState('');- const [defaultBranch, setDefaultBranch] = useState<string>();- const [adding, setAdding] = useState(false);-- const repository = parseGithubRepository(url);- const urlInvalid = Boolean(url.trim()) && !repository;-- const add = async () => {- if (!repository || adding) return;- setAdding(true);- try {- const environment = await attachRepository({- projectId,- repository: { defaultBranch, name: repository.fullName, url: repository.url },- ...(publish && { visibility: 'public' as const }),- });- close();- onAdded(environment.id);- } catch (error) {- console.error('Failed to add the repository to the project', error);- toast.error(t('overview.context.repository.attachFailed'));- } finally {- setAdding(false);- }- };-- return (- <>- <Flexbox gap={16} padding={16}>- <RepositoryList- selected={repository?.fullName}- onConnect={() => {- close();- navigate(GITHUB_RETURN_TO);- }}- onSelect={(picked) => {- setUrl(picked.htmlUrl);- setDefaultBranch(picked.defaultBranch);- }}- />- <Flexbox gap={6}>- <Text fontSize={13} weight={500}>- {t('createFromGithub.urlLabel')}- </Text>- <Input- aria-invalid={urlInvalid}- placeholder={t('createFromGithub.urlPlaceholder')}- style={urlInvalid ? { borderColor: cssVar.colorError } : undefined}- value={url}- onPressEnter={add}- onChange={(event) => {- setUrl(event.target.value);- // A typed URL names no branch; the repository's default applies.- setDefaultBranch(undefined);- }}- />- {urlInvalid && (- <Text fontSize={12} type={'danger'}>- {t('createFromGithub.urlInvalid')}- </Text>- )}- </Flexbox>- {publish && (- <Text fontSize={12} type={'secondary'}>- {t('overview.context.repository.publishHint')}- </Text>- )}- </Flexbox>- <ModalFooter>- <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>- <Button disabled={!repository} loading={adding} type={'primary'} onClick={add}>- {t('overview.context.repository.addAction')}- </Button>- </ModalFooter>- </>- );-};--export const openAddRepositoryModal = (props: AddRepositoryContentProps) =>- createModal({- content: <AddRepositoryContent {...props} />,- footer: null,- styles: { content: { padding: 0 } },- title: translate('overview.context.repository.addTitle', { ns: 'project' }),- width: 520,- });diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsxindex da1714d98b6..71d539c8af6 100644--- a/src/features/Projects/Workspace/ProjectComposer.tsx+++ b/src/features/Projects/Workspace/ProjectComposer.tsx@@ -1,10 +1,10 @@'use client';-import { ActionIcon, cssVar as lobeCssVar, Flexbox, toast } from '@lobehub/ui';+import { cssVar as lobeCssVar, Flexbox, toast } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { useSize } from 'ahooks';-import { PlusIcon, SettingsIcon } from 'lucide-react';+import { PlusIcon } from 'lucide-react';import { memo, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -19,8 +19,6 @@ import {import FileUpload from '@/features/ChatInput/ActionBar/Upload';import InputDragUpload from '@/features/Home/InputArea/InputDragUpload';import ModeSelect from '@/features/Home/InputArea/ModeSelect';-import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -29,15 +27,17 @@ import type { ProjectDetail } from '@/store/project';import { useCanManageProject } from '../useCanManageProject';import ProjectAgentSelect from './ProjectAgentSelect';import { projectComposerAgents } from './projectComposerAgents';-import ProjectRepositoryChip from './ProjectRepositoryChip';-import ProjectRunTargetChip from './ProjectRunTargetChip';+import ProjectWorkLocationPicker from './ProjectWorkLocationPicker';import {AttachmentsNotReadyError,+ DirectoryUnavailableError,getProjectComposerContextKey,type ProjectComposerMode,useProjectComposer,} from './useProjectComposer';+import { useProjectDirectory } from './useProjectDirectory';import { useProjectRepository } from './useProjectRepository';+import { useProjectWorkLocation } from './useProjectWorkLocation';const leftActions: ActionKeys[] = [];const rightActions: ActionKeys[] = [];@@ -121,7 +121,6 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {const containerRef = useRef<HTMLDivElement>(null);const { t } = useTranslation('project');const { t: tHome } = useTranslation('home');- const navigate = useWorkspaceAwareNavigate();const trayRef = useRef<HTMLDivElement>(null);const traySize = useSize(trayRef);const compact = !!traySize && traySize.width < COMPACT_TRAY_WIDTH;@@ -151,9 +150,16 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {);const repositoryState = useProjectRepository(project.id, sharedAgent);const canManageProject = useCanManageProject();- // A task is not started in a conversation, so it has no repository to pick.- const environmentId = mode === 'chat' ? repositoryState.repository?.id : undefined;- const { send, sending } = useProjectComposer(project, mode, agentId, environmentId);+ const location = useProjectWorkLocation(agentId);+ const directoryState = useProjectDirectory(project.id, location.machineDeviceId);+ // A task is not started in a conversation, so it has no repository or folder to pick.+ const place =+ mode !== 'chat'+ ? {}+ : location.target === 'sandbox'+ ? { environmentId: repositoryState.repository?.id }+ : { directoryId: directoryState.directory?.id };+ const { send, sending } = useProjectComposer(project, mode, agentId, place);useInitAgentConfig(agentId);const isAgentConfigLoading = useAgentStore((s) =>@@ -177,6 +183,10 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {toast.error(tHome('dashboard.task.attachmentsNotReady'));return;}+ if (error instanceof DirectoryUnavailableError) {+ toast.error(t('overview.context.location.directoryUnavailable'));+ return;+ }console.error('Failed to send from the project home', error);toast.error(t(mode === 'task' ? 'overview.createTaskFailed' : 'overview.sendFailed'));}@@ -222,25 +232,16 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {className={stylex.props(styles.trayTrailing).className}gap={2}>- {mode === 'chat' && (- <ProjectRepositoryChip- canManage={canManageProject}- compact={compact}- disabled={sending}- projectId={project.id}- publish={sharedAgent}- state={repositoryState}- />- )}- <ProjectRunTargetChip agentId={agentId} compact={compact} disabled={sending} />- <ActionIcon- aria-label={t('overview.context.settings')}- icon={SettingsIcon}- size={'small'}- title={t('overview.context.settings')}- onClick={() =>- navigate(getProjectSettingsPath(project.slug ?? project.id, 'environments'))- }+ <ProjectWorkLocationPicker+ canManage={canManageProject}+ compact={compact}+ directoryState={directoryState}+ disabled={sending}+ location={location}+ projectId={project.id}+ publish={sharedAgent}+ showRepositories={mode === 'chat'}+ state={repositoryState}/></Flexbox></Flexbox>diff --git a/src/features/Projects/Workspace/ProjectRepositoryChip.tsx b/src/features/Projects/Workspace/ProjectRepositoryChip.tsxdeleted file mode 100644index 91b851393e5..00000000000--- a/src/features/Projects/Workspace/ProjectRepositoryChip.tsx+++ /dev/null@@ -1,143 +0,0 @@-'use client';--import { Github } from '@lobehub/icons';-import { type DropdownItem, DropdownMenu, Icon, Tooltip } from '@lobehub/ui';-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';-import * as stylex from '@stylexjs/stylex';-import { CheckIcon, ChevronDownIcon, PlusIcon } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';-import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';--import { openAddRepositoryModal } from './AddRepositoryModal';-import type { useProjectRepository } from './useProjectRepository';--interface ProjectRepositoryChipProps {- /** Whether this member may link a repository to the project. */- canManage: boolean;- /** Icon only, the repository in the tooltip — for a narrow composer. */- compact?: boolean;- disabled?: boolean;- projectId: string;- /** Repositories added here are published: the agent is workspace-public and applies nothing else. */- publish?: boolean;- state: ReturnType<typeof useProjectRepository>;-}--/**- * Which of the project's repositories a new conversation works in. A project- * without one offers to add it here, linked to the project in the same step —- * the conversation needs nothing else to start on the code.- */-const ProjectRepositoryChip = ({- canManage,- compact,- disabled,- projectId,- publish,- state,-}: ProjectRepositoryChipProps) => {- const { t } = useTranslation('project');- const { loaded, repositories, repository, setPickedId } = state;-- const addRepository = () => openAddRepositoryModal({ onAdded: setPickedId, projectId, publish });-- if (!loaded) return null;-- if (!repository) {- if (!canManage) return null;- return (- <button- aria-label={t('overview.context.repository.add')}- disabled={disabled}- title={compact ? t('overview.context.repository.add') : undefined}- type={'button'}- {...stylex.props(workingDirectoryChipStyles.chip, styles.button)}- onClick={addRepository}- >- <Icon icon={PlusIcon} size={14} />- {!compact && <span>{t('overview.context.repository.add')}</span>}- </button>- );- }-- const slug = repositorySlug(repository) ?? repository.name;- const label = (- <>- <Github size={14} />- {!compact && (- <span {...stylex.props(workingDirectoryChipStyles.label)}>- {slug.split('/').pop() || repository.name}- </span>- )}- </>- );-- const items: DropdownItem[] = [- ...repositories.map((environment) => ({- extra: environment.id === repository.id ? <Icon icon={CheckIcon} size={14} /> : undefined,- icon: <Github size={14} />,- key: environment.id,- label: repositorySlug(environment) ?? environment.name,- onClick: () => setPickedId(environment.id),- })),- ...(canManage- ? [- { type: 'divider' as const },- {- icon: <Icon icon={PlusIcon} />,- key: 'add',- label: t('overview.context.repository.add'),- onClick: addRepository,- },- ]- : []),- ];-- const chip = (- <button- aria-label={slug}- data-testid={'project-repository-chip'}- disabled={disabled}- type={'button'}- {...stylex.props(workingDirectoryChipStyles.chip, styles.button)}- >- {label}- <Icon icon={ChevronDownIcon} size={12} />- </button>- );-- return (- <Tooltip- title={- compact- ? `${slug} · ${t('overview.context.repository.tooltip')}`- : t('overview.context.repository.tooltip')- }- >- <div>- {disabled ? (- chip- ) : (- <DropdownMenu items={items} placement={'bottomRight'}>- {chip}- </DropdownMenu>- )}- </div>- </Tooltip>- );-};--const styles = stylex.create({- // Body size and color: the tray says where the work happens, not a footnote.- button: {- borderWidth: 0,- fontFamily: 'inherit',- fontSize: '13px',- color: cssVar.colorText,- backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillSecondary },- },-});--export default ProjectRepositoryChip;diff --git a/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsx b/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsxdeleted file mode 100644index e65bf735375..00000000000--- a/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { fireEvent, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import ProjectRunTargetChip from './ProjectRunTargetChip';--const mocks = vi.hoisted(() => ({- agency: {- agencyConfig: undefined as- { executionTarget?: string; heterogeneousProvider?: { type: string } } | undefined,- canDisplayExecutionTarget: true,- canSelectExecutionTarget: true,- workspaceScoped: false,- },- selectExecutionTarget: vi.fn(),-}));--vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));--// The real menu opens on hover behind a portal; render its items inline so the-// cloud-switch action is reachable from the chip itself.-vi.mock('@lobehub/ui', async (importOriginal) => ({- ...(await importOriginal<object>()),- DropdownMenu: ({- children,- items,- }: {- children: ReactNode;- items?: { key: string; label: ReactNode; onClick?: () => void }[];- }) => (- <div>- {children}- {items?.map((item) => (- <button- data-testid={`run-target-menu-${item.key}`}- key={item.key}- type={'button'}- onClick={item.onClick}- >- {item.label}- </button>- ))}- </div>- ),-}));--vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => mocks.agency,-}));--vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));--vi.mock('@/features/ChatInput/hooks/useSelectExecutionTarget', () => ({- useSelectExecutionTarget: () => mocks.selectExecutionTarget,-}));--/** A device pick: resolvable everywhere, so the chip is not on the sandbox. */-const devicePick = (type?: string) => ({- boundDeviceId: 'device_1',- executionTarget: 'device',- ...(type ? { heterogeneousProvider: { type } } : {}),-});--beforeEach(() => {- mocks.agency.agencyConfig = undefined;- mocks.selectExecutionTarget.mockReset();- mocks.selectExecutionTarget.mockResolvedValue(true);-});--describe('ProjectRunTargetChip', () => {- it('does not offer the cloud switch to a device-only provider', () => {- // Amp has no sandbox toolchain: `resolveExecutionTarget` would coerce a- // stored sandbox target back to `none`, stripping the working device pick.- mocks.agency.agencyConfig = devicePick('amp');-- render(<ProjectRunTargetChip agentId={'agent_1'} />);-- expect(screen.getByTestId('project-run-target-chip')).toBeDisabled();- expect(screen.queryByTestId('run-target-menu-sandbox')).not.toBeInTheDocument();-- fireEvent.click(screen.getByTestId('project-run-target-chip'));-- expect(mocks.selectExecutionTarget).not.toHaveBeenCalled();- });-- it('keeps the cloud switch for a sandbox-capable provider', () => {- mocks.agency.agencyConfig = devicePick('claude-code');-- render(<ProjectRunTargetChip agentId={'agent_1'} />);-- expect(screen.getByTestId('project-run-target-chip')).toBeEnabled();-- fireEvent.click(screen.getByTestId('run-target-menu-sandbox'));-- expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('sandbox');- });-- it('keeps the cloud switch for an ordinary agent', () => {- mocks.agency.agencyConfig = devicePick();-- render(<ProjectRunTargetChip agentId={'agent_1'} />);-- expect(screen.getByTestId('project-run-target-chip')).toBeEnabled();-- fireEvent.click(screen.getByTestId('run-target-menu-sandbox'));-- expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('sandbox');- });-});diff --git a/src/features/Projects/Workspace/ProjectRunTargetChip.tsx b/src/features/Projects/Workspace/ProjectRunTargetChip.tsxdeleted file mode 100644index 134024aadc9..00000000000--- a/src/features/Projects/Workspace/ProjectRunTargetChip.tsx+++ /dev/null@@ -1,157 +0,0 @@-'use client';--import { isDesktop } from '@lobechat/const';-import type { DeviceExecutionTarget } from '@lobechat/types';-import { type DropdownItem, DropdownMenu, Icon, toast, Tooltip } from '@lobehub/ui';-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';-import * as stylex from '@stylexjs/stylex';-import {- ChevronDownIcon,- CloudIcon,- LaptopIcon,- type LucideIcon,- MonitorIcon,- MonitorOffIcon,- SparklesIcon,-} from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';-import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';-import {- isHeterogeneousSandboxExecutionAvailable,- resolveExecutionTarget,-} from '@/helpers/executionTarget';-import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';-import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';--const TARGET_ICONS: Record<DeviceExecutionTarget, LucideIcon> = {- auto: SparklesIcon,- device: MonitorIcon,- local: LaptopIcon,- none: MonitorOffIcon,- sandbox: CloudIcon,-};--interface ProjectRunTargetChipProps {- agentId: string;- /** Icon only, the target in the tooltip — for a narrow composer. */- compact?: boolean;- disabled?: boolean;-}--/**- * Where the picked agent's new conversation runs, resolved the way the run- * resolves it. The cloud sandbox is where a project's repository is checked- * out, so an agent that runs anywhere else is offered the switch here; a device- * pick stays with the conversation's own device picker.- */-const ProjectRunTargetChip = ({ agentId, compact, disabled }: ProjectRunTargetChipProps) => {- const { t } = useTranslation('project');- const { t: tChat } = useTranslation('chat');- const { agencyConfig, canDisplayExecutionTarget, canSelectExecutionTarget, workspaceScoped } =- useEffectiveAgencyConfig(agentId, { topicId: null });- const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);- const selectExecutionTarget = useSelectExecutionTarget(agentId);-- if (!canDisplayExecutionTarget) return null;-- const target = resolveExecutionTarget(agencyConfig, {- clientExecutionAvailable: isDesktop,- deviceRoutingAvailable,- isHetero: !!agencyConfig?.heterogeneousProvider?.type,- workspaceScoped,- });- const onSandbox = target === 'sandbox';- // A device-only heterogeneous provider (Amp, Cursor, OpenCode, Pi, …) has no- // sandbox toolchain: `resolveExecutionTarget` coerces a stored `sandbox`- // target back to `none`, so offering the switch would only strip the agent's- // runnable device target. Mirrors `HeteroDeviceSwitcher`'s `supportsSandbox`.- const sandboxAvailable = isHeterogeneousSandboxExecutionAvailable(- agencyConfig?.heterogeneousProvider?.type,- );- const switchable = !onSandbox && sandboxAvailable && canSelectExecutionTarget && !disabled;-- const switchToSandbox = async () => {- if (!(await selectExecutionTarget('sandbox')))- toast.error(t('overview.context.target.switchFailed'));- };-- const label =- target === 'device'- ? t('overview.context.target.device')- : tChat(`heteroAgent.executionTarget.${target}`);-- const chip = (- <button- aria-label={label}- data-testid={'project-run-target-chip'}- disabled={!switchable}- type={'button'}- {...stylex.props(- workingDirectoryChipStyles.chip,- styles.button,- !switchable && styles.static,- target === 'none' && styles.warning,- )}- >- <Icon icon={TARGET_ICONS[target]} size={14} />- {!compact && <span {...stylex.props(workingDirectoryChipStyles.label)}>{label}</span>}- {switchable && <Icon icon={ChevronDownIcon} size={12} />}- </button>- );-- const hint = onSandbox- ? t('overview.context.target.sandboxTooltip')- : target === 'none'- ? t('overview.context.target.noneTooltip')- : undefined;- const tooltip = compact ? [label, hint].filter(Boolean).join(' · ') : hint;-- if (!switchable)- return (- <Tooltip title={tooltip}>- <div>{chip}</div>- </Tooltip>- );-- const items: DropdownItem[] = [- {- icon: <Icon icon={CloudIcon} />,- key: 'sandbox',- label: t('overview.context.target.useSandbox'),- onClick: () => void switchToSandbox(),- },- ];-- return (- <Tooltip title={tooltip}>- <div>- <DropdownMenu items={items} placement={'bottomRight'}>- {chip}- </DropdownMenu>- </div>- </Tooltip>- );-};--const styles = stylex.create({- // Body size and color: the tray says where the work happens, not a footnote.- button: {- borderWidth: 0,- fontFamily: 'inherit',- fontSize: '13px',- color: cssVar.colorText,- backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillSecondary },- },- /** Shown, not picked: no hover, since nothing opens. */- static: {- cursor: 'default',- backgroundColor: { 'default': 'transparent', ':hover': 'transparent' },- },- warning: {- color: cssVar.colorWarning,- },-});--export default ProjectRunTargetChip;diff --git a/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsxnew file mode 100644index 00000000000..6dc4749e1d6--- /dev/null+++ b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx@@ -0,0 +1,422 @@+'use client';++import type { DeviceExecutionTarget } from '@lobechat/types';+import { Flexbox, Icon, Popover, Text, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDownIcon, FolderIcon, PlusIcon } from 'lucide-react';+import { type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import RepositoryAvatar from '@/components/RepositoryAvatar';+import OptionRow from '@/features/ChatInput/ControlBar/OptionRow';+import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';+import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';+import { ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';++import { openAddEnvironmentModal } from '../AddEnvironmentModal';+import { environmentRepositoryUrl } from '../environmentSource';+import { openAddDirectoryModal } from '../WorkingDirectories/AddDirectoryModal';+import { addedFolderTarget, type useProjectDirectory } from './useProjectDirectory';+import type { useProjectRepository } from './useProjectRepository';+import type { useProjectWorkLocation } from './useProjectWorkLocation';++/**+ * A submenu's list can arrive after it opens; sized to itself, its positioner+ * would keep the size it was first measured at.+ */+const SUBMENU_STYLES = {+ content: { padding: 4 },+ root: { height: 'auto', width: 'auto' },+};++const styles = stylex.create({+ // Body size and color: the tray says where the work happens, not a footnote.+ button: {+ borderWidth: 0,+ fontFamily: 'inherit',+ fontSize: '13px',+ color: cssVar.colorText,+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillSecondary },+ },+ /** Shown, not picked: no hover, since nothing opens. */+ static: {+ cursor: 'default',+ backgroundColor: { 'default': 'transparent', ':hover': 'transparent' },+ },+ warning: {+ color: cssVar.colorWarning,+ },+ header: {+ paddingBlock: '4px',+ paddingInline: '8px',+ fontSize: '12px',+ fontWeight: 500,+ color: cssVar.colorTextTertiary,+ },+ hint: {+ paddingInline: '8px',+ fontSize: '12px',+ color: cssVar.colorTextDescription,+ },+ list: {+ overflowY: 'auto',+ maxHeight: '280px',+ },+});++interface ProjectWorkLocationPickerProps {+ /** Whether this member may give the project another environment. */+ canManage: boolean;+ /** Icon only, the place in the tooltip — for a narrow composer. */+ compact?: boolean;+ /** The project folder a run on a device starts in. */+ directoryState: ReturnType<typeof useProjectDirectory>;+ disabled?: boolean;+ /** Where the agent runs and where it can be moved to. */+ location: ReturnType<typeof useProjectWorkLocation>;+ projectId: string;+ /** Environments added here are published: the agent is workspace-public and applies nothing else. */+ publish?: boolean;+ /** A task starts no conversation, so it has no code environment or folder to pick. */+ showRepositories?: boolean;+ state: ReturnType<typeof useProjectRepository>;+}++/**+ * Where a new project conversation works, in one place: the cloud sandbox —+ * in which of the project's code environments — or one of the agent's devices.+ * The target is the agent's, written the way the conversation's own device+ * picker writes it; the code environment is this conversation's.+ */+const ProjectWorkLocationPicker = ({+ canManage,+ compact,+ directoryState,+ disabled,+ location,+ projectId,+ publish,+ showRepositories = true,+ state,+}: ProjectWorkLocationPickerProps) => {+ const { t } = useTranslation('project');+ const { t: tChat } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const {+ boundDevice,+ deviceRows,+ displayed,+ localAvailable,+ currentDeviceId,+ sandboxAvailable,+ select: moveTo,+ switchable,+ target,+ } = location;+ const onSandbox = target === 'sandbox';++ const { repositories, repository, setPickedId } = state;+ const repositoryShown = showRepositories && onSandbox && !!repository;++ const select = async (next: DeviceExecutionTarget, deviceId?: string) => {+ setOpen(false);+ if (!(await moveTo(next, deviceId))) toast.error(t('overview.context.target.switchFailed'));+ };++ const pickRepository = (environmentId: string) => {+ setPickedId(environmentId);+ if (!onSandbox) void select('sandbox');+ else setOpen(false);+ };++ const { directory, directoriesOn, setPickedId: setDirectoryId } = directoryState;+ const directoryShown = showRepositories && !onSandbox && !!directory;++ /** A folder belongs to one machine; picking it moves the run there too. */+ const pickDirectory = (directoryId: string, next: 'device' | 'local', deviceId?: string) => {+ setDirectoryId(directoryId);+ void select(next, deviceId);+ };++ const addDirectory = (next: 'device' | 'local', deviceId?: string) => {+ setOpen(false);+ openAddDirectoryModal(projectId, undefined, {+ deviceId: next === 'local' ? currentDeviceId : deviceId,+ // Follow the folder to the machine it was saved on, which the dialog lets+ // the person change: this desktop runs it locally, any other as a device.+ onAdded: (added) => {+ const place = addedFolderTarget(added, next, currentDeviceId);+ pickDirectory(added.id, place.target, place.deviceId);+ },+ });+ };++ const addEnvironment = () => {+ setOpen(false);+ openAddEnvironmentModal({ onAdded: pickRepository, projectId, publish });+ };++ // What the chip says: the code environment when the run checks one out,+ // otherwise the place itself.+ let chipIcon: ReactNode = <ExecutionTargetIcon target={target} />;+ let chipLabel: string =+ target === 'device'+ ? (boundDevice?.friendlyName ?? boundDevice?.hostname ?? t('overview.context.target.device'))+ : tChat(`heteroAgent.executionTarget.${target}`);+ if (repositoryShown) {+ const slug = repositorySlug(repository) ?? repository.name;+ chipIcon = <RepositoryAvatar size={16} url={environmentRepositoryUrl(repository)} />;+ chipLabel = slug.split('/').pop() || repository.name;+ } else if (target === 'device') {+ chipIcon = <ExecutionTargetIcon devicePlatform={boundDevice?.platform} target={'device'} />;+ }+ // On a machine, the folder is what the conversation works in.+ const machineLabel = chipLabel;+ if (directoryShown) chipLabel = directory.name;++ const hint = onSandbox+ ? repositoryShown+ ? `${repositorySlug(repository) ?? repository.name} · ${tChat('heteroAgent.executionTarget.sandbox')}`+ : t('overview.context.target.sandboxTooltip')+ : target === 'none'+ ? t('overview.context.target.noneTooltip')+ : directoryShown+ ? `${directory.path} · ${machineLabel}`+ : showRepositories && (target === 'device' || target === 'local')+ ? t('overview.context.location.noDirectoryTooltip')+ : undefined;+ const tooltip = compact ? [chipLabel, hint].filter(Boolean).join(' · ') : hint;++ // Nothing to pick: a read-only target with no code environment to choose.+ // A fixed target still leaves the folder on its machine to choose.+ const machineFolders = directoriesOn(location.machineDeviceId ?? '');+ const interactive =+ !disabled &&+ (switchable ||+ (showRepositories && onSandbox && (repositories.length > 1 || canManage)) ||+ (showRepositories &&+ !onSandbox &&+ !!location.machineDeviceId &&+ (machineFolders.length > 1 || canManage)));++ const repositoryMenu = (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 260 }}>+ <div {...stylex.props(styles.header)}>{t('overview.context.location.environments')}</div>+ <div {...stylex.props(styles.list)}>+ {repositories.map((environment) => (+ <OptionRow+ compact+ icon={<RepositoryAvatar size={16} url={environmentRepositoryUrl(environment)} />}+ key={environment.id}+ label={environment.name}+ onClick={() => pickRepository(environment.id)}+ active={onSandbox && environment.id === repository?.id}+ // A name that already is the slug needs no second copy of it.+ hint={+ repositorySlug(environment) === environment.name+ ? undefined+ : repositorySlug(environment)+ }+ />+ ))}+ </div>+ {repositories.length === 0 && (+ <Text className={stylex.props(styles.hint).className}>+ {t('overview.context.location.noEnvironments')}+ </Text>+ )}+ {canManage && (+ <OptionRow+ compact+ icon={<Icon icon={PlusIcon} size={16} />}+ label={t('environment.add.title')}+ onClick={addEnvironment}+ />+ )}+ </Flexbox>+ );++ /** One machine's folders: the second level of its row. */+ const directoryMenu = (next: 'device' | 'local', deviceId?: string) => {+ const folders = directoriesOn((next === 'local' ? currentDeviceId : deviceId) ?? '');+ const onThisMachine =+ next === 'local'+ ? target === 'local'+ : target === 'device' && deviceId === boundDevice?.deviceId;+ return (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 260 }}>+ <div {...stylex.props(styles.header)}>{t('overview.context.location.directories')}</div>+ <div {...stylex.props(styles.list)}>+ {folders.map((folder) => (+ <OptionRow+ compact+ active={onThisMachine && folder.id === directory?.id}+ // A path is long: on its own line, so the folder's name stays whole.+ desc={folder.path}+ icon={<Icon icon={FolderIcon} size={16} />}+ key={folder.id}+ label={folder.name}+ onClick={() => pickDirectory(folder.id, next, deviceId)}+ />+ ))}+ </div>+ {folders.length === 0 && (+ <Text className={stylex.props(styles.hint).className}>+ {t('overview.context.location.noDirectories')}+ </Text>+ )}+ {canManage && (+ <OptionRow+ compact+ icon={<Icon icon={PlusIcon} size={16} />}+ label={t('settings.addDirectory')}+ onClick={() => addDirectory(next, deviceId)}+ />+ )}+ </Flexbox>+ );+ };++ /** A machine row opens its folders one level down, as the sandbox opens its repositories. */+ const machineRow = (row: ReactNode, next: 'device' | 'local', deviceId?: string) =>+ showRepositories ? (+ <Popover+ arrow={false}+ closeDelay={150}+ content={directoryMenu(next, deviceId)}+ key={deviceId ?? next}+ placement={'leftTop'}+ styles={SUBMENU_STYLES}+ trigger={['hover', 'click']}+ >+ <div data-testid={`project-location-machine-${deviceId ?? next}`}>{row}</div>+ </Popover>+ ) : (+ row+ );++ const sandboxRow = (+ <OptionRow+ active={onSandbox}+ arrow={showRepositories}+ desc={tChat('heteroAgent.executionTarget.sandboxDesc')}+ disabled={!switchable && !onSandbox}+ icon={<ExecutionTargetIcon target={'sandbox'} />}+ label={tChat('heteroAgent.executionTarget.sandbox')}+ onClick={() => {+ if (switchable) void select('sandbox');+ }}+ />+ );++ const content = (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>+ <div {...stylex.props(styles.header)}>{t('overview.context.location.title')}</div>+ {(sandboxAvailable || onSandbox) &&+ (showRepositories ? (+ <Popover+ arrow={false}+ closeDelay={150}+ content={repositoryMenu}+ // The chip sits at the composer's right edge, so the second level+ // opens inward rather than off the side of the window.+ placement={'leftTop'}+ styles={SUBMENU_STYLES}+ trigger={['hover', 'click']}+ >+ <div data-testid={'project-location-sandbox'}>{sandboxRow}</div>+ </Popover>+ ) : (+ sandboxRow+ ))}+ {(localAvailable || deviceRows.length > 0) && (+ <>+ <div {...stylex.props(styles.header)}>{t('overview.context.location.devices')}</div>+ {localAvailable &&+ machineRow(+ <OptionRow+ active={target === 'local'}+ arrow={showRepositories}+ desc={tChat('heteroAgent.executionTarget.localDesc')}+ icon={<ExecutionTargetIcon target={'local'} />}+ label={tChat('heteroAgent.executionTarget.local')}+ onClick={() => void select('local')}+ />,+ 'local',+ )}+ <div {...stylex.props(styles.list)}>+ {deviceRows.map((device) =>+ machineRow(+ <OptionRow+ active={target === 'device' && device.deviceId === boundDevice?.deviceId}+ arrow={showRepositories}+ icon={<ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />}+ label={device.friendlyName || device.hostname || device.deviceId}+ desc={tChat(+ device.online+ ? 'heteroAgent.executionTarget.online'+ : 'heteroAgent.executionTarget.offline',+ )}+ onClick={() => void select('device', device.deviceId)}+ />,+ 'device',+ device.deviceId,+ ),+ )}+ </div>+ </>+ )}+ </Flexbox>+ );++ if (!displayed && !repositoryShown) return null;++ const chip = (+ <button+ aria-label={chipLabel}+ data-testid={'project-location-chip'}+ disabled={!interactive}+ type={'button'}+ {...stylex.props(+ workingDirectoryChipStyles.chip,+ styles.button,+ !interactive && styles.static,+ target === 'none' && styles.warning,+ )}+ >+ {chipIcon}+ {!compact && <span {...stylex.props(workingDirectoryChipStyles.label)}>{chipLabel}</span>}+ {interactive && <Icon icon={ChevronDownIcon} size={12} />}+ </button>+ );++ if (!interactive)+ return (+ <Tooltip title={tooltip}>+ <div>{chip}</div>+ </Tooltip>+ );++ // A plain div between the popover and the chip: the popover merges trigger+ // props into its direct child.+ return (+ <Popover+ arrow={false}+ content={content}+ open={open}+ placement={'bottomRight'}+ styles={{ content: { padding: 4 } }}+ trigger={'click'}+ onOpenChange={setOpen}+ >+ <div>+ <Tooltip title={open ? undefined : tooltip}>+ <div>{chip}</div>+ </Tooltip>+ </div>+ </Popover>+ );+};++export default ProjectWorkLocationPicker;diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.tsindex b1b26de5c56..00ac22bc9ef 100644--- a/src/features/Projects/Workspace/useProjectComposer.test.ts+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts@@ -9,6 +9,7 @@ import type { ProjectDetail } from '@/store/project';import {AttachmentsNotReadyError,+ DirectoryUnavailableError,toConversationTitle,useProjectComposer,} from './useProjectComposer';@@ -17,6 +18,7 @@ const mocks = vi.hoisted(() => ({agentMap: {} as Record<string, unknown>,clearChatUploadFileList: vi.fn(),createProjectTopic: vi.fn(),+ startTopic: vi.fn(),createTask: vi.fn(),fileList: [] as unknown[],getAgentConfigById: vi.fn(),@@ -51,6 +53,7 @@ vi.mock('@/store/projectWorkingDirectory', () => ({useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>selector({createProjectTopic: mocks.createProjectTopic,+ startTopic: mocks.startTopic,}),}));@@ -206,7 +209,7 @@ describe('useProjectComposer', () => {it('starts the conversation in the repository picked in the context bar', async () => {mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });const { result } = renderHook(() =>- useProjectComposer(project, 'chat', 'coordinator', 'env-repo'),+ useProjectComposer(project, 'chat', 'coordinator', { environmentId: 'env-repo' }),);await act(async () => {@@ -218,6 +221,40 @@ describe('useProjectComposer', () => {);});+ // On a device the conversation is bound to the project folder picked there,+ // not to the device's default directory.+ it('starts the conversation in the project folder picked on a device', async () => {+ mocks.startTopic.mockResolvedValue({ id: 'tpc_dir' });+ const { result } = renderHook(() =>+ useProjectComposer(project, 'chat', 'coordinator', { directoryId: 'dir_mail' }),+ );++ await act(async () => {+ await result.current.send(composer('Run the tests'));+ });++ expect(mocks.startTopic).toHaveBeenCalledWith('dir_mail', 'coordinator', 'Run the tests');+ expect(mocks.createProjectTopic).not.toHaveBeenCalled();+ expect(mocks.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ context: { agentId: 'coordinator', topicId: 'tpc_dir' } }),+ );+ });++ it('keeps the draft and says why when the picked folder cannot be reached', async () => {+ mocks.startTopic.mockRejectedValue(new Error('Device is offline'));+ const send = composer('Run the tests');+ const { result } = renderHook(() =>+ useProjectComposer(project, 'chat', 'coordinator', { directoryId: 'dir_mail' }),+ );++ await act(async () => {+ await expect(result.current.send(send)).rejects.toBeInstanceOf(DirectoryUnavailableError);+ });++ expect(send.clearContent).not.toHaveBeenCalled();+ expect(mocks.sendMessage).not.toHaveBeenCalled();+ });+it('assigns a task to the picked project agent', async () => {mocks.createTask.mockResolvedValue({ id: 'task_1', identifier: 'T-1', name: 'Ship it' });const { result } = renderHook(() => useProjectComposer(project, 'task', 'reviewer'));diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.tsindex ffd8e3e58b3..7908bb98399 100644--- a/src/features/Projects/Workspace/useProjectComposer.ts+++ b/src/features/Projects/Workspace/useProjectComposer.ts@@ -97,6 +97,14 @@ const isAbort = (error: unknown) =>/** The project home composer's key for its draft attachments and context selections. */export const getProjectComposerContextKey = (projectId: string) => `project-home:${projectId}`;+/** The picked folder could not be reached: its device is offline, or the folder is gone. */+export class DirectoryUnavailableError extends Error {+ constructor(cause: unknown) {+ super('The project folder is not reachable', { cause });+ this.name = 'DirectoryUnavailableError';+ }+}+export class AttachmentsNotReadyError extends Error {constructor() {super('Attachments are still uploading');@@ -109,13 +117,18 @@ export const useProjectComposer = (mode: ProjectComposerMode,/** The project agent the message goes to; the main agent unless the user picked another. */agentId: string,- /** The project repository the conversation works in; the server picks the first when unset. */- environmentId?: string,+ /**+ * Where the conversation works: a project repository in the cloud sandbox+ * (the server picks the first when unset), or a project folder on a device.+ */+ place: { directoryId?: string; environmentId?: string } = {},) => {+ const { directoryId, environmentId } = place;const { t } = useTranslation('project');const navigate = useWorkspaceAwareNavigate();const workspaceSlug = useActiveWorkspaceSlug();const createProjectTopic = useProjectDirectoryStore((s) => s.createProjectTopic);+ const startDirectoryTopic = useProjectDirectoryStore((s) => s.startTopic);const createTask = useTaskStore((s) => s.createTask);const sendMessage = useChatStore((s) => s.sendMessage);const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);@@ -156,8 +169,16 @@ export const useProjectComposer = (// owns it from the start, and the message is sent into that exact topic.// Sending here rather than after the page loads keeps the attachments,// which cannot travel through the URL.+ //+ // A folder on a device is checked first — the device must be online and+ // the folder still there — so a conversation never starts somewhere the+ // person did not pick.const [topic] = await Promise.all([- createProjectTopic({ agentId, environmentId, projectId: project.id, title }),+ directoryId+ ? startDirectoryTopic(directoryId, agentId, title).catch((error: unknown) => {+ throw new DirectoryUnavailableError(error);+ })+ : createProjectTopic({ agentId, environmentId, projectId: project.id, title }),ensureAgentConfigLoaded(agentId),]);// Open the conversation right away: the send shows its message therediff --git a/src/features/Projects/Workspace/useProjectDirectory.test.ts b/src/features/Projects/Workspace/useProjectDirectory.test.tsnew file mode 100644index 00000000000..533dcc5c9a0--- /dev/null+++ b/src/features/Projects/Workspace/useProjectDirectory.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import type { ProjectDirectory } from '@/store/projectWorkingDirectory';++import { addedFolderTarget, directoriesOnDevice } from './useProjectDirectory';++const directory = (id: string, deviceId: string, extra: Partial<ProjectDirectory> = {}) =>+ ({+ deviceId,+ id,+ instanceId: `inst-${id}`,+ name: id,+ path: `/work/${id}`,+ permission: 'readWrite',+ ...extra,+ }) as ProjectDirectory;++describe('directoriesOnDevice', () => {+ const all = [+ directory('mail', 'studio'),+ directory('tts', 'studio'),+ directory('other', 'laptop'),+ directory('unlinked', 'studio', { instanceId: null }),+ directory('readonly', 'studio', { permission: 'read' } as Partial<ProjectDirectory>),+ ];++ it("offers the project's runnable folders on that machine only", () => {+ expect(directoriesOnDevice(all, 'studio').map((item) => item.id)).toEqual(['mail', 'tts']);+ });++ it('offers nothing without a machine, as on the cloud sandbox', () => {+ expect(directoriesOnDevice(all, undefined)).toEqual([]);+ });+});++describe('addedFolderTarget', () => {+ // Opened from device A's row, saved on device B: the run follows the folder.+ it('moves the run to the device the folder was saved on, not the row it came from', () => {+ expect(addedFolderTarget({ deviceId: 'laptop' }, 'device', 'desktop')).toEqual({+ deviceId: 'laptop',+ target: 'device',+ });+ });++ it('keeps a folder on this desktop local when added from the local row', () => {+ expect(addedFolderTarget({ deviceId: 'desktop' }, 'local', 'desktop')).toEqual({+ target: 'local',+ });+ });++ it('treats a folder moved to another machine from the local row as a device run', () => {+ expect(addedFolderTarget({ deviceId: 'studio' }, 'local', 'desktop')).toEqual({+ deviceId: 'studio',+ target: 'device',+ });+ });+});diff --git a/src/features/Projects/Workspace/useProjectDirectory.ts b/src/features/Projects/Workspace/useProjectDirectory.tsnew file mode 100644index 00000000000..ee0984295eb--- /dev/null+++ b/src/features/Projects/Workspace/useProjectDirectory.ts@@ -0,0 +1,57 @@+import { useState } from 'react';++import {+ type ProjectDirectory,+ useProjectDirectories,+ useProjectDirectoryStore,+} from '@/store/projectWorkingDirectory';++/**+ * The project's folders a run on `deviceId` can work in: on that machine,+ * linked to an environment and writable — the same rule a conversation's own+ * device picker applies.+ */+export const directoriesOnDevice = (directories: ProjectDirectory[], deviceId?: string) =>+ deviceId+ ? directories.filter(+ (directory) =>+ directory.deviceId === deviceId &&+ !!directory.instanceId &&+ directory.permission === 'readWrite',+ )+ : [];++/**+ * Where a run goes for a folder just added from a machine's row. The dialog+ * lets the person change the device, so the folder's own device decides, not+ * the row it was opened from: this desktop runs it locally when added from the+ * local row, any other machine as a device.+ */+export const addedFolderTarget = (+ added: { deviceId: string },+ from: 'device' | 'local',+ currentDeviceId?: string,+): { deviceId?: string; target: 'device' | 'local' } =>+ from === 'local' && added.deviceId === currentDeviceId+ ? { target: 'local' }+ : { deviceId: added.deviceId, target: 'device' };++/**+ * The project folder a new conversation on a device starts in: the person's+ * pick while it is still on that device, otherwise the device's first one.+ * Without one the run works wherever the device starts it.+ */+export const useProjectDirectory = (projectId: string, deviceId?: string) => {+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);+ const all = useProjectDirectories(projectId);+ const [pickedId, setPickedId] = useState<string>();+ const onDevice = directoriesOnDevice(all, deviceId);+ const directory = onDevice.find((item) => item.id === pickedId) ?? onDevice[0];++ return {+ directory,+ /** Every usable folder of the project on another machine, for that machine's row. */+ directoriesOn: (id: string) => directoriesOnDevice(all, id),+ setPickedId,+ };+};diff --git a/src/features/Projects/Workspace/useProjectWorkLocation.test.ts b/src/features/Projects/Workspace/useProjectWorkLocation.test.tsnew file mode 100644index 00000000000..cac124cd9e2--- /dev/null+++ b/src/features/Projects/Workspace/useProjectWorkLocation.test.ts@@ -0,0 +1,121 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useProjectWorkLocation } from './useProjectWorkLocation';++const mocks = vi.hoisted(() => ({+ agency: {+ agencyConfig: undefined as+ | {+ boundDeviceId?: string;+ executionTarget?: string;+ heterogeneousProvider?: { type: string };+ }+ | undefined,+ canDisplayExecutionTarget: true,+ canSelectExecutionTarget: true,+ workspaceScoped: false,+ },+ selectExecutionTarget: vi.fn(),+}));++vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => mocks.agency,+}));++vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => true }));++vi.mock('@/features/ChatInput/hooks/useSelectExecutionTarget', () => ({+ useSelectExecutionTarget: () => mocks.selectExecutionTarget,+}));++vi.mock('@/store/device', () => ({+ useDeviceList: () => ({+ data: [+ { deviceId: 'device_1', friendlyName: 'Studio Mac', online: true, scope: 'personal' },+ { deviceId: 'device_2', friendlyName: 'Build box', online: false, scope: 'personal' },+ ],+ }),+}));++const render = () => renderHook(() => useProjectWorkLocation('agent_1')).result.current;++beforeEach(() => {+ mocks.agency.agencyConfig = { executionTarget: 'sandbox' };+ mocks.agency.canSelectExecutionTarget = true;+ mocks.selectExecutionTarget.mockReset();+ mocks.selectExecutionTarget.mockResolvedValue(true);+});++describe('useProjectWorkLocation', () => {+ it('moves a cloud-sandbox agent to one of its devices', async () => {+ const location = render();++ expect(location.target).toBe('sandbox');+ expect(location.deviceRows.map((device) => device.deviceId)).toEqual(['device_1', 'device_2']);++ expect(location.machineDeviceId).toBeUndefined();++ await expect(location.select('device', 'device_1')).resolves.toBe(true);+ expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('device', 'device_1', undefined);+ });++ it('moves a device agent back to the cloud sandbox', async () => {+ mocks.agency.agencyConfig = { boundDeviceId: 'device_1', executionTarget: 'device' };+ const location = render();++ expect(location.boundDevice?.friendlyName).toBe('Studio Mac');+ // The machine whose project folders the conversation can start in.+ expect(location.machineDeviceId).toBe('device_1');++ await location.select('sandbox');+ expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('sandbox', undefined, undefined);+ });++ it('moves between devices but writes nothing for the current one', async () => {+ mocks.agency.agencyConfig = { boundDeviceId: 'device_1', executionTarget: 'device' };+ const location = render();++ await location.select('device', 'device_1');+ expect(mocks.selectExecutionTarget).not.toHaveBeenCalled();++ await location.select('device', 'device_2');+ expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('device', 'device_2', undefined);+ });++ it('reports a move that was not saved', async () => {+ mocks.selectExecutionTarget.mockResolvedValue(false);++ await expect(render().select('device', 'device_1')).resolves.toBe(false);+ });++ it('does not offer the cloud sandbox to a device-only provider', () => {+ mocks.agency.agencyConfig = {+ boundDeviceId: 'device_1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'amp' },+ };++ expect(render().sandboxAvailable).toBe(false);+ });++ // A fixed device still has project folders to choose between.+ it('keeps the fixed device listed so its folders stay a choice', () => {+ mocks.agency.canSelectExecutionTarget = false;+ mocks.agency.agencyConfig = { boundDeviceId: 'device_1', executionTarget: 'device' };+ const location = render();++ expect(location.switchable).toBe(false);+ expect(location.deviceRows.map((device) => device.deviceId)).toEqual(['device_1']);+ expect(location.machineDeviceId).toBe('device_1');+ });++ it('offers no other place when the target is fixed', () => {+ mocks.agency.canSelectExecutionTarget = false;+ const location = render();++ expect(location.switchable).toBe(false);+ expect(location.deviceRows).toEqual([]);+ expect(location.localAvailable).toBe(false);+ });+});diff --git a/src/features/Projects/Workspace/useProjectWorkLocation.ts b/src/features/Projects/Workspace/useProjectWorkLocation.tsnew file mode 100644index 00000000000..b2ba4df9a79--- /dev/null+++ b/src/features/Projects/Workspace/useProjectWorkLocation.ts@@ -0,0 +1,91 @@+'use client';++import { isDesktop } from '@lobechat/const';+import type { DeviceExecutionTarget } from '@lobechat/types';++import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';+import { devicePoolForAgent } from '@/features/ExecutionTargetPicker';+import {+ isHeterogeneousSandboxExecutionAvailable,+ resolveExecutionTarget,+} from '@/helpers/executionTarget';+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useAgentStore } from '@/store/agent';+import { useDeviceList } from '@/store/device';+import { useElectronStore } from '@/store/electron';++/**+ * Where the picked agent's new conversation runs, resolved the way the run+ * resolves it, and the places it can be moved to: the cloud sandbox and the+ * devices the agent's runs can reach. Written the way the conversation's own+ * device picker writes it, so the two never disagree.+ */+export const useProjectWorkLocation = (agentId: string) => {+ const { agencyConfig, canDisplayExecutionTarget, canSelectExecutionTarget, workspaceScoped } =+ useEffectiveAgencyConfig(agentId, { topicId: null });+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);+ const selectExecutionTarget = useSelectExecutionTarget(agentId);+ const isWorkspaceAgent = useAgentStore((s) => Boolean(s.agentMap[agentId]?.workspaceId));+ const { data: devices } = useDeviceList();++ const heteroType = agencyConfig?.heterogeneousProvider?.type;+ const target = resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ deviceRoutingAvailable,+ isHetero: !!heteroType,+ workspaceScoped,+ });+ const boundDevice = devices?.find((device) => device.deviceId === agencyConfig?.boundDeviceId);+ // This desktop's own gateway id, which a `local` run works on.+ const currentDeviceId = useElectronStore((s) =>+ isDesktop ? s.gatewayDeviceInfo?.deviceId : undefined,+ );+ const switchable = canDisplayExecutionTarget && canSelectExecutionTarget;++ /** Resolves `false` when the move was refused or failed; picking the current place is a no-op. */+ const select = async (next: DeviceExecutionTarget, deviceId?: string) => {+ if (next === target && (next !== 'device' || deviceId === boundDevice?.deviceId)) return true;+ // The plain local row clears the local fence, as the conversation picker's does.+ const options = next === 'local' ? { localSandbox: false } : undefined;+ return selectExecutionTarget(next, deviceId, options);+ };++ return {+ boundDevice,+ /** This desktop's gateway id, on desktop only. */+ currentDeviceId,+ /** Whether the place is shown at all; a member without access sees nothing. */+ displayed: canDisplayExecutionTarget,+ /**+ * The machines offered. A fixed target still lists the machine the run is+ * on: its project folders stay a choice even though the machine is not.+ */+ deviceRows: switchable+ ? deviceRoutingAvailable+ ? devicePoolForAgent(devices, isWorkspaceAgent)+ : []+ : target === 'device' && boundDevice+ ? [boundDevice]+ : [],+ /** This desktop, as a place of its own — or as the fixed place the run already is. */+ localAvailable: (switchable && isDesktop) || target === 'local',+ /**+ * A device-only heterogeneous provider (Amp, Cursor, OpenCode, Pi, …) has+ * no sandbox toolchain: `resolveExecutionTarget` would coerce a stored+ * `sandbox` back to `none`, stripping the agent's runnable device target.+ */+ sandboxAvailable: isHeterogeneousSandboxExecutionAvailable(heteroType),+ select,+ /** A fixed workspace target, or a member who may not change it, keeps the place as it is. */+ switchable,+ target,+ /** The machine a device or local run works on; none for the sandbox. */+ machineDeviceId:+ target === 'device'+ ? agencyConfig?.boundDeviceId+ : target === 'local'+ ? (currentDeviceId ?? agencyConfig?.boundDeviceId)+ : undefined,+ };+};diff --git a/src/features/Projects/environmentSource.test.ts b/src/features/Projects/environmentSource.test.tsnew file mode 100644index 00000000000..22c01bec481--- /dev/null+++ b/src/features/Projects/environmentSource.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { environmentRepositoryUrl, reusableEnvironments } from './environmentSource';++const environment = (id: string, visibility: 'private' | 'public', url?: string) => ({+ configuration: { sources: url ? [{ kind: 'git' as const, url }] : [] },+ id,+ visibility,+});++describe('environmentRepositoryUrl', () => {+ it('reads the repository an environment checks out', () => {+ expect(+ environmentRepositoryUrl(+ environment('env_1', 'private', 'https://github.com/lobehub/lobehub'),+ ),+ ).toBe('https://github.com/lobehub/lobehub');+ });++ it('has nothing for an environment without a repository', () => {+ expect(environmentRepositoryUrl(environment('env_1', 'private'))).toBeUndefined();+ expect(environmentRepositoryUrl({ configuration: null, id: 'env_2' })).toBeUndefined();+ });+});++describe('reusableEnvironments', () => {+ const available = [+ environment('env_linked', 'public'),+ environment('env_private', 'private'),+ environment('env_public', 'public'),+ ];+ const linked = [{ id: 'env_linked' }];++ it('offers the environments not in the project yet', () => {+ expect(reusableEnvironments(available, linked).map((item) => item.id)).toEqual([+ 'env_private',+ 'env_public',+ ]);+ });++ it('offers only published environments to a shared project', () => {+ expect(reusableEnvironments(available, linked, true).map((item) => item.id)).toEqual([+ 'env_public',+ ]);+ });+});diff --git a/src/features/Projects/environmentSource.ts b/src/features/Projects/environmentSource.tsnew file mode 100644index 00000000000..5a44ce9ae32--- /dev/null+++ b/src/features/Projects/environmentSource.ts@@ -0,0 +1,29 @@+import type { EnvironmentConfiguration } from '@lobechat/types';++interface EnvironmentLike {+ configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;+ id: string;+ visibility?: string | null;+}++/** The repository an environment checks out, when it names one. */+export const environmentRepositoryUrl = (environment: EnvironmentLike): string | undefined => {+ const source = environment.configuration?.sources?.find((item) => item.kind === 'git');+ return source?.kind === 'git' ? source.url : undefined;+};++/**+ * The environments that can still be added to a project: not linked yet, and —+ * for a project whose conversations run a workspace-public agent — published,+ * since that agent applies nothing else.+ */+export const reusableEnvironments = <T extends EnvironmentLike>(+ available: T[],+ linked: { id: string }[],+ publish?: boolean,+): T[] =>+ available.filter(+ (environment) =>+ !linked.some((item) => item.id === environment.id) &&+ (!publish || environment.visibility === 'public'),+ );