Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧳 feat: Choose Agent-Allowed Machines For New Chats (#16651)

Danny Avila2eee568542b3
diff --git a/.github/workflows/workspace-acceptance.yml b/.github/workflows/workspace-acceptance.yml
index bd1c0a7aaf..9cac759e7d 100644
--- a/.github/workflows/workspace-acceptance.yml
+++ b/.github/workflows/workspace-acceptance.yml
@@ -17,7 +17,7 @@ concurrency:
jobs:
workspace:
- name: Saved chat attach and offline detach (macOS)
+ name: Machine choices and saved chat transitions (macOS)
runs-on: macos-latest
timeout-minutes: 25
env:
@@ -67,6 +67,15 @@ jobs:
npm run build --prefix .native-code/service
cp .native-code/service/src/matplotlib-async.py .native-code/service/.build-service/src/matplotlib-async.py
+ - name: Verify harness lifecycle and generation readiness
+ run: node --test e2e/byom/*.test.mjs
+
+ - name: Exercise agent machine choices and native worker isolation
+ env:
+ BYOM_WORKSPACE_TRANSITIONS: 'false'
+ BYOM_CODE_REPO: ${{ github.workspace }}/.native-code
+ run: node e2e/byom/run.mjs
+
- name: Exercise saved-chat workspace transitions
env:
BYOM_WORKSPACE_TRANSITIONS: 'true'
@@ -85,6 +94,6 @@ jobs:
echo '### Native workspace acceptance'
echo "Head: \`$HEAD\`"
echo "Result: $RESULT"
- echo 'Scope: saved chat, agent switch without implicit access, no-workspace send/reload, explicit attach, approved native command, offline detach, continued chat/reload.'
+ echo 'Scope: native approvals, physical worker isolation, one agent choosing allowed machines in new chats, restored choices, fixed default, stopped-worker failure; saved chat, agent switch without implicit access, no-workspace send/reload, explicit attach, offline detach, continued chat/reload.'
echo 'Worker: `67d75d859aee891923c40cde1db073489d74a424`. Platform: macOS Seatbelt. No Linux/WSL certification.'
} >> "$GITHUB_STEP_SUMMARY"
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index 0613f4df0d..a60becd413 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -28,6 +28,7 @@ const {
codeExecutionAuthHeaders,
getCodeFileLocation,
resolveCodeExecutionContext,
+ resolveCodeExecutionWorkspaceSelections,
resolveMCPClientCapabilityProfile,
} = require('@librechat/api');
const {
@@ -385,6 +386,14 @@ const loadTools = async ({
statefulSessions,
environment: agent?.stateful_code_environment,
environmentId: agent?.code_environment_id,
+ environmentIds: agent?.code_environment_ids,
+ allowEnvironmentSelection:
+ options.req?.config?.endpoints?.agents?.statefulCodeSessions
+ ?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: options.req?.resolvedConversation,
+ request: options.req?.body,
+ }),
environments:
options.req?.config?.endpoints?.agents?.statefulCodeSessions?.environments,
userId: user,
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js
index bfa486c102..3fe8db05f5 100644
--- a/api/server/controllers/agents/v1.js
+++ b/api/server/controllers/agents/v1.js
@@ -44,7 +44,8 @@ const {
reconcileAgentWorkspaceDefault,
resolveAgentWorkspaceRestoreConfiguration,
shouldValidateAgentWorkspaceDefaultBinding,
- validateAgentWorkspaceDefaultBinding,
+ validateStatefulCodeEnvironment,
+ validateAgentCodeEnvironmentAllowlist,
marketplaceMineFilter,
resolveMarketplaceListQuery,
mapMarketplaceListError,
@@ -65,7 +66,6 @@ const {
AgentCapabilities,
EModelEndpoint,
FileSources,
- resolveAllowedStatefulCodeEnvironments,
removeCodeExecutionCaller,
hasActivePiiFields,
hasActivePiiPatterns,
@@ -481,69 +481,6 @@ const isCodeInterpreterCapabilityEnabled = (req) => {
return capabilities.includes(AgentCapabilities.execute_code);
};
-/** Reject a newly selected stateful workspace scope that the deployment owner
- * has excluded. Disabled sessions and unrelated edits remain saveable so an
- * allowlist tightening never silently rewrites or strands an existing agent. */
-const validateStatefulCodeEnvironment = (
- req,
- res,
- enabled,
- environment,
- environmentId,
- environmentIdSelected = false,
- workspaceId,
- currentWorkspaceId,
- currentEnvironmentId,
-) => {
- const configuredEnvironments =
- req.config?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.environments ?? [];
- const workspaceValidation = validateAgentWorkspaceDefaultBinding({
- workspaceId,
- environmentId,
- currentWorkspaceId,
- currentEnvironmentId,
- environments: configuredEnvironments,
- });
- if (!workspaceValidation.valid) {
- res.status(400).json({ error: workspaceValidation.error });
- return false;
- }
- if (enabled !== true && !environmentIdSelected) {
- return true;
- }
- if (environmentId != null) {
- const configuredEnvironment = configuredEnvironments.find(
- (configured) => configured.id === environmentId,
- );
- const pairingOnly =
- configuredEnvironment?.pairing?.allowPrincipalWorkers === true &&
- configuredEnvironment.pairing.workerId == null &&
- configuredEnvironment.workerId == null;
- if (configuredEnvironment == null || pairingOnly) {
- res.status(400).json({
- error: `Stateful code environment is not configured: ${environmentId}`,
- });
- return false;
- }
- }
- if (enabled !== true) {
- return true;
- }
-
- const allowedEnvironments = resolveAllowedStatefulCodeEnvironments(
- req.config?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.allowedEnvironments,
- );
- const resolvedEnvironment = environment ?? 'user';
- if (allowedEnvironments.includes(resolvedEnvironment)) {
- return true;
- }
-
- res.status(403).json({
- error: `Stateful code environment is not allowed by this deployment: ${resolvedEnvironment}`,
- });
- return false;
-};
-
/**
* @param {import('librechat-data-provider').AgentSubagentsConfig | undefined} subagents
* @param {Express.Request} req
@@ -806,6 +743,9 @@ const createAgentHandler = async (req, res) => {
agentData.code_environment_id,
agentData.code_environment_id != null,
agentData.code_workspace_id,
+ undefined,
+ undefined,
+ agentData.code_environment_ids,
)
) {
return;
@@ -1084,6 +1024,9 @@ const updateAgentHandler = async (req, res) => {
/** See the create path: retain hydrated file IDs through validation. */
normalizeToolResourceFiles(req.body?.tool_resources);
const validatedData = agentUpdateSchema.parse(req.body);
+ if (!validateAgentCodeEnvironmentAllowlist(req, res, validatedData.code_environment_ids)) {
+ return;
+ }
// Preserve explicit null for avatar to allow resetting the avatar
const {
avatar: avatarField,
@@ -1470,6 +1413,9 @@ const duplicateAgentHandler = async (req, res) => {
id: newAgentId,
author: userId,
});
+ if (!validateAgentCodeEnvironmentAllowlist(req, res, newAgentData.code_environment_ids)) {
+ return;
+ }
if (
isActiveAgentWorkspaceConfiguration(newAgentData) &&
!validateStatefulCodeEnvironment(
@@ -2024,6 +1970,9 @@ const revertAgentVersionHandler = async (req, res) => {
}
const revertVersion = existingAgent.versions?.[version_index];
+ if (!validateAgentCodeEnvironmentAllowlist(req, res, revertVersion?.code_environment_ids)) {
+ return;
+ }
const restoredWorkspaceConfiguration = revertVersion
? resolveAgentWorkspaceRestoreConfiguration({
version: revertVersion,
diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.js
index 73fc387d96..effe06002f 100644
--- a/api/server/controllers/agents/v1.spec.js
+++ b/api/server/controllers/agents/v1.spec.js
@@ -213,6 +213,70 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
};
});
+ describe('agent machine allowlist authorization', () => {
+ test.each(['create', 'update', 'duplicate', 'restore'])(
+ '%s refuses machine references outside the principal-scoped configuration',
+ async (ingress) => {
+ const source = await Agent.create({
+ id: `agent_${uuidv4()}`,
+ name: 'Machine reference source',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: mockReq.user.id,
+ stateful_code_sessions: false,
+ code_environment_ids: ingress === 'duplicate' ? ['another-users-vm'] : [],
+ versions: [
+ {
+ name: 'Earlier',
+ provider: 'openai',
+ model: 'gpt-4',
+ code_environment_ids: ['another-users-vm'],
+ },
+ ],
+ });
+ mockReq.config = {
+ endpoints: {
+ agents: {
+ statefulCodeSessions: {
+ allowedEnvironments: ['user'],
+ environments: [
+ {
+ id: 'own-vm',
+ name: 'Own VM',
+ type: 'attached',
+ baseURL: 'https://own.example.com/v1',
+ },
+ ],
+ },
+ },
+ },
+ };
+ mockReq.params.id = source.id;
+ if (ingress === 'create') {
+ mockReq.body = {
+ name: 'New agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ code_environment_ids: ['another-users-vm'],
+ };
+ await createAgentHandler(mockReq, mockRes);
+ } else if (ingress === 'update') {
+ mockReq.body = { code_environment_ids: ['another-users-vm'] };
+ await updateAgentHandler(mockReq, mockRes);
+ } else if (ingress === 'duplicate') {
+ await duplicateAgentHandler(mockReq, mockRes);
+ } else {
+ mockReq.body = { version_index: 0 };
+ await revertAgentVersionHandler(mockReq, mockRes);
+ }
+ expect(mockRes.status).toHaveBeenCalledWith(403);
+ expect(await Agent.countDocuments()).toBe(1);
+ const persisted = await Agent.findOne({ id: source.id }).lean();
+ expect(persisted.code_environment_ids).toEqual(source.code_environment_ids);
+ },
+ );
+ });
+
describe('createAgentHandler', () => {
test('removes programmatic tool options when Code Interpreter capability is disabled', async () => {
mockReq.body = {
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index df95bd051d..39fd0798fd 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -24,6 +24,7 @@ const {
collectCodeExecutionProfileRoutes,
getLazySubagentConfigId,
resolveCodeExecutionContext,
+ resolveCodeExecutionWorkspaceSelections,
optsOutOfAttachedCodeEnvironment,
isImplicitStatefulCodeRouteAvailable,
resolveCodeExecutionWorkspaceContext,
@@ -1141,6 +1142,13 @@ const initializeClientWithProvider = async ({
statefulSessions: statefulCodeSessions,
environment: statefulCodeEnvironment,
environmentId: agent.code_environment_id,
+ environmentIds: agent.code_environment_ids,
+ allowEnvironmentSelection:
+ appConfig.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: admittedConversation,
+ request: runtimeRequestBody,
+ }),
environments: configuredCodeEnvironments,
userId,
agentId: agent.id,
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index 43a94d6914..190bcb7a60 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -1686,6 +1686,7 @@ describe('initializeClient — subagent loading', () => {
[true, 'override-resolved', false],
[true, 'resolved', false],
[true, 'moved', true],
+ [true, 'inaccessible-choice', false],
[false, 'resolved-null', false],
[true, 'resolved-null', true],
[false, 'other-owner', false],
@@ -1727,6 +1728,11 @@ describe('initializeClient — subagent loading', () => {
],
};
req.body.codeWorkspaces = [{ environmentId: 'attached-vm', workspaceId: 'project-b' }];
+ if (source === 'inaccessible-choice') {
+ req.config.endpoints.agents.statefulCodeSessions.allowEnvironmentSelection = true;
+ await db.updateAgent({ id: SUBAGENT_ID }, { code_environment_ids: ['unavailable-vm'] });
+ req.body.codeWorkspaces = [{ environmentId: 'unavailable-vm', workspaceId: 'project-b' }];
+ }
if (source === 'request' && !registered) {
req.body.codeWorkspaces[0].workspaceId = 'removed-project';
}
@@ -1795,7 +1801,7 @@ describe('initializeClient — subagent loading', () => {
});
const defaultsWithoutAttached =
source === 'other-owner' || (source === 'resolved-null' && !movesEnabled);
- if (!registered && !defaultsWithoutAttached) {
+ if ((!registered && !defaultsWithoutAttached) || source === 'inaccessible-choice') {
await expect(initialization).rejects.toMatchObject({
code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,
});
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index b426000b5a..caad0c81dd 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -56,6 +56,7 @@ const {
resolveAttachedWorkspaceRequestTimeoutMs,
createContextProgrammaticBashTool,
resolveCodeExecutionContext,
+ resolveCodeExecutionWorkspaceSelections,
resolveCodeExecutionWorkspaceContext,
resolveRunFileCodeExecutionContext,
resolveCallerCapabilityProjectionSnapshot,
@@ -885,6 +886,13 @@ async function loadToolDefinitionsWrapper({
agent.stateful_code_sessions === true,
environment: agent.stateful_code_environment,
environmentId: agent.code_environment_id,
+ environmentIds: agent.code_environment_ids,
+ allowEnvironmentSelection:
+ req.config?.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: req.resolvedConversation,
+ request: runtimeRequestBody,
+ }),
environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,
userId: req.user.id,
agentId: agent.id,
@@ -1800,6 +1808,13 @@ async function loadAgentTools({
statefulSessions: statefulCodeSessions,
environment: agent.stateful_code_environment,
environmentId: agent.code_environment_id,
+ environmentIds: agent.code_environment_ids,
+ allowEnvironmentSelection:
+ req.config?.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: req.resolvedConversation,
+ request: runtimeRequestBody,
+ }),
environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,
userId: req.user.id,
agentId: agent.id,
@@ -2232,6 +2247,13 @@ async function loadToolsForExecution({
statefulSessions: statefulCodeSessions,
environment: agent?.stateful_code_environment,
environmentId: agent?.code_environment_id,
+ environmentIds: agent?.code_environment_ids,
+ allowEnvironmentSelection:
+ req.config?.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: req.resolvedConversation,
+ request: runtimeRequestBody,
+ }),
environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,
userId: req.user.id,
agentId: agent?.id,
diff --git a/client/src/common/agents-types.ts b/client/src/common/agents-types.ts
index eaffe6ee17..caa3d95c3c 100644
--- a/client/src/common/agents-types.ts
+++ b/client/src/common/agents-types.ts
@@ -52,6 +52,7 @@ export type AgentForm = {
stateful_code_environment?: StatefulCodeEnvironment;
/** Operator-configured managed or attached execution environment. */
code_environment_id?: string | null;
+ code_environment_ids?: string[];
code_workspace_id?: string;
repositoryInstructions?: 'prefer' | 'defer' | 'off';
/** Git authorship applied to sandboxed commands for this agent. */
diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
index 9582d2d0ae..8fb84b56db 100644
--- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
+++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
@@ -1,7 +1,7 @@
-import { useState } from 'react';
+import { useId, useState } from 'react';
import * as Ariakit from '@ariakit/react';
-import { Check, ChevronDown, Folder, FolderSync, FolderX, RefreshCw } from 'lucide-react';
import { TooltipAnchor, composerControlClasses, useToastContext } from '@librechat/client';
+import { Check, ChevronDown, Folder, FolderSync, FolderX, RefreshCw, Monitor } from 'lucide-react';
import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider';
import type { SetterOrUpdater } from 'recoil';
import type {
@@ -14,6 +14,7 @@ import {
useCodeWorkspaceRefresh,
useMoveConversationCodeEnvironmentMutation,
useReconcileConversationCodeEnvironmentMutation,
+ useCodeEnvironmentStatusQueries,
} from '~/data-provider';
import {
cn,
@@ -105,6 +106,7 @@ function chosenWorkspaceId(
function EnvironmentWorkspaces({
environment,
+ requiredBy,
workspaces,
emptyLabel,
hideOnClick,
@@ -112,6 +114,7 @@ function EnvironmentWorkspaces({
onSelect,
}: {
environment: CodeWorkspaceEnvironmentResult['environment'];
+ requiredBy?: CodeWorkspaceEnvironmentResult['requiredBy'];
workspaces: CodeWorkspaceEnvironmentResult['workspaces'];
emptyLabel: string;
hideOnClick: boolean;
@@ -120,10 +123,17 @@ function EnvironmentWorkspaces({
}) {
const localize = useLocalize();
return (
- <div>
+ <div data-code-environment-id={environment.id}>
<Ariakit.MenuHeading render={<div />} className={headingClasses}>
{environment.name ?? environment.id}
</Ariakit.MenuHeading>
+ {requiredBy != null && requiredBy.length > 0 && (
+ <p className="text-text-secondary px-2.5 pb-2 text-xs">
+ {localize('com_ui_code_workspace_used_by', {
+ 0: requiredBy.map(({ id, name }) => name || id).join(', '),
+ })}
+ </p>
+ )}
{workspaces.length === 0 && (
<div className="text-text-secondary px-2.5 py-2 text-sm">{emptyLabel}</div>
)}
@@ -177,6 +187,17 @@ function EnvironmentWorkspaces({
);
}
+function WorkspaceRequirements({ id, requirements }: { id: string; requirements: string[] }) {
+ if (requirements.length === 0) return null;
+ return (
+ <div id={id} role="status" aria-live="polite" className="text-text-secondary text-xs">
+ {requirements.map((requirement) => (
+ <p key={requirement}>{requirement}</p>
+ ))}
+ </div>
+ );
+}
+
export default function CodeWorkspaceMenu({
setConversation,
workspace,
@@ -186,10 +207,28 @@ export default function CodeWorkspaceMenu({
workspace: CodeWorkspaceResult;
disabled: boolean;
}) {
+ const requirementsId = useId();
const localize = useLocalize();
const { showToast } = useToastContext();
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
const isOpen = menuStore.useState('open');
+ const [machineId, setMachineId] = useState<string | null>(null);
+ const machine = workspace.machineOptions?.find(
+ ({ id }) =>
+ id === machineId && !workspace.environments.some(({ environment }) => environment.id === id),
+ );
+ const machineQueries = useCodeEnvironmentStatusQueries(
+ machine ? [machine.id] : [],
+ isOpen && machine != null && !workspace.locked,
+ );
+ const machineQuery = machineQueries[0];
+ const machineStatus = machineQuery?.data;
+ const machineReady =
+ machine != null &&
+ machineStatus?.environmentId === machine.id &&
+ machineStatus.status === 'ready' &&
+ machineStatus.workspaces != null &&
+ machineStatus.operations != null;
const moveMutation = useMoveConversationCodeEnvironmentMutation(setConversation);
const reconcileMutation = useReconcileConversationCodeEnvironmentMutation(setConversation);
const { refresh, isRefreshing } = useCodeWorkspaceRefresh();
@@ -228,18 +267,38 @@ export default function CodeWorkspaceMenu({
const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id));
const selectWorkspace = (selection: CodeWorkspaceSelection) => {
workspace.rememberSelection(selection);
+ const replacedIds = new Set(
+ workspace.machineOptionGroups?.filter((ids) => ids.includes(selection.environmentId)).flat(),
+ );
+ const owners = workspace.machineChoiceOwners
+ ?.filter(({ environmentIds }) => environmentIds.includes(selection.environmentId))
+ .map(({ agentId }) => agentId);
setConversation((current) => {
if (current == null) return current;
- const retained = (current.codeWorkspaces ?? workspace.selections ?? []).filter(
- ({ environmentId }) =>
- environmentIds.has(environmentId) && environmentId !== selection.environmentId,
+ const retained = (current.codeWorkspaces ?? workspace.selections ?? []).flatMap(
+ ({ agentIds, ...existing }) => {
+ if (
+ !environmentIds.has(existing.environmentId) ||
+ existing.environmentId === selection.environmentId
+ )
+ return [];
+ const remaining = agentIds?.filter((id) => !owners?.includes(id));
+ const fixed = workspace.fixedMachineIds?.includes(existing.environmentId);
+ if (
+ !fixed &&
+ (agentIds == null ? replacedIds.has(existing.environmentId) : remaining?.length === 0)
+ )
+ return [];
+ return [{ ...existing, ...(remaining?.length ? { agentIds: remaining } : {}) }];
+ },
);
return {
...current,
codeEnvironmentMode: 'attached',
- codeWorkspaces: [...retained, selection].sort((a, b) =>
- a.environmentId.localeCompare(b.environmentId),
- ),
+ codeWorkspaces: [
+ ...retained,
+ { ...selection, ...(owners?.length ? { agentIds: owners } : {}) },
+ ].sort((a, b) => a.environmentId.localeCompare(b.environmentId)),
};
});
};
@@ -264,7 +323,15 @@ export default function CodeWorkspaceMenu({
const chosenTargets =
transition?.targets.flatMap((target) => {
const workspaceId = chosenWorkspaceId(target, moveChoices);
- return workspaceId == null ? [] : [{ environmentId: target.environment.id, workspaceId }];
+ return workspaceId == null
+ ? []
+ : [
+ {
+ environmentId: target.environment.id,
+ workspaceId,
+ ...(target.selectionOwners?.length ? { agentIds: target.selectionOwners } : {}),
+ },
+ ];
}) ?? [];
/** A transition replaces the whole decision, so an empty target set is the detach and gets its
* own item: this one only confirms a decision that still names at least one workspace. */
@@ -311,12 +378,46 @@ export default function CodeWorkspaceMenu({
} else if (label == null) {
label = labelKey ? localize(labelKey) : localize('com_ui_code_workspace_choose');
}
+ if (onlyDescriptor && (workspace.machineOptions?.length ?? 0) > 1) {
+ label = `${onlyEnvironment?.environment.name ?? onlyEnvironment?.environment.id} · ${label}`;
+ }
const Icon =
workspace.mode === 'without_attached' ||
workspace.state === 'missing' ||
workspace.state === 'unavailable'
? FolderX
: Folder;
+ const pendingRequirements =
+ workspace.state === 'without_attached'
+ ? []
+ : workspace.environments.flatMap(({ environment, state, requiredBy }) => {
+ if (state === 'ready' || !requiredBy?.length) return [];
+ const agents = requiredBy.map(({ id, name }) => name || id).join(', ');
+ return [
+ state === 'choose'
+ ? localize('com_ui_code_workspace_required_for', {
+ 0: agents,
+ 1: environment.name ?? environment.id,
+ })
+ : localize('com_ui_code_workspace_agent_status', {
+ 0: agents,
+ 1: environment.name ?? environment.id,
+ 2: localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable'),
+ }),
+ ];
+ });
+ const requirements =
+ pendingRequirements.length === 0 && workspace.state === 'choose' && !workspace.canSubmit
+ ? [localize('com_ui_code_workspace_graph_selection_conflict')]
+ : pendingRequirements;
+ if (
+ requirements.length > 0 &&
+ new Set(
+ workspace.environments.flatMap(({ requiredBy }) => requiredBy?.map(({ id }) => id) ?? []),
+ ).size > 1
+ ) {
+ requirements.unshift(localize('com_ui_code_workspace_graph_requirement'));
+ }
if (workspace.locked && transition == null) {
/** A sealed decision with no transition on offer only reports where this chat runs: without a
@@ -327,26 +428,30 @@ export default function CodeWorkspaceMenu({
? localize('com_ui_code_workspace_without_attached_info')
: localize('com_ui_code_workspace_locked_recovery');
return (
- <TooltipAnchor
- description={recovery}
- render={
- <button
- type="button"
- data-testid="code-workspace-locked-status"
- disabled={disabled || isRefreshing}
- onClick={() => void refresh()}
- aria-label={`${label}. ${recovery}. ${localize('com_ui_retry')}`}
- aria-busy={isRefreshing}
- className={cn(composerControlClasses(), 'max-w-full min-w-0 px-2.5')}
- />
- }
- >
- <Icon className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
- <span role="status" className="max-w-[16rem] min-w-0 truncate">
- {label}
- </span>
- <RefreshCw className="text-text-secondary size-3 shrink-0" aria-hidden="true" />
- </TooltipAnchor>
+ <div className="flex min-w-0 flex-col items-start gap-1">
+ <TooltipAnchor
+ description={requirements.join(' ') || recovery}
+ render={
+ <button
+ type="button"
+ data-testid="code-workspace-locked-status"
+ disabled={disabled || isRefreshing}
+ onClick={() => void refresh()}
+ aria-label={`${label}. ${recovery}. ${localize('com_ui_retry')}`}
+ aria-describedby={requirements.length > 0 ? requirementsId : undefined}
+ aria-busy={isRefreshing}
+ className={cn(composerControlClasses(), 'max-w-full min-w-0 px-2.5')}
+ />
+ }
+ >
+ <Icon className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
+ <span role="status" className="max-w-[16rem] min-w-0 truncate">
+ {label}
+ </span>
+ <RefreshCw className="text-text-secondary size-3 shrink-0" aria-hidden="true" />
+ </TooltipAnchor>
+ <WorkspaceRequirements id={requirementsId} requirements={requirements} />
+ </div>
);
}
@@ -360,37 +465,43 @@ export default function CodeWorkspaceMenu({
return (
<Ariakit.MenuProvider store={menuStore}>
- <TooltipAnchor
- description={transitionText?.info ?? localize('com_ui_code_workspace')}
- disabled={isOpen}
- render={
- <Ariakit.MenuButton
- disabled={buttonDisabled}
- data-testid={renamesForMove ? 'code-workspace-move' : 'code-workspace'}
- aria-label={
- transitionText == null
- ? `${localize('com_ui_code_workspace')}: ${label}`
- : `${buttonLabel}. ${transitionText.info}`
- }
+ <div className="flex min-w-0 flex-col items-start gap-1">
+ <TooltipAnchor
+ description={
+ transitionText?.info ?? (requirements.join(' ') || localize('com_ui_code_workspace'))
+ }
+ disabled={isOpen}
+ render={
+ <Ariakit.MenuButton
+ disabled={buttonDisabled}
+ data-testid={renamesForMove ? 'code-workspace-move' : 'code-workspace'}
+ aria-describedby={requirements.length > 0 ? requirementsId : undefined}
+ aria-label={
+ transitionText == null
+ ? `${localize('com_ui_code_workspace')}: ${label}`
+ : `${buttonLabel}. ${transitionText.info}`
+ }
+ className={cn(
+ composerControlClasses(),
+ 'md:px-theme-control-x max-w-full min-w-0 px-2.5',
+ isOpen && 'bg-surface-hover',
+ buttonDisabled && 'cursor-not-allowed opacity-50',
+ )}
+ />
+ }
+ >
+ <ButtonIcon className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
+ <span className="max-w-[12rem] min-w-0 truncate">{buttonLabel}</span>
+ <ChevronDown
className={cn(
- composerControlClasses(),
- 'md:px-theme-control-x max-w-full min-w-0 px-2.5',
- isOpen && 'bg-surface-hover',
- buttonDisabled && 'cursor-not-allowed opacity-50',
+ 'text-text-secondary size-3 shrink-0 transition-transform',
+ isOpen && 'rotate-180',
)}
+ aria-hidden="true"
/>
- }
- >
- <ButtonIcon className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
- <span className="max-w-[12rem] min-w-0 truncate">{buttonLabel}</span>
- <ChevronDown
- className={cn(
- 'text-text-secondary size-3 shrink-0 transition-transform',
- isOpen && 'rotate-180',
- )}
- aria-hidden="true"
- />
- </TooltipAnchor>
+ </TooltipAnchor>
+ <WorkspaceRequirements id={requirementsId} requirements={requirements} />
+ </div>
<Ariakit.Menu
portal={true}
gutter={8}
@@ -413,6 +524,7 @@ export default function CodeWorkspaceMenu({
<EnvironmentWorkspaces
key={target.environment.id}
environment={target.environment}
+ requiredBy={target.requiredBy}
workspaces={target.workspaces}
emptyLabel={localize('com_ui_code_workspace_unavailable')}
hideOnClick={false}
@@ -499,19 +611,79 @@ export default function CodeWorkspaceMenu({
)}
</Ariakit.MenuItemRadio>
)}
- {workspace.environments.map(({ environment, state, workspaces, selected }) => (
- <EnvironmentWorkspaces
- key={environment.id}
- environment={environment}
- workspaces={workspaces}
- emptyLabel={localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable')}
- hideOnClick={true}
- isSelected={(workspaceId) =>
- workspace.mode === 'attached' && workspaceId === selected?.workspaceId
- }
- onSelect={selectWorkspace}
- />
- ))}
+ {workspace.environments.map(
+ ({ environment, state, workspaces, selected, requiredBy }) => (
+ <EnvironmentWorkspaces
+ key={environment.id}
+ environment={environment}
+ requiredBy={requiredBy}
+ workspaces={workspaces}
+ emptyLabel={localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable')}
+ hideOnClick={true}
+ isSelected={(workspaceId) =>
+ workspace.mode === 'attached' && workspaceId === selected?.workspaceId
+ }
+ onSelect={selectWorkspace}
+ />
+ ),
+ )}
+ {workspace.machineOptions?.some(({ id }) => !environmentIds.has(id)) && (
+ <>
+ <Ariakit.MenuSeparator className="border-border-light my-1 h-0 w-full border-t" />
+ <Ariakit.MenuHeading render={<div />} className={headingClasses}>
+ {localize('com_ui_code_environment_choose_machine')}
+ </Ariakit.MenuHeading>
+ {workspace.machineOptions
+ ?.filter(({ id }) => !environmentIds.has(id))
+ .map((candidate) => (
+ <Ariakit.MenuItem
+ key={candidate.id}
+ hideOnClick={false}
+ className={menuItemClasses(machineId === candidate.id)}
+ onClick={() => setMachineId(candidate.id)}
+ >
+ <Monitor
+ className="text-text-secondary mt-0.5 size-4 shrink-0"
+ aria-hidden="true"
+ />
+ <span className="text-text-primary min-w-0 flex-1 truncate text-left text-sm">
+ {candidate.name ?? candidate.id}
+ </span>
+ </Ariakit.MenuItem>
+ ))}
+ {machine != null &&
+ (machineReady ? (
+ <EnvironmentWorkspaces
+ environment={machine}
+ workspaces={machineStatus?.workspaces ?? []}
+ emptyLabel={localize('com_ui_code_workspace_unavailable')}
+ hideOnClick={true}
+ isSelected={() => false}
+ onSelect={selectWorkspace}
+ />
+ ) : (
+ <Ariakit.MenuItem
+ hideOnClick={false}
+ className={menuItemClasses()}
+ disabled={machineQuery?.isLoading}
+ aria-busy={machineQuery?.isLoading}
+ onClick={() => void machineQuery?.refetch()}
+ >
+ <RefreshCw
+ className="text-text-secondary mt-0.5 size-4 shrink-0"
+ aria-hidden="true"
+ />
+ <span role="status" className="text-text-secondary text-sm">
+ {localize(
+ machineQuery?.isLoading
+ ? 'com_ui_code_workspace_loading'
+ : 'com_ui_code_workspace_unavailable',
+ )}
+ </span>
+ </Ariakit.MenuItem>
+ ))}
+ </>
+ )}
</>
)}
<Ariakit.MenuSeparator className="border-border-light my-1 h-0 w-full border-t" />
diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
index c4a96b70ea..8bbb5076a6 100644
--- a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
@@ -20,7 +20,16 @@ jest.mock('librechat-data-provider', () => {
});
jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
+ useLocalize: () => (key: string, values?: Record<string, unknown>) => {
+ if (key === 'com_ui_code_workspace_required_for')
+ return `Choose a workspace for ${values?.[0]} on ${values?.[1]}.`;
+ if (key === 'com_ui_code_workspace_graph_requirement')
+ return 'Every coding agent in this chat needs a workspace, including subagents.';
+ if (key === 'com_ui_code_workspace_used_by') return `Used by ${values?.[0]}`;
+ if (key === 'com_ui_code_workspace_agent_status')
+ return `${values?.[0]} needs ${values?.[1]}: ${values?.[2]}`;
+ return key;
+ },
}));
jest.mock('@librechat/client', () => {
@@ -92,6 +101,221 @@ function renderMenu(ui: React.ReactElement) {
}
describe('CodeWorkspaceMenu', () => {
+ test('explains the missing reviewer workspace while the selected primary workspace is ready', async () => {
+ const reviewerMachine = { ...environment, id: 'reviewer-vm', name: 'Danny Skynet Trusted VM' };
+ const graph = workspace({ state: 'choose', canSubmit: false });
+ graph.environments[0].requiredBy = [{ id: 'lia', name: 'Lia' }];
+ graph.environments.push({
+ environment: reviewerMachine,
+ state: 'choose',
+ workspaces: [{ id: 'review', name: 'Review' }],
+ requiredBy: [{ id: 'reviewer', name: 'PR Reviewer' }],
+ });
+ renderMenu(
+ <CodeWorkspaceMenu setConversation={jest.fn()} workspace={graph} disabled={false} />,
+ );
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Choose a workspace for PR Reviewer on Danny Skynet Trusted VM.',
+ );
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Every coding agent in this chat needs a workspace, including subagents.',
+ );
+ expect(screen.getByRole('status')).not.toHaveTextContent('for Lia');
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ expect(screen.getByText('Used by Lia')).toBeVisible();
+ expect(screen.getByText('Used by PR Reviewer')).toBeVisible();
+ });
+
+ test('does not call an unavailable reviewer machine an unselected workspace', () => {
+ const graph = workspace({ state: 'unavailable', canSubmit: false });
+ graph.environments[0] = {
+ ...graph.environments[0],
+ state: 'unavailable',
+ selected: undefined,
+ requiredBy: [{ id: 'reviewer', name: 'PR Reviewer' }],
+ };
+ renderMenu(
+ <CodeWorkspaceMenu setConversation={jest.fn()} workspace={graph} disabled={false} />,
+ );
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'PR Reviewer needs Personal VM: com_ui_code_workspace_unavailable',
+ );
+ expect(screen.getByRole('status')).not.toHaveTextContent('Choose a workspace');
+ });
+
+ test('keeps a fixed graph machine when replacing an overlapping primary choice', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ const setter = jest.fn();
+ const selection = { environmentId: alternate.id, workspaceId: 'runtime' };
+ const graph = workspace({
+ machineOptionGroups: [[environment.id, alternate.id]],
+ fixedMachineIds: [alternate.id],
+ });
+ graph.environments.push({
+ environment: alternate,
+ state: 'ready',
+ workspaces: [{ id: 'runtime', name: 'Runtime' }],
+ selected: selection,
+ });
+ renderMenu(<CodeWorkspaceMenu setConversation={setter} workspace={graph} disabled={false} />);
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ await userEvent.click(screen.getByRole('menuitemradio', { name: /Project A/ }));
+ expect(
+ setter.mock.calls[0][0]({ ...conversation, codeWorkspaces: [selection] }).codeWorkspaces,
+ ).toEqual([{ environmentId: environment.id, workspaceId: 'project-a' }, selection]);
+ });
+ test('loads only a chosen allowed machine and replaces the draft selection', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ const read = jest.spyOn(dataService, 'getCodeEnvironmentStatus').mockResolvedValue({
+ environmentId: alternate.id,
+ status: 'ready',
+ operations: ['read_file'],
+ workspaces: [{ id: 'runtime', name: 'Runtime Project' }],
+ });
+ const setter = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setter}
+ workspace={workspace({
+ machineOptions: [environment, alternate],
+ machineOptionGroups: [[environment.id, alternate.id]],
+ })}
+ disabled={false}
+ />,
+ );
+ expect(read).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ expect(read).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Runtime VM' }));
+ await userEvent.click(await screen.findByRole('menuitemradio', { name: /Runtime Project/ }));
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(read).toHaveBeenCalledWith(alternate.id);
+ const next = setter.mock.calls[0][0]({
+ ...conversation,
+ codeWorkspaces: [{ environmentId: environment.id, workspaceId: 'project-a' }],
+ });
+ expect(next.codeWorkspaces).toEqual([{ environmentId: alternate.id, workspaceId: 'runtime' }]);
+ read.mockRestore();
+ });
+
+ test('records primary ownership on B while retaining the fixed reviewer on A', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ const read = jest.spyOn(dataService, 'getCodeEnvironmentStatus').mockResolvedValue({
+ environmentId: alternate.id,
+ status: 'ready',
+ operations: ['read_file'],
+ workspaces: [{ id: 'runtime', name: 'Runtime Project' }],
+ });
+ const setter = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setter}
+ workspace={workspace({
+ machineOptions: [environment, alternate],
+ machineOptionGroups: [[environment.id, alternate.id]],
+ machineChoiceOwners: [{ agentId: 'lia', environmentIds: [environment.id, alternate.id] }],
+ fixedMachineIds: [environment.id],
+ })}
+ disabled={false}
+ />,
+ );
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Runtime VM' }));
+ await userEvent.click(await screen.findByRole('menuitemradio', { name: /Runtime Project/ }));
+ expect(
+ setter.mock.calls[0][0]({
+ ...conversation,
+ codeWorkspaces: [
+ { environmentId: environment.id, workspaceId: 'project-a', agentIds: ['lia'] },
+ ],
+ }).codeWorkspaces,
+ ).toEqual([
+ { environmentId: environment.id, workspaceId: 'project-a' },
+ { environmentId: alternate.id, workspaceId: 'runtime', agentIds: ['lia'] },
+ ]);
+ read.mockRestore();
+ });
+
+ test('editing a child workspace preserves the primary agent machine choice', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ const child = { ...environment, id: 'child-vm', name: 'Child VM' };
+ const setter = jest.fn();
+ const rootSelection = { environmentId: environment.id, workspaceId: 'project-a' };
+ const childSelection = { environmentId: child.id, workspaceId: 'old' };
+ const graph = workspace({
+ machineOptions: [environment, alternate],
+ machineOptionGroups: [[environment.id, alternate.id]],
+ selections: [rootSelection, childSelection],
+ });
+ graph.environments.push({
+ environment: child,
+ state: 'ready',
+ selected: childSelection,
+ workspaces: [
+ { id: 'old', name: 'Old' },
+ { id: 'new', name: 'Child Project' },
+ ],
+ });
+ renderMenu(<CodeWorkspaceMenu setConversation={setter} workspace={graph} disabled={false} />);
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ await userEvent.click(screen.getByRole('menuitemradio', { name: /Child Project/ }));
+ const next = setter.mock.calls[0][0]({
+ ...conversation,
+ codeWorkspaces: [rootSelection, childSelection],
+ });
+ expect(next.codeWorkspaces).toEqual([
+ { environmentId: child.id, workspaceId: 'new' },
+ rootSelection,
+ ]);
+ });
+
+ test('offers a sole allowed alternative when the original default is no longer accessible', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={jest.fn()}
+ workspace={workspace({
+ state: 'unavailable',
+ environments: [],
+ machineOptions: [alternate],
+ })}
+ disabled={false}
+ />,
+ );
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ expect(screen.getByRole('menuitem', { name: 'Runtime VM' })).toBeVisible();
+ });
+
+ test('offers retry for an offline alternative without losing the current workspace', async () => {
+ const alternate = { ...environment, id: 'runtime-vm', name: 'Runtime VM' };
+ const read = jest
+ .spyOn(dataService, 'getCodeEnvironmentStatus')
+ .mockResolvedValueOnce({ environmentId: alternate.id, status: 'offline' })
+ .mockResolvedValue({
+ environmentId: alternate.id,
+ status: 'ready',
+ operations: ['read_file'],
+ workspaces: [{ id: 'runtime', name: 'Runtime Project' }],
+ });
+ const setter = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setter}
+ workspace={workspace({ machineOptions: [environment, alternate] })}
+ disabled={false}
+ />,
+ );
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Runtime VM' }));
+ const retry = await screen.findByRole('menuitem', {
+ name: 'com_ui_code_workspace_unavailable',
+ });
+ expect(setter).not.toHaveBeenCalled();
+ await userEvent.click(retry);
+ expect(await screen.findByRole('menuitemradio', { name: /Runtime Project/ })).toBeVisible();
+ expect(read).toHaveBeenCalledTimes(2);
+ read.mockRestore();
+ });
test('explains a failed reconciliation and retries without permitting workspace changes', async () => {
const store = createStore();
const request = {
diff --git a/client/src/components/SidePanel/Agents/AgentPanel.tsx b/client/src/components/SidePanel/Agents/AgentPanel.tsx
index 0c5e795e1f..78d064eb36 100644
--- a/client/src/components/SidePanel/Agents/AgentPanel.tsx
+++ b/client/src/components/SidePanel/Agents/AgentPanel.tsx
@@ -142,6 +142,7 @@ export function composeAgentUpdatePayload(
stateful_code_sessions,
stateful_code_environment,
code_environment_id,
+ code_environment_ids,
repositoryInstructions,
code_workspace_id,
git_identity,
@@ -215,6 +216,12 @@ export function composeAgentUpdatePayload(
stateful_code_sessions: normalizedStatefulCodeSessions,
stateful_code_environment: normalizedStatefulCodeEnvironment,
code_environment_id: agent_id ? code_environment_id : (code_environment_id ?? undefined),
+ code_environment_ids:
+ agent_id &&
+ typeof data.agent === 'object' &&
+ isEqual(code_environment_ids ?? [], data.agent?.code_environment_ids ?? [])
+ ? undefined
+ : code_environment_ids,
repositoryInstructions,
code_workspace_id,
git_identity: normalizedGitIdentity,
diff --git a/client/src/components/SidePanel/Agents/AgentSelect.tsx b/client/src/components/SidePanel/Agents/AgentSelect.tsx
index c0975b98b2..4081cf40b0 100644
--- a/client/src/components/SidePanel/Agents/AgentSelect.tsx
+++ b/client/src/components/SidePanel/Agents/AgentSelect.tsx
@@ -114,6 +114,7 @@ function AgentSelect({
avatar_action: null,
stateful_code_environment: fullAgent.stateful_code_environment ?? 'user',
code_environment_id: fullAgent.code_environment_id,
+ code_environment_ids: fullAgent.code_environment_ids ?? [],
repositoryInstructions: fullAgent.repositoryInstructions,
code_workspace_id: fullAgent.code_workspace_id,
git_identity: fullAgent.git_identity,
diff --git a/client/src/components/SidePanel/Agents/Code/Settings.tsx b/client/src/components/SidePanel/Agents/Code/Settings.tsx
index 2585d2b6d6..6e68ce3810 100644
--- a/client/src/components/SidePanel/Agents/Code/Settings.tsx
+++ b/client/src/components/SidePanel/Agents/Code/Settings.tsx
@@ -1,12 +1,5 @@
import { useCallback, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
-import {
- AgentCapabilities,
- agentGitIdentitySchema,
- STATEFUL_CODE_ENVIRONMENTS,
- resolveStatefulCodeEnvironment,
- resolveAllowedStatefulCodeEnvironments,
-} from 'librechat-data-provider';
import {
Switch,
Select,
@@ -20,7 +13,16 @@ import {
HoverCardTrigger,
CircleHelpIcon,
Input,
+ Checkbox,
} from '@librechat/client';
+import {
+ AgentCapabilities,
+ DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES,
+ agentGitIdentitySchema,
+ STATEFUL_CODE_ENVIRONMENTS,
+ resolveStatefulCodeEnvironment,
+ resolveAllowedStatefulCodeEnvironments,
+} from 'librechat-data-provider';
import type { StatefulCodeEnvironment } from 'librechat-data-provider';
import type { AgentForm } from '~/common';
import { useAuthContext, useGetAgentsConfig, useLocalize } from '~/hooks';
@@ -58,6 +60,10 @@ export default function CodeSettings() {
const codeEnabled = watch(AgentCapabilities.execute_code);
const environment = watch('stateful_code_environment') ?? 'user';
const codeEnvironmentId = watch('code_environment_id');
+ const additionalMachines = watch('code_environment_ids') ?? [];
+ const machineChoiceLimit =
+ agentsConfig?.statefulCodeSessions?.maxEnvironmentChoices ??
+ DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES;
const workspaceId = watch('code_workspace_id') ?? '';
const configuredEnvironments = agentsConfig?.statefulCodeSessions?.allowedEnvironments;
const executionEnvironments = agentsConfig?.statefulCodeSessions?.environments ?? [];
@@ -169,6 +175,30 @@ export default function CodeSettings() {
/>
</div>
</HoverCard>
+ {additionalMachines
+ .filter((id) => !executionEnvironments.some((candidate) => candidate.id === id))
+ .map((machineId) => (
+ <div key={machineId} className="flex items-center gap-2">
+ <Checkbox
+ id={`unavailable-code-machine-${machineId}`}
+ checked={true}
+ aria-label={localize('com_ui_code_environment_unavailable_choice', { 0: machineId })}
+ onCheckedChange={() =>
+ setValue(
+ 'code_environment_ids',
+ additionalMachines.filter((id) => id !== machineId),
+ { shouldDirty: true },
+ )
+ }
+ />
+ <label
+ htmlFor={`unavailable-code-machine-${machineId}`}
+ className="text-text-secondary text-sm"
+ >
+ {localize('com_ui_code_environment_unavailable_choice', { 0: machineId })}
+ </label>
+ </div>
+ ))}
{enabled && codeEnabled === true && (
<div className="space-y-2 pl-1">
{executionEnvironments.length > 0 && (
@@ -210,6 +240,55 @@ export default function CodeSettings() {
<p className="text-text-tertiary text-xs">
{localize('com_nav_info_code_environment')}
</p>
+ {agentsConfig?.statefulCodeSessions?.allowEnvironmentSelection === true &&
+ effectiveExecutionEnvironment?.type === 'attached' && (
+ <div className="space-y-1">
+ <p className="text-text-secondary text-sm font-medium">
+ {localize('com_ui_code_environment_per_chat')}
+ </p>
+ <p className="text-text-tertiary text-xs">
+ {localize('com_ui_code_environment_per_chat_info')}
+ </p>
+ <p className="text-text-tertiary text-xs">
+ {localize('com_ui_code_environment_choice_limit', { 0: machineChoiceLimit })}
+ </p>
+ {executionEnvironments
+ .filter(({ type }) => type === 'attached')
+ .map((candidate) => {
+ const isDefault = candidate.id === effectiveExecutionEnvironment.id;
+ const id = `code-machine-${candidate.id}`;
+ return (
+ <div key={candidate.id} className="flex items-center gap-2">
+ <Checkbox
+ id={id}
+ aria-label={candidate.name}
+ checked={isDefault || additionalMachines.includes(candidate.id)}
+ disabled={
+ isDefault ||
+ (!additionalMachines.includes(candidate.id) &&
+ additionalMachines.length >= machineChoiceLimit)
+ }
+ onCheckedChange={(checked) =>
+ setValue(
+ 'code_environment_ids',
+ checked === true
+ ? [...new Set([...additionalMachines, candidate.id])]
+ : additionalMachines.filter((value) => value !== candidate.id),
+ { shouldDirty: true },
+ )
+ }
+ />
+ <label htmlFor={id} className="text-text-secondary text-sm">
+ {candidate.name}
+ {isDefault
+ ? ` (${localize('com_ui_code_environment_default_machine')})`
+ : ''}
+ </label>
+ </div>
+ );
+ })}
+ </div>
+ )}
</>
)}
<label
diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts b/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts
index a1466d7ae2..c8d74c24ea 100644
--- a/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts
+++ b/client/src/components/SidePanel/Agents/__tests__/AgentPanel.helpers.spec.ts
@@ -61,6 +61,19 @@ const createForm = (): AgentForm => ({
});
describe('composeAgentUpdatePayload', () => {
+ it('omits unchanged unavailable machine choices but submits an explicit removal', () => {
+ const form = createForm();
+ form.agent = {
+ ...({ id: 'agent_123', code_environment_ids: ['missing'] } as Agent),
+ value: 'agent_123',
+ };
+ form.code_environment_ids = ['missing'];
+ expect(
+ composeAgentUpdatePayload(form, 'agent_123').payload.code_environment_ids,
+ ).toBeUndefined();
+ form.code_environment_ids = [];
+ expect(composeAgentUpdatePayload(form, 'agent_123').payload.code_environment_ids).toEqual([]);
+ });
it('includes avatar: null when resetting a persistent agent', () => {
const form = createForm();
form.avatar_action = 'reset';
diff --git a/client/src/components/SidePanel/Agents/__tests__/CodeSettings.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/CodeSettings.spec.tsx
index f468044403..bac5a94595 100644
--- a/client/src/components/SidePanel/Agents/__tests__/CodeSettings.spec.tsx
+++ b/client/src/components/SidePanel/Agents/__tests__/CodeSettings.spec.tsx
@@ -7,6 +7,8 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import type { AgentForm } from '~/common';
import CodeSettings from '../Code/Settings';
const mockWorkspaceStatusQueries = jest.fn();
+const mockMachineChoicesEnabled = jest.fn();
+const mockMachineChoiceLimit = jest.fn();
jest.mock('~/data-provider', () => ({
useCodeEnvironmentStatusQueries: () => mockWorkspaceStatusQueries(),
}));
@@ -18,13 +20,20 @@ jest.mock('~/hooks', () => ({
agentsConfig: {
capabilities: ['stateful_code_sessions'],
statefulCodeSessions: {
- environments: [{ id: 'byom', name: 'My machine', type: 'attached', default: true }],
+ allowEnvironmentSelection: mockMachineChoicesEnabled(),
+ maxEnvironmentChoices: mockMachineChoiceLimit(),
+ environments: [
+ { id: 'byom', name: 'My machine', type: 'attached', default: true },
+ { id: 'runtime', name: 'Runtime machine', type: 'attached' },
+ ],
},
},
}),
}));
beforeEach(() => {
+ mockMachineChoicesEnabled.mockReturnValue(false);
+ mockMachineChoiceLimit.mockReturnValue(32);
mockWorkspaceStatusQueries.mockReturnValue([
{
data: {
@@ -41,9 +50,11 @@ beforeEach(() => {
function IdentityForm({
savedIdentity,
savedWorkspace,
+ savedMachines,
}: {
savedIdentity?: AgentForm['git_identity'];
savedWorkspace?: string;
+ savedMachines?: string[];
}) {
const [dialogOpen, setDialogOpen] = useState(true);
const methods = useForm<AgentForm>({
@@ -53,6 +64,7 @@ function IdentityForm({
stateful_code_sessions: true,
git_identity: savedIdentity,
code_workspace_id: savedWorkspace,
+ code_environment_ids: savedMachines,
},
});
return (
@@ -71,11 +83,52 @@ function IdentityForm({
<output data-testid="identity">{JSON.stringify(methods.watch('git_identity'))}</output>
<output data-testid="workspace-default">{methods.watch('code_workspace_id')}</output>
<output data-testid="machine-default">{methods.watch('code_environment_id')}</output>
+ <output data-testid="machine-allowlist">
+ {JSON.stringify(methods.watch('code_environment_ids'))}
+ </output>
<output data-testid="repository-mode">{methods.watch('repositoryInstructions')}</output>
</FormProvider>
);
}
+test('defines an explicit machine allowlist without changing the default, and permits clearing it', () => {
+ mockMachineChoicesEnabled.mockReturnValue(true);
+ render(<IdentityForm />);
+ const alternative = screen.getByRole('checkbox', { name: 'Runtime machine' });
+ expect(alternative).not.toBeChecked();
+ expect(screen.getByRole('checkbox', { name: /My machine/ })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: /My machine/ })).toBeDisabled();
+ fireEvent.click(alternative);
+ expect(screen.getByTestId('machine-allowlist')).toHaveTextContent('["runtime"]');
+ expect(screen.getByTestId('machine-default')).toBeEmptyDOMElement();
+ fireEvent.click(alternative);
+ expect(screen.getByTestId('machine-allowlist')).toHaveTextContent('[]');
+});
+
+test('honors the server machine-choice limit without disabling the selected choice', () => {
+ mockMachineChoicesEnabled.mockReturnValue(true);
+ mockMachineChoiceLimit.mockReturnValue(1);
+ const { unmount } = render(<IdentityForm savedMachines={['missing']} />);
+ expect(screen.getByRole('checkbox', { name: 'Runtime machine' })).toBeDisabled();
+ unmount();
+ render(<IdentityForm savedMachines={['runtime']} />);
+ expect(screen.getByRole('checkbox', { name: 'Runtime machine' })).not.toBeDisabled();
+});
+
+test('lets an owner remove a machine that is no longer accessible', async () => {
+ mockMachineChoicesEnabled.mockReturnValue(true);
+ render(<IdentityForm savedMachines={['missing']} />);
+ fireEvent.click(
+ screen.getByRole('checkbox', { name: 'com_ui_code_environment_unavailable_choice' }),
+ );
+ expect(screen.getByTestId('machine-allowlist')).toHaveTextContent('[]');
+});
+
+test('does not offer machine choices when the deployment has not enabled them', () => {
+ render(<IdentityForm />);
+ expect(screen.queryByRole('checkbox', { name: 'Runtime machine' })).not.toBeInTheDocument();
+});
+
test('repository instruction mode defaults to prefer and retains an explicit off choice', async () => {
HTMLElement.prototype.scrollIntoView = jest.fn();
render(<IdentityForm />);
diff --git a/client/src/hooks/Agents/__tests__/codeDecision.test.ts b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
index 1268c41264..007182464d 100644
--- a/client/src/hooks/Agents/__tests__/codeDecision.test.ts
+++ b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
@@ -6,6 +6,20 @@ const conversation = (overrides: Partial<TConversation> = {}): TConversation =>
({ conversationId: 'existing', ...overrides }) as TConversation;
describe('withSubmittedCodeDecision', () => {
+ it('does not treat changed agent ownership as the same sealed route', () => {
+ const current = conversation({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ ...selection, agentIds: ['primary'] }],
+ });
+ const submitted = {
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [{ ...selection, agentIds: ['reviewer'] }],
+ };
+ expect(hasSameCodeDecision(current, submitted)).toBe(false);
+ expect(withSubmittedCodeDecision(current, submitted)?.codeWorkspaces).toEqual(
+ submitted.codeWorkspaces,
+ );
+ });
it('records the mode and selections the run was submitted with', () => {
expect(
withSubmittedCodeDecision(conversation(), {
diff --git a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
index 515e35c667..ee73eca9cc 100644
--- a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
+++ b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
@@ -70,6 +70,66 @@ describe('useCodeApprovalMode', () => {
});
});
+ test('uses the chosen machine policy without inheriting full access from the default', () => {
+ mockUseAgentToolPermissions.mockReturnValue({
+ agent: {
+ id: 'agent_1',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'mac',
+ code_environment_ids: ['runtime'],
+ },
+ });
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ allowEnvironmentSelection: true,
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits', 'fullAccess'],
+ environments: [
+ {
+ id: 'mac',
+ type: 'attached',
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['ask', 'allow'], default: 'ask' },
+ commandExecution: { allowed: ['ask', 'allow'], default: 'ask' },
+ },
+ },
+ },
+ {
+ id: 'runtime',
+ type: 'attached',
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['ask'], default: 'ask' },
+ commandExecution: { allowed: ['ask'], default: 'ask' },
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+ const runtime = renderHook(() =>
+ useCodeApprovalMode({
+ ...conversation,
+ codeApprovalMode: 'fullAccess',
+ codeWorkspaces: [{ environmentId: 'runtime', workspaceId: 'primary' }],
+ }),
+ );
+ expect(runtime.result.current.modes).toEqual(['ask']);
+ expect(runtime.result.current.selected).toBe('ask');
+ const application = renderHook(() =>
+ useCodeApprovalMode({
+ ...conversation,
+ codeApprovalMode: 'fullAccess',
+ codeWorkspaces: undefined,
+ }),
+ );
+ expect(application.result.current.selected).toBe('fullAccess');
+ });
+
test.each(['permitted', 'restricted', 'missing'])(
'full access requires every reachable machine: %s',
(policy) => {
diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
index bc44983ae3..8c2fc27a78 100644
--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
@@ -43,6 +43,471 @@ const conversation = (codeWorkspaces?: TConversation['codeWorkspaces']): TConver
}) as TConversation;
describe('useCodeWorkspace', () => {
+ describe('per-chat machines', () => {
+ function enableChoices() {
+ const config = mockAgentsConfig().agentsConfig;
+ config.statefulCodeSessions.allowEnvironmentSelection = true;
+ config.statefulCodeSessions.environments.push({
+ id: 'runtime-vm',
+ name: 'Runtime VM',
+ type: 'attached',
+ });
+ config.statefulCodeSessions.environments.push({
+ id: 'unlisted-vm',
+ name: 'Unlisted',
+ type: 'attached',
+ });
+ mockAgentPermissions().agent.code_environment_ids = ['runtime-vm'];
+ return config;
+ }
+
+ it('names the reviewer whose separate machine still needs a workspace', () => {
+ enableChoices();
+ mockAgentPermissions().agent.name = 'Lia';
+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };
+ mockAgentsMap.mockReturnValue({
+ reviewer: {
+ id: 'reviewer',
+ name: 'PR Reviewer',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'runtime-vm',
+ },
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: {
+ environmentId: id,
+ status: 'ready',
+ workspaces:
+ id === 'runtime-vm' ? [{ id: 'one' }, { id: 'two' }] : [{ id: 'project-a' }],
+ },
+ })),
+ );
+ const { result } = renderHook(() =>
+ useCodeWorkspace(
+ conversation([{ environmentId: 'personal-vm', workspaceId: 'project-a' }]),
+ ),
+ );
+ expect(result.current.canSubmit).toBe(false);
+ expect(
+ result.current.environments.find(({ environment }) => environment.id === 'runtime-vm'),
+ ).toMatchObject({ state: 'choose', requiredBy: [{ id: 'reviewer', name: 'PR Reviewer' }] });
+ });
+
+ it('shares one selected machine between Lia and a reviewer that both explicitly allow it', () => {
+ enableChoices();
+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };
+ mockAgentsMap.mockReturnValue({
+ reviewer: {
+ id: 'reviewer',
+ name: 'PR Reviewer',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'runtime-vm',
+ code_environment_ids: ['personal-vm'],
+ },
+ });
+ const selection = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }];
+ const { result } = renderHook(() => useCodeWorkspace(conversation(selection)));
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.environments).toHaveLength(1);
+ expect(result.current.environments[0].requiredBy).toEqual(
+ expect.arrayContaining([
+ { id: 'reviewer', name: 'PR Reviewer' },
+ { id: 'agent_primary', name: undefined },
+ ]),
+ );
+ expect(result.current.resolveSubmission(selection)?.codeWorkspaces).toEqual(selection);
+ });
+
+ it('preserves the default plus an overlapping machine required by a fixed reviewer', () => {
+ enableChoices();
+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };
+ mockAgentsMap.mockReturnValue({
+ reviewer: {
+ id: 'reviewer',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'runtime-vm',
+ },
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },
+ })),
+ );
+ const choices = [
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ { environmentId: 'runtime-vm', workspaceId: 'project-a' },
+ ];
+ const { result } = renderHook(() => useCodeWorkspace(conversation(choices)));
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.fixedMachineIds).toEqual(['runtime-vm']);
+ expect(result.current.resolveSubmission(choices)?.codeWorkspaces).toEqual(choices);
+ });
+
+ it('keeps a fixed reviewer on A while the primary explicitly chooses B, including reload', () => {
+ enableChoices();
+ mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['reviewer'] };
+ mockAgentsMap.mockReturnValue({
+ reviewer: {
+ id: 'reviewer',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'personal-vm',
+ },
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },
+ })),
+ );
+ const choices = [
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ { environmentId: 'runtime-vm', workspaceId: 'project-a', agentIds: ['agent_primary'] },
+ ];
+ const { result, rerender } = renderHook(
+ ({ saved }) =>
+ useCodeWorkspace({
+ ...conversation(choices),
+ conversationId: saved ? 'saved' : 'new',
+ codeEnvironmentMode: 'attached',
+ }),
+ { initialProps: { saved: false } },
+ );
+ expect(result.current.fixedMachineIds).toEqual(['personal-vm']);
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.resolveSubmission(choices)?.codeWorkspaces).toEqual(choices);
+ expect(
+ result.current.environments.find(({ environment }) => environment.id === 'runtime-vm')
+ ?.requiredBy,
+ ).toEqual([{ id: 'agent_primary', name: undefined }]);
+ rerender({ saved: true });
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.resolveSubmission(choices)?.codeWorkspaces).toEqual(choices);
+ });
+
+ it('offers an explicit saved-chat recovery target when the selected default disappears', () => {
+ const config = enableChoices();
+ config.statefulCodeSessions.environments = config.statefulCodeSessions.environments.filter(
+ ({ id }: { id: string }) => id !== 'personal-vm',
+ );
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },
+ })),
+ );
+ const selected = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }];
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(selected),
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ }),
+ );
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.transition).toMatchObject({
+ kind: 'move',
+ detachable: false,
+ from: selected,
+ });
+ expect(result.current.transition?.targets.map(({ environment }) => environment.id)).toEqual([
+ 'runtime-vm',
+ ]);
+ });
+
+ it('offers authorized alternatives without querying their status or blocking the default', () => {
+ enableChoices();
+ const { result } = renderHook(() => useCodeWorkspace(conversation()));
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.machineOptions?.map(({ id }) => id)).toEqual([
+ 'personal-vm',
+ 'runtime-vm',
+ ]);
+ expect(mockStatus).toHaveBeenLastCalledWith(['personal-vm'], true, {
+ notifyOnChangeProps: ['data', 'isLoading', 'isError'],
+ });
+ });
+
+ it('keeps two simultaneous chats independent and preserves the restored selection', () => {
+ enableChoices();
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: {
+ environmentId: id,
+ status: 'ready',
+ workspaces: [{ id: 'project-a', name: 'Project A' }],
+ },
+ })),
+ );
+ const selected = [{ environmentId: 'runtime-vm', workspaceId: 'project-a' }];
+ const first = renderHook(() => useCodeWorkspace(conversation(selected)));
+ const second = renderHook(() => useCodeWorkspace(conversation()));
+ expect(first.result.current.resolveSubmission()).toEqual({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: selected,
+ });
+ expect(second.result.current.selections?.[0].environmentId).toBe('personal-vm');
+ const restored = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(selected),
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ }),
+ );
+ expect(restored.result.current.canSubmit).toBe(true);
+ expect(restored.result.current.machineOptions).toBeUndefined();
+ });
+
+ it.each(['deployment', 'agent'])(
+ 'retains fixed binding when the %s opt-in is disabled',
+ (gate) => {
+ const config = enableChoices();
+ if (gate === 'deployment') config.statefulCodeSessions.allowEnvironmentSelection = false;
+ else mockAgentPermissions().agent.code_environment_ids = [];
+ const { result } = renderHook(() => useCodeWorkspace(conversation()));
+ expect(result.current.machineOptions).toBeUndefined();
+ expect(result.current.selections?.[0].environmentId).toBe('personal-vm');
+ },
+ );
+
+ it.each(['deployment', 'agent'])(
+ 'requires explicit recovery when the %s opt-in revokes a saved owned route',
+ (gate) => {
+ const config = enableChoices();
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: { environmentId: id, status: 'ready', workspaces: [{ id: 'project-a' }] },
+ })),
+ );
+ if (gate === 'deployment') config.statefulCodeSessions.allowEnvironmentSelection = false;
+ else mockAgentPermissions().agent.code_environment_ids = [];
+ const selected = [
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ { environmentId: 'runtime-vm', workspaceId: 'project-a', agentIds: ['agent_primary'] },
+ ];
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(selected),
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ }),
+ );
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.resolveSubmission(selected)).toBeUndefined();
+ expect(result.current.transition?.kind).toBe('move');
+ },
+ );
+
+ it('fails closed on inaccessible, unused or ambiguous non-default machines', () => {
+ const config = enableChoices();
+ mockAgentPermissions().agent.code_environment_ids.push('third-vm');
+ config.statefulCodeSessions.environments.push({
+ id: 'third-vm',
+ name: 'Third VM',
+ type: 'attached',
+ });
+ for (const selected of [
+ [{ environmentId: 'other-users-vm', workspaceId: 'primary' }],
+ [{ environmentId: 'unlisted-vm', workspaceId: 'primary' }],
+ [
+ { environmentId: 'runtime-vm', workspaceId: 'primary' },
+ { environmentId: 'third-vm', workspaceId: 'project-a' },
+ ],
+ [
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ { environmentId: 'runtime-vm', workspaceId: 'primary' },
+ ],
+ ]) {
+ const { result } = renderHook(() => useCodeWorkspace(conversation(selected)));
+ expect(result.current.canSubmit).toBe(false);
+ }
+ });
+
+ it('keeps child discovery available while graph choices are partial', () => {
+ const config = enableChoices();
+ config.statefulCodeSessions.environments.push(
+ { id: 'child-vm', name: 'Child', type: 'attached' },
+ { id: 'child-alternative', name: 'Child alternative', type: 'attached' },
+ );
+ mockAgentPermissions().agent.agent_ids = ['child'];
+ mockAgentsMap.mockReturnValue({
+ child: {
+ id: 'child',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'child-vm',
+ code_environment_ids: ['child-alternative'],
+ },
+ });
+ mockStatus.mockImplementation((ids: string[]) =>
+ ids.map((id) => ({
+ data: {
+ environmentId: id,
+ status: 'ready',
+ workspaces:
+ id === 'child-vm'
+ ? [
+ { id: 'one', name: 'One' },
+ { id: 'two', name: 'Two' },
+ ]
+ : [{ id: 'project-a', name: 'Project A' }],
+ },
+ })),
+ );
+ const selected = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }];
+ const { result, rerender } = renderHook(
+ ({ choices }) => useCodeWorkspace(conversation(choices)),
+ {
+ initialProps: { choices: selected },
+ },
+ );
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([
+ 'child-vm',
+ 'personal-vm',
+ ]);
+ expect(result.current.machineOptions?.map(({ id }) => id)).toEqual([
+ 'personal-vm',
+ 'runtime-vm',
+ 'child-vm',
+ 'child-alternative',
+ ]);
+ expect(result.current.machineOptionGroups).toEqual([
+ ['personal-vm', 'runtime-vm'],
+ ['child-vm', 'child-alternative'],
+ ]);
+ const choices = [
+ ...selected,
+ { environmentId: 'child-alternative', workspaceId: 'project-a' },
+ ];
+ rerender({ choices });
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.resolveSubmission(choices)?.codeWorkspaces).toEqual([
+ choices[1],
+ choices[0],
+ ]);
+ });
+
+ it('keeps recovery controls when an implicit attached default loses access to the chosen machine', () => {
+ const config = enableChoices();
+ config.statefulCodeSessions.environments[0].default = true;
+ config.statefulCodeSessions.environments = config.statefulCodeSessions.environments.filter(
+ ({ id }: { id: string }) => id !== 'runtime-vm',
+ );
+ delete mockAgentPermissions().agent.code_environment_id;
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ });
+ const selected = [{ environmentId: 'runtime-vm', workspaceId: 'primary' }];
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(selected),
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ }),
+ );
+ expect(result.current.required).toBe(true);
+ expect(result.current.visible).toBe(true);
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.environments[0].environment.id).toBe('personal-vm');
+ expect(result.current.transition).toMatchObject({
+ kind: 'move',
+ detachable: true,
+ from: selected,
+ });
+ });
+
+ it('offers a move-only recovery target after the agent revokes a saved alternative', () => {
+ enableChoices();
+ mockAgentPermissions().agent.code_environment_ids = [];
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ const selected = [{ environmentId: 'runtime-vm', workspaceId: 'primary' }];
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(selected),
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ }),
+ );
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.transition).toMatchObject({
+ kind: 'move',
+ detachable: false,
+ from: selected,
+ });
+ expect(result.current.transition?.targets.map(({ environment }) => environment.id)).toEqual([
+ 'personal-vm',
+ ]);
+ });
+
+ it('offers child alternatives even when the primary agent has a fixed machine', () => {
+ const config = enableChoices();
+ mockAgentPermissions().agent.code_environment_ids = [];
+ config.statefulCodeSessions.environments.push({
+ id: 'child-vm',
+ name: 'Child',
+ type: 'attached',
+ });
+ mockAgentPermissions().agent.agent_ids = ['child'];
+ mockAgentsMap.mockReturnValue({
+ child: {
+ id: 'child',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'child-vm',
+ code_environment_ids: ['runtime-vm'],
+ },
+ });
+ const { result } = renderHook(() => useCodeWorkspace(conversation()));
+ expect(result.current.machineOptions?.map(({ id }) => id)).toEqual([
+ 'runtime-vm',
+ 'child-vm',
+ ]);
+ expect(result.current.machineOptionGroups).toEqual([['child-vm', 'runtime-vm']]);
+ });
+
+ it('does not expose ignored choices for an implicit managed default alongside an attached child', () => {
+ const config = enableChoices();
+ config.statefulCodeSessions.environments[0].type = 'managed';
+ config.statefulCodeSessions.environments[0].default = true;
+ delete mockAgentPermissions().agent.code_environment_id;
+ config.statefulCodeSessions.environments.push({
+ id: 'child-vm',
+ name: 'Child',
+ type: 'attached',
+ });
+ mockAgentPermissions().agent.agent_ids = ['child'];
+ mockAgentsMap.mockReturnValue({
+ child: {
+ id: 'child',
+ stateful_code_sessions: true,
+ tools: [Tools.execute_code],
+ code_environment_id: 'child-vm',
+ },
+ });
+ const { result } = renderHook(() => useCodeWorkspace(conversation()));
+ expect(result.current.required).toBe(true);
+ expect(result.current.machineOptions).toBeUndefined();
+ expect(result.current.environments.map(({ environment }) => environment.id)).toEqual([
+ 'child-vm',
+ ]);
+ });
+ });
beforeEach(() => {
mockPreference.mockReset();
mockRememberPreference.mockReset();
diff --git a/client/src/hooks/Agents/codeDecision.ts b/client/src/hooks/Agents/codeDecision.ts
index 4b20cafba4..6897a28e36 100644
--- a/client/src/hooks/Agents/codeDecision.ts
+++ b/client/src/hooks/Agents/codeDecision.ts
@@ -1,4 +1,4 @@
-import { Constants } from 'librechat-data-provider';
+import { Constants, canonicalizeCodeWorkspaceSelections } from 'librechat-data-provider';
import type {
CodeEnvironmentMode,
EventSubmission,
@@ -12,10 +12,10 @@ function sameSelections(
): boolean {
if (!left?.length || !right?.length) return !left?.length && !right?.length;
if (left.length !== right.length) return false;
- const key = ({ environmentId, workspaceId }: CodeWorkspaceSelection) =>
- JSON.stringify([environmentId, workspaceId]);
- const held = new Set(left.map(key));
- return right.every((selection) => held.has(key(selection)));
+ return (
+ JSON.stringify(canonicalizeCodeWorkspaceSelections(left)) ===
+ JSON.stringify(canonicalizeCodeWorkspaceSelections(right))
+ );
}
/**
diff --git a/client/src/hooks/Agents/useCodeApprovalMode.ts b/client/src/hooks/Agents/useCodeApprovalMode.ts
index 1836784291..d94b0417a9 100644
--- a/client/src/hooks/Agents/useCodeApprovalMode.ts
+++ b/client/src/hooks/Agents/useCodeApprovalMode.ts
@@ -5,8 +5,15 @@ import {
isEphemeralAgentId,
getAllowedCodeApprovalModes,
CODE_APPROVAL_MODES,
+ resolveCodeEnvironmentSelection,
+} from 'librechat-data-provider';
+import type {
+ Agent,
+ TAgentsMap,
+ TConfig,
+ TPublicCodeEnvironment,
+ CodeWorkspaceSelection,
} from 'librechat-data-provider';
-import type { Agent, TAgentsMap, TConfig, TPublicCodeEnvironment } from 'librechat-data-provider';
import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
import { useCodeApprovalModePreference } from './codeApprovalPreference';
import useAgentToolPermissions from './useAgentToolPermissions';
@@ -45,8 +52,20 @@ export default function useCodeApprovalMode(
(agent) =>
agent.stateful_code_sessions === true && agent.tools?.includes(Tools.execute_code),
)
- .map((agent) => findExecutionEnvironment(agent, environments)),
- [environments, reachable],
+ .map((agent) =>
+ findExecutionEnvironment(
+ agent,
+ environments,
+ statefulCodeSessions?.allowEnvironmentSelection,
+ conversation?.codeWorkspaces,
+ ),
+ ),
+ [
+ environments,
+ reachable,
+ statefulCodeSessions?.allowEnvironmentSelection,
+ conversation?.codeWorkspaces,
+ ],
);
const attachedEnvironments = useMemo(
() =>
@@ -103,13 +122,76 @@ export default function useCodeApprovalMode(
return { available, modes, selected };
}
+/** The same per-agent eligibility gate is used for routing and draft discovery. Missing
+ * explicit defaults may recover to an allowed machine; managed defaults never opt in. */
+export function getCodeEnvironmentChoiceIds(
+ agent: Agent,
+ environments?: TPublicCodeEnvironment[],
+ allowEnvironmentSelection?: boolean,
+): string[] | undefined {
+ const defaultEnvironment = agent.code_environment_id
+ ? environments?.find((candidate) => candidate.id === agent.code_environment_id)
+ : environments?.find((candidate) => candidate.default === true);
+ if (
+ allowEnvironmentSelection !== true ||
+ !agent.code_environment_ids?.length ||
+ !(
+ defaultEnvironment?.type === 'attached' ||
+ (defaultEnvironment == null && Boolean(agent.code_environment_id))
+ )
+ ) {
+ return undefined;
+ }
+ return [
+ ...new Set([
+ agent.code_environment_id ?? defaultEnvironment?.id,
+ ...agent.code_environment_ids,
+ ]),
+ ].filter((id): id is string => id != null);
+}
+
export function findExecutionEnvironment(
agent: Agent,
environments?: TPublicCodeEnvironment[],
+ allowEnvironmentSelection?: boolean,
+ selections?: CodeWorkspaceSelection[],
): TPublicCodeEnvironment | undefined {
- return agent.code_environment_id
+ const defaultEnvironment = agent.code_environment_id
? environments?.find((candidate) => candidate.id === agent.code_environment_id)
: environments?.find((candidate) => candidate.default === true);
+ const allowSelection =
+ getCodeEnvironmentChoiceIds(agent, environments, allowEnvironmentSelection) != null;
+ const selection = resolveCodeEnvironmentSelection({
+ agentId: agent.id,
+ environmentId: agent.code_environment_id ?? defaultEnvironment?.id,
+ environmentIds: agent.code_environment_ids,
+ allowSelection,
+ selections,
+ });
+ if (!selection.valid) return undefined;
+ const resolved = selection.environmentId
+ ? environments?.find((candidate) => candidate.id === selection.environmentId)
+ : defaultEnvironment;
+ return allowSelection && resolved?.type !== 'attached' ? undefined : resolved;
+}
+
+/** Discovery can expose an authorized recovery target after a default disappears. This never
+ * admits execution: a saved chat must explicitly replace its sealed decision before using it. */
+export function findCodeWorkspaceDiscoveryEnvironment(
+ agent: Agent,
+ environments?: TPublicCodeEnvironment[],
+ allowEnvironmentSelection?: boolean,
+ selections?: CodeWorkspaceSelection[],
+): TPublicCodeEnvironment | undefined {
+ return (
+ findExecutionEnvironment(agent, environments, allowEnvironmentSelection, selections) ??
+ findExecutionEnvironment(agent, environments) ??
+ environments?.find(
+ ({ id, type }) =>
+ type === 'attached' &&
+ getCodeEnvironmentChoiceIds(agent, environments, allowEnvironmentSelection)?.includes(id),
+ )
+ );
}
export function collectReachableAgents(
diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts
index a1bd358d3a..c19fe6a6b2 100644
--- a/client/src/hooks/Agents/useCodeWorkspace.ts
+++ b/client/src/hooks/Agents/useCodeWorkspace.ts
@@ -4,6 +4,7 @@ import {
Tools,
isEphemeralAgentId,
isCodeWorkspaceSelections,
+ resolveCodeEnvironmentSelection,
} from 'librechat-data-provider';
import {
AgentCapabilities,
@@ -30,7 +31,12 @@ import {
useIsReplacingConversationCodeEnvironment,
useConversationCodeEnvironmentRecovery,
} from '~/data-provider';
-import { collectReachableAgents, findExecutionEnvironment } from './useCodeApprovalMode';
+import {
+ collectReachableAgents,
+ findExecutionEnvironment,
+ getCodeEnvironmentChoiceIds,
+ findCodeWorkspaceDiscoveryEnvironment,
+} from './useCodeApprovalMode';
import { useWorkspacePreferences } from './workspacePreferences';
import useAgentToolPermissions from './useAgentToolPermissions';
import useHasAccess from '~/hooks/Roles/useHasAccess';
@@ -50,6 +56,10 @@ export type CodeWorkspaceState =
export interface CodeWorkspaceEnvironmentResult {
environment: TPublicCodeEnvironment;
+ /** Coding agents whose execution requires this machine, including reachable subagents. */
+ requiredBy?: Array<{ id: string; name?: string | null }>;
+ /** Selectable agents whose binding must be retained when this target is explicitly moved. */
+ selectionOwners?: string[];
state: Exclude<CodeWorkspaceState, 'not_required' | 'relocatable'>;
workspaces: CodeWorkspaceDescriptor[];
selected?: CodeWorkspaceSelection;
@@ -97,6 +107,13 @@ export interface CodeWorkspaceResult {
* environment keeps it, so the state it is in stays visible and reversible. */
visible: boolean;
environments: CodeWorkspaceEnvironmentResult[];
+ /** Alternative machines are discovered on demand; an idle machine never blocks this chat. */
+ machineOptions?: TPublicCodeEnvironment[];
+ /** Each group belongs to one reachable coding agent, not the whole graph. */
+ machineOptionGroups?: string[][];
+ machineChoiceOwners?: Array<{ agentId: string; environmentIds: string[] }>;
+ /** Fixed graph targets must survive an alternative pick for a different agent. */
+ fixedMachineIds?: string[];
transition?: CodeWorkspaceTransition;
selections?: CodeWorkspaceSelection[];
resolveSelections: (
@@ -141,7 +158,7 @@ function resolveEnvironmentSelection({
}): CodeWorkspaceSelection | undefined {
if (status?.status !== 'ready' || status.environmentId !== environment.id) return undefined;
if (stored != null && workspaces.some(({ id }) => id === stored.workspaceId)) {
- return { environmentId: environment.id, workspaceId: stored.workspaceId };
+ return { ...stored, environmentId: environment.id };
}
if (!hasStoredSelections && workspaces.length === 1) {
return { environmentId: environment.id, workspaceId: workspaces[0].id };
@@ -198,15 +215,28 @@ export default function useCodeWorkspace(
const unique = new Map<string, TPublicCodeEnvironment>();
const defaults = new Map<string, Set<string>>();
const preferenceAgentIds = new Map<string, Set<string>>();
+ const requiredBy = new Map<string, Array<{ id: string; name?: string | null }>>();
let complete = true;
for (const agent of reachable.agents) {
if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {
continue;
}
- const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments);
- if (agent.code_environment_id && environment == null) complete = false;
+ const environment = findCodeWorkspaceDiscoveryEnvironment(
+ agent,
+ statefulCodeSessions?.environments,
+ statefulCodeSessions?.allowEnvironmentSelection,
+ conversation?.codeWorkspaces,
+ );
+ /** Discovery must remain available while a graph draft is partial or its sealed
+ * route needs recovery. Only final submission resolves the entire graph strictly. */
+ if (environment == null && agent.code_environment_id) {
+ complete = false;
+ }
if (environment?.type !== 'attached') continue;
unique.set(environment.id, environment);
+ const owners = requiredBy.get(environment.id) ?? [];
+ owners.push({ id: agent.id, name: agent.name });
+ requiredBy.set(environment.id, owners);
if (agent.code_environment_id === environment.id && agent.code_workspace_id) {
const choices = defaults.get(environment.id) ?? new Set<string>();
choices.add(agent.code_workspace_id);
@@ -224,7 +254,12 @@ export default function useCodeWorkspace(
if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {
continue;
}
- const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments);
+ const environment = findCodeWorkspaceDiscoveryEnvironment(
+ agent,
+ statefulCodeSessions?.environments,
+ statefulCodeSessions?.allowEnvironmentSelection,
+ conversation?.codeWorkspaces,
+ );
if (environment?.type !== 'attached') continue;
const owners = preferenceAgentIds.get(environment.id) ?? new Set<string>();
owners.add(rootAgentId);
@@ -235,6 +270,7 @@ export default function useCodeWorkspace(
complete,
defaults,
preferenceAgentIds,
+ requiredBy,
environments: [...unique.values()].sort((a, b) => a.id.localeCompare(b.id)),
};
}, [
@@ -242,9 +278,11 @@ export default function useCodeWorkspace(
addedConversation?.agent_id,
agentsMap,
conversation?.agent_id,
+ conversation?.codeWorkspaces,
primaryAgent,
reachable.agents,
statefulCodeSessions?.environments,
+ statefulCodeSessions?.allowEnvironmentSelection,
]);
const isAgentsConversation =
(conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents;
@@ -295,6 +333,41 @@ export default function useCodeWorkspace(
/** A new chat and a saved chat that never decided are both still choosing, so agent defaults, a
* remembered selection, and a sole workspace apply to each. */
const undecided = conversation != null && !locked;
+ const machineChoiceOwners =
+ required &&
+ supportsEnvironmentDecisions &&
+ statefulCodeSessions?.allowEnvironmentSelection === true
+ ? reachable.agents.flatMap((agent) => {
+ if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) {
+ return [];
+ }
+ const ids = getCodeEnvironmentChoiceIds(agent, statefulCodeSessions.environments, true);
+ return ids == null ? [] : [{ agentId: agent.id, environmentIds: ids }];
+ })
+ : undefined;
+ const machineOptionGroups = undecided
+ ? machineChoiceOwners?.map(({ environmentIds }) => environmentIds)
+ : undefined;
+ const machineOptions = machineOptionGroups?.length
+ ? statefulCodeSessions?.environments?.filter(
+ ({ id, type }) =>
+ type === 'attached' && machineOptionGroups.some((ids) => ids.includes(id)),
+ )
+ : undefined;
+ const fixedMachineIds = reachable.agents.flatMap((agent) => {
+ if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code))
+ return [];
+ if (
+ getCodeEnvironmentChoiceIds(
+ agent,
+ statefulCodeSessions?.environments,
+ statefulCodeSessions?.allowEnvironmentSelection,
+ ) != null
+ )
+ return [];
+ const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments);
+ return environment?.type === 'attached' ? [environment.id] : [];
+ });
const environmentResults = attachedEnvironments.map((environment, index) => {
const status = statuses[index];
const workspaces =
@@ -343,7 +416,17 @@ export default function useCodeWorkspace(
else if (selected != null) state = 'ready';
else if (stored != null) state = 'missing';
else if (workspaces.length === 0) state = 'unavailable';
- return { environment, state, workspaces, selected };
+ return {
+ environment,
+ state,
+ workspaces,
+ selected,
+ requiredBy: workspaceMetadata.requiredBy.get(environment.id),
+ selectionOwners: workspaceMetadata.requiredBy
+ .get(environment.id)
+ ?.filter(({ id }) => machineChoiceOwners?.some(({ agentId }) => agentId === id))
+ .map(({ id }) => id),
+ };
});
const resolveSelections = useCallback(
@@ -351,12 +434,9 @@ export default function useCodeWorkspace(
if (!required || !selectionMetadataComplete || !isCodeWorkspaceSelections(selections ?? [])) {
return undefined;
}
- /** A saved chat's decision is sealed as a whole: trimming a selection its agents no longer use
- * would submit a set the persisted decision rejects. */
- if (
- locked &&
- selections?.some(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))
- ) {
+ /** Never silently discard a machine the user picked. A sealed choice needs a transition;
+ * a draft choice not used by the graph must be corrected before it can execute elsewhere. */
+ if (selections?.some(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))) {
return undefined;
}
const resolved: CodeWorkspaceSelection[] = [];
@@ -374,6 +454,7 @@ export default function useCodeWorkspace(
resolved.push({
environmentId: result.environment.id,
workspaceId: requested.workspaceId,
+ ...(requested.agentIds == null ? {} : { agentIds: requested.agentIds }),
});
continue;
}
@@ -383,9 +464,35 @@ export default function useCodeWorkspace(
}
return undefined;
}
+ if (
+ statefulCodeSessions?.allowEnvironmentSelection === true &&
+ reachable.agents.some(
+ (agent) =>
+ agent.stateful_code_sessions === true &&
+ agent.tools?.includes(Tools.execute_code) &&
+ getCodeEnvironmentChoiceIds(agent, statefulCodeSessions.environments, true) != null &&
+ !resolveCodeEnvironmentSelection({
+ agentId: agent.id,
+ environmentId:
+ agent.code_environment_id ??
+ statefulCodeSessions.environments?.find(({ default: isDefault }) => isDefault)?.id,
+ environmentIds: agent.code_environment_ids,
+ allowSelection: true,
+ selections: resolved,
+ }).valid,
+ )
+ )
+ return undefined;
return resolved.sort((a, b) => a.environmentId.localeCompare(b.environmentId));
},
- [attachedEnvironmentIds, environmentResults, locked, required, selectionMetadataComplete],
+ [
+ attachedEnvironmentIds,
+ environmentResults,
+ required,
+ selectionMetadataComplete,
+ reachable.agents,
+ statefulCodeSessions,
+ ],
);
const selections = resolveSelections(storedSelections);
@@ -554,6 +661,10 @@ export default function useCodeWorkspace(
canSubmit,
visible,
environments: environmentResults,
+ machineOptions,
+ machineOptionGroups,
+ machineChoiceOwners,
+ fixedMachineIds,
transition,
selections,
resolveSelections,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 4f702f5192..f961fa280e 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -78,6 +78,13 @@
"com_ui_code_approval_mode": "Code approval mode",
"com_ui_code_workspace": "Code workspace",
"com_ui_code_workspace_choose": "Choose workspace",
+ "com_ui_code_workspace_required_for": "Choose a workspace for {{0}} on {{1}}.",
+ "com_ui_code_workspace_graph_requirement": "Every coding agent in this chat needs a workspace, including subagents.",
+ "com_ui_code_workspace_used_by": "Used by {{0}}",
+ "com_ui_code_environment_choice_limit": "Select up to {{0}} additional machines. The default machine is always allowed.",
+ "com_ui_code_environment_unavailable_choice": "Unavailable machine: {{0}} (uncheck to remove)",
+ "com_ui_code_workspace_agent_status": "{{0}} needs {{1}}: {{2}}",
+ "com_ui_code_workspace_graph_selection_conflict": "The selected machines do not match this agent's workspace requirements. Review the agents listed under each machine and select their required workspaces.",
"com_ui_code_workspace_loading": "Loading workspace…",
"com_ui_code_workspace_missing": "Workspace missing",
"com_ui_code_workspace_unavailable": "Workspace unavailable",
@@ -2740,6 +2747,10 @@
"com_ui_stateful_sessions": "Stateful code sessions",
"com_ui_stateful_code_environment": "Stateful environment",
"com_ui_code_environment": "Execution environment",
+ "com_ui_code_environment_per_chat": "Machines available in new chats",
+ "com_ui_code_environment_per_chat_info": "Choose the machines this agent may use. Each new chat can pick one of these machines if its user has access. The default and existing chats stay unchanged.",
+ "com_ui_code_environment_default_machine": "default",
+ "com_ui_code_environment_choose_machine": "Choose another machine",
"com_ui_code_environment_attached": "attached VM",
"com_ui_code_environment_deployment_default": "Deployment default",
"com_nav_info_code_environment": "Choose the managed runtime or attached VM that owns this workspace.",
diff --git a/e2e/byom/README.md b/e2e/byom/README.md
index c263501d60..507c931446 100644
--- a/e2e/byom/README.md
+++ b/e2e/byom/README.md
@@ -33,7 +33,7 @@ BYOM_WORKSPACE_TRANSITIONS=true BYOM_CODE_REPO=/absolute/path/to/code-interprete
This enables the decision protocol and attach/detach policy only in the disposable test app.
-The `Native Workspace Acceptance` workflow runs this transition variant on a hosted macOS
+The `Native Workspace Acceptance` workflow runs both variants on a hosted macOS
runner when the harness changes in a `dev` pull request. It pins the Code API/worker revision
and uses the native Seatbelt policy unchanged. It does not upload identities, raw logs or
browser state. This proves the macOS journey only; Linux and WSL2 require their own native run.
@@ -57,6 +57,30 @@ do not relax that policy to make the test pass.
8. Stopping B produces a persisted tool failure, not success or fallback to A.
9. Selecting **Full access** runs commands and physically creates a file without
approval prompts, survives reload, and can switch back to **Ask before changes**.
+10. Giving one agent an explicit additional-machine list lets new chats select worker B,
+ persist that choice across reload, and still start on default worker A in a separate chat.
+ Both chats read different physical files. An offline B never falls back to A.
+
+The disposable fixture enables `endpoints.agents.statefulCodeSessions.allowEnvironmentSelection`
+and the environment-decision protocol. Production deployments keep fixed-agent routing unless
+that opt-in is enabled and the agent has a nonempty `code_environment_ids` list. The default
+`code_environment_id` is implicitly allowed; every additional machine still requires the user's
+own access and current worker capabilities. This does not move an existing chat between machines.
+
+Each coding agent in the graph contributes its machine requirement, including lazy subagents.
+The composer identifies an unselected agent and machine beneath the picker, and each machine
+section lists its agents. Agents may share one selection when they explicitly allow that machine.
+Explicit choices record the choosing agents in `codeWorkspaces[].agentIds`, so Lia can use B
+while a fixed reviewer stays on A. Ownership survives persistence, reload and decision sealing.
+Legacy selections without ownership prefer the selected default; without it, exactly one
+permitted target must match. Independent fixed-machine requirements survive alternative picks.
+Update every API replica and refresh clients before enabling the opt-in: old validators reject
+ownership-bearing choices rather than silently rerouting them. The builder also permits removing
+saved machines that are no longer accessible, without blocking unrelated edits to the agent.
+
+`maxEnvironmentChoices` limits additional machines per agent (default 32, ceiling 128). The
+builder uses the same limit; create, update, duplicate and restore authorize all listed machines
+against the loaded principal-scoped config before reserving database references.
Assertions inspect **tool outputs**, not echoed arguments or the model's final prose.
The default hosted Code API URL is deliberately pointed at an invalid local route,
diff --git a/e2e/byom/native.spec.ts b/e2e/byom/native.spec.ts
index 8d2a83070b..8613ff8d9d 100644
--- a/e2e/byom/native.spec.ts
+++ b/e2e/byom/native.spec.ts
@@ -4,6 +4,7 @@ import { spawn } from 'node:child_process';
import { mkdir, open, readFile, readdir } from 'node:fs/promises';
import { expect, test } from '@playwright/test';
import type { ChildProcess } from 'node:child_process';
+import { readGenerationStatus } from './status.mjs';
import {
getAccessToken,
requestJson,
@@ -178,7 +179,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
token,
method: 'POST',
body: {
- name: `Native ${worker.environmentId}`,
+ name: 'Lia',
provider: 'Acceptance',
model: 'acceptance',
instructions: 'Run exactly the requested tool.',
@@ -243,6 +244,10 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
{ timeout: 45_000 },
)
.toBe(true);
+ /** Persistence can finish before the browser leaves /c/new. Starting another turn then
+ * would snapshot no old message IDs and mistake the preceding result for the new one. */
+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
+ await expect(page.getByTestId('stop-generation-button')).toBeHidden();
/** Never count echoed tool arguments or the deterministic model's final text as proof. */
const outputs =
result!.content?.flatMap((part) =>
@@ -259,10 +264,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
await expect
.poll(
async () => {
- const status = await requestJson<{ active: boolean }>(page, {
- path: `/api/agents/chat/status/${conversationId}`,
- token,
- });
+ const status = await generationStatus(conversationId);
return status.active;
},
{ timeout: 30_000 },
@@ -275,10 +277,17 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
return conversationId;
}
+ async function generationStatus(conversationId: string) {
+ const response = await page.request.get(`/api/agents/chat/status/${conversationId}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ return readGenerationStatus(response);
+ }
+
async function readDecision(conversationId: string) {
return requestJson<{
codeEnvironmentMode?: string;
- codeWorkspaces?: Array<{ environmentId: string; workspaceId: string }>;
+ codeWorkspaces?: Array<{ environmentId: string; workspaceId: string; agentIds?: string[] }>;
}>(page, { path: `/api/convos/${conversationId}`, token });
}
@@ -325,10 +334,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
await expect
.poll(
async () => {
- const status = await requestJson<{ active: boolean }>(page, {
- path: `/api/agents/chat/status/${streamId}`,
- token,
- });
+ const status = await generationStatus(streamId!);
return status.active;
},
{ timeout: 30_000 },
@@ -342,8 +348,10 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
expect(ordinaryDecision.codeEnvironmentMode).toBe('without_attached');
expect(ordinaryDecision.codeWorkspaces ?? []).toEqual([]);
await page.getByTestId('model-selector-button').click();
- await page.locator('#model-search').fill(`Native ${a.environmentId}`);
- await page.getByRole('option', { name: new RegExp(`Native ${a.environmentId}`) }).click();
+ await page.locator('#model-search').fill('Lia');
+ const codingOption = page.getByRole('option', { name: /^Lia\b/ });
+ await expect(codingOption).toBeVisible({ timeout: 30_000 });
+ await codingOption.click();
await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
await expect(page.getByTestId('code-workspace')).toContainText('No workspace');
expect(await chat('Continue without granting workspace access.')).toBe(conversationId);
@@ -351,9 +359,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
codeEnvironmentMode: 'without_attached',
});
await page.reload();
- await expect(page.getByTestId('model-selector-button')).toContainText(
- `Native ${a.environmentId}`,
- );
+ await expect(page.getByTestId('model-selector-button')).toContainText('Lia');
await expect(page.getByTestId('code-workspace')).toContainText('No workspace');
await page.getByTestId('code-workspace').click();
await page.getByRole('menuitem', { name: /^Attach / }).click();
@@ -437,15 +443,112 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
const b = await startWorker('b');
await select(b);
- expect(await turn('read')).toMatch(/could not be read|not found/i);
+ expect(await turn('read')).toMatch(/could not be read|not found|INVALID_PATH/i);
expect(await readdir(b.root)).not.toContain('proof.txt');
expect(await turn('create', 'Approve')).toContain('Created workspace/proof.txt');
expect(await readFile(path.join(b.root, 'proof.txt'), 'utf8')).toBe('native-original');
expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-edited');
+ /** One agent can start independent chats on only its explicitly permitted machines. */
+ const updated = await requestJson<{
+ id: string;
+ code_environment_id: string;
+ code_environment_ids: string[];
+ }>(page, {
+ path: `/api/agents/${coding.id}`,
+ token,
+ method: 'PATCH',
+ body: { code_environment_ids: [b.environmentId] },
+ });
+ expect(updated.code_environment_id).toBe(a.environmentId);
+ expect(updated.code_environment_ids).toEqual([b.environmentId]);
+ await page.goto(`/c/new?agent_id=${encodeURIComponent(coding.id)}`);
+ await expect(page.getByTestId('code-workspace')).toContainText('Acceptance a');
+ await page.getByTestId('code-workspace').click();
+ await page.getByRole('menuitem', { name: 'Acceptance b', exact: true }).click();
+ await page
+ .locator(`[data-code-environment-id="${b.environmentId}"]`)
+ .getByRole('menuitemradio', { name: /workspace/ })
+ .click();
+ await expect(page.getByTestId('code-workspace')).toContainText('Acceptance b');
+ selectedWorker = b;
+ expect(await turn('read')).toContain('native-original');
+ const runtimeChat = new URL(page.url()).pathname.slice(3);
+ expect((await readDecision(runtimeChat)).codeWorkspaces).toEqual([
+ { environmentId: b.environmentId, workspaceId: 'primary', agentIds: [coding.id] },
+ ]);
+ await page.reload();
+ expect((await readDecision(runtimeChat)).codeWorkspaces).toEqual([
+ { environmentId: b.environmentId, workspaceId: 'primary', agentIds: [coding.id] },
+ ]);
+ expect(await turn('read')).toContain('native-original');
+ await page.goto(`/c/new?agent_id=${encodeURIComponent(coding.id)}`);
+ await expect(page.getByTestId('code-workspace')).toContainText('Acceptance a');
+ selectedWorker = a;
+ expect(await turn('read')).toContain('native-edited');
+ const applicationChat = new URL(page.url()).pathname.slice(3);
+ expect(applicationChat).not.toBe(runtimeChat);
+ expect((await readDecision(applicationChat)).codeWorkspaces).toEqual([
+ { environmentId: a.environmentId, workspaceId: 'primary' },
+ ]);
+
+ /** A fixed lazy reviewer on A must not pull the primary's explicit choice of B back to A. */
+ const reviewer = await requestJson<{ id: string }>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name: 'PR Reviewer',
+ provider: 'Acceptance',
+ model: 'acceptance',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ stateful_code_environment: 'conversation',
+ code_environment_id: a.environmentId,
+ },
+ });
+ await requestJson(page, {
+ path: `/api/agents/${coding.id}`,
+ token,
+ method: 'PATCH',
+ body: { subagents: { enabled: true, allowSelf: false, agent_ids: [reviewer.id] } },
+ });
+ await page.goto(`/c/new?agent_id=${encodeURIComponent(coding.id)}`);
+ await page.getByTestId('code-workspace').click();
+ await page.getByRole('menuitem', { name: 'Acceptance b', exact: true }).click();
+ await page
+ .locator(`[data-code-environment-id="${b.environmentId}"]`)
+ .getByRole('menuitemradio', { name: /workspace/ })
+ .click();
+ await expect(page.getByTestId('code-workspace')).toContainText('2 code workspaces');
+ await page.getByTestId('code-workspace').click();
+ await expect(page.getByText('Used by PR Reviewer', { exact: true })).toBeVisible();
+ await expect(page.getByText('Used by Lia', { exact: true })).toBeVisible();
+ await page.keyboard.press('Escape');
+ selectedWorker = b;
+ expect(await turn('read')).toContain('native-original');
+ const graphChat = new URL(page.url()).pathname.slice(3);
+ const graphSelections = [
+ { environmentId: a.environmentId, workspaceId: 'primary' },
+ { environmentId: b.environmentId, workspaceId: 'primary', agentIds: [coding.id] },
+ ].sort((left, right) => left.environmentId.localeCompare(right.environmentId));
+ expect((await readDecision(graphChat)).codeWorkspaces).toEqual(graphSelections);
+ await page.reload();
+ expect(await turn('read')).toContain('native-original');
+ expect((await readDecision(graphChat)).codeWorkspaces).toEqual(graphSelections);
+ await requestJson(page, {
+ path: `/api/agents/${coding.id}`,
+ token,
+ method: 'PATCH',
+ body: { subagents: { enabled: false, allowSelf: false, agent_ids: [] } },
+ });
+ /** Return to the sealed runtime chat to exercise offline failure with no default fallback. */
+ await page.goto(`/c/${runtimeChat}`);
+ selectedWorker = b;
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
await stop(b.child);
const offline = await turn('offline', 'Approve');
- expect(offline).toMatch(/failed|offline|unavailable|could not|not ready/i);
+ expect(offline).toMatch(/failed|offline|unavailable|could not|not ready|ASSIGNMENT_EXPIRED/i);
expect(offline).not.toMatch(/Created workspace\/offline/);
expect(await readdir(a.root)).not.toContain('offline.txt');
expect(await readdir(b.root)).not.toContain('offline.txt');
@@ -461,6 +564,9 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
crossTurnEdit: true,
rejectedWriteAbsent: true,
twoWorkerIsolation: true,
+ sameAgentMachineAllowlist: true,
+ independentChatMachineSelections: true,
+ restoredMachineSelection: true,
offlineFailsClosed: true,
}),
contentType: 'application/json',
diff --git a/e2e/byom/run.mjs b/e2e/byom/run.mjs
index 7820b3d4b9..95f1cf7fe3 100644
--- a/e2e/byom/run.mjs
+++ b/e2e/byom/run.mjs
@@ -158,12 +158,13 @@ try {
cache: true,
endpoints: {
agents: {
- capabilities: ['tools', 'execute_code', 'stateful_code_sessions'],
+ capabilities: ['tools', 'execute_code', 'stateful_code_sessions', 'subagents'],
/** BYOM supplies the safe Ask baseline. The endpoint bypass permits a
* per-turn Accept edits selection without weakening command approvals. */
toolApproval: { enabled: true, mode: 'bypass' },
statefulCodeSessions: {
allowedEnvironments: ['conversation'],
+ allowEnvironmentSelection: true,
...(workspaceTransitions && {
conversationMoves: { enabled: true, allowAttachDetach: true },
}),
@@ -216,7 +217,7 @@ try {
CODEAPI_JWT_KID: 'acceptance',
CODEAPI_JWT_SINGLE_TENANT_ID: 'acceptance',
BYOM_ENROLLMENT_TOKEN: adminToken,
- ...(workspaceTransitions && { CODE_ENVIRONMENT_DECISION_VERSION: '1' }),
+ CODE_ENVIRONMENT_DECISION_VERSION: '1',
/** Deliberately unusable: accidental default routing must fail, never hit production. */
LIBRECHAT_CODE_BASEURL: `${appURL}/forbidden-default-codeapi`,
LIBRECHAT_CODE_BASEURL_STATEFUL: codeURL,
@@ -247,7 +248,7 @@ try {
appEnv,
root,
);
- await ready(appURL, app);
+ await ready(`${appURL}/readyz`, app);
await mkdir(path.join(runDir, 'workers'), { mode: 0o700 });
console.log(
`Native BYOM acceptance: ${appURL}; Code API ${codeURL}; Redis ${redisPort}; Mongo ${mongo.instanceInfo.port}`,
diff --git a/e2e/byom/status.mjs b/e2e/byom/status.mjs
new file mode 100644
index 0000000000..73ae1900c5
--- /dev/null
+++ b/e2e/byom/status.mjs
@@ -0,0 +1,10 @@
+/** A verified generation snapshot may temporarily be unavailable while terminal writes settle.
+ * Treat only the protocol's explicit readiness response as pending, never an arbitrary failure. */
+export async function readGenerationStatus(response) {
+ if (response.ok()) return response.json();
+ if (response.status() === 503) {
+ const body = await response.json().catch(() => null);
+ if (body?.code === 'SERVER_NOT_READY') return { active: true };
+ }
+ throw new Error(`Generation status request failed with HTTP ${response.status()}`);
+}
diff --git a/e2e/byom/status.test.mjs b/e2e/byom/status.test.mjs
new file mode 100644
index 0000000000..ca4c081cb7
--- /dev/null
+++ b/e2e/byom/status.test.mjs
@@ -0,0 +1,36 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readGenerationStatus } from './status.mjs';
+
+function response(status, body) {
+ return { ok: () => status === 200, status: () => status, json: async () => body };
+}
+
+test('waits through explicit generation readiness without claiming completion', async () => {
+ assert.deepEqual(await readGenerationStatus(response(503, { code: 'SERVER_NOT_READY' })), {
+ active: true,
+ });
+ assert.deepEqual(await readGenerationStatus(response(200, { active: false })), {
+ active: false,
+ });
+});
+
+test('does not hide an authorization failure or unrelated service error', async () => {
+ for (const status of [403, 404, 500, 503]) {
+ await assert.rejects(readGenerationStatus(response(status, { code: 'UNEXPECTED' })), {
+ message: `Generation status request failed with HTTP ${status}`,
+ });
+ }
+});
+
+test('does not retry an HTML gateway error as generation readiness', async () => {
+ await assert.rejects(
+ readGenerationStatus({
+ ...response(503),
+ json: async () => {
+ throw new SyntaxError('Not JSON');
+ },
+ }),
+ { message: 'Generation status request failed with HTTP 503' },
+ );
+});
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 226f3d5431..dd4669e625 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -772,6 +772,12 @@ endpoints:
# # "stateful_code_sessions" is highly experimental and may change substantially.
# # (optional) Limit the workspace scopes users may select. Omit to allow all three.
# statefulCodeSessions:
+ # # Let new chats choose an attached machine from their agent's explicit machine allowlist.
+ # # Keep false until ALL API replicas support this field, then refresh clients.
+ # # Omitted/false preserves agents' fixed machine bindings.
+ # allowEnvironmentSelection: false
+ # # Maximum additional machines per agent; default 32, supported ceiling 128.
+ # maxEnvironmentChoices: 32
# # Keep move-only behavior unless attach/detach is explicitly enabled.
# # Enable only after ALL API replicas run this build and advertise decision protocol 1
# # (CODE_ENVIRONMENT_DECISION_VERSION=1), then refresh clients.
diff --git a/packages/api/openapi/agents.openapi.json b/packages/api/openapi/agents.openapi.json
index df429025b7..1511c1ddd3 100644
--- a/packages/api/openapi/agents.openapi.json
+++ b/packages/api/openapi/agents.openapi.json
@@ -2124,6 +2124,14 @@
"type": "string",
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
},
+ "code_environment_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
+ },
+ "maxItems": 128
+ },
"code_workspace_id": {
"anyOf": [
{
@@ -2560,6 +2568,14 @@
],
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
},
+ "code_environment_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
+ },
+ "maxItems": 128
+ },
"code_workspace_id": {
"anyOf": [
{
@@ -3023,6 +3039,14 @@
],
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
},
+ "code_environment_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
+ },
+ "maxItems": 128
+ },
"code_workspace_id": {
"anyOf": [
{
diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts
index cab8387219..3fa37ae475 100644
--- a/packages/api/src/agents/__tests__/initialize.test.ts
+++ b/packages/api/src/agents/__tests__/initialize.test.ts
@@ -3615,6 +3615,67 @@ describe('initializeAgent — execute_code capability expansion', () => {
}
});
+ it('routes a restored machine selection before file priming and tool discovery', async () => {
+ const { agent, req, res, loadTools, db } = createMocks();
+ agent.tools = ['execute_code'];
+ agent.stateful_code_sessions = true;
+ agent.code_environment_id = 'application-vm';
+ agent.code_environment_ids = ['runtime-vm'];
+ req.config = {
+ endpoints: {
+ agents: {
+ statefulCodeSessions: {
+ allowEnvironmentSelection: true,
+ environments: ['application-vm', 'runtime-vm'].map((id) => ({
+ id,
+ name: id,
+ type: 'attached',
+ owner: 'deployment',
+ baseURL: `https://${id}.example.com/v1`,
+ workerId: `worker-${id}`,
+ })),
+ },
+ },
+ },
+ } as NonNullable<typeof req.config>;
+ req.resolvedConversation = {
+ conversationId: 'chat-runtime',
+ codeWorkspaces: [
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ { environmentId: 'runtime-vm', workspaceId: 'primary', agentIds: [agent.id] },
+ ],
+ };
+ const result = await initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ conversationId: 'chat-runtime',
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ codeEnvAvailable: true,
+ statefulSessionsAvailable: true,
+ requestBody: {
+ codeWorkspaces: [{ environmentId: 'application-vm', workspaceId: 'primary' }],
+ },
+ },
+ db,
+ );
+ expect(loadTools).toHaveBeenCalledWith(
+ expect.objectContaining({
+ codeExecutionContext: expect.objectContaining({
+ environmentId: 'runtime-vm',
+ baseUrl: 'https://runtime-vm.example.com/v1',
+ bridgeWorkerId: 'worker-runtime-vm',
+ }),
+ }),
+ );
+ expect(result.codeExecutionContext?.environmentId).toBe('runtime-vm');
+ expect(agent.code_environment_id).toBe('application-vm');
+ });
+
it.each([false, true])(
'uses the validated attached workspace operation ceiling: protectedEdit=%s',
async (protectedEdit) => {
diff --git a/packages/api/src/agents/execution.spec.ts b/packages/api/src/agents/execution.spec.ts
index bc8b7bacba..7bb33d67ba 100644
--- a/packages/api/src/agents/execution.spec.ts
+++ b/packages/api/src/agents/execution.spec.ts
@@ -1,6 +1,7 @@
import winston from 'winston';
import { Writable } from 'node:stream';
import { logger } from '@librechat/data-schemas';
+import type { Agent, TConversation } from 'librechat-data-provider';
import type { CodeExecutionContext } from './execution';
import {
assertCodeExecutionApprovalBinding,
@@ -9,14 +10,206 @@ import {
codeExecutionHeaders,
getCodeWorkspaceSelections,
resolveCodeExecutionContext,
+ resolveCodeExecutionWorkspaceSelections,
} from './execution';
+import { CodeWorkspaceSelectionError } from '~/code/errors';
+import { loadAddedAgent } from './added';
jest.mock('@librechat/agents', () => ({
+ ...jest.requireActual('@librechat/agents'),
Constants: { EXECUTE_CODE: 'execute_code' },
getCodeBaseURL: jest.fn(() => 'http://code-default.test/v1///'),
}));
+describe('resolveCodeExecutionWorkspaceSelections', () => {
+ it('keeps persisted choices and empty sets authoritative over request overrides', () => {
+ const requested = [{ environmentId: 'runtime-vm', workspaceId: 'runtime' }];
+ const persisted = [{ environmentId: 'application-vm', workspaceId: 'app' }];
+ expect(
+ resolveCodeExecutionWorkspaceSelections({
+ conversation: { codeWorkspaces: persisted },
+ request: { codeWorkspaces: requested },
+ }),
+ ).toBe(persisted);
+ expect(
+ resolveCodeExecutionWorkspaceSelections({
+ conversation: { codeWorkspaces: [] },
+ request: { codeWorkspaces: requested },
+ }),
+ ).toEqual([]);
+ expect(
+ resolveCodeExecutionWorkspaceSelections({ request: { codeWorkspaces: requested } }),
+ ).toBe(requested);
+ expect(resolveCodeExecutionWorkspaceSelections({})).toBeUndefined();
+ });
+});
+
describe('resolveCodeExecutionContext', () => {
+ describe('per-chat attached machines', () => {
+ const environments = ['application-vm', 'runtime-vm'].map((id) => ({
+ id,
+ name: id,
+ type: 'attached' as const,
+ owner: 'deployment' as const,
+ baseURL: `https://${id}.example.com/v1`,
+ workerId: `worker-${id}`,
+ configSchema: {
+ permissions: {
+ commandExecution: { allowed: ['ask' as const, 'deny' as const], default: 'ask' as const },
+ },
+ },
+ settings: {
+ permissions: {
+ commandExecution: id === 'runtime-vm' ? ('deny' as const) : ('ask' as const),
+ },
+ },
+ }));
+ const params = {
+ statefulSessions: true,
+ environmentId: 'application-vm',
+ environments,
+ userId: 'user-1',
+ agentId: 'lia',
+ conversationId: 'chat-runtime',
+ allowEnvironmentSelection: true,
+ environmentIds: ['runtime-vm'],
+ workspaceSelections: [{ environmentId: 'runtime-vm', workspaceId: 'primary' }],
+ };
+
+ it('keeps the owned route after the real added-agent loader assigns its runtime suffix', async () => {
+ const added = await loadAddedAgent(
+ { req: {}, conversation: { agent_id: 'agent_lia' } as TConversation },
+ {
+ getAgent: async () => ({ id: 'agent_lia' }) as Agent,
+ getMCPServerTools: jest.fn(),
+ },
+ );
+ expect(added?.id).toBe('agent_lia____1');
+ expect(
+ resolveCodeExecutionContext({
+ ...params,
+ agentId: added?.id,
+ workspaceSelections: [
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ { environmentId: 'runtime-vm', workspaceId: 'primary', agentIds: ['agent_lia'] },
+ ],
+ }).environmentId,
+ ).toBe('runtime-vm');
+ });
+
+ it.each([false, true])('rejects revoked owned routes when allowSelection=%s', (enabled) => {
+ expect(() =>
+ resolveCodeExecutionContext({
+ ...params,
+ allowEnvironmentSelection: enabled,
+ environmentIds: [],
+ workspaceSelections: [
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ { environmentId: 'runtime-vm', workspaceId: 'primary', agentIds: ['lia'] },
+ ],
+ }),
+ ).toThrow(CodeWorkspaceSelectionError);
+ });
+
+ it('uses explicit ownership for a primary alternative without moving its fixed reviewer', () => {
+ const choices = [
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ { environmentId: 'runtime-vm', workspaceId: 'primary', agentIds: ['lia'] },
+ ];
+ expect(
+ resolveCodeExecutionContext({ ...params, workspaceSelections: choices }).environmentId,
+ ).toBe('runtime-vm');
+ expect(
+ resolveCodeExecutionContext({
+ ...params,
+ agentId: 'reviewer',
+ environmentIds: undefined,
+ workspaceSelections: choices,
+ }).environmentId,
+ ).toBe('application-vm');
+ });
+
+ it('routes the same agent independently per chat, including policy and session partitions', () => {
+ const runtime = resolveCodeExecutionContext(params);
+ const application = resolveCodeExecutionContext({
+ ...params,
+ conversationId: 'chat-application',
+ workspaceSelections: [{ environmentId: 'application-vm', workspaceId: 'primary' }],
+ });
+ expect(runtime).toMatchObject({
+ environmentId: 'runtime-vm',
+ bridgeWorkerId: 'worker-runtime-vm',
+ baseUrl: 'https://runtime-vm.example.com/v1',
+ codeEnvironmentSettings: environments[1].settings,
+ });
+ expect(application.environmentId).toBe('application-vm');
+ expect(application.codeEnvironmentSettings?.permissions?.commandExecution).toBe('ask');
+ expect(runtime.codeEnvironmentSettings?.permissions?.commandExecution).toBe('deny');
+ expect(runtime.executionRouteKey).not.toBe(application.executionRouteKey);
+ expect(runtime.codeSessionKey).not.toBe(application.codeSessionKey);
+ expect(runtime.conversationWorkspaceInstanceId).not.toBe(
+ application.conversationWorkspaceInstanceId,
+ );
+ });
+
+ it.each(['allowEnvironmentSelection', 'environmentIds'] as const)(
+ 'retains fixed routing when %s is disabled',
+ (gate) => {
+ expect(
+ resolveCodeExecutionContext({
+ ...params,
+ ...(gate === 'allowEnvironmentSelection'
+ ? { allowEnvironmentSelection: false }
+ : { environmentIds: [] }),
+ }).environmentId,
+ ).toBe('application-vm');
+ },
+ );
+
+ it('rejects routes outside the authorized config instead of falling back', () => {
+ expect(() =>
+ resolveCodeExecutionContext({ ...params, environments: [environments[0]] }),
+ ).toThrow(CodeWorkspaceSelectionError);
+ });
+
+ it('preserves the selected default when another graph agent needs an allowed alternative', () => {
+ expect(
+ resolveCodeExecutionContext({
+ ...params,
+ workspaceSelections: [
+ ...params.workspaceSelections,
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ ],
+ }).environmentId,
+ ).toBe('application-vm');
+ });
+
+ it('rejects ambiguous non-default selections and attempts to select managed execution', () => {
+ expect(() =>
+ resolveCodeExecutionContext({
+ ...params,
+ workspaceSelections: [
+ ...params.workspaceSelections,
+ { environmentId: 'application-vm', workspaceId: 'primary' },
+ ],
+ environmentId: 'missing-default',
+ environmentIds: ['application-vm', 'runtime-vm'],
+ }),
+ ).toThrow('The selected attached workspace is invalid.');
+ expect(() =>
+ resolveCodeExecutionContext({
+ ...params,
+ environments: [environments[0], { ...environments[1], type: 'managed' }],
+ }),
+ ).toThrow('does not advertise selectable workspaces');
+ });
+
+ it('can choose another authorized machine when the old default has disappeared', () => {
+ expect(
+ resolveCodeExecutionContext({ ...params, environments: [environments[1]] }).environmentId,
+ ).toBe('runtime-vm');
+ });
+ });
const originalStatefulUrl = process.env.LIBRECHAT_CODE_BASEURL_STATEFUL;
afterEach(() => {
@@ -569,6 +762,14 @@ describe('stateful code approval target binding', () => {
{ environmentId: 'environment-a', workspaceId: 'project-a' },
]);
});
+
+ it('retains graph ownership when removing live workspace capabilities', () => {
+ const owned = context();
+ owned.codeWorkspace!.agentIds = ['agent-a'];
+ expect(getCodeWorkspaceSelections([owned])).toEqual([
+ { environmentId: 'environment-a', workspaceId: 'project-a', agentIds: ['agent-a'] },
+ ]);
+ });
});
describe('codeExecutionAuthHeaders', () => {
diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.ts
index dac98f3470..f3441b3a04 100644
--- a/packages/api/src/agents/execution.ts
+++ b/packages/api/src/agents/execution.ts
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
import { logger } from '@librechat/data-schemas';
import { Constants, getCodeBaseURL } from '@librechat/agents';
+import { resolveCodeEnvironmentSelection } from 'librechat-data-provider';
import type {
Agents,
CodeWorkspaceOperation,
@@ -12,10 +13,23 @@ import type {
TAgentsEndpoint,
} from 'librechat-data-provider';
import type { WorkspaceEditFileFeature } from '~/code/edits';
+import { CodeWorkspaceSelectionError } from '~/code/errors';
export const CODE_API_EXPECTED_PROFILE_HEADER = 'X-CodeAPI-Expected-Profile';
export const CODE_API_BRIDGE_WORKER_HEADER = 'X-LibreChat-Code-Worker-ID';
+/** Persisted choices are authoritative, including an empty set. All execution ingresses share
+ * this precedence so a request cannot replace an admitted conversation's machine selection. */
+export function resolveCodeExecutionWorkspaceSelections({
+ conversation,
+ request,
+}: {
+ conversation?: { codeWorkspaces?: unknown } | null;
+ request?: { codeWorkspaces?: unknown } | null;
+}): unknown {
+ return conversation?.codeWorkspaces ?? request?.codeWorkspaces;
+}
+
export type CodeExecutionProfile = 'default' | 'stateful';
export type CodeEnvironmentConfig = NonNullable<
NonNullable<TAgentsEndpoint['statefulCodeSessions']>['environments']
@@ -78,6 +92,7 @@ export function getCodeWorkspaceSelections(
selections.set(workspace.environmentId, {
environmentId: workspace.environmentId,
workspaceId: workspace.workspaceId,
+ ...(workspace.agentIds == null ? {} : { agentIds: [...workspace.agentIds] }),
});
}
if (selections.size === 0) return undefined;
@@ -302,19 +317,20 @@ function resolveRuntimeSessionHint(params: {
return `${prefix}:user:${scopeFingerprint(userId)}`;
}
+function isExecutableEnvironment(environment: CodeEnvironmentConfig): boolean {
+ return !(
+ environment.pairing?.allowPrincipalWorkers === true &&
+ environment.pairing.workerId == null &&
+ environment.workerId == null
+ );
+}
+
function resolveConfiguredEnvironment(params: {
environmentId?: string | null;
environments?: readonly CodeEnvironmentConfig[];
}): CodeEnvironmentConfig | undefined {
const { environmentId, environments } = params;
- const executableEnvironments = environments?.filter(
- (environment) =>
- !(
- environment.pairing?.allowPrincipalWorkers === true &&
- environment.pairing.workerId == null &&
- environment.workerId == null
- ),
- );
+ const executableEnvironments = environments?.filter(isExecutableEnvironment);
if (environmentId) {
const configured = executableEnvironments?.find(
(environment) => environment.id === environmentId,
@@ -335,6 +351,10 @@ export function resolveCodeExecutionContext(params: {
userId?: string | null;
agentId?: string | null;
conversationId?: string | null;
+ /** Deployment ceiling and the persisted agent machine allowlist are both required. */
+ allowEnvironmentSelection?: boolean;
+ environmentIds?: readonly string[];
+ workspaceSelections?: unknown;
}): CodeExecutionContext {
if (!params.statefulSessions) {
return {
@@ -346,7 +366,39 @@ export function resolveCodeExecutionContext(params: {
}
const environment = normalizeStatefulCodeEnvironment(params.environment);
- const configuredEnvironment = resolveConfiguredEnvironment(params);
+ const defaultEnvironment = params.environments?.find(
+ (candidate) =>
+ isExecutableEnvironment(candidate) &&
+ (params.environmentId ? candidate.id === params.environmentId : candidate.default === true),
+ );
+ const allowSelection =
+ params.allowEnvironmentSelection === true &&
+ (params.environmentIds?.length ?? 0) > 0 &&
+ (defaultEnvironment?.type === 'attached' ||
+ (defaultEnvironment == null && Boolean(params.environmentId)));
+ const selection = resolveCodeEnvironmentSelection({
+ agentId: params.agentId,
+ environmentId: params.environmentId ?? defaultEnvironment?.id,
+ environmentIds: params.environmentIds,
+ allowSelection,
+ selections: params.workspaceSelections,
+ });
+ if (!selection.valid) throw new CodeWorkspaceSelectionError('invalid');
+ if (
+ allowSelection &&
+ !params.environments?.some(
+ (candidate) => candidate.id === selection.environmentId && isExecutableEnvironment(candidate),
+ )
+ ) {
+ throw new CodeWorkspaceSelectionError('invalid');
+ }
+ const configuredEnvironment = resolveConfiguredEnvironment({
+ ...params,
+ environmentId: selection.environmentId,
+ });
+ if (allowSelection && configuredEnvironment?.type !== 'attached') {
+ throw new CodeWorkspaceSelectionError('unsupported');
+ }
if (!params.userId) {
throw new Error('Stateful code environments require an authenticated user ID.');
}
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 4ee56c8f96..63b0f19ae8 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -76,6 +76,7 @@ import {
import {
normalizeStatefulCodeEnvironment,
resolveCodeExecutionContext,
+ resolveCodeExecutionWorkspaceSelections,
type CodeEnvironmentConfig,
type CodeExecutionContext,
} from './execution';
@@ -1585,6 +1586,13 @@ export async function initializeAgent(
statefulSessions: effectiveStatefulSessions,
environment: statefulCodeEnvironment,
environmentId: agent.code_environment_id,
+ environmentIds: agent.code_environment_ids,
+ allowEnvironmentSelection:
+ appConfig?.endpoints?.agents?.statefulCodeSessions?.allowEnvironmentSelection,
+ workspaceSelections: resolveCodeExecutionWorkspaceSelections({
+ conversation: runtime.resolvedConversation,
+ request: requestBody,
+ }),
environments: configuredCodeEnvironments,
userId: requestFileOwnerId,
agentId: agent.id,
diff --git a/packages/api/src/agents/lazySubagents.ts b/packages/api/src/agents/lazySubagents.ts
index aa24824513..50e1ac20e7 100644
--- a/packages/api/src/agents/lazySubagents.ts
+++ b/packages/api/src/agents/lazySubagents.ts
@@ -23,6 +23,7 @@ type VersionedAgent = Pick<
| 'stateful_code_sessions'
| 'stateful_code_environment'
| 'code_environment_id'
+ | 'code_environment_ids'
| 'git_identity'
| 'artifacts'
| 'recursion_limit'
@@ -96,6 +97,7 @@ export function selectLazySubagentConfig(agent: VersionedAgent): Omit<VersionedA
stateful_code_sessions,
stateful_code_environment,
code_environment_id,
+ code_environment_ids,
git_identity,
artifacts,
recursion_limit,
@@ -129,6 +131,7 @@ export function selectLazySubagentConfig(agent: VersionedAgent): Omit<VersionedA
stateful_code_sessions,
stateful_code_environment,
code_environment_id,
+ code_environment_ids,
git_identity,
artifacts,
recursion_limit,
diff --git a/packages/api/src/agents/management.spec.ts b/packages/api/src/agents/management.spec.ts
index a2fadc8059..01939c853e 100644
--- a/packages/api/src/agents/management.spec.ts
+++ b/packages/api/src/agents/management.spec.ts
@@ -54,6 +54,23 @@ describe('Agent Management contract', () => {
).toBe(false);
});
describe('inputs', () => {
+ it('round-trips the explicit machine allowlist through management create, update and response', () => {
+ const code_environment_ids = ['machine-a', 'machine-b'];
+ expect(
+ agentManagementCreateSchema.parse({
+ provider: 'openAI',
+ model: 'gpt-5',
+ code_environment_ids,
+ }),
+ ).toMatchObject({ code_environment_ids });
+ expect(agentManagementUpdateSchema.parse({ code_environment_ids: [] })).toEqual({
+ code_environment_ids: [],
+ });
+ expect(
+ projectAgentManagementResponse({ ...persistedAgent, code_environment_ids })
+ .code_environment_ids,
+ ).toEqual(code_environment_ids);
+ });
it('keeps create and update fields aligned with the browser Agent validators', () => {
expect(
agentManagementCreateSchema.parse({
diff --git a/packages/api/src/agents/management.ts b/packages/api/src/agents/management.ts
index 1573243b5e..306b17aa79 100644
--- a/packages/api/src/agents/management.ts
+++ b/packages/api/src/agents/management.ts
@@ -282,6 +282,7 @@ export function projectAgentManagementResponse(
stateful_code_sessions: source.stateful_code_sessions,
stateful_code_environment: source.stateful_code_environment,
code_environment_id: source.code_environment_id,
+ code_environment_ids: source.code_environment_ids,
code_workspace_id: source.code_workspace_id,
repositoryInstructions: source.repositoryInstructions,
git_identity: source.git_identity,
diff --git a/packages/api/src/agents/validation.spec.ts b/packages/api/src/agents/validation.spec.ts
index 8b3a75637e..66f6ea4806 100644
--- a/packages/api/src/agents/validation.spec.ts
+++ b/packages/api/src/agents/validation.spec.ts
@@ -349,6 +349,27 @@ describe('agentCreateSchema with subagents', () => {
});
describe('stateful code environments', () => {
+ it('rejects a machine list above the wire safety ceiling before any persistence', () => {
+ expect(
+ agentUpdateSchema.safeParse({
+ code_environment_ids: Array.from({ length: 129 }, (_, i) => `machine-${i}`),
+ }).success,
+ ).toBe(false);
+ });
+ it.each([{ value: ['machine-a', 'machine-b'] }, { value: [] }])(
+ 'accepts an explicit machine allowlist of $value',
+ ({ value }) => {
+ expect(agentUpdateSchema.parse({ code_environment_ids: value })).toEqual({
+ code_environment_ids: value,
+ });
+ },
+ );
+ it.each([{ value: true }, { value: ['bad/path'] }, { value: [1] }])(
+ 'rejects malformed machine allowlists',
+ ({ value }) => {
+ expect(agentUpdateSchema.safeParse({ code_environment_ids: value }).success).toBe(false);
+ },
+ );
it.each(['user', 'agent-user', 'conversation'])('accepts %s', (environment) => {
const result = agentCreateSchema.safeParse({
provider: 'openAI',
diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.ts
index 49ada6e212..ca7965fb22 100644
--- a/packages/api/src/agents/validation.ts
+++ b/packages/api/src/agents/validation.ts
@@ -1,6 +1,7 @@
import { z } from 'zod';
import {
CODE_WORKSPACE_ID_PATTERN,
+ MAX_AGENT_CODE_ENVIRONMENT_CHOICES,
MemoryScope,
SkillsScope,
getMaxSubagents,
@@ -415,6 +416,9 @@ export const agentSubagentsSchema: z.ZodOptional<z.ZodType<AgentSubagentsConfig>
/** Base agent schema with all common fields */
const agentCodeEnvironmentIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/);
+const agentCodeEnvironmentIdsSchema: z.ZodArray<z.ZodString> = z
+ .array(agentCodeEnvironmentIdSchema)
+ .max(MAX_AGENT_CODE_ENVIRONMENT_CHOICES);
const agentGitIdentityUpdateSchema: z.ZodType<AgentGitIdentity | null | undefined> =
agentGitIdentitySchema.nullable();
@@ -507,6 +511,7 @@ export const agentBaseSchema: z.ZodObject<
stateful_code_sessions: z.ZodOptional<z.ZodBoolean>;
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
code_environment_id: z.ZodOptional<z.ZodString>;
+ code_environment_ids: z.ZodOptional<typeof agentCodeEnvironmentIdsSchema>;
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
repositoryInstructions: z.ZodOptional<z.ZodEnum<['prefer', 'defer', 'off']>>;
git_identity: typeof agentGitIdentitySchema;
@@ -585,6 +590,7 @@ export const agentBaseSchema: z.ZodObject<
stateful_code_sessions: z.boolean().optional(),
stateful_code_environment: z.enum(['user', 'agent-user', 'conversation']).optional(),
code_environment_id: agentCodeEnvironmentIdSchema.optional(),
+ code_environment_ids: agentCodeEnvironmentIdsSchema.optional(),
code_workspace_id: agentCodeWorkspaceIdSchema.optional(),
repositoryInstructions: z.enum(['prefer', 'defer', 'off']).optional(),
git_identity: agentGitIdentitySchema,
@@ -686,6 +692,7 @@ export const agentCreateSchema: z.ZodObject<
stateful_code_sessions: z.ZodOptional<z.ZodBoolean>;
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
code_environment_id: z.ZodOptional<z.ZodString>;
+ code_environment_ids: z.ZodOptional<typeof agentCodeEnvironmentIdsSchema>;
git_identity: typeof agentGitIdentitySchema;
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
repositoryInstructions: z.ZodOptional<z.ZodEnum<['prefer', 'defer', 'off']>>;
@@ -823,6 +830,7 @@ export const agentUpdateSchema: z.ZodObject<
stateful_code_sessions: z.ZodOptional<z.ZodBoolean>;
stateful_code_environment: z.ZodOptional<z.ZodEnum<['user', 'agent-user', 'conversation']>>;
code_environment_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
+ code_environment_ids: z.ZodOptional<typeof agentCodeEnvironmentIdsSchema>;
code_workspace_id: z.ZodOptional<typeof agentCodeWorkspaceIdSchema>;
repositoryInstructions: z.ZodOptional<z.ZodEnum<['prefer', 'defer', 'off']>>;
git_identity: typeof agentGitIdentityUpdateSchema;
diff --git a/packages/api/src/agents/workspace.spec.ts b/packages/api/src/agents/workspace.spec.ts
index 81f3f1a949..10d0b0a889 100644
--- a/packages/api/src/agents/workspace.spec.ts
+++ b/packages/api/src/agents/workspace.spec.ts
@@ -4,6 +4,8 @@ import {
reconcileAgentWorkspaceDefault,
resolveAgentWorkspaceRestoreConfiguration,
validateAgentWorkspaceDefaultBinding,
+ validateAgentCodeEnvironmentAllowlist,
+ validateStatefulCodeEnvironment,
} from './workspace';
describe('restored agent workspace configuration', () => {
@@ -23,6 +25,7 @@ describe('restored agent workspace configuration', () => {
stateful_code_environment: 'conversation',
code_environment_id: undefined,
code_workspace_id: undefined,
+ code_environment_ids: undefined,
});
expect(isActiveAgentWorkspaceConfiguration(restored)).toBe(true);
});
@@ -46,6 +49,7 @@ describe('restored agent workspace configuration', () => {
stateful_code_environment: 'user',
code_environment_id: 'removed-vm',
code_workspace_id: 'project-a',
+ code_environment_ids: undefined,
});
expect(isActiveAgentWorkspaceConfiguration(restored)).toBe(false);
});
@@ -83,6 +87,85 @@ describe('reconcileAgentWorkspaceDefault', () => {
});
});
+describe('agent machine allowlist authorization', () => {
+ const req = (maximum = 32) =>
+ ({
+ config: {
+ endpoints: {
+ agents: {
+ statefulCodeSessions: {
+ maxEnvironmentChoices: maximum,
+ environments: [
+ { id: 'authorized', type: 'attached', baseURL: 'https://code.test' },
+ { id: 'managed', type: 'managed' },
+ { id: 'control-plane', type: 'attached', pairing: { allowPrincipalWorkers: true } },
+ ],
+ },
+ },
+ },
+ },
+ }) as Parameters<typeof validateAgentCodeEnvironmentAllowlist>[0];
+ let res: Parameters<typeof validateAgentCodeEnvironmentAllowlist>[1];
+ let json: jest.Mock;
+ let status: jest.Mock;
+ beforeEach(() => {
+ json = jest.fn();
+ status = jest.fn(() => ({ json }));
+ res = { status } as unknown as typeof res;
+ });
+ it('authorizes each additional machine with the loaded principal-scoped config', () => {
+ expect(validateAgentCodeEnvironmentAllowlist(req(), res, ['authorized'])).toBe(true);
+ expect(status).not.toHaveBeenCalled();
+ });
+ it.each(['another-principals-machine', 'managed', 'control-plane'])(
+ 'refuses %s before reservations even without a default or active sessions',
+ (id) => {
+ expect(
+ validateStatefulCodeEnvironment(
+ req(),
+ res,
+ false,
+ undefined,
+ undefined,
+ false,
+ undefined,
+ undefined,
+ undefined,
+ [id],
+ ),
+ ).toBe(false);
+ expect(status).toHaveBeenCalledWith(403);
+ },
+ );
+ it('enforces the deployment limit before scanning any candidate IDs', () => {
+ expect(validateAgentCodeEnvironmentAllowlist(req(1), res, ['authorized', 'missing'])).toBe(
+ false,
+ );
+ expect(status).toHaveBeenCalledWith(400);
+ expect(json).toHaveBeenCalledWith({
+ error: 'Agent machine choices exceed the configured maximum of 1',
+ });
+ });
+ it('allows removing choices and unrelated edits without reauthorizing inaccessible stored choices', () => {
+ expect(validateAgentCodeEnvironmentAllowlist(req(), res, [])).toBe(true);
+ expect(validateAgentCodeEnvironmentAllowlist(req(), res, undefined)).toBe(true);
+ });
+ it('restores a version list instead of inheriting current machine privileges', () => {
+ expect(
+ resolveAgentWorkspaceRestoreConfiguration({
+ version: { code_environment_ids: ['authorized'] },
+ current: { code_environment_ids: ['revoked'] },
+ }).code_environment_ids,
+ ).toEqual(['authorized']);
+ expect(
+ resolveAgentWorkspaceRestoreConfiguration({
+ version: {},
+ current: { code_environment_ids: ['revoked'] },
+ }).code_environment_ids,
+ ).toBeUndefined();
+ });
+});
+
describe('validateAgentWorkspaceDefaultBinding', () => {
const environments = [
{ id: 'attached-vm', type: 'attached' },
diff --git a/packages/api/src/agents/workspace.ts b/packages/api/src/agents/workspace.ts
index 2d8d195149..99ab1ba461 100644
--- a/packages/api/src/agents/workspace.ts
+++ b/packages/api/src/agents/workspace.ts
@@ -1,3 +1,10 @@
+import {
+ DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES,
+ resolveAllowedStatefulCodeEnvironments,
+} from 'librechat-data-provider';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types';
+
interface AgentWorkspaceUpdate {
code_environment_id?: string | null;
code_workspace_id?: string;
@@ -13,6 +20,7 @@ interface AgentWorkspaceConfiguration {
stateful_code_sessions?: boolean;
stateful_code_environment?: string | null;
code_environment_id?: string | null;
+ code_environment_ids?: string[];
code_workspace_id?: string;
}
@@ -49,9 +57,102 @@ export function resolveAgentWorkspaceRestoreConfiguration({
code_workspace_id: Object.prototype.hasOwnProperty.call(version, 'code_workspace_id')
? version.code_workspace_id
: undefined,
+ code_environment_ids: Object.prototype.hasOwnProperty.call(version, 'code_environment_ids')
+ ? version.code_environment_ids
+ : undefined,
};
}
+/** Validate all new references against the request's already-loaded, principal-scoped config
+ * before the persistence layer acquires deletion reservations. Unrelated edits omit the list. */
+export function validateAgentCodeEnvironmentAllowlist(
+ req: Pick<ServerRequest, 'config'>,
+ res: Pick<Response, 'status'>,
+ environmentIds?: readonly string[],
+): boolean {
+ if (environmentIds == null) return true;
+ const policy = req.config?.endpoints?.agents?.statefulCodeSessions;
+ const maximum = policy?.maxEnvironmentChoices ?? DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES;
+ if (environmentIds.length > maximum) {
+ res
+ .status(400)
+ .json({ error: `Agent machine choices exceed the configured maximum of ${maximum}` });
+ return false;
+ }
+ for (const id of environmentIds) {
+ const environment = policy?.environments?.find((candidate) => candidate.id === id);
+ if (
+ environment?.type !== 'attached' ||
+ (environment.pairing?.allowPrincipalWorkers === true &&
+ environment.pairing.workerId == null &&
+ environment.workerId == null)
+ ) {
+ res.status(403).json({
+ error: 'One or more agent machine choices are not authorized attached environments',
+ });
+ return false;
+ }
+ }
+ return true;
+}
+
+/** Shared create/update/duplicate/restore policy. CJS controllers only wire the validated data
+ * and loaded request config into this boundary; they do not implement routing authorization. */
+export function validateStatefulCodeEnvironment(
+ req: Pick<ServerRequest, 'config'>,
+ res: Pick<Response, 'status'>,
+ enabled?: boolean,
+ environment?: string | null,
+ environmentId?: string | null,
+ environmentIdSelected = false,
+ workspaceId?: string,
+ currentWorkspaceId?: string,
+ currentEnvironmentId?: string | null,
+ environmentIds?: readonly string[],
+): boolean {
+ if (!validateAgentCodeEnvironmentAllowlist(req, res, environmentIds)) return false;
+ const policy = req.config?.endpoints?.agents?.statefulCodeSessions;
+ const configuredEnvironments = policy?.environments ?? [];
+ const workspaceValidation = validateAgentWorkspaceDefaultBinding({
+ workspaceId,
+ environmentId,
+ currentWorkspaceId,
+ currentEnvironmentId,
+ environments: configuredEnvironments,
+ });
+ if (!workspaceValidation.valid) {
+ res.status(400).json({ error: workspaceValidation.error });
+ return false;
+ }
+ if (enabled !== true && !environmentIdSelected) return true;
+ if (environmentId != null) {
+ const configured = configuredEnvironments.find((candidate) => candidate.id === environmentId);
+ if (
+ configured == null ||
+ (configured.pairing?.allowPrincipalWorkers === true &&
+ configured.pairing.workerId == null &&
+ configured.workerId == null)
+ ) {
+ res
+ .status(400)
+ .json({ error: `Stateful code environment is not configured: ${environmentId}` });
+ return false;
+ }
+ }
+ if (enabled !== true) return true;
+ const resolvedEnvironment = environment ?? 'user';
+ if (
+ resolveAllowedStatefulCodeEnvironments(policy?.allowedEnvironments).includes(
+ resolvedEnvironment as 'user' | 'agent-user' | 'conversation',
+ )
+ )
+ return true;
+ res.status(403).json({
+ error: `Stateful code environment is not allowed by this deployment: ${resolvedEnvironment}`,
+ });
+ return false;
+}
+
export function shouldValidateAgentWorkspaceDefaultBinding({
workspaceId,
environmentId,
diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.ts
index 81e3b92b3a..3155ca6d67 100644
--- a/packages/api/src/code/capabilities.spec.ts
+++ b/packages/api/src/code/capabilities.spec.ts
@@ -667,6 +667,21 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
expect(fetchSpy).not.toHaveBeenCalled();
});
+ it('rejects changed agent ownership on a sealed selection before contacting Code API', async () => {
+ const fetchSpy = jest.spyOn(globalThis, 'fetch');
+ const selected = { environmentId: 'personal', workspaceId: 'project-a' };
+ await expect(
+ resolveCodeExecutionWorkspaceContext({
+ context,
+ requestedSelections: [{ ...selected, agentIds: ['reviewer'] }],
+ persistedSelections: [{ ...selected, agentIds: ['primary'] }],
+ environments,
+ getAppConfig,
+ }),
+ ).rejects.toMatchObject({ reason: 'locked' });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
it('fails when the saved workspace disappears instead of selecting another', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(workspaceStatus([{ id: 'replacement' }]));
diff --git a/packages/api/src/code/capabilities.ts b/packages/api/src/code/capabilities.ts
index 4603eb296b..2214ce4771 100644
--- a/packages/api/src/code/capabilities.ts
+++ b/packages/api/src/code/capabilities.ts
@@ -1,13 +1,15 @@
import { logger } from '@librechat/data-schemas';
-import { ErrorTypes, isCodeWorkspaceSelections } from 'librechat-data-provider';
-import type {
- CodeWorkspaceSelection,
- CodeWorkspaceSelectionErrorReason,
+import {
+ isCodeWorkspaceSelections,
+ canonicalizeCodeWorkspaceSelections,
} from 'librechat-data-provider';
+import type { CodeWorkspaceSelection } from 'librechat-data-provider';
import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';
import type { createAppConfigService } from '~/app/service';
import type { CodeBridgeWorkerStatus } from './bridge';
export type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
+export { CodeWorkspaceSelectionError } from './errors';
+import { CodeWorkspaceSelectionError } from './errors';
import {
CodeBridgeStatusError,
createCodeBridgeStatusPoller,
@@ -18,44 +20,10 @@ export type CodeCapabilityConfigLoader = ReturnType<typeof createAppConfigServic
const pollWorkerStatus = createCodeBridgeStatusPoller();
-function codeWorkspaceSelectionErrorMessage(reason: CodeWorkspaceSelectionErrorReason): string {
- switch (reason) {
- case 'required':
- return 'Choose an attached workspace before using this agent.';
- case 'invalid':
- return 'The selected attached workspace is invalid.';
- case 'worker_unavailable':
- return 'The attached code environment is unavailable. Reconnect the machine and try again.';
- case 'unsupported':
- return 'The attached code environment does not advertise selectable workspaces. Update the LibreChat Code worker and try again.';
- case 'missing':
- return 'The selected workspace is no longer registered on this machine. Restore the previous registration or start a new conversation.';
- case 'locked':
- return 'This conversation already has a different code environment decision.';
- }
-}
-
-export class CodeWorkspaceSelectionError extends Error {
- readonly code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE = ErrorTypes.CODE_WORKSPACE_UNAVAILABLE;
- readonly status: number = 409;
- readonly statusCode: number = 409;
-
- constructor(public readonly reason: CodeWorkspaceSelectionErrorReason) {
- super(codeWorkspaceSelectionErrorMessage(reason));
- this.name = 'CodeWorkspaceSelectionError';
- }
-}
-
function canonicalWorkspaceSelections(
selections: CodeWorkspaceSelection[],
): CodeWorkspaceSelection[] {
- return [...selections].sort((left, right) => {
- if (left.environmentId < right.environmentId) return -1;
- if (left.environmentId > right.environmentId) return 1;
- if (left.workspaceId < right.workspaceId) return -1;
- if (left.workspaceId > right.workspaceId) return 1;
- return 0;
- });
+ return canonicalizeCodeWorkspaceSelections(selections);
}
function sameWorkspaceSelections(
diff --git a/packages/api/src/code/decision.spec.ts b/packages/api/src/code/decision.spec.ts
index 90609892e6..f66c240239 100644
--- a/packages/api/src/code/decision.spec.ts
+++ b/packages/api/src/code/decision.spec.ts
@@ -10,6 +10,28 @@ import { CodeWorkspaceSelectionError } from './capabilities';
const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
describe('resolveConversationCodeEnvironmentDecision', () => {
+ it('seals agent ownership, accepts reordered retries and refuses a route reassignment', () => {
+ const selected = { ...selection, agentIds: ['reviewer', 'primary'] };
+ const conversation = {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [selected],
+ };
+ expect(
+ resolveConversationCodeEnvironmentDecision({
+ conversationId: 'saved',
+ conversation,
+ requestedSelections: [{ ...selected, agentIds: ['primary', 'reviewer'] }],
+ }).codeWorkspaces,
+ ).toEqual([{ ...selected, agentIds: ['primary', 'reviewer'] }]);
+ expect(() =>
+ resolveConversationCodeEnvironmentDecision({
+ conversationId: 'saved',
+ conversation,
+ requestedSelections: [{ ...selected, agentIds: ['other'] }],
+ }),
+ ).toThrow(CodeWorkspaceSelectionError);
+ });
it('defaults a new conversation without a selection to no attached environment', () => {
expect(resolveConversationCodeEnvironmentDecision({ conversationId: 'new' })).toEqual({
mode: 'without_attached',
diff --git a/packages/api/src/code/decision.ts b/packages/api/src/code/decision.ts
index 2eec82ec84..32d16e2f8c 100644
--- a/packages/api/src/code/decision.ts
+++ b/packages/api/src/code/decision.ts
@@ -1,4 +1,8 @@
-import { isCodeEnvironmentMode, isCodeWorkspaceSelections } from 'librechat-data-provider';
+import {
+ isCodeEnvironmentMode,
+ isCodeWorkspaceSelections,
+ canonicalizeCodeWorkspaceSelections,
+} from 'librechat-data-provider';
import type {
CodeEnvironmentMode,
CodeWorkspaceSelection,
@@ -19,13 +23,7 @@ export type StoredConversationDecision = Pick<
> & { codeEnvironmentRevision?: number };
function canonicalSelections(selections: CodeWorkspaceSelection[]): CodeWorkspaceSelection[] {
- return [...selections].sort((left, right) => {
- if (left.environmentId < right.environmentId) return -1;
- if (left.environmentId > right.environmentId) return 1;
- if (left.workspaceId < right.workspaceId) return -1;
- if (left.workspaceId > right.workspaceId) return 1;
- return 0;
- });
+ return canonicalizeCodeWorkspaceSelections(selections);
}
function sameSelections(left: CodeWorkspaceSelection[], right: CodeWorkspaceSelection[]): boolean {
diff --git a/packages/api/src/code/environments.integration.spec.ts b/packages/api/src/code/environments.integration.spec.ts
index e869a35a12..97c18c1ae0 100644
--- a/packages/api/src/code/environments.integration.spec.ts
+++ b/packages/api/src/code/environments.integration.spec.ts
@@ -450,55 +450,110 @@ describe('code environment registry', () => {
).resolves.toBeNull();
});
- test('fences removal while an agent write is reserving the environment', async () => {
+ test('cancels expired removal when a surviving agent allows the machine', async () => {
const registry = createCodeEnvironmentRegistry(mongoose);
- const methods = createMethods(mongoose);
const ownerId = new Types.ObjectId();
- await registry.register({
+ await mongoose.models.User.create({
+ _id: ownerId,
+ email: '[email protected]',
+ provider: 'local',
+ });
+ const environment = await registry.register({
actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
environment: {
- id: 'agent-write-race',
- name: 'Agent write race',
+ id: 'additional-reconcile',
+ name: 'Additional reconcile',
type: 'attached',
baseURL: 'https://code.example.com',
controlPlaneId: 'shared-code-api',
},
});
- const Agent = mongoose.models.Agent;
- const createAgent = Agent.create.bind(Agent);
- let enteredCreate!: () => void;
- let releaseCreate!: () => void;
- const entered = new Promise<void>((resolve) => (enteredCreate = resolve));
- const release = new Promise<void>((resolve) => (releaseCreate = resolve));
- const createSpy = jest.spyOn(Agent, 'create').mockImplementationOnce(async (input) => {
- enteredCreate();
- await release;
- return await createAgent(input);
- });
-
- const pendingAgent = methods.createAgent({
- id: 'agent_write_race',
- name: 'Agent write race',
+ await createMethods(mongoose).createAgent({
+ id: 'agent_additional_reconcile',
author: ownerId,
- model: 'test-model',
- provider: 'test-provider',
- code_environment_id: 'agent-write-race',
+ provider: 'test',
+ model: 'test',
+ code_environment_ids: [environment.id],
});
- await entered;
+ await mongoose.models.CodeEnvironment.updateOne(
+ { environmentId: environment.id },
+ {
+ $set: {
+ deletionStartedAt: new Date(),
+ deletionLeaseExpiresAt: new Date(Date.now() - 1_000),
+ deletionLeaseId: 'expired',
+ },
+ },
+ );
+ const fetchImpl = jest.fn();
+ await reconcileCodeEnvironmentLifecycle({ mongoose, fetchImpl });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ const preserved = await mongoose.models.CodeEnvironment.findOne({
+ environmentId: environment.id,
+ }).lean<{ deletionStartedAt?: Date }>();
+ expect(preserved).not.toBeNull();
+ expect(preserved?.deletionStartedAt).toBeUndefined();
+ });
- await expect(
- registry.remove({
+ test.each(['code_environment_id', 'code_environment_ids'])(
+ 'fences removal while an agent write is reserving %s',
+ async (field) => {
+ const registry = createCodeEnvironmentRegistry(mongoose);
+ const methods = createMethods(mongoose);
+ const ownerId = new Types.ObjectId();
+ await registry.register({
actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
- environmentId: 'agent-write-race',
- }),
- ).rejects.toMatchObject({ name: 'CodeEnvironmentInUseError' });
+ environment: {
+ id: 'agent-write-race',
+ name: 'Agent write race',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ controlPlaneId: 'shared-code-api',
+ },
+ });
+ const Agent = mongoose.models.Agent;
+ const createAgent = Agent.create.bind(Agent);
+ let enteredCreate!: () => void;
+ let releaseCreate!: () => void;
+ const entered = new Promise<void>((resolve) => (enteredCreate = resolve));
+ const release = new Promise<void>((resolve) => (releaseCreate = resolve));
+ const createSpy = jest.spyOn(Agent, 'create').mockImplementationOnce(async (input) => {
+ enteredCreate();
+ await release;
+ return await createAgent(input);
+ });
- releaseCreate();
- await expect(pendingAgent).resolves.toMatchObject({
- code_environment_id: 'agent-write-race',
- });
- createSpy.mockRestore();
- });
+ const pendingAgent = methods.createAgent({
+ id: 'agent_write_race',
+ name: 'Agent write race',
+ author: ownerId,
+ model: 'test-model',
+ provider: 'test-provider',
+ [field]: field === 'code_environment_ids' ? ['agent-write-race'] : 'agent-write-race',
+ });
+ await entered;
+
+ await expect(
+ registry.remove({
+ actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
+ environmentId: 'agent-write-race',
+ }),
+ ).rejects.toMatchObject({ name: 'CodeEnvironmentInUseError' });
+
+ releaseCreate();
+ await expect(pendingAgent).resolves.toMatchObject({
+ [field]: field === 'code_environment_ids' ? ['agent-write-race'] : 'agent-write-race',
+ });
+ createSpy.mockRestore();
+ // Once the reservation is released, the durable reference still fences removal.
+ await expect(
+ registry.remove({
+ actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
+ environmentId: 'agent-write-race',
+ }),
+ ).rejects.toMatchObject({ name: 'CodeEnvironmentInUseError' });
+ },
+ );
test('revokes every user-bound worker before account deletion', async () => {
const ownerId = new Types.ObjectId();
@@ -1096,39 +1151,42 @@ describe('code environment registry', () => {
await expect(mongoose.models.CodeEnvironment.findById(environment._id)).resolves.toBeNull();
});
- test('preserves a creator-owned environment referenced by another surviving agent', async () => {
- const registry = createCodeEnvironmentRegistry(mongoose);
- const methods = createMethods(mongoose);
- const ownerId = new Types.ObjectId();
- const teammateId = new Types.ObjectId();
- const environment = await registry.register({
- actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
- environment: {
- id: 'shared-deployment-worker',
- name: 'Shared deployment worker',
- type: 'attached',
- baseURL: 'https://code.example.com',
- controlPlaneId: 'shared-code-api',
- workerPrincipal: { type: 'deployment', id: 'shared-control-plane' },
- },
- });
- await mongoose.models.Agent.create({
- id: 'agent_survives_owner',
- name: 'Surviving agent',
- author: teammateId,
- model: 'test-model',
- provider: 'test-provider',
- code_environment_id: environment.id,
- });
+ test.each(['code_environment_id', 'code_environment_ids'])(
+ 'preserves a creator-owned environment referenced by another surviving agent via %s',
+ async (field) => {
+ const registry = createCodeEnvironmentRegistry(mongoose);
+ const methods = createMethods(mongoose);
+ const ownerId = new Types.ObjectId();
+ const teammateId = new Types.ObjectId();
+ const environment = await registry.register({
+ actor: { userId: ownerId, role: 'USER', idOnTheSource: null },
+ environment: {
+ id: 'shared-deployment-worker',
+ name: 'Shared deployment worker',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ controlPlaneId: 'shared-code-api',
+ workerPrincipal: { type: 'deployment', id: 'shared-control-plane' },
+ },
+ });
+ await mongoose.models.Agent.create({
+ id: 'agent_survives_owner',
+ name: 'Surviving agent',
+ author: teammateId,
+ model: 'test-model',
+ provider: 'test-provider',
+ [field]: field === 'code_environment_ids' ? [environment.id] : environment.id,
+ });
- await expect(methods.deleteUserCodeEnvironments(ownerId)).resolves.toBe(0);
- await expect(
- mongoose.models.CodeEnvironment.findOne({ environmentId: environment.id }),
- ).resolves.not.toBeNull();
- await expect(
- mongoose.models.AclEntry.countDocuments({ resourceId: environment.resourceId }),
- ).resolves.toBeGreaterThan(0);
- });
+ await expect(methods.deleteUserCodeEnvironments(ownerId)).resolves.toBe(0);
+ await expect(
+ mongoose.models.CodeEnvironment.findOne({ environmentId: environment.id }),
+ ).resolves.not.toBeNull();
+ await expect(
+ mongoose.models.AclEntry.countDocuments({ resourceId: environment.resourceId }),
+ ).resolves.toBeGreaterThan(0);
+ },
+ );
test('recovers expired agent reservations and removal leases', async () => {
const methods = createMethods(mongoose);
diff --git a/packages/api/src/code/environments.ts b/packages/api/src/code/environments.ts
index 6d79aec095..897bc7c777 100644
--- a/packages/api/src/code/environments.ts
+++ b/packages/api/src/code/environments.ts
@@ -73,7 +73,7 @@ export type CodeEnvironmentLifecycleTarget = CodeEnvironmentSummary & {
function agentReferenceFilter(environmentId: string, tenantId?: string) {
return {
- code_environment_id: environmentId,
+ $or: [{ code_environment_id: environmentId }, { code_environment_ids: environmentId }],
...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
};
}
diff --git a/packages/api/src/code/errors.ts b/packages/api/src/code/errors.ts
index 4bf582e3ee..db30c013ca 100644
--- a/packages/api/src/code/errors.ts
+++ b/packages/api/src/code/errors.ts
@@ -1,6 +1,34 @@
import { ErrorTypes, isCodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
import type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
+function codeWorkspaceSelectionErrorMessage(reason: CodeWorkspaceSelectionErrorReason): string {
+ switch (reason) {
+ case 'required':
+ return 'Choose an attached workspace before using this agent.';
+ case 'invalid':
+ return 'The selected attached workspace is invalid.';
+ case 'worker_unavailable':
+ return 'The attached code environment is unavailable. Reconnect the machine and try again.';
+ case 'unsupported':
+ return 'The attached code environment does not advertise selectable workspaces. Update the LibreChat Code worker and try again.';
+ case 'missing':
+ return 'The selected workspace is no longer registered on this machine. Restore the previous registration or start a new conversation.';
+ case 'locked':
+ return 'This conversation already has a different code environment decision.';
+ }
+}
+
+export class CodeWorkspaceSelectionError extends Error {
+ readonly code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE = ErrorTypes.CODE_WORKSPACE_UNAVAILABLE;
+ readonly status: number = 409;
+ readonly statusCode: number = 409;
+
+ constructor(public readonly reason: CodeWorkspaceSelectionErrorReason) {
+ super(codeWorkspaceSelectionErrorMessage(reason));
+ this.name = 'CodeWorkspaceSelectionError';
+ }
+}
+
interface CodeWorkspaceErrorLike {
code?: string;
reason?: string;
diff --git a/packages/api/src/code/lifecycle.ts b/packages/api/src/code/lifecycle.ts
index fe394d95df..a63f903217 100644
--- a/packages/api/src/code/lifecycle.ts
+++ b/packages/api/src/code/lifecycle.ts
@@ -16,7 +16,7 @@ let reconcileInFlight: Promise<void> | undefined;
function agentReferenceFilter(environmentId: string, tenantId?: string) {
return {
- code_environment_id: environmentId,
+ $or: [{ code_environment_id: environmentId }, { code_environment_ids: environmentId }],
...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
};
}
diff --git a/packages/api/src/endpoints/config/endpoints.spec.ts b/packages/api/src/endpoints/config/endpoints.spec.ts
index 2c0446ad02..e4a8839a37 100644
--- a/packages/api/src/endpoints/config/endpoints.spec.ts
+++ b/packages/api/src/endpoints/config/endpoints.spec.ts
@@ -305,6 +305,28 @@ describe('createEndpointsConfigService', () => {
});
});
+ it('advertises machine selection only when the deployment enables it', async () => {
+ const deps = createMockDeps({
+ loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({
+ [EModelEndpoint.agents]: { userProvide: false, order: 0 },
+ }),
+ getAppConfig: jest.fn().mockResolvedValue(
+ appConfig({
+ endpoints: {
+ [EModelEndpoint.agents]: {
+ statefulCodeSessions: { allowEnvironmentSelection: true },
+ },
+ },
+ }),
+ ),
+ });
+ const { getEndpointsConfig } = createEndpointsConfigService(deps);
+ const result = await getEndpointsConfig(fakeReq());
+ expect(result?.[EModelEndpoint.agents]?.statefulCodeSessions?.allowEnvironmentSelection).toBe(
+ true,
+ );
+ });
+
it.each([
[{ enabled: true }, ['ask']],
[{ enabled: true, mode: 'default' }, ['ask']],
diff --git a/packages/api/src/endpoints/config/endpoints.ts b/packages/api/src/endpoints/config/endpoints.ts
index 4578261044..825996d688 100644
--- a/packages/api/src/endpoints/config/endpoints.ts
+++ b/packages/api/src/endpoints/config/endpoints.ts
@@ -1,6 +1,7 @@
import {
AuthType,
CODE_APPROVAL_MODES,
+ DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES,
EModelEndpoint,
isAgentsEndpoint,
orderEndpointsConfig,
@@ -102,6 +103,14 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {
const clientStatefulCodeSessions = statefulCodeSessions
? {
allowedEnvironments: statefulCodeSessions.allowedEnvironments,
+ ...(statefulCodeSessions.allowEnvironmentSelection === true
+ ? {
+ allowEnvironmentSelection: true,
+ maxEnvironmentChoices:
+ statefulCodeSessions.maxEnvironmentChoices ??
+ DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES,
+ }
+ : {}),
approvalsEnabled: toolApproval?.enabled !== false,
approvalModes,
environments: statefulCodeSessions.environments
diff --git a/packages/data-provider/specs/codeWorkspace.spec.ts b/packages/data-provider/specs/codeWorkspace.spec.ts
index 543dbd4150..6d62c3b162 100644
--- a/packages/data-provider/specs/codeWorkspace.spec.ts
+++ b/packages/data-provider/specs/codeWorkspace.spec.ts
@@ -49,4 +49,28 @@ describe('isCodeWorkspaceSelections', () => {
]),
).toBe(false);
});
+
+ it('accepts bounded ownership and rejects an agent assigned to two machines', () => {
+ expect(
+ isCodeWorkspaceSelections([
+ { environmentId: 'a', workspaceId: 'root', agentIds: ['primary', 'reviewer'] },
+ ]),
+ ).toBe(true);
+ expect(
+ isCodeWorkspaceSelections([
+ { environmentId: 'a', workspaceId: 'root', agentIds: ['primary'] },
+ { environmentId: 'b', workspaceId: 'root', agentIds: ['primary'] },
+ ]),
+ ).toBe(false);
+ for (const agentIds of [
+ [],
+ ['primary', 'primary'],
+ ['../escape'],
+ Array.from({ length: 129 }, (_, i) => `agent-${i}`),
+ ]) {
+ expect(isCodeWorkspaceSelection({ environmentId: 'a', workspaceId: 'root', agentIds })).toBe(
+ false,
+ );
+ }
+ });
});
diff --git a/packages/data-provider/src/agents/identity.ts b/packages/data-provider/src/agents/identity.ts
new file mode 100644
index 0000000000..3c0054fa88
--- /dev/null
+++ b/packages/data-provider/src/agents/identity.ts
@@ -0,0 +1,9 @@
+/** Strips the runtime index suffix from saved or ephemeral agent IDs. */
+export function stripAgentIdSuffix(agentId: string): string {
+ return agentId.replace(/____\d+$/, '');
+}
+
+/** Distinguishes parallel runtime nodes without changing the saved agent identity. */
+export function appendAgentIdSuffix(agentId: string, index: number): string {
+ return `${agentId}____${index}`;
+}
diff --git a/packages/data-provider/src/code/selection.spec.ts b/packages/data-provider/src/code/selection.spec.ts
new file mode 100644
index 0000000000..5b33e8ff35
--- /dev/null
+++ b/packages/data-provider/src/code/selection.spec.ts
@@ -0,0 +1,199 @@
+import { resolveCodeEnvironmentSelection } from './workspace';
+import { appendAgentIdSuffix } from '../agents/identity';
+
+describe('chat machine selection', () => {
+ const defaultId = 'application-vm';
+ const selections = [{ environmentId: 'runtime-vm', workspaceId: 'primary' }];
+
+ it.each([0, 1, 2])('matches stable ownership for parallel runtime index %s', (index) => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: appendAgentIdSuffix('primary', index),
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: [
+ { environmentId: defaultId, workspaceId: 'primary' },
+ { ...selections[0], agentIds: ['primary'] },
+ ],
+ }),
+ ).toEqual({ valid: true, environmentId: 'runtime-vm' });
+ });
+
+ it.each([
+ { allowSelection: false, environmentIds: ['runtime-vm'] },
+ { allowSelection: true, environmentIds: [] },
+ { allowSelection: false, environmentIds: [] },
+ ])('refuses a revoked owned alternative instead of falling back: %j', (gate) => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ ...gate,
+ agentId: 'primary',
+ environmentId: defaultId,
+ selections: [
+ { environmentId: defaultId, workspaceId: 'primary' },
+ { ...selections[0], agentIds: ['primary'] },
+ ],
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it("does not inherit another agent's explicitly owned alternative", () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: 'primary',
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: [{ ...selections[0], agentIds: ['other'] }],
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it('keeps an explicitly owned default after machine selection is disabled', () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: appendAgentIdSuffix('primary', 1),
+ environmentId: defaultId,
+ allowSelection: false,
+ selections: [{ environmentId: defaultId, workspaceId: 'primary', agentIds: ['primary'] }],
+ }),
+ ).toEqual({ valid: true, environmentId: defaultId });
+ });
+
+ it('routes the selectable primary to B while its fixed reviewer keeps A', () => {
+ const graph = [
+ { environmentId: defaultId, workspaceId: 'primary' },
+ { ...selections[0], agentIds: ['primary'] },
+ ];
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: 'primary',
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: graph,
+ }),
+ ).toEqual({ valid: true, environmentId: 'runtime-vm' });
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: 'reviewer',
+ environmentId: defaultId,
+ selections: graph,
+ }),
+ ).toEqual({ valid: true, environmentId: defaultId });
+ });
+
+ it('rejects an explicitly owned choice outside the agent allowlist rather than falling back', () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ agentId: 'primary',
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: [
+ { environmentId: defaultId, workspaceId: 'primary' },
+ { environmentId: 'foreign', workspaceId: 'primary', agentIds: ['primary'] },
+ ],
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it('retains the agent default without an opt-in or a chat choice', () => {
+ expect(resolveCodeEnvironmentSelection({ environmentId: defaultId, selections })).toEqual({
+ valid: true,
+ environmentId: defaultId,
+ });
+ expect(
+ resolveCodeEnvironmentSelection({ environmentId: defaultId, allowSelection: true }),
+ ).toEqual({
+ valid: true,
+ environmentId: defaultId,
+ });
+ });
+
+ it('uses the chat choice without mutating the agent or the selection', () => {
+ const frozen = Object.freeze(selections.map((selection) => Object.freeze({ ...selection })));
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ allowSelection: true,
+ selections: frozen,
+ environmentIds: ['runtime-vm'],
+ }),
+ ).toEqual({
+ valid: true,
+ environmentId: 'runtime-vm',
+ });
+ });
+
+ it.each(
+ [
+ [{ environmentId: 'runtime-vm', workspaceId: '' }],
+ [...selections, ...selections],
+ { environmentId: 'runtime-vm' },
+ ].map((invalid) => ({ invalid })),
+ )('rejects malformed or ambiguous choices', ({ invalid }) => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ allowSelection: true,
+ selections: invalid,
+ environmentIds: ['runtime-vm'],
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it('preserves the selected default when another graph agent needs an allowed alternative', () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: [...selections, { environmentId: defaultId, workspaceId: 'primary' }],
+ }),
+ ).toEqual({ valid: true, environmentId: defaultId });
+ });
+
+ it('rejects multiple allowed non-default machines without guessing', () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm', 'another-vm'],
+ allowSelection: true,
+ selections: [...selections, { environmentId: 'another-vm', workspaceId: 'primary' }],
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it('rejects a machine omitted from the agent allowlist', () => {
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ environmentIds: ['another-vm'],
+ allowSelection: true,
+ selections,
+ }),
+ ).toEqual({ valid: false });
+ });
+
+ it('resolves each agent independently in a graph with disjoint machine lists', () => {
+ const graph = [...selections, { environmentId: 'another-vm', workspaceId: 'repo' }];
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: defaultId,
+ environmentIds: ['runtime-vm'],
+ allowSelection: true,
+ selections: graph,
+ }),
+ ).toEqual({ valid: true, environmentId: 'runtime-vm' });
+ expect(
+ resolveCodeEnvironmentSelection({
+ environmentId: 'another-vm',
+ environmentIds: ['yet-another-vm'],
+ allowSelection: true,
+ selections: graph,
+ }),
+ ).toEqual({ valid: true, environmentId: 'another-vm' });
+ });
+});
diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts
index 5afb6567ab..b3dbc43170 100644
--- a/packages/data-provider/src/code/workspace.ts
+++ b/packages/data-provider/src/code/workspace.ts
@@ -1,6 +1,11 @@
+import { stripAgentIdSuffix } from '../agents/identity';
+
export const CODE_WORKSPACE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
/** Protocol-v1 ceiling enforced by the worker and Code API. */
export const CODE_WORKSPACE_MAX_COUNT = 32;
+/** Wire/storage safety ceiling; deployments may set a lower per-agent choice limit. */
+export const MAX_AGENT_CODE_ENVIRONMENT_CHOICES = 128;
+export const DEFAULT_AGENT_CODE_ENVIRONMENT_CHOICES = 32;
/** API/client protocol for immutable conversation-owned environment decisions. */
export const CODE_ENVIRONMENT_DECISION_VERSION = 1 as const;
/** API/client protocol for an owner's explicit move of a sealed environment decision. */
@@ -122,6 +127,8 @@ export function isCodeWorkspaceEnvironment(
export interface CodeWorkspaceSelection {
environmentId: string;
workspaceId: string;
+ /** Explicit graph-agent ownership of a chat machine choice; absent on legacy selections. */
+ agentIds?: string[];
}
export function isCodeEnvironmentMode(value: unknown): value is CodeEnvironmentMode {
@@ -140,11 +147,21 @@ export function isCodeWorkspaceSelection(value: unknown): value is CodeWorkspace
}
const selection = value as Record<string, unknown>;
return (
- Object.keys(selection).every((key) => key === 'environmentId' || key === 'workspaceId') &&
+ Object.keys(selection).every((key) =>
+ ['environmentId', 'workspaceId', 'agentIds'].includes(key),
+ ) &&
typeof selection.environmentId === 'string' &&
CODE_WORKSPACE_ID_PATTERN.test(selection.environmentId) &&
typeof selection.workspaceId === 'string' &&
- CODE_WORKSPACE_ID_PATTERN.test(selection.workspaceId)
+ CODE_WORKSPACE_ID_PATTERN.test(selection.workspaceId) &&
+ (selection.agentIds === undefined ||
+ (Array.isArray(selection.agentIds) &&
+ selection.agentIds.length > 0 &&
+ selection.agentIds.length <= MAX_AGENT_CODE_ENVIRONMENT_CHOICES &&
+ selection.agentIds.every(
+ (id) => typeof id === 'string' && CODE_WORKSPACE_ID_PATTERN.test(id),
+ ) &&
+ new Set(selection.agentIds).size === selection.agentIds.length))
);
}
@@ -152,11 +169,74 @@ export function isCodeWorkspaceSelection(value: unknown): value is CodeWorkspace
export function isCodeWorkspaceSelections(value: unknown): value is CodeWorkspaceSelection[] {
if (!Array.isArray(value)) return false;
const environmentIds = new Set<string>();
+ const agentIds = new Set<string>();
return value.every((selection) => {
if (!isCodeWorkspaceSelection(selection) || environmentIds.has(selection.environmentId)) {
return false;
}
environmentIds.add(selection.environmentId);
+ for (const id of selection.agentIds ?? []) {
+ if (agentIds.has(id)) return false;
+ agentIds.add(id);
+ if (agentIds.size > MAX_AGENT_CODE_ENVIRONMENT_CHOICES) return false;
+ }
return true;
});
}
+
+/** Stable decision serialization includes ownership so replay cannot change an agent's route. */
+export function canonicalizeCodeWorkspaceSelections(
+ selections: CodeWorkspaceSelection[],
+): CodeWorkspaceSelection[] {
+ return selections
+ .map(({ environmentId, workspaceId, agentIds }) => ({
+ environmentId,
+ workspaceId,
+ ...(agentIds == null ? {} : { agentIds: [...agentIds].sort() }),
+ }))
+ .sort((left, right) => left.environmentId.localeCompare(right.environmentId));
+}
+
+/** Resolves an agent's default or its chat-owned machine choice. Callers still authorize the
+ * resolved ID against their principal-scoped environment list and verify live capabilities. */
+export function resolveCodeEnvironmentSelection({
+ environmentId,
+ environmentIds,
+ agentId,
+ allowSelection,
+ selections,
+}: {
+ environmentId?: string | null;
+ environmentIds?: readonly string[];
+ agentId?: string | null;
+ allowSelection?: boolean;
+ selections?: unknown;
+}): { valid: true; environmentId?: string | null } | { valid: false } {
+ if (selections == null) return { valid: true, environmentId };
+ if (!isCodeWorkspaceSelections(selections)) return { valid: false };
+ if (selections.length === 0) return { valid: true, environmentId };
+ /** Ownership is persisted under the saved agent ID, not the parallel actor's runtime ID.
+ * Check it before feature gates so revoked routes cannot silently revert to the default. */
+ const stableAgentId = agentId == null ? undefined : stripAgentIdSuffix(agentId);
+ const owned =
+ stableAgentId == null
+ ? undefined
+ : selections.find((selection) => selection.agentIds?.includes(stableAgentId));
+ if (owned != null) {
+ if (owned.environmentId === environmentId) return { valid: true, environmentId };
+ return allowSelection === true && environmentIds?.includes(owned.environmentId)
+ ? { valid: true, environmentId: owned.environmentId }
+ : { valid: false };
+ }
+ if (!allowSelection) return { valid: true, environmentId };
+ const allowed = new Set(environmentIds ?? []);
+ if (environmentId) allowed.add(environmentId);
+ const matches = selections.filter((selection) => allowed.has(selection.environmentId));
+ /** A graph may need an alternative for a different agent. Preserve this agent's explicit
+ * default when present; without it, require exactly one allowed target rather than guessing. */
+ const selectedDefault = matches.find((selection) => selection.environmentId === environmentId);
+ if (selectedDefault != null) return { valid: true, environmentId };
+ const legacy = matches.filter((selection) => selection.agentIds == null);
+ if (legacy.length !== 1) return { valid: false };
+ return { valid: true, environmentId: legacy[0].environmentId };
+}
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index c57bff3c9f..8139be6282 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -48,6 +48,7 @@ import {
CODE_ENVIRONMENT_MOVE_VERSION,
CODE_ENVIRONMENT_TRANSITION_VERSION,
CODE_WORKSPACE_RECOVERY_VERSION,
+ MAX_AGENT_CODE_ENVIRONMENT_CHOICES,
} from './code/workspace';
import { ComponentTypes, SettingTypes, OptionTypes } from './generate';
import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';
@@ -1507,6 +1508,16 @@ export const agentsEndpointSchema = baseEndpointSchema
statefulCodeSessions: z
.object({
allowedEnvironments: z.array(z.enum(STATEFUL_CODE_ENVIRONMENTS)).min(1),
+ /** Allow agents with a machine allowlist to use a chat-owned machine instead of their default.
+ * Enable after every API replica supports per-chat machine routing. */
+ allowEnvironmentSelection: z.boolean().optional(),
+ /** Maximum additional machine choices saved on an agent (wire ceiling: 128). */
+ maxEnvironmentChoices: z
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_AGENT_CODE_ENVIRONMENT_CHOICES)
+ .optional(),
/** Server-only personal worker enrollment policy. Effective principal
* policy may tighten, but never raise, the deployment ceiling. */
principalWorkers: z
diff --git a/packages/data-provider/src/parsers.ts b/packages/data-provider/src/parsers.ts
index 9f49538d26..bf9ad180e7 100644
--- a/packages/data-provider/src/parsers.ts
+++ b/packages/data-provider/src/parsers.ts
@@ -683,9 +683,7 @@ export function isEphemeralAgentId(agentId: string | null | undefined): boolean
* stripAgentIdSuffix('openAI__gpt-4o___GPT-4o____1') // => 'openAI__gpt-4o___GPT-4o'
* stripAgentIdSuffix('agent_abc123') // => 'agent_abc123' (unchanged)
*/
-export function stripAgentIdSuffix(agentId: string): string {
- return agentId.replace(/____\d+$/, '');
-}
+export { stripAgentIdSuffix } from './agents/identity';
/**
* Appends an index suffix (____N) to an agent ID.
@@ -695,6 +693,4 @@ export function stripAgentIdSuffix(agentId: string): string {
* appendAgentIdSuffix('agent_abc123', 1) // => 'agent_abc123____1'
* appendAgentIdSuffix('openAI__gpt-4o___GPT-4o', 1) // => 'openAI__gpt-4o___GPT-4o____1'
*/
-export function appendAgentIdSuffix(agentId: string, index: number): string {
- return `${agentId}____${index}`;
-}
+export { appendAgentIdSuffix } from './agents/identity';
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 471c0c5f0a..cfc0c38b99 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -4,7 +4,11 @@ import type { AgentSubagentGraph } from './types/agents';
import type { SearchResultData } from './types/web';
import type { FunctionTool } from './types/tools';
import type { TFile } from './types/files';
-import { CODE_ENVIRONMENT_MODES, CODE_WORKSPACE_ID_PATTERN } from './code/workspace';
+import {
+ CODE_ENVIRONMENT_MODES,
+ CODE_WORKSPACE_ID_PATTERN,
+ MAX_AGENT_CODE_ENVIRONMENT_CHOICES,
+} from './code/workspace';
import { userSubmittedMessageFieldPathSchema } from './filters';
import { TFeedback, feedbackSchema } from './feedback';
import { CODE_APPROVAL_MODES } from './code/approval';
@@ -423,6 +427,7 @@ export const defaultAgentFormValues = {
[Tools.memory]: false,
stateful_code_environment: 'user' as const,
code_environment_id: undefined as string | null | undefined,
+ code_environment_ids: [] as string[],
code_workspace_id: undefined as string | undefined,
repositoryInstructions: undefined as 'prefer' | 'defer' | 'off' | undefined,
category: 'general',
@@ -1195,6 +1200,11 @@ export const tConversationSchema = z.object({
.object({
environmentId: z.string().regex(CODE_WORKSPACE_ID_PATTERN),
workspaceId: z.string().regex(CODE_WORKSPACE_ID_PATTERN),
+ agentIds: z
+ .array(z.string().regex(CODE_WORKSPACE_ID_PATTERN))
+ .min(1)
+ .max(MAX_AGENT_CODE_ENVIRONMENT_CHOICES)
+ .optional(),
})
.strict(),
)
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index 236fa9882e..4f16626bd6 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -712,6 +712,9 @@ export type TConfig = {
allowedEnvironments: StatefulCodeEnvironment[];
environments?: TPublicCodeEnvironment[];
approvalsEnabled?: boolean;
+ /** Allow new chats to choose among the agent's explicitly listed machines. */
+ allowEnvironmentSelection?: boolean;
+ maxEnvironmentChoices?: number;
/** Approval modes the endpoint policy permits the client to offer. */
approvalModes?: CodeApprovalMode[];
};
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index e210c75c94..86c5fc4620 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -1040,6 +1040,9 @@ export type Agent = {
stateful_code_environment?: StatefulCodeEnvironment;
/** Operator-configured managed or attached stateful execution environment. */
code_environment_id?: string | null;
+ /** Additional attached machines new chats may choose; the saved ID remains the default.
+ * This allowlist never grants the user access to a machine. */
+ code_environment_ids?: string[];
/** Default attached workspace for new chats; empty means no agent default. */
code_workspace_id?: string;
repositoryInstructions?: 'prefer' | 'defer' | 'off';
@@ -1106,6 +1109,7 @@ export type AgentCreateParams = {
| 'stateful_code_sessions'
| 'stateful_code_environment'
| 'code_environment_id'
+ | 'code_environment_ids'
| 'code_workspace_id'
| 'repositoryInstructions'
| 'artifacts'
@@ -1142,6 +1146,7 @@ export type AgentUpdateParams = {
| 'stateful_code_sessions'
| 'stateful_code_environment'
| 'code_environment_id'
+ | 'code_environment_ids'
| 'git_identity'
| 'code_workspace_id'
| 'repositoryInstructions'
diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.ts
index 7cb0fe49bb..aa27fd19e4 100644
--- a/packages/data-schemas/src/methods/agent.spec.ts
+++ b/packages/data-schemas/src/methods/agent.spec.ts
@@ -27,7 +27,7 @@ import {
EDGE_CLEANUP_MAX_SWEEPS,
type AgentMethods,
} from './agent';
-import { withCodeEnvironmentReference } from './codeEnvironment';
+import { withCodeEnvironmentReference, withCodeEnvironmentReferences } from './codeEnvironment';
import { tenantStorage } from '~/config/tenantContext';
import { createAclEntryMethods } from './aclEntry';
import { createModels } from '~/models';
@@ -2461,6 +2461,22 @@ describe('Agent Methods', () => {
expect((await revertAgentVersion({ id: agentId }, 0))?.code_workspace_id).toBeUndefined();
});
+ test('restores machine selection opt-in and clears it when restoring an older version', async () => {
+ const agentId = `agent_${uuidv4()}`;
+ await createAgent({
+ id: agentId,
+ provider: 'test',
+ model: 'test-model',
+ author: new mongoose.Types.ObjectId(),
+ });
+ await updateAgent({ id: agentId }, { code_environment_ids: ['runtime-vm'] });
+ await updateAgent({ id: agentId }, { code_environment_ids: [] });
+ expect((await revertAgentVersion({ id: agentId }, 1))?.code_environment_ids).toEqual([
+ 'runtime-vm',
+ ]);
+ expect((await revertAgentVersion({ id: agentId }, 0))?.code_environment_ids).toBeUndefined();
+ });
+
test('should handle parameter objects correctly', async () => {
const agentId = `agent_${uuidv4()}`;
const authorId = new mongoose.Types.ObjectId();
@@ -3114,62 +3130,150 @@ describe('Agent Methods', () => {
expect(compensate).toHaveBeenCalledWith(undefined);
});
- test('does not overwrite an intervening Agent update when acquiring an environment reference', async () => {
- const agentId = `agent_${uuidv4()}`;
+ test.each(['code_environment_id', 'code_environment_ids'])(
+ 'does not overwrite an intervening Agent update when acquiring %s',
+ async (field) => {
+ const agentId = `agent_${uuidv4()}`;
+ const environmentId = `environment_${uuidv4()}`;
+ const authorId = new mongoose.Types.ObjectId();
+ await createAgent({
+ id: agentId,
+ name: 'Original agent name',
+ author: authorId,
+ model: 'test-model',
+ provider: 'test-provider',
+ });
+ await mongoose.models.CodeEnvironment.create({
+ environmentId,
+ name: 'Concurrent update environment',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ controlPlaneId: 'shared-code-api',
+ createdBy: authorId,
+ });
+ const CodeEnvironment = mongoose.models.CodeEnvironment;
+ const reserve = CodeEnvironment.findOneAndUpdate.bind(CodeEnvironment);
+ let enteredReserve!: () => void;
+ let releaseReserve!: () => void;
+ const entered = new Promise<void>((resolve) => (enteredReserve = resolve));
+ const release = new Promise<void>((resolve) => (releaseReserve = resolve));
+ const reserveSpy = jest.spyOn(CodeEnvironment, 'findOneAndUpdate').mockImplementationOnce(
+ (...args: Parameters<typeof CodeEnvironment.findOneAndUpdate>) =>
+ ({
+ lean: async () => {
+ enteredReserve();
+ await release;
+ return await reserve(...args).lean();
+ },
+ }) as ReturnType<typeof CodeEnvironment.findOneAndUpdate>,
+ );
+ const guardedUpdate = updateAgent(
+ { id: agentId },
+ {
+ name: 'Guarded update name',
+ [field]: field === 'code_environment_ids' ? [environmentId] : environmentId,
+ },
+ );
+ await entered;
+ await Agent.updateOne(
+ { id: agentId },
+ { $set: { description: 'Intervening update survived' } },
+ );
+ releaseReserve();
+
+ await expect(guardedUpdate).resolves.toBeNull();
+ await expect(Agent.findOne({ id: agentId }).lean()).resolves.toMatchObject({
+ name: 'Original agent name',
+ description: 'Intervening update survived',
+ });
+ await expect(Agent.findOne({ id: agentId }).lean()).resolves.not.toHaveProperty(field);
+ reserveSpy.mockRestore();
+ },
+ );
+ test('rejects additional machine references on create, update and version restore during removal', async () => {
+ const author = new mongoose.Types.ObjectId();
const environmentId = `environment_${uuidv4()}`;
- const authorId = new mongoose.Types.ObjectId();
- await createAgent({
- id: agentId,
- name: 'Original agent name',
- author: authorId,
- model: 'test-model',
- provider: 'test-provider',
- });
await mongoose.models.CodeEnvironment.create({
environmentId,
- name: 'Concurrent update environment',
+ name: 'Additional machine',
type: 'attached',
baseURL: 'https://code.example.com',
controlPlaneId: 'shared-code-api',
- createdBy: authorId,
- });
- const CodeEnvironment = mongoose.models.CodeEnvironment;
- const reserve = CodeEnvironment.findOneAndUpdate.bind(CodeEnvironment);
- let enteredReserve!: () => void;
- let releaseReserve!: () => void;
- const entered = new Promise<void>((resolve) => (enteredReserve = resolve));
- const release = new Promise<void>((resolve) => (releaseReserve = resolve));
- const reserveSpy = jest.spyOn(CodeEnvironment, 'findOneAndUpdate').mockImplementationOnce(
- (...args: Parameters<typeof CodeEnvironment.findOneAndUpdate>) =>
- ({
- lean: async () => {
- enteredReserve();
- await release;
- return await reserve(...args).lean();
- },
- }) as ReturnType<typeof CodeEnvironment.findOneAndUpdate>,
- );
- const guardedUpdate = updateAgent(
- { id: agentId },
- { name: 'Guarded update name', code_environment_id: environmentId },
- );
- await entered;
- await Agent.updateOne(
- { id: agentId },
- { $set: { description: 'Intervening update survived' } },
- );
- releaseReserve();
-
- await expect(guardedUpdate).resolves.toBeNull();
- await expect(Agent.findOne({ id: agentId }).lean()).resolves.toMatchObject({
- name: 'Original agent name',
- description: 'Intervening update survived',
+ createdBy: author,
});
- await expect(Agent.findOne({ id: agentId }).lean()).resolves.not.toHaveProperty(
- 'code_environment_id',
+ const id = `agent_${uuidv4()}`;
+ await createAgent({
+ id,
+ name: 'Additional machine agent',
+ author,
+ model: 'test',
+ provider: 'test',
+ code_environment_ids: [environmentId],
+ });
+ await updateAgent({ id }, { code_environment_ids: [] });
+ await mongoose.models.CodeEnvironment.updateOne(
+ { environmentId },
+ { $set: { deletionStartedAt: new Date() } },
);
+ await expect(
+ createAgent({ id: `agent_${uuidv4()}`, author, code_environment_ids: [environmentId] }),
+ ).rejects.toMatchObject({ name: 'CodeEnvironmentReferenceError' });
+ await expect(
+ updateAgent({ id }, { $set: { code_environment_ids: [environmentId] } }),
+ ).rejects.toMatchObject({ name: 'CodeEnvironmentReferenceError' });
+ for (const operator of ['$push', '$addToSet']) {
+ await expect(
+ updateAgent({ id }, { [operator]: { code_environment_ids: { $each: [environmentId] } } }),
+ ).rejects.toMatchObject({ name: 'CodeEnvironmentReferenceError' });
+ }
+ await expect(revertAgentVersion({ id }, 0)).rejects.toMatchObject({
+ name: 'CodeEnvironmentReferenceError',
+ });
+ expect((await getAgent({ id }))?.code_environment_ids).toEqual([]);
+ });
+
+ test('refuses an oversized reference list before acquiring any reservations', async () => {
+ const reserveSpy = jest.spyOn(mongoose.models.CodeEnvironment, 'findOneAndUpdate');
+ const operation = jest.fn();
+ await expect(
+ withCodeEnvironmentReferences(
+ mongoose,
+ Array.from({ length: 130 }, (_, i) => `machine-${i}`),
+ operation,
+ ),
+ ).rejects.toThrow('storage safety ceiling');
+ expect(reserveSpy).not.toHaveBeenCalled();
+ expect(operation).not.toHaveBeenCalled();
reserveSpy.mockRestore();
});
+
+ test('releases acquired machine references when a later acquisition fails', async () => {
+ const createdBy = new mongoose.Types.ObjectId();
+ const ids = [`environment_${uuidv4()}`, `environment_${uuidv4()}`];
+ for (const [index, environmentId] of ids.entries()) {
+ await mongoose.models.CodeEnvironment.create({
+ environmentId,
+ name: 'Acquisition guard',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ controlPlaneId: 'shared-code-api',
+ createdBy,
+ ...(index === 1 ? { deletionStartedAt: new Date() } : {}),
+ });
+ }
+ const operation = jest.fn();
+ await expect(withCodeEnvironmentReferences(mongoose, ids, operation)).rejects.toMatchObject({
+ name: 'CodeEnvironmentReferenceError',
+ });
+ expect(operation).not.toHaveBeenCalled();
+ expect(
+ (
+ await mongoose.models.CodeEnvironment.findOne({
+ environmentId: ids[0],
+ }).lean<CodeEnvironmentDocument>()
+ )?.pendingAgentReferences,
+ ).toEqual([]);
+ });
test('should preserve skills enabled when pruning deleted ids on an all-scoped revert', async () => {
const agentId = `agent_${uuidv4()}`;
const authorId = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 29c5959275..2c844d8537 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -12,7 +12,7 @@ import {
import type { FilterQuery, Model, PipelineStage, ProjectionType, Types } from 'mongoose';
import type { AgentSortOption, AgentToolResources } from 'librechat-data-provider';
import type { IAgent, IAclEntry, IUser, ActionQuery } from '~/types';
-import { withCodeEnvironmentReference } from './codeEnvironment';
+import { withCodeEnvironmentReferences } from './codeEnvironment';
import { OWNER_ACL_PERMISSION_BIT_SUPERSETS } from './aclEntry';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { filterExistingSkillIds } from './skill';
@@ -1169,6 +1169,13 @@ export function createAgentMethods(
} {
const { removeAllPermissions, getActions, getSoleOwnedResourceIds, isExternalSkillId } = deps;
+ function codeEnvironmentReferences(data: Record<string, unknown>): string[] {
+ return [
+ data.code_environment_id,
+ ...(Array.isArray(data.code_environment_ids) ? data.code_environment_ids : []),
+ ].filter((id): id is string => typeof id === 'string' && id.length > 0);
+ }
+
async function restoreAgentAfterReferenceLoss(
Agent: Model<IAgent>,
agentAfterWrite: IAgent | null,
@@ -1180,7 +1187,10 @@ export function createAgentMethods(
const restored = await Agent.replaceOne(
{
_id: agentAfterWrite._id,
- code_environment_id: lostEnvironmentId,
+ $or: [
+ { code_environment_id: lostEnvironmentId },
+ { code_environment_ids: lostEnvironmentId },
+ ],
updatedAt,
},
originalAgent,
@@ -1194,6 +1204,10 @@ export function createAgentMethods(
{ _id: agentAfterWrite._id, code_environment_id: lostEnvironmentId },
{ $unset: { code_environment_id: 1 } },
);
+ await Agent.updateOne(
+ { _id: agentAfterWrite._id, code_environment_ids: lostEnvironmentId },
+ { $pull: { code_environment_ids: lostEnvironmentId } },
+ );
}
}
@@ -1235,11 +1249,10 @@ export function createAgentMethods(
extractMCPServerNames(agentData.tools as string[] | undefined),
};
- return await withCodeEnvironmentReference(
+ return await withCodeEnvironmentReferences(
mongoose,
- typeof agentData.code_environment_id === 'string' ? agentData.code_environment_id : undefined,
+ codeEnvironmentReferences(agentData),
async () => (await Agent.create(initialAgentData)).toObject() as IAgent,
- undefined,
async (createdAgent) => {
await Agent.deleteOne({ _id: createdAgent._id });
},
@@ -1574,37 +1587,42 @@ export function createAgentMethods(
}
}
- const directEnvironmentId = updateData.code_environment_id;
- const setEnvironmentId =
- typeof updateData.$set === 'object' && updateData.$set != null
- ? (updateData.$set as { code_environment_id?: unknown }).code_environment_id
- : undefined;
- let nextEnvironmentId: string | undefined;
- if (typeof directEnvironmentId === 'string') {
- nextEnvironmentId = directEnvironmentId;
- } else if (typeof setEnvironmentId === 'string') {
- nextEnvironmentId = setEnvironmentId;
+ const nextEnvironmentIds = codeEnvironmentReferences({
+ ...updateData,
+ ...(typeof updateData.$set === 'object' && updateData.$set != null ? updateData.$set : {}),
+ });
+ for (const operator of ['$push', '$addToSet']) {
+ const update = updateData[operator] as { code_environment_ids?: unknown } | undefined;
+ const values = update?.code_environment_ids;
+ const added =
+ values != null && typeof values === 'object' && '$each' in values
+ ? (values as { $each: unknown }).$each
+ : values;
+ nextEnvironmentIds.push(
+ ...codeEnvironmentReferences({
+ code_environment_ids: Array.isArray(added) ? added : [added],
+ }),
+ );
}
- const updatedAgent = await withCodeEnvironmentReference(
+ const updatedAgent = await withCodeEnvironmentReferences(
mongoose,
- nextEnvironmentId,
+ nextEnvironmentIds,
async () =>
(await Agent.findOneAndUpdate(
- currentAgent == null || nextEnvironmentId == null
+ currentAgent == null || nextEnvironmentIds.length === 0
? searchParameter
: { ...searchParameter, _id: currentAgent._id, updatedAt: currentRevision },
updateData,
mongoOptions,
).lean()) as IAgent | null,
- undefined,
- async (agentAfterUpdate) => {
- if (agentAfterUpdate == null || nextEnvironmentId == null) return;
+ async (agentAfterUpdate, lostEnvironmentId) => {
+ if (agentAfterUpdate == null) return;
if (currentAgent == null) return;
await restoreAgentAfterReferenceLoss(
Agent,
agentAfterUpdate,
currentAgent.toObject() as IAgent,
- nextEnvironmentId,
+ lostEnvironmentId,
);
},
);
@@ -2032,6 +2050,7 @@ export function createAgentMethods(
projection.stateful_code_sessions = 1;
projection.code_environment_id = 1;
projection.code_workspace_id = 1;
+ projection.code_environment_ids = 1;
projection.repositoryInstructions = 1;
projection.agent_ids = 1;
projection['edges.from'] = 1;
@@ -2629,6 +2648,7 @@ export function createAgentMethods(
for (const field of [
'code_environment_id',
'code_workspace_id',
+ 'code_environment_ids',
'repositoryInstructions',
'git_identity',
'skills_scope',
@@ -2642,27 +2662,24 @@ export function createAgentMethods(
Object.keys(unsetOnRestore).length > 0
? { $set: revertToVersion, $unset: unsetOnRestore }
: { $set: revertToVersion };
- const revertedAgent = await withCodeEnvironmentReference(
+ const revertedAgent = await withCodeEnvironmentReferences(
mongoose,
- typeof revertToVersion.code_environment_id === 'string'
- ? revertToVersion.code_environment_id
- : undefined,
+ codeEnvironmentReferences(revertToVersion),
async () =>
await Agent.findOneAndUpdate(
{ ...searchParameter, _id: agent._id, updatedAt: originalRevision },
revertUpdate,
{ new: true },
).lean<IAgent>(),
- undefined,
- async (agentAfterRevert) => {
- if (agentAfterRevert == null || typeof revertToVersion.code_environment_id !== 'string') {
+ async (agentAfterRevert, lostEnvironmentId) => {
+ if (agentAfterRevert == null) {
return;
}
await restoreAgentAfterReferenceLoss(
Agent,
agentAfterRevert,
agent.toObject() as IAgent,
- revertToVersion.code_environment_id,
+ lostEnvironmentId,
);
},
);
diff --git a/packages/data-schemas/src/methods/codeEnvironment.ts b/packages/data-schemas/src/methods/codeEnvironment.ts
index 98d7f0ee13..c6d9555dd3 100644
--- a/packages/data-schemas/src/methods/codeEnvironment.ts
+++ b/packages/data-schemas/src/methods/codeEnvironment.ts
@@ -1,6 +1,6 @@
import { Types } from 'mongoose';
import { createHash } from 'crypto';
-import { ResourceType } from 'librechat-data-provider';
+import { ResourceType, MAX_AGENT_CODE_ENVIRONMENT_CHOICES } from 'librechat-data-provider';
import type { CodeEnvironmentUserSettings } from 'librechat-data-provider';
import type { Model } from 'mongoose';
import type { CodeEnvironmentDocument } from '~/types';
@@ -49,7 +49,7 @@ function ownerSlotId(ownerId: Types.ObjectId, slot: number): Types.ObjectId {
function agentReferenceFilter(environmentId: string, tenantId?: string) {
return {
- code_environment_id: environmentId,
+ $or: [{ code_environment_id: environmentId }, { code_environment_ids: environmentId }],
...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
};
}
@@ -142,6 +142,31 @@ async function renewCodeEnvironmentReference(
}
}
+/** Hold every machine reference until the write settles. Nesting the existing
+ * guards renews already-acquired leases and releases them if a later acquisition fails. */
+export async function withCodeEnvironmentReferences<T>(
+ mongoose: typeof import('mongoose'),
+ environmentIds: string[],
+ operation: () => Promise<T>,
+ onReferenceLoss?: (result: T, environmentId: string) => Promise<void>,
+): Promise<T> {
+ if (environmentIds.length > MAX_AGENT_CODE_ENVIRONMENT_CHOICES + 1) {
+ throw new Error('Agent code environment references exceed the storage safety ceiling');
+ }
+ const ids = [...new Set(environmentIds.filter(Boolean))];
+ const run = (index: number): Promise<T> =>
+ index === ids.length
+ ? operation()
+ : withCodeEnvironmentReference(
+ mongoose,
+ ids[index],
+ () => run(index + 1),
+ undefined,
+ (result) => onReferenceLoss?.(result, ids[index]) ?? Promise.resolve(),
+ );
+ return await run(0);
+}
+
export async function withCodeEnvironmentReference<T>(
mongoose: typeof import('mongoose'),
environmentId: string | undefined,
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index dab595a979..becc2ed8b3 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -1338,6 +1338,24 @@ describe('Conversation Operations', () => {
const userId = 'user123';
const unsetFields = { codeEnvironmentMode: 1, codeWorkspaces: 1 };
+ it('preserves explicit agent ownership through save, reload and a stale ordinary save', async () => {
+ const conversationId = uuidv4();
+ const codeWorkspaces = [{ ...mac, agentIds: ['primary', 'reviewer'] }];
+ await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces },
+ );
+ expect((await getConvo(userId, conversationId))?.codeWorkspaces).toEqual(codeWorkspaces);
+ await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces: [vm] },
+ );
+ expect(
+ (await methods.readAdmittedConvoCodeEnvironmentDecision(userId, conversationId))
+ ?.codeWorkspaces,
+ ).toEqual(codeWorkspaces);
+ });
+
it.each([
{ codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
{ codeEnvironmentMode: 'without_attached' },
diff --git a/packages/data-schemas/src/schema/agent.ts b/packages/data-schemas/src/schema/agent.ts
index d043ca1e84..6d8ffc9230 100644
--- a/packages/data-schemas/src/schema/agent.ts
+++ b/packages/data-schemas/src/schema/agent.ts
@@ -95,6 +95,7 @@ const agentSchema: Schema<IAgent> = new Schema<IAgent>(
type: String,
},
code_workspace_id: { type: String },
+ code_environment_ids: { type: [String], default: undefined },
repositoryInstructions: { type: String, enum: ['prefer', 'defer', 'off'] },
git_identity: {
type: new Schema(
diff --git a/packages/data-schemas/src/schema/agentWorkspace.spec.ts b/packages/data-schemas/src/schema/agentWorkspace.spec.ts
index a3d1fd00b0..cad46902ef 100644
--- a/packages/data-schemas/src/schema/agentWorkspace.spec.ts
+++ b/packages/data-schemas/src/schema/agentWorkspace.spec.ts
@@ -1,6 +1,21 @@
import { model, models } from 'mongoose';
import agentSchema from './agent';
+it('round-trips per-chat machine selection without changing the default', () => {
+ const Agent = models.WorkspaceDefaultAgent ?? model('WorkspaceDefaultAgent', agentSchema);
+ const agent = new Agent({
+ code_environment_id: 'machine-a',
+ code_environment_ids: ['machine-b'],
+ });
+ expect(new Agent(agent.toObject()).toObject()).toMatchObject({
+ code_environment_id: 'machine-a',
+ code_environment_ids: ['machine-b'],
+ });
+ agent.code_environment_ids = [];
+ expect(new Agent(agent.toObject()).toObject().code_environment_ids).toEqual([]);
+ expect(new Agent({}).code_environment_ids).toBeUndefined();
+});
+
it('persists repository instruction preference and rejects unknown modes', () => {
const Agent = models.WorkspaceDefaultAgent ?? model('WorkspaceDefaultAgent', agentSchema);
const agent = new Agent({ repositoryInstructions: 'off' });
diff --git a/packages/data-schemas/src/schema/defaults.ts b/packages/data-schemas/src/schema/defaults.ts
index 3bc5a32140..5529ecabb0 100644
--- a/packages/data-schemas/src/schema/defaults.ts
+++ b/packages/data-schemas/src/schema/defaults.ts
@@ -129,6 +129,7 @@ export const conversationPreset: {
type: {
environmentId: { type: StringConstructor; required: boolean };
workspaceId: { type: StringConstructor; required: boolean };
+ agentIds: { type: StringConstructor[]; default: undefined };
_id: boolean;
}[];
default: undefined;
@@ -329,6 +330,7 @@ export const conversationPreset: {
{
environmentId: { type: String, required: true },
workspaceId: { type: String, required: true },
+ agentIds: { type: [String], default: undefined },
_id: false,
},
],
diff --git a/packages/data-schemas/src/types/agent.ts b/packages/data-schemas/src/types/agent.ts
index 9563be72a7..bf224f202c 100644
--- a/packages/data-schemas/src/types/agent.ts
+++ b/packages/data-schemas/src/types/agent.ts
@@ -43,6 +43,7 @@ export interface IAgent extends Omit<Document, 'model'> {
stateful_code_sessions?: boolean;
stateful_code_environment?: 'user' | 'agent-user' | 'conversation';
code_environment_id?: string;
+ code_environment_ids?: string[];
code_workspace_id?: string;
repositoryInstructions?: 'prefer' | 'defer' | 'off';
git_identity?: AgentGitIdentity | null;